summaryrefslogtreecommitdiffstats
path: root/src/gui/dialogs/qprintdialog_unix.cpp
blob: bb9b9306fd20029d49732a39dcff6c74829b0ab5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
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
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qplatformdefs.h"

#ifndef QT_NO_PRINTDIALOG

#include "private/qabstractprintdialog_p.h"
#include <QtGui/qmessagebox.h>
#include "qprintdialog.h"
#include "qfiledialog.h"
#include <QtCore/qdir.h>
#include <QtGui/qevent.h>
#include <QtGui/qfilesystemmodel.h>
#include <QtGui/qstyleditemdelegate.h>
#include <QtGui/qprinter.h>

#include <QtGui/qdialogbuttonbox.h>

#include "qfscompleter_p.h"
#include "ui_qprintpropertieswidget.h"
#include "ui_qprintsettingsoutput.h"
#include "ui_qprintwidget.h"

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
#  include <private/qcups_p.h>
#  include <cups/cups.h>
#  include <private/qpdf_p.h>
#else
#  include <QtCore/qlibrary.h>
#endif

#include <private/qprinterinfo_unix_p.h>

QT_BEGIN_NAMESPACE

class QOptionTreeItem;
class QPPDOptionsModel;

class QPrintPropertiesDialog : public QDialog
{
    Q_OBJECT
public:
    QPrintPropertiesDialog(QAbstractPrintDialog *parent = 0);
    ~QPrintPropertiesDialog();

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    void setCups(QCUPSSupport *cups) { m_cups = cups; }
    void addItemToOptions(QOptionTreeItem *parent, QList<const ppd_option_t*>& options, QList<const char*>& markedOptions) const;
#endif

    void selectPrinter();
    void selectPdfPsPrinter(const QPrinter *p);

    /// copy printer properties to the widget
    void applyPrinterProperties(QPrinter *p);
    void setupPrinter() const;

protected:
    void showEvent(QShowEvent* event);

private:
    Ui::QPrintPropertiesWidget widget;
    QDialogButtonBox *m_buttons;
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    QCUPSSupport *m_cups;
    QPPDOptionsModel *m_cupsOptionsModel;
#endif
};

class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
{
    Q_DECLARE_PUBLIC(QPrintDialog)
    Q_DECLARE_TR_FUNCTIONS(QPrintDialog)
public:
    QPrintDialogPrivate();
    ~QPrintDialogPrivate();

    void init();
    /// copy printer properties to the widget
    void applyPrinterProperties(QPrinter *p);

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    void selectPrinter(QCUPSSupport *cups);
#endif

    void _q_chbPrintLastFirstToggled(bool);
#ifndef QT_NO_MESSAGEBOX
    void _q_checkFields();
#endif
    void _q_collapseOrExpandDialog();

    void setupPrinter();
    void updateWidgets();

    virtual void setTabs(const QList<QWidget*> &tabs);

    Ui::QPrintSettingsOutput options;
    QUnixPrintWidget *top;
    QWidget *bottom;
    QDialogButtonBox *buttons;
    QPushButton *collapseButton;
};

#if defined (Q_OS_UNIX)
class QUnixPrintWidgetPrivate
{
public:
    QUnixPrintWidgetPrivate(QUnixPrintWidget *q);
    ~QUnixPrintWidgetPrivate();

    /// copy printer properties to the widget
    void applyPrinterProperties(QPrinter *p);
    bool checkFields();
    void setupPrinter();
    void setOptionsPane(QPrintDialogPrivate *pane);
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    void setCupsProperties();
#endif

// slots
    void _q_printerChanged(int index);
    void _q_btnPropertiesClicked();
    void _q_btnBrowseClicked();

    QUnixPrintWidget * const parent;
    QPrintPropertiesDialog *propertiesDialog;
    Ui::QPrintWidget widget;
    QAbstractPrintDialog * q;
    QPrinter *printer;
    QList<QPrinterDescription> lprPrinters;
    void updateWidget();

private:
    QPrintDialogPrivate *optionsPane;
    bool filePrintersAdded;
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    QCUPSSupport* cups;
    int cupsPrinterCount;
    const cups_dest_t* cupsPrinters;
    const ppd_file_t* cupsPPD;
#endif
};
#endif

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
class QOptionTreeItem
{
public:
    enum ItemType { Root, Group, Option, Choice };

    QOptionTreeItem(ItemType t, int i, const void* p, const char* desc, QOptionTreeItem* pi)
        : type(t),
          index(i),
          ptr(p),
          description(desc),
          selected(-1),
          selDescription(0),
          parentItem(pi) {}

    ~QOptionTreeItem() {
        while (!childItems.isEmpty())
            delete childItems.takeFirst();
    }

    ItemType type;
    int index;
    const void* ptr;
    const char* description;
    int selected;
    const char* selDescription;
    QOptionTreeItem* parentItem;
    QList<QOptionTreeItem*> childItems;
};

class QPPDOptionsModel : public QAbstractItemModel
{
    friend class QPPDOptionsEditor;
public:
    QPPDOptionsModel(QCUPSSupport *cups, QObject *parent = 0);
    ~QPPDOptionsModel();

