file.cpp
author insilmaril
Wed, 20 Jun 2007 11:05:39 +0000
changeset 520 0ccc00c05a22
parent 502 f3465a5f0dc4
child 521 27cb122a88a6
permissions -rw-r--r--
scripted exports (continued)
     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 copyDir (QDir src, QDir dst)
   130 {
   131 	system ("cp -r "+src.path()+"/* "+dst.path());
   132 
   133 	/*
   134 	ErrorCode err=success;
   135 
   136 	Process *cpProc=new Process ();
   137 	QStringList args;
   138 	cpProc->setWorkingDirectory (src.path());
   139 	args <<"-r";
   140 	args <<src.path();
   141 	args <<dst.path();
   142 
   143 	cpProc->start ("cp",args);
   144 	if (!cpProc->waitForStarted() )
   145 	{	
   146 		// zip could not be started
   147 		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   148 					   QObject::tr("Couldn't start zip to compress data."));
   149 		err=aborted;
   150 	} else
   151 	{
   152 		// zip could be started
   153 		cpProc->waitForFinished();
   154 		if (cpProc->exitStatus()!=QProcess::NormalExit )
   155 		{
   156 			QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   157 						   QObject::tr("cp didn't exit normally")+
   158 						   "\n" + cpProc->getErrout());
   159 			err=aborted;
   160 		} else
   161 		{
   162 			if (cpProc->exitCode()>0)
   163 			{
   164 				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   165 						   QString("cp exit code:  %1").arg(cpProc->exitCode() )+
   166 						   "\n" + cpProc->getErrout() );
   167 				err=aborted;
   168 			}
   169 		}
   170 	}	// cp could be started
   171 	*/
   172 }
   173 
   174 void makeSubDirs (const QString &s)
   175 {
   176 	QDir d(s);
   177 	d.mkdir(s);
   178 	d.mkdir ("images");	
   179 	d.mkdir ("flags");	
   180 }
   181 
   182 ErrorCode zipDir (const QDir &zipDir, const QString &zipName)
   183 {
   184 	ErrorCode err=success;
   185 	
   186 	// zip the temporary directory
   187 	QStringList args;
   188 	Process *zipProc=new Process ();
   189 	zipProc->setWorkingDirectory (zipDir.path());
   190 	args <<"-r";
   191 	args <<zipName;
   192 	args <<".";
   193 
   194 	zipProc->start ("zip",args);
   195 	if (!zipProc->waitForStarted() )
   196 	{	
   197 		// zip could not be started
   198 		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   199 					   QObject::tr("Couldn't start zip to compress data."));
   200 		err=aborted;
   201 	} else
   202 	{
   203 		// zip could be started
   204 		zipProc->waitForFinished();
   205 		if (zipProc->exitStatus()!=QProcess::NormalExit )
   206 		{
   207 			QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   208 						   QObject::tr("zip didn't exit normally")+
   209 						   "\n" + zipProc->getErrout());
   210 			err=aborted;
   211 		} else
   212 		{
   213 			if (zipProc->exitCode()>0)
   214 			{
   215 				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   216 						   QString("zip exit code:  %1").arg(zipProc->exitCode() )+
   217 						   "\n" + zipProc->getErrout() );
   218 				err=aborted;
   219 			}
   220 		}
   221 	}	// zip could be started
   222 	return err;	
   223 }
   224 
   225 ErrorCode unzipDir (const QDir &zipDir, const QString &zipName)
   226 {
   227 	ErrorCode err=success;
   228 
   229 	// Try to unzip file
   230 	QStringList args;
   231 	Process *zipProc=new Process ();
   232 	zipProc->setWorkingDirectory (zipDir.path());
   233 	args << "-o";	// overwrite existing files!
   234 	args << zipName ;
   235 	args << "-d";
   236 	args << zipDir.path();
   237 
   238 	zipProc->start ("unzip",args);
   239 	if (!zipProc->waitForStarted() )
   240 	{
   241 		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   242 					   QObject::tr("Couldn't start unzip to decompress data."));
   243 		err=aborted;
   244 		
   245 	} else
   246 	{
   247 		zipProc->waitForFinished();
   248 		if (zipProc->exitStatus()!=QProcess::NormalExit )
   249 		{
   250 			QMessageBox::critical( 0,QObject::tr( "Critical Error" ),
   251 						   QObject::tr("unzip didn't exit normally") +
   252 						   zipProc->getErrout() );
   253 			err=aborted;
   254 		} else
   255 		{
   256 			if (zipProc->exitCode()>0)
   257 			{
   258 				if (zipProc->exitCode()==9)
   259 					// no zipped file, but maybe .xml or old version? Try again.
   260 					err=nozip;
   261 				else	
   262 				{
   263 					QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   264 								   QString("unzip exit code:  %1").arg(zipProc->exitCode() ) +
   265 								   zipProc->getErrout() );
   266 					err=aborted;
   267 				}
   268 			} 
   269 		}
   270 	}
   271 	return err;	
   272 }
   273 
   274 bool loadStringFromDisk (const QString &fname, QString &s)
   275 {
   276 	s="";
   277 	QFile file ( fname);
   278 	if ( !file.open( QIODevice::ReadOnly ) ) return false;
   279 
   280 	QTextStream ts( &file );
   281 	ts.setEncoding (QTextStream::UnicodeUTF8);
   282 	while ( !ts.atEnd() ) 
   283 		s+=ts.readLine()+"\n"; 
   284 	file.close();
   285 	return true;
   286 }
   287 
   288 bool saveStringToDisk (const QString &fname, const QString &s)
   289 {
   290 	QFile file( fname);
   291 
   292 	file.setName ( fname);
   293 	if ( !file.open( QIODevice::WriteOnly ) ) 
   294 	{
   295 		file.close();
   296 		return false;
   297 	}	
   298 
   299 	// Write it finally, and write in UTF8, no matter what 
   300 	QTextStream ts( &file );
   301 	ts.setEncoding (QTextStream::UnicodeUTF8);
   302 	ts << s;
   303 	file.close();
   304 	return true;
   305 }
   306 
   307 
   308 ImagePreview::ImagePreview (QWidget *par=0): QLabel (par)
   309 {
   310 	fdia=(Q3FileDialog*)par;
   311 }
   312 
   313 void ImagePreview::previewUrl( const Q3Url &u )
   314 {
   315     QString path = u.path();
   316     QPixmap pix( path );
   317     if ( pix.isNull() )
   318 	{
   319 		// Strange: If we have fd->setMode (QFileDialog::ExistingFiles)
   320 		// in the filedialog, then there are 3 calls to previewURL 
   321 		// for each selection. And only the first is the actual selected file
   322 		// while the following 2 point to the directory above the current one.
   323 		// So here's my workaround:
   324 		
   325 		if (fdia && fdia->selectedFiles().count()==0)
   326 			setText( QObject::tr("This is not an image.") );
   327 		if (fdia &&fdia->selectedFiles().count()>1)
   328 			setText( QObject::tr("Sorry, no preview for\nmultiple selected files.") );
   329 	}	
   330     else
   331 	{
   332 		float max_w=300;
   333 		float max_h=300;
   334 		float r;
   335 		if (pix.width()>max_w)
   336 		{
   337 			r=max_w / pix.width();
   338 			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
   339 			// TODO not a resize, but a shrink/enlarge is needed here...
   340 		}
   341 		if (pix.height()>max_h)
   342 		{
   343 			r=max_h / pix.height();
   344 			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
   345 			// TODO not a resize, but a shrink/enlarge is needed here...
   346 		}
   347         setPixmap( pix );
   348 	}	
   349 }
   350 
   351 ImageIO::ImageIO ()
   352 {
   353 	// Create list with supported image types
   354 	// foreach (QByteArray format, QImageWriter::supportedImageFormats()) 
   355 	// imageTypes.append( tr("%1...").arg(QString(format).toUpper()));
   356 	imageFilters.append ("Images (*.png *.jpg *.jpeg *.bmp *.bmp *.ppm *.xpm *.xbm)");
   357 	imageTypes.append ("PNG");
   358 	imageFilters.append ("Portable Network Graphics (*.png)");
   359 	imageTypes.append ("PNG");
   360 	imageFilters.append ("Joint Photographic Experts Group (*.jpg)");
   361 	imageTypes.append ("JPG");
   362 	imageFilters.append ("Joint Photographic Experts Group (*.jpeg)");
   363 	imageTypes.append ("JPG");
   364 	imageFilters.append ("Windows Bitmap (*.bmp)");
   365 	imageTypes.append ("BMP");
   366 	imageFilters.append ("Portable Pixmap (*.ppm)");
   367 	imageTypes.append ("PPM");
   368 	imageFilters.append ("X11 Bitmap (*.xpm)");
   369 	imageTypes.append ("XPM");
   370 	imageFilters.append ("X11 Bitmap (*.xbm)");
   371 	imageTypes.append ("XBM");
   372 }
   373 
   374 QStringList ImageIO::getFilters()
   375 {
   376 	return imageFilters;
   377 }
   378 
   379 QString ImageIO::getType(QString filter)
   380 {
   381 	for (int i=0;i<imageFilters.count()+1;i++)
   382 		if (imageFilters.at(i)==filter) return imageTypes.at(i);
   383 	return QString();	
   384 }
   385 
   386