]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Encapsulate all menu related stuff inside Menu.cpp and simplify a few things.
[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 "LyX.h"
33 #include "LyXFunc.h"
34 #include "LyXRC.h"
35 #include "Session.h"
36 #include "version.h"
37
38 #include "support/debug.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/FileName.h"
41 #include "support/ForkedCalls.h"
42 #include "support/gettext.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         //FIXME: quitOnLastWindowClosed is true by default, at least on Windows and
143         // X11 platforms. We should have a lyxrc setting for this in order to let the
144         // application stay resident.
145         /*
146         if (lyxrc.quit_on_last_window_closed)
147                 setQuitOnLastWindowClosed(false);
148         */
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         // all windows in a Mac application share the same menu bar.
179         QMenuBar *menuBar = new QMenuBar(0);
180         // This allows to translate the strings that appear in the LyX menu.
181         addMenuTranslator();
182 #endif
183
184         using namespace lyx::graphics;
185
186         Image::newImage = boost::bind(&GuiImage::newImage);
187         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
188
189         // needs to be done before reading lyxrc
190         QWidget w;
191         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
192
193         guiApp = this;
194
195         // Set the cache to 5120 kilobytes which corresponds to screen size of
196         // 1280 by 1024 pixels with a color depth of 32 bits.
197         QPixmapCache::setCacheLimit(5120);
198
199         // Initialize RC Fonts
200         if (lyxrc.roman_font_name.empty())
201                 lyxrc.roman_font_name = fromqstr(romanFontName());
202
203         if (lyxrc.sans_font_name.empty())
204                 lyxrc.sans_font_name = fromqstr(sansFontName());
205
206         if (lyxrc.typewriter_font_name.empty())
207                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
208
209         general_timer_.setInterval(500);
210         connect(&general_timer_, SIGNAL(timeout()),
211                 this, SLOT(handleRegularEvents()));
212         general_timer_.start();
213 }
214
215
216 GuiApplication::~GuiApplication()
217 {
218         socket_notifiers_.clear();
219 }
220
221
222 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
223 {
224         FuncStatus flag;
225         bool enable = true;
226
227         switch(cmd.action) {
228
229         case LFUN_WINDOW_CLOSE:
230                 enable = view_ids_.size() > 0;
231                 break;
232
233         default:
234                 if (!current_view_) {
235                         enable = false;
236                         break;
237                 }
238         }
239
240         if (!enable)
241                 flag.enabled(false);
242
243         return flag;
244 }
245
246         
247 bool GuiApplication::dispatch(FuncRequest const & cmd)
248 {
249         switch(cmd.action) {
250
251         case LFUN_WINDOW_NEW:
252                 createView(toqstr(cmd.argument()));
253                 break;
254
255         case LFUN_WINDOW_CLOSE:
256                 // update bookmark pit of the current buffer before window close
257                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
258                         theLyXFunc().gotoBookmark(i+1, false, false);
259                 current_view_->close();
260                 break;
261
262         case LFUN_LYX_QUIT:
263                 // quitting is triggered by the gui code
264                 // (leaving the event loop).
265                 current_view_->message(from_utf8(N_("Exiting.")));
266                 if (closeAllViews())
267                         quit();
268                 break;
269
270         case LFUN_SCREEN_FONT_UPDATE: {
271                 // handle the screen font changes.
272                 font_loader_.update();
273                 // Backup current_view_
274                 GuiView * view = current_view_;
275                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
276                 // to skip the refresh.
277                 current_view_ = 0;
278                 BufferList::iterator it = theBufferList().begin();
279                 BufferList::iterator const end = theBufferList().end();
280                 for (; it != end; ++it)
281                         (*it)->changed();
282                 // Restore current_view_
283                 current_view_ = view;
284                 break;
285         }
286
287         default:
288                 // Notify the caller that the action has not been dispatched.
289                 return false;
290         }
291
292         // The action has been dispatched.
293         return true;
294 }
295
296
297 void GuiApplication::resetGui()
298 {
299         map<int, GuiView *>::iterator it;
300         for (it = views_.begin(); it != views_.end(); ++it)
301                 it->second->resetDialogs();
302
303         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
304 }
305
306
307 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
308 {
309         ids.clear();
310         map<int, GuiView *>::const_iterator it;
311         for (it = stdmap.begin(); it != stdmap.end(); ++it)
312                 ids.push_back(it->first);
313 }
314
315
316 void GuiApplication::createView(QString const & geometry_arg)
317 {
318         updateIds(views_, view_ids_);
319         int id = 0;
320         while (views_.find(id) != views_.end())
321                 id++;
322         views_[id] = new GuiView(id);
323         updateIds(views_, view_ids_);
324
325         GuiView * view  = views_[id];
326         theLyXFunc().setLyXView(view);
327
328         view->show();
329         if (!geometry_arg.isEmpty()) {
330 #ifdef Q_WS_WIN
331                 int x, y;
332                 int w, h;
333                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
334                 re.indexIn(geometry_arg);
335                 w = re.cap(1).toInt();
336                 h = re.cap(2).toInt();
337                 x = re.cap(3).toInt();
338                 y = re.cap(4).toInt();
339                 view->setGeometry(x, y, w, h);
340 #endif
341         }
342         view->setFocus();
343
344         setCurrentView(*view);
345 }
346
347
348
349
350 Clipboard & GuiApplication::clipboard()
351 {
352         return clipboard_;
353 }
354
355
356 Selection & GuiApplication::selection()
357 {
358         return selection_;
359 }
360
361
362 int GuiApplication::exec()
363 {
364         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
365         return QApplication::exec();
366 }
367
368
369 void GuiApplication::exit(int status)
370 {
371         QApplication::exit(status);
372 }
373
374
375 void GuiApplication::execBatchCommands()
376 {
377         LyX::ref().execBatchCommands();
378 }
379
380
381 void GuiApplication::restoreGuiSession()
382 {
383         if (!lyxrc.load_session)
384                 return;
385
386         Session & session = LyX::ref().session();
387         vector<FileName> const & lastopened = session.lastOpened().getfiles();
388         // do not add to the lastfile list since these files are restored from
389         // last session, and should be already there (regular files), or should
390         // not be added at all (help files).
391         for_each(lastopened.begin(), lastopened.end(),
392                 bind(&GuiView::loadDocument, current_view_, _1, false));
393
394         // clear this list to save a few bytes of RAM
395         session.lastOpened().clear();
396 }
397
398
399 QString const GuiApplication::romanFontName()
400 {
401         QFont font;
402         font.setKerning(false);
403         font.setStyleHint(QFont::Serif);
404         font.setFamily("serif");
405
406         return QFontInfo(font).family();
407 }
408
409
410 QString const GuiApplication::sansFontName()
411 {
412         QFont font;
413         font.setKerning(false);
414         font.setStyleHint(QFont::SansSerif);
415         font.setFamily("sans");
416
417         return QFontInfo(font).family();
418 }
419
420
421 QString const GuiApplication::typewriterFontName()
422 {
423         QFont font;
424         font.setKerning(false);
425         font.setStyleHint(QFont::TypeWriter);
426         font.setFamily("monospace");
427
428         return QFontInfo(font).family();
429 }
430
431
432 void GuiApplication::handleRegularEvents()
433 {
434         ForkedCallsController::handleCompletedProcesses();
435 }
436
437
438 bool GuiApplication::event(QEvent * e)
439 {
440         switch(e->type()) {
441         case QEvent::FileOpen: {
442                 // Open a file; this happens only on Mac OS X for now
443                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
444
445                 if (!current_view_ || !current_view_->view())
446                         // The application is not properly initialized yet.
447                         // So we acknowledge the event and delay the file opening
448                         // until LyX is ready.
449                         // FIXME UNICODE: FileName accept an utf8 encoded string.
450                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
451                 else
452                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
453                                 qstring_to_ucs4(foe->file())));
454
455                 e->accept();
456                 return true;
457         }
458         default:
459                 return QApplication::event(e);
460         }
461 }
462
463
464 bool GuiApplication::notify(QObject * receiver, QEvent * event)
465 {
466         try {
467                 return QApplication::notify(receiver, event);
468         }
469         catch (ExceptionMessage const & e) {
470                 switch(e.type_) { 
471                 case ErrorException:
472                         LyX::cref().emergencyCleanup();
473                         setQuitOnLastWindowClosed(false);
474                         closeAllViews();
475                         Alert::error(e.title_, e.details_);
476 #ifndef NDEBUG
477                         // Properly crash in debug mode in order to get a useful backtrace.
478                         abort();
479 #endif
480                         // In release mode, try to exit gracefully.
481                         this->exit(1);
482
483                 case BufferException: {
484                         Buffer * buf = current_view_->buffer();
485                         docstring details = e.details_ + '\n';
486                         details += theBufferList().emergencyWrite(buf);
487                         theBufferList().release(buf);
488                         details += _("\nThe current document was closed.");
489                         Alert::error(e.title_, details);
490                         return false;
491                 }
492                 case WarningException:
493                         Alert::warning(e.title_, e.details_);
494                         return false;
495                 };
496         }
497         catch (exception const & e) {
498                 docstring s = _("LyX has caught an exception, it will now "
499                         "attempt to save all unsaved documents and exit."
500                         "\n\nException: ");
501                 s += from_ascii(e.what());
502                 Alert::error(_("Software exception Detected"), s);
503                 LyX::cref().exit(1);
504         }
505         catch (...) {
506                 docstring s = _("LyX has caught some really weird exception, it will "
507                         "now attempt to save all unsaved documents and exit.");
508                 Alert::error(_("Software exception Detected"), s);
509                 LyX::cref().exit(1);
510         }
511
512         return false;
513 }
514
515
516 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
517 {
518         QColor const & qcol = color_cache_.get(col);
519         if (!qcol.isValid()) {
520                 rgbcol.r = 0;
521                 rgbcol.g = 0;
522                 rgbcol.b = 0;
523                 return false;
524         }
525         rgbcol.r = qcol.red();
526         rgbcol.g = qcol.green();
527         rgbcol.b = qcol.blue();
528         return true;
529 }
530
531
532 string const GuiApplication::hexName(ColorCode col)
533 {
534         return ltrim(fromqstr(color_cache_.get(col).name()), "#");
535 }
536
537
538 void GuiApplication::updateColor(ColorCode)
539 {
540         // FIXME: Bleh, can't we just clear them all at once ?
541         color_cache_.clear();
542 }
543
544
545 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
546 {
547         SocketNotifier * sn = new SocketNotifier(this, fd, func);
548         socket_notifiers_[fd] = sn;
549         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
550 }
551
552
553 void GuiApplication::socketDataReceived(int fd)
554 {
555         socket_notifiers_[fd]->func_();
556 }
557
558
559 void GuiApplication::unregisterSocketCallback(int fd)
560 {
561         socket_notifiers_.erase(fd);
562 }
563
564
565 void GuiApplication::commitData(QSessionManager & sm)
566 {
567         /// The implementation is required to avoid an application exit
568         /// when session state save is triggered by session manager.
569         /// The default implementation sends a close event to all
570         /// visible top level widgets when session managment allows
571         /// interaction.
572         /// We are changing that to close all wiew one by one.
573         /// FIXME: verify if the default implementation is enough now.
574         if (sm.allowsInteraction() && !closeAllViews())
575                 sm.cancel();
576 }
577
578
579 void GuiApplication::addMenuTranslator()
580 {
581         installTranslator(new MenuTranslator(this));
582 }
583
584
585 bool GuiApplication::unregisterView(int id)
586 {
587         updateIds(views_, view_ids_);
588         BOOST_ASSERT(views_.find(id) != views_.end());
589         BOOST_ASSERT(views_[id]);
590
591         map<int, GuiView *>::iterator it;
592         for (it = views_.begin(); it != views_.end(); ++it) {
593                 if (it->first == id) {
594                         views_.erase(id);
595                         break;
596                 }
597         }
598         updateIds(views_, view_ids_);
599         return true;
600 }
601
602
603 bool GuiApplication::closeAllViews()
604 {
605         updateIds(views_, view_ids_);
606         if (views_.empty())
607                 return true;
608
609         map<int, GuiView*> const cmap = views_;
610         map<int, GuiView*>::const_iterator it;
611         for (it = cmap.begin(); it != cmap.end(); ++it) {
612                 if (!it->second->close())
613                         return false;
614         }
615
616         views_.clear();
617         view_ids_.clear();
618         return true;
619 }
620
621
622 GuiView & GuiApplication::view(int id) const
623 {
624         BOOST_ASSERT(views_.find(id) != views_.end());
625         return *views_.find(id)->second;
626 }
627
628
629 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
630 {
631         vector<int>::const_iterator it = view_ids_.begin();
632         vector<int>::const_iterator const end = view_ids_.end();
633         for (; it != end; ++it)
634                 view(*it).hideDialog(name, inset);
635 }
636
637
638 Buffer const * GuiApplication::updateInset(Inset const * inset) const
639 {
640         Buffer const * buffer_ = 0;
641         vector<int>::const_iterator it = view_ids_.begin();
642         vector<int>::const_iterator const end = view_ids_.end();
643         for (; it != end; ++it) {
644                 Buffer const * ptr = view(*it).updateInset(inset);
645                 if (ptr)
646                         buffer_ = ptr;
647         }
648         return buffer_;
649 }
650
651
652 void GuiApplication::readMenus(Lexer & lex)
653 {
654         menus().read(lex);
655 }
656
657
658 bool GuiApplication::searchMenu(FuncRequest const & func,
659         vector<docstring> & names) const
660 {
661         return menus().searchMenu(func, names);
662 }
663
664
665 ////////////////////////////////////////////////////////////////////////
666 // X11 specific stuff goes here...
667 #ifdef Q_WS_X11
668 bool GuiApplication::x11EventFilter(XEvent * xev)
669 {
670         if (!current_view_)
671                 return false;
672
673         switch (xev->type) {
674         case SelectionRequest: {
675                 if (xev->xselectionrequest.selection != XA_PRIMARY)
676                         break;
677                 LYXERR(Debug::GUI, "X requested selection.");
678                 BufferView * bv = current_view_->view();
679                 if (bv) {
680                         docstring const sel = bv->requestSelection();
681                         if (!sel.empty())
682                                 selection_.put(sel);
683                 }
684                 break;
685         }
686         case SelectionClear: {
687                 if (xev->xselectionclear.selection != XA_PRIMARY)
688                         break;
689                 LYXERR(Debug::GUI, "Lost selection.");
690                 BufferView * bv = current_view_->view();
691                 if (bv)
692                         bv->clearSelection();
693                 break;
694         }
695         }
696         return false;
697 }
698 #endif
699
700 } // namespace frontend
701
702
703 ////////////////////////////////////////////////////////////////////
704 //
705 // Font stuff
706 //
707 ////////////////////////////////////////////////////////////////////
708
709 frontend::FontLoader & theFontLoader()
710 {
711         BOOST_ASSERT(frontend::guiApp);
712         return frontend::guiApp->fontLoader();
713 }
714
715
716 frontend::FontMetrics const & theFontMetrics(Font const & f)
717 {
718         return theFontMetrics(f.fontInfo());
719 }
720
721
722 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
723 {
724         BOOST_ASSERT(frontend::guiApp);
725         return frontend::guiApp->fontLoader().metrics(f);
726 }
727
728
729 frontend::Clipboard & theClipboard()
730 {
731         BOOST_ASSERT(frontend::guiApp);
732         return frontend::guiApp->clipboard();
733 }
734
735
736 frontend::Selection & theSelection()
737 {
738         BOOST_ASSERT(frontend::guiApp);
739         return frontend::guiApp->selection();
740 }
741
742 } // namespace lyx
743
744 #include "GuiApplication_moc.cpp"