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