    int columnCount(const QModelIndex& parent = QModelIndex()) const;
    int rowCount(const QModelIndex& parent = QModelIndex()) const;
    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const;
    QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex& index) const;
    Qt::ItemFlags flags(const QModelIndex& index) const;
    QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;

    QOptionTreeItem* rootItem;
    QCUPSSupport *cups;
    const ppd_file_t* ppd;
    void parseItems();
    void parseGroups(QOptionTreeItem* parent);
    void parseOptions(QOptionTreeItem* parent);
    void parseChoices(QOptionTreeItem* parent);
};

class QPPDOptionsEditor : public QStyledItemDelegate
{
    Q_OBJECT
public:
    QPPDOptionsEditor(QObject* parent = 0) : QStyledItemDelegate(parent) {}
    ~QPPDOptionsEditor() {}

    QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
    void setEditorData(QWidget* editor, const QModelIndex& index) const;
    void setModelData( QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const;

private slots:
    void cbChanged(int index);

};

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

QPrintPropertiesDialog::QPrintPropertiesDialog(QAbstractPrintDialog *parent)
    : QDialog(parent)
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    , m_cups(0), m_cupsOptionsModel(0)
#endif
{
    QVBoxLayout *lay = new QVBoxLayout(this);
    this->setLayout(lay);
    QWidget *content = new QWidget(this);
    widget.setupUi(content);
    m_buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this);
    lay->addWidget(content);
    lay->addWidget(m_buttons);

    connect(m_buttons->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(accept()));
    connect(m_buttons->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(reject()));
}

QPrintPropertiesDialog::~QPrintPropertiesDialog()
{
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    delete m_cupsOptionsModel;
#else
    delete widget.cupsPropertiesPage;
#endif
}

void QPrintPropertiesDialog::applyPrinterProperties(QPrinter *p)
{
    widget.pageSetup->setPrinter(p);
}

void QPrintPropertiesDialog::setupPrinter() const
{
    widget.pageSetup->setupPrinter();

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    QPPDOptionsModel* model = static_cast<QPPDOptionsModel*>(widget.treeView->model());
    if (model) {
        QOptionTreeItem* rootItem = model->rootItem;
        QList<const ppd_option_t*> options;
        QList<const char*> markedOptions;

        addItemToOptions(rootItem, options, markedOptions);
        model->cups->saveOptions(options, markedOptions);
    }
#endif
}

void QPrintPropertiesDialog::selectPrinter()
{
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    widget.pageSetup->selectPrinter(m_cups);
    widget.treeView->setModel(0);
    if (m_cups && QCUPSSupport::isAvailable()) {

        if (m_cupsOptionsModel == 0) {
            m_cupsOptionsModel = new QPPDOptionsModel(m_cups);

            widget.treeView->setItemDelegate(new QPPDOptionsEditor(this));
        } else {
            // update the model
            m_cupsOptionsModel->parseItems();
        }

        if (m_cupsOptionsModel->rowCount() > 0) {
            widget.treeView->setModel(m_cupsOptionsModel);

            for (int i = 0; i < m_cupsOptionsModel->rowCount(); ++i)
                widget.treeView->expand(m_cupsOptionsModel->index(i,0));

            widget.tabs->setTabEnabled(1, true); // enable the advanced tab
        } else {
            widget.tabs->setTabEnabled(1, false);
        }

    } else
#endif
    {
        widget.cupsPropertiesPage->setEnabled(false);
        widget.pageSetup->selectPrinter(0);
    }
}

void QPrintPropertiesDialog::selectPdfPsPrinter(const QPrinter *p)
{
    widget.treeView->setModel(0);
    widget.pageSetup->selectPdfPsPrinter(p);
    widget.tabs->setTabEnabled(1, false); // disable the advanced tab
}

void QPrintPropertiesDialog::showEvent(QShowEvent* event)
{
    widget.treeView->resizeColumnToContents(0);
    event->accept();
}

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
void QPrintPropertiesDialog::addItemToOptions(QOptionTreeItem *parent, QList<const ppd_option_t*>& options, QList<const char*>& markedOptions) const
{
    for (int i = 0; i < parent->childItems.count(); ++i) {
        QOptionTreeItem *itm = parent->childItems.at(i);
        if (itm->type == QOptionTreeItem::Option) {
            const ppd_option_t* opt = reinterpret_cast<const ppd_option_t*>(itm->ptr);
            options << opt;
            if (qstrcmp(opt->defchoice, opt->choices[itm->selected].choice) != 0) {
                markedOptions << opt->keyword << opt->choices[itm->selected].choice;
            }
        } else {
            addItemToOptions(itm, options, markedOptions);
        }
    }
}
#endif

QPrintDialogPrivate::QPrintDialogPrivate()
    : top(0), bottom(0), buttons(0), collapseButton(0)
{
}

QPrintDialogPrivate::~QPrintDialogPrivate()
{
}

void QPrintDialogPrivate::init()
{
    Q_Q(QPrintDialog);

    top = new QUnixPrintWidget(0, q);
    bottom = new QWidget(q);
    options.setupUi(bottom);
    options.color->setIconSize(QSize(32, 32));
    options.color->setIcon(QIcon(QLatin1String(":/trolltech/dialogs/qprintdialog/images/status-color.png")));
    options.grayscale->setIconSize(QSize(32, 32));
    options.grayscale->setIcon(QIcon(QLatin1String(":/trolltech/dialogs/qprintdialog/images/status-gray-scale.png")));
    top->d->setOptionsPane(this);

    buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, q);
    collapseButton = new QPushButton(QPrintDialog::tr("&Options >>"), buttons);
    buttons->addButton(collapseButton, QDialogButtonBox::ResetRole);
    bottom->setVisible(false);

    QPushButton *printButton = buttons->button(QDialogButtonBox::Ok);
    printButton->setText(QPrintDialog::tr("&Print"));
    printButton->setDefault(true);

    QVBoxLayout *lay = new QVBoxLayout(q);
    q->setLayout(lay);
    lay->addWidget(top);
    lay->addWidget(bottom);
    lay->addWidget(buttons);

    QPrinter* p = q->printer();

    applyPrinterProperties(p);

