file.cpp
author insilmaril
Tue, 04 Jul 2006 12:10:56 +0000
branchqt4-port
changeset 7 84f76a3876d7
parent 4 ec3d2962893d
child 19 caba269c3757
permissions -rw-r--r--
fixed recent maps and xlinks
     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 (QString s)
    69 {
    70 	// Create unique directory e.g. s="/tmp/vym-XXXXXX"
    71 
    72 	// Convert QString to string first
    73 	char *p;
    74 	int bytes=s.length();
    75 	p=(char*) malloc (bytes+1);
    76 	int i;
    77 	for (i=0;i<bytes;i++)
    78 		p[i]=s.at(i).latin1();
    79 	p[bytes]=0;	
    80 	QString r=mkdtemp (p);
    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 	Process *zipProc=new Process ();
   143 	zipProc->clearArguments();
   144 	zipProc->setWorkingDirectory (QDir(zipDir));
   145 	zipProc->addArgument ("zip");
   146 	zipProc->addArgument ("-r");
   147 	zipProc->addArgument (zipName);
   148 	zipProc->addArgument (".");
   149 
   150 	if (!zipProc->start() )
   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->waitFinished();
   160 		if (!zipProc->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->exitStatus()>0)
   169 			{
   170 				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
   171 						   QString("zip exit code:  %1").arg(zipProc->exitStatus() )+
   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 	Process *zipProc=new Process ();
   186 	zipProc->clearArguments();
   187 	zipProc->setWorkingDirectory (zipDir);
   188 	zipProc->addArgument ("unzip");
   189 	zipProc->addArgument ("-o");	// overwrite existing files!
   190 	zipProc->addArgument (zipName );
   191 	zipProc->addArgument ("-d");
   192 	zipProc->addArgument (zipDir.path());
   193 
   194 	if (!zipProc->start() )
   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->waitFinished();
   203 		if (!zipProc->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->exitStatus()>0)
   212 			{
   213 				if (zipProc->exitStatus()==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->exitStatus() ) +
   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 			// FIXME 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 			// FIXME 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 }
   339 
   340