/***************************************************************************
    kuninstallerview.cpp  -  Source file of class KUninstallerView
    ------------------------------------------------------------------------
    begin                : Wed Mar 10 08:47:08 MET 1999
                                           
    copyright            : (C) 1999 by Geri House                         
    email                : ge_ha@yahoo.com                                     
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   * 
 *                                                                         *
 ***************************************************************************/


#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <qlabel.h>
#include <qheader.h>
#include <qdir.h>
#include <qmessagebox.h>
#include <qtooltip.h>
#include <qfiledialog.h>
#include <qdialog.h>
#include <qcursor.h>

#include <kmsgbox.h>
#include <kiconloader.h>
#include <ksimpleconfig.h>

#include "kuninstaller.h"
#include "kuninstallerview.h"

bool KUninstallerView::saveUninstalling=true;
QString KUninstallerView::savePath="";
int KUninstallerView::numberBackups=0;

KUninstallerView::KUninstallerView(KApplication* a, KUninstallerApp *parent)
	: QWidget((QWidget*)parent){
	parentApp=parent;
	stopped=FALSE;
	dialog=0;
	localeKDE=0;
	installKDE=0;
	
	QGroupBox *group1 = new QGroupBox(this, "Group1");
	group1->setGeometry( 20, 10, 250, 70 );
	
	QLabel* label_1;
	label_1 = new QLabel( this, "label_1" );
	label_1->setGeometry( 100, 15, 120, 25 );
	{
		QFont font( "helvetica", 16, 75, 0 );
		label_1->setFont( font );
	}
	label_1->setText( i18n("Application:") );

	applicationCombo = new QLineEdit( this, "applicationCombo" );
	applicationCombo->setGeometry( 50, 45, 150, 26 );
    applicationCombo->setText("");
    QToolTip::add(applicationCombo, i18n("Type in or select Application Name"));

    applBtn = new QPushButton(this, "button");
    applBtn->setPixmap(kapp->getIconLoader()->loadIcon("mini/folder_open.xpm"));
    applBtn->setGeometry(210, 45, 26, 26);
    QToolTip::add(applBtn, i18n("Choose a KDE Application for Uninstalling"));

	group2 = new QGroupBox(this, "Group2");
	
	label_2 = new QLabel( this, "label_2" );
	label_2->setGeometry( 360, 15, 120, 25 );
	{
		QFont font( "helvetica", 16, 75, 0 );
		label_2->setFont( font );
	}
	label_2->setText( i18n("Backups:") );
	
	backupCombo = new QComboBox( FALSE, this, "backupCombo" );
	backupCombo->setGeometry( 310, 45, 150, 26 );
	backupCombo->setSizeLimit( 10 );
	backupCombo->setMaxCount(20);

    installBtn = new QPushButton(this, "button");
    installBtn->setPixmap(kapp->getIconLoader()->loadIcon("undo.xpm"));
    installBtn->setGeometry(470, 45, 26, 26);
    QToolTip::add(installBtn, i18n("Install selected Application Backup"));

    deleteBtn = new QPushButton(this, "button");
    deleteBtn->setPixmap(kapp->getIconLoader()->loadIcon("delete.xpm"));
    deleteBtn->setGeometry(504, 45, 26, 26);
    QToolTip::add(deleteBtn, i18n("Delete selected Application Backup"));
	
	showBackupBox();
	
	searchListBox = new KUninstallListView( this, "searchListBox" );	
    searchListBox->addColumn( i18n("Name") );
    searchListBox->setColumnWidthMode(0,QListView::Maximum);
    searchListBox->addColumn( i18n("Size"), 70);
    searchListBox->setColumnAlignment( 1, AlignRight );
    searchListBox->header()->hide();
    QToolTip::add(searchListBox, i18n("List of all Application parts"));

    panner = new KNewPanner(this,"Panner",KNewPanner::Vertical,KNewPanner::Percent, 80);
    sizeLabel = new QLabel(panner,"size");
    sizeLabel->setFrameStyle(QFrame::Panel|QFrame::Sunken);
    sizeLabel->setText("0");
    sizeLabel->setAlignment(AlignRight);
    QToolTip::add(sizeLabel, i18n("Size of checked Items"));

    numLabel = new QLabel(panner,"number");
    setNumberLabel(0);
    numLabel->setFrameStyle(QFrame::Panel|QFrame::Sunken);
    QToolTip::add(numLabel, i18n("Number of checked Items"));
    panner->activate(numLabel,sizeLabel);

    connect(applicationCombo,SIGNAL(returnPressed()),
            parentApp, SLOT(slotSearch()));
    connect(applBtn,SIGNAL(clicked()),
            this, SLOT(openApplDialog()));
    connect(deleteBtn,SIGNAL(clicked()),
            this, SLOT(deleteSelectedBackup()));
    connect(installBtn,SIGNAL(clicked()),
            this, SLOT(installSelectedBackup()));
    connect(searchListBox,SIGNAL(changeChecked( KUninstallListItem * )),
            this, SLOT(updateLabels(KUninstallListItem *)));
    connect(searchListBox,SIGNAL(emitUpdateNumLabel( int )),
            this, SLOT(setNumberLabel(int)));
    connect(searchListBox,SIGNAL(emitUpdateSizeLabel( float )),
            this, SLOT(setSizeLabel(float)));
    searchListBox->viewport()->installEventFilter( this );
}