#ifdef QT_NO_MESSAGEBOX
    QObject::connect(buttons, SIGNAL(accepted()), q, SLOT(accept()));
#else
    QObject::connect(buttons, SIGNAL(accepted()), q, SLOT(_q_checkFields()));
#endif
    QObject::connect(buttons, SIGNAL(rejected()), q, SLOT(reject()));

    QObject::connect(options.reverse, SIGNAL(toggled(bool)),
                     q, SLOT(_q_chbPrintLastFirstToggled(bool)));

    QObject::connect(collapseButton, SIGNAL(released()), q, SLOT(_q_collapseOrExpandDialog()));
}

void QPrintDialogPrivate::applyPrinterProperties(QPrinter *p)
{
    if (p->colorMode() == QPrinter::Color)
        options.color->setChecked(true);
    else
        options.grayscale->setChecked(true);

    switch(p->duplex()) {
    case QPrinter::DuplexNone:
        options.noDuplex->setChecked(true); break;
    case QPrinter::DuplexLongSide:
    case QPrinter::DuplexAuto:
        options.duplexLong->setChecked(true); break;
    case QPrinter::DuplexShortSide:
        options.duplexShort->setChecked(true); break;
    }
    options.copies->setValue(p->copyCount());
    options.collate->setChecked(p->collateCopies());
    options.reverse->setChecked(p->pageOrder() == QPrinter::LastPageFirst);
    top->d->applyPrinterProperties(p);
}

void QPrintDialogPrivate::_q_chbPrintLastFirstToggled(bool checked)
{
    Q_Q(QPrintDialog);
    if (checked)
        q->printer()->setPageOrder(QPrinter::LastPageFirst);
    else
        q->printer()->setPageOrder(QPrinter::FirstPageFirst);
}

void QPrintDialogPrivate::_q_collapseOrExpandDialog()
{
    int collapseHeight = 0;
    Q_Q(QPrintDialog);
    QWidget *widgetToHide = bottom;
    if (widgetToHide->isVisible()) {
        collapseButton->setText(QPrintDialog::tr("&Options >>"));
        collapseHeight = widgetToHide->y() + widgetToHide->height() - (top->y() + top->height());
    }
    else
        collapseButton->setText(QPrintDialog::tr("&Options <<"));
    widgetToHide->setVisible(! widgetToHide->isVisible());
    if (! widgetToHide->isVisible()) { // make it shrink
        q->layout()->activate();
        q->resize( QSize(q->width(), q->height() - collapseHeight) );
    }
}

#ifndef QT_NO_MESSAGEBOX
void QPrintDialogPrivate::_q_checkFields()
{
    Q_Q(QPrintDialog);
    if (top->d->checkFields())
        q->accept();
}
#endif // QT_NO_MESSAGEBOX

void QPrintDialogPrivate::setupPrinter()
{
    Q_Q(QPrintDialog);
    QPrinter* p = q->printer();

    if (options.duplex->isEnabled()) {
        if (options.noDuplex->isChecked())
            p->setDuplex(QPrinter::DuplexNone);
        else if (options.duplexLong->isChecked())
            p->setDuplex(QPrinter::DuplexLongSide);
        else
            p->setDuplex(QPrinter::DuplexShortSide);
    }

    p->setColorMode( options.color->isChecked() ? QPrinter::Color : QPrinter::GrayScale );

    // print range
    if (options.printAll->isChecked()) {
        p->setPrintRange(QPrinter::AllPages);
        p->setFromTo(0,0);
    } else if (options.printSelection->isChecked()) {
        p->setPrintRange(QPrinter::Selection);
        p->setFromTo(0,0);
    } else if (options.printCurrentPage->isChecked()) {
        p->setPrintRange(QPrinter::CurrentPage);
        p->setFromTo(0,0);
    } else if (options.printRange->isChecked()) {
        p->setPrintRange(QPrinter::PageRange);
        p->setFromTo(options.from->value(), qMax(options.from->value(), options.to->value()));
    }

    // copies
    p->setCopyCount(options.copies->value());
    p->setCollateCopies(options.collate->isChecked());

    top->d->setupPrinter();
}

