print.cpp 41.1 KB
Newer Older
1
/*
2
3
4
 * Copyright © 2016-2017 Jan Grulich <jgrulich@redhat.com>
 * Copyright © 2007,2010 by John Layt <john@layt.net>
 * Copyright © 2007 Alex Merry <huntedhacker@tiscali.co.uk>
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "print.h"
22
#include "utils.h"
23

24
25
26
#include <KProcess>

#include <QFile>
27
28
#include <QLoggingCategory>
#include <QPrinter>
29
#include <QPrintEngine>
30
#include <QPrintDialog>
31
#include <QStandardPaths>
32
33
34
// #include <QtPrintSupport/private/qprint_p.h>
#include <QtPrintSupport/private/qcups_p.h>
#include <QUrl>
35
#include <QTemporaryFile>
36

Jan Grulich's avatar
Jan Grulich committed
37
Q_LOGGING_CATEGORY(XdgDesktopPortalKdePrint, "xdp-kde-print")
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

// INFO: code below is copied from Qt as there is no public API for converting key to PageSizeId

// TODO seems to by Windows only stuff
// Standard sources data
// struct StandardPaperSource {
//     QPrinter::PaperSource sourceNum;
//     const char *source;
// }
//
// static const StandardPaperSource qt_paperSources[] = {
//     {QPrinter::Auto, "Auto"},
//     {QPrinter::Cassette, "Cassette"},
//     {QPrinter::Envelope, "Envelope"},
//     {QPrinter::EnvelopeManual, "EnvelopeManual"},
//     {QPrinter::FormSource, "FormSource"},
//     {QPrinter::LargeCapacity, "LargeCapacity"},
//     {QPrinter::LargeFormat, "AnyLargeFormat"},
//     {QPrinter::Lower, "Lower"},
//     {QPrinter::Middle, "Middle"},
//     {QPrinter::Manual, "Manual"},
//     {QPrinter::Manual, "ManualFeed"},
//     {QPrinter::OnlyOne, "OnlyOne"}, // = QPrint::Upper
//     {QPrinter::Tractor, "Tractor"},
//     {QPrinter::SmallFormat, "AnySmallFormat"},
//     {QPrinter::Upper, "Upper"},
// };

// Standard sizes data
struct StandardPageSize {
    QPageSize::PageSizeId id;
    const char *mediaOption;  // PPD standard mediaOption ID
};

// Standard page sizes taken from the Postscript PPD Standard v4.3
// See http://partners.adobe.com/public/developer/en/ps/5003.PPD_Spec_v4.3.pdf
// Excludes all Transverse and Rotated sizes
75
76
// NB!This table needs to be in sync with QPageSize::PageSizeId
const static StandardPageSize qt_pageSizes[] = {
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

    // Existing Qt sizes including ISO, US, ANSI and other standards
    {QPageSize::A4, "A4"},
    {QPageSize::B5, "ISOB5"},
    {QPageSize::Letter, "Letter"},
    {QPageSize::Legal, "Legal"},
    {QPageSize::Executive, "Executive.7.5x10in"}, // Qt size differs from Postscript / Windows
    {QPageSize::A0, "A0"},
    {QPageSize::A1, "A1"},
    {QPageSize::A2, "A2"},
    {QPageSize::A3, "A3"},
    {QPageSize::A5, "A5"},
    {QPageSize::A6, "A6"},
    {QPageSize::A7, "A7"},
    {QPageSize::A8, "A8"},
    {QPageSize::A9, "A9"},
    {QPageSize::B0, "ISOB0"},
    {QPageSize::B1, "ISOB1"},
    {QPageSize::B10, "ISOB10"},
    {QPageSize::B2, "ISOB2"},
    {QPageSize::B3, "ISOB3"},
    {QPageSize::B4, "ISOB4"},
    {QPageSize::B6, "ISOB6"},
    {QPageSize::B7, "ISOB7"},
    {QPageSize::B8, "ISOB8"},
    {QPageSize::B9, "ISOB9"},
    {QPageSize::C5E, "EnvC5"},
    {QPageSize::Comm10E, "Env10"},
    {QPageSize::DLE, "EnvDL"},
    {QPageSize::Folio, "Folio"},
    {QPageSize::Ledger, "Ledger"},
    {QPageSize::Tabloid, "Tabloid"},
    {QPageSize::Custom, "Custom"}, // Special case to keep in sync with QPageSize::PageSizeId

    // ISO Standard Sizes
    {QPageSize::A10, "A10"},
    {QPageSize::A3Extra, "A3Extra"},
    {QPageSize::A4Extra, "A4Extra"},
    {QPageSize::A4Plus, "A4Plus"},
    {QPageSize::A4Small, "A4Small"},
    {QPageSize::A5Extra, "A5Extra"},
    {QPageSize::B5Extra, "ISOB5Extra"},

    // JIS Standard Sizes
    {QPageSize::JisB0, "B0"},
    {QPageSize::JisB1, "B1"},
    {QPageSize::JisB2, "B2"},
    {QPageSize::JisB3, "B3"},
    {QPageSize::JisB4, "B4"},
    {QPageSize::JisB5, "B5"},
    {QPageSize::JisB6, "B6"},
    {QPageSize::JisB7, "B7"},
    {QPageSize::JisB8, "B8"},
    {QPageSize::JisB9, "B9"},
    {QPageSize::JisB10, "B10"},

    // ANSI / US Standard sizes
    {QPageSize::AnsiC, "AnsiC"},
    {QPageSize::AnsiD, "AnsiD"},
    {QPageSize::AnsiE, "AnsiE"},
    {QPageSize::LegalExtra, "LegalExtra"},
    {QPageSize::LetterExtra, "LetterExtra"},
    {QPageSize::LetterPlus, "LetterPlus"},
    {QPageSize::LetterSmall, "LetterSmall"},
    {QPageSize::TabloidExtra, "TabloidExtra"},

    // Architectural sizes
    {QPageSize::ArchA, "ARCHA"},
    {QPageSize::ArchB, "ARCHB"},
    {QPageSize::ArchC, "ARCHC"},
    {QPageSize::ArchD, "ARCHD"},
    {QPageSize::ArchE, "ARCHE"},

    // Inch-based Sizes
    {QPageSize::Imperial7x9, "7x9"},
    {QPageSize::Imperial8x10, "8x10"},
    {QPageSize::Imperial9x11, "9x11"},
    {QPageSize::Imperial9x12, "9x12"},
    {QPageSize::Imperial10x11, "10x11"},
    {QPageSize::Imperial10x13, "10x13"},
    {QPageSize::Imperial10x14, "10x14"},
    {QPageSize::Imperial12x11, "12x11"},
    {QPageSize::Imperial15x11, "15x11"},

    // Other Page Sizes
    {QPageSize::ExecutiveStandard, "Executive"},   // Qt size differs from Postscript / Windows
    {QPageSize::Note, "Note"},
    {QPageSize::Quarto, "Quarto"},
    {QPageSize::Statement, "Statement"},
    {QPageSize::SuperA, "SuperA"},
    {QPageSize::SuperB, "SuperB"},
    {QPageSize::Postcard, "Postcard"},
    {QPageSize::DoublePostcard, "DoublePostcard"},
    {QPageSize::Prc16K, "PRC16K"},
    {QPageSize::Prc32K, "PRC32K"},
    {QPageSize::Prc32KBig, "PRC32KBig"},

    // Fan Fold Sizes
    {QPageSize::FanFoldUS, "FanFoldUS"},
    {QPageSize::FanFoldGerman, "FanFoldGerman"},
    {QPageSize::FanFoldGermanLegal, "FanFoldGermanLegal"},

    // ISO Envelopes
    {QPageSize::EnvelopeB4, "EnvISOB4"},
    {QPageSize::EnvelopeB5, "EnvISOB5"},
    {QPageSize::EnvelopeB6, "EnvISOB6"},
    {QPageSize::EnvelopeC0, "EnvC0"},
    {QPageSize::EnvelopeC1, "EnvC1"},
    {QPageSize::EnvelopeC2, "EnvC2"},
    {QPageSize::EnvelopeC3, "EnvC3"},
    {QPageSize::EnvelopeC4, "EnvC4"},
    {QPageSize::EnvelopeC6, "EnvC6"},
    {QPageSize::EnvelopeC65, "EnvC65"},
    {QPageSize::EnvelopeC7, "EnvC7"},

    // US Envelopes
    {QPageSize::Envelope9, "Env9"},
    {QPageSize::Envelope11, "Env11"},
    {QPageSize::Envelope12, "Env12"},
    {QPageSize::Envelope14, "Env14"},
    {QPageSize::EnvelopeMonarch, "EnvMonarch"},
    {QPageSize::EnvelopePersonal, "EnvPersonal"},

    // Other Envelopes
    {QPageSize::EnvelopeChou3, "EnvChou3"},
    {QPageSize::EnvelopeChou4, "EnvChou4"},
    {QPageSize::EnvelopeInvite, "EnvInvite"},
    {QPageSize::EnvelopeItalian, "EnvItalian"},
    {QPageSize::EnvelopeKaku2, "EnvKaku2"},
    {QPageSize::EnvelopeKaku3, "EnvKaku3"},
    {QPageSize::EnvelopePrc1, "EnvPRC1"},
    {QPageSize::EnvelopePrc2, "EnvPRC2"},
    {QPageSize::EnvelopePrc3, "EnvPRC3"},
    {QPageSize::EnvelopePrc4, "EnvPRC4"},
    {QPageSize::EnvelopePrc5, "EnvPRC5"},
    {QPageSize::EnvelopePrc6, "EnvPRC6"},
    {QPageSize::EnvelopePrc7, "EnvPRC7"},
    {QPageSize::EnvelopePrc8, "EnvPRC8"},
    {QPageSize::EnvelopePrc9, "EnvPRC9"},
    {QPageSize::EnvelopePrc10, "EnvPRC10"},
    {QPageSize::EnvelopeYou4, "EnvYou4"}
};

// Return key name for PageSize
static QString qt_keyForPageSizeId(QPageSize::PageSizeId id)
{
    return QString::fromLatin1(qt_pageSizes[id].mediaOption);
}

// Return id name for PPD Key
static QPageSize::PageSizeId qt_idForPpdKey(const QString &ppdKey)
{
    if (ppdKey.isEmpty()) {
        return QPageSize::Custom;
    }

    for (int i = 0; i <= int(QPageSize::LastPageSize); ++i) {
        if (QLatin1String(qt_pageSizes[i].mediaOption) == ppdKey) {
            return qt_pageSizes[i].id;
        }
    }
    return QPageSize::Custom;
}

241
242
PrintPortal::PrintPortal(QObject *parent)
    : QDBusAbstractAdaptor(parent)
243
244
245
{
}

246
PrintPortal::~PrintPortal()
247
248
249
{
}

250
uint PrintPortal::Print(const QDBusObjectPath &handle,
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                  const QString &app_id,
                  const QString &parent_window,
                  const QString &title,
                  const QDBusUnixFileDescriptor &fd,
                  const QVariantMap &options,
                  QVariantMap &results)
{
    qCDebug(XdgDesktopPortalKdePrint) << "Print called with parameters:";
    qCDebug(XdgDesktopPortalKdePrint) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdePrint) << "    app_id: " << app_id;
    qCDebug(XdgDesktopPortalKdePrint) << "    parent_window: " << parent_window;
    qCDebug(XdgDesktopPortalKdePrint) << "    title: " << title;
    qCDebug(XdgDesktopPortalKdePrint) << "    fd: " << fd.fileDescriptor();
    qCDebug(XdgDesktopPortalKdePrint) << "    options: " << options;

266
267
268
269
    QFile fileToPrint;
    if (fileToPrint.open(fd.fileDescriptor(), QIODevice::ReadOnly)) {
        QPrinter *printer = nullptr;
        // Use printer associated with token if possible
Laurent Montel's avatar
Laurent Montel committed
270
271
        if (options.contains(QStringLiteral("token"))) {
            printer = m_printers.value(options.value(QStringLiteral("token")).toUInt());
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
        } else {
            // Use the last configured printer otherwise
            if (m_printers.count()) {
                printer = m_printers.last();
            }
        }

        if (!printer) {
            qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: no QPrinter what can be used for printing";
            return 1;
        }

        // We are going to print to a file
        if (!printer->outputFileName().isEmpty()) {
            if (QFile::exists(printer->outputFileName())) {
                QFile::remove(printer->outputFileName());
            }

            QByteArray pdfContent = fileToPrint.readAll();
            QFile outputFile(printer->outputFileName());
            if (outputFile.open(QIODevice::ReadWrite)) {
                outputFile.write(pdfContent);
                outputFile.close();
            } else {
                qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: couldn't open the file for writing";
            }

            fileToPrint.close();

            return 0;

            // TODO poscript support?

            // Print to a printer via lpr command
        } else {
            // The code below is copied from Okular
            bool useCupsOptions = cupsAvailable();
            QString exe;
            QStringList argList;

            //Decide what executable to use to print with, need the CUPS version of lpr if available
            //Some distros name the CUPS version of lpr as lpr-cups or lpr.cups so try those first
            //before default to lpr, or failing that to lp
            if (!QStandardPaths::findExecutable(QStringLiteral("lpr-cups")).isEmpty()) {
                exe = QStringLiteral("lpr-cups");
            } else if (!QStandardPaths::findExecutable(QStringLiteral("lpr.cups")).isEmpty()) {
                exe = QStringLiteral("lpr.cups");
            } else if (!QStandardPaths::findExecutable(QStringLiteral("lpr")).isEmpty()) {
                exe = QStringLiteral("lpr");
            } else if (!QStandardPaths::findExecutable(QStringLiteral("lp")).isEmpty()) {
                exe = QStringLiteral("lp");
            } else {
                qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: couldn't run lpr command for printing";
                return 1;
            }

            QTemporaryFile tempFile;
            if (tempFile.open()) {
                tempFile.write(fileToPrint.readAll());
                tempFile.close();
            } else {
                qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: couldn't create temporary file for printing";
                return 1;
            }

            argList = printArguments(printer, useCupsOptions, exe, printer->orientation()) << tempFile.fileName();
338
            // qCDebug(XdgDesktopPortalKdePrint) << "Executing" << exe << "with arguments" << argList << tempFile.fileName();
339
340
341
342
343
344
345
346
347
348
349
350
351
352
            int retValue = KProcess::execute(exe, argList);

            if (retValue <= 0) {
                qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: running KProcess failed";
                return 1;
            }

            return retValue;
        }
    } else {
        qCDebug(XdgDesktopPortalKdePrint) << "Failed to print: couldn't not read from fd";
        return 1;
    }

353
354
355
    return 0;
}

356
uint PrintPortal::PreparePrint(const QDBusObjectPath &handle,
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                         const QString &app_id,
                         const QString &parent_window,
                         const QString &title,
                         const QVariantMap &settings,
                         const QVariantMap &page_setup,
                         const QVariantMap &options,
                         QVariantMap &results)
{
    qCDebug(XdgDesktopPortalKdePrint) << "PreparePrint called with parameters:";
    qCDebug(XdgDesktopPortalKdePrint) << "    handle: " << handle.path();
    qCDebug(XdgDesktopPortalKdePrint) << "    app_id: " << app_id;
    qCDebug(XdgDesktopPortalKdePrint) << "    parent_window: " << parent_window;
    qCDebug(XdgDesktopPortalKdePrint) << "    title: " << title;
    qCDebug(XdgDesktopPortalKdePrint) << "    settings: " << settings;
    qCDebug(XdgDesktopPortalKdePrint) << "    page_setup: " << page_setup;
    qCDebug(XdgDesktopPortalKdePrint) << "    options: " << options;

    // Create new one
    QPrinter *printer = new QPrinter();

    // First we have to load pre-configured options

    // Process settings (used by printer)
Laurent Montel's avatar
Laurent Montel committed
380
    if (settings.contains(QStringLiteral("orientation"))) {
381
382
        // TODO: what is the difference between this and the one in page setup
    }
Laurent Montel's avatar
Laurent Montel committed
383
    if (settings.contains(QStringLiteral("paper-format"))) {
384
385
        // TODO: what is the difference between this and the one in page setup
    }
Laurent Montel's avatar
Laurent Montel committed
386
    if (settings.contains(QStringLiteral("paper-width"))) {
387
388
        // TODO: what is the difference between this and the one in page setup
    }
Laurent Montel's avatar
Laurent Montel committed
389
    if (settings.contains(QStringLiteral("paper-height"))) {
390
391
        // TODO: what is the difference between this and the one in page setup
    }
Laurent Montel's avatar
Laurent Montel committed
392
393
    if (settings.contains(QStringLiteral("n-copies"))) {
        printer->setCopyCount(settings.value(QStringLiteral("n-copies")).toString().toInt());
394
    }
Laurent Montel's avatar
Laurent Montel committed
395
    if (settings.contains(QStringLiteral("default-source"))) {
396
397
        // TODO seems to be windows only stuff
    }
Laurent Montel's avatar
Laurent Montel committed
398
    if (settings.contains(QStringLiteral("quality"))) {
399
400
        // TODO doesn't seem to be used by Qt
    }
Laurent Montel's avatar
Laurent Montel committed
401
402
    if (settings.contains(QStringLiteral("resolution"))) {
        printer->setResolution(settings.value(QStringLiteral("resolution")).toString().toInt());
403
    }
Laurent Montel's avatar
Laurent Montel committed
404
405
    if (settings.contains(QStringLiteral("use-color"))) {
        printer->setColorMode(settings.value(QStringLiteral("use-color")).toString() == QLatin1String("yes") ? QPrinter::Color : QPrinter::GrayScale);
406
    }
Laurent Montel's avatar
Laurent Montel committed
407
408
    if (settings.contains(QStringLiteral("duplex"))) {
        const QString duplex = settings.value(QStringLiteral("duplex")).toString();
409
410
411
412
413
414
415
416
        if (duplex == QLatin1String("simplex")) {
            printer->setDuplex(QPrinter::DuplexNone);
        } else if (duplex == QLatin1String("horizontal")) {
            printer->setDuplex(QPrinter::DuplexShortSide);
        } else if (duplex == QLatin1String("vertical")) {
            printer->setDuplex(QPrinter::DuplexLongSide);
        }
    }
Laurent Montel's avatar
Laurent Montel committed
417
418
    if (settings.contains(QStringLiteral("collate"))) {
        printer->setCollateCopies(settings.value(QStringLiteral("collate")).toString() == QLatin1String("yes"));
419
    }
Laurent Montel's avatar
Laurent Montel committed
420
421
    if (settings.contains(QStringLiteral("reverse"))) {
        printer->setPageOrder(settings.value(QStringLiteral("reverse")).toString() == QLatin1String("yes") ? QPrinter::LastPageFirst : QPrinter::FirstPageFirst);
422
423
    }

Laurent Montel's avatar
Laurent Montel committed
424
    if (settings.contains(QStringLiteral("media-type"))) {
425
426
        // TODO doesn't seem to be used by Qt
    }
Laurent Montel's avatar
Laurent Montel committed
427
    if (settings.contains(QStringLiteral("dither"))) {
428
429
        // TODO doesn't seem to be used by Qt
    }
Laurent Montel's avatar
Laurent Montel committed
430
    if (settings.contains(QStringLiteral("scale"))) {
431
432
        // TODO doesn't seem to be used by Qt
    }
Laurent Montel's avatar
Laurent Montel committed
433
434
    if (settings.contains(QStringLiteral("print-pages"))) {
        const QString printPages = settings.value(QStringLiteral("print-pages")).toString();
435
436
437
438
439
440
441
442
443
444
        if (printPages == QLatin1String("all")) {
            printer->setPrintRange(QPrinter::AllPages);
        } else if (printPages == QLatin1String("selection")) {
            printer->setPrintRange(QPrinter::Selection);
        } else if (printPages == QLatin1String("current")) {
            printer->setPrintRange(QPrinter::CurrentPage);
        } else if (printPages == QLatin1String("ranges")) {
            printer->setPrintRange(QPrinter::PageRange);
        }
    }
Laurent Montel's avatar
Laurent Montel committed
445
446
    if (settings.contains(QStringLiteral("page-ranges"))) {
        const QString range = settings.value(QStringLiteral("page-ranges")).toString();
447
448
449
450
451
452
453
454
455
        // Gnome supports format like 1-5,7,9,11-15, however Qt support only e.g.1-15
        // so get the first and the last value
        const QStringList ranges = range.split(QLatin1Char(','));
        if (ranges.count()) {
            QStringList firstRangeValues = ranges.first().split(QLatin1Char('-'));
            QStringList lastRangeValues = ranges.last().split(QLatin1Char('-'));
            printer->setFromTo(firstRangeValues.first().toInt(), lastRangeValues.last().toInt());
        }
    }
Laurent Montel's avatar
Laurent Montel committed
456
    if (settings.contains(QStringLiteral("page-set"))) {
457
        // WARNING Qt internal private API, anyway the print dialog doesn't seem to
458
        // read these properties, but I'll leave it here in case this changes in future
Laurent Montel's avatar
Laurent Montel committed
459
        const QString pageSet = settings.value(QStringLiteral("page-set")).toString();
460
461
462
463
464
465
466
467
        if (pageSet == QLatin1String("all")) {
            QCUPSSupport::setPageSet(printer, QCUPSSupport::AllPages);
        } else if (pageSet == QLatin1String("even")) {
            QCUPSSupport::setPageSet(printer, QCUPSSupport::EvenPages);
        } else if (pageSet == QLatin1String("odd")) {
            QCUPSSupport::setPageSet(printer, QCUPSSupport::OddPages);
        }
    }
468

Laurent Montel's avatar
Laurent Montel committed
469
    if (settings.contains(QStringLiteral("finishings"))) {
470
471
472
473
474
        // TODO doesn't seem to be used by Qt
    }

    QCUPSSupport::PagesPerSheet pagesPerSheet = QCUPSSupport::OnePagePerSheet;
    QCUPSSupport::PagesPerSheetLayout pagesPerSheetLayout = QCUPSSupport::LeftToRightTopToBottom;
Laurent Montel's avatar
Laurent Montel committed
475
    if (settings.contains(QStringLiteral("number-up"))) {
476
        // WARNING Qt internal private API, anyway the print dialog doesn't seem to
477
        // read these properties, but I'll leave it here in case this changes in future
Laurent Montel's avatar
Laurent Montel committed
478
        const QString numberUp = settings.value(QStringLiteral("number-up")).toString();
479
480
481
482
483
484
485
486
487
488
489
490
491
492
        if (numberUp == QLatin1String("1")) {
            pagesPerSheet = QCUPSSupport::OnePagePerSheet;
        } else if (numberUp == QLatin1String("2")) {
            pagesPerSheet = QCUPSSupport::TwoPagesPerSheet;
        } else if (numberUp == QLatin1String("4")) {
            pagesPerSheet = QCUPSSupport::FourPagesPerSheet;
        } else if (numberUp == QLatin1String("6")) {
            pagesPerSheet = QCUPSSupport::SixPagesPerSheet;
        } else if (numberUp == QLatin1String("9")) {
            pagesPerSheet = QCUPSSupport::NinePagesPerSheet;
        } else if (numberUp == QLatin1String("16")) {
            pagesPerSheet = QCUPSSupport::SixteenPagesPerSheet;
        }
    }
Laurent Montel's avatar
Laurent Montel committed
493
    if (settings.contains(QStringLiteral("number-up-layout"))) {
494
        // WARNING Qt internal private API, anyway the print dialog doesn't seem to
495
        // read these properties, but I'll leave it here in case this changes in future
Laurent Montel's avatar
Laurent Montel committed
496
        const QString layout = settings.value(QStringLiteral("number-up-layout")).toString();
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
        if (layout == QLatin1String("lrtb")) {
            pagesPerSheetLayout = QCUPSSupport::LeftToRightTopToBottom;
        } else if (layout == QLatin1String("lrbt")) {
            pagesPerSheetLayout = QCUPSSupport::LeftToRightBottomToTop;
        } else if (layout == QLatin1String("rltb")) {
            pagesPerSheetLayout = QCUPSSupport::RightToLeftTopToBottom;
        } else if (layout == QLatin1String("rlbt")) {
            pagesPerSheetLayout = QCUPSSupport::RightToLeftBottomToTop;
        } else if (layout == QLatin1String("tblr")) {
            pagesPerSheetLayout = QCUPSSupport::TopToBottomLeftToRight;
        } else if (layout == QLatin1String("tbrl")) {
            pagesPerSheetLayout = QCUPSSupport::TopToBottomRightToLeft;
        } else if (layout == QLatin1String("btlr")) {
            pagesPerSheetLayout = QCUPSSupport::BottomToTopLeftToRight;
        } else if (layout == QLatin1String("btrl")) {
            pagesPerSheetLayout = QCUPSSupport::BottomToTopRightToLeft;
        }
    }
    QCUPSSupport::setPagesPerSheetLayout(printer, pagesPerSheet, pagesPerSheetLayout);

Laurent Montel's avatar
Laurent Montel committed
517
    if (settings.contains(QStringLiteral("output-bin"))) {
518
519
        // TODO not sure what this setting represents
    }
Laurent Montel's avatar
Laurent Montel committed
520
    if (settings.contains(QStringLiteral("resolution-x"))) {
521
522
523
        // TODO possible to set only full resolution, but I can count the total
        // resolution I guess, anyway doesn't seem to be used by the print dialog
    }
Laurent Montel's avatar
Laurent Montel committed
524
    if (settings.contains(QStringLiteral("resolution-y"))) {
525
526
527
        // TODO possible to set only full resolution, but I can count the total
        // resolution I guess, anyway doesn't seem to be used by the print dialog
    }
Laurent Montel's avatar
Laurent Montel committed
528
    if (settings.contains(QStringLiteral("printer-lpi"))) {
529
530
        // TODO not possible to set, maybe count it?
    }
Laurent Montel's avatar
Laurent Montel committed
531
    if (settings.contains(QStringLiteral("output-basename"))) {
532
533
534
        // TODO processed in output-uri
        // printer->setOutputFileName(settings.value(QLatin1String("output-basename")).toString());
    }
Laurent Montel's avatar
Laurent Montel committed
535
    if (settings.contains(QStringLiteral("output-file-format"))) {
536
537
538
539
        // TODO only PDF supported by Qt so when printing to file we can use PDF only
        // btw. this should be already set automatically because we set output file name
        printer->setOutputFormat(QPrinter::PdfFormat);
    }
Laurent Montel's avatar
Laurent Montel committed
540
541
    if (settings.contains(QStringLiteral("output-uri"))) {
        const QUrl uri = QUrl(settings.value(QStringLiteral("output-uri")).toString());
542
543
        // Check whether the uri is not just a directory name and whether we don't need to
        // append output-basename
Laurent Montel's avatar
Laurent Montel committed
544
545
        if (settings.contains(QStringLiteral("output-basename"))) {
            const QString basename = settings.value(QStringLiteral("output-basename")).toString();
546
547
548
549
550
551
552
553
554
555
556
            if (!uri.toDisplayString().endsWith(basename) && uri.toDisplayString().endsWith(QLatin1Char('/'))) {
                printer->setOutputFileName(uri.toDisplayString() + basename);
            }
        } else {
            printer->setOutputFileName(uri.toDisplayString());
        }
    }

    // Process page setup
    QMarginsF pageMargins = printer->pageLayout().margins(QPageLayout::Millimeter);

Laurent Montel's avatar
Laurent Montel committed
557
558
    if (page_setup.contains(QStringLiteral("PPDName"))) {
        printer->setPageSize(QPageSize(qt_idForPpdKey(page_setup.value(QStringLiteral("PPDName")).toString())));
559
    }
Laurent Montel's avatar
Laurent Montel committed
560
    if (page_setup.contains(QStringLiteral("Name"))) {
561
        // TODO: Try to use name instead of PPDName, at least I think it's how it's supposed to be used
Laurent Montel's avatar
Laurent Montel committed
562
563
        if (!page_setup.contains(QStringLiteral("PPDName"))) {
            printer->setPageSize(QPageSize(qt_idForPpdKey(page_setup.value(QStringLiteral("PPDName")).toString())));
564
565
        }
    }
Laurent Montel's avatar
Laurent Montel committed
566
    if (page_setup.contains(QStringLiteral("DisplayName"))) {
567
568
        // TODO: This should just set a different name for the standardized one I guess
        printer->setPageSize(QPageSize(printer->pageLayout().pageSize().size(QPageSize::Millimeter),
Laurent Montel's avatar
Laurent Montel committed
569
                                       QPageSize::Millimeter, page_setup.value(QStringLiteral("DisplayName")).toString()));
570
    }
Laurent Montel's avatar
Laurent Montel committed
571
    if (page_setup.contains(QStringLiteral("Width")) && page_setup.contains(QStringLiteral("Height"))) {
572
        QSizeF paperSize;
Laurent Montel's avatar
Laurent Montel committed
573
574
575
        paperSize.setHeight(page_setup.value(QStringLiteral("Height")).toReal());
        paperSize.setWidth(page_setup.value(QStringLiteral("Width")).toReal());
        printer->setPageSize(QPageSize(paperSize, QPageSize::Millimeter, page_setup.value(QStringLiteral("DisplayName")).toString()));
576
    }
Laurent Montel's avatar
Laurent Montel committed
577
578
    if (page_setup.contains(QStringLiteral("MarginTop"))) {
        pageMargins.setTop(page_setup.value(QStringLiteral("MarginTop")).toReal());
579
    }
Laurent Montel's avatar
Laurent Montel committed
580
581
    if (page_setup.contains(QStringLiteral("MarginBottom"))) {
        pageMargins.setBottom(page_setup.value(QStringLiteral("MarginBottom")).toReal());
582
    }
Laurent Montel's avatar
Laurent Montel committed
583
584
    if (page_setup.contains(QStringLiteral("MarginLeft"))) {
        pageMargins.setLeft(page_setup.value(QStringLiteral("MarginLeft")).toReal());
585
    }
Laurent Montel's avatar
Laurent Montel committed
586
587
    if (page_setup.contains(QStringLiteral("MarginRight"))) {
        pageMargins.setRight(page_setup.value(QStringLiteral("MarginLeft")).toReal());
588
    }
Laurent Montel's avatar
Laurent Montel committed
589
590
    if (page_setup.contains(QStringLiteral("Orientation"))) {
        const QString orientation = page_setup.value(QStringLiteral("Orientation")).toString();
591
        if (orientation == QLatin1String("landscape") ||
592
                orientation == QLatin1String("reverse_landscape")) {
593
594
595
596
597
598
599
600
601
602
            printer->setPageOrientation(QPageLayout::Landscape);
        } else if (orientation == QLatin1String("portrait") ||
                   orientation == QLatin1String("reverse_portrait")) {
            printer->setPageOrientation(QPageLayout::Portrait);
        }
    }

    printer->setPageMargins(pageMargins, QPageLayout::Millimeter);

    QPrintDialog *printDialog = new QPrintDialog(printer);
603
    Utils::setParentWindow(printDialog, parent_window);
604
605
606

    // Process options

Laurent Montel's avatar
Laurent Montel committed
607
608
    if (options.contains(QStringLiteral("modal"))) {
        printDialog->setModal(options.value(QStringLiteral("modal")).toBool());
609
610
611
612
613
614
615
616
617
    }

    // Pass back what we configured

    if (printDialog->exec() == QDialog::Accepted) {
        QVariantMap resultingSettings;
        QVariantMap resultingPageSetup;

        // Process back printer settings
Laurent Montel's avatar
Laurent Montel committed
618
619
620
        resultingSettings.insert(QStringLiteral("n-copies"), QString::number(printer->copyCount()));
        resultingSettings.insert(QStringLiteral("resolution"), QString::number(printer->resolution()));
        resultingSettings.insert(QStringLiteral("use-color"), printer->colorMode() == QPrinter::Color ? QLatin1String("yes") : QLatin1String("no"));
621
        if (printer->duplex() == QPrinter::DuplexNone) {
Laurent Montel's avatar
Laurent Montel committed
622
            resultingSettings.insert(QStringLiteral("duplex"), QLatin1String("simplex"));
623
        } else if (printer->duplex() == QPrinter::DuplexShortSide) {
Laurent Montel's avatar
Laurent Montel committed
624
            resultingSettings.insert(QStringLiteral("duplex"), QLatin1String("horizontal"));
625
        } else if (printer->duplex() == QPrinter::DuplexLongSide) {
Laurent Montel's avatar
Laurent Montel committed
626
            resultingSettings.insert(QStringLiteral("duplex"), QLatin1String("vertical"));
627
        }
Laurent Montel's avatar
Laurent Montel committed
628
629
        resultingSettings.insert(QStringLiteral("collate"), printer->collateCopies() ? QLatin1String("yes") : QLatin1String("no"));
        resultingSettings.insert(QStringLiteral("reverse"), printer->pageOrder() == QPrinter::LastPageFirst ? QLatin1String("yes") : QLatin1String("no"));
630
        if (printer->printRange() == QPrinter::AllPages) {
Laurent Montel's avatar
Laurent Montel committed
631
            resultingSettings.insert(QStringLiteral("print-pages"), QLatin1String("all"));
632
        } else if (printer->printRange() == QPrinter::Selection) {
Laurent Montel's avatar
Laurent Montel committed
633
            resultingSettings.insert(QStringLiteral("print-pages"), QLatin1String("selection"));
634
        } else if (printer->printRange() == QPrinter::CurrentPage) {
Laurent Montel's avatar
Laurent Montel committed
635
            resultingSettings.insert(QStringLiteral("print-pages"), QLatin1String("current"));
636
        } else if (printer->printRange() == QPrinter::PageRange) {
Laurent Montel's avatar
Laurent Montel committed
637
            resultingSettings.insert(QStringLiteral("print-pages"), QLatin1String("ranges"));
638
639
640
            const int fromPageToIndex = printer->fromPage() ? printer->fromPage() - 1 : printer->fromPage();
            const int toPageToIndex = printer->toPage() ? printer->toPage() - 1 : printer->toPage();
            resultingSettings.insert(QStringLiteral("page-ranges"), QStringLiteral("%1-%2").arg(fromPageToIndex).arg(toPageToIndex));
641
642
        }
        // Set cups specific properties
643
        const QStringList cupsOptions = printer->printEngine()->property(PPK_CupsOptions).toStringList();
644
        qCDebug(XdgDesktopPortalKdePrint) << cupsOptions;
645
        if (cupsOptions.contains(QLatin1String("page-set"))) {
Laurent Montel's avatar
Laurent Montel committed
646
            resultingSettings.insert(QStringLiteral("page-set"), cupsOptions.at(cupsOptions.indexOf(QStringLiteral("page-set")) + 1));
647
648
        }
        if (cupsOptions.contains(QLatin1String("number-up"))) {
Laurent Montel's avatar
Laurent Montel committed
649
            resultingSettings.insert(QStringLiteral("number-up"), cupsOptions.at(cupsOptions.indexOf(QStringLiteral("number-up")) + 1));
650
651
        }
        if (cupsOptions.contains(QLatin1String("number-up-layout"))) {
Laurent Montel's avatar
Laurent Montel committed
652
            resultingSettings.insert(QStringLiteral("number-up-layout"), cupsOptions.at(cupsOptions.indexOf(QStringLiteral("number-up-layout")) + 1));
653
654
655
        }

        if (printer->outputFormat() == QPrinter::PdfFormat) {
Laurent Montel's avatar
Laurent Montel committed
656
            resultingSettings.insert(QStringLiteral("output-file-format"), QLatin1String("pdf"));
657
658
659
        }

        if (!printer->outputFileName().isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
660
            resultingSettings.insert(QStringLiteral("output-uri"), QUrl::fromLocalFile(printer->outputFileName()).toDisplayString());
661
662
663
        }

        // Process back page setup
Laurent Montel's avatar
Laurent Montel committed
664
        resultingPageSetup.insert(QStringLiteral("PPDName"), qt_keyForPageSizeId(printer->pageLayout().pageSize().id()));
665
        // TODO: verify if this make sense
Laurent Montel's avatar
Laurent Montel committed
666
        resultingPageSetup.insert(QStringLiteral("Name"), qt_keyForPageSizeId(printer->pageLayout().pageSize().id()));
667
        // TODO: verify if this make sense
Laurent Montel's avatar
Laurent Montel committed
668
669
670
671
672
673
674
675
        resultingPageSetup.insert(QStringLiteral("DisplayName"), qt_keyForPageSizeId(printer->pageLayout().pageSize().id()));
        resultingPageSetup.insert(QStringLiteral("Width"), printer->pageLayout().pageSize().size(QPageSize::Millimeter).width());
        resultingPageSetup.insert(QStringLiteral("Height"), printer->pageLayout().pageSize().size(QPageSize::Millimeter).height());
        resultingPageSetup.insert(QStringLiteral("MarginTop"), printer->pageLayout().margins(QPageLayout::Millimeter).top());
        resultingPageSetup.insert(QStringLiteral("MarginBottom"), printer->pageLayout().margins(QPageLayout::Millimeter).bottom());
        resultingPageSetup.insert(QStringLiteral("MarginLeft"), printer->pageLayout().margins(QPageLayout::Millimeter).left());
        resultingPageSetup.insert(QStringLiteral("MarginRight"), printer->pageLayout().margins(QPageLayout::Millimeter).right());
        resultingPageSetup.insert(QStringLiteral("Orientation"), printer->pageLayout().orientation() == QPageLayout::Landscape ? QLatin1String("landscape") : QLatin1String("portrait"));
676
677
678
679
680
681
682
683

        qCDebug(XdgDesktopPortalKdePrint) << "Settings: ";
        qCDebug(XdgDesktopPortalKdePrint) << "---------------------------";
        qCDebug(XdgDesktopPortalKdePrint) << resultingSettings;
        qCDebug(XdgDesktopPortalKdePrint) << "Page setup: ";
        qCDebug(XdgDesktopPortalKdePrint) << "---------------------------";
        qCDebug(XdgDesktopPortalKdePrint) << resultingPageSetup;

684
        uint token = QDateTime::currentDateTime().toSecsSinceEpoch();
Laurent Montel's avatar
Laurent Montel committed
685
686
687
        results.insert(QStringLiteral("settings"), resultingSettings);
        results.insert(QStringLiteral("page-setup"), resultingPageSetup);
        results.insert(QStringLiteral("token"), token);
688
689
690
691
692
693

        m_printers.insert(token, printer);

        printDialog->deleteLater();
        return 0;
    } else {
694
        printDialog->deleteLater();
695
696
697
698
699
        return 1;
    }

    return 0;
}
700

701
QStringList PrintPortal::destination(const QPrinter *printer, const QString &version)
702
703
704
705
706
707
708
709
710
711
712
713
{
    if (version == QLatin1String("lp")) {
        return QStringList(QStringLiteral("-d")) << printer->printerName();
    }

    if (version.startsWith(QLatin1String("lpr"))) {
        return QStringList(QStringLiteral("-P")) << printer->printerName();
    }

    return QStringList();
}

714
QStringList PrintPortal::copies(const QPrinter *printer, const QString &version)
715
716
717
718
719
720
721
722
723
724
725
726
727
728
{
    int cp = printer->actualNumCopies();

    if (version == QLatin1String("lp")) {
        return QStringList(QStringLiteral("-n")) << QStringLiteral("%1").arg(cp);
    }

    if (version.startsWith(QLatin1String("lpr"))) {
        return QStringList() << QStringLiteral("-#%1").arg(cp);
    }

    return QStringList();
}

729
QStringList PrintPortal::jobname(const QPrinter *printer, const QString &version)
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
{
    if (!printer->docName().isEmpty()) {

        if (version == QLatin1String("lp")) {
            return QStringList(QStringLiteral("-t")) << printer->docName();
        }

        if (version.startsWith(QLatin1String("lpr"))) {
            const QString shortenedDocName = QString::fromUtf8(printer->docName().toUtf8().left(255));
            return QStringList(QStringLiteral("-J")) << shortenedDocName;
        }
    }

    return QStringList();
}

// What about Upper and MultiPurpose?  And others in PPD???
747
QString PrintPortal::mediaPaperSource(const QPrinter *printer)
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
{
    switch (printer->paperSource()) {
    case QPrinter::Auto:
        return QString();
    case QPrinter::Cassette:
        return QStringLiteral("Cassette");
    case QPrinter::Envelope:
        return QStringLiteral("Envelope");
    case QPrinter::EnvelopeManual:
        return QStringLiteral("EnvelopeManual");
    case QPrinter::FormSource:
        return QStringLiteral("FormSource");
    case QPrinter::LargeCapacity:
        return QStringLiteral("LargeCapacity");
    case QPrinter::LargeFormat:
        return QStringLiteral("LargeFormat");
    case QPrinter::Lower:
        return QStringLiteral("Lower");
    case QPrinter::MaxPageSource:
        return QStringLiteral("MaxPageSource");
    case QPrinter::Middle:
        return QStringLiteral("Middle");
    case QPrinter::Manual:
        return QStringLiteral("Manual");
    case QPrinter::OnlyOne:
        return QStringLiteral("OnlyOne");
    case QPrinter::Tractor:
        return QStringLiteral("Tractor");
    case QPrinter::SmallFormat:
        return QStringLiteral("SmallFormat");
    default:
        return QString();
    }
}

783
QStringList PrintPortal::optionOrientation(const QPrinter *printer, QPrinter::Orientation documentOrientation)
784
785
786
787
788
789
790
791
792
793
794
795
796
{
    // portrait and landscape options rotate the document according to the document orientation
    // If we want to print a landscape document as one would expect it, we have to pass the
    // portrait option so that the document is not rotated additionally
    if (printer->orientation() == documentOrientation) {
        // the user wants the document printed as is
        return QStringList(QStringLiteral("-o")) << QStringLiteral("portrait");
    } else {
        // the user expects the document being rotated by 90 degrees
        return QStringList(QStringLiteral("-o")) << QStringLiteral("landscape");
    }
}

797
QStringList PrintPortal::optionDoubleSidedPrinting(const QPrinter *printer)
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
{
    switch (printer->duplex()) {
    case QPrinter::DuplexNone:
        return QStringList(QStringLiteral("-o")) << QStringLiteral("sides=one-sided");
    case QPrinter::DuplexAuto:
        if (printer->orientation() == QPrinter::Landscape) {
            return QStringList(QStringLiteral("-o")) << QStringLiteral("sides=two-sided-short-edge");
        } else {
            return QStringList(QStringLiteral("-o")) << QStringLiteral("sides=two-sided-long-edge");
        }
    case QPrinter::DuplexLongSide:
        return QStringList(QStringLiteral("-o")) << QStringLiteral("sides=two-sided-long-edge");
    case QPrinter::DuplexShortSide:
        return QStringList(QStringLiteral("-o")) << QStringLiteral("sides=two-sided-short-edge");
    default:
        return QStringList();  //Use printer default
    }
}

817
QStringList PrintPortal::optionPageOrder(const QPrinter *printer)
818
819
820
821
822
823
824
{
    if (printer->pageOrder() == QPrinter::LastPageFirst) {
        return QStringList(QStringLiteral("-o")) << QStringLiteral("outputorder=reverse");
    }
    return QStringList(QStringLiteral("-o")) << QStringLiteral("outputorder=normal");
}

825
QStringList PrintPortal::optionCollateCopies(const QPrinter *printer)
826
827
828
829
830
831
832
{
    if (printer->collateCopies()) {
        return QStringList(QStringLiteral("-o")) << QStringLiteral("Collate=True");
    }
    return QStringList(QStringLiteral("-o")) << QStringLiteral("Collate=False");
}

833
QStringList PrintPortal::optionPageMargins(const QPrinter *printer)
834
835
836
837
838
839
840
841
842
843
844
845
846
{
    if (printer->printEngine()->property(QPrintEngine::PPK_PageMargins).isNull()) {
        return QStringList();
    } else {
        qreal l, t, r, b;
        printer->getPageMargins(&l, &t, &r, &b, QPrinter::Point);
        return QStringList(QStringLiteral("-o")) << QStringLiteral("page-left=%1").arg(l)
               <<  QStringLiteral("-o")  << QStringLiteral("page-top=%1").arg(t)
               <<  QStringLiteral("-o")  << QStringLiteral("page-right=%1").arg(r)
               <<  QStringLiteral("-o")  << QStringLiteral("page-bottom=%1").arg(b) << QStringLiteral("-o") << QStringLiteral("fit-to-page");
    }
}

847
QStringList PrintPortal::optionCupsProperties(const QPrinter *printer)
848
849
850
851
852
{
    QStringList dialogOptions = printer->printEngine()->property(QPrintEngine::PrintEnginePropertyKey(0xfe00)).toStringList();
    QStringList cupsOptions;

    for (int i = 0; i < dialogOptions.count(); i = i + 2) {
853
854
855
856
857
        // Ignore some cups properties as the pdf we get is already formatted using these
        if (dialogOptions[i] == QLatin1String("number-up") || dialogOptions[i] == QLatin1String("number-up-layout")) {
            continue;
        }

858
859
860
861
862
863
864
865
866
867
        if (dialogOptions[i + 1].isEmpty()) {
            cupsOptions << QStringLiteral("-o") << dialogOptions[i];
        } else {
            cupsOptions << QStringLiteral("-o") << dialogOptions[i] + QLatin1Char('=') + dialogOptions[i + 1];
        }
    }

    return cupsOptions;
}

868
QStringList PrintPortal::optionMedia(const QPrinter *printer)
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
{
    if (!qt_keyForPageSizeId(printer->pageLayout().pageSize().id()).isEmpty() &&
            !mediaPaperSource(printer).isEmpty()) {
        return QStringList(QStringLiteral("-o")) <<
               QStringLiteral("media=%1,%2").arg(qt_keyForPageSizeId(printer->pageLayout().pageSize().id()), mediaPaperSource(printer));
    }

    if (!qt_keyForPageSizeId(printer->pageLayout().pageSize().id()).isEmpty()) {
        return QStringList(QStringLiteral("-o")) <<
               QStringLiteral("media=%1").arg(qt_keyForPageSizeId(printer->pageLayout().pageSize().id()));
    }

    if (!mediaPaperSource(printer).isEmpty()) {
        return QStringList(QStringLiteral("-o")) <<
               QStringLiteral("media=%1").arg(mediaPaperSource(printer));
    }

    return QStringList();
}

889
QStringList PrintPortal::pages(const QPrinter *printer, bool useCupsOptions, const QString &version)
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
{
    if (printer->printRange() == QPrinter::PageRange) {
        if (version == QLatin1String("lp")) {
            return QStringList(QStringLiteral("-P")) << QStringLiteral("%1-%2").arg(printer->fromPage())
                   .arg(printer->toPage());
        }

        if (version.startsWith(QLatin1String("lpr")) && useCupsOptions) {
            return QStringList(QStringLiteral("-o")) << QStringLiteral("page-ranges=%1-%2").arg(printer->fromPage())
                   .arg(printer->toPage());
        }
    }

    return QStringList(); // AllPages
}

906
QStringList PrintPortal::cupsOptions(const QPrinter *printer, QPrinter::Orientation documentOrientation)
907
908
909
{
    QStringList optionList;

910
911
912
    // if (!optionMedia(printer).isEmpty()) {
    //     optionList << optionMedia(printer);
    // }
913

914
915
916
    // if (!optionOrientation(printer, documentOrientation).isEmpty()) {
    //     optionList << optionOrientation(printer, documentOrientation);
    // }
917
918
919
920
921
922
923
924
925
926
927
928
929

    if (!optionDoubleSidedPrinting(printer).isEmpty()) {
        optionList << optionDoubleSidedPrinting(printer);
    }

    if (!optionPageOrder(printer).isEmpty()) {
        optionList << optionPageOrder(printer);
    }

    if (!optionCollateCopies(printer).isEmpty()) {
        optionList << optionCollateCopies(printer);
    }

930
931
932
    // if (!optionPageMargins(printer).isEmpty()) {
    //     optionList << optionPageMargins(printer);
    // }
933
934
935
936
937
938

    optionList << optionCupsProperties(printer);

    return optionList;
}

939
QStringList PrintPortal::printArguments(const QPrinter *printer, bool useCupsOptions,
940
941
942
943
944
945
946
947
                                  const QString &version, QPrinter::Orientation documentOrientation)
{
    QStringList argList;

    if (!destination(printer, version).isEmpty()) {
        argList << destination(printer, version);
    }

948
949
950
    // if (!copies(printer, version).isEmpty()) {
    //     argList << copies(printer, version);
    // }
951
952
953
954
955

    if (!jobname(printer, version).isEmpty()) {
        argList << jobname(printer, version);
    }

956
957
958
959
    // if (!pages(printer, useCupsOptions, version).isEmpty()) {
    //     argList << pages(printer, useCupsOptions, version);
    // }

960
961
962
963
964
965
966
967
968
969
970
    if (useCupsOptions && !cupsOptions(printer, documentOrientation).isEmpty()) {
        argList << cupsOptions(printer, documentOrientation);
    }

    if (version == QLatin1String("lp")) {
        argList << QStringLiteral("--");
    }

    return argList;
}

971
bool PrintPortal::cupsAvailable()
972
973
974
975
976
977
978
979
980
981
{
    // Ideally we would have access to the private Qt method
    // QCUPSSupport::cupsAvailable() to do this as it is very complex routine.
    // However, if CUPS is available then QPrinter::numCopies() will always return 1
    // whereas if CUPS is not available it will return the real number of copies.
    // This behaviour is guaranteed never to change, so we can use it as a reliable substitute.
    QPrinter testPrinter;
    testPrinter.setNumCopies(2);
    return (testPrinter.numCopies() == 1);
}