KUninstallerView::~KUninstallerView(){
}

void KUninstallerView::resizeEvent ( QResizeEvent * e) {
	group2->setGeometry( 280, 10, width()-300, 70 );
    searchListBox->setGeometry(20,90,width()-40,height()-130);
    panner->setGeometry(20,90+height()-127,width()-40,20);
    int ysize=searchListBox->width()-70;
    if (searchListBox->verticalScrollBar()->isVisible()==TRUE)
        ysize-= searchListBox->verticalScrollBar()->width();
    searchListBox->header()->setCellSize(0,ysize);
    panner->setAbsSeparatorPos(width()-110,TRUE);
    QWidget::resizeEvent(e);
}


bool KUninstallerView::search() {
    int ret=0;
    numberItems=0;
    sumSize=0;
    stopped=FALSE;
    applicationCombo->setEnabled(FALSE);
    applBtn->setEnabled(FALSE);
	removeTree();
    if (strcmp(applicationCombo->text(),"")==0)
		QMessageBox::information ( this, i18n("Search error"), i18n("No Application selected"),
		              QMessageBox::Ok);
	else if ( strlen(applicationCombo->text())<3)
		QMessageBox::information ( this, i18n("Search error"),
				i18n("Application Name have to be at least 3 letters!"),
		        QMessageBox::Ok);
	else{		
		findPattern=applicationCombo->text();	
		findPattern+='*';	
		QString strDir;
		if (stopped==FALSE) {
	        strDir = kapp->kde_bindir();
		    ret +=find(strDir, FALSE, TRUE);
		}
		// set Path for the Backup Directory
		strApplDir=savePath;
		strApplDir+="/";
		strApplDir+=applicationCombo->text();
		strApplDir+="-backup";
		// reset findPattern because of name completion
		findPattern=applicationCombo->text();	
		findPattern+='*';	
		if (stopped==FALSE) {
			strDir = kapp->localkdedir();
			ret +=find(strDir,TRUE);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_htmldir ();		
			ret +=find(strDir, TRUE);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_appsdir ();
			ret +=find(strDir, TRUE);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_icondir ();
			ret +=find(strDir);
			strDir+="/mini";
			ret +=find(strDir);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_datadir ();
			ret +=find(strDir, TRUE);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_localedir ();
			ret +=find(strDir, TRUE);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_cgidir ();
			ret +=find(strDir);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_sounddir ();
			ret +=find(strDir);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_toolbardir ();
			ret +=find(strDir);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_partsdir ();
			ret +=find(strDir);
		}
		if (stopped==FALSE) {
    		strDir = kapp->kde_configdir ();
    		ret +=find(strDir);
		}
		if (ret==0 ) {
			KMsgBox::message(this, i18n("Search information"),
	          	i18n("No Application parts found for deleting!"),
	          	KMsgBox::INFORMATION);
			wipeOff();
			ret=FALSE;
		}	
			
	}
    applicationCombo->setEnabled(TRUE);
    applBtn->setEnabled(TRUE);
	return ret;
}