void QPrintDialogPrivate::updateWidgets()
{
    Q_Q(QPrintDialog);
    options.gbPrintRange->setVisible(q->isOptionEnabled(QPrintDialog::PrintPageRange) ||
                                     q->isOptionEnabled(QPrintDialog::PrintSelection) ||
                                     q->isOptionEnabled(QPrintDialog::PrintCurrentPage));

    options.printRange->setEnabled(q->isOptionEnabled(QPrintDialog::PrintPageRange));
    options.printSelection->setVisible(q->isOptionEnabled(QPrintDialog::PrintSelection));
    options.printCurrentPage->setVisible(q->isOptionEnabled(QPrintDialog::PrintCurrentPage));
    options.collate->setVisible(q->isOptionEnabled(QPrintDialog::PrintCollateCopies));

    switch (q->printRange()) {
    case QPrintDialog::AllPages:
        options.printAll->setChecked(true);
        break;
    case QPrintDialog::Selection:
        options.printSelection->setChecked(true);
        break;
    case QPrintDialog::PageRange:
        options.printRange->setChecked(true);
        break;
    case QPrintDialog::CurrentPage:
        if (q->isOptionEnabled(QPrintDialog::PrintCurrentPage))
            options.printCurrentPage->setChecked(true);
        break;
    default:
        break;
    }
    const int minPage = qMax(1, qMin(q->minPage() , q->maxPage()));
    const int maxPage = qMax(1, q->maxPage() == INT_MAX ? 9999 : q->maxPage());

    options.from->setMinimum(minPage);
    options.to->setMinimum(minPage);
    options.from->setMaximum(maxPage);
    options.to->setMaximum(maxPage);

    options.from->setValue(q->fromPage());
    options.to->setValue(q->toPage());
    top->d->updateWidget();
}

void QPrintDialogPrivate::setTabs(const QList<QWidget*> &tabWidgets)
{
    while(options.tabs->count() > 2)
        delete options.tabs->widget(2);

    QList<QWidget*>::ConstIterator iter = tabWidgets.begin();
    while(iter != tabWidgets.constEnd()) {
        QWidget *tab = *iter;
        options.tabs->addTab(tab, tab->windowTitle());
        ++iter;
    }
}

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
void QPrintDialogPrivate::selectPrinter(QCUPSSupport *cups)
{
    options.duplex->setEnabled(cups && cups->ppdOption("Duplex"));
}
#endif

////////////////////////////////////////////////////////////////////////////////

QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
    : QAbstractPrintDialog(*(new QPrintDialogPrivate), printer, parent)
{
    Q_D(QPrintDialog);
    d->init();
}

/*!
    Constructs a print dialog with the given \a parent.
*/
QPrintDialog::QPrintDialog(QWidget *parent)
    : QAbstractPrintDialog(*(new QPrintDialogPrivate), 0, parent)
{
    Q_D(QPrintDialog);
    d->init();
}

QPrintDialog::~QPrintDialog()
{
}

void QPrintDialog::setVisible(bool visible)
{
    Q_D(QPrintDialog);

    if (visible)
        d->updateWidgets();

    QAbstractPrintDialog::setVisible(visible);
}

int QPrintDialog::exec()
{
    return QDialog::exec();
}

void QPrintDialog::accept()
{
    Q_D(QPrintDialog);
    d->setupPrinter();
    QDialog::accept();
}

#ifdef QT3_SUPPORT
QPrinter *QPrintDialog::printer() const
{
    Q_D(const QPrintDialog);
    return d->printer;
}

void QPrintDialog::setPrinter(QPrinter *printer, bool pickupSettings)
{
    if (!printer)
        return;

    Q_D(QPrintDialog);
    d->printer = printer;

    if (pickupSettings)
        d->applyPrinterProperties(printer);
}

void QPrintDialog::addButton(QPushButton *button)
{
    Q_D(QPrintDialog);
    d->buttons->addButton(button, QDialogButtonBox::HelpRole);
}
#endif // QT3_SUPPORT

#if defined (Q_OS_UNIX)

/*! \internal
*/
QUnixPrintWidgetPrivate::QUnixPrintWidgetPrivate(QUnixPrintWidget *p)
    : parent(p), propertiesDialog(0), printer(0), optionsPane(0), filePrintersAdded(false)
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    , cups(0), cupsPrinterCount(0), cupsPrinters(0), cupsPPD(0)
#endif
{
    q = 0;
    if (parent)
        q = qobject_cast<QAbstractPrintDialog*> (parent->parent());

    widget.setupUi(parent);

    int currentPrinterIndex = 0;
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    cups = new QCUPSSupport;
    if (QCUPSSupport::isAvailable()) {
        cupsPPD = cups->currentPPD();
        cupsPrinterCount = cups->availablePrintersCount();
        cupsPrinters = cups->availablePrinters();

        for (int i = 0; i < cupsPrinterCount; ++i) {
            QString printerName(QString::fromLocal8Bit(cupsPrinters[i].name));
            if (cupsPrinters[i].instance)
                printerName += QLatin1Char('/') + QString::fromLocal8Bit(cupsPrinters[i].instance);

            widget.printers->addItem(printerName);
            if (cupsPrinters[i].is_default)
                widget.printers->setCurrentIndex(i);
        }
        // the model depends on valid ppd. so before enabling the
        // properties button we make sure the ppd is in fact valid.
        if (cupsPrinterCount && cups->currentPPD()) {
            widget.properties->setEnabled(true);
        }
        currentPrinterIndex = cups->currentPrinterIndex();
    } else {
#endif
        currentPrinterIndex = qt_getLprPrinters(lprPrinters);
        // populating printer combo
        QList<QPrinterDescription>::const_iterator i = lprPrinters.constBegin();
        for(; i != lprPrinters.constEnd(); ++i)
            widget.printers->addItem((*i).name);
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    }
#endif

#if !defined(QT_NO_FILESYSTEMMODEL) && !defined(QT_NO_COMPLETER)
    QFileSystemModel *fsm = new QFileSystemModel(widget.filename);
    fsm->setRootPath(QDir::homePath());
    widget.filename->setCompleter(new QCompleter(fsm, widget.filename));
#endif
    _q_printerChanged(currentPrinterIndex);

    QObject::connect(widget.printers, SIGNAL(currentIndexChanged(int)),
                     parent, SLOT(_q_printerChanged(int)));
    QObject::connect(widget.fileBrowser, SIGNAL(clicked()), parent, SLOT(_q_btnBrowseClicked()));
    QObject::connect(widget.properties, SIGNAL(clicked()), parent, SLOT(_q_btnPropertiesClicked()));

    // disable features that QPrinter does not yet support.
    widget.preview->setVisible(false);
}

