file.cpp
author insilmaril
Mon, 19 Feb 2007 12:01:52 +0000
changeset 428 9ae68208e2ff
parent 412 8059b6aa74d7
child 502 f3465a5f0dc4
permissions -rw-r--r--
1.8.67 Bugfixes
     1 #include <QMessageBox>
     2 #include <QPixmap>
     3 #include <QLabel>
     4 #include <QTextStream>
     5 #include <iostream>
     6 
     7 #include "file.h"
     8 #include "process.h"
     9 
    10 
    11 QString maskPath(QString p)
    12 {
    13 	// Change " " to "\ " to enable blanks in filenames
    14 	p=p.replace(QChar('&'),"\\&");
    15 	return p.replace(QChar(' '),"\\ ");
    16 }
    17 
    18 QString convertToRel (const QString &src, const QString &dst)
    19 {
    20 	QString s=src;
    21 	QString d=dst;
    22 	int i;
    23 
    24 	if (s==d) 
    25 	{
    26 		// Special case, we just need the name of the file,
    27 		// not the complete path
    28 		i=d.findRev ("/");
    29 		d=d.right (d.length()-i-1);
    30 	} else
    31 	{
    32 		// Find relative path from src to dst
    33 
    34 		// Remove the first "/"
    35 		if (s.section ("/",0,0).isEmpty()) 
    36 		{
    37 			s=s.right (s.length()-1);
    38 			d=d.right (d.length()-1);
    39 		}
    40 		
    41 		// remove identical left parts
    42 		while (s.section("/",0,0) == d.section("/",0,0) ) 
    43 		{
    44 			i=s.find ("/");
    45 			s=s.right (s.length()-i-1);
    46 			d=d.right (d.length()-i-1);
    47 		}
    48 
    49 		// Now take care of paths where we have to go back first
    50 		int srcsep=s.count("/");
    51 		int dstsep=d.count("/");
    52 		if (srcsep <=  dstsep )
    53 		{
    54 			// find path to go up first and then back to dst
    55 			i=1;
    56 			while (i<=srcsep) 
    57 			{
    58 				d="../"+d;
    59 				i++;
    60 			}	
    61 		}
    62 	}	
    63 	return d;
    64 }
    65 
    66 QString makeUniqueDir (bool &ok,QString s)
    67 {
    68 	// Create unique directory e.g. s="/tmp/vym-XXXXXX"
    69 
    70 	// Convert QString to string first
    71 	ok=true;
    72 	char *p;
    73 	int bytes=s.length();
    74 	p=(char*) malloc (bytes+1);
    75 	int i;
    76 	for (i=0;i<bytes;i++)
    77 		p[i]=s.at(i).latin1();
    78 	p[bytes]=0;	
    79 	QString r=mkdtemp (p);
    80 	if (r.isEmpty()) ok=false;
    81 	free (p);
    82 	return r;
    83 }
    84 
    85 void removeDir(QDir d)
    86 {
    87 	if (d.path().left(4)!="/tmp")
    88 	{
    89 		// This _should_ not be necessary, but proved to be useful ;-)
    90 		qWarning ("file.cpp::removeDir should remove "+d.path()+" - aborted.");
    91 		return;
    92 	}
    93 
    94 	// Traverse directories
    95 	d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
    96 	QFileInfoList list = d.entryInfoList();
    97 	QFileInfo fi;
    98 
    99 	for (int i = 0; i < list.size(); ++i) 
   100 	{
   101 		fi=list.at(i);
   102 		if (fi.fileName() != "." && fi.fileName() != ".." )
   103 		{
   104 			if ( !d.cd(fi.fileName()) ) 
   105 				qWarning ("removeDir() cannot find the directory "+fi.fileName());
   106 			else 
   107 			{
   108 				// Recursively remove subdirs
   109 				removeDir (d);
   110 				d.cdUp();
   111 			}
   112 		}	
   113 	}
   114 
   115 	// Traverse files
   116 	d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
   117 	list = d.entryInfoList();
   118 
   119 	for (int i = 0; i < list.size(); ++i) 
   120 	{
   121 		fi=list.at(i);
   122 		QFile (fi.filePath()).remove(); 
   123 	}	
   124 
   125 	if (!d.rmdir(d.path()))
   126 		qWarning ("removeDir("+d.path()+") failed!");
   127 }		
   128 
   129 void makeSubDirs (const QString &s)
   130 {
   131 	QDir d(s);
   132 	d.mkdir(s);
   133 	d.mkdir ("images");	
   134 	d.mkdir ("flags");	
   135 }
   136 
   137 ErrorCode zipDir (const QDir &zipDir, const QString &zipName)
   138 {
   139 	ErrorCode err=success;
   140 	
   141 	// zip the temporary directory
   142 	QStringList args;
   143 	Process *zipProc=new Process ();
   144 	zipProc->setWorkingDirectory (zipDir.path());
   145 	args <<"-r";
   146 	args <<zipName;
   147 	args <<".";
   148 
   149 	zipProc->start ("zip",args);
   150 	if (!zipProc->waitForStarted() )
   151 	{	
   152 		// zip could not be started
   153 		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   154 					   QObject::tr("Couldn't start zip to compress data."));
   155 		err=aborted;
   156 	} else
   157 	{
   158 		// zip could be started
   159 		zipProc->waitForFinished();
   160 		if (zipProc->exitStatus()!=QProcess::NormalExit )
   161 		{
   162 			QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   163 						   QObject::tr("zip didn't exit normally")+
   164 						   "\n" + zipProc->getErrout());
   165 			err=aborted;
   166 		} else
   167 		{
   168 			if (zipProc->exitCode()>0)
   169 			{
   170 				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   171 						   QString("zip exit code:  %1").arg(zipProc->exitCode() )+
   172 						   "\n" + zipProc->getErrout() );
   173 				err=aborted;
   174 			}
   175 		}
   176 	}	// zip could be started
   177 	return err;	
   178 }
   179 
   180 ErrorCode unzipDir (const QDir &zipDir, const QString &zipName)
   181 {
   182 	ErrorCode err=success;
   183 
   184 	// Try to unzip file
   185 	QStringList args;
   186 	Process *zipProc=new Process ();
   187 	zipProc->setWorkingDirectory (zipDir.path());
   188 	args << "-o";	// overwrite existing files!
   189 	args << zipName ;
   190 	args << "-d";
   191 	args << zipDir.path();
   192 
   193 	zipProc->start ("unzip",args);
   194 	if (!zipProc->waitForStarted() )
   195 	{
   196 		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   197 					   QObject::tr("Couldn't start unzip to decompress data."));
   198 		err=aborted;
   199 		
   200 	} else
   201 	{
   202 		zipProc->waitForFinished();
   203 		if (zipProc->exitStatus()!=QProcess::NormalExit )
   204 		{
   205 			QMessageBox::critical( 0,QObject::tr( "Critical Error" ),
   206 						   QObject::tr("unzip didn't exit normally") +
   207 						   zipProc->getErrout() );
   208 			err=aborted;
   209 		} else
   210 		{
   211 			if (zipProc->exitCode()>0)
   212 			{
   213 				if (zipProc->exitCode()==9)
   214 					// no zipped file, but maybe .xml or old version? Try again.
   215 					err=nozip;
   216 				else	
   217 				{
   218 					QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   219 								   QString("unzip exit code:  %1").arg(zipProc->exitCode() ) +
   220 								   zipProc->getErrout() );
   221 					err=aborted;
   222 				}
   223 			} 
   224 		}
   225 	}
   226 	return err;	
   227 }
   228 
   229 bool loadStringFromDisk (const QString &fname, QString &s)
   230 {
   231 	s="";
   232 	QFile file ( fname);
   233 	if ( !file.open( QIODevice::ReadOnly ) ) return false;
   234 
   235 	QTextStream ts( &file );
   236 	ts.setEncoding (QTextStream::UnicodeUTF8);
   237 	while ( !ts.atEnd() ) 
   238 		s+=ts.readLine()+"\n"; 
   239 	file.close();
   240 	return true;
   241 }
   242 
   243 bool saveStringToDisk (const QString &fname, const QString &s)
   244 {
   245 	QFile file( fname);
   246 
   247 	file.setName ( fname);
   248 	if ( !file.open( QIODevice::WriteOnly ) ) 
   249 	{
   250 		file.close();
   251 		return false;
   252 	}	
   253 
   254 	// Write it finally, and write in UTF8, no matter what 
   255 	QTextStream ts( &file );
   256 	ts.setEncoding (QTextStream::UnicodeUTF8);
   257 	ts << s;
   258 	file.close();
   259 	return true;
   260 }
   261 
   262 
   263 ImagePreview::ImagePreview (QWidget *par=0): QLabel (par)
   264 {
   265 	fdia=(Q3FileDialog*)par;
   266 }
   267 
   268 void ImagePreview::previewUrl( const Q3Url &u )
   269 {
   270     QString path = u.path();
   271     QPixmap pix( path );
   272     if ( pix.isNull() )
   273 	{
   274 		// Strange: If we have fd->setMode (QFileDialog::ExistingFiles)
   275 		// in the filedialog, then there are 3 calls to previewURL 
   276 		// for each selection. And only the first is the actual selected file
   277 		// while the following 2 point to the directory above the current one.
   278 		// So here's my workaround:
   279 		
   280 		if (fdia && fdia->selectedFiles().count()==0)
   281 			setText( QObject::tr("This is not an image.") );
   282 		if (fdia &&fdia->selectedFiles().count()>1)
   283 			setText( QObject::tr("Sorry, no preview for\nmultiple selected files.") );
   284 	}	
   285     else
   286 	{
   287 		float max_w=300;
   288 		float max_h=300;
   289 		float r;
   290 		if (pix.width()>max_w)
   291 		{
   292 			r=max_w / pix.width();
   293 			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
   294 			// TODO not a resize, but a shrink/enlarge is needed here...
   295 		}
   296 		if (pix.height()>max_h)
   297 		{
   298 			r=max_h / pix.height();
   299 			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
   300 			// TODO not a resize, but a shrink/enlarge is needed here...
   301 		}
   302         setPixmap( pix );
   303 	}	
   304 }
   305 
   306 ImageIO::ImageIO ()
   307 {
   308 	// Create list with supported image types
   309 	// foreach (QByteArray format, QImageWriter::supportedImageFormats()) 
   310 	// imageTypes.append( tr("%1...").arg(QString(format).toUpper()));
   311 	imageFilters.append ("Images (*.png *.jpg *.jpeg *.bmp *.bmp *.ppm *.xpm *.xbm)");
   312 	imageTypes.append ("PNG");
   313 	imageFilters.append ("Portable Network Graphics (*.png)");
   314 	imageTypes.append ("PNG");
   315 	imageFilters.append ("Joint Photographic Experts Group (*.jpg)");
   316 	imageTypes.append ("JPG");
   317 	imageFilters.append ("Joint Photographic Experts Group (*.jpeg)");
   318 	imageTypes.append ("JPG");
   319 	imageFilters.append ("Windows Bitmap (*.bmp)");
   320 	imageTypes.append ("BMP");
   321 	imageFilters.append ("Portable Pixmap (*.ppm)");
   322 	imageTypes.append ("PPM");
   323 	imageFilters.append ("X11 Bitmap (*.xpm)");
   324 	imageTypes.append ("XPM");
   325 	imageFilters.append ("X11 Bitmap (*.xbm)");
   326 	imageTypes.append ("XBM");
   327 }
   328 
   329 QStringList ImageIO::getFilters()
   330 {
   331 	return imageFilters;
   332 }
   333 
   334 QString ImageIO::getType(QString filter)
   335 {
   336 	for (int i=0;i<imageFilters.count()+1;i++)
   337 		if (imageFilters.at(i)==filter) return imageTypes.at(i);
   338 	return QString();	
   339 }
   340 
   341