File: file.cpp

package info (click to toggle)
vym 1.10.0-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 5,376 kB
  • ctags: 1,926
  • sloc: cpp: 18,468; xml: 277; sh: 211; perl: 89; makefile: 26
file content (435 lines) | stat: -rw-r--r-- 10,157 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#include <QMessageBox>
#include <QPixmap>
#include <QLabel>
#include <QTextStream>
#include <iostream>

#include "file.h"
#include "process.h"


QString maskPath(QString p)
{
	// Change " " to "\ " to enable blanks in filenames
	p=p.replace(QChar('&'),"\\&");
	return p.replace(QChar(' '),"\\ ");
}

QString convertToRel (const QString &src, const QString &dst)
{
	QString s=src;
	QString d=dst;
	int i;

	if (s==d) 
	{
		// Special case, we just need the name of the file,
		// not the complete path
		i=d.findRev ("/");
		d=d.right (d.length()-i-1);
	} else
	{
		// Find relative path from src to dst

		// Remove the first "/"
		if (s.section ("/",0,0).isEmpty()) 
		{
			s=s.right (s.length()-1);
			d=d.right (d.length()-1);
		}
		
		// remove identical left parts
		while (s.section("/",0,0) == d.section("/",0,0) ) 
		{
			i=s.find ("/");
			s=s.right (s.length()-i-1);
			d=d.right (d.length()-i-1);
		}

		// Now take care of paths where we have to go back first
		int srcsep=s.count("/");
		int dstsep=d.count("/");
		if (srcsep <=  dstsep )
		{
			// find path to go up first and then back to dst
			i=1;
			while (i<=srcsep) 
			{
				d="../"+d;
				i++;
			}	
		}
	}	
	return d;
}

#include <QFileDialog>
extern QString vymName;
extern QDir lastFileDir;

QString browseDirectory (QWidget *parent,const QString &caption)
{
	QFileDialog fd(parent,caption);
	fd.setMode (QFileDialog::DirectoryOnly);
	fd.setCaption(vymName+ " - "+caption);
	fd.setDir (lastFileDir);
	fd.show();
	
	if ( fd.exec() == QDialog::Accepted )
		return fd.selectedFile();
	else
		return "";
}



bool reallyWriteDirectory(const QString &dir)
{
	QStringList eList = QDir(dir).entryList();
	if (eList.first() ==".")  eList.pop_front();	// remove "."
	if (eList.first() =="..") eList.pop_front();	// remove "."
	if (!eList.isEmpty())
	{
		QMessageBox mb( vymName,
			QObject::tr("The directory %1 is not empty.\nDo you risk to overwrite its contents?","write directory").arg(dir),
		QMessageBox::Warning,
		QMessageBox::Yes ,
		QMessageBox::Cancel | QMessageBox::Default,
		QMessageBox::QMessageBox::NoButton );

		mb.setButtonText( QMessageBox::Yes, QObject::tr("Overwrite") );
		mb.setButtonText( QMessageBox::No, QObject::tr("Cancel"));
		switch( mb.exec() ) 
		{
			case QMessageBox::Yes:
				// save 
				return true;
			case QMessageBox::Cancel:
				// do nothing
				return false;
		}
	}
	return true;
}

QString makeUniqueDir (bool &ok,QString s)
{
	// Create unique directory e.g. s="/tmp/vym-XXXXXX"

	// Convert QString to string first
	ok=true;
	char *p;
	int bytes=s.length();
	p=(char*) malloc (bytes+1);
	int i;
	for (i=0;i<bytes;i++)
		p[i]=s.at(i).latin1();
	p[bytes]=0;	
	QString r=mkdtemp (p);
	if (r.isEmpty()) ok=false;
	free (p);
	return r;
}