void QUnixPrintWidgetPrivate::updateWidget()
{
    const bool printToFile = q == 0 || q->isOptionEnabled(QPrintDialog::PrintToFile);
    if (printToFile && !filePrintersAdded) {
        if (widget.printers->count())
            widget.printers->insertSeparator(widget.printers->count());
        widget.printers->addItem(QPrintDialog::tr("Print to File (PDF)"));
        widget.printers->addItem(QPrintDialog::tr("Print to File (Postscript)"));
        filePrintersAdded = true;
    }
    if (!printToFile && filePrintersAdded) {
        widget.printers->removeItem(widget.printers->count()-1);
        widget.printers->removeItem(widget.printers->count()-1);
        if (widget.printers->count())
            widget.printers->removeItem(widget.printers->count()-1); // remove separator
        filePrintersAdded = false;
    }
    if (printer && filePrintersAdded && (printer->outputFormat() != QPrinter::NativeFormat
                                         || printer->printerName().isEmpty()))
    {
        if (printer->outputFormat() == QPrinter::PdfFormat)
            widget.printers->setCurrentIndex(widget.printers->count() - 2);
        else if (printer->outputFormat() == QPrinter::PostScriptFormat)
            widget.printers->setCurrentIndex(widget.printers->count() - 1);
        widget.filename->setEnabled(true);
        widget.lOutput->setEnabled(true);
    }

    widget.filename->setVisible(printToFile);
    widget.lOutput->setVisible(printToFile);
    widget.fileBrowser->setVisible(printToFile);

    widget.properties->setVisible(q->isOptionEnabled(QAbstractPrintDialog::PrintShowPageSize));
}

QUnixPrintWidgetPrivate::~QUnixPrintWidgetPrivate()
{
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    delete cups;
#endif
}

void QUnixPrintWidgetPrivate::_q_printerChanged(int index)
{
    if (index < 0)
        return;
    const int printerCount = widget.printers->count();
    widget.filename->setEnabled(false);
    widget.lOutput->setEnabled(false);

    if (filePrintersAdded) {
        Q_ASSERT(index != printerCount - 3); // separator
        if (index > printerCount - 3) { // PDF or postscript
            bool pdfPrinter = (index == printerCount - 2);
            widget.location->setText(QPrintDialog::tr("Local file"));
            widget.type->setText(QPrintDialog::tr("Write %1 file").arg(pdfPrinter ? QString::fromLatin1("PDF")
                                                                       : QString::fromLatin1("PostScript")));
            widget.properties->setEnabled(true);
            widget.filename->setEnabled(true);
            QString filename = widget.filename->text();
            QString suffix = QFileInfo(filename).suffix();
            if (pdfPrinter && suffix == QLatin1String("ps"))
                filename = filename.replace(QLatin1String(".ps"), QLatin1String(".pdf"));
            if (!pdfPrinter && suffix == QLatin1String("pdf"))
                filename = filename.replace(QLatin1String(".pdf"), QLatin1String(".ps"));
            widget.filename->setText(filename);
            widget.lOutput->setEnabled(true);
            if (propertiesDialog)
                propertiesDialog->selectPdfPsPrinter(printer);
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
            if (optionsPane)
                optionsPane->selectPrinter(0);
#endif
            return;
        }
    }

    widget.location->setText(QString());
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    if (QCUPSSupport::isAvailable()) {
        cups->setCurrentPrinter(index);

        const cups_option_t *opt = cups->printerOption(QString::fromLatin1("printer-location"));
        QString location;
        if (opt)
            location = QString::fromLocal8Bit(opt->value);
        widget.location->setText(location);

        cupsPPD = cups->currentPPD();
        // set printer type line
        QString type;
        if (cupsPPD)
            type = QString::fromLocal8Bit(cupsPPD->manufacturer) + QLatin1String(" - ") + QString::fromLocal8Bit(cupsPPD->modelname);
        widget.type->setText(type);
        if (propertiesDialog)
            propertiesDialog->selectPrinter();
        if (optionsPane)
            optionsPane->selectPrinter(cups);
    } else {
        if (optionsPane)
            optionsPane->selectPrinter(0);
#endif
        if (lprPrinters.count() > 0) {
            QString type = lprPrinters.at(index).name + QLatin1Char('@') + lprPrinters.at(index).host;
            if (!lprPrinters.at(index).comment.isEmpty())
            type += QLatin1String(", ") + lprPrinters.at(index).comment;
            widget.type->setText(type);
            if (propertiesDialog)
                propertiesDialog->selectPrinter();
        }
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    }
#endif
}

