summaryrefslogtreecommitdiffstats
path: root/scribus/util_ghostscript.cpp
blob: 0e0223d843cb18a441315a78baae8b9e385dc4c5 (plain)
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
For general Scribus (>=1.3.2) copyright and licensing information please refer
to the COPYING file provided with the program. Following this notice may exist
a copyright and/or license notice that predates the release of Scribus 1.3.2
for which a new license (GPL+exception) is in place.
*/
/***************************************************************************
                          gsutil.cpp  -  description
                             -------------------
    begin                : Fri Sep 14 2001
    copyright            : (C) 2001 by Franz Schmid
    copyright            : (C) 2006- Scribus Team (code moved from util.cpp)
    email                : Franz.Schmid@altmuehlnet.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "util_ghostscript.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QPainter>
#include <QPixmap>
#include <QProcess>

#include "scconfig.h"

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#if defined(_WIN32)
#include <windows.h>
#ifndef KEY_WOW64_32KEY
	#define KEY_WOW64_32KEY (0x0200)
#endif
#ifndef KEY_WOW64_64KEY
	#define KEY_WOW64_64KEY (0x0100)
#endif
#endif

#include "prefsfile.h"
#include "prefsmanager.h"
#include "scpaths.h"
#include "scribuscore.h"
#include "scribus.h"
#include "util.h"

using namespace std;


int callGS(const QStringList& args_in, const QString device)
{
	QString cmd;
 	QStringList args;
	PrefsManager* prefsManager = PrefsManager::instance();
	args.append( "-q" );
	args.append( "-dNOPAUSE" );
	args.append( "-dQUIET" );
	args.append( "-dPARANOIDSAFER" );
	args.append( "-dBATCH" );
	// Choose rendering device
	if (!device.isEmpty())
		args.append( QString("-sDEVICE=%1").arg(device) ); // user specified device
	else if (!ScCore->havePNGAlpha())
		args.append( "-sDEVICE=png16m" );
	else
		args.append( "-sDEVICE=pngalpha" );
	// and antialiasing
	if (prefsManager->appPrefs.gs_AntiAliasText)
		args.append( "-dTextAlphaBits=4" );
	if (prefsManager->appPrefs.gs_AntiAliasGraphics)
		args.append( "-dGraphicsAlphaBits=4" );

	// Add any extra font paths being used by Scribus to gs's font search path
	PrefsContext *pc = PrefsManager::instance()->prefsFile->getContext("Fonts");
	PrefsTable *extraFonts = pc->getTable("ExtraFontDirs");
	const char sep = ScPaths::envPathSeparator;
	if (extraFonts->getRowCount() >= 1)
		cmd = QString("-sFONTPATH=%1").arg(QDir::toNativeSeparators(extraFonts->get(0,0)));
	for (int i = 1; i < extraFonts->getRowCount(); ++i)
		cmd += QString("%1%2").arg(sep).arg(QDir::toNativeSeparators(extraFonts->get(i,0)));
	if( !cmd.isEmpty() )
		args.append( cmd );

	args += args_in;
	args.append("-c");
	args.append("showpage");
//	qDebug(args.join(" ").toAscii());
	return System( getShortPathName(prefsManager->ghostscriptExecutable()), args );
}

int callGS(const QString& args_in, const QString device)
{
	PrefsManager* prefsManager=PrefsManager::instance();
	QString cmd1 = getShortPathName(prefsManager->ghostscriptExecutable());
	cmd1 += " -q -dNOPAUSE -dQUIET -dPARANOIDSAFER -dBATCH";
	// Choose rendering device
	if (!device.isEmpty())
		// user specified device
		cmd1 += " -sDEVICE="+device;
	else if (!ScCore->havePNGAlpha())
		cmd1 += " -sDEVICE=png16m";
	else
		cmd1 += " -sDEVICE=pngalpha";
	// and antialiasing
	if (prefsManager->appPrefs.gs_AntiAliasText)
		cmd1 += " -dTextAlphaBits=4";
	if (prefsManager->appPrefs.gs_AntiAliasGraphics)
		cmd1 += " -dGraphicsAlphaBits=4";

	// Add any extra font paths being used by Scribus to gs's font search path
	PrefsContext *pc = PrefsManager::instance()->prefsFile->getContext("Fonts");
	PrefsTable *extraFonts = pc->getTable("ExtraFontDirs");
#ifndef _WIN32
	if (extraFonts->getRowCount() >= 1)
		cmd1 += QString(" -sFONTPATH='%1'").arg(extraFonts->get(0,0));
	for (int i = 1; i < extraFonts->getRowCount(); ++i)
		cmd1 += QString(":'%1'").arg(extraFonts->get(i,0));
#else
	if (extraFonts->getRowCount() >= 1)
		cmd1 += QString(" -sFONTPATH=\"%1\"").arg(extraFonts->get(0,0));
	for (int i = 1; i < extraFonts->getRowCount(); ++i)
		cmd1 += QString(";\"%1\"").arg(extraFonts->get(i,0));
#endif

	// then add any user specified args and run gs
	cmd1 += " " + args_in + " -c showpage";
//	qDebug("Calling gs as: %s", cmd1.ascii());
	return system(cmd1.toLocal8Bit().constData());
}

int convertPS2PS(QString in, QString out, const QStringList& opts, int level)
{
	PrefsManager* prefsManager=PrefsManager::instance();
	QStringList args;
	args.append( "-q" );
	args.append( "-dQUIET" );
	args.append( "-dNOPAUSE" );
	args.append( "-dPARANOIDSAFER" );
	args.append( "-dBATCH" );
	if( level == 2 )
	{
		int major = 0, minor = 0;
		// ps2write cannot be detected with testGSAvailability()
		// so determine availability according to gs version.
		getNumericGSVersion(major, minor);
		if ((major >=8 && minor >= 53) || major > 8)
			args.append( "-sDEVICE=ps2write" );
		else
		{
			args.append( "-sDEVICE=pswrite" );
			args.append( QString("-dLanguageLevel=%1").arg(level) );
		}
			
	}
	else
	{
		args.append( "-sDEVICE=pswrite" );
		if(level <= 3)
			args.append( QString("-dLanguageLevel=%1").arg(level) );
	}
	args += opts;
	args.append( QString("-sOutputFile=%1").arg(QDir::toNativeSeparators(out)) );
	args.append( QDir::toNativeSeparators(in) );
	int ret = System( getShortPathName(prefsManager->ghostscriptExecutable()), args );
	return ret;
}

int convertPS2PDF(QString in, QString out, const QStringList& opts)
{
	PrefsManager* prefsManager=PrefsManager::instance();
	QStringList args;
	args.append( "-q" );
	args.append( "-dQUIET" );
	args.append( "-dNOPAUSE" );
	args.append( "-dPARANOIDSAFER" );
	args.append( "-dBATCH" );
	args.append( "-sDEVICE=pdfwrite" );
	args += opts;
	args.append( QString("-sOutputFile=%1").arg(QDir::toNativeSeparators(out)) );
	args.append( QDir::toNativeSeparators(in) );
	int ret = System( getShortPathName(prefsManager->ghostscriptExecutable()), args );
	return ret;
}

bool testGSAvailability( void )
{
	QStringList args;
	PrefsManager* prefsManager = PrefsManager::instance();
	return testGSAvailability(prefsManager->ghostscriptExecutable());
}

bool testGSAvailability( const QString& gsPath )
{
	QStringList args;
	args.append( "-h" );
	QProcess proc;
	proc.start(getShortPathName(gsPath), args);
	if (!proc.waitForStarted(5000))
		return false;
	proc.waitForFinished(5000);
	return (proc.exitCode()==0);
}

bool testGSDeviceAvailability( const QString& device )
{
	QStringList args;
	PrefsManager* prefsManager = PrefsManager::instance();
	args.append( QString("-sDEVICE=%1").arg( device ) );
	args.append( "-c" );
	args.append( "quit" );
	QProcess proc;
	proc.start(getShortPathName(prefsManager->ghostscriptExecutable()), args);
	if (!proc.waitForStarted(5000))
		return false;
	proc.waitForFinished(5000);
	return (proc.exitCode()==0);
}

// Return the GhostScript version string, or QString::null if it couldn't be retrived.
QString getGSVersion()
{
	QStringList args;
	args.append(QString("--version").toLocal8Bit());
	QString gsExe = getShortPathName(PrefsManager::instance()->ghostscriptExecutable());
	QProcess proc;
	proc.start(gsExe.toLocal8Bit(), args);
	if (proc.waitForStarted(5000))
		while (!proc.waitForFinished(5000))
			qApp->processEvents();
	QString gsVer;
	if (proc.exitStatus()==QProcess::NormalExit)
		gsVer = proc.readAllStandardOutput();
	return gsVer;
}

// Return the GhostScript major and minor version numbers.
bool getNumericGSVersion(int & major, int & minor)
{
	QString gs_ver_string(getGSVersion());
	return getNumericGSVersion(gs_ver_string, major, minor);
}

bool getNumericGSVersion(const QString& ver, int& major, int& minor)
{
	// gs's version string is of the form MAJOR.MINOR, so look for the .
	// then convert to numbers. 7.07 will become (7,7) for example.
	bool success = false;
	major = ver.section('.', 0, 0).toInt(&success);
	if (!success)
		return false;
	minor = ver.section('.', 1, 1).toInt(&success);
	if (!success)
		return false;
	return true;
}

QString getGSDefaultExeName(void)
{
	QString gsName("gs");
#if defined _WIN32
	// Set gsName to its default value
	gsName = "gswin32c.exe";

	// Test is we are running a 64bit version of WINDOWS
	bool isWindows64 = false;
	wchar_t* procArch = _wgetenv(L"PROCESSOR_ARCHITECTURE");
	if (procArch)
	{
		isWindows64 |= (wcscmp(procArch, L"AMD64") == 0);
		isWindows64 |= (wcscmp(procArch, L"IA64") == 0);
	}
	wchar_t* procArchWow64 = _wgetenv(L"PROCESSOR_ARCHITEW6432");
	if (procArchWow64) isWindows64 = true;

	// Search for Ghostsscript executable in native registry
	QMap<int, QString> gsVersions;
	gsVersions.unite( getGSExePaths("SOFTWARE\\GPL Ghostscript") );
	gsVersions.unite( getGSExePaths("SOFTWARE\\AFPL Ghostscript") );

	// If running on Windows 64bit, search alternate registry view,
	// ie 32bit registry if process is 64bit, 64bit registry if process is 32bit
	if (isWindows64)
	{
		gsVersions.unite( getGSExePaths("SOFTWARE\\GPL Ghostscript", true) );
		gsVersions.unite( getGSExePaths("SOFTWARE\\AFPL Ghostscript", true) );
	}

	if (gsVersions.isEmpty())
		return gsName;

	int currentVer = 0;
	QString gsPath;
	QMap<int, QString>::ConstIterator it, itEnd = gsVersions.constEnd();
	for (it = gsVersions.constBegin(); it != itEnd; ++it)
	{
		int version = it.key();
		if (version > currentVer)
		{
			gsPath = it.value();
			QFileInfo fInfo(gsPath);
			if (fInfo.exists())
			{
				gsName = gsPath;
				currentVer = version;
			}
		}
	}
#endif
#if defined Q_OS_MAC
	QStringList gsPaths;
	gsPaths << "/usr/bin/gs" << "/usr/local/bin/gs" << "/opt/local/bin/gs" << "/sw/bin/gs";
	for (int i = 0; i < gsPaths.size(); ++i)
	{
		QFileInfo fInfo(gsPaths.at(i));
		if (fInfo.exists())
		{
			gsName = gsPaths.at(i);
			break;
		}
	}
#endif
	return gsName;
}

QMap<int, QString> SCRIBUS_API getGSExePaths(const QString& regKey, bool alternateView)
{
	QMap<int, QString> gsVersions;
#if defined _WIN32
	// Try to locate GhostScript thanks to the registry
	DWORD size;
	HKEY hKey1, hKey2;
	DWORD regType = REG_SZ;
	REGSAM flags  = KEY_READ;
	WCHAR regVersion[MAX_PATH];
	WCHAR regPath[MAX_PATH];
	WCHAR gsPath[MAX_PATH];
	QString gsVersion, gsExeName, gsName;

	bool isWin64Api = false;
#if defined(_WIN64)
	isWin64Api = true;
#endif

	gsExeName = isWin64Api ? "gswin64c.exe" : "gswin32c.exe";
	if (alternateView)
	{
		gsExeName = isWin64Api ? "gswin32c.exe" : "gswin64c.exe";
		flags |= (isWin64Api ? KEY_WOW64_32KEY : KEY_WOW64_64KEY);
	}

	if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, (LPCWSTR) regKey.utf16(), 0, flags, &hKey1) == ERROR_SUCCESS)
	{
		size = sizeof(regVersion)/sizeof(WCHAR) - 1;
		DWORD keyIndex = 0;
		while (RegEnumKeyExW(hKey1, keyIndex, regVersion, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
		{
			int gsNumericVer, gsMajor, gsMinor;
			wcscpy(regPath, (const wchar_t*) regKey.utf16());
			wcscat(regPath, L"\\");
			wcscat(regPath, regVersion);
			if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, regPath, 0, flags, &hKey2) == ERROR_SUCCESS)
			{
				size = sizeof(gsPath) - 1;
				if (RegQueryValueExW(hKey2, L"GS_DLL", 0, &regType, (LPBYTE) gsPath, &size) == ERROR_SUCCESS)
				{
					// We now have GhostScript dll path, but we want gswin32c.exe
					// Normally gswin32c.exe and gsdll.dll are in the same directory
					if ( getNumericGSVersion(QString::fromUtf16((const ushort*) regVersion), gsMajor, gsMinor) )
					{
						gsNumericVer = gsMajor * 1000 + gsMinor;
						gsName = QString::fromUtf16((const ushort*) gsPath);
						size   = gsName.lastIndexOf("\\");
						if (size > 0)
						{
							gsName  = gsName.left(size + 1);
							gsName += gsExeName;
							gsName.replace("\\", "/");
							gsVersions.insert(gsNumericVer, gsName);
						}	
					}	
				}
				RegCloseKey(hKey2);
			}
			keyIndex++;
		}
		RegCloseKey(hKey1);
	}
#else
	int gsNumericVer, gsMajor, gsMinor;
	PrefsManager* prefsManager=PrefsManager::instance();
	if (getNumericGSVersion(gsMajor, gsMinor))
	{
		gsNumericVer = gsMajor * 1000 + gsMinor;
		gsVersions.insert(gsNumericVer, prefsManager->ghostscriptExecutable());
	}
#endif
	return gsVersions;
}

QPixmap LoadPDF(QString fn, int Page, int Size, int *w, int *h)
{
	QString tmp, cmd1, cmd2;
	QString pdfFile = QDir::toNativeSeparators(fn);
	QString tmpFile = QDir::toNativeSeparators(ScPaths::getTempFileDir() + "sc.png");
	QPixmap pm;
	int ret = -1;
	tmp.setNum(Page);
	QStringList args;
	args.append("-r72");
//	args.append("-sOutputFile=\""+tmpFile+"\"");
	args.append("-sOutputFile="+tmpFile);
	args.append("-dFirstPage="+tmp);
	args.append("-dLastPage="+tmp);
//	args.append("\""+pdfFile+"\"");
	args.append(pdfFile);
	ret = callGS(args);
	if (ret == 0)
	{
		QImage image;
		image.load(tmpFile);
		QFile::remove(tmpFile);
		QImage im2;
		*h = image.height();
		*w = image.width();
		double sx = image.width() / static_cast<double>(Size);
		double sy = image.height() / static_cast<double>(Size);
		double t = (sy < sx ? sx : sy);
		im2 = image.scaled(static_cast<int>(image.width() / t), static_cast<int>(image.height() / t), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
		pm=QPixmap::fromImage(im2);
		QPainter p;
		p.begin(&pm);
		p.setBrush(Qt::NoBrush);
		p.setPen(Qt::black);
		p.drawRect(0, 0, pm.width(), pm.height());
		p.end();
		im2.detach();
	}
	return pm;
}