void removeDir(QDir d)
{
	if (d.path().left(4)!="/tmp")
	{
		// This _should_ not be necessary, but proved to be useful ;-)
		qWarning ("file.cpp::removeDir should remove "+d.path()+" - aborted.");
		return;
	}

	// Traverse directories
	d.setFilter( QDir::Dirs| QDir::Hidden | QDir::NoSymLinks );
	QFileInfoList list = d.entryInfoList();
	QFileInfo fi;

	for (int i = 0; i < list.size(); ++i) 
	{
		fi=list.at(i);
		if (fi.fileName() != "." && fi.fileName() != ".." )
		{
			if ( !d.cd(fi.fileName()) ) 
				qWarning ("removeDir() cannot find the directory "+fi.fileName());
			else 
			{
				// Recursively remove subdirs
				removeDir (d);
				d.cdUp();
			}
		}	
	}

	// Traverse files
	d.setFilter( QDir::Files| QDir::Hidden | QDir::NoSymLinks );
	list = d.entryInfoList();

	for (int i = 0; i < list.size(); ++i) 
	{
		fi=list.at(i);
		QFile (fi.filePath()).remove(); 
	}	

	if (!d.rmdir(d.path()))
		qWarning ("removeDir("+d.path()+") failed!");
}		

void copyDir (QDir src, QDir dst)
{
	system ("cp -r "+src.path()+"/* "+dst.path());

	/*
	ErrorCode err=success;

	Process *cpProc=new Process ();
	QStringList args;
	cpProc->setWorkingDirectory (src.path());
	args <<"-r";
	args <<src.path();
	args <<dst.path();

	cpProc->start ("cp",args);
	if (!cpProc->waitForStarted() )
	{	
		// zip could not be started
		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
					   QObject::tr("Couldn't start zip to compress data."));
		err=aborted;
	} else
	{
		// zip could be started
		cpProc->waitForFinished();
		if (cpProc->exitStatus()!=QProcess::NormalExit )
		{
			QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
						   QObject::tr("cp didn't exit normally")+
						   "\n" + cpProc->getErrout());
			err=aborted;
		} else
		{
			if (cpProc->exitCode()>0)
			{
				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
						   QString("cp exit code:  %1").arg(cpProc->exitCode() )+
						   "\n" + cpProc->getErrout() );
				err=aborted;
			}
		}
	}	// cp could be started
	*/
}

void makeSubDirs (const QString &s)
{
	QDir d(s);
	d.mkdir(s);
	d.mkdir ("images");	
	d.mkdir ("flags");	
}

ErrorCode zipDir (const QDir &zipDir, const QString &zipName)
{
	ErrorCode err=success;
	
	// zip the temporary directory
	QStringList args;
	Process *zipProc=new Process ();
	zipProc->setWorkingDirectory (zipDir.path());
	args <<"-r";
	args <<zipName;
	args <<".";

	zipProc->start ("zip",args);
	if (!zipProc->waitForStarted() )
	{	
		// zip could not be started
		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
					   QObject::tr("Couldn't start zip to compress data."));
		err=aborted;
	} else
	{
		// zip could be started
		zipProc->waitForFinished();
		if (zipProc->exitStatus()!=QProcess::NormalExit )
		{
			QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
						   QObject::tr("zip didn't exit normally")+
						   "\n" + zipProc->getErrout());
			err=aborted;
		} else
		{
			if (zipProc->exitCode()>0)
			{
				QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
						   QString("zip exit code:  %1").arg(zipProc->exitCode() )+
						   "\n" + zipProc->getErrout() );
				err=aborted;
			}
		}
	}	// zip could be started
	return err;	
}

ErrorCode unzipDir (const QDir &zipDir, const QString &zipName)
{
	ErrorCode err=success;

	// Try to unzip file
	QStringList args;
	Process *zipProc=new Process ();
	zipProc->setWorkingDirectory (zipDir.path());
	args << "-o";	// overwrite existing files!
	args << zipName ;
	args << "-d";
	args << zipDir.path();

	zipProc->start ("unzip",args);
	if (!zipProc->waitForStarted() )
	{
		QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
					   QObject::tr("Couldn't start unzip to decompress data."));
		err=aborted;
		
	} else
	{
		zipProc->waitForFinished();
		if (zipProc->exitStatus()!=QProcess::NormalExit )
		{
			QMessageBox::critical( 0,QObject::tr( "Critical Error" ),
						   QObject::tr("unzip didn't exit normally") +
						   zipProc->getErrout() );
			err=aborted;
		} else
		{
			if (zipProc->exitCode()>0)
			{
				if (zipProc->exitCode()==9)
					// no zipped file, but maybe .xml or old version? Try again.
					err=nozip;
				else	
				{
					QMessageBox::critical( 0, QObject::tr( "Critical Error" ),
								   QString("unzip exit code:  %1").arg(zipProc->exitCode() ) +
								   zipProc->getErrout() );
					err=aborted;
				}
			} 
		}
	}
	return err;	
}