void QUnixPrintWidgetPrivate::setOptionsPane(QPrintDialogPrivate *pane)
{
    optionsPane = pane;
    if (optionsPane)
        _q_printerChanged(widget.printers->currentIndex());
}

void QUnixPrintWidgetPrivate::_q_btnBrowseClicked()
{
    QString filename = widget.filename->text();
#ifndef QT_NO_FILEDIALOG
    filename = QFileDialog::getSaveFileName(parent, QPrintDialog::tr("Print To File ..."), filename,
                                            QString(), 0, QFileDialog::DontConfirmOverwrite);
#else
    filename.clear();
#endif
    if (!filename.isEmpty()) {
        widget.filename->setText(filename);
        if (filename.endsWith(QString::fromLatin1(".ps"), Qt::CaseInsensitive))
            widget.printers->setCurrentIndex(widget.printers->count() - 1); // the postscript one
        else if (filename.endsWith(QString::fromLatin1(".pdf"), Qt::CaseInsensitive))
            widget.printers->setCurrentIndex(widget.printers->count() - 2); // the pdf one
        else if (widget.printers->currentIndex() != widget.printers->count() - 1) // if ps is not selected, pdf is default
            widget.printers->setCurrentIndex(widget.printers->count() - 2); // the pdf one
    }
}

void QUnixPrintWidgetPrivate::applyPrinterProperties(QPrinter *p)
{
    if (p == 0)
        return;
    printer = p;
    if (p->outputFileName().isEmpty()) {
        QString home = QString::fromLocal8Bit(qgetenv("HOME").constData());
        QString cur = QDir::currentPath();
        if (home.at(home.length()-1) != QLatin1Char('/'))
            home += QLatin1Char('/');
        if (cur.at(cur.length()-1) != QLatin1Char('/'))
            cur += QLatin1Char('/');
        if (cur.left(home.length()) != home)
            cur = home;
#ifdef Q_WS_X11
        if (p->docName().isEmpty()) {
            if (p->outputFormat() == QPrinter::PostScriptFormat)
                cur += QLatin1String("print.ps");
            else
                cur += QLatin1String("print.pdf");
        } else {
            QRegExp re(QString::fromLatin1("(.*)\\.\\S+"));
            if (re.exactMatch(p->docName()))
                cur += re.cap(1);
            else
                cur += p->docName();
            if (p->outputFormat() == QPrinter::PostScriptFormat)
                cur += QLatin1String(".ps");
            else
                cur += QLatin1String(".pdf");
        }
#endif
        widget.filename->setText(cur);
    }
    else
        widget.filename->setText( p->outputFileName() );
    QString printer = p->printerName();
    if (!printer.isEmpty()) {
        for (int i = 0; i < widget.printers->count(); ++i) {
            if (widget.printers->itemText(i) == printer) {
                widget.printers->setCurrentIndex(i);
                break;
            }
        }
    }
    // PDF and PS printers are not added to the dialog yet, we'll handle those cases in QUnixPrintWidgetPrivate::updateWidget

    if (propertiesDialog)
        propertiesDialog->applyPrinterProperties(p);
}

#ifndef QT_NO_MESSAGEBOX
bool QUnixPrintWidgetPrivate::checkFields()
{
    if (widget.filename->isEnabled()) {
        QString file = widget.filename->text();
        QFile f(file);
        QFileInfo fi(f);
        bool exists = fi.exists();
        bool opened = false;
        if (exists && fi.isDir()) {
            QMessageBox::warning(q, q->windowTitle(),
                            QPrintDialog::tr("%1 is a directory.\nPlease choose a different file name.").arg(file));
            return false;
        } else if ((exists && !fi.isWritable()) || !(opened = f.open(QFile::Append))) {
            QMessageBox::warning(q, q->windowTitle(),
                            QPrintDialog::tr("File %1 is not writable.\nPlease choose a different file name.").arg(file));
            return false;
        } else if (exists) {
            int ret = QMessageBox::question(q, q->windowTitle(),
                                            QPrintDialog::tr("%1 already exists.\nDo you want to overwrite it?").arg(file),
                                            QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
            if (ret == QMessageBox::No)
                return false;
        }
        if (opened) {
            f.close();
            if (!exists)
                f.remove();
        }
    }

    // Every test passed. Accept the dialog.
    return true;
}
#endif // QT_NO_MESSAGEBOX

void QUnixPrintWidgetPrivate::_q_btnPropertiesClicked()
{
    if (!propertiesDialog) {
        propertiesDialog = new QPrintPropertiesDialog(q);
        propertiesDialog->setResult(QDialog::Rejected);
    }

    if (propertiesDialog->result() == QDialog::Rejected) {
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
        propertiesDialog->setCups(cups);
#endif
        propertiesDialog->applyPrinterProperties(q->printer());

        if (q->isOptionEnabled(QPrintDialog::PrintToFile)
            && (widget.printers->currentIndex() > widget.printers->count() - 3)) // PDF or postscript
            propertiesDialog->selectPdfPsPrinter(q->printer());
        else
            propertiesDialog->selectPrinter();
    }
    propertiesDialog->exec();
}

#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
void QUnixPrintWidgetPrivate::setCupsProperties()
{
    if (cups && QCUPSSupport::isAvailable() && cups->pageSizes()) {
        QPrintEngine *engine = printer->printEngine();
        const ppd_option_t* pageSizes = cups->pageSizes();
        QByteArray cupsPageSize;
        for (int i = 0; i < pageSizes->num_choices; ++i) {
            if (static_cast<int>(pageSizes->choices[i].marked) == 1)
                cupsPageSize = pageSizes->choices[i].choice;
        }
        engine->setProperty(PPK_CupsStringPageSize, QString::fromLatin1(cupsPageSize));
        engine->setProperty(PPK_CupsOptions, cups->options());

        QRect pageRect = cups->pageRect(cupsPageSize);
        engine->setProperty(PPK_CupsPageRect, pageRect);

        QRect paperRect = cups->paperRect(cupsPageSize);
        engine->setProperty(PPK_CupsPaperRect, paperRect);

        for (int ps = 0; ps < QPrinter::NPaperSize; ++ps) {
            QPdf::PaperSize size = QPdf::paperSize(QPrinter::PaperSize(ps));
            if (size.width == paperRect.width() && size.height == paperRect.height())
                printer->setPaperSize(static_cast<QPrinter::PaperSize>(ps));
        }
    }
}
#endif

void QUnixPrintWidgetPrivate::setupPrinter()
{
    const int printerCount = widget.printers->count();
    const int index = widget.printers->currentIndex();

    if (filePrintersAdded && index > printerCount - 3) { // PDF or postscript
        printer->setPrinterName(QString());
        Q_ASSERT(index != printerCount - 3); // separator
        if (index == printerCount - 2)
            printer->setOutputFormat(QPrinter::PdfFormat);
        else
            printer->setOutputFormat(QPrinter::PostScriptFormat);
        QString path = widget.filename->text();
        if (QDir::isRelativePath(path))
            path = QDir::homePath() + QDir::separator() + path;
        printer->setOutputFileName(path);
    }
    else {
        printer->setPrinterName(widget.printers->currentText());
        printer->setOutputFileName(QString());
    }

    if (propertiesDialog && propertiesDialog->result() == QDialog::Accepted)
        propertiesDialog->setupPrinter();
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)
    if (!propertiesDialog)
        setCupsProperties();
#endif
}


