Debian Codegraph @

src/qdjviewexporters.cpp

raw
1 //C- -*- C++ -*-
2 //C- -------------------------------------------------------------------
3 //C- DjView4
4 //C- Copyright (c) 2006- Leon Bottou
5 //C-
6 //C- This software is subject to, and may be distributed under, the
7 //C- GNU General Public License, either version 2 of the license,
8 //C- or (at your option) any later version. The license should have
9 //C- accompanied the software or you may obtain a copy of the license
10 //C- from the Free Software Foundation at http://www.fsf.org .
11 //C-
12 //C- This program is distributed in the hope that it will be useful,
13 //C- but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 //C- GNU General Public License for more details.
16 //C- ------------------------------------------------------------------
17
18 #if AUTOCONF
19 # include "config.h"
20 #else
21 # define HAVE_STRING_H 1
22 # define HAVE_SYS_TYPES_H 1
23 # define HAVE_STRERROR 1
24 # ifndef WIN32
25 # define HAVE_SYS_WAIT_H 1
26 # define HAVE_WAITPID 1
27 # define HAVE_UNISTD_H 1
28 # endif
29 #endif
30
31 #include <stddef.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <stdarg.h>
35 #include <errno.h>
36 #include <limits.h>
37 #include <signal.h>
38 #if HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
41 #if HAVE_SYS_WAIT_H
42 # include <sys/wait.h>
43 #endif
44 #if HAVE_STRING_H
45 # include <string.h>
46 #endif
47 #if HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50 #if HAVE_TIFF
51 # include <tiff.h>
52 # include <tiffio.h>
53 # include <tiffconf.h>
54 # include "tiff2pdf.h"
55 #endif
56 #ifdef WIN32
57 # include <io.h>
58 #endif
59
60 #include <QApplication>
61 #include <QCheckBox>
62 #include <QDebug>
63 #include <QDir>
64 #include <QDialog>
65 #include <QFile>
66 #include <QFileDialog>
67 #include <QFileInfo>
68 #include <QImageWriter>
69 #include <QList>
70 #include <QMap>
71 #include <QMessageBox>
72 #include <QObject>
73 #include <QPointer>
74 #include <QPrinter>
75 #include <QPrintDialog>
76 #include <QPrintEngine>
77 #include <QRegExp>
78 #include <QSettings>
79 #include <QSpinBox>
80 #include <QString>
81 #include <QTemporaryFile>
82 #include <QTimer>
83
84 #include <libdjvu/miniexp.h>
85 #include <libdjvu/ddjvuapi.h>
86
87 #include "qdjview.h"
88 #include "qdjviewprefs.h"
89 #include "qdjviewdialogs.h"
90 #include "qdjviewexporters.h"
91 #include "qdjvuwidget.h"
92 #include "qdjvu.h"
93
94 #ifdef WIN32
95 # define wdup(fh) _dup(fh)
96 #else
97 # define wdup(fh) (fh)
98 #endif
99
100 // ----------------------------------------
101 // FACTORY
102
103
104 typedef QDjViewExporter* (*exporter_creator_t)(QDialog*,QDjView*,QString);
105
106 static QStringList exporterNames;
107 static QMap<QString,QStringList> exporterInfo;
108 static QMap<QString,exporter_creator_t> exporterCreators;
109
110
111 static void
112 addExporterData(QString name, QString suffix,
113 QString lname, QString filter,
114 exporter_creator_t creator)
115 {
116 QStringList info;
117 info << name << suffix << lname << filter;
118 exporterNames << name;
119 exporterInfo[name] = info;
120 exporterCreators[name] = creator;
121 }
122
123
124 static void createExporterData();
125
126
127 QDjViewExporter *
128 QDjViewExporter::create(QDialog *dialog, QDjView *djview, QString name)
129 {
130 if (exporterNames.isEmpty())
131 createExporterData();
132 if (exporterCreators.contains(name))
133 return (*exporterCreators[name])(dialog, djview, name);
134 return 0;
135 }
136
137 QStringList
138 QDjViewExporter::names()
139 {
140 if (exporterNames.isEmpty())
141 createExporterData();
142 return exporterNames;
143 }
144
145 QStringList
146 QDjViewExporter::info(QString name)
147 {
148 if (exporterNames.isEmpty())
149 createExporterData();
150 if (exporterInfo.contains(name))
151 return exporterInfo[name];
152 return QStringList();
153 }
154
155
156
157
158
159 // ----------------------------------------
160 // QDJVIEWEXPORTER
161
162
163
164 QDjViewExporter::~QDjViewExporter()
165 {
166 }
167
168
169 bool
170 QDjViewExporter::exportOnePageOnly()
171 {
172 return false;
173 }
174
175
176 void
177 QDjViewExporter::resetProperties()
178 {
179 // reset all properties to default values
180 }
181
182
183 void
184 QDjViewExporter::loadProperties(QString)
185 {
186 // fill properties from settings keyed by string
187 }
188
189
190 void
191 QDjViewExporter::saveProperties(QString)
192 {
193 // save properties into settings keyed by string
194 }
195
196
197 bool
198 QDjViewExporter::loadPrintSetup(QPrinter*, QPrintDialog*)
199 {
200 // fill properties using printer and print dialog data
201 return false;
202 }
203
204
205 bool
206 QDjViewExporter::savePrintSetup(QPrinter*)
207 {
208 // save properties into printer settings
209 return false;
210 }
211
212
213 int
214 QDjViewExporter::propertyPages()
215 {
216 return 0;
217 }
218
219
220 QWidget*
221 QDjViewExporter::propertyPage(int)
222 {
223 return 0;
224 }
225
226
227 void
228 QDjViewExporter::setFromTo(int fp, int tp)
229 {
230 fromPage = fp;
231 toPage = tp;
232 }
233
234
235 void
236 QDjViewExporter::setErrorCaption(QString caption)
237 {
238 errorCaption = caption;
239 }
240
241
242 ddjvu_status_t
243 QDjViewExporter::status()
244 {
245 return DDJVU_JOB_NOTSTARTED;
246 }
247
248
249 QString
250 QDjViewExporter::name()
251 {
252 return exporterName;
253 }
254
255
256 bool
257 QDjViewExporter::print(QPrinter *)
258 {
259 qWarning("QDjViewExporter does not support printing.");
260 return false;
261 }
262
263
264 void
265 QDjViewExporter::stop()
266 {
267 }
268
269
270 void
271 QDjViewExporter::error(QString message, QString filename, int lineno)
272 {
273 if (! errorDialog)
274 {
275 errorDialog = new QDjViewErrorDialog(parent);
276 errorDialog->prepare(QMessageBox::Critical, errorCaption);
277 connect(errorDialog, SIGNAL(closing()), parent, SLOT(reject()));
278 errorDialog->setWindowModality(Qt::WindowModal);
279 }
280 errorDialog->error(message, filename, lineno);
281 errorDialog->show();
282 }
283
284
285 QDjViewExporter::QDjViewExporter(QDialog *parent, QDjView *djview, QString name)
286 : parent(parent), djview(djview),
287 errorDialog(0),
288 exporterName(name),
289 fromPage(0),
290 toPage(-1)
291 {
292 }
293
294
295
296
297
298
299 // ----------------------------------------
300 // QDJVIEWDJVUEXPORTER
301
302
303
304
305 class QDjViewDjVuExporter : public QDjViewExporter
306 {
307 Q_OBJECT
308 public:
309 static QDjViewExporter *create(QDialog*, QDjView*, QString);
310 static void setup();
311 public:
312 ~QDjViewDjVuExporter();
313 QDjViewDjVuExporter(QDialog *parent, QDjView *djview,
314 QString name, bool indirect);
315 virtual bool save(QString fileName);
316 virtual void stop();
317 virtual ddjvu_status_t status();
318 protected:
319 QFile file;
320 QDjVuJob *job;
321 FILE *output;
322 bool indirect;
323 bool failed;
324 };
325
326
327 QDjViewExporter*
328 QDjViewDjVuExporter::create(QDialog *parent, QDjView *djview, QString name)
329 {
330 if (name == "DJVU/BUNDLED")
331 return new QDjViewDjVuExporter(parent, djview, name, false);
332 if (name == "DJVU/INDIRECT")
333 return new QDjViewDjVuExporter(parent, djview, name, true);
334 return 0;
335 }
336
337
338 void
339 QDjViewDjVuExporter::setup()
340 {
341 addExporterData("DJVU/BUNDLED", "djvu",
342 tr("DjVu Bundled Document"),
343 tr("DjVu Files (*.djvu *.djv)"),
344 QDjViewDjVuExporter::create);
345 addExporterData("DJVU/INDIRECT", "djvu",
346 tr("DjVu Indirect Document"),
347 tr("DjVu Files (*.djvu *.djv)"),
348 QDjViewDjVuExporter::create);
349 }
350
351
352 QDjViewDjVuExporter::QDjViewDjVuExporter(QDialog *parent, QDjView *djview,
353 QString name, bool indirect)
354 : QDjViewExporter(parent, djview, name),
355 job(0),
356 output(0),
357 indirect(indirect),
358 failed(false)
359 {
360 }
361
362
363 QDjViewDjVuExporter::~QDjViewDjVuExporter()
364 {
365 QIODevice::OpenMode mode = file.openMode();
366 ddjvu_status_t st = status();
367 if (st == DDJVU_JOB_STARTED)
368 if (job)
369 ddjvu_job_stop(*job);
370 if (output)
371 ::fclose(output);
372 output = 0;
373 if (file.openMode())
374 file.close();
375 if (st != DDJVU_JOB_OK)
376 if (mode & (QIODevice::WriteOnly|QIODevice::Append))
377 file.remove();
378 if (djview)
379 ddjvu_cache_clear(djview->getDjVuContext());
380 }
381
382
383 bool
384 QDjViewDjVuExporter::save(QString fname)
385 {
386 QDjVuDocument *document = djview->getDocument();
387 int pagenum = djview->pageNum();
388 if (output || document==0 || pagenum <= 0 || fname.isEmpty())
389 return false;
390 QFileInfo info(fname);
391 QDir::Filters filters = QDir::AllEntries|QDir::NoDotAndDotDot;
392 if (indirect && !info.dir().entryList(filters).isEmpty() &&
393 QMessageBox::question(parent,
394 tr("Question - DjView", "dialog caption"),
395 tr("<html> This file belongs to a non empty "
396 "directory. Saving an indirect document "
397 "creates many files in this directory. "
398 "Do you want to continue and risk "
399 "overwriting files in this directory?"
400 "</html>"),
401 tr("Con&tinue"),
402 tr("&Cancel") ) )
403 return false;
404 toPage = qBound(0, toPage, pagenum-1);
405 fromPage = qBound(0, fromPage, pagenum-1);
406 QByteArray pagespec;
407 if (fromPage == toPage && pagenum > 1)
408 pagespec.append(QString("--pages=%1").arg(fromPage+1).toLocal8Bit());
409 else if (fromPage != 0 || toPage != pagenum - 1)
410 pagespec.append(QString("--pages=%1-%2").arg(fromPage+1).arg(toPage+1).toLocal8Bit());
411 QByteArray namespec;
412 if (indirect)
413 namespec = "--indirect=" + fname.toUtf8();
414
415 int argc = 0;
416 const char *argv[2];
417 if (! namespec.isEmpty())
418 argv[argc++] = namespec.data();
419 if (! pagespec.isEmpty())
420 argv[argc++] = pagespec.data();
421
422 file.setFileName(fname);
423 file.remove();
424 if (file.open(QIODevice::WriteOnly))
425 output = ::fdopen(wdup(file.handle()), "wb");
426 if (! output)
427 {
428 failed = true;
429 QString message = tr("Unknown error.");
430 if (! file.errorString().isEmpty())
431 message = tr("System error: %1.").arg(file.errorString());
432 error(message, __FILE__, __LINE__);
433 return false;
434 }
435 ddjvu_job_t *pjob;
436 pjob = ddjvu_document_save(*document, output, argc, argv);
437 if (! pjob)
438 {
439 failed = true;
440 // error messages went to the document
441 connect(document, SIGNAL(error(QString,QString,int)),
442 this, SLOT(error(QString,QString,int)) );
443 qApp->sendEvent(&djview->getDjVuContext(), new QEvent(QEvent::User));
444 disconnect(document, 0, this, 0);
445 // main error message
446 QString message = tr("Save job creation failed!");
447 error(message, __FILE__, __LINE__);
448 return false;
449 }
450 job = new QDjVuJob(pjob, this);
451 connect(job, SIGNAL(error(QString,QString,int)),
452 this, SLOT(error(QString,QString,int)) );
453 connect(job, SIGNAL(progress(int)),
454 this, SIGNAL(progress(int)) );
455 emit progress(0);
456 return true;
457 }
458
459
460 void
461 QDjViewDjVuExporter::stop()
462 {
463 if (job && status() == DDJVU_JOB_STARTED)
464 ddjvu_job_stop(*job);
465 }
466
467
468 ddjvu_status_t
469 QDjViewDjVuExporter::status()
470 {
471 if (job)
472 return ddjvu_job_status(*job);
473 else if (failed)
474 return DDJVU_JOB_FAILED;
475 else
476 return DDJVU_JOB_NOTSTARTED;
477 }
478
479
480
481
482
483 // ----------------------------------------
484 // QDJVIEWPSEXPORTER
485
486
487 #include "ui_qdjviewexportps1.h"
488 #include "ui_qdjviewexportps2.h"
489 #include "ui_qdjviewexportps3.h"
490
491
492 class QDjViewPSExporter : public QDjViewExporter
493 {
494 Q_OBJECT
495 public:
496 static QDjViewExporter *create(QDialog*, QDjView*, QString);
497 static void setup();
498 public:
499 ~QDjViewPSExporter();
500 QDjViewPSExporter(QDialog *parent, QDjView *djview,
501 QString name, bool eps);
502 virtual bool exportOnePageOnly();
503 virtual void resetProperties();
504 virtual void loadProperties(QString group);
505 virtual void saveProperties(QString group);
506 virtual bool loadPrintSetup(QPrinter *printer, QPrintDialog *dialog);
507 virtual bool savePrintSetup(QPrinter *printer);
508 virtual int propertyPages();
509 virtual QWidget* propertyPage(int num);
510 virtual bool save(QString fileName);
511 virtual bool print(QPrinter *printer);
512 virtual ddjvu_status_t status();
513 virtual void stop();
514 public slots:
515 void refresh();
516 protected:
517 bool start();
518 void openFile();
519 void closeFile();
520 protected:
521 QFile file;
522 QDjVuJob *job;
523 FILE *output;
524 int outputfd;
525 int copies;
526 bool collate;
527 bool lastfirst;
528 bool duplex;
529 bool failed;
530 bool encapsulated;
531 QPrinter *printer;
532 QPointer<QWidget> page1;
533 QPointer<QWidget> page2;
534 QPointer<QWidget> page3;
535 Ui::QDjViewExportPS1 ui1;
536 Ui::QDjViewExportPS2 ui2;
537 Ui::QDjViewExportPS3 ui3;
538 };
539
540
541 QDjViewExporter*
542 QDjViewPSExporter::create(QDialog *parent, QDjView *djview, QString name)
543 {
544 if (name == "PS")
545 return new QDjViewPSExporter(parent, djview, name, false);
546 if (name == "EPS")
547 return new QDjViewPSExporter(parent, djview, name, true);
548 return 0;
549 }
550
551
552 void
553 QDjViewPSExporter::setup()
554 {
555 addExporterData("PS", "ps",
556 tr("PostScript"),
557 tr("PostScript Files (*.ps *.eps)"),
558 QDjViewPSExporter::create);
559 addExporterData("EPS", "eps",
560 tr("Encapsulated PostScript"),
561 tr("PostScript Files (*.ps *.eps)"),
562 QDjViewPSExporter::create);
563 }
564
565
566 QDjViewPSExporter::~QDjViewPSExporter()
567 {
568 // cleanup output
569 QIODevice::OpenMode mode = file.openMode();
570 ddjvu_status_t st = status();
571 if (st == DDJVU_JOB_STARTED)
572 if (job)
573 ddjvu_job_stop(*job);
574 closeFile();
575 if (st != DDJVU_JOB_OK)
576 if (mode & (QIODevice::WriteOnly|QIODevice::Append))
577 file.remove();
578 // delete property pages
579 delete page1;
580 delete page2;
581 delete page3;
582 }
583
584
585 QDjViewPSExporter::QDjViewPSExporter(QDialog *parent, QDjView *djview,
586 QString name, bool eps)
587 : QDjViewExporter(parent, djview, name),
588 job(0),
589 output(0),
590 outputfd(-1),
591 copies(1),
592 collate(true),
593 lastfirst(false),
594 duplex(false),
595 failed(false),
596 encapsulated(eps),
597 printer(0)
598 {
599 // create pages
600 page1 = new QWidget();
601 page2 = new QWidget();
602 page3 = new QWidget();
603 ui1.setupUi(page1);
604 ui2.setupUi(page2);
605 ui3.setupUi(page3);
606 page1->setObjectName(tr("PostScript","tab caption"));
607 page2->setObjectName(tr("Position","tab caption"));
608 page3->setObjectName(tr("Booklet","tab caption"));
609 resetProperties();
610 // connect stuff
611 connect(ui2.autoOrientCheckBox, SIGNAL(clicked()),
612 this, SLOT(refresh()) );
613 connect(ui3.bookletCheckBox, SIGNAL(clicked()),
614 this, SLOT(refresh()) );
615 connect(ui2.zoomSpinBox, SIGNAL(valueChanged(int)),
616 ui2.zoomButton, SLOT(click()) );
617 // whatsthis
618 page1->setWhatsThis(tr("<html><b>PostScript options.</b><br>"
619 "Option <tt>Color</tt> enables color printing. "
620 "Document pages can be decorated with frame "
621 "and crop marks. "
622 "PostScript language level 1 is only useful "
623 "with very old printers. Level 2 works with most "
624 "printers. Level 3 print color document faster "
625 "on recent printers.</html>") );
626 page2->setWhatsThis(tr("<html><b>Position and scaling.</b><br>"
627 "Option <tt>Scale to fit</tt> accommodates "
628 "whatever paper size your printer uses. "
629 "Zoom factor <tt>100%</tt> reproduces the initial "
630 "document size. Orientation <tt>Automatic</tt> "
631 "chooses portrait or landscape on a page per "
632 "page basis.</html>") );
633 page3->setWhatsThis(tr("<html><b>Producing booklets.</b><br>"
634 "The booklet mode prints the selected "
635 "pages as sheets suitable for folding one or several "
636 "booklets. Several booklets might be produced when "
637 "a maximum number of sheets per booklet is "
638 "specified. You can either use a duplex printer or "
639 "print rectos and versos separately.<p> "
640 "Shifting rectos and versos is useful "
641 "with poorly aligned duplex printers. "
642 "The center margins determine how much "
643 "space is left between the pages to fold the "
644 "sheets. This space slowly increases from the "
645 "inner sheet to the outer sheet."
646 "</html>") );
647 // adjust ui
648 refresh();
649 }
650
651
652 bool
653 QDjViewPSExporter::exportOnePageOnly()
654 {
655 return encapsulated;
656 }
657
658
659 void
660 QDjViewPSExporter::resetProperties()
661 {
662 ui1.colorButton->setChecked(true);
663 ui1.frameCheckBox->setChecked(false);
664 ui1.cropMarksCheckBox->setChecked(false);
665 ui1.levelSpinBox->setValue(3);
666 ui2.autoOrientCheckBox->setChecked(true);
667 ui2.scaleToFitButton->setChecked(true);
668 ui2.zoomSpinBox->setValue(100);
669 ui3.bookletCheckBox->setChecked(false);
670 ui3.sheetsSpinBox->setValue(0);
671 ui3.rectoVersoCombo->setCurrentIndex(0);
672 ui3.rectoVersoShiftSpinBox->setValue(0);
673 ui3.centerMarginSpinBox->setValue(18);
674 ui3.centerIncreaseSpinBox->setValue(40);
675 refresh();
676 }
677
678
679 void
680 QDjViewPSExporter::loadProperties(QString group)
681 {
682 // load settings (ui1)
683 QSettings s;
684 if (group.isEmpty())
685 group = "Export-" + name();
686 s.beginGroup(group);
687 bool color = s.value("color", true).toBool();
688 ui1.colorButton->setChecked(color);
689 ui1.grayScaleButton->setChecked(!color);
690 ui1.frameCheckBox->setChecked(s.value("frame", false).toBool());
691 ui1.cropMarksCheckBox->setChecked(s.value("cropMarks", false).toBool());
692 int level = s.value("psLevel", 3).toInt();
693 ui1.levelSpinBox->setValue(qBound(1,level,3));
694 // load settings (ui2)
695 ui2.autoOrientCheckBox->setChecked(s.value("autoOrient", true).toBool());
696 bool landscape = s.value("landscape",false).toBool();
697 ui2.portraitButton->setChecked(!landscape);
698 ui2.landscapeButton->setChecked(landscape);
699 int zoom = s.value("zoom",0).toInt();
700 ui2.scaleToFitButton->setChecked(zoom == 0);
701 ui2.zoomButton->setChecked(zoom!=0);
702 ui2.zoomSpinBox->setValue(zoom ? qBound(25,zoom,2400) : 100);
703 // load settings (ui3)
704 ui3.bookletCheckBox->setChecked(s.value("booklet", false).toBool());
705 ui3.sheetsSpinBox->setValue(s.value("bookletSheets", 0).toInt());
706 int rectoVerso = qBound(0, s.value("bookletRectoVerso",0).toInt(), 2);
707 ui3.rectoVersoCombo->setCurrentIndex(rectoVerso);
708 int rectoVersoShift = qBound(-72, s.value("bookletShift",0).toInt(), 72);
709 ui3.rectoVersoShiftSpinBox->setValue(rectoVersoShift);
710 int centerMargin = qBound(0, s.value("bookletCenter", 18).toInt(), 144);
711 ui3.centerMarginSpinBox->setValue(centerMargin);
712 int centerIncrease = qBound(0, s.value("bookletCenterAdd", 40).toInt(), 200);
713 ui3.centerIncreaseSpinBox->setValue(centerIncrease);
714 }
715
716
717 void
718 QDjViewPSExporter::saveProperties(QString group)
719 {
720 // save properties
721 QSettings s;
722 if (group.isEmpty())
723 group = "Export-" + name();
724 s.beginGroup(group);
725 s.setValue("color", ui1.colorButton->isChecked());
726 s.setValue("frame", ui1.frameCheckBox->isChecked());
727 s.setValue("cropMarks", ui1.cropMarksCheckBox->isChecked());
728 s.setValue("psLevel", ui1.levelSpinBox->value());
729 s.setValue("autoOrient", ui2.autoOrientCheckBox->isChecked());
730 s.setValue("landscape", ui2.landscapeButton->isChecked());
731 int zoom = ui2.zoomSpinBox->value();
732 s.setValue("zoom", QVariant(ui2.zoomButton->isChecked() ? zoom : 0));
733 s.setValue("booklet", ui3.bookletCheckBox->isChecked());
734 s.setValue("bookletSheets", ui3.sheetsSpinBox->value());
735 s.setValue("bookletRectoVerso", ui3.rectoVersoCombo->currentIndex());
736 s.setValue("bookletShift", ui3.rectoVersoShiftSpinBox->value());
737 s.setValue("bookletCenter", ui3.centerMarginSpinBox->value());
738 s.setValue("bookletCenterAdd", ui3.centerIncreaseSpinBox->value());
739 }
740
741
742 bool
743 QDjViewPSExporter::loadPrintSetup(QPrinter *printer, QPrintDialog *dialog)
744 {
745 bool grayscale = (printer->colorMode() == QPrinter::GrayScale);
746 #if QT_VERSION >= 0x60000
747 bool landscape = printer->pageLayout().orientation() == QPageLayout::Landscape;
748 #else
749 bool landscape = (printer->orientation() == QPrinter::Landscape);
750 #endif
751 ui1.grayScaleButton->setChecked(grayscale);
752 ui1.colorButton->setChecked(!grayscale);
753 ui2.landscapeButton->setChecked(landscape);
754 ui2.portraitButton->setChecked(!landscape);
755 // BEGIN HACK //
756 // Directly steal settings from print dialog.
757 copies = 1;
758 collate = true;
759 lastfirst = false;
760 #if QT_VERSION >= 0x50000
761 QSpinBox* lcop = dialog->findChild<QSpinBox*>("copies");
762 QCheckBox* lcol = dialog->findChild<QCheckBox*>("collate");
763 QCheckBox* lplf = dialog->findChild<QCheckBox*>("reverse");
764 #elif QT_VERSION >= 0x40400
765 QSpinBox* lcop = qFindChild<QSpinBox*>(dialog, "copies");
766 QCheckBox* lcol = qFindChild<QCheckBox*>(dialog, "collate");
767 QCheckBox* lplf = qFindChild<QCheckBox*>(dialog, "reverse");
768 #else
769 QSpinBox* lcop = qFindChild<QSpinBox*>(dialog, "sbNumCopies");
770 QCheckBox* lcol = qFindChild<QCheckBox*>(dialog, "chbCollate");
771 QCheckBox* lplf = qFindChild<QCheckBox*>(dialog, "chbPrintLastFirst");
772 #endif
773 if (lcop)
774 copies = qMax(1, lcop->value());
775 if (lcol)
776 collate = lcol->isChecked();
777 if (lplf)
778 lastfirst = lplf->isChecked();
779 // END HACK //
780 return true;
781 }
782
783
784 bool
785 QDjViewPSExporter::savePrintSetup(QPrinter *printer)
786 {
787 bool g = ui1.grayScaleButton->isChecked();
788 bool l = ui2.landscapeButton->isChecked();
789 printer->setColorMode(g ? QPrinter::GrayScale : QPrinter::Color);
790 #if QT_VERSION >= 0x60000
791 printer->setPageOrientation(l ? QPageLayout::Landscape : QPageLayout::Portrait);
792 #else
793 printer->setOrientation(l ? QPrinter::Landscape : QPrinter::Portrait);
794 #endif
795 return true;
796 }
797
798
799 int
800 QDjViewPSExporter::propertyPages()
801 {
802 return (encapsulated) ? 1 : 3;
803 }
804
805
806 QWidget*
807 QDjViewPSExporter::propertyPage(int n)
808 {
809 if (n == 0)
810 return page1;
811 else if (n == 1)
812 return page2;
813 else if (n == 2)
814 return page3;
815 return 0;
816 }
817
818
819 void
820 QDjViewPSExporter::refresh()
821 {
822 if (encapsulated)
823 {
824 ui1.cropMarksCheckBox->setEnabled(false);
825 ui1.cropMarksCheckBox->setChecked(false);
826 }
827 bool autoOrient = ui2.autoOrientCheckBox->isChecked();
828 ui2.portraitButton->setEnabled(!autoOrient);
829 ui2.landscapeButton->setEnabled(!autoOrient);
830 bool booklet = ui3.bookletCheckBox->isChecked();
831 ui3.bookletGroupBox->setEnabled(booklet);
832 bool nojob = (status() < DDJVU_JOB_STARTED);
833 page1->setEnabled(nojob);
834 page2->setEnabled(nojob && !encapsulated);
835 page3->setEnabled(nojob && !encapsulated);
836 }
837
838
839 void
840 QDjViewPSExporter::openFile()
841 {
842 if (printer)
843 {
844 file.close();
845 if (! printer->outputFileName().isEmpty())
846 file.setFileName(printer->outputFileName());
847 }
848 if (! file.fileName().isEmpty())
849 {
850 file.remove();
851 if (file.open(QIODevice::WriteOnly))
852 output = ::fdopen(wdup(file.handle()), "wb");
853 }
854 else if (printer)
855 {
856 QString printerName = printer->printerName();
857 // disable sigpipe
858 #ifdef SIGPIPE
859 # ifndef HAVE_SIGACTION
860 # ifdef SA_RESTART
861 # define HAVE_SIGACTION 1
862 # endif
863 # endif
864 # if HAVE_SIGACTION
865 sigset_t mask;
866 struct sigaction act;
867 sigemptyset(&mask);
868 sigaddset(&mask, SIGPIPE);
869 sigprocmask(SIG_BLOCK, &mask, 0);
870 sigaction(SIGPIPE, 0, &act);
871 act.sa_handler = SIG_IGN;
872 sigaction(SIGPIPE, &act, 0);
873 # else
874 signal(SIGPIPE, SIG_IGN);
875 # endif
876 #endif
877 // Arguments for lp/lpr
878 QVector<const char*> lpargs;
879 QVector<const char*> lprargs;
880 lpargs << "lp";
881 lprargs << "lpr";
882 QByteArray pname = printerName.toLocal8Bit();
883 if (! pname.isEmpty())
884 {
885 lpargs << "-d";
886 lpargs << pname.data();
887 lprargs << "-P";
888 lprargs << pname.data();
889 }
890 // Arguments for cups.
891 bool cups = false;
892 QList<QByteArray> cargs;
893 QPrintEngine *engine = printer->printEngine();
894 # define PPK_CupsOptions QPrintEngine::PrintEnginePropertyKey(0xfe00)
895 # define PPK_CupsStringPageSize QPrintEngine::PrintEnginePropertyKey(0xfe03)
896 QVariant cPageSize = engine->property(PPK_CupsStringPageSize);
897 QVariant cOptions = engine->property(PPK_CupsOptions);
898 if (! cPageSize.toString().isEmpty())
899 {
900 cups = true;
901 cargs << "-o" << "media=" + cPageSize.toString().toLocal8Bit();
902 }
903 QStringList options = cOptions.toStringList();
904 if (! options.isEmpty())
905 {
906 cups = true;
907 QStringList::const_iterator it = options.constBegin();
908 while (it != options.constEnd())
909 {
910 cargs << "-o";
911 cargs << (*it).toLocal8Bit() + "=" + (*(it+1)).toLocal8Bit();
912 it += 2;
913 }
914 }
915 QByteArray bCopies = QByteArray::number(copies);
916 if (cups)
917 {
918 if (collate)
919 cargs << "-o" << "Collate=True";
920 if (lastfirst)
921 cargs << "-o" << "outputorder=reverse";
922 lastfirst = false;
923 if (duplex)
924 cargs << "-o" << "sides=two-sided-long-edge";
925 // add cups option for number of copies
926 if (copies > 1)
927 {
928 lprargs << "-#" << bCopies.data();
929 lpargs << "-n" << bCopies.data();
930 }
931 // add remaining cups options
932 for(int i=0; i<cargs.size(); i++)
933 {
934 lprargs << cargs.at(i).data();
935 lpargs << cargs.at(i).data();
936 }
937 // reset copies since cups takes care of it
938 copies = 1;
939 }
940 // open pipe for lp/lpr.
941 lpargs << 0;
942 lprargs << 0;
943 #ifndef WIN32
944 int fds[2];
945 if (pipe(fds) == 0)
946 {
947 int pid = fork();
948 if (pid == 0)
949 {
950 // rehash file descriptors
951 #if defined(_SC_OPEN_MAX)
952 int nfd = (int)sysconf(_SC_OPEN_MAX);
953 #elif defined(_POSIX_OPEN_MAX)
954 int nfd = (int)_POSIX_OPEN_MAX;
955 #elif defined(OPEN_MAX)
956 int nfd = (int)OPEN_MAX;
957 #else
958 int nfd = 256;
959 #endif
960 ::close(0);
961 int status = ::dup(fds[0]);
962 for (int i=1; i<nfd; i++)
963 ::close(i);
964 if (status >= 0 && fork() == 0)
965 {
966 // try lp and lpr
967 (void)execvp("lpr", (char**)lprargs.data());
968 (void)execv("/bin/lpr", (char**)lprargs.data());
969 (void)execv("/usr/bin/lpr", (char**)lprargs.data());
970 (void)execvp("lp", (char**)lpargs.data());
971 (void)execv("/bin/lp", (char**)lpargs.data());
972 (void)execv("/usr/bin/lp", (char**)lpargs.data());
973 }
974 // exit without running destructors
975 (void)execlp("true", "true", (char *)0);
976 (void)execl("/bin/true", "true", (char *)0);
977 (void)execl("/usr/bin/true", "true", (char *)0);
978 ::_exit(0);
979 ::exit(0);
980 }
981 ::close(fds[0]);
982 outputfd = fds[1];
983 output = fdopen(outputfd, "wb");
984 if (pid >= 0)
985 {
986 # if HAVE_WAITPID
987 ::waitpid(pid, 0, 0);
988 # else
989 ::wait(0);
990 # endif
991 }
992 else
993 closeFile();
994 }
995 #endif
996 }
997 }
998
999
1000 void
1001 QDjViewPSExporter::closeFile()
1002 {
1003 if (output)
1004 ::fclose(output);
1005 if (outputfd >= 0)
1006 ::close(outputfd);
1007 if (file.openMode())
1008 file.close();
1009 output = 0;
1010 outputfd = -1;
1011 printer = 0;
1012 }
1013
1014
1015 bool
1016 QDjViewPSExporter::save(QString fname)
1017 {
1018 if (output)
1019 return false;
1020 printer = 0;
1021 file.close();
1022 file.setFileName(fname);
1023 return start();
1024 }
1025
1026
1027 bool
1028 QDjViewPSExporter::print(QPrinter *qprinter)
1029 {
1030 if (output)
1031 return false;
1032 printer = qprinter;
1033 file.close();
1034 file.setFileName(QString());
1035 QDjViewPrefs *prefs = QDjViewPrefs::instance();
1036 prefs->printReverse = lastfirst;
1037 prefs->printCollate = collate;
1038 return start();
1039 }
1040
1041
1042 bool
1043 QDjViewPSExporter::start()
1044 {
1045 QDjViewPrefs *prefs = QDjViewPrefs::instance();
1046 QDjVuDocument *document = djview->getDocument();
1047 int pagenum = djview->pageNum();
1048 if (document==0 || pagenum <= 0)
1049 return false;
1050 int tpg = qBound(0, toPage, pagenum-1);
1051 int fpg = qBound(0, fromPage, pagenum-1);
1052 openFile();
1053 if (! output)
1054 return false;
1055
1056 // prepare arguments
1057 QList<QByteArray> args;
1058 if (copies > 1)
1059 args << QString("--copies=%1").arg(copies).toLocal8Bit();
1060 if (fromPage == toPage && pagenum > 1)
1061 args << QString("--pages=%1").arg(fpg+1).toLocal8Bit();
1062 else if (fromPage != 0 || toPage != pagenum - 1)
1063 args << QString("--pages=%1-%2").arg(fpg+1).arg(tpg+1).toLocal8Bit();
1064 if (! ui2.autoOrientCheckBox->isChecked())
1065 {
1066 if (ui2.portraitButton->isChecked())
1067 args << QByteArray("--orientation=portrait");
1068 else if (ui2.landscapeButton->isChecked())
1069 args << QByteArray("--orientation=landscape");
1070 }
1071 if (ui2.zoomButton->isChecked())
1072 args << QString("--zoom=%1").arg(ui2.zoomSpinBox->value()).toLocal8Bit();
1073 if (ui1.frameCheckBox->isChecked())
1074 args << QByteArray("--frame=yes");
1075 if (ui1.cropMarksCheckBox->isChecked())
1076 args << QByteArray("--cropmarks=yes");
1077 if (ui1.levelSpinBox)
1078 args << QString("--level=%1").arg(ui1.levelSpinBox->value()).toLocal8Bit();
1079 if (ui1.grayScaleButton->isChecked())
1080 args << QByteArray("--color=no");
1081 if (prefs && prefs->printerGamma != 0.0)
1082 {
1083 double gamma = qBound(0.3, prefs->printerGamma, 5.0);
1084 args << QByteArray("--colormatch=no");
1085 args << QString("--gamma=%1").arg(gamma).toLocal8Bit();
1086 }
1087 if (ui3.bookletCheckBox->isChecked())
1088 {
1089 int bMode = ui3.rectoVersoCombo->currentIndex();
1090 if (bMode == 1)
1091 args << QByteArray("--booklet=recto");
1092 else if (bMode == 2)
1093 args << QByteArray("--booklet=verso");
1094 else
1095 args << QByteArray("--booklet=yes");
1096 int bMax = ui3.sheetsSpinBox->value();
1097 if (bMax > 0)
1098 args << QString("--bookletmax=%1").arg(bMax).toLocal8Bit();
1099 int bAlign = ui3.rectoVersoShiftSpinBox->value();
1100 args << QString("--bookletalign=%1").arg(bAlign).toLocal8Bit();
1101 int bCenter = ui3.centerMarginSpinBox->value();
1102 int bIncr = ui3.centerIncreaseSpinBox->value() * 10;
1103 args << QString("--bookletfold=%1+%2")
1104 .arg(bCenter).arg(bIncr).toLocal8Bit();
1105 }
1106 if (encapsulated)
1107 args << QByteArray("--format=eps");
1108 QDjVuWidget::DisplayMode displayMode;
1109 displayMode = djview->getDjVuWidget()->displayMode();
1110 if (displayMode == QDjVuWidget::DISPLAY_STENCIL)
1111 args << QByteArray("--mode=black");
1112 else if (displayMode == QDjVuWidget::DISPLAY_BG)
1113 args << QByteArray("--mode=background");
1114 else if (displayMode == QDjVuWidget::DISPLAY_FG)
1115 args << QByteArray("--mode=foreground");
1116
1117 // convert arguments
1118 int argc = args.count();
1119 QVector<const char*> argv(argc);
1120 for (int i=0; i<argc; i++)
1121 argv[i] = args[i].constData();
1122
1123 // start print job
1124 ddjvu_job_t *pjob;
1125 pjob = ddjvu_document_print(*document, output, argc, argv.data());
1126 if (! pjob)
1127 {
1128 failed = true;
1129 // error messages went to the document
1130 connect(document, SIGNAL(error(QString,QString,int)),
1131 this, SLOT(error(QString,QString,int)) );
1132 qApp->sendEvent(&djview->getDjVuContext(), new QEvent(QEvent::User));
1133 disconnect(document, 0, this, 0);
1134 // main error message
1135 QString message = tr("Save job creation failed!");
1136 error(message, __FILE__, __LINE__);
1137 return false;
1138 }
1139 job = new QDjVuJob(pjob, this);
1140 connect(job, SIGNAL(error(QString,QString,int)),
1141 this, SLOT(error(QString,QString,int)) );
1142 connect(job, SIGNAL(progress(int)),
1143 this, SIGNAL(progress(int)) );
1144 emit progress(0);
1145 refresh();
1146 return true;
1147 }
1148
1149
1150 void
1151 QDjViewPSExporter::stop()
1152 {
1153 if (job && status() == DDJVU_JOB_STARTED)
1154 ddjvu_job_stop(*job);
1155 }
1156
1157
1158 ddjvu_status_t
1159 QDjViewPSExporter::status()
1160 {
1161 if (job)
1162 return ddjvu_job_status(*job);
1163 else if (failed)
1164 return DDJVU_JOB_FAILED;
1165 else
1166 return DDJVU_JOB_NOTSTARTED;
1167 }
1168
1169
1170 // ----------------------------------------
1171 // QDJVIEWPAGEEXPORTER
1172
1173
1174 class QDjViewPageExporter : public QDjViewExporter
1175 {
1176 Q_OBJECT
1177 public:
1178 ~QDjViewPageExporter();
1179 QDjViewPageExporter(QDialog *parent, QDjView *djview, QString name);
1180 virtual ddjvu_status_t status() { return curStatus; }
1181 public slots:
1182 virtual bool start();
1183 virtual void stop();
1184 virtual void error(QString message, QString filename, int lineno);
1185 protected slots:
1186 void checkPage();
1187 protected:
1188 virtual void openFile() {}
1189 virtual void closeFile() {}
1190 virtual void doFinal() {}
1191 virtual void doPage() = 0;
1192 ddjvu_status_t curStatus;
1193 QDjVuPage *curPage;
1194 int curProgress;
1195 };
1196
1197
1198 QDjViewPageExporter::~QDjViewPageExporter()
1199 {
1200 curStatus = DDJVU_JOB_NOTSTARTED;
1201 closeFile();
1202 }
1203
1204
1205 QDjViewPageExporter::QDjViewPageExporter(QDialog *parent, QDjView *djview,
1206 QString name)
1207 : QDjViewExporter(parent, djview, name),
1208 curStatus(DDJVU_JOB_NOTSTARTED),
1209 curPage(0), curProgress(0)
1210 {
1211 }
1212
1213
1214 bool
1215 QDjViewPageExporter::start()
1216 {
1217 if (curStatus != DDJVU_JOB_STARTED)
1218 {
1219 curStatus = DDJVU_JOB_STARTED;
1220 openFile();
1221 checkPage();
1222 }
1223 if (curStatus <= DDJVU_JOB_OK)
1224 return true;
1225 return false;
1226 }
1227
1228
1229 void
1230 QDjViewPageExporter::stop()
1231 {
1232 if (curStatus == DDJVU_JOB_STARTED)
1233 curStatus = DDJVU_JOB_STOPPED;
1234 if (curPage)
1235 if (ddjvu_page_decoding_status(*curPage) == DDJVU_JOB_STARTED)
1236 ddjvu_job_stop(ddjvu_page_job(*curPage));
1237 emit progress(curProgress);
1238 }
1239
1240
1241 void
1242 QDjViewPageExporter::error(QString message, QString filename, int lineno)
1243 {
1244 if (curStatus == DDJVU_JOB_STARTED)
1245 curStatus = DDJVU_JOB_FAILED;
1246 QDjViewExporter::error(message, filename, lineno);
1247 }
1248
1249
1250 void
1251 QDjViewPageExporter::checkPage()
1252 {
1253 QDjVuDocument *document = djview->getDocument();
1254 int pagenum = djview->pageNum();
1255 if (document==0 || pagenum <= 0)
1256 return;
1257 ddjvu_status_t pageStatus = DDJVU_JOB_NOTSTARTED;
1258 if (curPage)
1259 pageStatus = ddjvu_page_decoding_status(*curPage);
1260 if (pageStatus > DDJVU_JOB_OK)
1261 {
1262 curStatus = pageStatus;
1263 emit progress(curProgress);
1264 disconnect(curPage, 0, this, 0);
1265 delete curPage;
1266 curPage = 0;
1267 closeFile();
1268 return;
1269 }
1270 int tpg = qBound(0, toPage, pagenum-1);
1271 int fpg = qBound(0, fromPage, pagenum-1);
1272 int nextPage = fpg;
1273 if (pageStatus == DDJVU_JOB_OK)
1274 {
1275 nextPage = curPage->pageNo() + 1;
1276 doPage();
1277 curProgress = 100 * (nextPage - fpg) / (1 + tpg - fpg);
1278 disconnect(curPage, 0, this, 0);
1279 delete curPage;
1280 curPage = 0;
1281 if (curStatus < DDJVU_JOB_OK && nextPage > tpg)
1282 {
1283 curStatus = DDJVU_JOB_OK;
1284 doFinal();
1285 }
1286 emit progress(curProgress);
1287 if (curStatus >= DDJVU_JOB_OK)
1288 closeFile();
1289 }
1290 if (curStatus == DDJVU_JOB_STARTED && !curPage)
1291 {
1292 curPage = new QDjVuPage(document, nextPage, this);
1293 connect(curPage, SIGNAL(pageinfo()),
1294 this, SLOT(checkPage()));
1295 connect(curPage, SIGNAL(error(QString,QString,int)),
1296 this, SLOT(error(QString,QString,int)) );
1297 if (ddjvu_page_decoding_done(*curPage))
1298 QTimer::singleShot(0, this, SLOT(checkPage()));
1299 }
1300 }
1301
1302
1303
1304
1305
1306 // ----------------------------------------
1307 // QDJVIEWTIFFEXPORTER
1308
1309
1310 #include "ui_qdjviewexporttiff.h"
1311
1312
1313 class QDjViewTiffExporter : public QDjViewPageExporter
1314 {
1315 Q_OBJECT
1316 public:
1317 static QDjViewExporter *create(QDialog*, QDjView*, QString);
1318 static void setup();
1319 public:
1320 ~QDjViewTiffExporter();
1321 QDjViewTiffExporter(QDialog *parent, QDjView *djview, QString name);
1322 virtual void resetProperties();
1323 virtual void loadProperties(QString group);
1324 virtual void saveProperties(QString group);
1325 virtual int propertyPages();
1326 virtual QWidget* propertyPage(int num);
1327 virtual bool save(QString fileName);
1328 protected:
1329 virtual void closeFile();
1330 virtual void doPage();
1331 protected:
1332 void checkTiffSupport();
1333 Ui::QDjViewExportTiff ui;
1334 QPointer<QWidget> page;
1335 QFile file;
1336 #if HAVE_TIFF
1337 TIFF *tiff;
1338 #else
1339 FILE *tiff;
1340 #endif
1341 };
1342
1343
1344 QDjViewExporter*
1345 QDjViewTiffExporter::create(QDialog *parent, QDjView *djview, QString name)
1346 {
1347 if (name == "TIFF")
1348 return new QDjViewTiffExporter(parent, djview, name);
1349 return 0;
1350 }
1351
1352
1353 void
1354 QDjViewTiffExporter::setup()
1355 {
1356 addExporterData("TIFF", "tiff",
1357 tr("TIFF Document"),
1358 tr("TIFF Files (*.tiff *.tif)"),
1359 QDjViewTiffExporter::create);
1360 }
1361
1362
1363 QDjViewTiffExporter::~QDjViewTiffExporter()
1364 {
1365 closeFile();
1366 delete page;
1367 }
1368
1369
1370 QDjViewTiffExporter::QDjViewTiffExporter(QDialog *parent, QDjView *djview,
1371 QString name)
1372 : QDjViewPageExporter(parent, djview, name),
1373 tiff(0)
1374 {
1375 page = new QWidget();
1376 ui.setupUi(page);
1377 page->setObjectName(tr("TIFF Options", "tab caption"));
1378 resetProperties();
1379 page->setWhatsThis(tr("<html><b>TIFF options.</b><br>"
1380 "The resolution box specifies an upper "
1381 "limit for the resolution of the TIFF images. "
1382 "Forcing bitonal G4 compression "
1383 "encodes all pages in black and white "
1384 "using the CCITT Group 4 compression. "
1385 "Allowing JPEG compression uses lossy JPEG "
1386 "for all non bitonal or subsampled images. "
1387 "Otherwise, allowing deflate compression "
1388 "produces more compact (but less portable) files "
1389 "than the default packbits compression."
1390 "</html>") );
1391 }
1392
1393
1394 void
1395 QDjViewTiffExporter::checkTiffSupport()
1396 {
1397 #ifdef CCITT_SUPPORT
1398 ui.bitonalCheckBox->setEnabled(true);
1399 #else
1400 ui.bitonalCheckBox->setEnabled(false);
1401 #endif
1402 #ifdef JPEG_SUPPORT
1403 ui.jpegCheckBox->setEnabled(true);
1404 ui.jpegSpinBox->setEnabled(true);
1405 #else
1406 ui.jpegCheckBox->setEnabled(false);
1407 ui.jpegSpinBox->setEnabled(false);
1408 #endif
1409 #ifdef ZIP_SUPPORT
1410 ui.deflateCheckBox->setEnabled(true);
1411 #else
1412 ui.deflateCheckBox->setEnabled(false);
1413 #endif
1414 }
1415
1416
1417 void
1418 QDjViewTiffExporter::resetProperties()
1419 {
1420 ui.dpiSpinBox->setValue(600);
1421 ui.bitonalCheckBox->setChecked(false);
1422 ui.jpegCheckBox->setChecked(true);
1423 ui.jpegSpinBox->setValue(75);
1424 ui.deflateCheckBox->setChecked(true);
1425 checkTiffSupport();
1426 }
1427
1428
1429 void
1430 QDjViewTiffExporter::loadProperties(QString group)
1431 {
1432 QSettings s;
1433 if (group.isEmpty())
1434 group = "Export-" + name();
1435 s.beginGroup(group);
1436 ui.dpiSpinBox->setValue(s.value("dpi", 600).toInt());
1437 ui.bitonalCheckBox->setChecked(s.value("bitonal", false).toBool());
1438 ui.jpegCheckBox->setChecked(s.value("jpeg", true).toBool());
1439 ui.jpegSpinBox->setValue(s.value("jpegQuality", 75).toInt());
1440 ui.deflateCheckBox->setChecked(s.value("deflate", true).toBool());
1441 checkTiffSupport();
1442 }
1443
1444
1445 void
1446 QDjViewTiffExporter::saveProperties(QString group)
1447 {
1448 QSettings s;
1449 if (group.isEmpty())
1450 group = "Export-" + name();
1451 s.beginGroup(group);
1452 s.setValue("dpi", ui.dpiSpinBox->value());
1453 s.setValue("bitonal", ui.bitonalCheckBox->isChecked());
1454 s.setValue("jpeg", ui.jpegCheckBox->isChecked());
1455 s.setValue("jpegQuality", ui.jpegSpinBox->value());
1456 s.setValue("deflate", ui.deflateCheckBox->isChecked());
1457 }
1458
1459
1460 int
1461 QDjViewTiffExporter::propertyPages()
1462 {
1463 return 1;
1464 }
1465
1466
1467 QWidget*
1468 QDjViewTiffExporter::propertyPage(int num)
1469 {
1470 if (num == 0)
1471 return page;
1472 return 0;
1473 }
1474
1475
1476 #if HAVE_TIFF
1477
1478 static QDjViewTiffExporter *tiffExporter;
1479
1480 static void
1481 tiffHandler(const char *, const char *fmt, va_list ap)
1482 {
1483 QString message;
1484 #if QT_VERSION >= 0x50500
1485 message.vasprintf(fmt, ap);
1486 #else
1487 message.vsprintf(fmt, ap);
1488 #endif
1489 tiffExporter->error(message, __FILE__, __LINE__);
1490 }
1491
1492 #endif
1493
1494
1495 void
1496 QDjViewTiffExporter::closeFile()
1497 {
1498 #if HAVE_TIFF
1499 tiffExporter = this;
1500 TIFFSetErrorHandler(tiffHandler);
1501 TIFFSetWarningHandler(0);
1502 if (tiff)
1503 TIFFClose(tiff);
1504 #endif
1505 tiff = 0;
1506 QIODevice::OpenMode mode = file.openMode();
1507 file.close();
1508 if (curStatus > DDJVU_JOB_OK)
1509 if (mode & (QIODevice::WriteOnly|QIODevice::Append))
1510 file.remove();
1511 }
1512
1513
1514 bool
1515 QDjViewTiffExporter::save(QString fname)
1516 {
1517 if (file.openMode())
1518 return false;
1519 file.setFileName(fname);
1520 return start();
1521 }
1522
1523
1524 void
1525 QDjViewTiffExporter::doPage()
1526 {
1527 ddjvu_format_t *fmt = 0;
1528 char *image = 0;
1529 QString message;
1530 #if HAVE_TIFF
1531 tiffExporter = this;
1532 TIFFSetErrorHandler(tiffHandler);
1533 TIFFSetWarningHandler(0);
1534 QDjVuPage *page = curPage;
1535 // open file or write directory
1536 if (tiff)
1537 TIFFWriteDirectory(tiff);
1538 else if (file.open(QIODevice::ReadWrite))
1539 tiff = TIFFFdOpen(wdup(file.handle()), file.fileName().toLocal8Bit().data(),"w");
1540 if (!tiff)
1541 message = tr("Cannot open output file.");
1542 else
1543 {
1544 // determine rectangle
1545 ddjvu_rect_t rect;
1546 int imgdpi = ddjvu_page_get_resolution(*page);
1547 int dpi = qMin(imgdpi, ui.dpiSpinBox->value());
1548 rect.x = rect.y = 0;
1549 rect.w = ( ddjvu_page_get_width(*page) * dpi + imgdpi/2 ) / imgdpi;
1550 rect.h = ( ddjvu_page_get_height(*page) * dpi + imgdpi/2 ) / imgdpi;
1551 // determine mode
1552 ddjvu_render_mode_t mode = DDJVU_RENDER_COLOR;
1553 QDjVuWidget::DisplayMode displayMode;
1554 displayMode = djview->getDjVuWidget()->displayMode();
1555 if (ui.bitonalCheckBox->isChecked())
1556 mode = DDJVU_RENDER_BLACK;
1557 else if (displayMode == QDjVuWidget::DISPLAY_STENCIL)
1558 mode = DDJVU_RENDER_BLACK;
1559 else if (displayMode == QDjVuWidget::DISPLAY_BG)
1560 mode = DDJVU_RENDER_BACKGROUND;
1561 else if (displayMode == QDjVuWidget::DISPLAY_FG)
1562 mode = DDJVU_RENDER_FOREGROUND;
1563 // determine format and compression
1564 ddjvu_page_type_t type = ddjvu_page_get_type(*page);
1565 ddjvu_format_style_t style = DDJVU_FORMAT_RGB24;
1566 int compression = COMPRESSION_NONE;
1567 if (ui.bitonalCheckBox->isChecked())
1568 style = DDJVU_FORMAT_MSBTOLSB;
1569 else if (mode==DDJVU_RENDER_BLACK
1570 || type==DDJVU_PAGETYPE_BITONAL)
1571 style = (dpi == imgdpi)
1572 ? DDJVU_FORMAT_MSBTOLSB
1573 : DDJVU_FORMAT_GREY8;
1574 #ifdef CCITT_SUPPORT
1575 if (style == DDJVU_FORMAT_MSBTOLSB
1576 && TIFFFindCODEC(COMPRESSION_CCITT_T6))
1577 compression = COMPRESSION_CCITT_T6;
1578 #endif
1579 #ifdef JPEG_SUPPORT
1580 else if (ui.jpegCheckBox->isChecked()
1581 && style != DDJVU_FORMAT_MSBTOLSB
1582 && TIFFFindCODEC(COMPRESSION_JPEG))
1583 compression = COMPRESSION_JPEG;
1584 #endif
1585 #ifdef ZIP_SUPPORT
1586 else if (ui.deflateCheckBox->isChecked()
1587 && style != DDJVU_FORMAT_MSBTOLSB
1588 && TIFFFindCODEC(COMPRESSION_DEFLATE))
1589 compression = COMPRESSION_DEFLATE;
1590 #endif
1591 #ifdef PACKBITS_SUPPORT
1592 else if (TIFFFindCODEC(COMPRESSION_PACKBITS))
1593 compression = COMPRESSION_PACKBITS;
1594 #endif
1595 fmt = ddjvu_format_create(style, 0, 0);
1596 ddjvu_format_set_row_order(fmt, 1);
1597 ddjvu_format_set_gamma(fmt, 2.2);
1598 // set parameters
1599 int quality = ui.jpegSpinBox->value();
1600 TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, (uint32)rect.w);
1601 TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, (uint32)rect.h);
1602 TIFFSetField(tiff, TIFFTAG_XRESOLUTION, (float)(dpi));
1603 TIFFSetField(tiff, TIFFTAG_YRESOLUTION, (float)(dpi));
1604 TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
1605 TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
1606 #ifdef CCITT_SUPPORT
1607 if (compression != COMPRESSION_CCITT_T6)
1608 #endif
1609 #ifdef JPEG_SUPPORT
1610 if (compression != COMPRESSION_JPEG)
1611 #endif
1612 #ifdef ZIP_SUPPORT
1613 if (compression != COMPRESSION_DEFLATE)
1614 #endif
1615 TIFFSetField(tiff, TIFFTAG_ROWSPERSTRIP, (uint32)64);
1616 if (style == DDJVU_FORMAT_MSBTOLSB) {
1617 TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, (uint16)1);
1618 TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)1);
1619 TIFFSetField(tiff, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB);
1620 TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression);
1621 TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
1622 } else {
1623 TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, (uint16)8);
1624 TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression);
1625 #ifdef JPEG_SUPPORT
1626 if (compression == COMPRESSION_JPEG)
1627 TIFFSetField(tiff, TIFFTAG_JPEGQUALITY, quality);
1628 #endif
1629 if (style == DDJVU_FORMAT_GREY8) {
1630 TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)1);
1631 TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
1632 } else {
1633 TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, (uint16)3);
1634 TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression);
1635 #ifdef JPEG_SUPPORT
1636 if (compression == COMPRESSION_JPEG) {
1637 TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR);
1638 TIFFSetField(tiff, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
1639 } else
1640 #endif
1641 TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
1642 }
1643 }
1644 // render and save
1645 char white = (char)0xff;
1646 int rowsize = rect.w * 3;
1647 if (style == DDJVU_FORMAT_MSBTOLSB) {
1648 white = 0x00;
1649 rowsize = (rect.w + 7) / 8;
1650 } else if (style == DDJVU_FORMAT_GREY8)
1651 rowsize = rect.w;
1652 if (! (image = (char*)malloc(rowsize * rect.h)))
1653 message = tr("Out of memory.");
1654 else if (rowsize != TIFFScanlineSize(tiff))
1655 message = tr("Internal error.");
1656 else
1657 {
1658 char *s = image;
1659 ddjvu_rect_t *r = &rect;
1660 if (! ddjvu_page_render(*page, mode, r, r, fmt, rowsize, image))
1661 memset(image, white, rowsize * rect.h);
1662 for (int i=0; i<(int)rect.h; i++, s+=rowsize)
1663 TIFFWriteScanline(tiff, s, i, 0);
1664 }
1665 }
1666 #else
1667 message = tr("TIFF export has not been compiled.");
1668 #endif
1669 if (! message.isEmpty())
1670 error(message, __FILE__, __LINE__);
1671 if (fmt)
1672 ddjvu_format_release(fmt);
1673 if (image)
1674 free(image);
1675 }
1676
1677
1678
1679
1680
1681
1682
1683 // ----------------------------------------
1684 // QDJVIEWPDFEXPORTER
1685
1686
1687 class QDjViewPdfExporter : public QDjViewTiffExporter
1688 {
1689 Q_OBJECT
1690 public:
1691 static QDjViewExporter *create(QDialog*, QDjView*, QString);
1692 static void setup();
1693 public:
1694 QDjViewPdfExporter(QDialog *parent, QDjView *djview, QString name);
1695 virtual bool save(QString fileName);
1696 protected:
1697 virtual void doFinal();
1698 protected:
1699 QTemporaryFile tempFile;
1700 QFile pdfFile;
1701 };
1702
1703
1704 QDjViewExporter*
1705 QDjViewPdfExporter::create(QDialog *parent, QDjView *djview, QString name)
1706 {
1707 if (name == "PDF")
1708 return new QDjViewPdfExporter(parent, djview, name);
1709 return 0;
1710 }
1711
1712
1713 void
1714 QDjViewPdfExporter::setup()
1715 {
1716 addExporterData("PDF", "pdf",
1717 tr("PDF Document"),
1718 tr("PDF Files (*.pdf)"),
1719 QDjViewPdfExporter::create);
1720 }
1721
1722
1723 QDjViewPdfExporter::QDjViewPdfExporter(QDialog *parent, QDjView *djview,
1724 QString name)
1725 : QDjViewTiffExporter(parent, djview, name)
1726 {
1727 page->setObjectName(tr("PDF Options", "tab caption"));
1728 page->setWhatsThis(tr("<html><b>PDF options.</b><br>"
1729 "These options control the characteristics of "
1730 "the images embedded in the exported PDF files. "
1731 "The resolution box limits their maximal resolution. "
1732 "Forcing bitonal G4 compression "
1733 "encodes all pages in black and white "
1734 "using the CCITT Group 4 compression. "
1735 "Allowing JPEG compression uses lossy JPEG "
1736 "for all non bitonal or subsampled images. "
1737 "Otherwise, allowing deflate compression "
1738 "produces more compact files. "
1739 "</html>") );
1740 }
1741
1742
1743 void
1744 QDjViewPdfExporter::doFinal()
1745 {
1746 QString message;
1747 // close tiff
1748 #if HAVE_TIFF2PDF
1749 tiffExporter = this;
1750 TIFFSetErrorHandler(tiffHandler);
1751 TIFFSetWarningHandler(0);
1752 if (tiff)
1753 TIFFClose(tiff);
1754 tiff = 0;
1755 // open files
1756 TIFF *input = 0;
1757 FILE *output = 0;
1758 QByteArray inameArray = file.fileName().toLocal8Bit();
1759 QByteArray onameArray = pdfFile.fileName().toLocal8Bit();
1760 file.close();
1761 if (file.open(QIODevice::ReadOnly))
1762 input = TIFFFdOpen(wdup(file.handle()), inameArray.data(), "r");
1763 if (pdfFile.open(QIODevice::WriteOnly))
1764 output = ::fdopen(wdup(pdfFile.handle()),"wb");
1765 if (input && output)
1766 {
1767 const char *argv[3];
1768 argv[0] = "tiff2pdf";
1769 argv[1] = "-o";
1770 argv[2] = onameArray.data();
1771 if (tiff2pdf(input, output, 3, argv) != EXIT_SUCCESS)
1772 message = tr("Error while creating pdf file.");
1773 }
1774 else if (! output)
1775 {
1776 message = tr("Unable to create output file.");
1777 if (! pdfFile.errorString().isEmpty())
1778 message = tr("System error: %1.").arg(pdfFile.errorString());
1779 }
1780 else
1781 message = tr("Unable to reopen temporary file.");
1782 // close all
1783 if (input)
1784 TIFFClose(input);
1785 if (output)
1786 fclose(output);
1787 if (file.openMode())
1788 file.close();
1789 if (pdfFile.openMode())
1790 pdfFile.close();
1791 if (tempFile.openMode())
1792 tempFile.close();
1793 if (tempFile.exists())
1794 tempFile.remove();
1795 #else
1796 message = tr("PDF export was not compiled.");
1797 #endif
1798 if (!message.isEmpty())
1799 {
1800 curStatus = DDJVU_JOB_FAILED;
1801 error(message, __FILE__, __LINE__);
1802 }
1803 }
1804
1805
1806 bool
1807 QDjViewPdfExporter::save(QString fname)
1808 {
1809 if (file.openMode() || tempFile.openMode() || pdfFile.openMode())
1810 return false;
1811 pdfFile.setFileName(fname);
1812 tempFile.setFileTemplate(fname);
1813 if (tempFile.open())
1814 {
1815 file.setFileName(tempFile.fileName());
1816 tempFile.close();
1817 return start();
1818 }
1819 // prepare error message
1820 QString message = tr("Unable to create temporary file.");
1821 if (! tempFile.errorString().isEmpty())
1822 message = tr("System error: %1.").arg(tempFile.errorString());
1823 error(message, __FILE__, __LINE__);
1824 return false;
1825 }
1826
1827
1828 // ----------------------------------------
1829 // QDJVIEWIMGEXPORTER
1830
1831
1832
1833 class QDjViewImgExporter : public QDjViewPageExporter
1834 {
1835 Q_OBJECT
1836 public:
1837 static QDjViewExporter *create(QDialog*, QDjView*, QString);
1838 static void setup();
1839 public:
1840 QDjViewImgExporter(QDialog *parent, QDjView *djview,
1841 QString name, QByteArray format);
1842 virtual bool exportOnePageOnly();
1843 virtual bool save(QString fname);
1844 protected:
1845 virtual void doPage();
1846 QString fileName;
1847 QByteArray format;
1848 };
1849
1850
1851 QDjViewExporter*
1852 QDjViewImgExporter::create(QDialog *parent, QDjView *djview, QString name)
1853 {
1854 QByteArray format = name.toLocal8Bit();
1855 QList<QByteArray> formats = QImageWriter::supportedImageFormats();
1856
1857 if (formats.contains(format))
1858 return new QDjViewImgExporter(parent, djview, name, format);
1859 return 0;
1860 }
1861
1862
1863 void
1864 QDjViewImgExporter::setup()
1865 {
1866 QByteArray format;
1867 QList<QByteArray> formats = QImageWriter::supportedImageFormats();
1868 foreach(format, formats)
1869 {
1870 QString name = QString::fromLocal8Bit(format);
1871 QString uname = name.toUpper();
1872 QString suffix = name.toLower();
1873 addExporterData(name, suffix,
1874 tr("%1 Image", "JPG Image").arg(uname),
1875 tr("%1 Files (*.%2)", "JPG Files").arg(uname).arg(suffix),
1876 QDjViewImgExporter::create);
1877 }
1878 }
1879
1880
1881 QDjViewImgExporter::QDjViewImgExporter(QDialog *parent, QDjView *djview,
1882 QString name, QByteArray format)
1883 : QDjViewPageExporter(parent, djview, name),
1884 format(format)
1885 {
1886 }
1887
1888
1889 bool
1890 QDjViewImgExporter::exportOnePageOnly()
1891 {
1892 return true;
1893 }
1894
1895
1896 bool
1897 QDjViewImgExporter::save(QString fname)
1898 {
1899 fileName = fname;
1900 return start();
1901 }
1902
1903
1904 void
1905 QDjViewImgExporter::doPage()
1906 {
1907 QDjVuPage *page = curPage;
1908 // determine rectangle
1909 ddjvu_rect_t rect;
1910 int imgdpi = ddjvu_page_get_resolution(*page);
1911 int dpi = imgdpi; // (TODO: add property page with resolution!)
1912 rect.x = rect.y = 0;
1913 rect.w = ( ddjvu_page_get_width(*page) * dpi + imgdpi/2 ) / imgdpi;
1914 rect.h = ( ddjvu_page_get_height(*page) * dpi + imgdpi/2 ) / imgdpi;
1915 // prepare format
1916 ddjvu_format_t *fmt = 0;
1917 #if DDJVUAPI_VERSION < 18
1918 unsigned int masks[3] = { 0xff0000, 0xff00, 0xff };
1919 fmt = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 3, masks);
1920 #else
1921 unsigned int masks[4] = { 0xff0000, 0xff00, 0xff, 0xff000000 };
1922 fmt = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 4, masks);
1923 #endif
1924 ddjvu_format_set_row_order(fmt, true);
1925 ddjvu_format_set_gamma(fmt, 2.2);
1926 // determine mode (TODO: add property page with mode!)
1927 ddjvu_render_mode_t mode = DDJVU_RENDER_COLOR;
1928 QDjVuWidget::DisplayMode displayMode;
1929 displayMode = djview->getDjVuWidget()->displayMode();
1930 if (displayMode == QDjVuWidget::DISPLAY_STENCIL)
1931 mode = DDJVU_RENDER_BLACK;
1932 else if (displayMode == QDjVuWidget::DISPLAY_BG)
1933 mode = DDJVU_RENDER_BACKGROUND;
1934 else if (displayMode == QDjVuWidget::DISPLAY_FG)
1935 mode = DDJVU_RENDER_FOREGROUND;
1936 // compute image
1937 QString message;
1938 QImage img(rect.w, rect.h, QImage::Format_RGB32);
1939 if (! ddjvu_page_render(*page, mode, &rect, &rect, fmt,
1940 img.bytesPerLine(), (char*)img.bits() ))
1941 message = tr("Cannot render page.");
1942 else
1943 {
1944 QFile file(fileName);
1945 QImageWriter writer(&file, format);
1946 if (! writer.write(img))
1947 {
1948 message = file.errorString();
1949 file.remove();
1950 if (writer.error() == QImageWriter::UnsupportedFormatError)
1951 message = tr("Image format %1 not supported.")
1952 .arg(QString::fromLocal8Bit(format).toUpper());
1953 #if HAVE_STRERROR
1954 if (file.error() == QFile::OpenError && errno > 0)
1955 message = strerror(errno);
1956 #endif
1957 }
1958 }
1959 if (! message.isEmpty())
1960 error(message, __FILE__, __LINE__);
1961 if (fmt)
1962 ddjvu_format_release(fmt);
1963 }
1964
1965
1966
1967
1968 // ----------------------------------------
1969 // QDJVIEWPRNEXPORTER
1970
1971
1972
1973 #include "ui_qdjviewexportprn.h"
1974
1975
1976 class QDjViewPrnExporter : public QDjViewPageExporter
1977 {
1978 Q_OBJECT
1979 public:
1980 static QDjViewExporter *create(QDialog*, QDjView*, QString);
1981 static void setup();
1982 public:
1983 ~QDjViewPrnExporter();
1984 QDjViewPrnExporter(QDialog *parent, QDjView *djview, QString name);
1985 virtual void resetProperties();
1986 virtual void loadProperties(QString group);
1987 virtual void saveProperties(QString group);
1988 virtual bool loadPrintSetup(QPrinter *printer, QPrintDialog *dialog);
1989 virtual bool savePrintSetup(QPrinter *printer);
1990 virtual int propertyPages();
1991 virtual QWidget* propertyPage(int num);
1992 virtual bool save(QString fileName);
1993 virtual bool print(QPrinter *printer);
1994 protected:
1995 virtual void closeFile();
1996 virtual void doPage();
1997 protected:
1998 Ui::QDjViewExportPrn ui;
1999 QPointer<QWidget> page;
2000 QPrinter *printer;
2001 QPainter *painter;
2002 QString fileName;
2003 };
2004
2005
2006 QDjViewExporter*
2007 QDjViewPrnExporter::create(QDialog *parent, QDjView *djview, QString name)
2008 {
2009 if (name == "PRN")
2010 return new QDjViewPrnExporter(parent, djview, name);
2011 return 0;
2012 }
2013
2014
2015 void
2016 QDjViewPrnExporter::setup()
2017 {
2018 addExporterData("PRN", "prn",
2019 tr("Printer data"),
2020 tr("PRN Files (*.prn)"),
2021 QDjViewPrnExporter::create);
2022 }
2023
2024
2025 QDjViewPrnExporter::~QDjViewPrnExporter()
2026 {
2027 closeFile();
2028 delete page;
2029 }
2030
2031
2032 QDjViewPrnExporter::QDjViewPrnExporter(QDialog *parent, QDjView *djview,
2033 QString name)
2034 : QDjViewPageExporter(parent, djview, name),
2035 printer(0),
2036 painter(0)
2037 {
2038 page = new QWidget();
2039 ui.setupUi(page);
2040 page->setObjectName(tr("Printing Options", "tab caption"));
2041 resetProperties();
2042 page->setWhatsThis(tr("<html><b>Printing options.</b><br>"
2043 "Option <tt>Color</tt> enables color printing. "
2044 "Document pages can be decorated with a frame. "
2045 "Option <tt>Scale to fit</tt> accommodates "
2046 "whatever paper size your printer uses. "
2047 "Zoom factor <tt>100%</tt> reproduces the initial "
2048 "document size. Orientation <tt>Automatic</tt> "
2049 "chooses portrait or landscape on a page per "
2050 "page basis.</html>") );
2051 }
2052
2053
2054 void
2055 QDjViewPrnExporter::resetProperties()
2056 {
2057 ui.colorButton->setChecked(true);
2058 ui.frameCheckBox->setChecked(false);
2059 ui.cropMarksCheckBox->setChecked(false);
2060 ui.autoOrientCheckBox->setChecked(true);
2061 ui.scaleToFitButton->setChecked(true);
2062 ui.zoomSpinBox->setValue(100);
2063 }
2064
2065
2066 void
2067 QDjViewPrnExporter::loadProperties(QString group)
2068 {
2069 QSettings s;
2070 if (group.isEmpty())
2071 group = "Export-" + name();
2072 s.beginGroup(group);
2073 bool color = s.value("color", true).toBool();
2074 ui.colorButton->setChecked(color);
2075 ui.grayScaleButton->setChecked(!color);
2076 ui.frameCheckBox->setChecked(s.value("frame", false).toBool());
2077 ui.cropMarksCheckBox->setChecked(false);
2078 ui.autoOrientCheckBox->setChecked(s.value("autoOrient", true).toBool());
2079 bool landscape = s.value("landscape",false).toBool();
2080 ui.portraitButton->setChecked(!landscape);
2081 ui.landscapeButton->setChecked(landscape);
2082 int zoom = s.value("zoom",0).toInt();
2083 ui.scaleToFitButton->setChecked(zoom == 0);
2084 ui.zoomButton->setChecked(zoom!=0);
2085 ui.zoomSpinBox->setValue(zoom ? qBound(25,zoom,2400) : 100);
2086 }
2087
2088
2089 void
2090 QDjViewPrnExporter::saveProperties(QString group)
2091 {
2092 QSettings s;
2093 if (group.isEmpty())
2094 group = "Export-" + name();
2095 s.beginGroup(group);
2096 s.setValue("color", ui.colorButton->isChecked());
2097 s.setValue("frame", ui.frameCheckBox->isChecked());
2098 s.setValue("autoOrient", ui.autoOrientCheckBox->isChecked());
2099 s.setValue("landscape", ui.landscapeButton->isChecked());
2100 int zoom = ui.zoomSpinBox->value();
2101 s.setValue("zoom", QVariant(ui.zoomButton->isChecked() ? zoom : 0));
2102 }
2103
2104
2105 bool
2106 QDjViewPrnExporter::loadPrintSetup(QPrinter *printer, QPrintDialog *)
2107 {
2108 bool grayscale = (printer->colorMode() == QPrinter::GrayScale);
2109 #if QT_VERSION >= 0x60000
2110 bool landscape = printer->pageLayout().orientation() == QPageLayout::Landscape;
2111 #else
2112 bool landscape = (printer->orientation() == QPrinter::Landscape);
2113 #endif
2114 ui.grayScaleButton->setChecked(grayscale);
2115 ui.colorButton->setChecked(!grayscale);
2116 ui.landscapeButton->setChecked(landscape);
2117 ui.portraitButton->setChecked(!landscape);
2118 return true;
2119 }
2120
2121
2122 bool
2123 QDjViewPrnExporter::savePrintSetup(QPrinter *printer)
2124 {
2125 bool grayscale = ui.grayScaleButton->isChecked();
2126 bool landscape = ui.landscapeButton->isChecked();
2127 printer->setColorMode(grayscale ? QPrinter::GrayScale : QPrinter::Color);
2128 #if QT_VERSION >= 0x60000
2129 printer->setPageOrientation(landscape ? QPageLayout::Landscape : QPageLayout::Portrait);
2130 #else
2131 printer->setOrientation(landscape ? QPrinter::Landscape : QPrinter::Portrait);
2132 #endif
2133 return true;
2134 }
2135
2136
2137 int
2138 QDjViewPrnExporter::propertyPages()
2139 {
2140 return 1;
2141 }
2142
2143
2144 QWidget*
2145 QDjViewPrnExporter::propertyPage(int num)
2146 {
2147 if (num == 0)
2148 return page;
2149 return 0;
2150 }
2151
2152
2153 bool
2154 QDjViewPrnExporter::save(QString fileName)
2155 {
2156 closeFile();
2157 this->fileName = fileName;
2158 printer = new QPrinter(QPrinter::HighResolution);
2159 printer->setOutputFileName(fileName);
2160 #if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
2161 printer->setOutputFormat(QPrinter::PdfFormat);
2162 #endif
2163 return start();
2164 }
2165
2166
2167 bool
2168 QDjViewPrnExporter::print(QPrinter *printer)
2169 {
2170 closeFile();
2171 this->printer = printer;
2172 return start();
2173 }
2174
2175
2176 void
2177 QDjViewPrnExporter::closeFile()
2178 {
2179 if (painter)
2180 delete painter;
2181 painter = 0;
2182 if (printer && !fileName.isEmpty())
2183 delete printer;
2184 printer = 0;
2185 if (curStatus > DDJVU_JOB_OK && !fileName.isEmpty())
2186 ::remove(QFile::encodeName(fileName).data());
2187 fileName = QString();
2188 }
2189
2190
2191 void
2192 QDjViewPrnExporter::doPage()
2193 {
2194 QDjVuPage *page = curPage;
2195 // determine zoom factor and rectangles
2196 ddjvu_rect_t rect;
2197 rect.x = rect.y = 0;
2198 rect.w = ddjvu_page_get_width(*page);
2199 rect.h = ddjvu_page_get_height(*page);
2200 #if QT_VERSION >= 0x60000
2201 QRect pageRect = printer->pageLayout().paintRectPixels(printer->resolution());
2202 #else
2203 QRect pageRect = printer->pageRect();
2204 #endif
2205 bool landscape = false;
2206 int prndpi = printer->resolution();
2207 int imgdpi = ddjvu_page_get_resolution(*page);
2208 if (ui.autoOrientCheckBox->isChecked())
2209 landscape = (rect.w > rect.h) ^ (pageRect.width() > pageRect.height());
2210 else if (ui.landscapeButton->isChecked())
2211 landscape = true;
2212 int printW = (landscape) ? pageRect.height() : pageRect.width();
2213 int printH = (landscape) ? pageRect.width() : pageRect.height();
2214 int targetW = (rect.w * prndpi + imgdpi/2 ) / imgdpi;
2215 int targetH = (rect.h * prndpi + imgdpi/2 ) / imgdpi;
2216 int zoom = 100;
2217 if (ui.zoomButton->isChecked())
2218 zoom = qBound(25, ui.zoomSpinBox->value(), 2400);
2219 else if (ui.scaleToFitButton->isChecked())
2220 zoom = qMin( printW * 100 / targetW, printH * 100 / targetH);
2221 targetW = targetW * zoom / 100;
2222 targetH = targetH * zoom / 100;
2223 int dpi = qMin(prndpi * zoom / 100, imgdpi);
2224 rect.w = ( rect.w * dpi + imgdpi/2 ) / imgdpi;
2225 rect.h = ( rect.h * dpi + imgdpi/2 ) / imgdpi;
2226 // create image
2227 QImage::Format imageFormat = QImage::Format_RGB32;
2228 if (ddjvu_page_get_type(*page) == DDJVU_PAGETYPE_BITONAL && dpi >= imgdpi)
2229 imageFormat = QImage::Format_Mono;
2230 else if (ui.grayScaleButton->isChecked())
2231 imageFormat = QImage::Format_Indexed8;
2232 QImage img(rect.w, rect.h, imageFormat);
2233 // render
2234 bool rendered = false;
2235 ddjvu_format_t *fmt = 0;
2236 ddjvu_render_mode_t mode = DDJVU_RENDER_COLOR;
2237 QDjViewPrefs *prefs = QDjViewPrefs::instance();
2238 if (imageFormat == QImage::Format_RGB32)
2239 {
2240 #if DDJVUAPI_VERSION < 18
2241 unsigned int masks[3] = { 0xff0000, 0xff00, 0xff };
2242 fmt = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 3, masks);
2243 #else
2244 unsigned int masks[4] = { 0xff0000, 0xff00, 0xff, 0xff000000 };
2245 fmt = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 4, masks);
2246 #endif
2247 if (prefs->printerGamma > 0)
2248 ddjvu_format_set_gamma(fmt, prefs->printerGamma);
2249 ddjvu_format_set_row_order(fmt, true);
2250 if (ddjvu_page_render(*page, mode, &rect, &rect, fmt,
2251 img.bytesPerLine(), (char*)img.bits() ))
2252 rendered = true;
2253 }
2254 else if (imageFormat == QImage::Format_Indexed8)
2255 {
2256 #if QT_VERSION >= 0x40600
2257 img.setColorCount(256);
2258 #else
2259 img.setNumColors(256);
2260 #endif
2261 for (int i=0; i<256; i++)
2262 img.setColor(i, qRgb(i,i,i));
2263 fmt = ddjvu_format_create(DDJVU_FORMAT_GREY8, 0, 0);
2264 if (prefs->printerGamma > 0)
2265 ddjvu_format_set_gamma(fmt, prefs->printerGamma);
2266 ddjvu_format_set_row_order(fmt, true);
2267 if (ddjvu_page_render(*page, mode, &rect, &rect, fmt,
2268 img.bytesPerLine(), (char*)img.bits() ))
2269 rendered = true;
2270 }
2271 else if (imageFormat == QImage::Format_Mono)
2272 {
2273 fmt = ddjvu_format_create(DDJVU_FORMAT_MSBTOLSB, 0, 0);
2274 ddjvu_format_set_row_order(fmt, true);
2275 if (ddjvu_page_render(*page, mode, &rect, &rect, fmt,
2276 img.bytesPerLine(), (char*)img.bits() ))
2277 rendered = true;
2278 if (rendered)
2279 img.invertPixels();
2280 }
2281 // prepare painter
2282 if (! painter)
2283 painter = new QPainter(printer);
2284 else
2285 printer->newPage();
2286 // prepare settings
2287 painter->save();
2288 if (landscape)
2289 {
2290 painter->translate(QPoint(pageRect.width(),0));
2291 painter->rotate(90);
2292 }
2293 painter->translate(qMax(0, (printW-targetW)/2), qMax(0, (printH-targetH)/2));
2294
2295 // print page
2296 QRect sourceRect(0,0,rect.w,rect.h);
2297 QRect targetRect(0,0,targetW,targetH);
2298 if (rendered)
2299 painter->drawImage(targetRect, img, sourceRect);
2300 QPen pen(Qt::black, 0, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin);
2301 painter->setPen(pen);
2302 painter->setBrush(Qt::NoBrush);
2303 if (ui.frameCheckBox->isChecked())
2304 painter->drawRect(targetRect);
2305 // finish
2306 painter->restore();
2307 if (! rendered)
2308 {
2309 QString pageName = djview->pageName(curPage->pageNo());
2310 error(tr("Cannot render page %1.").arg(pageName), __FILE__, __LINE__);
2311 }
2312 if (fmt)
2313 ddjvu_format_release(fmt);
2314 fmt = 0;
2315 }
2316
2317
2318
2319
2320
2321
2322 // ----------------------------------------
2323 // CREATEEXPORTERDATA
2324
2325
2326 static void
2327 createExporterData()
2328 {
2329 QDjViewDjVuExporter::setup();
2330 #if HAVE_TIFF2PDF
2331 QDjViewPdfExporter::setup();
2332 #endif
2333 #if HAVE_TIFF
2334 QDjViewTiffExporter::setup();
2335 #endif
2336 QDjViewPSExporter::setup();
2337 QDjViewImgExporter::setup();
2338 QDjViewPrnExporter::setup();
2339 }
2340
2341
2342
2343 // ----------------------------------------
2344 // MOC
2345
2346 #include "qdjviewexporters.moc"
2347
2348
2349
2350
2351
2352 /* -------------------------------------------------------------
2353 Local Variables:
2354 c++-font-lock-extra-types: ( "\\sw+_t" "[A-Z]\\sw*[a-z]\\sw*" )
2355 End:
2356 ------------------------------------------------------------- */