bool loadStringFromDisk (const QString &fname, QString &s)
{
	s="";
	QFile file ( fname);
	if ( !file.open( QIODevice::ReadOnly ) ) return false;

	QTextStream ts( &file );
	ts.setEncoding (QTextStream::UnicodeUTF8);
	while ( !ts.atEnd() ) 
		s+=ts.readLine()+"\n"; 
	file.close();
	return true;
}

bool saveStringToDisk (const QString &fname, const QString &s)
{
	QFile file( fname);

	file.setName ( fname);
	if ( !file.open( QIODevice::WriteOnly ) ) 
	{
		file.close();
		return false;
	}	

	// Write it finally, and write in UTF8, no matter what 
	QTextStream ts( &file );
	ts.setEncoding (QTextStream::UnicodeUTF8);
	ts << s;
	file.close();
	return true;
}


ImagePreview::ImagePreview (QWidget *par=0): QLabel (par)
{
	fdia=(Q3FileDialog*)par;
}

void ImagePreview::previewUrl( const Q3Url &u )
{
    QString path = u.path();
    QPixmap pix( path );
    if ( pix.isNull() )
	{
		// Strange: If we have fd->setMode (QFileDialog::ExistingFiles)
		// in the filedialog, then there are 3 calls to previewURL 
		// for each selection. And only the first is the actual selected file
		// while the following 2 point to the directory above the current one.
		// So here's my workaround:
		
		if (fdia && fdia->selectedFiles().count()==0)
			setText( QObject::tr("This is not an image.") );
		if (fdia &&fdia->selectedFiles().count()>1)
			setText( QObject::tr("Sorry, no preview for\nmultiple selected files.") );
	}	
    else
	{
		float max_w=300;
		float max_h=300;
		float r;
		if (pix.width()>max_w)
		{
			r=max_w / pix.width();
			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
			// TODO not a resize, but a shrink/enlarge is needed here...
		}
		if (pix.height()>max_h)
		{
			r=max_h / pix.height();
			pix.resize(qRound(pix.width()*r), qRound(pix.height()*r));
			// TODO not a resize, but a shrink/enlarge is needed here...
		}
        setPixmap( pix );
	}	
}

ImageIO::ImageIO ()
{
	// Create list with supported image types
	// foreach (QByteArray format, QImageWriter::supportedImageFormats()) 
	// imageTypes.append( tr("%1...").arg(QString(format).toUpper()));
	imageFilters.append ("Images (*.png *.jpg *.jpeg *.bmp *.bmp *.ppm *.xpm *.xbm)");
	imageTypes.append ("PNG");
	imageFilters.append ("Portable Network Graphics (*.png)");
	imageTypes.append ("PNG");
	imageFilters.append ("Joint Photographic Experts Group (*.jpg)");
	imageTypes.append ("JPG");
	imageFilters.append ("Joint Photographic Experts Group (*.jpeg)");
	imageTypes.append ("JPG");
	imageFilters.append ("Windows Bitmap (*.bmp)");
	imageTypes.append ("BMP");
	imageFilters.append ("Portable Pixmap (*.ppm)");
	imageTypes.append ("PPM");
	imageFilters.append ("X11 Bitmap (*.xpm)");
	imageTypes.append ("XPM");
	imageFilters.append ("X11 Bitmap (*.xbm)");
	imageTypes.append ("XBM");
}

QStringList ImageIO::getFilters()
{
	return imageFilters;
}

QString ImageIO::getType(QString filter)
{
	for (int i=0;i<imageFilters.count()+1;i++)
		if (imageFilters.at(i)==filter) return imageTypes.at(i);
	return QString();	
}