/*! \internal
*/
QUnixPrintWidget::QUnixPrintWidget(QPrinter *printer, QWidget *parent)
    : QWidget(parent), d(new QUnixPrintWidgetPrivate(this))
{
    d->applyPrinterProperties(printer);
}

/*! \internal
*/
QUnixPrintWidget::~QUnixPrintWidget()
{
    delete d;
}

/*! \internal

    Updates the printer with the states held in the QUnixPrintWidget.
*/
void QUnixPrintWidget::updatePrinter()
{
    d->setupPrinter();
}

#endif

////////////////////////////////////////////////////////////////////////////////
#if !defined(QT_NO_CUPS) && !defined(QT_NO_LIBRARY)

QPPDOptionsModel::QPPDOptionsModel(QCUPSSupport *c, QObject *parent)
    : QAbstractItemModel(parent), rootItem(0), cups(c), ppd(c->currentPPD())
{
    parseItems();
}

QPPDOptionsModel::~QPPDOptionsModel()
{
}

int QPPDOptionsModel::columnCount(const QModelIndex&) const
{
    return 2;
}

int QPPDOptionsModel::rowCount(const QModelIndex& parent) const
{
    QOptionTreeItem* itm;
    if (!parent.isValid())
        itm = rootItem;
    else
        itm = reinterpret_cast<QOptionTreeItem*>(parent.internalPointer());

    if (itm->type == QOptionTreeItem::Option)
        return 0;

    return itm->childItems.count();
}

QVariant QPPDOptionsModel::data(const QModelIndex& index, int role) const
{
    switch(role) {
        case Qt::FontRole: {
            QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());
            if (itm && itm->type == QOptionTreeItem::Group){
                QFont font = QApplication::font();
                font.setBold(true);
                return QVariant(font);
            }
            return QVariant();
        }
        break;

        case Qt::DisplayRole: {
            QOptionTreeItem* itm;
            if (!index.isValid())
                itm = rootItem;
            else
                itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());

            if (index.column() == 0)
                return cups->unicodeString(itm->description);
            else if (itm->type == QOptionTreeItem::Option && itm->selected > -1)
                return cups->unicodeString(itm->selDescription);
            else
                return QVariant();
        }
        break;

        default:
            return QVariant();
    }
    if (role != Qt::DisplayRole)
        return QVariant();
}

QModelIndex QPPDOptionsModel::index(int row, int column, const QModelIndex& parent) const
{
    QOptionTreeItem* itm;
    if (!parent.isValid())
        itm = rootItem;
    else
        itm = reinterpret_cast<QOptionTreeItem*>(parent.internalPointer());

    return createIndex(row, column, itm->childItems.at(row));
}


QModelIndex QPPDOptionsModel::parent(const QModelIndex& index) const
{
    if (!index.isValid())
        return QModelIndex();

    QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());

    if (itm->parentItem && itm->parentItem != rootItem)
        return createIndex(itm->parentItem->index, 0, itm->parentItem);
    else
        return QModelIndex();
}