bool KUninstallerView::remove() {
    bool ret=FALSE;
    if (localeKDE->childCount()==0 && installKDE->childCount()==0)
		KMsgBox::message(this, i18n("Remove error"),
	          i18n("No Application parts to delete!"),
	          KMsgBox::EXCLAMATION);
	else if (numberItems==0)	
		KMsgBox::message(this, i18n("Remove error"),
	          i18n("No Application parts checked for delete!"),
	          KMsgBox::EXCLAMATION);
	else {	
	    if ((stopped==TRUE) && (KMsgBox::yesNo(this, i18n("Remove"),
	          i18n("Searching was aborted before!\n Continue with removing ?"),
	          KMsgBox::QUESTION) != 1)) {
	          return ret;
	    }
	    QString output=i18n("All checked Application parts should be deleted ?\n");
	    if (saveUninstalling==true)
	    	output+=i18n("(A Backup will be created !)");
	    else
	    	output+=i18n("(Without creation of a backup!)");
	    if (KMsgBox::yesNo(this, i18n("Remove"), output, KMsgBox::QUESTION) == 1) {
		    QDir dir(savePath);
		    strApplDir=savePath;
		    strApplDir+="/";
		    strApplDir+=applicationCombo->text();
		    strApplDir+="-backup";
		    if (saveUninstalling==true) {
		    	if (dir.exists()==FALSE) {
		    		if (dir.mkdir(savePath)==FALSE) {
		    			QString str(i18n("Creating of Backup-Directory fails!\n"));
		    			str+=i18n("Reason: ");
		    			str+=strerror(errno);
		    			str+=i18n("\n\nCheck your configuration settings!");
						KMsgBox::message(this, i18n("Remove error"), str, KMsgBox::EXCLAMATION);		    			    			
		    			return FALSE;
		    		}
		    	}
		    	if (dir.exists(strApplDir)==TRUE) {
		    		removeRecursiveBackup(strApplDir);
		    	}
		    	if (dir.mkdir(strApplDir)==FALSE) {
		    		QString str(i18n("Creating of Backup-Directory for Application fails!\n"));
		    		str+=i18n("Reason: ");
		    		str+=strerror(errno);
		    		str+=i18n("\n\nCheck your configuration settings!");
					KMsgBox::message(this, i18n("Remove error"), str, KMsgBox::EXCLAMATION);		    			    			
		    		return FALSE;
		    	}
		    }
			KUninstallListItem *parent=(KUninstallListItem*)searchListBox->firstChild();	
    		for (int i=0;i<searchListBox->childCount();i++) {
		   	    ret=removeRecursive(parent, strApplDir);
				if (stopped==TRUE)
					break;
				parent=(KUninstallListItem*)parent->nextSibling();
			}	
		}
	}	
	if (ret==TRUE) {
	    QString str;
	    str.setNum(numberItems);
	    str.prepend(i18n("Summary of Deinstallation: \n"));
	    str+=i18n(" elements with a sum size of ");
	    str+=size2Ascii(sumSize);
	    str+=i18n("Byte have been deleted!");
		KMsgBox::message(this, i18n("Remove summery"),
	          str, KMsgBox::INFORMATION);		
		if (localeKDE->childCount()==0 && installKDE->childCount()==0) {
			ret=TRUE;
			wipeOff();
			showBackupBox();
		}	
		else
			ret=FALSE;	
	}
	return ret;
}

void KUninstallerView::wipeOff() {
	removeTree();
    stopped=FALSE;
    setNumberLabel(0);
    setSizeLabel(0);
	applicationCombo->setText("");
}

