Debian Codegraph @

sys/Printer.cpp

raw
1 /* Printer.cpp
2 *
3 * Copyright (C) 1998-2017,2021,2023,2025,2026 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <unistd.h> // close
20
21 #include "melder.h"
22
23 #if defined (_WIN32)
24 #include <windows.h>
25 #endif
26
27 #include "Printer.h"
28 #include "praat.h" // topShell
29 #include "Ui.h"
30 #include "site.h"
31 #include "GraphicsP.h"
32
33 #if cocoa
34 #include "Picture.h"
35 #endif
36
37 /*
38 Everything must look the same on every printer, including on PDF,
39 so the margins must be constant with respect to the paper, not to the writable page.
40 */
41 Printer thePrinter = {
42 kGraphicsPostscript_spots::DEFAULT,
43 kGraphicsPostscript_paperSize::DEFAULT,
44 kGraphicsPostscript_orientation::DEFAULT,
45 false, true,
46 kGraphicsPostscript_fontChoiceStrategy::DEFAULT,
47 600, 5100, 6600,
48 1.0
49 };
50
51 void Printer_prefs () {
52 Preferences_addEnum (U"Printer.spots", & thePrinter. spots, kGraphicsPostscript_spots, kGraphicsPostscript_spots::DEFAULT);
53 Preferences_addEnum (U"Printer.paperSize", & thePrinter. paperSize, kGraphicsPostscript_paperSize, kGraphicsPostscript_paperSize::DEFAULT);
54 Preferences_addBool (U"Printer.allowDirectPostScript", & thePrinter. allowDirectPostScript, true);
55 Preferences_addEnum (U"Printer.fontChoiceStrategy", & thePrinter. fontChoiceStrategy, kGraphicsPostscript_fontChoiceStrategy, kGraphicsPostscript_fontChoiceStrategy::DEFAULT);
56 }
57
58 #if cocoa
59 static NSView *theMacView;
60 #endif
61 #ifdef _WIN32
62 static PRINTDLG theWinPrint;
63 static HDC theWinDC;
64 #endif
65
66 #if defined (_WIN32)
67 int Printer_postScript_printf (void *stream, const char *format, ... ) {
68 static union { char chars [3002]; short shorts [1501]; } theLine;
69 int length;
70 va_list args;
71 va_start (args, format);
72 (void) stream;
73 vsprintf (theLine.chars + 2, format, args);
74 length = strlen (theLine.chars + 2); // TODO: check overflow
75 theLine.shorts [0] = length;
76 if (length > 0 && theLine.chars [length + 1] == '\n') {
77 theLine.chars [length + 1] = '\r';
78 theLine.chars [length + 2] = '\n';
79 theLine.chars [length + 3] = '\0';
80 length ++;
81 }
82 Escape (theWinDC, POSTSCRIPT_PASSTHROUGH, length + 2, theLine.chars, nullptr);
83 va_end (args);
84 return 1;
85 }
86 #endif
87
88 #if defined (_WIN32)
89 static void initPostScriptPage () {
90 /*
91 * Save the driver's state.
92 */
93 Printer_postScript_printf (nullptr, "/PraatPictureSaveObject save def\n");
94 /*
95 * The LaserWriter driver puts the coordinates upside down.
96 * According to the PostScript Reference Manual,
97 * "There are few situations in which a PostScript language program
98 * should execute initgraphics explicitly."
99 * This is one of them.
100 BUG: it probably is *not* one of them. Just do something like
101 currentmatrix [1 0 -1 0 0 0] mul setmatrix
102 or whatever it is.
103 */
104 #if 1
105 Printer_postScript_printf (nullptr, "initmatrix initclip\n");
106 #else
107 Printer_postScript_printf (nullptr, "8 8 scale initclip\n");
108 #endif
109 }
110 static void exitPostScriptPage () {
111 Printer_postScript_printf (nullptr, "PraatPictureSaveObject restore\n");
112 }
113 #endif
114
115 #if cocoa
116 #elif defined (_WIN32)
117 static void initPrinter () {
118 }
119 #endif
120
121 void Printer_nextPage () {
122 #if cocoa
123 [theMacView endPage];
124 [theMacView beginPageInRect: [theMacView bounds] atPlacement: NSMakePoint (0, 0)];
125 #elif defined (_WIN32)
126 if (thePrinter. postScript) {
127 exitPostScriptPage ();
128 EndPage (theWinDC);
129 StartPage (theWinDC);
130 initPostScriptPage ();
131 } else {
132 if (EndPage (theWinDC) < 0)
133 (void) 0; // FIXME: should give the opportunity of cancellation
134 StartPage (theWinDC);
135 /*
136 * Since StartPage has reset the DC, restore some of our non-default settings.
137 */
138 SetBkMode (theWinDC, TRANSPARENT);
139 SetTextAlign (theWinDC, TA_LEFT | TA_BASELINE | TA_NOUPDATECP);
140 }
141 #endif
142 }
143
144 int Printer_pageSetup () {
145 #if cocoa
146 NSPageLayout *cocoaPageSetupDialog = [NSPageLayout pageLayout];
147 [cocoaPageSetupDialog runModal];
148 #elif defined (_WIN32)
149 #endif
150 return 1;
151 }
152
153 #ifdef _WIN32
154 static BOOL CALLBACK AbortFunc (HDC hdc, int nCode) {
155 MSG msg;
156 (void) hdc;
157 (void) nCode;
158 while (PeekMessage (& msg, 0, 0, 0, PM_REMOVE)) {
159 TranslateMessage (& msg);
160 DispatchMessage (& msg);
161 }
162 return true;
163 }
164 HDC Printer_getDC () {
165 if (! theWinPrint. hDevMode) {
166 memset (& theWinPrint, 0, sizeof (PRINTDLG));
167 theWinPrint. lStructSize = sizeof (PRINTDLG);
168 theWinPrint. Flags = PD_RETURNDEFAULT | PD_RETURNDC;
169 PrintDlg (& theWinPrint);
170 }
171 return theWinPrint. hDC;
172 }
173 #endif
174
175 #if cocoa
176 static void (*theDraw) (void *boss, Graphics g);
177 static void *theBoss;
178 @interface GuiCocoaPrintingArea : NSView @end
179 @implementation GuiCocoaPrintingArea {
180 //GuiButton d_userData;
181 }
182 - (void) drawRect: (NSRect) dirtyRect {
183 trace (U"printing ", dirtyRect. origin. x, U" ", dirtyRect. origin. y, U" ", dirtyRect. size. width, U" ", dirtyRect. size. height);
184 int currentPage = [[NSPrintOperation currentOperation] currentPage];
185 {// scope
186 autoGraphics graphics = Graphics_create_screenPrinter (nullptr, self);
187 theDraw (theBoss, graphics.get());
188 }
189 }
190 - (BOOL) isFlipped {
191 return YES;
192 }
193 - (NSPoint) locationOfPrintRect: (NSRect) aRect {
194 (void) aRect;
195 return NSMakePoint (0.0, 0.0); // the origin of the rect's coordinate system is always the top left corner of the physical page
196 }
197 - (BOOL) knowsPageRange: (NSRangePointer) range {
198 range -> length = 1;
199 return YES;
200 }
201 - (NSRect) rectForPage: (NSInteger) pageNumber {
202 (void) pageNumber; // every page has the same rectangle
203 return [self bounds];
204 }
205 - (void) printOperationDidRun: (NSPrintOperation *) printOperation success: (BOOL) success contextInfo: (void *) contextInfo {
206 }
207 @end
208 #endif
209
210 int Printer_print (void (*draw) (void *boss, Graphics g), void *boss) {
211 try {
212 #if defined (UNIX)
213 structMelderFile tempFile { };
214 char tempPath_utf8 [] = "/tmp/picXXXXXX";
215 close (mkstemp (tempPath_utf8));
216 Melder_pathToFile (Melder_peek8to32_u (tempPath_utf8), & tempFile);
217 {// scope
218 autoGraphics graphics = Graphics_create_postscriptjob (& tempFile, thePrinter. resolution,
219 thePrinter. spots, thePrinter. paperSize, thePrinter. orientation, thePrinter. magnification);
220 draw (boss, graphics.get());
221 }
222 char command [500];
223 snprintf (command,500, Melder_peek32to8 (Site_getPrintCommand ()), tempPath_utf8);
224 system (command);
225 MelderFile_delete (& tempFile);
226 #elif cocoa
227 theDraw = draw;
228 theBoss = boss;
229 NSPrintInfo *info = [NSPrintInfo sharedPrintInfo];
230 NSSize paperSize = [info paperSize];
231 //NSLog (@"%f %f", paperSize. width, paperSize. height);
232 thePrinter. paperWidth = paperSize. width / 0.12;
233 thePrinter. paperHeight = paperSize. height / 0.12;
234 [info setLeftMargin: 0.0];
235 [info setRightMargin: 0.0];
236 [info setTopMargin: 0.0];
237 [info setBottomMargin: 0.0];
238 /*
239 * Although the paper size reported may be 595 x 842 points (A4),
240 * 783 points (just under 11 inches) is the largest height that keeps the view on one page.
241 */
242 int viewWidth = paperSize. width;
243 int viewHeight = paperSize. height;
244 NSLog (@"%d %d", viewWidth, viewHeight);
245 NSRect rect = NSMakeRect (0, 0, viewWidth, viewHeight);
246 NSView *cocoaPrintingArea = [[GuiCocoaPrintingArea alloc] initWithFrame: rect];
247 theMacView = cocoaPrintingArea;
248 [cocoaPrintingArea setBoundsSize: NSMakeSize (viewWidth / 0.12, viewHeight / 0.12)]; // 72 points per inch / 600 dpi = 0.12 points per dot
249 [cocoaPrintingArea setBoundsOrigin: NSMakePoint (0, 0)];
250 NSPrintOperation *op = [NSPrintOperation
251 printOperationWithView: cocoaPrintingArea];
252 #if 1
253 if (op) [op runOperation];
254 #else
255 /*
256 * This may crash with multiple pages.
257 */
258 if (op) {
259 [op setCanSpawnSeparateThread: NO];
260 NSView *pictureView = ((GraphicsScreen) Picture_peekGraphics ((Picture) boss)) -> d_macView;
261 [op
262 runOperationModalForWindow: [pictureView window]
263 delegate: cocoaPrintingArea
264 didRunSelector: @selector(printOperationDidRun:success:contextInfo:)
265 contextInfo: nil
266 ];
267 }
268 #endif
269 #elif defined (_WIN32)
270 int postScriptCode = POSTSCRIPT_PASSTHROUGH;
271 DOCINFO docInfo;
272 DEVMODE *devMode;
273 initPrinter ();
274 #if 1
275 if (! theWinPrint. hDevMode) {
276 memset (& theWinPrint, 0, sizeof (PRINTDLG));
277 theWinPrint. lStructSize = sizeof (PRINTDLG);
278 theWinPrint. Flags = PD_RETURNDEFAULT;
279 if (! PrintDlg (& theWinPrint))
280 Melder_throw (U"Cannot initialize printer.");
281 }
282 #endif
283 #if 0
284 constexpr DWORD PRINTER_NAME_BUFFER_SIZE = 100;
285 WCHAR printerName [PRINTER_NAME_BUFFER_SIZE];
286 DWORD printerNameLengthIncludingTrailingNull = PRINTER_NAME_BUFFER_SIZE;
287 GetDefaultPrinter (printerName, & printerNameLengthIncludingTrailingNull);
288 Melder_casual (U"Printer_print: name ", Melder_peekWto32 (printerName));
289 if (Melder_equ (Melder_peekWto32 (printerName), U"Microsoft Print to PDF")) {
290 HWND hwnd = (HWND) XtWindow (theCurrentPraatApplication -> topShell -> d_xmShell);
291 HANDLE printerHandle;
292 OpenPrinter (printerName, & printerHandle, nullptr);
293 WCHAR deviceName [] = L"device name";
294 LONG devModeSize = DocumentProperties (hwnd, printerHandle, deviceName, nullptr, nullptr, 0);
295 Melder_casual (U"Printer_print: devModeSize ", devModeSize);
296 static BYTE devMode2 [5420];
297 if (DocumentProperties (hwnd, printerHandle, deviceName, (PDEVMODEW) devMode2, nullptr, DM_OUT_BUFFER) < 0)
298 Melder_casual (U"Printer_print: second call to DocumentProperties fails.");
299 ((DEVMODE *) devMode2) -> dmFields = DM_PAPERLENGTH | DM_PAPERWIDTH;
300 ((DEVMODE *) devMode2) -> dmPaperWidth = 6.0 * thePrinter. resolution; // attempt to change, but...
301 ((DEVMODE *) devMode2) -> dmPaperLength = 4.0 * thePrinter. resolution; // attempt to change, but...
302 //((DEVMODE *) devMode2) -> dmPaperSize = 0;
303 Melder_casual (U"Printer_print: paper width ", ((DEVMODE *) devMode2) -> dmPaperWidth);
304 Melder_casual (U"Printer_print: paper length ", ((DEVMODE *) devMode2) -> dmPaperLength);
305 if (DocumentProperties (hwnd, printerHandle, deviceName, (PDEVMODEW) devMode2, (PDEVMODEW) devMode2, DM_OUT_BUFFER | DM_IN_BUFFER) < 0)
306 Melder_casual (U"Printer_print: third call to DocumentProperties fails.");
307 Melder_casual (U"Printer_print: paper width ", ((DEVMODE *) devMode2) -> dmPaperWidth); // ...as of 20210920, this has still been overridden
308 Melder_casual (U"Printer_print: paper length ", ((DEVMODE *) devMode2) -> dmPaperLength); // ...as of 20210920, this has still been overridden
309 theWinPrint. hDC = CreateDCW (nullptr, L"Microsoft Print to PDF", nullptr, (PDEVMODEW) devMode2);
310 Melder_casual (U"Printer_print: hDC ", Melder_pointer (theWinPrint. hDC));
311 static DEVMODE * devMode3;
312 devMode3 = (PDEVMODEW) devMode2;
313 Melder_casual (U"Printer_print: devMode3 ", Melder_pointer (devMode3));
314 theWinPrint. hDevMode = & devMode3;
315 Melder_casual (U"Printer_print: theWinPrint. hDevMode ", Melder_pointer (theWinPrint. hDevMode));
316 ClosePrinter (printerHandle);
317 }
318 #else
319 if (Melder_backgrounding) {
320 theWinPrint. Flags = PD_RETURNDEFAULT | PD_RETURNDC;
321 if (! PrintDlg (& theWinPrint) || ! theWinPrint. hDC)
322 Melder_throw (U"Cannot print from a script on this computer.");
323 } else {
324 theWinPrint. Flags &= ~ PD_RETURNDEFAULT;
325 theWinPrint. Flags |= PD_RETURNDC;
326 if (! PrintDlg (& theWinPrint))
327 return 1;
328 }
329 #endif
330 theWinDC = theWinPrint. hDC;
331 thePrinter. postScript = thePrinter. allowDirectPostScript &&
332 Escape (theWinDC, QUERYESCSUPPORT, sizeof (int), (LPSTR) & postScriptCode, nullptr);
333 Melder_casual (U"Printer_print: PostScript ", thePrinter. postScript);
334 /*
335 * The HP colour inkjet printer returns in dmFields:
336 * 0, 1, 8, 9, 10, 11, 12, 13, 14, 15, 23, 24, 25, 26 = DM_ORIENTATION |
337 * DM_PAPERSIZE | DM_COPIES | DM_DEFAULTSOURCE | DM_PRINTQUALITY |
338 * DM_COLOR | DM_DUPLEX | DM_YRESOLUTION | DM_TTOPTION | DM_COLLATE |
339 * DM_ICMMETHOD | DM_ICMINTENT | DM_MEDIATYPE | DM_DITHERTYPE
340 */
341 devMode = * (DEVMODE **) theWinPrint. hDevMode;
342 thePrinter. resolution = devMode -> dmFields & DM_YRESOLUTION ? devMode -> dmYResolution :
343 devMode -> dmFields & DM_PRINTQUALITY ?
344 ( devMode -> dmPrintQuality > 0 ? devMode -> dmPrintQuality : 300 ) : 300;
345 if (devMode -> dmFields & DM_PAPERWIDTH) {
346 thePrinter. paperWidth = devMode -> dmPaperWidth * thePrinter. resolution / 254;
347 thePrinter. paperHeight = devMode -> dmPaperLength * thePrinter. resolution / 254;
348 } else if (devMode -> dmFields & DM_PAPERSIZE) {
349 static struct { float width, height; } sizes [] = { { 0, 0 }, { 8.5, 11 }, { 8.5, 11 }, { 11, 17 },
350 { 17, 11 }, { 8.5, 14 }, { 5.5, 8.5 }, { 7.25, 10.5 }, { 297/25.4, 420/25.4 },
351 { 210/25.4, 297/25.4 }, { 210/25.4, 297/25.4 }, { 148.5/25.4, 210/25.4 },
352 { 250/25.4, 354/25.4 }, { 182/25.4, 257/25.4 }, { 8.5, 13 },
353 { 215/25.4, 275/25.4 }, { 10, 14 }, { 11, 17 }, { 8.5, 11 }, { 3.875, 8.875 },
354 { 4.125, 9.5 }, { 4.5, 10.375 } };
355 int paperSize = devMode -> dmPaperSize;
356 if (paperSize <= 0 || paperSize > 21)
357 paperSize = 1;
358 thePrinter. paperWidth = sizes [paperSize]. width * thePrinter. resolution;
359 thePrinter. paperHeight = sizes [paperSize]. height * thePrinter. resolution;
360 if (devMode -> dmOrientation == DMORIENT_LANDSCAPE)
361 std::swap (thePrinter. paperWidth, thePrinter. paperHeight);
362 } else {
363 thePrinter. paperWidth = 1000;
364 thePrinter. paperHeight = 1000;
365 }
366 Melder_casual (U"Printer_print: paper width ", thePrinter. paperWidth);
367 Melder_casual (U"Printer_print: paper length ", thePrinter. paperHeight);
368 EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell -> d_xmShell), false);
369 SetAbortProc (theWinDC, AbortFunc);
370 memset (& docInfo, 0, sizeof (DOCINFO));
371 docInfo. cbSize = sizeof (DOCINFO);
372 docInfo. lpszDocName = L"Praatjes";
373 docInfo. lpszOutput = nullptr;
374 if (thePrinter. postScript) {
375 StartDoc (theWinDC, & docInfo);
376 StartPage (theWinDC);
377 initPostScriptPage ();
378 {// scope
379 autoGraphics graphics = Graphics_create_postscriptprinter ();
380 draw (boss, graphics.get());
381 }
382 exitPostScriptPage ();
383 EndPage (theWinDC);
384 EndDoc (theWinDC);
385 } else {
386 StartDoc (theWinDC, & docInfo);
387 StartPage (theWinDC);
388 {// scope
389 autoGraphics graphics = Graphics_create_screenPrinter (nullptr, theWinDC);
390 draw (boss, graphics.get());
391 }
392 if (EndPage (theWinDC) < 0) {
393 Melder_throw (U"Cannot print page.");
394 } else {
395 EndDoc (theWinDC);
396 }
397 }
398 EnableWindow ((HWND) XtWindow (theCurrentPraatApplication -> topShell -> d_xmShell), true);
399 DeleteDC (theWinDC), theWinDC = nullptr;
400 #endif
401 return 1;
402 } catch (MelderError) {
403 Melder_throw (U"Not printed.");
404 }
405 }
406
407 /* End of file Printer.cpp */