]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Cleanup LyXFunc::dispatch() following JMarc advice.
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "qt_helpers.h"
18 #include "GuiImage.h"
19 #include "GuiView.h"
20
21 #include "frontends/alert.h"
22 #include "frontends/Application.h"
23 #include "frontends/NoGuiFontLoader.h"
24 #include "frontends/NoGuiFontMetrics.h"
25 #include "frontends/FontLoader.h"
26 #include "frontends/FontMetrics.h"
27
28 #include "support/ExceptionMessage.h"
29 #include "support/FileName.h"
30 #include "support/lstrings.h"
31 #include "support/os.h"
32 #include "support/Package.h"
33
34 #include "Buffer.h"
35 #include "BufferList.h"
36 #include "BufferView.h"
37 #include "debug.h"
38 #include "Font.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "gettext.h"
42 #include "LyX.h"
43 #include "LyXFunc.h"
44 #include "LyXRC.h"
45 #include "Session.h"
46 #include "version.h"
47
48 #include <QApplication>
49 #include <QClipboard>
50 #include <QEventLoop>
51 #include <QFileOpenEvent>
52 #include <QLocale>
53 #include <QLibraryInfo>
54 #include <QPixmapCache>
55 #include <QRegExp>
56 #include <QSessionManager>
57 #include <QSocketNotifier>
58 #include <QTextCodec>
59 #include <QTimer>
60 #include <QTranslator>
61 #include <QWidget>
62
63 #ifdef Q_WS_X11
64 #include <X11/Xatom.h>
65 #include <X11/Xlib.h>
66 #undef CursorShape
67 #undef None
68 #endif
69
70 #include <boost/bind.hpp>
71
72 #include <exception>
73
74 using std::endl;
75 using std::map;
76 using std::string;
77 using std::vector;
78
79
80 namespace lyx {
81
82 frontend::Application * createApplication(int & argc, char * argv[])
83 {
84         return new frontend::GuiApplication(argc, argv);
85 }
86
87
88 namespace frontend {
89
90 class SocketNotifier : public QSocketNotifier
91 {
92 public:
93         /// connect a connection notification from the LyXServerSocket
94         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
95                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
96         {}
97
98 public:
99         /// The callback function
100         Application::SocketCallback func_;
101 };
102
103
104 ////////////////////////////////////////////////////////////////////////
105 // Mac specific stuff goes here...
106
107 class MenuTranslator : public QTranslator
108 {
109 public:
110         MenuTranslator(QObject * parent)
111                 : QTranslator(parent)
112         {}
113
114         QString translate(const char * /*context*/, 
115           const char * sourceText, 
116           const char * /*comment*/ = 0) 
117         {
118                 string const s = sourceText;
119                 if (s == N_("About %1") || s == N_("Preferences") 
120                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
121                         return qt_(s);
122                 else 
123                         return QString();
124         }
125 };
126
127
128 ///////////////////////////////////////////////////////////////
129 // You can find more platform specific stuff
130 // at the end of this file...
131 ///////////////////////////////////////////////////////////////
132
133
134 using support::FileName;
135
136 GuiApplication * guiApp;
137
138
139 GuiApplication::GuiApplication(int & argc, char ** argv)
140         : QApplication(argc, argv), Application(), current_view_(0)
141 {
142         QString app_name = "LyX";
143         QCoreApplication::setOrganizationName(app_name);
144         QCoreApplication::setOrganizationDomain("lyx.org");
145         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
146
147         // Qt bug? setQuitOnLastWindowClosed(true); does not work
148         setQuitOnLastWindowClosed(false);
149
150 #ifdef Q_WS_X11
151         // doubleClickInterval() is 400 ms on X11 which is just too long.
152         // On Windows and Mac OS X, the operating system's value is used.
153         // On Microsoft Windows, calling this function sets the double
154         // click interval for all applications. So we don't!
155         QApplication::setDoubleClickInterval(300);
156 #endif
157
158         // install translation file for Qt built-in dialogs
159         QString language_name = QString("qt_") + QLocale::system().name();
160         
161         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
162         // Short-named translator can be loaded from a long name, but not the
163         // opposite. Therefore, long name should be used without truncation.
164         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
165         if (qt_trans_.load(language_name,
166                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
167         {
168                 installTranslator(&qt_trans_);
169                 // even if the language calls for RtL, don't do that
170                 setLayoutDirection(Qt::LeftToRight);
171                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
172                         << fromqstr(language_name));
173         } else
174                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
175                         << fromqstr(language_name));
176
177 #ifdef Q_WS_MACX
178         // This allows to translate the strings that appear in the LyX menu.
179         addMenuTranslator();
180 #endif
181
182         using namespace lyx::graphics;
183
184         Image::newImage = boost::bind(&GuiImage::newImage);
185         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
186
187         // needs to be done before reading lyxrc
188         QWidget w;
189         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
190
191         guiApp = this;
192
193         // Set the cache to 5120 kilobytes which corresponds to screen size of
194         // 1280 by 1024 pixels with a color depth of 32 bits.
195         QPixmapCache::setCacheLimit(5120);
196
197         // Initialize RC Fonts
198         if (lyxrc.roman_font_name.empty())
199                 lyxrc.roman_font_name = fromqstr(romanFontName());
200
201         if (lyxrc.sans_font_name.empty())
202                 lyxrc.sans_font_name = fromqstr(sansFontName());
203
204         if (lyxrc.typewriter_font_name.empty())
205                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
206 }
207
208
209 GuiApplication::~GuiApplication()
210 {
211         socket_notifiers_.clear();
212 }
213
214
215 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
216 {
217         FuncStatus flag;
218         bool enable = true;
219
220         switch(cmd.action) {
221
222         case LFUN_WINDOW_CLOSE:
223                 enable = view_ids_.size() > 0;
224                 break;
225
226         default:
227                 if (!current_view_) {
228                         enable = false;
229                         break;
230                 }
231         }
232
233         if (!enable)
234                 flag.enabled(false);
235
236         return flag;
237 }
238
239         
240 bool GuiApplication::dispatch(FuncRequest const & cmd)
241 {
242         switch(cmd.action) {
243
244         case LFUN_WINDOW_NEW:
245                 createView(toqstr(cmd.argument()));
246                 break;
247
248         case LFUN_WINDOW_CLOSE:
249                 // update bookmark pit of the current buffer before window close
250                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
251                         theLyXFunc().gotoBookmark(i+1, false, false);
252                 // ask the user for saving changes or cancel quit
253                 if (!theBufferList().quitWriteAll())
254                         break;
255                 current_view_->close();
256                 break;
257
258         case LFUN_LYX_QUIT:
259                 // quitting is triggered by the gui code
260                 // (leaving the event loop).
261                 current_view_->message(from_utf8(N_("Exiting.")));
262                 if (theBufferList().quitWriteAll())
263                         closeAllViews();
264                 break;
265
266         case LFUN_SCREEN_FONT_UPDATE: {
267                 // handle the screen font changes.
268                 font_loader_.update();
269                 // Backup current_view_
270                 GuiView * view = current_view_;
271                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
272                 // to skip the refresh.
273                 current_view_ = 0;
274                 BufferList::iterator it = theBufferList().begin();
275                 BufferList::iterator const end = theBufferList().end();
276                 for (; it != end; ++it)
277                         (*it)->changed();
278                 // Restore current_view_
279                 current_view_ = view;
280                 break;
281         }
282
283         default:
284                 // Notify the caller that the action has not been dispatched.
285                 return false;
286         }
287
288         // The action has been dispatched.
289         return true;
290 }
291
292
293 void GuiApplication::resetGui()
294 {
295         map<int, GuiView *>::iterator it;
296         for (it = views_.begin(); it != views_.end(); ++it)
297                 it->second->resetDialogs();
298
299         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
300 }
301
302
303 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
304 {
305         ids.clear();
306         map<int, GuiView *>::const_iterator it;
307         for (it = stdmap.begin(); it != stdmap.end(); ++it)
308                 ids.push_back(it->first);
309 }
310
311
312 void GuiApplication::createView(QString const & geometry_arg)
313 {
314         updateIds(views_, view_ids_);
315         int id = 0;
316         while (views_.find(id) != views_.end())
317                 id++;
318         views_[id] = new GuiView(id);
319         updateIds(views_, view_ids_);
320
321         GuiView * view  = views_[id];
322         theLyXFunc().setLyXView(view);
323
324         view->show();
325         if (!geometry_arg.isEmpty()) {
326 #ifdef Q_WS_WIN
327                 int x, y;
328                 int w, h;
329                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
330                 re.indexIn(geometry_arg);
331                 w = re.cap(1).toInt();
332                 h = re.cap(2).toInt();
333                 x = re.cap(3).toInt();
334                 y = re.cap(4).toInt();
335                 view->setGeometry(x, y, w, h);
336 #endif
337         }
338         view->setFocus();
339
340         setCurrentView(*view);
341 }
342
343
344
345
346 Clipboard & GuiApplication::clipboard()
347 {
348         return clipboard_;
349 }
350
351
352 Selection & GuiApplication::selection()
353 {
354         return selection_;
355 }
356
357
358 int GuiApplication::exec()
359 {
360         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
361         return QApplication::exec();
362 }
363
364
365 void GuiApplication::exit(int status)
366 {
367         QApplication::exit(status);
368 }
369
370
371 void GuiApplication::execBatchCommands()
372 {
373         LyX::ref().execBatchCommands();
374 }
375
376
377 QString const GuiApplication::romanFontName()
378 {
379         QFont font;
380         font.setKerning(false);
381         font.setStyleHint(QFont::Serif);
382         font.setFamily("serif");
383
384         return QFontInfo(font).family();
385 }
386
387
388 QString const GuiApplication::sansFontName()
389 {
390         QFont font;
391         font.setKerning(false);
392         font.setStyleHint(QFont::SansSerif);
393         font.setFamily("sans");
394
395         return QFontInfo(font).family();
396 }
397
398
399 QString const GuiApplication::typewriterFontName()
400 {
401         QFont font;
402         font.setKerning(false);
403         font.setStyleHint(QFont::TypeWriter);
404         font.setFamily("monospace");
405
406         return QFontInfo(font).family();
407 }
408
409
410 bool GuiApplication::event(QEvent * e)
411 {
412         switch(e->type()) {
413         case QEvent::FileOpen: {
414                 // Open a file; this happens only on Mac OS X for now
415                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
416
417                 if (!current_view_ || !current_view_->view())
418                         // The application is not properly initialized yet.
419                         // So we acknowledge the event and delay the file opening
420                         // until LyX is ready.
421                         // FIXME UNICODE: FileName accept an utf8 encoded string.
422                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
423                 else
424                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
425                                 qstring_to_ucs4(foe->file())));
426
427                 e->accept();
428                 return true;
429         }
430         default:
431                 return QApplication::event(e);
432         }
433 }
434
435
436 bool GuiApplication::notify(QObject * receiver, QEvent * event)
437 {
438         try {
439                 return QApplication::notify(receiver, event);
440         }
441         catch (support::ExceptionMessage const & e) {
442                 if (e.type_ == support::ErrorException) {
443                         Alert::error(e.title_, e.details_);
444                         LyX::cref().emergencyCleanup();
445                         QApplication::exit(1);
446                 } else if (e.type_ == support::WarningException) {
447                         Alert::warning(e.title_, e.details_);
448                         return false;
449                 }
450         }
451         catch (std::exception const & e) {
452                 docstring s = _("LyX has caught an exception, it will now "
453                         "attemp to save all unsaved documents and exit."
454                         "\n\nException: ");
455                 s += from_ascii(e.what());
456                 Alert::error(_("Software exception Detected"), s);
457                 LyX::cref().emergencyCleanup();
458                 QApplication::exit(1);
459         }
460         catch (...) {
461                 docstring s = _("LyX has caught some really weird exception, it will "
462                         "now attemp to save all unsaved documents and exit.");
463                 Alert::error(_("Software exception Detected"), s);
464                 LyX::cref().emergencyCleanup();
465                 QApplication::exit(1);
466         }
467
468         return false;
469 }
470
471
472 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
473 {
474         QColor const & qcol = color_cache_.get(col);
475         if (!qcol.isValid()) {
476                 rgbcol.r = 0;
477                 rgbcol.g = 0;
478                 rgbcol.b = 0;
479                 return false;
480         }
481         rgbcol.r = qcol.red();
482         rgbcol.g = qcol.green();
483         rgbcol.b = qcol.blue();
484         return true;
485 }
486
487
488 string const GuiApplication::hexName(ColorCode col)
489 {
490         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
491 }
492
493
494 void GuiApplication::updateColor(ColorCode)
495 {
496         // FIXME: Bleh, can't we just clear them all at once ?
497         color_cache_.clear();
498 }
499
500
501 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
502 {
503         SocketNotifier * sn = new SocketNotifier(this, fd, func);
504         socket_notifiers_[fd] = sn;
505         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
506 }
507
508
509 void GuiApplication::socketDataReceived(int fd)
510 {
511         socket_notifiers_[fd]->func_();
512 }
513
514
515 void GuiApplication::unregisterSocketCallback(int fd)
516 {
517         socket_notifiers_.erase(fd);
518 }
519
520
521 void GuiApplication::commitData(QSessionManager & sm)
522 {
523         /// The implementation is required to avoid an application exit
524         /// when session state save is triggered by session manager.
525         /// The default implementation sends a close event to all
526         /// visible top level widgets when session managment allows
527         /// interaction.
528         /// We are changing that to write all unsaved buffers...
529         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
530                 sm.cancel();
531 }
532
533
534 void GuiApplication::addMenuTranslator()
535 {
536         installTranslator(new MenuTranslator(this));
537 }
538
539
540 bool GuiApplication::unregisterView(int id)
541 {
542         updateIds(views_, view_ids_);
543         BOOST_ASSERT(views_.find(id) != views_.end());
544         BOOST_ASSERT(views_[id]);
545
546         map<int, GuiView *>::iterator it;
547         for (it = views_.begin(); it != views_.end(); ++it) {
548                 if (it->first == id) {
549                         views_.erase(id);
550                         break;
551                 }
552         }
553         updateIds(views_, view_ids_);
554         return true;
555 }
556
557
558 bool GuiApplication::closeAllViews()
559 {
560         updateIds(views_, view_ids_);
561         if (views_.empty()) {
562                 // quit in CloseEvent will not be triggert
563                 qApp->quit();
564                 return true;
565         }
566
567         map<int, GuiView*> const cmap = views_;
568         map<int, GuiView*>::const_iterator it;
569         for (it = cmap.begin(); it != cmap.end(); ++it) {
570                 // TODO: return false when close event was ignored
571                 //       e.g. quitWriteAll()->'Cancel'
572                 //       maybe we need something like 'bool closeView()'
573                 it->second->close();
574                 // unregisterd by the CloseEvent
575         }
576
577         views_.clear();
578         view_ids_.clear();
579         return true;
580 }
581
582
583 GuiView & GuiApplication::view(int id) const
584 {
585         BOOST_ASSERT(views_.find(id) != views_.end());
586         return *views_.find(id)->second;
587 }
588
589
590 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
591 {
592         vector<int>::const_iterator it = view_ids_.begin();
593         vector<int>::const_iterator const end = view_ids_.end();
594         for (; it != end; ++it)
595                 view(*it).hideDialog(name, inset);
596 }
597
598
599 Buffer const * GuiApplication::updateInset(Inset const * inset) const
600 {
601         Buffer const * buffer_ = 0;
602         vector<int>::const_iterator it = view_ids_.begin();
603         vector<int>::const_iterator const end = view_ids_.end();
604         for (; it != end; ++it) {
605                 Buffer const * ptr = view(*it).updateInset(inset);
606                 if (ptr)
607                         buffer_ = ptr;
608         }
609         return buffer_;
610 }
611
612
613 ////////////////////////////////////////////////////////////////////////
614 // X11 specific stuff goes here...
615 #ifdef Q_WS_X11
616 bool GuiApplication::x11EventFilter(XEvent * xev)
617 {
618         if (!current_view_)
619                 return false;
620
621         switch (xev->type) {
622         case SelectionRequest: {
623                 if (xev->xselectionrequest.selection != XA_PRIMARY)
624                         break;
625                 LYXERR(Debug::GUI, "X requested selection.");
626                 BufferView * bv = current_view_->view();
627                 if (bv) {
628                         docstring const sel = bv->requestSelection();
629                         if (!sel.empty())
630                                 selection_.put(sel);
631                 }
632                 break;
633         }
634         case SelectionClear: {
635                 if (xev->xselectionclear.selection != XA_PRIMARY)
636                         break;
637                 LYXERR(Debug::GUI, "Lost selection.");
638                 BufferView * bv = current_view_->view();
639                 if (bv)
640                         bv->clearSelection();
641                 break;
642         }
643         }
644         return false;
645 }
646 #endif
647
648 } // namespace frontend
649
650
651 ////////////////////////////////////////////////////////////////////
652 //
653 // Font stuff
654 //
655 ////////////////////////////////////////////////////////////////////
656
657 frontend::FontLoader & theFontLoader()
658 {
659         static frontend::NoGuiFontLoader no_gui_font_loader;
660
661         if (!use_gui)
662                 return no_gui_font_loader;
663
664         BOOST_ASSERT(frontend::guiApp);
665         return frontend::guiApp->fontLoader();
666 }
667
668
669 frontend::FontMetrics const & theFontMetrics(Font const & f)
670 {
671         return theFontMetrics(f.fontInfo());
672 }
673
674
675 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
676 {
677         static frontend::NoGuiFontMetrics no_gui_font_metrics;
678
679         if (!use_gui)
680                 return no_gui_font_metrics;
681
682         BOOST_ASSERT(frontend::guiApp);
683         return frontend::guiApp->fontLoader().metrics(f);
684 }
685
686
687 frontend::Clipboard & theClipboard()
688 {
689         BOOST_ASSERT(frontend::guiApp);
690         return frontend::guiApp->clipboard();
691 }
692
693
694 frontend::Selection & theSelection()
695 {
696         BOOST_ASSERT(frontend::guiApp);
697         return frontend::guiApp->selection();
698 }
699
700 } // namespace lyx
701
702 #include "GuiApplication_moc.cpp"