]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
The core is now clean enough that we don't need the NoGuiFontLoader/Metrics anymore...
[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 "support/ExceptionMessage.h"
27 #include "support/FileName.h"
28 #include "support/ForkedCalls.h"
29 #include "support/lstrings.h"
30 #include "support/os.h"
31 #include "support/Package.h"
32
33 #include "Buffer.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
36 #include "support/debug.h"
37 #include "Font.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "support/gettext.h"
41 #include "LyX.h"
42 #include "LyXFunc.h"
43 #include "LyXRC.h"
44 #include "Session.h"
45 #include "version.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                 // ask the user for saving changes or cancel quit
255                 if (!current_view_->quitWriteAll())
256                         break;
257                 current_view_->close();
258                 break;
259
260         case LFUN_LYX_QUIT:
261                 // quitting is triggered by the gui code
262                 // (leaving the event loop).
263                 current_view_->message(from_utf8(N_("Exiting.")));
264                 if (current_view_->quitWriteAll())
265                         closeAllViews();
266                 break;
267
268         case LFUN_SCREEN_FONT_UPDATE: {
269                 // handle the screen font changes.
270                 font_loader_.update();
271                 // Backup current_view_
272                 GuiView * view = current_view_;
273                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
274                 // to skip the refresh.
275                 current_view_ = 0;
276                 BufferList::iterator it = theBufferList().begin();
277                 BufferList::iterator const end = theBufferList().end();
278                 for (; it != end; ++it)
279                         (*it)->changed();
280                 // Restore current_view_
281                 current_view_ = view;
282                 break;
283         }
284
285         default:
286                 // Notify the caller that the action has not been dispatched.
287                 return false;
288         }
289
290         // The action has been dispatched.
291         return true;
292 }
293
294
295 void GuiApplication::resetGui()
296 {
297         map<int, GuiView *>::iterator it;
298         for (it = views_.begin(); it != views_.end(); ++it)
299                 it->second->resetDialogs();
300
301         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
302 }
303
304
305 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
306 {
307         ids.clear();
308         map<int, GuiView *>::const_iterator it;
309         for (it = stdmap.begin(); it != stdmap.end(); ++it)
310                 ids.push_back(it->first);
311 }
312
313
314 void GuiApplication::createView(QString const & geometry_arg)
315 {
316         updateIds(views_, view_ids_);
317         int id = 0;
318         while (views_.find(id) != views_.end())
319                 id++;
320         views_[id] = new GuiView(id);
321         updateIds(views_, view_ids_);
322
323         GuiView * view  = views_[id];
324         theLyXFunc().setLyXView(view);
325
326         view->show();
327         if (!geometry_arg.isEmpty()) {
328 #ifdef Q_WS_WIN
329                 int x, y;
330                 int w, h;
331                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
332                 re.indexIn(geometry_arg);
333                 w = re.cap(1).toInt();
334                 h = re.cap(2).toInt();
335                 x = re.cap(3).toInt();
336                 y = re.cap(4).toInt();
337                 view->setGeometry(x, y, w, h);
338 #endif
339         }
340         view->setFocus();
341
342         setCurrentView(*view);
343 }
344
345
346
347
348 Clipboard & GuiApplication::clipboard()
349 {
350         return clipboard_;
351 }
352
353
354 Selection & GuiApplication::selection()
355 {
356         return selection_;
357 }
358
359
360 int GuiApplication::exec()
361 {
362         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
363         return QApplication::exec();
364 }
365
366
367 void GuiApplication::exit(int status)
368 {
369         QApplication::exit(status);
370 }
371
372
373 void GuiApplication::execBatchCommands()
374 {
375         LyX::ref().execBatchCommands();
376 }
377
378
379 void GuiApplication::restoreGuiSession()
380 {
381         if (!lyxrc.load_session)
382                 return;
383
384         Session & session = LyX::ref().session();
385         vector<FileName> const & lastopened = session.lastOpened().getfiles();
386         // do not add to the lastfile list since these files are restored from
387         // last session, and should be already there (regular files), or should
388         // not be added at all (help files).
389         for_each(lastopened.begin(), lastopened.end(),
390                 bind(&GuiView::loadDocument, current_view_, _1, false));
391
392         // clear this list to save a few bytes of RAM
393         session.lastOpened().clear();
394 }
395
396
397 QString const GuiApplication::romanFontName()
398 {
399         QFont font;
400         font.setKerning(false);
401         font.setStyleHint(QFont::Serif);
402         font.setFamily("serif");
403
404         return QFontInfo(font).family();
405 }
406
407
408 QString const GuiApplication::sansFontName()
409 {
410         QFont font;
411         font.setKerning(false);
412         font.setStyleHint(QFont::SansSerif);
413         font.setFamily("sans");
414
415         return QFontInfo(font).family();
416 }
417
418
419 QString const GuiApplication::typewriterFontName()
420 {
421         QFont font;
422         font.setKerning(false);
423         font.setStyleHint(QFont::TypeWriter);
424         font.setFamily("monospace");
425
426         return QFontInfo(font).family();
427 }
428
429
430 void GuiApplication::handleRegularEvents()
431 {
432         ForkedCallsController::handleCompletedProcesses();
433 }
434
435
436 bool GuiApplication::event(QEvent * e)
437 {
438         switch(e->type()) {
439         case QEvent::FileOpen: {
440                 // Open a file; this happens only on Mac OS X for now
441                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
442
443                 if (!current_view_ || !current_view_->view())
444                         // The application is not properly initialized yet.
445                         // So we acknowledge the event and delay the file opening
446                         // until LyX is ready.
447                         // FIXME UNICODE: FileName accept an utf8 encoded string.
448                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
449                 else
450                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
451                                 qstring_to_ucs4(foe->file())));
452
453                 e->accept();
454                 return true;
455         }
456         default:
457                 return QApplication::event(e);
458         }
459 }
460
461
462 bool GuiApplication::notify(QObject * receiver, QEvent * event)
463 {
464         try {
465                 return QApplication::notify(receiver, event);
466         }
467         catch (ExceptionMessage const & e) {
468                 if (e.type_ == ErrorException) {
469                         Alert::error(e.title_, e.details_);
470                         LyX::cref().exit(1);
471                 } else if (e.type_ == WarningException) {
472                         Alert::warning(e.title_, e.details_);
473                         return false;
474                 }
475         }
476         catch (exception const & e) {
477                 docstring s = _("LyX has caught an exception, it will now "
478                         "attempt to save all unsaved documents and exit."
479                         "\n\nException: ");
480                 s += from_ascii(e.what());
481                 Alert::error(_("Software exception Detected"), s);
482                 LyX::cref().exit(1);
483         }
484         catch (...) {
485                 docstring s = _("LyX has caught some really weird exception, it will "
486                         "now attempt to save all unsaved documents and exit.");
487                 Alert::error(_("Software exception Detected"), s);
488                 LyX::cref().exit(1);
489         }
490
491         return false;
492 }
493
494
495 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
496 {
497         QColor const & qcol = color_cache_.get(col);
498         if (!qcol.isValid()) {
499                 rgbcol.r = 0;
500                 rgbcol.g = 0;
501                 rgbcol.b = 0;
502                 return false;
503         }
504         rgbcol.r = qcol.red();
505         rgbcol.g = qcol.green();
506         rgbcol.b = qcol.blue();
507         return true;
508 }
509
510
511 string const GuiApplication::hexName(ColorCode col)
512 {
513         return ltrim(fromqstr(color_cache_.get(col).name()), "#");
514 }
515
516
517 void GuiApplication::updateColor(ColorCode)
518 {
519         // FIXME: Bleh, can't we just clear them all at once ?
520         color_cache_.clear();
521 }
522
523
524 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
525 {
526         SocketNotifier * sn = new SocketNotifier(this, fd, func);
527         socket_notifiers_[fd] = sn;
528         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
529 }
530
531
532 void GuiApplication::socketDataReceived(int fd)
533 {
534         socket_notifiers_[fd]->func_();
535 }
536
537
538 void GuiApplication::unregisterSocketCallback(int fd)
539 {
540         socket_notifiers_.erase(fd);
541 }
542
543
544 void GuiApplication::commitData(QSessionManager & sm)
545 {
546         /// The implementation is required to avoid an application exit
547         /// when session state save is triggered by session manager.
548         /// The default implementation sends a close event to all
549         /// visible top level widgets when session managment allows
550         /// interaction.
551         /// We are changing that to write all unsaved buffers...
552         if (sm.allowsInteraction() && !current_view_->quitWriteAll())
553                 sm.cancel();
554 }
555
556
557 void GuiApplication::addMenuTranslator()
558 {
559         installTranslator(new MenuTranslator(this));
560 }
561
562
563 bool GuiApplication::unregisterView(int id)
564 {
565         updateIds(views_, view_ids_);
566         BOOST_ASSERT(views_.find(id) != views_.end());
567         BOOST_ASSERT(views_[id]);
568
569         map<int, GuiView *>::iterator it;
570         for (it = views_.begin(); it != views_.end(); ++it) {
571                 if (it->first == id) {
572                         views_.erase(id);
573                         break;
574                 }
575         }
576         updateIds(views_, view_ids_);
577         return true;
578 }
579
580
581 bool GuiApplication::closeAllViews()
582 {
583         updateIds(views_, view_ids_);
584         if (views_.empty()) {
585                 // quit in CloseEvent will not be triggert
586                 qApp->quit();
587                 return true;
588         }
589
590         map<int, GuiView*> const cmap = views_;
591         map<int, GuiView*>::const_iterator it;
592         for (it = cmap.begin(); it != cmap.end(); ++it) {
593                 // TODO: return false when close event was ignored
594                 //       e.g. quitWriteAll()->'Cancel'
595                 //       maybe we need something like 'bool closeView()'
596                 it->second->close();
597                 // unregisterd by the CloseEvent
598         }
599
600         views_.clear();
601         view_ids_.clear();
602         return true;
603 }
604
605
606 GuiView & GuiApplication::view(int id) const
607 {
608         BOOST_ASSERT(views_.find(id) != views_.end());
609         return *views_.find(id)->second;
610 }
611
612
613 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
614 {
615         vector<int>::const_iterator it = view_ids_.begin();
616         vector<int>::const_iterator const end = view_ids_.end();
617         for (; it != end; ++it)
618                 view(*it).hideDialog(name, inset);
619 }
620
621
622 Buffer const * GuiApplication::updateInset(Inset const * inset) const
623 {
624         Buffer const * buffer_ = 0;
625         vector<int>::const_iterator it = view_ids_.begin();
626         vector<int>::const_iterator const end = view_ids_.end();
627         for (; it != end; ++it) {
628                 Buffer const * ptr = view(*it).updateInset(inset);
629                 if (ptr)
630                         buffer_ = ptr;
631         }
632         return buffer_;
633 }
634
635
636 ////////////////////////////////////////////////////////////////////////
637 // X11 specific stuff goes here...
638 #ifdef Q_WS_X11
639 bool GuiApplication::x11EventFilter(XEvent * xev)
640 {
641         if (!current_view_)
642                 return false;
643
644         switch (xev->type) {
645         case SelectionRequest: {
646                 if (xev->xselectionrequest.selection != XA_PRIMARY)
647                         break;
648                 LYXERR(Debug::GUI, "X requested selection.");
649                 BufferView * bv = current_view_->view();
650                 if (bv) {
651                         docstring const sel = bv->requestSelection();
652                         if (!sel.empty())
653                                 selection_.put(sel);
654                 }
655                 break;
656         }
657         case SelectionClear: {
658                 if (xev->xselectionclear.selection != XA_PRIMARY)
659                         break;
660                 LYXERR(Debug::GUI, "Lost selection.");
661                 BufferView * bv = current_view_->view();
662                 if (bv)
663                         bv->clearSelection();
664                 break;
665         }
666         }
667         return false;
668 }
669 #endif
670
671 } // namespace frontend
672
673
674 ////////////////////////////////////////////////////////////////////
675 //
676 // Font stuff
677 //
678 ////////////////////////////////////////////////////////////////////
679
680 frontend::FontLoader & theFontLoader()
681 {
682         BOOST_ASSERT(frontend::guiApp);
683         return frontend::guiApp->fontLoader();
684 }
685
686
687 frontend::FontMetrics const & theFontMetrics(Font const & f)
688 {
689         return theFontMetrics(f.fontInfo());
690 }
691
692
693 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
694 {
695         BOOST_ASSERT(frontend::guiApp);
696         return frontend::guiApp->fontLoader().metrics(f);
697 }
698
699
700 frontend::Clipboard & theClipboard()
701 {
702         BOOST_ASSERT(frontend::guiApp);
703         return frontend::guiApp->clipboard();
704 }
705
706
707 frontend::Selection & theSelection()
708 {
709         BOOST_ASSERT(frontend::guiApp);
710         return frontend::guiApp->selection();
711 }
712
713 } // namespace lyx
714
715 #include "GuiApplication_moc.cpp"