void KUninstallerView::undo() {
	bool ret=TRUE;
	QDir dir=QDir::home();
	dir.setPath(strApplDir);
	QString dirName = dir.dirName();
	dirName.truncate(dirName.findRev('-'));
	applicationCombo->setText(dirName);
	const QFileInfoList *list=dir.entryInfoList ( "*.ori", QDir::Files);
	unsigned int index=0;
	removeTree();
	if (list!=0 && list->count()!=0) {
		QFileInfo* firstInfo=list->first();
		for (index=0;index<list->count();index++) {
	  		KSimpleConfig kconfig(firstInfo->absFilePath());
	  		QString source=firstInfo->fileName();
	  		source.truncate(source.findRev('.'));
	  		source.prepend("/");
	  		source.prepend(firstInfo->dirPath());
	  		QString target=kconfig.readEntry("Link");
			QFileInfo tinfo(target);
			ret=move_a_file (source,target);
			if (ret==TRUE)
	  			insertItem(tinfo);
			firstInfo=list->next();
		}
		if (ret==TRUE) {
			removeRecursiveBackup(strApplDir);
			showBackupBox();
		}	
		else
			KMsgBox::message(this, i18n("Undo information"),
	          	i18n("Error during undo of backup!\nApplication isn't completely installed"),
	          	KMsgBox::INFORMATION);				
	}	
}

void KUninstallerView::stop() {
    stopped=TRUE;
}

QStrList *KUninstallerView::getTextForPrinting() {
    QStrList *strList=0;
	if (searchListBox->childCount()>0) {
    	strList=new QStrList();
    	QString str(i18n("These are the parts of the application "));
    	str+= applicationCombo->text();
    	str+=" :";
    	strList->append(str);
    	KUninstallListItem *parent1= (KUninstallListItem *)searchListBox->firstChild();
		for(int i=0;i<searchListBox->childCount();i++) {
		    strList->append(parent1->text());	
        	KUninstallListItem *item=(KUninstallListItem*)parent1->firstChild();
			while (item!=0) {
				QString str("        ");
				str+= item->text();
		    	strList->append(str);	
		   		item=(KUninstallListItem *)item->nextSibling();		     	
		    }
		   	parent1=(KUninstallListItem *)parent1->nextSibling();
		    strList->append("\n");	
		}
	}
	return strList;
}

int KUninstallerView::find(QString path, bool isRecursive, bool completeName) {
	// return code: 0 means nothing found , 1 means ok
    int ret=0;
	QDir dir(path);
	if (stopped==TRUE)
	   return ret;
	QString findPatternLower =  findPattern.lower();
	dir.setFilter(QDir::Dirs | QDir::Hidden | QDir::Files);
	if (dir.exists()==TRUE) {
	    const QFileInfoList *strList = dir.entryInfoList();
		QFileInfo *f=strList->first();
		while (f!=0) {
			QString tmpStr(f->absFilePath());
        	if ((dir.match(findPattern,f->fileName())==TRUE ||
        	    dir.match(findPatternLower,f->fileName())==TRUE) &&
        	    (f->absFilePath().contains("-backup")==0)) {
        	    	insertItem(*f);
        	    	if (completeName==TRUE) {
        	    		if (f->baseName()!=applicationCombo->text())
        	    			applicationCombo->setText(f->baseName());
        	    	}
					ret=1;
			}
			else if (isRecursive==TRUE) {
			    if ((f->fileName()!=".") && (f->fileName()!="..") 
				     && f->isDir() && f->isSymLink()==FALSE) {
					qApp->processEvents();	// for processing pending events
				    ret=find(f->absFilePath(),isRecursive);
				}	
			}
		    f=strList->next();
		}
	}		
	return ret;
}

