Bug 1805294 [wpt PR 37463] - WebKit export of https://bugs.webkit.org/show_bug.cgi...
[gecko.git] / widget / nsPrintSettingsService.cpp
blobecc4e1a7f8207146b76d17b5c10308a1bcde50dc
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->showMarginGuides() = aSettings->GetShowMarginGuides();
126 data->printSelectionOnly() = aSettings->GetPrintSelectionOnly();
128 aSettings->GetTitle(data->title());
129 aSettings->GetDocURL(data->docURL());
131 aSettings->GetHeaderStrLeft(data->headerStrLeft());
132 aSettings->GetHeaderStrCenter(data->headerStrCenter());
133 aSettings->GetHeaderStrRight(data->headerStrRight());
135 aSettings->GetFooterStrLeft(data->footerStrLeft());
136 aSettings->GetFooterStrCenter(data->footerStrCenter());
137 aSettings->GetFooterStrRight(data->footerStrRight());
139 aSettings->GetPrintSilent(&data->printSilent());
140 aSettings->GetShrinkToFit(&data->shrinkToFit());
142 aSettings->GetPaperId(data->paperId());
143 aSettings->GetPaperWidth(&data->paperWidth());
144 aSettings->GetPaperHeight(&data->paperHeight());
145 aSettings->GetPaperSizeUnit(&data->paperSizeUnit());
147 aSettings->GetPrintReversed(&data->printReversed());
148 aSettings->GetPrintInColor(&data->printInColor());
149 aSettings->GetOrientation(&data->orientation());
151 aSettings->GetNumCopies(&data->numCopies());
152 aSettings->GetNumPagesPerSheet(&data->numPagesPerSheet());
154 data->outputDestination() = aSettings->GetOutputDestination();
156 data->outputFormat() = aSettings->GetOutputFormat();
157 data->printPageDelay() = aSettings->GetPrintPageDelay();
158 data->resolution() = aSettings->GetResolution();
159 data->duplex() = aSettings->GetDuplex();
161 aSettings->GetIsInitializedFromPrinter(&data->isInitializedFromPrinter());
162 aSettings->GetIsInitializedFromPrefs(&data->isInitializedFromPrefs());
164 // Initialize the platform-specific values that don't
165 // default-initialize, so that we don't send uninitialized data over
166 // IPC (which leads to valgrind warnings, and, for bools, fatal
167 // assertions).
168 // data->driverName() default-initializes
169 // data->deviceName() default-initializes
170 // data->GTKPrintSettings() default-initializes
172 return NS_OK;
175 NS_IMETHODIMP
176 nsPrintSettingsService::DeserializeToPrintSettings(const PrintData& data,
177 nsIPrintSettings* settings) {
178 settings->SetPageRanges(data.pageRanges());
180 settings->SetEdgeTop(data.edgeTop());
181 settings->SetEdgeLeft(data.edgeLeft());
182 settings->SetEdgeBottom(data.edgeBottom());
183 settings->SetEdgeRight(data.edgeRight());
185 settings->SetMarginTop(data.marginTop());
186 settings->SetMarginLeft(data.marginLeft());
187 settings->SetMarginBottom(data.marginBottom());
188 settings->SetMarginRight(data.marginRight());
189 settings->SetUnwriteableMarginTop(data.unwriteableMarginTop());
190 settings->SetUnwriteableMarginLeft(data.unwriteableMarginLeft());
191 settings->SetUnwriteableMarginBottom(data.unwriteableMarginBottom());
192 settings->SetUnwriteableMarginRight(data.unwriteableMarginRight());
194 settings->SetScaling(data.scaling());
196 settings->SetPrintBGColors(data.printBGColors());
197 settings->SetPrintBGImages(data.printBGImages());
198 settings->SetHonorPageRuleMargins(data.honorPageRuleMargins());
199 settings->SetIgnoreUnwriteableMargins(data.ignoreUnwriteableMargins());
200 settings->SetShowMarginGuides(data.showMarginGuides());
201 settings->SetPrintSelectionOnly(data.printSelectionOnly());
203 settings->SetTitle(data.title());
204 settings->SetDocURL(data.docURL());
206 // Header strings...
207 settings->SetHeaderStrLeft(data.headerStrLeft());
208 settings->SetHeaderStrCenter(data.headerStrCenter());
209 settings->SetHeaderStrRight(data.headerStrRight());
211 // Footer strings...
212 settings->SetFooterStrLeft(data.footerStrLeft());
213 settings->SetFooterStrCenter(data.footerStrCenter());
214 settings->SetFooterStrRight(data.footerStrRight());
216 settings->SetPrintSilent(data.printSilent());
217 settings->SetShrinkToFit(data.shrinkToFit());
219 settings->SetPaperId(data.paperId());
221 settings->SetPaperWidth(data.paperWidth());
222 settings->SetPaperHeight(data.paperHeight());
223 settings->SetPaperSizeUnit(data.paperSizeUnit());
225 settings->SetPrintReversed(data.printReversed());
226 settings->SetPrintInColor(data.printInColor());
227 settings->SetOrientation(data.orientation());
229 settings->SetNumCopies(data.numCopies());
230 settings->SetNumPagesPerSheet(data.numPagesPerSheet());
232 settings->SetOutputDestination(
233 nsIPrintSettings::OutputDestinationType(data.outputDestination()));
234 // Output stream intentionally unset, child processes shouldn't care about it.
236 settings->SetOutputFormat(data.outputFormat());
237 settings->SetPrintPageDelay(data.printPageDelay());
238 settings->SetResolution(data.resolution());
239 settings->SetDuplex(data.duplex());
240 settings->SetIsInitializedFromPrinter(data.isInitializedFromPrinter());
241 settings->SetIsInitializedFromPrefs(data.isInitializedFromPrefs());
243 return NS_OK;
246 /** ---------------------------------------------------
247 * Helper function - Creates the "prefix" for the pref
248 * It is either "print."
249 * or "print.printer_<print name>."
251 const char* nsPrintSettingsService::GetPrefName(const char* aPrefName,
252 const nsAString& aPrinterName) {
253 if (!aPrefName || !*aPrefName) {
254 NS_ERROR("Must have a valid pref name!");
255 return aPrefName;
258 mPrefName.AssignLiteral("print.");
260 if (aPrinterName.Length()) {
261 mPrefName.AppendLiteral("printer_");
262 AppendUTF16toUTF8(aPrinterName, mPrefName);
263 mPrefName.Append('.');
265 mPrefName += aPrefName;
267 return mPrefName.get();
271 * This will either read in the generic prefs (not specific to a printer)
272 * or read the prefs in using the printer name to qualify.
273 * It is either "print.attr_name" or "print.printer_HPLasr5.attr_name"
275 nsresult nsPrintSettingsService::ReadPrefs(nsIPrintSettings* aPS,
276 const nsAString& aPrinterName,
277 uint32_t aFlags) {
278 NS_ENSURE_ARG_POINTER(aPS);
280 bool noValidPrefsFound = true;
281 bool b;
282 nsAutoString str;
283 int32_t iVal;
284 double dbl;
286 #define GETBOOLPREF(_prefname, _retval) \
287 NS_SUCCEEDED( \
288 Preferences::GetBool(GetPrefName(_prefname, aPrinterName), _retval))
290 #define GETSTRPREF(_prefname, _retval) \
291 NS_SUCCEEDED( \
292 Preferences::GetString(GetPrefName(_prefname, aPrinterName), _retval))
294 #define GETINTPREF(_prefname, _retval) \
295 NS_SUCCEEDED( \
296 Preferences::GetInt(GetPrefName(_prefname, aPrinterName), _retval))
298 #define GETDBLPREF(_prefname, _retval) \
299 NS_SUCCEEDED(ReadPrefDouble(GetPrefName(_prefname, aPrinterName), _retval))
301 bool gotPaperSizeFromPrefs = false;
302 int16_t paperSizeUnit;
303 double paperWidth, paperHeight;
305 // Paper size prefs are read as a group
306 if (aFlags & nsIPrintSettings::kInitSavePaperSize) {
307 gotPaperSizeFromPrefs = GETINTPREF(kPrintPaperSizeUnit, &iVal) &&
308 GETDBLPREF(kPrintPaperWidth, paperWidth) &&
309 GETDBLPREF(kPrintPaperHeight, paperHeight) &&
310 GETSTRPREF(kPrintPaperId, str);
311 paperSizeUnit = (int16_t)iVal;
313 if (gotPaperSizeFromPrefs &&
314 paperSizeUnit != nsIPrintSettings::kPaperSizeInches &&
315 paperSizeUnit != nsIPrintSettings::kPaperSizeMillimeters) {
316 gotPaperSizeFromPrefs = false;
319 if (gotPaperSizeFromPrefs) {
320 // Bug 315687: Sanity check paper size to avoid paper size values in
321 // mm when the size unit flag is inches. The value 100 is arbitrary
322 // and can be changed.
323 gotPaperSizeFromPrefs =
324 (paperSizeUnit != nsIPrintSettings::kPaperSizeInches) ||
325 (paperWidth < 100.0) || (paperHeight < 100.0);
328 if (gotPaperSizeFromPrefs) {
329 aPS->SetPaperSizeUnit(paperSizeUnit);
330 aPS->SetPaperWidth(paperWidth);
331 aPS->SetPaperHeight(paperHeight);
332 aPS->SetPaperId(str);
333 noValidPrefsFound = false;
337 nsIntSize pageSizeInTwips; // to sanity check margins
338 if (!gotPaperSizeFromPrefs) {
339 aPS->GetPaperSizeUnit(&paperSizeUnit);
340 aPS->GetPaperWidth(&paperWidth);
341 aPS->GetPaperHeight(&paperHeight);
343 if (paperSizeUnit == nsIPrintSettings::kPaperSizeMillimeters) {
344 pageSizeInTwips = nsIntSize((int)NS_MILLIMETERS_TO_TWIPS(paperWidth),
345 (int)NS_MILLIMETERS_TO_TWIPS(paperHeight));
346 } else {
347 pageSizeInTwips = nsIntSize((int)NS_INCHES_TO_TWIPS(paperWidth),
348 (int)NS_INCHES_TO_TWIPS(paperHeight));
351 auto MarginIsOK = [&pageSizeInTwips](const nsIntMargin& aMargin) {
352 return aMargin.top >= 0 && aMargin.right >= 0 && aMargin.bottom >= 0 &&
353 aMargin.left >= 0 && aMargin.LeftRight() < pageSizeInTwips.width &&
354 aMargin.TopBottom() < pageSizeInTwips.height;
357 if (aFlags & nsIPrintSettings::kInitSaveUnwriteableMargins) {
358 nsIntMargin margin;
359 bool allPrefsRead =
360 GETINTPREF(kUnwriteableMarginTopTwips, &margin.top) &&
361 GETINTPREF(kUnwriteableMarginRightTwips, &margin.right) &&
362 GETINTPREF(kUnwriteableMarginBottomTwips, &margin.bottom) &&
363 GETINTPREF(kUnwriteableMarginLeftTwips, &margin.left);
364 if (!allPrefsRead) {
365 // We failed to read the new unwritable margin twips prefs. Try to read
366 // the old ones in case they exist.
367 allPrefsRead =
368 ReadInchesIntToTwipsPref(
369 GetPrefName(kUnwriteableMarginTop, aPrinterName), margin.top) &&
370 ReadInchesIntToTwipsPref(
371 GetPrefName(kUnwriteableMarginLeft, aPrinterName), margin.left) &&
372 ReadInchesIntToTwipsPref(
373 GetPrefName(kUnwriteableMarginBottom, aPrinterName),
374 margin.bottom) &&
375 ReadInchesIntToTwipsPref(
376 GetPrefName(kUnwriteableMarginRight, aPrinterName), margin.right);
378 // SetUnwriteableMarginInTwips does its own validation and drops negative
379 // values individually. We still want to block overly large values though,
380 // so we do that part of MarginIsOK manually.
381 if (allPrefsRead && margin.LeftRight() < pageSizeInTwips.width &&
382 margin.TopBottom() < pageSizeInTwips.height) {
383 aPS->SetUnwriteableMarginInTwips(margin);
384 noValidPrefsFound = false;
388 if (aFlags & nsIPrintSettings::kInitSaveMargins) {
389 int32_t halfInch = NS_INCHES_TO_INT_TWIPS(0.5);
390 nsIntMargin margin(halfInch, halfInch, halfInch, halfInch);
391 bool prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginTop, aPrinterName),
392 margin.top);
393 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginLeft, aPrinterName),
394 margin.left) ||
395 prefRead;
396 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginBottom, aPrinterName),
397 margin.bottom) ||
398 prefRead;
400 prefRead = ReadInchesToTwipsPref(GetPrefName(kMarginRight, aPrinterName),
401 margin.right) ||
402 prefRead;
403 if (prefRead && MarginIsOK(margin)) {
404 aPS->SetMarginInTwips(margin);
405 noValidPrefsFound = false;
407 prefRead = GETBOOLPREF(kIgnoreUnwriteableMargins, &b);
408 if (prefRead) {
409 aPS->SetIgnoreUnwriteableMargins(b);
414 if (aFlags & nsIPrintSettings::kInitSaveEdges) {
415 nsIntMargin margin(0, 0, 0, 0);
416 bool prefRead = ReadInchesIntToTwipsPref(
417 GetPrefName(kEdgeTop, aPrinterName), margin.top);
418 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeLeft, aPrinterName),
419 margin.left) ||
420 prefRead;
422 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeBottom, aPrinterName),
423 margin.bottom) ||
424 prefRead;
426 prefRead = ReadInchesIntToTwipsPref(GetPrefName(kEdgeRight, aPrinterName),
427 margin.right) ||
428 prefRead;
430 if (prefRead && MarginIsOK(margin)) {
431 aPS->SetEdgeInTwips(margin);
432 noValidPrefsFound = false;
436 if (aFlags & nsIPrintSettings::kInitSaveHeaderLeft) {
437 if (GETSTRPREF(kPrintHeaderStrLeft, str)) {
438 aPS->SetHeaderStrLeft(str);
439 noValidPrefsFound = false;
443 if (aFlags & nsIPrintSettings::kInitSaveHeaderCenter) {
444 if (GETSTRPREF(kPrintHeaderStrCenter, str)) {
445 aPS->SetHeaderStrCenter(str);
446 noValidPrefsFound = false;
450 if (aFlags & nsIPrintSettings::kInitSaveHeaderRight) {
451 if (GETSTRPREF(kPrintHeaderStrRight, str)) {
452 aPS->SetHeaderStrRight(str);
453 noValidPrefsFound = false;
457 if (aFlags & nsIPrintSettings::kInitSaveFooterLeft) {
458 if (GETSTRPREF(kPrintFooterStrLeft, str)) {
459 aPS->SetFooterStrLeft(str);
460 noValidPrefsFound = false;
464 if (aFlags & nsIPrintSettings::kInitSaveFooterCenter) {
465 if (GETSTRPREF(kPrintFooterStrCenter, str)) {
466 aPS->SetFooterStrCenter(str);
467 noValidPrefsFound = false;
471 if (aFlags & nsIPrintSettings::kInitSaveFooterRight) {
472 if (GETSTRPREF(kPrintFooterStrRight, str)) {
473 aPS->SetFooterStrRight(str);
474 noValidPrefsFound = false;
478 if (aFlags & nsIPrintSettings::kInitSaveBGColors) {
479 if (GETBOOLPREF(kPrintBGColors, &b)) {
480 aPS->SetPrintBGColors(b);
481 noValidPrefsFound = false;
485 if (aFlags & nsIPrintSettings::kInitSaveBGImages) {
486 if (GETBOOLPREF(kPrintBGImages, &b)) {
487 aPS->SetPrintBGImages(b);
488 noValidPrefsFound = false;
492 if (aFlags & nsIPrintSettings::kInitSaveReversed) {
493 if (GETBOOLPREF(kPrintReversed, &b)) {
494 aPS->SetPrintReversed(b);
495 noValidPrefsFound = false;
499 if (aFlags & nsIPrintSettings::kInitSaveInColor) {
500 if (GETBOOLPREF(kPrintInColor, &b)) {
501 aPS->SetPrintInColor(b);
502 noValidPrefsFound = false;
506 if (aFlags & nsIPrintSettings::kInitSaveOrientation) {
507 if (GETINTPREF(kPrintOrientation, &iVal) &&
508 (iVal == nsIPrintSettings::kPortraitOrientation ||
509 iVal == nsIPrintSettings::kLandscapeOrientation)) {
510 aPS->SetOrientation(iVal);
511 noValidPrefsFound = false;
515 if (aFlags & nsIPrintSettings::kInitSavePrintToFile) {
516 if (GETBOOLPREF(kPrintToFile, &b)) {
517 aPS->SetOutputDestination(
518 b ? nsIPrintSettings::kOutputDestinationFile
519 : nsIPrintSettings::kOutputDestinationPrinter);
520 noValidPrefsFound = false;
524 if (aFlags & nsIPrintSettings::kInitSaveToFileName) {
525 if (GETSTRPREF(kPrintToFileName, str)) {
526 if (StringEndsWith(str, u".ps"_ns)) {
527 // We only support PDF since bug 1425188 landed. Users may still have
528 // prefs with .ps filenames if they last saved a file as Postscript
529 // though, so we fix that up here. (The pref values will be
530 // overwritten the next time they save to file as a PDF.)
531 str.Truncate(str.Length() - 2);
532 str.AppendLiteral("pdf");
534 aPS->SetToFileName(str);
535 noValidPrefsFound = false;
539 if (aFlags & nsIPrintSettings::kInitSavePageDelay) {
540 // milliseconds
541 if (GETINTPREF(kPrintPageDelay, &iVal) && iVal >= 0 && iVal <= 1000) {
542 aPS->SetPrintPageDelay(iVal);
543 noValidPrefsFound = false;
547 if (aFlags & nsIPrintSettings::kInitSaveShrinkToFit) {
548 if (GETBOOLPREF(kPrintShrinkToFit, &b)) {
549 aPS->SetShrinkToFit(b);
550 noValidPrefsFound = false;
554 if (aFlags & nsIPrintSettings::kInitSaveScaling) {
555 // The limits imposed here are fairly arbitrary and mainly intended to
556 // purge bad values which tend to be negative and/or very large. If we
557 // get complaints from users that settings outside these values "aren't
558 // saved" then we can consider increasing them.
559 if (GETDBLPREF(kPrintScaling, dbl) && dbl >= 0.05 && dbl <= 20) {
560 aPS->SetScaling(dbl);
561 noValidPrefsFound = false;
565 if (aFlags & nsIPrintSettings::kInitSaveDuplex) {
566 if (GETINTPREF(kPrintDuplex, &iVal)) {
567 aPS->SetDuplex(iVal);
568 noValidPrefsFound = false;
572 // Not Reading In:
573 // Number of Copies
574 // Print Resolution
576 return noValidPrefsFound ? NS_ERROR_NOT_AVAILABLE : NS_OK;
579 nsresult nsPrintSettingsService::WritePrefs(nsIPrintSettings* aPS,
580 const nsAString& aPrinterName,
581 uint32_t aFlags) {
582 NS_ENSURE_ARG_POINTER(aPS);
584 if (aFlags & nsIPrintSettings::kInitSaveMargins) {
585 nsIntMargin margin = aPS->GetMarginInTwips();
586 WriteInchesFromTwipsPref(GetPrefName(kMarginTop, aPrinterName), margin.top);
587 WriteInchesFromTwipsPref(GetPrefName(kMarginLeft, aPrinterName),
588 margin.left);
589 WriteInchesFromTwipsPref(GetPrefName(kMarginBottom, aPrinterName),
590 margin.bottom);
591 WriteInchesFromTwipsPref(GetPrefName(kMarginRight, aPrinterName),
592 margin.right);
593 Preferences::SetBool(GetPrefName(kIgnoreUnwriteableMargins, aPrinterName),
594 aPS->GetIgnoreUnwriteableMargins());
597 if (aFlags & nsIPrintSettings::kInitSaveEdges) {
598 nsIntMargin edge = aPS->GetEdgeInTwips();
599 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeTop, aPrinterName), edge.top);
600 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeLeft, aPrinterName),
601 edge.left);
602 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeBottom, aPrinterName),
603 edge.bottom);
604 WriteInchesIntFromTwipsPref(GetPrefName(kEdgeRight, aPrinterName),
605 edge.right);
608 if (aFlags & nsIPrintSettings::kInitSaveUnwriteableMargins) {
609 nsIntMargin unwriteableMargin = aPS->GetUnwriteableMarginInTwips();
610 Preferences::SetInt(GetPrefName(kUnwriteableMarginTopTwips, aPrinterName),
611 unwriteableMargin.top);
612 Preferences::SetInt(GetPrefName(kUnwriteableMarginLeftTwips, aPrinterName),
613 unwriteableMargin.left);
614 Preferences::SetInt(
615 GetPrefName(kUnwriteableMarginBottomTwips, aPrinterName),
616 unwriteableMargin.bottom);
617 Preferences::SetInt(GetPrefName(kUnwriteableMarginRightTwips, aPrinterName),
618 unwriteableMargin.right);
620 // Remove the old unwriteableMargin prefs.
621 Preferences::ClearUser(GetPrefName(kUnwriteableMarginTop, aPrinterName));
622 Preferences::ClearUser(GetPrefName(kUnwriteableMarginRight, aPrinterName));
623 Preferences::ClearUser(GetPrefName(kUnwriteableMarginBottom, aPrinterName));
624 Preferences::ClearUser(GetPrefName(kUnwriteableMarginLeft, aPrinterName));
627 // Paper size prefs are saved as a group
628 if (aFlags & nsIPrintSettings::kInitSavePaperSize) {
629 int16_t sizeUnit;
630 double width, height;
631 nsString name;
633 if (NS_SUCCEEDED(aPS->GetPaperSizeUnit(&sizeUnit)) &&
634 NS_SUCCEEDED(aPS->GetPaperWidth(&width)) &&
635 NS_SUCCEEDED(aPS->GetPaperHeight(&height)) &&
636 NS_SUCCEEDED(aPS->GetPaperId(name))) {
637 Preferences::SetInt(GetPrefName(kPrintPaperSizeUnit, aPrinterName),
638 int32_t(sizeUnit));
639 WritePrefDouble(GetPrefName(kPrintPaperWidth, aPrinterName), width);
640 WritePrefDouble(GetPrefName(kPrintPaperHeight, aPrinterName), height);
641 Preferences::SetString(GetPrefName(kPrintPaperId, aPrinterName), name);
645 bool b;
646 nsString uStr;
647 int32_t iVal;
648 double dbl;
650 if (aFlags & nsIPrintSettings::kInitSaveHeaderLeft) {
651 if (NS_SUCCEEDED(aPS->GetHeaderStrLeft(uStr))) {
652 Preferences::SetString(GetPrefName(kPrintHeaderStrLeft, aPrinterName),
653 uStr);
657 if (aFlags & nsIPrintSettings::kInitSaveHeaderCenter) {
658 if (NS_SUCCEEDED(aPS->GetHeaderStrCenter(uStr))) {
659 Preferences::SetString(GetPrefName(kPrintHeaderStrCenter, aPrinterName),
660 uStr);
664 if (aFlags & nsIPrintSettings::kInitSaveHeaderRight) {
665 if (NS_SUCCEEDED(aPS->GetHeaderStrRight(uStr))) {
666 Preferences::SetString(GetPrefName(kPrintHeaderStrRight, aPrinterName),
667 uStr);
671 if (aFlags & nsIPrintSettings::kInitSaveFooterLeft) {
672 if (NS_SUCCEEDED(aPS->GetFooterStrLeft(uStr))) {
673 Preferences::SetString(GetPrefName(kPrintFooterStrLeft, aPrinterName),
674 uStr);
678 if (aFlags & nsIPrintSettings::kInitSaveFooterCenter) {
679 if (NS_SUCCEEDED(aPS->GetFooterStrCenter(uStr))) {
680 Preferences::SetString(GetPrefName(kPrintFooterStrCenter, aPrinterName),
681 uStr);
685 if (aFlags & nsIPrintSettings::kInitSaveFooterRight) {
686 if (NS_SUCCEEDED(aPS->GetFooterStrRight(uStr))) {
687 Preferences::SetString(GetPrefName(kPrintFooterStrRight, aPrinterName),
688 uStr);
692 if (aFlags & nsIPrintSettings::kInitSaveBGColors) {
693 b = aPS->GetPrintBGColors();
694 Preferences::SetBool(GetPrefName(kPrintBGColors, aPrinterName), b);
697 if (aFlags & nsIPrintSettings::kInitSaveBGImages) {
698 b = aPS->GetPrintBGImages();
699 Preferences::SetBool(GetPrefName(kPrintBGImages, aPrinterName), b);
702 if (aFlags & nsIPrintSettings::kInitSaveReversed) {
703 if (NS_SUCCEEDED(aPS->GetPrintReversed(&b))) {
704 Preferences::SetBool(GetPrefName(kPrintReversed, aPrinterName), b);
708 if (aFlags & nsIPrintSettings::kInitSaveInColor) {
709 if (NS_SUCCEEDED(aPS->GetPrintInColor(&b))) {
710 Preferences::SetBool(GetPrefName(kPrintInColor, aPrinterName), b);
714 if (aFlags & nsIPrintSettings::kInitSaveOrientation) {
715 if (NS_SUCCEEDED(aPS->GetOrientation(&iVal))) {
716 Preferences::SetInt(GetPrefName(kPrintOrientation, aPrinterName), iVal);
720 // Only the general version of this pref is saved
721 if ((aFlags & nsIPrintSettings::kInitSavePrinterName) &&
722 aPrinterName.IsEmpty()) {
723 if (NS_SUCCEEDED(aPS->GetPrinterName(uStr))) {
724 Preferences::SetString(kPrinterName, uStr);
728 if (aFlags & nsIPrintSettings::kInitSavePrintToFile) {
729 Preferences::SetBool(GetPrefName(kPrintToFile, aPrinterName),
730 aPS->GetOutputDestination() ==
731 nsIPrintSettings::kOutputDestinationFile);
734 if (aFlags & nsIPrintSettings::kInitSaveToFileName) {
735 if (NS_SUCCEEDED(aPS->GetToFileName(uStr))) {
736 Preferences::SetString(GetPrefName(kPrintToFileName, aPrinterName), uStr);
740 if (aFlags & nsIPrintSettings::kInitSavePageDelay) {
741 if (NS_SUCCEEDED(aPS->GetPrintPageDelay(&iVal))) {
742 Preferences::SetInt(GetPrefName(kPrintPageDelay, aPrinterName), iVal);
746 if (aFlags & nsIPrintSettings::kInitSaveShrinkToFit) {
747 if (NS_SUCCEEDED(aPS->GetShrinkToFit(&b))) {
748 Preferences::SetBool(GetPrefName(kPrintShrinkToFit, aPrinterName), b);
752 if (aFlags & nsIPrintSettings::kInitSaveScaling) {
753 if (NS_SUCCEEDED(aPS->GetScaling(&dbl))) {
754 WritePrefDouble(GetPrefName(kPrintScaling, aPrinterName), dbl);
758 if (aFlags & nsIPrintSettings::kInitSaveDuplex) {
759 if (NS_SUCCEEDED(aPS->GetDuplex(&iVal))) {
760 Preferences::SetInt(GetPrefName(kPrintDuplex, aPrinterName), iVal);
764 // Not Writing Out:
765 // Number of Copies
766 // Print Resolution
768 return NS_OK;
771 NS_IMETHODIMP
772 nsPrintSettingsService::GetDefaultPrintSettingsForPrinting(
773 nsIPrintSettings** aPrintSettings) {
774 nsresult rv = CreateNewPrintSettings(aPrintSettings);
775 NS_ENSURE_SUCCESS(rv, rv);
777 nsIPrintSettings* settings = *aPrintSettings;
779 // For security reasons, we don't pass the printer name to content processes.
780 // Once bug 1776169 is fixed, we can just assert that this is the parent
781 // process.
782 bool usePrinterName = XRE_IsParentProcess();
784 if (usePrinterName) {
785 nsAutoString printerName;
786 settings->GetPrinterName(printerName);
787 if (printerName.IsEmpty()) {
788 GetLastUsedPrinterName(printerName);
789 settings->SetPrinterName(printerName);
791 InitPrintSettingsFromPrinter(printerName, settings);
794 InitPrintSettingsFromPrefs(settings, usePrinterName,
795 nsIPrintSettings::kInitSaveAll);
797 return NS_OK;
800 NS_IMETHODIMP
801 nsPrintSettingsService::CreateNewPrintSettings(
802 nsIPrintSettings** aNewPrintSettings) {
803 return _CreatePrintSettings(aNewPrintSettings);
806 NS_IMETHODIMP
807 nsPrintSettingsService::GetLastUsedPrinterName(
808 nsAString& aLastUsedPrinterName) {
809 MOZ_ASSERT(XRE_IsParentProcess());
811 aLastUsedPrinterName.Truncate();
812 Preferences::GetString(kPrinterName, aLastUsedPrinterName);
813 return NS_OK;
816 NS_IMETHODIMP
817 nsPrintSettingsService::InitPrintSettingsFromPrinter(
818 const nsAString& aPrinterName, nsIPrintSettings* aPrintSettings) {
819 // Don't get print settings from the printer in the child when printing via
820 // parent, these will be retrieved in the parent later in the print process.
821 if (XRE_IsContentProcess()) {
822 return NS_OK;
825 NS_ENSURE_ARG_POINTER(aPrintSettings);
827 #ifdef DEBUG
828 nsString printerName;
829 aPrintSettings->GetPrinterName(printerName);
830 if (!printerName.Equals(aPrinterName)) {
831 NS_WARNING("Printer names should match!");
833 #endif
835 bool isInitialized;
836 aPrintSettings->GetIsInitializedFromPrinter(&isInitialized);
837 if (isInitialized) return NS_OK;
839 nsresult rv;
840 nsCOMPtr<nsIPrinterList> printerList =
841 do_GetService(NS_PRINTER_LIST_CONTRACTID, &rv);
842 NS_ENSURE_SUCCESS(rv, rv);
844 rv = printerList->InitPrintSettingsFromPrinter(aPrinterName, aPrintSettings);
845 NS_ENSURE_SUCCESS(rv, rv);
847 aPrintSettings->SetIsInitializedFromPrinter(true);
848 return rv;
851 /** ---------------------------------------------------
852 * Helper function - Returns either the name or sets the length to zero
854 static nsresult GetAdjustedPrinterName(nsIPrintSettings* aPS, bool aUsePNP,
855 nsAString& aPrinterName) {
856 NS_ENSURE_ARG_POINTER(aPS);
858 aPrinterName.Truncate();
859 if (!aUsePNP) return NS_OK;
861 // Get the Printer Name from the PrintSettings
862 // to use as a prefix for Pref Names
863 nsresult rv = aPS->GetPrinterName(aPrinterName);
864 NS_ENSURE_SUCCESS(rv, rv);
866 // Convert any whitespaces, carriage returns or newlines to _
867 // The below algorithm is supposedly faster than using iterators
868 constexpr auto replSubstr = u"_"_ns;
869 const char* replaceStr = " \n\r";
871 int32_t x;
872 for (x = 0; x < (int32_t)strlen(replaceStr); x++) {
873 char16_t uChar = replaceStr[x];
875 int32_t i = 0;
876 while ((i = aPrinterName.FindChar(uChar, i)) != kNotFound) {
877 aPrinterName.Replace(i, 1, replSubstr);
878 i++;
881 return NS_OK;
884 NS_IMETHODIMP
885 nsPrintSettingsService::InitPrintSettingsFromPrefs(nsIPrintSettings* aPS,
886 bool aUsePNP,
887 uint32_t aFlags) {
888 NS_ENSURE_ARG_POINTER(aPS);
890 bool isInitialized;
891 aPS->GetIsInitializedFromPrefs(&isInitialized);
893 if (isInitialized) {
894 return NS_OK;
897 auto globalPrintSettings = aFlags;
898 #ifndef MOZ_WIDGET_ANDROID
899 globalPrintSettings &= nsIPrintSettings::kGlobalSettings;
900 #endif
902 nsAutoString prtName;
903 // read any non printer specific prefs
904 // with empty printer name
905 nsresult rv = ReadPrefs(aPS, prtName, globalPrintSettings);
906 if (NS_FAILED(rv) && rv != NS_ERROR_NOT_AVAILABLE) {
907 NS_WARNING("ReadPrefs failed");
910 // Get the Printer Name from the PrintSettings to use as a prefix for Pref
911 // Names
912 rv = GetAdjustedPrinterName(aPS, aUsePNP, prtName);
913 NS_ENSURE_SUCCESS(rv, rv);
915 if (prtName.IsEmpty()) {
916 NS_WARNING("Caller should supply a printer name.");
917 return NS_OK;
920 // Now read any printer specific prefs
921 rv = ReadPrefs(aPS, prtName, aFlags);
922 if (NS_SUCCEEDED(rv)) {
923 aPS->SetIsInitializedFromPrefs(true);
926 return NS_OK;
930 * Save all of the printer settings; if we can find a printer name, save
931 * printer-specific preferences. Otherwise, save generic ones.
933 nsresult nsPrintSettingsService::MaybeSavePrintSettingsToPrefs(
934 nsIPrintSettings* aPS, uint32_t aFlags) {
935 NS_ENSURE_ARG_POINTER(aPS);
936 MOZ_DIAGNOSTIC_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
937 MOZ_ASSERT(!(aFlags & nsIPrintSettings::kInitSavePrinterName),
938 "Use SaveLastUsedPrintNameToPrefs");
940 if (!Preferences::GetBool("print.save_print_settings", false)) {
941 return NS_OK;
944 // Get the printer name from the PrinterSettings for an optional prefix.
945 nsAutoString prtName;
946 nsresult rv = GetAdjustedPrinterName(aPS, true, prtName);
947 NS_ENSURE_SUCCESS(rv, rv);
949 #ifndef MOZ_WIDGET_ANDROID
950 // On most platforms we should always use a prefix when saving print settings
951 // to prefs. Saving without a prefix risks breaking printing for users
952 // without a good way for us to fix things for them (unprefixed prefs act as
953 // defaults and can result in values being inappropriately propagated to
954 // prefixed prefs).
955 if (prtName.IsEmpty()) {
956 MOZ_DIAGNOSTIC_ASSERT(false, "Print settings must be saved with a prefix");
957 return NS_ERROR_FAILURE;
959 #endif
961 return WritePrefs(aPS, prtName, aFlags);
964 nsresult nsPrintSettingsService::MaybeSaveLastUsedPrinterNameToPrefs(
965 const nsAString& aPrinterName) {
966 MOZ_DIAGNOSTIC_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
968 if (!Preferences::GetBool("print.save_print_settings", false)) {
969 return NS_OK;
972 if (!aPrinterName.IsEmpty()) {
973 Preferences::SetString(kPrinterName, aPrinterName);
975 return NS_OK;
978 //-----------------------------------------------------
979 //-- Protected Methods --------------------------------
980 //-----------------------------------------------------
981 nsresult nsPrintSettingsService::ReadPrefDouble(const char* aPrefId,
982 double& aVal) {
983 NS_ENSURE_ARG_POINTER(aPrefId);
985 nsAutoCString str;
986 nsresult rv = Preferences::GetCString(aPrefId, str);
987 if (NS_FAILED(rv) || str.IsEmpty()) {
988 return NS_ERROR_NOT_AVAILABLE;
991 double value = str.ToDouble(&rv);
992 if (NS_FAILED(rv)) {
993 return rv;
996 aVal = value;
997 return NS_OK;
1000 nsresult nsPrintSettingsService::WritePrefDouble(const char* aPrefId,
1001 double aVal) {
1002 NS_ENSURE_ARG_POINTER(aPrefId);
1004 nsAutoCString str;
1005 str.AppendFloat(aVal);
1006 return Preferences::SetCString(aPrefId, str);
1009 bool nsPrintSettingsService::ReadInchesToTwipsPref(const char* aPrefId,
1010 int32_t& aTwips) {
1011 nsAutoString str;
1012 nsresult rv = Preferences::GetString(aPrefId, str);
1013 if (NS_FAILED(rv) || str.IsEmpty()) {
1014 return false;
1017 float inches = str.ToFloat(&rv);
1018 if (NS_FAILED(rv)) {
1019 return false;
1022 aTwips = NS_INCHES_TO_INT_TWIPS(inches);
1023 return true;
1026 void nsPrintSettingsService::WriteInchesFromTwipsPref(const char* aPrefId,
1027 int32_t aTwips) {
1028 double inches = NS_TWIPS_TO_INCHES(aTwips);
1029 nsAutoCString inchesStr;
1030 inchesStr.AppendFloat(inches);
1032 Preferences::SetCString(aPrefId, inchesStr);
1035 bool nsPrintSettingsService::ReadInchesIntToTwipsPref(const char* aPrefId,
1036 int32_t& aTwips) {
1037 int32_t value;
1038 nsresult rv = Preferences::GetInt(aPrefId, &value);
1039 if (NS_FAILED(rv)) {
1040 return false;
1043 aTwips = NS_INCHES_TO_INT_TWIPS(float(value) / 100.0f);
1044 return true;
1047 void nsPrintSettingsService::WriteInchesIntFromTwipsPref(const char* aPrefId,
1048 int32_t aTwips) {
1049 Preferences::SetInt(aPrefId,
1050 int32_t(NS_TWIPS_TO_INCHES(aTwips) * 100.0f + 0.5f));
1053 void nsPrintSettingsService::ReadJustification(const char* aPrefId,
1054 int16_t& aJust,
1055 int16_t aInitValue) {
1056 aJust = aInitValue;
1057 nsAutoString justStr;
1058 if (NS_SUCCEEDED(Preferences::GetString(aPrefId, justStr))) {
1059 if (justStr.EqualsASCII(kJustRight)) {
1060 aJust = nsIPrintSettings::kJustRight;
1061 } else if (justStr.EqualsASCII(kJustCenter)) {
1062 aJust = nsIPrintSettings::kJustCenter;
1063 } else {
1064 aJust = nsIPrintSettings::kJustLeft;
1069 //---------------------------------------------------
1070 void nsPrintSettingsService::WriteJustification(const char* aPrefId,
1071 int16_t aJust) {
1072 switch (aJust) {
1073 case nsIPrintSettings::kJustLeft:
1074 Preferences::SetCString(aPrefId, kJustLeft);
1075 break;
1077 case nsIPrintSettings::kJustCenter:
1078 Preferences::SetCString(aPrefId, kJustCenter);
1079 break;
1081 case nsIPrintSettings::kJustRight:
1082 Preferences::SetCString(aPrefId, kJustRight);
1083 break;
1084 } // switch