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