bool KUninstallerView::removeRecursive(KUninstallListItem *parent, const char* backupStr)  {
	bool ret=FALSE;
	QDir dir(strApplDir);
	QString newFile;
	if (parent!=0) {
		if (parent->childCount()==0)
			ret=TRUE;
		else {	
        	KUninstallListItem *item=(KUninstallListItem*)parent->firstChild();
			while (item!=0) {
		    	KUninstallListItem * olditem=item;	
		   		item=(KUninstallListItem *)olditem->nextSibling();		     	
		   		if (olditem->isOn()==TRUE) {
		    		if (saveUninstalling==true) {
		    			QString str= olditem->info().fileName();
		    			str+="*.ori";
		    			const QFileInfoList *list=dir.entryInfoList ( str, QDir::Files);
		    			unsigned int index=0;
		    			if (list!=0 && list->count()!=0) {
		    				QFileInfo* firstStr=list->first();
		    				for (index=0;index<list->count();index++) {
	  							KSimpleConfig kconfig(firstStr->absFilePath());
	  							QString oriPath=kconfig.readEntry("Link");
	  							if (oriPath==olditem->info().absFilePath()) {
	  								newFile=firstStr->filePath();
	  								break;
	  							}		    					
		    					firstStr=list->next();
		    				}
		    			}
		    			if (index==list->count()) {
		   		    		newFile=backupStr;
		    				newFile+="/";
		    				newFile+=olditem->info().fileName();
		    				str=newFile;
		    				str.truncate(newFile.findRev('/'));
		    				if (str==strApplDir) {
		    					index++;
		    					str.setNum(index);
		    					newFile+=str;
		    				}		
		    			}
		    		}
		   	    	if (olditem->info().isDir()==TRUE) {
		    			if (saveUninstalling==true) {
		    			    if (dir.mkdir(newFile)==TRUE)
		   	    				ret=removeRecursive(olditem, newFile);
		   	    			else {
		    					QString str(i18n("Backup error!\n"));
		    					str+=i18n("Reason: ");
		    					str+=strerror(errno);
								KMsgBox::message(this, i18n("Backup error"), str, KMsgBox::EXCLAMATION);		    			    			
		   	    				break;	
		   	    			}	
		    			}
		    			else
		   	    			ret=removeRecursive(olditem);
		   	    		if (ret==TRUE)
		   	    			dir.rmdir(olditem->info().absFilePath());
		   	    	}		
		   	    	else {
		    			if (saveUninstalling==true) {
		    				if (move_a_file (olditem->info().absFilePath(),newFile)==FALSE) {	
		    					QString str(i18n("Backup error!\n"));
		    					str+=i18n("Reason: ");
		    					str+=strerror(errno);
								KMsgBox::message(this, i18n("Backup error"), str, KMsgBox::EXCLAMATION);		    			    			
		    			    	break;
		    			    }	
		    	    	}
						else		    			
							dir.remove((const char*)olditem->info().absFilePath());
		    	    	ret=TRUE;
		    		}
					if (saveUninstalling==true && backupStr==strApplDir) {
		    			newFile+=".ori";	
	  					KSimpleConfig kconfig(newFile);
		   	    		kconfig.writeEntry("Link",(const char*)olditem->info().absFilePath());

		   	    	}
		   	    	if (ret==TRUE && olditem->childCount()==0)
		   	    		delete olditem;
		    	}	
				if (stopped==TRUE)
					break;
		    }	
		}
	}			
	return ret;
}

void KUninstallerView::saveOptions(KConfig * config) {
}

void KUninstallerView::readOptions(KConfig * config) {
  config->setGroup("OPTIONS");
  saveUninstalling=config->readBoolEntry("Backup", true);
  if (config->readBoolEntry("DefaultPath", true)==true) {
  	 savePath=kapp->localkdedir();
	 savePath+="/share/apps/kuninstaller";
  }	
  else
     savePath=config->readEntry("Path","");
  if ( saveUninstalling == true)
  		numberBackups=config->readNumEntry("NumberBackups",5);
  else		
       numberBackups=0;
}

QString KUninstallerView::size2Ascii(float fsize) {
	QString tmpString;
	if (fsize>=(1024*1024))
	{
		fsize/=(1024*1024);
 		tmpString.sprintf( "%3.2f M", fsize );
	}	
	else if (fsize>=1024)
	{
		fsize/=1024;
		tmpString.sprintf( "%3.2f K", fsize );
	}	
	else
		tmpString.sprintf( "%4.0f", fsize );
	return tmpString;
}


void KUninstallerView::setNumberLabel(int number) {
    numberItems=number;
    QString str;
    str.setNum(number);
    str+=" Object(s) Checked";
	numLabel->setText(str);
}

void KUninstallerView::setSizeLabel(float number) {
    sumSize=number;
    QString str=size2Ascii(number);
	sizeLabel->setText(str);
}