Qt::ItemFlags QPPDOptionsModel::flags(const QModelIndex& index) const
{
    if (!index.isValid() || reinterpret_cast<QOptionTreeItem*>(index.internalPointer())->type == QOptionTreeItem::Group)
        return Qt::ItemIsEnabled;

    if (index.column() == 1)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;

    return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

void QPPDOptionsModel::parseItems()
{
    emit layoutAboutToBeChanged();
    ppd = cups->currentPPD();
    delete rootItem;
    rootItem = new QOptionTreeItem(QOptionTreeItem::Root, 0, ppd, "Root Item", 0);
    parseGroups(rootItem);
    emit layoutChanged();
}

void QPPDOptionsModel::parseGroups(QOptionTreeItem* parent)
{
    if (parent->type == QOptionTreeItem::Root) {

        const ppd_file_t* ppdFile = reinterpret_cast<const ppd_file_t*>(parent->ptr);

        if (ppdFile) {
            for (int i = 0; i < ppdFile->num_groups; ++i) {
                QOptionTreeItem* group = new QOptionTreeItem(QOptionTreeItem::Group, i, &ppdFile->groups[i], ppdFile->groups[i].text, parent);
                parent->childItems.append(group);
                parseGroups(group); // parse possible subgroups
                parseOptions(group); // parse options
            }
        }
    } else if (parent->type == QOptionTreeItem::Group) {

        const ppd_group_t* group = reinterpret_cast<const ppd_group_t*>(parent->ptr);

        if (group) {
            for (int i = 0; i < group->num_subgroups; ++i) {
                QOptionTreeItem* subgroup = new QOptionTreeItem(QOptionTreeItem::Group, i, &group->subgroups[i], group->subgroups[i].text, parent);
                parent->childItems.append(subgroup);
                parseGroups(subgroup); // parse possible subgroups
                parseOptions(subgroup); // parse options
            }
        }
    }
}

void QPPDOptionsModel::parseOptions(QOptionTreeItem* parent)
{
    const ppd_group_t* group = reinterpret_cast<const ppd_group_t*>(parent->ptr);
    for (int i = 0; i < group->num_options; ++i) {
        QOptionTreeItem* opt = new QOptionTreeItem(QOptionTreeItem::Option, i, &group->options[i], group->options[i].text, parent);
        parent->childItems.append(opt);
        parseChoices(opt);
    }
}

void QPPDOptionsModel::parseChoices(QOptionTreeItem* parent)
{
    const ppd_option_t* option = reinterpret_cast<const ppd_option_t*>(parent->ptr);
    bool marked = false;
    for (int i = 0; i < option->num_choices; ++i) {
        QOptionTreeItem* choice = new QOptionTreeItem(QOptionTreeItem::Choice, i, &option->choices[i], option->choices[i].text, parent);
        if (static_cast<int>(option->choices[i].marked) == 1) {
            parent->selected = i;
            parent->selDescription = option->choices[i].text;
            marked = true;
        } else if (!marked && qstrcmp(option->choices[i].choice, option->defchoice) == 0) {
            parent->selected = i;
            parent->selDescription = option->choices[i].text;
        }
        parent->childItems.append(choice);
    }
}

QVariant QPPDOptionsModel::headerData(int section, Qt::Orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    switch(section){
        case 0:
            return QVariant(QApplication::translate("QPPDOptionsModel", "Name"));
        case 1:
            return QVariant(QApplication::translate("QPPDOptionsModel", "Value"));
        default:
            return QVariant();
    }
}

////////////////////////////////////////////////////////////////////////////////

QWidget* QPPDOptionsEditor::createEditor(QWidget* parent, const QStyleOptionViewItem&, const QModelIndex& index) const
{
    if (index.column() == 1 && reinterpret_cast<QOptionTreeItem*>(index.internalPointer())->type == QOptionTreeItem::Option)
        return new QComboBox(parent);
    else
        return 0;
}

void QPPDOptionsEditor::setEditorData(QWidget* editor, const QModelIndex& index) const
{
    if (index.column() != 1)
        return;

    QComboBox* cb = static_cast<QComboBox*>(editor);
    QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());

    if (itm->selected == -1)
        cb->addItem(QString());

    for (int i = 0; i < itm->childItems.count(); ++i)
        cb->addItem(QString::fromLocal8Bit(itm->childItems.at(i)->description));

    if (itm->selected > -1)
        cb->setCurrentIndex(itm->selected);

    connect(cb, SIGNAL(currentIndexChanged(int)), this, SLOT(cbChanged(int)));
}

void QPPDOptionsEditor::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QComboBox* cb = static_cast<QComboBox*>(editor);
    QOptionTreeItem* itm = reinterpret_cast<QOptionTreeItem*>(index.internalPointer());

    if (itm->selected == cb->currentIndex())
        return;

    const ppd_option_t* opt = reinterpret_cast<const ppd_option_t*>(itm->ptr);
    QPPDOptionsModel* m = static_cast<QPPDOptionsModel*>(model);

    if (m->cups->markOption(opt->keyword, opt->choices[cb->currentIndex()].choice) == 0) {
        itm->selected = cb->currentIndex();
        itm->selDescription = reinterpret_cast<const ppd_option_t*>(itm->ptr)->choices[itm->selected].text;
    }
}

void QPPDOptionsEditor::cbChanged(int)
{
/*
    emit commitData(static_cast<QWidget*>(sender()));
*/
}

#endif

QT_END_NAMESPACE

#include "moc_qprintdialog.cpp"
#include "qprintdialog_unix.moc"
#include "qrc_qprintdialog.cpp"

#endif // QT_NO_PRINTDIALOG