Bug 1826564 [wpt PR 39394] - Update mypy, a=testonly
[gecko.git] / widget / nsPrintSettingsService.cpp
blobc33b05be0ebda9db5556ef1c37e605940736fded
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "nsPrintSettingsService.h"
8 #include "mozilla/embedding/PPrintingTypes.h"
9 #include "mozilla/layout/RemotePrintJobChild.h"
10 #include "mozilla/RefPtr.h"
11 #include "nsCoord.h"
12 #include "nsIPrinterList.h"
13 #include "nsReadableUtils.h"
14 #include "nsPrintSettingsImpl.h"
15 #include "nsServiceManagerUtils.h"
16 #include "nsSize.h"
18 #include "nsArray.h"
19 #include "nsXPCOM.h"
20 #include "nsXULAppAPI.h"
22 #include "nsIStringEnumerator.h"
23 #include "stdlib.h"
24 #include "mozilla/StaticPrefs_print.h"
25 #include "mozilla/Preferences.h"
26 #include "nsPrintfCString.h"
28 using namespace mozilla;
29 using namespace mozilla::embedding;
31 typedef mozilla::layout::RemotePrintJobChild RemotePrintJobChild;
33 NS_IMPL_ISUPPORTS(nsPrintSettingsService, nsIPrintSettingsService)
35 // Pref Constants
36 static const char kMarginTop[] = "print_margin_top";
37 static const char kMarginLeft[] = "print_margin_left";
38 static const char kMarginBottom[] = "print_margin_bottom";
39 static const char kMarginRight[] = "print_margin_right";
40 static const char kEdgeTop[] = "print_edge_top";
41 static const char kEdgeLeft[] = "print_edge_left";
42 static const char kEdgeBottom[] = "print_edge_bottom";
43 static const char kEdgeRight[] = "print_edge_right";
45 static const char kIgnoreUnwriteableMargins[] =
46 "print_ignore_unwriteable_margins";
48 static const char kUnwriteableMarginTopTwips[] =
49 "print_unwriteable_margin_top_twips";
50 static const char kUnwriteableMarginLeftTwips[] =
51 "print_unwriteable_margin_left_twips";
52 static const char kUnwriteableMarginBottomTwips[] =
53 "print_unwriteable_margin_bottom_twips";
54 static const char kUnwriteableMarginRightTwips[] =
55 "print_unwriteable_margin_right_twips";
57 // These are legacy versions of the above UnwriteableMargin prefs. The new ones,
58 // which are in twips, were introduced to more accurately record the values.
59 static const char kUnwriteableMarginTop[] = "print_unwriteable_margin_top";
60 static const char kUnwriteableMarginLeft[] = "print_unwriteable_margin_left";
61 static const char kUnwriteableMarginBottom[] =
62 "print_unwriteable_margin_bottom";
63 static const char kUnwriteableMarginRight[] = "print_unwriteable_margin_right";
65 // Prefs for Print Options
66 static const char kPrintHeaderStrLeft[] = "print_headerleft";
67 static const char kPrintHeaderStrCenter[] = "print_headercenter";
68 static const char kPrintHeaderStrRight[] = "print_headerright";
69 static const char kPrintFooterStrLeft[] = "print_footerleft";
70 static const char kPrintFooterStrCenter[] = "print_footercenter";
71 static const char kPrintFooterStrRight[] = "print_footerright";
73 // Additional Prefs
74 static const char kPrintReversed[] = "print_reversed";
75 static const char kPrintInColor[] = "print_in_color";
76 static const char kPrintPaperId[] = "print_paper_id";
77 static const char kPrintPaperSizeUnit[] = "print_paper_size_unit";
78 static const char kPrintPaperWidth[] = "print_paper_width";
79 static const char kPrintPaperHeight[] = "print_paper_height";
80 static const char kPrintOrientation[] = "print_orientation";
81 static const char kPrinterName[] = "print_printer";
82 static const char kPrintToFile[] = "print_to_file";
83 static const char kPrintToFileName[] = "print_to_filename";
84 static const char kPrintPageDelay[] = "print_page_delay";
85 static const char kPrintBGColors[] = "print_bgcolor";
86 static const char kPrintBGImages[] = "print_bgimages";
87 static const char kPrintShrinkToFit[] = "print_shrink_to_fit";
88 static const char kPrintScaling[] = "print_scaling";
89 static const char kPrintDuplex[] = "print_duplex";
91 static const char kJustLeft[] = "left";
92 static const char kJustCenter[] = "center";
93 static const char kJustRight[] = "right";
95 #define NS_PRINTER_LIST_CONTRACTID "@mozilla.org/gfx/printerlist;1"
97 nsresult nsPrintSettingsService::Init() { return NS_OK; }
99 NS_IMETHODIMP
100 nsPrintSettingsService::SerializeToPrintData(nsIPrintSettings* aSettings,
101 PrintData* data) {
102 aSettings->GetPageRanges(data->pageRanges());
104 aSettings->GetEdgeTop(&data->edgeTop());
105 aSettings->GetEdgeLeft(&data->edgeLeft());
106 aSettings->GetEdgeBottom(&data->edgeBottom());
107 aSettings->GetEdgeRight(&data->edgeRight());
109 aSettings->GetMarginTop(&data->marginTop());
110 aSettings->GetMarginLeft(&data->marginLeft());
111 aSettings->GetMarginBottom(&data->marginBottom());
112 aSettings->GetMarginRight(&data->marginRight());
113 aSettings->GetUnwriteableMarginTop(&data->unwriteableMarginTop());
114 aSettings->GetUnwriteableMarginLeft(&data->unwriteableMarginLeft());
115 aSettings->GetUnwriteableMarginBottom(&data->unwriteableMarginBottom());
116 aSettings->GetUnwriteableMarginRight(&data->unwriteableMarginRight());
118 aSettings->GetScaling(&data->scaling());
120 data->printBGColors() = aSettings->GetPrintBGColors();
121 data->printBGImages() = aSettings->GetPrintBGImages();
123 data->ignoreUnwriteableMargins() = aSettings->GetIgnoreUnwriteableMargins();
124 data->honorPageRuleMargins() = aSettings->GetHonorPageRuleMargins();
125 data->usePageRuleSizeAsPaperSize() =
126 aSettings->GetUsePageRuleSizeAsPaperSize();
127 data->showMarginGuides() = aSettings->GetShowMarginGuides();
128 data->printSelectionOnly() = aSettings->GetPrintSelectionOnly();
130 aSettings->GetTitle(data->title());
131 aSettings->GetDocURL(data->docURL());
133 aSettings->GetHeaderStrLeft(data->headerStrLeft());
134 aSettings->GetHeaderStrCenter(data->headerStrCenter());
135 aSettings->GetHeaderStrRight(data->headerStrRight());
137 aSettings->GetFooterStrLeft(data->footerStrLeft());
138 aSettings->GetFooterStrCenter(data->footerStrCenter());
139 aSettings->GetFooterStrRight(data->footerStrRight());
141 aSettings->GetPrintSilent(&data->printSilent());
142 aSettings->GetShrinkToFit(&data->shrinkToFit());
144 aSettings->GetPaperId(data->paperId());
145 aSettings->GetPaperWidth(&data->paperWidth());
146 aSettings->GetPaperHeight(&data->paperHeight());
147 aSettings->GetPaperSizeUnit(&data->paperSizeUnit());
149 aSettings->GetPrintReversed(&data->printReversed());
150 aSettings->GetPrintInColor(&data->printInColor());
151 aSettings->GetOrientation(&data->orientation());
153 aSettings->GetNumCopies(&data->numCopies());
154 aSettings->GetNumPagesPerSheet(&data->numPagesPerSheet());
156 data->outputDestination() = aSettings->GetOutputDestination();
158 data->outputFormat() = aSettings->GetOutputFormat();
159 data->printPageDelay() = aSettings->GetPrintPageDelay();
160 data->resolution() = aSettings->GetResolution();
161 data->duplex() = aSettings->GetDuplex();
163 aSettings->GetIsInitializedFromPrinter(&data->isInitializedFromPrinter());
164 aSettings->GetIsInitializedFromPrefs(&data->isInitializedFromPrefs());
166 // Initialize the platform-specific values that don't
167 // default-initialize, so that we don't send uninitialized data over
168 // IPC (which leads to valgrind warnings, and, for bools, fatal
169 // assertions).
170 // data->driverName() default-initializes
171 // data->deviceName() default-initializes
172 // data->GTKPrintSettings() default-initializes
174 return NS_OK;
177 NS_IMETHODIMP
178 nsPrintSettingsService::DeserializeToPrintSettings(const PrintData& data,
179 nsIPrintSettings* settings) {
180 settings->SetPageRanges(data.pageRanges());
182 settings->SetEdgeTop(data.edgeTop());
183 settings->SetEdgeLeft(data.edgeLeft());
184 settings->SetEdgeBottom(data.edgeBottom());
185 settings->SetEdgeRight(data.edgeRight());
187 settings->SetMarginTop(data.marginTop());
188 settings->SetMarginLeft(data.marginLeft());
189 settings->SetMarginBottom(data.marginBottom());
190 settings->SetMarginRight(data.marginRight());
191 settings->SetUnwriteableMarginTop(data.unwriteableMarginTop());
192 settings->SetUnwriteableMarginLeft(data.unwriteableMarginLeft());
193 settings->SetUnwriteableMarginBottom(data.unwriteableMarginBottom());
194 settings->SetUnwriteableMarginRight(data.unwriteableMarginRight());
196 settings->SetScaling(data.scaling());
198 settings->SetPrintBGColors(data.printBGColors());
199 settings->SetPrintBGImages(data.printBGImages());
200 settings->SetHonorPageRuleMargins(data.honorPageRuleMargins());
201 settings->SetUsePageRuleSizeAsPaperSize(data.usePageRuleSizeAsPaperSize());
202 settings->SetIgnoreUnwriteableMargins(data.ignoreUnwriteableMargins());
203 settings->SetShowMarginGuides(data.showMarginGuides());
204 settings->SetPrintSelectionOnly(data.printSelectionOnly());
206 settings->SetTitle(data.title());
207 settings->SetDocURL(data.docURL());
209 // Header strings...
210 settings->SetHeaderStrLeft(data.headerStrLeft());
211 settings->SetHeaderStrCenter(data.headerStrCenter());
212 settings->SetHeaderStrRight(data.headerStrRight());
214 // Footer strings...
215 settings->SetFooterStrLeft(data.footerStrLeft());
216 settings->SetFooterStrCenter(data.footerStrCenter());
217 settings->SetFooterStrRight(data.footerStrRight());
219 settings->SetPrintSilent(data.printSilent());
220 settings->SetShrinkToFit(data.shrinkToFit());
222 settings->SetPaperId(data.paperId());
224 settings->SetPaperWidth(data.paperWidth());
225 settings->SetPaperHeight(data.paperHeight());
226 settings->SetPaperSizeUnit(data.paperSizeUnit());
228 settings->SetPrintReversed(data.printReversed());
229 settings->SetPrintInColor(data.printInColor());
230 settings->SetOrientation(data.orientation());
232 settings->SetNumCopies(data.numCopies());
233 settings->SetNumPagesPerSheet(data.numPagesPerSheet());
235 settings->SetOutputDestination(
236 nsIPrintSettings::OutputDestinationType(data.outputDestination()));
237 // Output stream intentionally unset, child processes shouldn't care about it.
239 settings->SetOutputFormat(data.outputFormat());
240 settings->SetPrintPageDelay(data.printPageDelay());
241 settings->SetResolution(data.resolution());
242 settings->SetDuplex(data.duplex());
243 settings->SetIsInitializedFromPrinter(data.isInitializedFromPrinter());
244 settings->SetIsInitializedFromPrefs(data.isInitializedFromPrefs());
246 return NS_OK;
249 /** ---------------------------------------------------
250 * Helper function - Creates the "prefix" for the pref
251 * It is either "print."
252 * or "print.printer_<print name>."
254 const char* nsPrintSettingsService::GetPrefName(const char* aPrefName,
255 const nsAString& aPrinterName) {
256 if (!aPrefName || !*aPrefName) {
257 NS_ERROR("Must have a valid pref name!");
258 return aPrefName;
261 mPrefName.AssignLiteral("print.");
263 if (aPrinterName.Length()) {
264 mPrefName.AppendLiteral("printer_");
265 AppendUTF16toUTF8(aPrinterName, mPrefName);
266 mPrefName.Append('.');
268 mPrefName += aPrefName;
270 return mPrefName.get();
274 * This will either read in the generic prefs (not specific to a printer)
275 * or read the prefs in using the printer name to qualify.
276 * It is either "print.attr_name" or "print.printer_HPLasr5.attr_name"
278 nsresult nsPrintSettingsService::ReadPrefs(nsIPrintSettings* aPS,
279 const nsAString& aPrinterName,
280 uint32_t aFlags) {
281 NS_ENSURE_ARG_POINTER(aPS);
283 bool noValidPrefsFound = true;
284 bool b;
285 nsAutoString str;
286 int32_t iVal;
287 double dbl;
289 #define GETBOOLPREF(_prefname, _retval) \
290 NS_SUCCEEDED( \
291 Preferences::GetBool(GetPrefName(_prefname, aPrinterName), _retval))
293 #define GETSTRPREF(_prefname, _retval) \
294 NS_SUCCEEDED( \
295 Preferences::GetString(GetPrefName(_prefname, aPrinterName), _retval))
297 #define GETINTPREF(_prefname, _retval) \
298 NS_SUCCEEDED( \
299 Preferences::GetInt(GetPrefName(_prefname, aPrinterName), _retval))
301 #define GETDBLPREF(_prefname, _retval) \
302 NS_SUCCEEDED(ReadPrefDouble(GetPrefName(_prefname, aPrinterName), _retval))
304 bool gotPaperSizeFromPrefs = false;
305 int16_t paperSizeUnit;
306 double paperWidth, paperHeight;
308 // Paper size prefs are read as a group
309 if (aFlags & nsIPrintSettings::kInitSavePaperSize) {
310 gotPaperSizeFromPrefs = GETINTPREF(kPrintPaperSizeUnit, &iVal) &&
311 GETDBLPREF(kPrintPaperWidth, paperWidth) &&
312 GETDBLPREF(kPrintPaperHeight, paperHeight) &&
313 GETSTRPREF(kPrintPaperId, str);
314 paperSizeUnit = (int16_t)iVal;
316 if (gotPaperSizeFromPrefs &&
317 paperSizeUnit != nsIPrintSettings::kPaperSizeInches &&
318 paperSizeUnit != nsIPrintSettings::kPaperSizeMillimeters) {
319 gotPaperSizeFromPrefs = false;
322 if (gotPaperSizeFromPrefs) {
323 // Bug 315687: Sanity check paper size to avoid paper size values in
324 // mm when the size unit flag is inches. The value 100 is arbitrary
325 // and can be changed.
326 gotPaperSizeFromPrefs =
327 (paperSizeUnit != nsIPrintSettings::kPaperSizeInches) ||
328 (paperWidth < 100.0) || (paperHeight < 100.0);
331 if (gotPaperSizeFromPrefs) {
332 aPS->SetPaperSizeUnit(paperSizeUnit);
333 aPS->SetPaperWidth(paperWidth);
334 aPS->SetPaperHeight(paperHeight);
335 aPS->SetPaperId(str);
336 noValidPrefsFound = false;
340 nsIntSize pageSizeInTwips; // to sanity check margins
341 if (!gotPaperSizeFromPrefs) {
342 aPS->GetPaperSizeUnit(&paperSizeUnit);
343 aPS->GetPaperWidth(&paperWidth);
344 aPS->GetPaperHeight(&paperHeight);
346 if (paperSizeUnit == nsIPrintSettings::kPaperSizeMillimeters) {
347 pageSizeInTwips = nsIntSize((int)NS_MILLIMETERS_TO_TWIPS(paperWidth),
348 (int)NS_MILLIMETERS_TO_TWIPS(paperHeight));
349 } else {
350 pageSizeInTwips = nsIntSize((int)NS_INCHES_TO_TWIPS(paperWidth),
351 (int)NS_INCHES_TO_TWIPS(paperHeight));
354 auto MarginIsOK = [&pageSizeInTwips](const nsIntMargin& aMargin) {
355 return aMargin.top >= 0 && aMargin.right >= 0 && aMargin.bottom >= 0 &&
356 aMargin.left >= 0 && aMargin.LeftRight() < pageSizeInTwips.width &&
357 aMargin.TopBottom() < pageSizeInTwips.height;
360 if (aFlags & nsIPrintSettings::kInitSaveUnwriteableMargins) {
361 nsIntMargin margin;
362 bool allPrefsRead =
363 GETINTPREF(kUnwriteableMarginTopTwips, &margin.top) &&
364 GETINTPREF(kUnwriteableMarginRightTwips, &margin.right) &&
365 GETINTPREF(kUnwriteableMarginBottomTwips, &margin.bottom) &&
366 GETINTPREF(kUnwriteableMarginLeftTwips, &margin.left);
367 if (!allPrefsRead) {
368 // We failed to read the new unwritable margin twips prefs. Try to read
369 // the old ones in case they exist.
370 allPrefsRead =
371 ReadInchesIntToTwipsPref(
372 GetPrefName(kUnwriteableMarginTop, aPrinterName), margin.top) &&
373 ReadInchesIntToTwipsPref(
374 GetPrefName(kUnwriteableMarginLeft, aPrinterName), margin.left) &&
375 ReadInchesIntToTwipsPref(
376 GetPrefName(kUnwriteableMarginBottom, aPrinterName),
377 margin.bottom) &&
378 ReadInchesIntToTwipsPref(
379 GetPrefName(kUnwriteableMarginRight, aPrinterName), margin.right);
381 // SetUnwriteableMarginInTwips does its own validation and drops negative
382 // values individually. We still want to block overly large values though,
383 // so we do that part of MarginIsOK manually.
384 if (allPrefsRead && margin.LeftRight() < pageSizeInTwips.width &&
385 margin.TopBottom() < pageSizeInTwips.height) {
386 aPS->SetUnwriteableMarginInTwips(margin);
387 noValidPrefsFound = false;
391 if (aFlags & nsIPrintSettings::kInitSaveMargins) {
392 int32_t halfInch = NS_INCHES_TO_INT_TWIPS(0.5);
393 nsIntMargin margin(halfInch, halfInch, halfInch, halfInch);
394 bool prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginTop, aPrinterName),
395 margin.top);
396 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginLeft, aPrinterName),
397 margin.left) ||
398 prefRead;
399 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginBottom, aPrinterName),
400 margin.bottom) ||
401 prefRead;
403 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginRight, aPrinterName),
404 margin.right) ||
405 prefRead;
406 if (prefRead && MarginIsOK(margin)) {
407 aPS->SetMarginInTwips(margin);
408 noValidPrefsFound = false;
410 prefRead = GETBOOLPREF(kIgnoreUnwriteableMargins, &b);
411 if (prefRead) {
412 aPS->SetIgnoreUnwriteableMargins(b);
417 if (aFlags & nsIPrintSettings::kInitSaveEdges) {
418 nsIntMargin margin(0, 0, 0, 0);
419 bool prefRead = ReadInchesIntToTwipsPref(
420 GetPrefName(kEdgeTop, aPrinterName), margin.top);
421 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeLeft, aPrinterName),
422 margin.left) ||
423 prefRead;
425 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeBottom, aPrinterName),
426 margin.bottom) ||
427 prefRead;
429 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeRight, aPrinterName),
430 margin.right) ||
431 prefRead;
433 if (prefRead && MarginIsOK(margin)) {
434 aPS->SetEdgeInTwips(margin);
435 noValidPrefsFound = false;
439 if (aFlags & nsIPrintSettings::kInitSaveHeaderLeft) {
440 if (GETSTRPREF(kPrintHeaderStrLeft, str)) {
441 aPS->SetHeaderStrLeft(str);
442 noValidPrefsFound = false;
446 if (aFlags & nsIPrintSettings::kInitSaveHeaderCenter) {
447 if (GETSTRPREF(kPrintHeaderStrCenter, str)) {
448 aPS->SetHeaderStrCenter(str);
449 noValidPrefsFound = false;
453 if (aFlags & nsIPrintSettings::kInitSaveHeaderRight) {
454 if (GETSTRPREF(kPrintHeaderStrRight, str)) {
455 aPS->SetHeaderStrRight(str);
456 noValidPrefsFound = false;
460 if (aFlags & nsIPrintSettings::kInitSaveFooterLeft) {
461 if (GETSTRPREF(kPrintFooterStrLeft, str)) {
462 aPS->SetFooterStrLeft(str);
463 noValidPrefsFound = false;
467 if (aFlags & nsIPrintSettings::kInitSaveFooterCenter) {
468 if (GETSTRPREF(kPrintFooterStrCenter, str)) {
469 aPS->SetFooterStrCenter(str);
470 noValidPrefsFound = false;
474 if (aFlags & nsIPrintSettings::kInitSaveFooterRight) {
475 if (GETSTRPREF(kPrintFooterStrRight, str)) {
476 aPS->SetFooterStrRight(str);
477 noValidPrefsFound = false;
481 if (aFlags & nsIPrintSettings::kInitSaveBGColors) {
482 if (GETBOOLPREF(kPrintBGColors, &b)) {
483 aPS->SetPrintBGColors(b);
484 noValidPrefsFound = false;
488 if (aFlags & nsIPrintSettings::kInitSaveBGImages) {
489 if (GETBOOLPREF(kPrintBGImages, &b)) {
490 aPS->SetPrintBGImages(b);
491 noValidPrefsFound = false;
495 if (aFlags & nsIPrintSettings::kInitSaveReversed) {
496 if (GETBOOLPREF(kPrintReversed, &b)) {
497 aPS->SetPrintReversed(b);
498 noValidPrefsFound = false;
502 if (aFlags & nsIPrintSettings::kInitSaveInColor) {
503 if (GETBOOLPREF(kPrintInColor, &b)) {
504 aPS->SetPrintInColor(b);
505 noValidPrefsFound = false;
509 if (aFlags & nsIPrintSettings::kInitSaveOrientation) {
510 if (GETINTPREF(kPrintOrientation, &iVal) &&
511 (iVal == nsIPrintSettings::kPortraitOrientation ||
512 iVal == nsIPrintSettings::kLandscapeOrientation)) {
513 aPS->SetOrientation(iVal);
514 noValidPrefsFound = false;
518 if (aFlags & nsIPrintSettings::kInitSavePrintToFile) {
519 if (GETBOOLPREF(kPrintToFile, &b)) {
520 aPS->SetOutputDestination(
521 b ? nsIPrintSettings::kOutputDestinationFile
522 : nsIPrintSettings::kOutputDestinationPrinter);
523 noValidPrefsFound = false;
527 if (aFlags & nsIPrintSettings::kInitSaveToFileName) {
528 if (GETSTRPREF(kPrintToFileName, str)) {
529 if (StringEndsWith(str, u".ps"_ns)) {
530 // We only support PDF since bug 1425188 landed. Users may still have
531 // prefs with .ps filenames if they last saved a file as Postscript
532 // though, so we fix that up here. (The pref values will be
533 // overwritten the next time they save to file as a PDF.)
534 str.Truncate(str.Length() - 2);
535 str.AppendLiteral("pdf");
537 aPS->SetToFileName(str);
538 noValidPrefsFound = false;
542 if (aFlags & nsIPrintSettings::kInitSavePageDelay) {
543 // milliseconds
544 if (GETINTPREF(kPrintPageDelay, &iVal) && iVal >= 0 && iVal <= 1000) {
545 aPS->SetPrintPageDelay(iVal);
546 noValidPrefsFound = false;
550 if (aFlags & nsIPrintSettings::kInitSaveShrinkToFit) {
551 if (GETBOOLPREF(kPrintShrinkToFit, &b)) {
552 aPS->SetShrinkToFit(b);
553 noValidPrefsFound = false;
557 if (aFlags & nsIPrintSettings::kInitSaveScaling) {
558 // The limits imposed here are fairly arbitrary and mainly intended to
559 // purge bad values which tend to be negative and/or very large. If we
560 // get complaints from users that settings outside these values "aren't
561 // saved" then we can consider increasing them.
562 if (GETDBLPREF(kPrintScaling, dbl) && dbl >= 0.05 && dbl <= 20) {
563 aPS->SetScaling(dbl);
564 noValidPrefsFound = false;
568 if (aFlags & nsIPrintSettings::kInitSaveDuplex) {
569 if (GETINTPREF(kPrintDuplex, &iVal)) {
570 aPS->SetDuplex(iVal);
571 noValidPrefsFound = false;
575 // Not Reading In:
576 // Number of Copies
577 // Print Resolution
579 return noValidPrefsFound ? NS_ERROR_NOT_AVAILABLE : NS_OK;
582 nsresult nsPrintSettingsService::WritePrefs(nsIPrintSettings* aPS,
583 const nsAString& aPrinterName,
584 uint32_t aFlags) {
585 NS_ENSURE_ARG_POINTER(aPS);
587 if (aFlags & nsIPrintSettings::kInitSaveMargins) {
588 nsIntMargin margin = aPS->GetMarginInTwips();
589 WriteInchesFromTwipsPref(GetPrefName(kMarginTop, aPrinterName), margin.top);
590 WriteInchesFromTwipsPref(GetPrefName(kMarginLeft, aPrinterName),
591 margin.left);
592 WriteInchesFromTwipsPref(GetPrefName(kMarginBottom, aPrinterName),
593 margin.bottom);
594 WriteInchesFromTwipsPref(GetPrefName(kMarginRight, aPrinterName),
595 margin.right);
596 Preferences::SetBool(GetPrefName(kIgnoreUnwriteableMargins, aPrinterName),
597 aPS->GetIgnoreUnwriteableMargins());
600 if (aFlags & nsIPrintSettings::kInitSaveEdges) {
601 nsIntMargin edge = aPS->GetEdgeInTwips();
602 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeTop, aPrinterName), edge.top);
603 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeLeft, aPrinterName),
604 edge.left);
605 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeBottom, aPrinterName),
606 edge.bottom);
607 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeRight, aPrinterName),
608 edge.right);
611 if (aFlags & nsIPrintSettings::kInitSaveUnwriteableMargins) {
612 nsIntMargin unwriteableMargin = aPS->GetUnwriteableMarginInTwips();
613 Preferences::SetInt(GetPrefName(kUnwriteableMarginTopTwips, aPrinterName),
614 unwriteableMargin.top);
615 Preferences::SetInt(GetPrefName(kUnwriteableMarginLeftTwips, aPrinterName),
616 unwriteableMargin.left);
617 Preferences::SetInt(
618 GetPrefName(kUnwriteableMarginBottomTwips, aPrinterName),
619 unwriteableMargin.bottom);
620 Preferences::SetInt(GetPrefName(kUnwriteableMarginRightTwips, aPrinterName),
621 unwriteableMargin.right);
623 // Remove the old unwriteableMargin prefs.
624 Preferences::ClearUser(GetPrefName(kUnwriteableMarginTop, aPrinterName));
625 Preferences::ClearUser(GetPrefName(kUnwriteableMarginRight, aPrinterName));
626 Preferences::ClearUser(GetPrefName(kUnwriteableMarginBottom, aPrinterName));
627 Preferences::ClearUser(GetPrefName(kUnwriteableMarginLeft, aPrinterName));
630 // Paper size prefs are saved as a group
631 if (aFlags & nsIPrintSettings::kInitSavePaperSize) {
632 int16_t sizeUnit;
633 double width, height;
634 nsString name;
636 if (NS_SUCCEEDED(aPS->GetPaperSizeUnit(&sizeUnit)) &&
637 NS_SUCCEEDED(aPS->GetPaperWidth(&width)) &&
638 NS_SUCCEEDED(aPS->GetPaperHeight(&height)) &&
639 NS_SUCCEEDED(aPS->GetPaperId(name))) {
640 Preferences::SetInt(GetPrefName(kPrintPaperSizeUnit, aPrinterName),
641 int32_t(sizeUnit));
642 WritePrefDouble(GetPrefName(kPrintPaperWidth, aPrinterName), width);
643 WritePrefDouble(GetPrefName(kPrintPaperHeight, aPrinterName), height);
644 Preferences::SetString(GetPrefName(kPrintPaperId, aPrinterName), name);
648 bool b;
649 nsString uStr;
650 int32_t iVal;
651 double dbl;
653 if (aFlags & nsIPrintSettings::kInitSaveHeaderLeft) {
654 if (NS_SUCCEEDED(aPS->GetHeaderStrLeft(uStr))) {
655 Preferences::SetString(GetPrefName(kPrintHeaderStrLeft, aPrinterName),
656 uStr);
660 if (aFlags & nsIPrintSettings::kInitSaveHeaderCenter) {
661 if (NS_SUCCEEDED(aPS->GetHeaderStrCenter(uStr))) {
662 Preferences::SetString(GetPrefName(kPrintHeaderStrCenter, aPrinterName),
663 uStr);
667 if (aFlags & nsIPrintSettings::kInitSaveHeaderRight) {
668 if (NS_SUCCEEDED(aPS->GetHeaderStrRight(uStr))) {
669 Preferences::SetString(GetPrefName(kPrintHeaderStrRight, aPrinterName),
670 uStr);
674 if (aFlags & nsIPrintSettings::kInitSaveFooterLeft) {
675 if (NS_SUCCEEDED(aPS->GetFooterStrLeft(uStr))) {
676 Preferences::SetString(GetPrefName(kPrintFooterStrLeft, aPrinterName),
677 uStr);
681 if (aFlags & nsIPrintSettings::kInitSaveFooterCenter) {
682 if (NS_SUCCEEDED(aPS->GetFooterStrCenter(uStr))) {
683 Preferences::SetString(GetPrefName(kPrintFooterStrCenter, aPrinterName),
684 uStr);
688 if (aFlags & nsIPrintSettings::kInitSaveFooterRight) {
689 if (NS_SUCCEEDED(aPS->GetFooterStrRight(uStr))) {
690 Preferences::SetString(GetPrefName(kPrintFooterStrRight, aPrinterName),
691 uStr);
695 if (aFlags & nsIPrintSettings::kInitSaveBGColors) {
696 b = aPS->GetPrintBGColors();
697 Preferences::SetBool(GetPrefName(kPrintBGColors, aPrinterName), b);
700 if (aFlags & nsIPrintSettings::kInitSaveBGImages) {
701 b = aPS->GetPrintBGImages();
702 Preferences::SetBool(GetPrefName(kPrintBGImages, aPrinterName), b);
705 if (aFlags & nsIPrintSettings::kInitSaveReversed) {
706 if (NS_SUCCEEDED(aPS->GetPrintReversed(&b))) {
707 Preferences::SetBool(GetPrefName(kPrintReversed, aPrinterName), b);
711 if (aFlags & nsIPrintSettings::kInitSaveInColor) {
712 if (NS_SUCCEEDED(aPS->GetPrintInColor(&b))) {
713 Preferences::SetBool(GetPrefName(kPrintInColor, aPrinterName), b);
717 if (aFlags & nsIPrintSettings::kInitSaveOrientation) {
718 if (NS_SUCCEEDED(aPS->GetOrientation(&iVal))) {
719 Preferences::SetInt(GetPrefName(kPrintOrientation, aPrinterName), iVal);
723 // Only the general version of this pref is saved
724 if ((aFlags & nsIPrintSettings::kInitSavePrinterName) &&
725 aPrinterName.IsEmpty()) {
726 if (NS_SUCCEEDED(aPS->GetPrinterName(uStr))) {
727 Preferences::SetString(kPrinterName, uStr);
731 if (aFlags & nsIPrintSettings::kInitSavePrintToFile) {
732 Preferences::SetBool(GetPrefName(kPrintToFile, aPrinterName),
733 aPS->GetOutputDestination() ==
734 nsIPrintSettings::kOutputDestinationFile);
737 if (aFlags & nsIPrintSettings::kInitSaveToFileName) {
738 if (NS_SUCCEEDED(aPS->GetToFileName(uStr))) {
739 Preferences::SetString(GetPrefName(kPrintToFileName, aPrinterName), uStr);
743 if (aFlags & nsIPrintSettings::kInitSavePageDelay) {
744 if (NS_SUCCEEDED(aPS->GetPrintPageDelay(&iVal))) {
745 Preferences::SetInt(GetPrefName(kPrintPageDelay, aPrinterName), iVal);
749 if (aFlags & nsIPrintSettings::kInitSaveShrinkToFit) {
750 if (NS_SUCCEEDED(aPS->GetShrinkToFit(&b))) {
751 Preferences::SetBool(GetPrefName(kPrintShrinkToFit, aPrinterName), b);
755 if (aFlags & nsIPrintSettings::kInitSaveScaling) {
756 if (NS_SUCCEEDED(aPS->GetScaling(&dbl))) {
757 WritePrefDouble(GetPrefName(kPrintScaling, aPrinterName), dbl);
761 if (aFlags & nsIPrintSettings::kInitSaveDuplex) {
762 if (NS_SUCCEEDED(aPS->GetDuplex(&iVal))) {
763 Preferences::SetInt(GetPrefName(kPrintDuplex, aPrinterName), iVal);
767 // Not Writing Out:
768 // Number of Copies
769 // Print Resolution
771 return NS_OK;
774 NS_IMETHODIMP
775 nsPrintSettingsService::GetDefaultPrintSettingsForPrinting(
776 nsIPrintSettings** aPrintSettings) {
777 nsresult rv = CreateNewPrintSettings(aPrintSettings);
778 NS_ENSURE_SUCCESS(rv, rv);
780 nsIPrintSettings* settings = *aPrintSettings;
782 // For security reasons, we don't pass the printer name to content processes.
783 // Once bug 1776169 is fixed, we can just assert that this is the parent
784 // process.
785 bool usePrinterName = XRE_IsParentProcess();
787 if (usePrinterName) {
788 nsAutoString printerName;
789 settings->GetPrinterName(printerName);
790 if (printerName.IsEmpty()) {
791 GetLastUsedPrinterName(printerName);
792 settings->SetPrinterName(printerName);
794 InitPrintSettingsFromPrinter(printerName, settings);
797 InitPrintSettingsFromPrefs(settings, usePrinterName,
798 nsIPrintSettings::kInitSaveAll);
800 return NS_OK;
803 NS_IMETHODIMP
804 nsPrintSettingsService::CreateNewPrintSettings(
805 nsIPrintSettings** aNewPrintSettings) {
806 return _CreatePrintSettings(aNewPrintSettings);
809 NS_IMETHODIMP
810 nsPrintSettingsService::GetLastUsedPrinterName(
811 nsAString& aLastUsedPrinterName) {
812 MOZ_ASSERT(XRE_IsParentProcess());
814 aLastUsedPrinterName.Truncate();
815 Preferences::GetString(kPrinterName, aLastUsedPrinterName);
816 return NS_OK;
819 NS_IMETHODIMP
820 nsPrintSettingsService::InitPrintSettingsFromPrinter(
821 const nsAString& aPrinterName, nsIPrintSettings* aPrintSettings) {
822 // Don't get print settings from the printer in the child when printing via
823 // parent, these will be retrieved in the parent later in the print process.
824 if (XRE_IsContentProcess()) {
825 return NS_OK;
828 NS_ENSURE_ARG_POINTER(aPrintSettings);
830 #ifdef DEBUG
831 nsString printerName;
832 aPrintSettings->GetPrinterName(printerName);
833 if (!printerName.Equals(aPrinterName)) {
834 NS_WARNING("Printer names should match!");
836 #endif
838 bool isInitialized;
839 aPrintSettings->GetIsInitializedFromPrinter(&isInitialized);
840 if (isInitialized) return NS_OK;
842 nsresult rv;
843 nsCOMPtr<nsIPrinterList> printerList =
844 do_GetService(NS_PRINTER_LIST_CONTRACTID, &rv);
845 NS_ENSURE_SUCCESS(rv, rv);
847 rv = printerList->InitPrintSettingsFromPrinter(aPrinterName, aPrintSettings);
848 NS_ENSURE_SUCCESS(rv, rv);
850 aPrintSettings->SetIsInitializedFromPrinter(true);
851 return rv;
854 /** ---------------------------------------------------
855 * Helper function - Returns either the name or sets the length to zero
857 static nsresult GetAdjustedPrinterName(nsIPrintSettings* aPS, bool aUsePNP,
858 nsAString& aPrinterName) {
859 NS_ENSURE_ARG_POINTER(aPS);
861 aPrinterName.Truncate();
862 if (!aUsePNP) return NS_OK;
864 // Get the Printer Name from the PrintSettings
865 // to use as a prefix for Pref Names
866 nsresult rv = aPS->GetPrinterName(aPrinterName);
867 NS_ENSURE_SUCCESS(rv, rv);
869 // Convert any whitespaces, carriage returns or newlines to _
870 // The below algorithm is supposedly faster than using iterators
871 constexpr auto replSubstr = u"_"_ns;
872 const char* replaceStr = " \n\r";
874 int32_t x;
875 for (x = 0; x < (int32_t)strlen(replaceStr); x++) {
876 char16_t uChar = replaceStr[x];
878 int32_t i = 0;
879 while ((i = aPrinterName.FindChar(uChar, i)) != kNotFound) {
880 aPrinterName.Replace(i, 1, replSubstr);
881 i++;
884 return NS_OK;
887 NS_IMETHODIMP
888 nsPrintSettingsService::InitPrintSettingsFromPrefs(nsIPrintSettings* aPS,
889 bool aUsePNP,
890 uint32_t aFlags) {
891 NS_ENSURE_ARG_POINTER(aPS);
893 bool isInitialized;
894 aPS->GetIsInitializedFromPrefs(&isInitialized);
896 if (isInitialized) {
897 return NS_OK;
900 auto globalPrintSettings = aFlags;
901 #ifndef MOZ_WIDGET_ANDROID
902 globalPrintSettings &= nsIPrintSettings::kGlobalSettings;
903 #endif
905 nsAutoString prtName;
906 // read any non printer specific prefs
907 // with empty printer name
908 nsresult rv = ReadPrefs(aPS, prtName, globalPrintSettings);
909 if (NS_FAILED(rv) && rv != NS_ERROR_NOT_AVAILABLE) {
910 NS_WARNING("ReadPrefs failed");
913 // Get the Printer Name from the PrintSettings to use as a prefix for Pref
914 // Names
915 rv = GetAdjustedPrinterName(aPS, aUsePNP, prtName);
916 NS_ENSURE_SUCCESS(rv, rv);
918 if (prtName.IsEmpty()) {
919 NS_WARNING("Caller should supply a printer name.");
920 return NS_OK;
923 // Now read any printer specific prefs
924 rv = ReadPrefs(aPS, prtName, aFlags);
925 if (NS_SUCCEEDED(rv)) {
926 aPS->SetIsInitializedFromPrefs(true);
929 return NS_OK;
933 * Save all of the printer settings; if we can find a printer name, save
934 * printer-specific preferences. Otherwise, save generic ones.
936 nsresult nsPrintSettingsService::MaybeSavePrintSettingsToPrefs(
937 nsIPrintSettings* aPS, uint32_t aFlags) {
938 NS_ENSURE_ARG_POINTER(aPS);
939 MOZ_DIAGNOSTIC_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
940 MOZ_ASSERT(!(aFlags & nsIPrintSettings::kInitSavePrinterName),
941 "Use SaveLastUsedPrintNameToPrefs");
943 if (!Preferences::GetBool("print.save_print_settings", false)) {
944 return NS_OK;
947 // Get the printer name from the PrinterSettings for an optional prefix.
948 nsAutoString prtName;
949 nsresult rv = GetAdjustedPrinterName(aPS, true, prtName);
950 NS_ENSURE_SUCCESS(rv, rv);
952 #ifndef MOZ_WIDGET_ANDROID
953 // On most platforms we should always use a prefix when saving print settings
954 // to prefs. Saving without a prefix risks breaking printing for users
955 // without a good way for us to fix things for them (unprefixed prefs act as
956 // defaults and can result in values being inappropriately propagated to
957 // prefixed prefs).
958 if (prtName.IsEmpty()) {
959 MOZ_DIAGNOSTIC_ASSERT(false, "Print settings must be saved with a prefix");
960 return NS_ERROR_FAILURE;
962 #endif
964 return WritePrefs(aPS, prtName, aFlags);
967 nsresult nsPrintSettingsService::MaybeSaveLastUsedPrinterNameToPrefs(
968 const nsAString& aPrinterName) {
969 MOZ_DIAGNOSTIC_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
971 if (!Preferences::GetBool("print.save_print_settings", false)) {
972 return NS_OK;
975 if (!aPrinterName.IsEmpty()) {
976 Preferences::SetString(kPrinterName, aPrinterName);
978 return NS_OK;
981 //-----------------------------------------------------
982 //-- Protected Methods --------------------------------
983 //-----------------------------------------------------
984 nsresult nsPrintSettingsService::ReadPrefDouble(const char* aPrefId,
985 double& aVal) {
986 NS_ENSURE_ARG_POINTER(aPrefId);
988 nsAutoCString str;
989 nsresult rv = Preferences::GetCString(aPrefId, str);
990 if (NS_FAILED(rv) || str.IsEmpty()) {
991 return NS_ERROR_NOT_AVAILABLE;
994 double value = str.ToDouble(&rv);
995 if (NS_FAILED(rv)) {
996 return rv;
999 aVal = value;
1000 return NS_OK;
1003 nsresult nsPrintSettingsService::WritePrefDouble(const char* aPrefId,
1004 double aVal) {
1005 NS_ENSURE_ARG_POINTER(aPrefId);
1007 nsAutoCString str;
1008 str.AppendFloat(aVal);
1009 return Preferences::SetCString(aPrefId, str);
1012 bool nsPrintSettingsService::ReadInchesToTwipsPref(const char* aPrefId,
1013 int32_t& aTwips) {
1014 nsAutoString str;
1015 nsresult rv = Preferences::GetString(aPrefId, str);
1016 if (NS_FAILED(rv) || str.IsEmpty()) {
1017 return false;
1020 float inches = str.ToFloat(&rv);
1021 if (NS_FAILED(rv)) {
1022 return false;
1025 aTwips = NS_INCHES_TO_INT_TWIPS(inches);
1026 return true;
1029 void nsPrintSettingsService::WriteInchesFromTwipsPref(const char* aPrefId,
1030 int32_t aTwips) {
1031 double inches = NS_TWIPS_TO_INCHES(aTwips);
1032 nsAutoCString inchesStr;
1033 inchesStr.AppendFloat(inches);
1035 Preferences::SetCString(aPrefId, inchesStr);
1038 bool nsPrintSettingsService::ReadInchesIntToTwipsPref(const char* aPrefId,
1039 int32_t& aTwips) {
1040 int32_t value;
1041 nsresult rv = Preferences::GetInt(aPrefId, &value);
1042 if (NS_FAILED(rv)) {
1043 return false;
1046 aTwips = NS_INCHES_TO_INT_TWIPS(float(value) / 100.0f);
1047 return true;
1050 void nsPrintSettingsService::WriteInchesIntFromTwipsPref(const char* aPrefId,
1051 int32_t aTwips) {
1052 Preferences::SetInt(aPrefId,
1053 int32_t(NS_TWIPS_TO_INCHES(aTwips) * 100.0f + 0.5f));
1056 void nsPrintSettingsService::ReadJustification(const char* aPrefId,
1057 int16_t& aJust,
1058 int16_t aInitValue) {
1059 aJust = aInitValue;
1060 nsAutoString justStr;
1061 if (NS_SUCCEEDED(Preferences::GetString(aPrefId, justStr))) {
1062 if (justStr.EqualsASCII(kJustRight)) {
1063 aJust = nsIPrintSettings::kJustRight;
1064 } else if (justStr.EqualsASCII(kJustCenter)) {
1065 aJust = nsIPrintSettings::kJustCenter;
1066 } else {
1067 aJust = nsIPrintSettings::kJustLeft;
1072 //---------------------------------------------------
1073 void nsPrintSettingsService::WriteJustification(const char* aPrefId,
1074 int16_t aJust) {
1075 switch (aJust) {
1076 case nsIPrintSettings::kJustLeft:
1077 Preferences::SetCString(aPrefId, kJustLeft);
1078 break;
1080 case nsIPrintSettings::kJustCenter:
1081 Preferences::SetCString(aPrefId, kJustCenter);
1082 break;
1084 case nsIPrintSettings::kJustRight:
1085 Preferences::SetCString(aPrefId, kJustRight);
1086 break;
1087 } // switch