void KUninstallerView::updateLabels(KUninstallListItem * check) {
    int number=0;
   	if (check->isOn()==FALSE) {
        numberItems-=searchListBox->getLastNumber();
   		sumSize-= searchListBox->getLastSize();
    }
    else {
     	sumSize+= check->getSizeAndNumber(number);
        numberItems+=number;
    }
    setNumberLabel(numberItems);
    setSizeLabel(sumSize);
 }

void KUninstallerView::setItemLabels(KUninstallListItem *item, bool withoutSize) {
	if (withoutSize==FALSE) {
		int number=0;
		float fsize=item->getSizeAndNumber(number);
 		numberItems+=number;
		setNumberLabel(numberItems);
		sumSize+= fsize;
		setSizeLabel(sumSize);
	}
}

void KUninstallerView::openApplDialog() {
    if (dialog==0)
    	dialog = new KApplDialog(0,"Dialog");
	dialog->show();
    connect(dialog,SIGNAL(setApplName(const char*)), applicationCombo, SLOT(setText(const char*)));
}

void KUninstallerView::removeTree() {
    delete installKDE;
    delete localeKDE;
	installKDE=0;
	localeKDE=0;
    searchListBox->clear();
}

void KUninstallerView::createTree() {
	if (localeKDE == 0) {
	    QString str = kapp->localkdedir();
	    QFileInfo f(str);
        str.prepend(i18n("Locale KDE Directory -> "));
		localeKDE = new KUninstallListItem(f,searchListBox,str);
		localeKDE->setOpen(TRUE);
	}
	if (installKDE == 0) {	
		QString str = kapp->kde_bindir();
	    QFileInfo f(str);
        str.truncate(str.findRev('/'));
        str.prepend(i18n("KDE Install Directory -> "));
		installKDE = new KUninstallListItem(f,searchListBox,str);
		installKDE->setOpen(TRUE);
    }
}

void KUninstallerView::insertItem(QFileInfo f)
{
	createTree();
    KUninstallListItem *item=0;
    QString str = f.absFilePath();
	if (str.contains(kapp->localkdedir())>0)  {
    	QString str1 = kapp->localkdedir();
     	str.remove(0,str1.length());
     	str.prepend(".");
		item = new KUninstallListItem(f,localeKDE,str, QCheckListItem::CheckBox);
	}
	else  {
        QString str1 = kapp->kde_bindir();
        str.remove(0,str1.findRev('/'));
        str.prepend(".");
		item = new KUninstallListItem(f,installKDE,str, QCheckListItem::CheckBox);
	}
	item->setOn(TRUE);
	if (f.isDir()==TRUE)
		item->showChildItems();
	setItemLabels(item);
	item->setOpen(FALSE);
}

void KUninstallerView::showBackupBox() {
	if (saveUninstalling==false) {
		group2->hide();
		label_2->hide();
		backupCombo->hide();
		deleteBtn->hide();
		installBtn->hide();
	}
	else {
		group2->show();
		label_2->show();
		deleteBtn->show();
		installBtn->show();
		backupCombo->show();
		QDir dir(savePath);
		const QStrList *list=dir.entryList ( "*-backup", QDir::Dirs);
		const char* str=list->first();
		backupCombo->clear();
		if ( list->count()>0) {
			backupCombo->setEnabled(TRUE);
			deleteBtn->setEnabled(TRUE);
			installBtn->setEnabled(TRUE);
			for (int i=0;i<(int)list->count();i++) {
			 	backupCombo->insertItem(str);
			 	str=list->next();
			}
		}
		else {
			backupCombo->setEnabled(FALSE);
			deleteBtn->setEnabled(FALSE);
			installBtn->setEnabled(FALSE);
		}	
	}	
}

void KUninstallerView::deleteSelectedBackup() {
	if (backupCombo->currentText()=="")
			KMsgBox::message(this, i18n("Backup information"),
	          	i18n("No Application Backup selected for deleting!"),
	          	KMsgBox::INFORMATION);		
	QString str(i18n("The Application Backup "));
	str+= backupCombo->currentText();
	str+=i18n(" should be deleted ?");     	
	if (KMsgBox::yesNo(this, i18n("Backup Deleting"), str, KMsgBox::QUESTION) == 1) {
		  QString str1=savePath;
		  str1+="/";
		  str1+=backupCombo->currentText();
		  removeRecursiveBackup(str1);
	}
	showBackupBox();
}

