forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPsEngine.cpp
More file actions
387 lines (340 loc) · 13.2 KB
/
Copy pathPsEngine.cpp
File metadata and controls
387 lines (340 loc) · 13.2 KB
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
/* Copyright 2015 the SumatraPDF project authors (see AUTHORS file).
License: GPLv3 */
// utils
#include "BaseUtil.h"
#include <zlib.h>
#include "ByteReader.h"
#include "FileUtil.h"
#include "WinUtil.h"
// rendering engines
#include "BaseEngine.h"
#include "PdfEngine.h"
#include "PsEngine.h"
static WCHAR *GetGhostscriptPath()
{
const WCHAR *gsProducts[] = {
L"AFPL Ghostscript",
L"Aladdin Ghostscript",
L"GPL Ghostscript",
L"GNU Ghostscript",
};
// find all installed Ghostscript versions
WStrVec versions;
REGSAM access = KEY_READ | KEY_WOW64_32KEY;
TryAgain64Bit:
for (int i = 0; i < dimof(gsProducts); i++) {
HKEY hkey;
ScopedMem<WCHAR> keyName(str::Join(L"Software\\", gsProducts[i]));
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, access, &hkey) != ERROR_SUCCESS)
continue;
WCHAR subkey[32];
for (DWORD ix = 0; RegEnumKey(hkey, ix, subkey, dimof(subkey)) == ERROR_SUCCESS; ix++)
versions.Append(str::Dup(subkey));
RegCloseKey(hkey);
}
if ((access & KEY_WOW64_32KEY)) {
// also look for 64-bit Ghostscript versions under 64-bit Windows
access = KEY_READ | KEY_WOW64_64KEY;
#ifndef _WIN64
// (unless this is 32-bit Windows)
if (IsRunningInWow64())
#endif
goto TryAgain64Bit;
}
versions.SortNatural();
// return the path to the newest installation
for (size_t ix = versions.Count(); ix > 0; ix--) {
for (int i = 0; i < dimof(gsProducts); i++) {
ScopedMem<WCHAR> keyName(str::Format(L"Software\\%s\\%s",
gsProducts[i], versions.At(ix - 1)));
ScopedMem<WCHAR> GS_DLL(ReadRegStr(HKEY_LOCAL_MACHINE, keyName, L"GS_DLL"));
if (!GS_DLL)
continue;
ScopedMem<WCHAR> dir(path::GetDir(GS_DLL));
ScopedMem<WCHAR> exe(path::Join(dir, L"gswin32c.exe"));
if (file::Exists(exe))
return exe.StealData();
exe.Set(path::Join(dir, L"gswin64c.exe"));
if (file::Exists(exe))
return exe.StealData();
}
}
// if Ghostscript isn't found in the Registry, try finding it in the %PATH%
DWORD size = GetEnvironmentVariable(L"PATH", nullptr, 0);
ScopedMem<WCHAR> envpath(AllocArray<WCHAR>(size));
if (size > 0 && envpath) {
GetEnvironmentVariable(L"PATH", envpath, size);
WStrVec paths;
paths.Split(envpath, L";", true);
for (size_t ix = 0; ix < paths.Count(); ix++) {
ScopedMem<WCHAR> exe(path::Join(paths.At(ix), L"gswin32c.exe"));
if (file::Exists(exe))
return exe.StealData();
exe.Set(path::Join(paths.At(ix), L"gswin64c.exe"));
if (file::Exists(exe))
return exe.StealData();
}
}
return nullptr;
}
class ScopedFile {
ScopedMem<WCHAR> path;
public:
explicit ScopedFile(const WCHAR *path) : path(str::Dup(path)) { }
~ScopedFile() {
if (path)
file::Delete(path);
}
};
static RectI ExtractDSCPageSize(const WCHAR *fileName)
{
char header[1024] = { 0 };
file::ReadN(fileName, header, sizeof(header) - 1);
if (!str::StartsWith(header, "%!PS-Adobe-"))
return RectI();
// PostScript creators are supposed to set the page size
// e.g. through a setpagedevice call in PostScript code,
// some creators however fail to do so and only indicate
// the page size in a DSC BoundingBox comment.
char *nl = header;
geomutil::RectT<float> bbox;
while ((nl = strchr(nl + 1, '\n')) != nullptr && '%' == nl[1]) {
if (str::StartsWith(nl + 1, "%%BoundingBox:") &&
str::Parse(nl + 1, "%%%%BoundingBox: 0 0 %f %f% ", &bbox.dx, &bbox.dy)) {
return bbox.ToInt();
}
}
return RectI();
}
static BaseEngine *ps2pdf(const WCHAR *fileName)
{
// TODO: read from gswin32c's stdout instead of using a TEMP file
ScopedMem<WCHAR> shortPath(path::ShortPath(fileName));
ScopedMem<WCHAR> tmpFile(path::GetTempPath(L"PsE"));
ScopedFile tmpFileScope(tmpFile);
ScopedMem<WCHAR> gswin32c(GetGhostscriptPath());
if (!shortPath || !tmpFile || !gswin32c)
return nullptr;
// try to help Ghostscript determine the intended page size
ScopedMem<WCHAR> psSetup;
RectI page = ExtractDSCPageSize(fileName);
if (!page.IsEmpty())
psSetup.Set(str::Format(L" << /PageSize [%i %i] >> setpagedevice", page.dx, page.dy));
ScopedMem<WCHAR> cmdLine(str::Format(
L"\"%s\" -q -dSAFER -dNOPAUSE -dBATCH -dEPSCrop -sOutputFile=\"%s\" -sDEVICE=pdfwrite -c \".setpdfwrite%s\" -f \"%s\"",
gswin32c.Get(), tmpFile.Get(), psSetup ? psSetup.Get() : L"", shortPath.Get()));
fprintf(stderr, "- %s:%d: using '%ls' for creating '%%TEMP%%\\%ls'\n", path::GetBaseName(__FILE__), __LINE__, gswin32c.Get(), path::GetBaseName(tmpFile));
// TODO: the PS-to-PDF conversion can hang the UI for several seconds
HANDLE process = LaunchProcess(cmdLine, nullptr, CREATE_NO_WINDOW);
if (!process)
return nullptr;
DWORD timeout = 10000;
#ifdef DEBUG
// allow to disable the timeout for debugging purposes
if (GetEnvironmentVariable(L"SUMATRAPDF_NO_GHOSTSCRIPT_TIMEOUT", nullptr, 0))
timeout = INFINITE;
#endif
DWORD exitCode = EXIT_FAILURE;
WaitForSingleObject(process, timeout);
GetExitCodeProcess(process, &exitCode);
TerminateProcess(process, 1);
CloseHandle(process);
if (exitCode != EXIT_SUCCESS)
return nullptr;
size_t len;
ScopedMem<char> pdfData(file::ReadAll(tmpFile, &len));
if (!pdfData)
return nullptr;
ScopedComPtr<IStream> stream(CreateStreamFromData(pdfData, len));
if (!stream)
return nullptr;
return PdfEngine::CreateFromStream(stream);
}
static BaseEngine *psgz2pdf(const WCHAR *fileName)
{
ScopedMem<WCHAR> tmpFile(path::GetTempPath(L"PsE"));
ScopedFile tmpFileScope(tmpFile);
if (!tmpFile)
return nullptr;
gzFile inFile = gzopen_w(fileName, "rb");
if (!inFile)
return nullptr;
FILE *outFile = nullptr;
errno_t err = _wfopen_s(&outFile, tmpFile, L"wb");
if (err != 0 || !outFile) {
gzclose(inFile);
return nullptr;
}
char buffer[12*1024];
for (;;) {
int len = gzread(inFile, buffer, sizeof(buffer));
if (len <= 0)
break;
fwrite(buffer, 1, len, outFile);
}
fclose(outFile);
gzclose(inFile);
return ps2pdf(tmpFile);
}
// PsEngineImpl is mostly a proxy for a PdfEngine that's fed whatever
// the ps2pdf conversion from Ghostscript returns
class PsEngineImpl : public BaseEngine {
public:
PsEngineImpl() : fileName(nullptr), pdfEngine(nullptr) { }
virtual ~PsEngineImpl() {
delete pdfEngine;
}
BaseEngine *Clone() override {
BaseEngine *newEngine = pdfEngine->Clone();
if (!newEngine)
return nullptr;
PsEngineImpl *clone = new PsEngineImpl();
if (fileName)
clone->fileName.Set(str::Dup(fileName));
clone->pdfEngine = newEngine;
return clone;
}
const WCHAR *FileName() const override { return fileName; };
int PageCount() const override {
return pdfEngine->PageCount();
}
RectD PageMediabox(int pageNo) override {
return pdfEngine->PageMediabox(pageNo);
}
RectD PageContentBox(int pageNo, RenderTarget target=Target_View) override {
return pdfEngine->PageContentBox(pageNo, target);
}
RenderedBitmap *RenderBitmap(int pageNo, float zoom, int rotation,
RectD *pageRect=nullptr, /* if nullptr: defaults to the page's mediabox */
RenderTarget target=Target_View, AbortCookie **cookie_out=nullptr) override {
return pdfEngine->RenderBitmap(pageNo, zoom, rotation, pageRect, target, cookie_out);
}
PointD Transform(PointD pt, int pageNo, float zoom, int rotation, bool inverse=false) override {
return pdfEngine->Transform(pt, pageNo, zoom, rotation, inverse);
}
RectD Transform(RectD rect, int pageNo, float zoom, int rotation, bool inverse=false) override {
return pdfEngine->Transform(rect, pageNo, zoom, rotation, inverse);
}
unsigned char *GetFileData(size_t *cbCount) override {
return (unsigned char *)file::ReadAll(fileName, cbCount);
}
bool SaveFileAs(const WCHAR *copyFileName, bool includeUserAnnots=false) override {
UNUSED(includeUserAnnots);
return fileName ? CopyFile(fileName, copyFileName, FALSE) : false;
}
bool SaveFileAsPDF(const WCHAR *pdfFileName, bool includeUserAnnots=false) override {
return pdfEngine->SaveFileAs(pdfFileName, includeUserAnnots);
}
WCHAR * ExtractPageText(int pageNo, const WCHAR *lineSep, RectI **coordsOut=nullptr,
RenderTarget target=Target_View) override {
return pdfEngine->ExtractPageText(pageNo, lineSep, coordsOut, target);
}
bool HasClipOptimizations(int pageNo) override {
return pdfEngine->HasClipOptimizations(pageNo);
}
PageLayoutType PreferredLayout() override {
return pdfEngine->PreferredLayout();
}
WCHAR *GetProperty(DocumentProperty prop) override {
// omit properties created by Ghostscript
if (!pdfEngine || Prop_CreationDate == prop || Prop_ModificationDate == prop ||
Prop_PdfVersion == prop || Prop_PdfProducer == prop || Prop_PdfFileStructure == prop) {
return nullptr;
}
return pdfEngine->GetProperty(prop);
}
bool SupportsAnnotation(bool forSaving=false) const override {
return !forSaving && pdfEngine->SupportsAnnotation();
}
void UpdateUserAnnotations(Vec<PageAnnotation> *list) override {
pdfEngine->UpdateUserAnnotations(list);
}
bool AllowsPrinting() const override {
return pdfEngine->AllowsPrinting();
}
bool AllowsCopyingText() const override {
return pdfEngine->AllowsCopyingText();
}
float GetFileDPI() const override {
return pdfEngine->GetFileDPI();
}
const WCHAR *GetDefaultFileExt() const override {
return !str::EndsWithI(fileName, L".eps") ? L".ps" : L".eps";
}
bool BenchLoadPage(int pageNo) override {
return pdfEngine->BenchLoadPage(pageNo);
}
Vec<PageElement *> *GetElements(int pageNo) override {
return pdfEngine->GetElements(pageNo);
}
PageElement *GetElementAtPos(int pageNo, PointD pt) override {
return pdfEngine->GetElementAtPos(pageNo, pt);
}
PageDestination *GetNamedDest(const WCHAR *name) override {
return pdfEngine->GetNamedDest(name);
}
bool HasTocTree() const override {
return pdfEngine->HasTocTree();
}
DocTocItem *GetTocTree() override {
return pdfEngine->GetTocTree();
}
char *GetDecryptionKey() const override {
return pdfEngine->GetDecryptionKey();
}
static BaseEngine *CreateFromFile(const WCHAR *fileName);
protected:
ScopedMem<WCHAR> fileName;
BaseEngine *pdfEngine;
bool Load(const WCHAR *fileName) {
AssertCrash(!this->fileName && !pdfEngine);
if (!fileName)
return false;
this->fileName.Set(str::Dup(fileName));
if (file::StartsWith(fileName, "\x1F\x8B"))
pdfEngine = psgz2pdf(fileName);
else
pdfEngine = ps2pdf(fileName);
return pdfEngine != nullptr;
}
};
BaseEngine *PsEngineImpl::CreateFromFile(const WCHAR *fileName)
{
PsEngineImpl *engine = new PsEngineImpl();
if (!engine->Load(fileName)) {
delete engine;
return nullptr;
}
return engine;
}
namespace PsEngine {
bool IsAvailable()
{
ScopedMem<WCHAR> gswin32c(GetGhostscriptPath());
return gswin32c.Get() != nullptr;
}
bool IsSupportedFile(const WCHAR *fileName, bool sniff)
{
if (!IsAvailable())
return false;
if (sniff) {
char header[2048] = { 0 };
file::ReadN(fileName, header, sizeof(header) - 1);
if (str::StartsWith(header, "\xC5\xD0\xD3\xC6")) {
// Windows-format EPS file - cf. http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdf
DWORD psStart = ByteReader(header, sizeof(header)).DWordLE(4);
return psStart >= sizeof(header) - 12 || str::StartsWith(header + psStart, "%!PS-Adobe-");
}
return str::StartsWith(header, "%!") ||
// also sniff PJL (Printer Job Language) files containing Postscript data
str::StartsWith(header, "\x1B%-12345X@PJL") && str::Find(header, "\n%!PS-Adobe-");
}
return str::EndsWithI(fileName, L".ps") ||
str::EndsWithI(fileName, L".ps.gz") ||
str::EndsWithI(fileName, L".eps");
}
BaseEngine *CreateFromFile(const WCHAR *fileName)
{
return PsEngineImpl::CreateFromFile(fileName);
}
}