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