Debian Codegraph @

src/djview.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 #endif
21
22 #include <libdjvu/ddjvuapi.h>
23 #include <libdjvu/miniexp.h>
24 #include <locale.h>
25 #include <stdio.h>
26
27 #include "qdjvu.h"
28 #include "qdjview.h"
29 #include "qdjvuwidget.h"
30 #include "djview.h"
31 #ifndef NPDJVU
32 # include "qdjviewplugin.h"
33 #endif
34
35 #include <QtGlobal>
36 #include <QApplication>
37 #include <QByteArray>
38 #include <QDebug>
39 #include <QDir>
40 #include <QFileOpenEvent>
41 #include <QLibraryInfo>
42 #include <QLocale>
43 #include <QRegExp>
44 #include <QSettings>
45 #include <QSessionManager>
46 #include <QString>
47 #include <QStringList>
48 #include <QTranslator>
49 #if QT_VERSION >= 0x60000
50 # define reReplace(s,r,a) (r).replaceIn((s),(a))
51 # define reIndex(s,r,p) (r).indexIn((s),(p))
52 #else
53 # define reReplace(s,r,a) (s).replace((r),(a))
54 # define reIndex(s,r,p) (s).indexOf((r),(p))
55 #endif
56
57 #if defined(Q_OS_WIN32)
58 # include <mbctype.h>
59 #endif
60
61
62 #ifdef QT_NO_DEBUG
63 static bool verbose = false;
64 #else
65 static bool verbose = true;
66 #endif
67 static bool appReady = false;
68
69 static void
70 qt4MessageHandler(QtMsgType type, const char *msg)
71 {
72 switch (type)
73 {
74 case QtFatalMsg:
75 fprintf(stderr,"djview fatal error: %s\n", msg);
76 abort();
77 case QtCriticalMsg:
78 fprintf(stderr,"djview critical error: %s\n", msg);
79 break;
80 case QtWarningMsg:
81 if (verbose || !appReady)
82 fprintf(stderr,"djview: %s\n", msg);
83 break;
84 default:
85 if (verbose || !appReady)
86 fprintf(stderr,"%s\n", msg);
87 break;
88 }
89 }
90
91 #if QT_VERSION >= 0x50000
92 static void
93 qt5MessageHandler(QtMsgType type, const QMessageLogContext&, const QString &msg)
94 {
95 QByteArray bmsg = msg.toLocal8Bit();
96 qt4MessageHandler(type, bmsg.data());
97 }
98 #endif
99
100
101 static void
102 message(QString string, bool prefix=true)
103 {
104 QByteArray m = string.toLocal8Bit();
105 if (prefix)
106 fprintf(stderr, "djview: ");
107 fprintf(stderr, "%s\n", (const char*) m);
108 }
109
110 static void
111 message(QStringList sl)
112 {
113 foreach (QString s, sl)
114 message(s);
115 }
116
117 QDjViewApplication::QDjViewApplication(int &argc, char **argv)
118 : QApplication(argc, argv),
119 context(argv[0])
120 {
121 // Message handler
122 #if QT_VERSION >= 0x50000
123 qInstallMessageHandler(qt5MessageHandler);
124 #else
125 qInstallMsgHandler(qt4MessageHandler);
126 #endif
127
128 // Locale should not mess with printf
129 // We do this again because old libdjvulibre
130 // did not correctly set LC_NUMERIC.
131 #ifdef LC_ALL
132 ::setlocale(LC_ALL, "");
133 # ifdef LC_NUMERIC
134 ::setlocale(LC_NUMERIC, "C");
135 # endif
136 #endif
137
138 // Parse arguments using OEM code page under windows.
139 #if defined(Q_OS_WIN32)
140 _setmbcp(_MB_CP_OEM);
141 #endif
142 // Mac/Cocoa bug workaround
143 #if defined(Q_OS_DARWIN) && defined(QT_MAC_USE_COCOA) && QT_VERSION<0x40503
144 extern void qt_mac_set_native_menubar(bool);
145 qt_mac_set_native_menubar(false);
146 #endif
147
148 // Enable highdpi pixmaps
149 #if QT_VERSION >= 0x50200 && QT_VERSION < 0x60000
150 setAttribute(Qt::AA_UseHighDpiPixmaps, true);
151 #endif
152
153 // Tooltip opacity
154 #if QT_VERSION >= 0x60000
155 setStyleSheet("QToolTip {opacity: 250;}");
156 #endif
157
158 // Wire session management signals
159 connect(this, SIGNAL(saveStateRequest(QSessionManager&)),
160 this, SLOT(saveSessionState(QSessionManager&)) );
161
162 // Install translators
163 QStringList langs = getTranslationLangs();
164 QTranslator *djviewTrans = new QTranslator(this);
165 QTranslator *qtTrans = new QTranslator(this);
166 if (loadTranslators(langs, djviewTrans, qtTrans))
167 {
168 installTranslator(qtTrans);
169 installTranslator(djviewTrans);
170 }
171 else
172 {
173 delete qtTrans;
174 delete djviewTrans;
175 }
176 // Application is ready
177 appReady = true;
178 }
179
180
181 QDjView *
182 QDjViewApplication::newWindow()
183 {
184 if (lastWindow && !lastWindow->getDocument())
185 return lastWindow;
186 QDjView *main = new QDjView(context);
187 main->setAttribute(Qt::WA_DeleteOnClose);
188 lastWindow = main;
189 return main;
190 }
191
192
193 static void
194 addDirectory(QStringList &dirs, QString path)
195 {
196 QString dirname = QDir::cleanPath(path);
197 if (! dirs.contains(dirname))
198 dirs << dirname;
199 }
200
201
202 QStringList
203 QDjViewApplication::getTranslationDirs()
204 {
205 if (translationDirs.isEmpty())
206 {
207 QStringList dirs;
208 QDir dir = applicationDirPath();
209 QString dirPath = dir.canonicalPath();
210 addDirectory(dirs, dirPath);
211 #ifdef DIR_DATADIR
212 QString datadir = DIR_DATADIR;
213 addDirectory(dirs, datadir + "/djvu/djview4");
214 addDirectory(dirs, datadir + "/djview4");
215 #endif
216 #ifdef Q_OS_DARWIN
217 addDirectory(dirs, dirPath + "/Resources/$LANG.lproj");
218 addDirectory(dirs, dirPath + "/../Resources/$LANG.lproj");
219 addDirectory(dirs, dirPath + "/../../Resources/$LANG.lproj");
220 #endif
221 addDirectory(dirs, dirPath + "/share/djvu/djview4");
222 addDirectory(dirs, dirPath + "/share/djview4");
223 addDirectory(dirs, dirPath + "/../share/djvu/djview4");
224 addDirectory(dirs, dirPath + "/../share/djview4");
225 addDirectory(dirs, dirPath + "/../../share/djvu/djview4");
226 addDirectory(dirs, dirPath + "/../../share/djview4");
227 addDirectory(dirs, "/usr/share/djvu/djview4");
228 addDirectory(dirs, "/usr/share/djview4");
229 #if QT_VERSION >= 0x68000
230 foreach(QString dir, QLibraryInfo::paths(QLibraryInfo::TranslationsPath))
231 addDirectory(dirs, dir);
232 #elif QT_VERSION >= 0x60000
233 addDirectory(dirs, QLibraryInfo::path(QLibraryInfo::TranslationsPath));
234 #else
235 addDirectory(dirs, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
236 #endif
237 translationDirs = dirs;
238 }
239 return translationDirs;
240 }
241
242
243 static void
244 addLang(QStringList &langs, QString s)
245 {
246 if (s.size() > 0)
247 {
248 s = s.replace(QChar('-'), QChar('_'));
249 if (! langs.contains(s))
250 langs << s;
251 #ifdef Q_OS_DARWIN
252 if (s == "zh_Hans" && ! langs.contains("zh_CN"))
253 langs << "zh_CN";
254 if (s == "zh_Hant" && ! langs.contains("zh_TW"))
255 langs << "zh_TW";
256 #endif
257 }
258 }
259
260
261 QStringList
262 QDjViewApplication::getTranslationLangs()
263 {
264 if (translationLangs.isEmpty())
265 {
266 QStringList langs;
267 addLang(langs, QSettings().value("language").toString());
268 QString varLanguage = QString::fromLocal8Bit(::getenv("LANGUAGE"));
269 foreach(QString lang, varLanguage.split(":"))
270 if (! lang.isEmpty())
271 addLang(langs, lang);
272 #ifdef LC_MESSAGES
273 addLang(langs, QString::fromLocal8Bit(::setlocale(LC_MESSAGES, 0)));
274 #endif
275 addLang(langs, QString::fromLocal8Bit(::getenv("LANG")));
276 #ifdef Q_OS_DARWIN
277 QSettings g(".", "globalPreferences");
278 foreach (QString lang, g.value("AppleLanguages").toStringList())
279 addLang(langs, lang);
280 #endif
281 addLang(langs, QLocale::system().name());
282 translationLangs = langs;
283 }
284 return translationLangs;
285 }
286
287
288 static bool loadOneTranslator(QTranslator *trans,
289 QString name, QString lang, QStringList dirs)
290 {
291 foreach (QString dir, dirs)
292 {
293 QRegExp relang = QRegExp("\\$LANG(?!\\w)");
294 QString llang = lang.toLower();
295 if (reIndex(dir, relang, 0) >= 0) {
296 QString delims = "-_.";
297 QString d = reReplace(dir, relang, llang);
298 while (! QDir(d).exists() ) {
299 int k = -1;
300 for (int i=0; i<(int)delims.length(); i++) {
301 int j = llang.lastIndexOf(delims[i]);
302 if (j > k)
303 k = j;
304 }
305 if (k > 0)
306 llang.truncate(k);
307 else
308 break;
309 }
310 dir = reReplace(dir, relang, llang);
311 }
312 if (QDir(dir).exists())
313 {
314 if (trans->load(name + "_" + lang, dir, "_.-"))
315 return true;
316 QString llang = lang.toLower();
317 if (lang != llang && trans->load(name + "_" + llang, dir, "_.-"))
318 return true;
319 }
320 }
321 return false;
322 }
323
324 bool
325 QDjViewApplication::loadTranslators(QStringList langs,
326 QTranslator *dTrans, QTranslator *qTrans)
327 {
328 QStringList dirs = getTranslationDirs();
329 foreach (QString lang, langs)
330 {
331 if (dTrans && dTrans->isEmpty())
332 loadOneTranslator(dTrans, "djview", lang, dirs);
333 if (qTrans && qTrans->isEmpty())
334 loadOneTranslator(qTrans, "qt", lang, dirs);
335 if (!(dTrans && dTrans->isEmpty()) && !(qTrans && qTrans->isEmpty()))
336 return true;
337 if (lang.startsWith("en_") || lang == "en")
338 break;
339 }
340 if (dTrans && !dTrans->isEmpty())
341 return true;
342 return false;
343 }
344
345
346 bool
347 QDjViewApplication::event(QEvent *ev)
348 {
349 if (ev->type() == QEvent::FileOpen)
350 {
351 QString name = static_cast<QFileOpenEvent*>(ev)->file();
352 QDjView *main = newWindow();
353 if (main->open(name))
354 {
355 main->show();
356 }
357 else
358 {
359 message(tr("cannot open '%1'.").arg(name));
360 delete main;
361 }
362 return true;
363 }
364 else if (ev->type() == QEvent::Close)
365 {
366 closeAllWindows();
367 }
368 return QApplication::event(ev);
369 }
370
371 void
372 QDjViewApplication::saveSessionState(QSessionManager &sm)
373 {
374 int n = 0;
375 QSettings s;
376 foreach(QWidget *w, topLevelWidgets())
377 {
378 QDjView *djview = qobject_cast<QDjView*>(w);
379 if (djview && !djview->objectName().isEmpty() &&
380 djview->getViewerMode() == QDjView::STANDALONE )
381 {
382 if (++n == 1)
383 {
384 QStringList discard = QStringList(applicationFilePath());
385 discard << QLatin1String("-discard") << sessionId();
386 sm.setDiscardCommand(discard);
387 QStringList restart = QStringList(applicationFilePath());
388 restart << QLatin1String("-session");
389 restart << sessionId() + "_" + sessionKey();
390 sm.setRestartCommand(restart);
391 QString id = QLatin1String("session_") + sessionId();
392 s.sync();
393 s.remove(id);
394 s.beginGroup(id);
395 }
396 s.beginGroup(QString::number(n));
397 djview->saveSession(&s);
398 s.endGroup();
399 }
400 }
401 if (n > 0)
402 {
403 s.setValue("windows", n);
404 s.endGroup();
405 s.sync();
406 }
407 }
408
409
410 #ifndef NPDJVU
411
412 static void
413 usage()
414 {
415 QString msg = QDjViewApplication::tr
416 ("Usage: djview [options] [filename-or-url]\n"
417 "Common options include:\n"
418 "-help~~~Prints this message.\n"
419 "-verbose~~~Prints all warning messages.\n"
420 "-display <xdpy>~~~Select the X11 display <xdpy>.\n"
421 "-geometry <xgeom>~~~Select the initial window geometry.\n"
422 "-font <xlfd>~~~Select the X11 name of the main font.\n"
423 "-style <qtstyle>~~~Select the QT user interface style.\n"
424 "-fullscreen, -fs~~~Start djview in full screen mode.\n"
425 "-page=<page>~~~Jump to page <page>.\n"
426 "-zoom=<zoom>~~~Set zoom factor.\n"
427 "-continuous=<yn>~~~Set continuous layout.\n"
428 "-sidebyside=<yn>~~~Set side-by-side layout.\n" );
429
430 // align tabs
431 QStringList opts = msg.split("\n");
432 int tab = 0;
433 foreach (QString s, opts)
434 tab = qMax(tab, s.indexOf("~~~"));
435 foreach (QString s, opts)
436 {
437 int pos = s.indexOf("~~~");
438 if (pos >= 0)
439 s = QString(" %1 %2").arg(s.left(pos), -tab).arg(s.mid(pos+3));
440 message(s, false);
441 }
442 exit(10);
443 }
444
445
446 int
447 main(int argc, char *argv[])
448 {
449 // Application data
450 QApplication::setOrganizationName(DJVIEW_ORG);
451 QApplication::setOrganizationDomain(DJVIEW_DOMAIN);
452 QApplication::setApplicationName(DJVIEW_APP);
453
454 // Message handler
455 #if QT_VERSION >= 0x50000
456 qInstallMessageHandler(qt5MessageHandler);
457 #else
458 qInstallMsgHandler(qt4MessageHandler);
459 #endif
460
461 // Set verbose flag as early as possible
462 #ifdef Q_OS_UNIX
463 const char *s = ::getenv("DJVIEW_VERBOSE");
464 if (s && strcmp(s,"0"))
465 verbose = true;
466 #endif
467 for (int i=1; i<argc; i++)
468 {
469 char *s = argv[i];
470 while (s && *s=='-')
471 s++;
472 if (! strcmp(s, "verbose"))
473 verbose = true;
474 }
475
476 // Color specification
477 // (cause XRender errors under many versions of Qt4/X11)
478 #ifndef Q_WS_X11
479 # if QT_VERSION < 0x50000
480 QApplication::setColorSpec(QApplication::ManyColor);
481 # endif
482 #endif
483
484 // Plugin mode
485 #if WITH_DJVIEWPLUGIN
486 if (argc==2 && !strcmp(argv[1],"-netscape"))
487 {
488 verbose = true;
489 QDjViewPlugin dispatcher(argv[0]);
490 return dispatcher.exec();
491 }
492 #endif
493
494 // Discard session
495 if (argc==3 && !strcmp(argv[1],"-discard"))
496 {
497 QSettings s;
498 s.remove(QLatin1String("session_")+QLatin1String(argv[2]));
499 s.sync();
500 return 0;
501 }
502
503 // Create application
504 QDjViewApplication app(argc, argv);
505
506 // Restore session
507 if (app.isSessionRestored())
508 {
509 QSettings s;
510 s.beginGroup(QLatin1String("session_") + app.sessionId());
511 int windows = s.value("windows").toInt();
512 if (windows > 0)
513 {
514 for (int n=1; n<=windows; n++)
515 {
516 QDjView *w = new QDjView(*app.djvuContext());
517 w->setAttribute(Qt::WA_DeleteOnClose);
518 s.beginGroup(QString::number(n));
519 w->restoreSession(&s);
520 s.endGroup();
521 w->show();
522 }
523 return app.exec();
524 }
525 }
526
527 // Process command line (from QCoreApplication for win unicode)
528 QStringList args;
529 QDjView *main = app.newWindow();
530 QStringList qargv = QCoreApplication::arguments();
531 int qi = 1;
532 while (qi < qargv.size() && qargv.at(qi)[0] == '-')
533 {
534 QString arg = qargv.at(qi);
535 arg = reReplace(arg, QRegExp("^-+"),"");
536 QString key = arg.section(QChar('='),0,1);
537 if (arg == "help")
538 usage();
539 else if (arg == "verbose")
540 verbose = true;
541 else if (arg == "quiet")
542 verbose = false;
543 else if (arg == "fix")
544 message(QApplication::tr("Option '-fix' is deprecated."));
545 else
546 args += arg;
547 qi += 1;
548 }
549 if (qi < qargv.size() - 1)
550 usage();
551
552 // Open file
553 if (qi == qargv.size() - 1)
554 {
555 QString name = qargv.at(qi);
556 bool okay = true;
557 if (reIndex(name, QRegExp("^[a-zA-Z]{3,8}:/"), 0) >= 0)
558 okay = main->open(QUrl(name));
559 else
560 okay = main->open(name);
561 if (! okay)
562 {
563 message(QDjView::tr("cannot open '%1'.").arg(name));
564 exit(10);
565 }
566 }
567
568 // Process options and go
569 foreach(QString arg, args)
570 message(main->parseArgument(arg));
571 main->show();
572 return app.exec();
573 }
574
575 #endif
576
577
578 /* -------------------------------------------------------------
579 Local Variables:
580 c++-font-lock-extra-types: ( "\\sw+_t" "[A-Z]\\sw*[a-z]\\sw*" )
581 End:
582 ------------------------------------------------------------- */