void KUninstallerView::installSelectedBackup() {
	QString oldDir=strApplDir;
	strApplDir=savePath;
	strApplDir+="/";
	strApplDir+=backupCombo->currentText();
	undo();
	strApplDir=oldDir;
	parentApp->enableCommand(ID_NEW);
}

void KUninstallerView::removeAllBackups() {
	if (backupCombo->count()==0)
			KMsgBox::message(this, i18n("Remove Backups"),
	          	i18n("No Application Backups available!"),
	          	KMsgBox::INFORMATION);	
	          			
    else if (KMsgBox::yesNo(this, i18n("Remove Backups"), i18n("Remove all Application Backups ?"),
    		KMsgBox::QUESTION) == 1) {	
		for (int i=0;i<backupCombo->count();i++) {
			QString str=savePath;
			str+="/";
			str+=backupCombo->text(i);
			removeRecursiveBackup(str);
		}
		showBackupBox();
	}
}

bool  KUninstallerView::removeRecursiveBackup(QString str) {
	bool ret=TRUE;
	QDir dir(str);
	const QFileInfoList *list=dir.entryInfoList ( QDir::Files| QDir::Dirs| QDir::Hidden);
	if (list!=0) {
		QFileInfo *f=list->first();
		while (f!=0) {
			if (f->fileName()!="." && f->fileName()!="..") {
				if (f->isDir()==TRUE) {
					ret=removeRecursiveBackup(f->absFilePath());
				}		
				else {
					dir.remove(f->absFilePath());
					ret=TRUE;
				}	
			}
			f=list->next();
		}
	}
	if (ret==TRUE) {
		dir.home();
		dir.rmdir(str);
	}	
	return ret;
}

bool KUninstallerView::move_a_file (QString source, QString target) {
	bool ret=FALSE;
	unsigned int bufferSize = BUFFERSIZE;
	char *cBuffer = new char[bufferSize];
	int throughput;

	QDir dir=QDir::home();
	QFileInfo sinfo(source);
	struct stat temp_state;
    lstat(source, &temp_state);
	
	if (sinfo.isDir()==TRUE) {
		if (mkdir ((const char*)target,temp_state.st_mode)!=-1) {
			ret=TRUE;
			dir.setPath(source);
			const QFileInfoList *list=dir.entryInfoList ( QDir::Files|QDir::Dirs);
			if (list!=0) {
				QFileInfo *f=list->first();
				while (f!=0) {
					if (f->fileName()!="." && f->fileName()!="..") {
						QString newTarget=target;
						newTarget+="/";
						newTarget+=f->fileName();
						ret=move_a_file(f->absFilePath(),newTarget);
					}
					f=list->next();
				}
			}	
		}
		else {
			QString str(i18n("Undo error!\n"));
			str+=i18n("Reason: ");
		 	str+=strerror(errno);
			KMsgBox::message(this, i18n("Undo error"), str, KMsgBox::EXCLAMATION);	
			ret=FALSE;	    			    			
		}
	}
	else {
		QFile inFile(source);
		QFile outFile(target);

		if(inFile.exists()) {
			if (inFile.open(IO_ReadOnly|IO_Raw)==TRUE) {
				if(outFile.open(IO_WriteOnly|IO_Truncate|IO_Raw)==TRUE) {
					if (sinfo.size()!=0) {
						throughput = inFile.readBlock(cBuffer,bufferSize);
						while (throughput != -1 && throughput != 0) {
							if (outFile.writeBlock(cBuffer,throughput) == throughput) {
								ret = TRUE;
								throughput = inFile.readBlock(cBuffer,bufferSize);
							}
							else {
								ret = FALSE;
								break;
							}
						}
					}
					else
						ret=TRUE;   // for 0 Byte files
       				if (ret==FALSE)
						ret=dir.remove(target);
					else {
						chmod(target, temp_state.st_mode);
						ret=dir.remove(source);	
					}			
				}
 			}
		}
	}
	return ret;
}




















































































































































































Documentation generated by haeusler@stiegl on Fri Apr 16 09:31:32 MET DST 1999