]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
This is the last of the commits that hopes to enforce the distinction between "layout...
[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         //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                 if (e.type_ == ErrorException) {
471                         LyX::cref().emergencyCleanup();
472                         setQuitOnLastWindowClosed(false);
473                         closeAllViews();
474                         Alert::error(e.title_, e.details_);
475 #ifndef NDEBUG
476                         // Properly crash in debug mode in order to get a useful backtrace.
477                         abort();
478 #endif
479                         // In release mode, try to exit gracefully.
480                         this->exit(1);
481                 } else if (e.type_ == WarningException) {
482                         Alert::warning(e.title_, e.details_);
483                         return false;
484                 }
485         }
486         catch (exception const & e) {
487                 docstring s = _("LyX has caught an exception, it will now "
488                         "attempt to save all unsaved documents and exit."
489                         "\n\nException: ");
490                 s += from_ascii(e.what());
491                 Alert::error(_("Software exception Detected"), s);
492                 LyX::cref().exit(1);
493         }
494         catch (...) {
495                 docstring s = _("LyX has caught some really weird exception, it will "
496                         "now attempt to save all unsaved documents and exit.");
497                 Alert::error(_("Software exception Detected"), s);
498                 LyX::cref().exit(1);
499         }
500
501         return false;
502 }
503
504
505 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
506 {
507         QColor const & qcol = color_cache_.get(col);
508         if (!qcol.isValid()) {
509                 rgbcol.r = 0;
510                 rgbcol.g = 0;
511                 rgbcol.b = 0;
512                 return false;
513         }
514         rgbcol.r = qcol.red();
515         rgbcol.g = qcol.green();
516         rgbcol.b = qcol.blue();
517         return true;
518 }
519
520
521 string const GuiApplication::hexName(ColorCode col)
522 {
523         return ltrim(fromqstr(color_cache_.get(col).name()), "#");
524 }
525
526
527 void GuiApplication::updateColor(ColorCode)
528 {
529         // FIXME: Bleh, can't we just clear them all at once ?
530         color_cache_.clear();
531 }
532
533
534 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
535 {
536         SocketNotifier * sn = new SocketNotifier(this, fd, func);
537         socket_notifiers_[fd] = sn;
538         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
539 }
540
541
542 void GuiApplication::socketDataReceived(int fd)
543 {
544         socket_notifiers_[fd]->func_();
545 }
546
547
548 void GuiApplication::unregisterSocketCallback(int fd)
549 {
550         socket_notifiers_.erase(fd);
551 }
552
553
554 void GuiApplication::commitData(QSessionManager & sm)
555 {
556         /// The implementation is required to avoid an application exit
557         /// when session state save is triggered by session manager.
558         /// The default implementation sends a close event to all
559         /// visible top level widgets when session managment allows
560         /// interaction.
561         /// We are changing that to close all wiew one by one.
562         /// FIXME: verify if the default implementation is enough now.
563         if (sm.allowsInteraction() && !closeAllViews())
564                 sm.cancel();
565 }
566
567
568 void GuiApplication::addMenuTranslator()
569 {
570         installTranslator(new MenuTranslator(this));
571 }
572
573
574 bool GuiApplication::unregisterView(int id)
575 {
576         updateIds(views_, view_ids_);
577         BOOST_ASSERT(views_.find(id) != views_.end());
578         BOOST_ASSERT(views_[id]);
579
580         map<int, GuiView *>::iterator it;
581         for (it = views_.begin(); it != views_.end(); ++it) {
582                 if (it->first == id) {
583                         views_.erase(id);
584                         break;
585                 }
586         }
587         updateIds(views_, view_ids_);
588         return true;
589 }
590
591
592 bool GuiApplication::closeAllViews()
593 {
594         updateIds(views_, view_ids_);
595         if (views_.empty())
596                 return true;
597
598         map<int, GuiView*> const cmap = views_;
599         map<int, GuiView*>::const_iterator it;
600         for (it = cmap.begin(); it != cmap.end(); ++it) {
601                 if (!it->second->close())
602                         return false;
603         }
604
605         views_.clear();
606         view_ids_.clear();
607         return true;
608 }
609
610
611 GuiView & GuiApplication::view(int id) const
612 {
613         BOOST_ASSERT(views_.find(id) != views_.end());
614         return *views_.find(id)->second;
615 }
616
617
618 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
619 {
620         vector<int>::const_iterator it = view_ids_.begin();
621         vector<int>::const_iterator const end = view_ids_.end();
622         for (; it != end; ++it)
623                 view(*it).hideDialog(name, inset);
624 }
625
626
627 Buffer const * GuiApplication::updateInset(Inset const * inset) const
628 {
629         Buffer const * buffer_ = 0;
630         vector<int>::const_iterator it = view_ids_.begin();
631         vector<int>::const_iterator const end = view_ids_.end();
632         for (; it != end; ++it) {
633                 Buffer const * ptr = view(*it).updateInset(inset);
634                 if (ptr)
635                         buffer_ = ptr;
636         }
637         return buffer_;
638 }
639
640
641 ////////////////////////////////////////////////////////////////////////
642 // X11 specific stuff goes here...
643 #ifdef Q_WS_X11
644 bool GuiApplication::x11EventFilter(XEvent * xev)
645 {
646         if (!current_view_)
647                 return false;
648
649         switch (xev->type) {
650         case SelectionRequest: {
651                 if (xev->xselectionrequest.selection != XA_PRIMARY)
652                         break;
653                 LYXERR(Debug::GUI, "X requested selection.");
654                 BufferView * bv = current_view_->view();
655                 if (bv) {
656                         docstring const sel = bv->requestSelection();
657                         if (!sel.empty())
658                                 selection_.put(sel);
659                 }
660                 break;
661         }
662         case SelectionClear: {
663                 if (xev->xselectionclear.selection != XA_PRIMARY)
664                         break;
665                 LYXERR(Debug::GUI, "Lost selection.");
666                 BufferView * bv = current_view_->view();
667                 if (bv)
668                         bv->clearSelection();
669                 break;
670         }
671         }
672         return false;
673 }
674 #endif
675
676 } // namespace frontend
677
678
679 ////////////////////////////////////////////////////////////////////
680 //
681 // Font stuff
682 //
683 ////////////////////////////////////////////////////////////////////
684
685 frontend::FontLoader & theFontLoader()
686 {
687         BOOST_ASSERT(frontend::guiApp);
688         return frontend::guiApp->fontLoader();
689 }
690
691
692 frontend::FontMetrics const & theFontMetrics(Font const & f)
693 {
694         return theFontMetrics(f.fontInfo());
695 }
696
697
698 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
699 {
700         BOOST_ASSERT(frontend::guiApp);
701         return frontend::guiApp->fontLoader().metrics(f);
702 }
703
704
705 frontend::Clipboard & theClipboard()
706 {
707         BOOST_ASSERT(frontend::guiApp);
708         return frontend::guiApp->clipboard();
709 }
710
711
712 frontend::Selection & theSelection()
713 {
714         BOOST_ASSERT(frontend::guiApp);
715         return frontend::guiApp->selection();
716 }
717
718 } // namespace lyx
719
720 #include "GuiApplication_moc.cpp"