]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
c4bbcf46f7d5e4035a7c302577d142fb916f385f
[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         // create new view
319         updateIds(views_, view_ids_);
320         int id = 0;
321         while (views_.find(id) != views_.end())
322                 id++;
323         GuiView * view = new GuiView(id);
324         
325         // copy the icon size from old view
326         if (viewCount() > 0)
327                 view->setIconSize(current_view_->iconSize());
328
329         // register view
330         views_[id] = view;
331         updateIds(views_, view_ids_);
332         
333         theLyXFunc().setLyXView(view);
334         view->show();
335         if (!geometry_arg.isEmpty()) {
336 #ifdef Q_WS_WIN
337                 int x, y;
338                 int w, h;
339                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
340                 re.indexIn(geometry_arg);
341                 w = re.cap(1).toInt();
342                 h = re.cap(2).toInt();
343                 x = re.cap(3).toInt();
344                 y = re.cap(4).toInt();
345                 view->setGeometry(x, y, w, h);
346 #endif
347         }
348         view->setFocus();
349
350         setCurrentView(*view);
351 }
352
353
354
355
356 Clipboard & GuiApplication::clipboard()
357 {
358         return clipboard_;
359 }
360
361
362 Selection & GuiApplication::selection()
363 {
364         return selection_;
365 }
366
367
368 int GuiApplication::exec()
369 {
370         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
371         return QApplication::exec();
372 }
373
374
375 void GuiApplication::exit(int status)
376 {
377         QApplication::exit(status);
378 }
379
380
381 void GuiApplication::execBatchCommands()
382 {
383         LyX::ref().execBatchCommands();
384 }
385
386
387 void GuiApplication::restoreGuiSession()
388 {
389         if (!lyxrc.load_session)
390                 return;
391
392         Session & session = LyX::ref().session();
393         vector<FileName> const & lastopened = session.lastOpened().getfiles();
394         // do not add to the lastfile list since these files are restored from
395         // last session, and should be already there (regular files), or should
396         // not be added at all (help files).
397         for_each(lastopened.begin(), lastopened.end(),
398                 bind(&GuiView::loadDocument, current_view_, _1, false));
399
400         // clear this list to save a few bytes of RAM
401         session.lastOpened().clear();
402 }
403
404
405 QString const GuiApplication::romanFontName()
406 {
407         QFont font;
408         font.setKerning(false);
409         font.setStyleHint(QFont::Serif);
410         font.setFamily("serif");
411
412         return QFontInfo(font).family();
413 }
414
415
416 QString const GuiApplication::sansFontName()
417 {
418         QFont font;
419         font.setKerning(false);
420         font.setStyleHint(QFont::SansSerif);
421         font.setFamily("sans");
422
423         return QFontInfo(font).family();
424 }
425
426
427 QString const GuiApplication::typewriterFontName()
428 {
429         QFont font;
430         font.setKerning(false);
431         font.setStyleHint(QFont::TypeWriter);
432         font.setFamily("monospace");
433
434         return QFontInfo(font).family();
435 }
436
437
438 void GuiApplication::handleRegularEvents()
439 {
440         ForkedCallsController::handleCompletedProcesses();
441 }
442
443
444 bool GuiApplication::event(QEvent * e)
445 {
446         switch(e->type()) {
447         case QEvent::FileOpen: {
448                 // Open a file; this happens only on Mac OS X for now
449                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
450
451                 if (!current_view_ || !current_view_->view())
452                         // The application is not properly initialized yet.
453                         // So we acknowledge the event and delay the file opening
454                         // until LyX is ready.
455                         // FIXME UNICODE: FileName accept an utf8 encoded string.
456                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
457                 else
458                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
459                                 qstring_to_ucs4(foe->file())));
460
461                 e->accept();
462                 return true;
463         }
464         default:
465                 return QApplication::event(e);
466         }
467 }
468
469
470 bool GuiApplication::notify(QObject * receiver, QEvent * event)
471 {
472         try {
473                 return QApplication::notify(receiver, event);
474         }
475         catch (ExceptionMessage const & e) {
476                 switch(e.type_) { 
477                 case ErrorException:
478                         LyX::cref().emergencyCleanup();
479                         setQuitOnLastWindowClosed(false);
480                         closeAllViews();
481                         Alert::error(e.title_, e.details_);
482 #ifndef NDEBUG
483                         // Properly crash in debug mode in order to get a useful backtrace.
484                         abort();
485 #endif
486                         // In release mode, try to exit gracefully.
487                         this->exit(1);
488
489                 case BufferException: {
490                         Buffer * buf = current_view_->buffer();
491                         docstring details = e.details_ + '\n';
492                         details += theBufferList().emergencyWrite(buf);
493                         theBufferList().release(buf);
494                         details += _("\nThe current document was closed.");
495                         Alert::error(e.title_, details);
496                         return false;
497                 }
498                 case WarningException:
499                         Alert::warning(e.title_, e.details_);
500                         return false;
501                 };
502         }
503         catch (exception const & e) {
504                 docstring s = _("LyX has caught an exception, it will now "
505                         "attempt to save all unsaved documents and exit."
506                         "\n\nException: ");
507                 s += from_ascii(e.what());
508                 Alert::error(_("Software exception Detected"), s);
509                 LyX::cref().exit(1);
510         }
511         catch (...) {
512                 docstring s = _("LyX has caught some really weird exception, it will "
513                         "now attempt to save all unsaved documents and exit.");
514                 Alert::error(_("Software exception Detected"), s);
515                 LyX::cref().exit(1);
516         }
517
518         return false;
519 }
520
521
522 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
523 {
524         QColor const & qcol = color_cache_.get(col);
525         if (!qcol.isValid()) {
526                 rgbcol.r = 0;
527                 rgbcol.g = 0;
528                 rgbcol.b = 0;
529                 return false;
530         }
531         rgbcol.r = qcol.red();
532         rgbcol.g = qcol.green();
533         rgbcol.b = qcol.blue();
534         return true;
535 }
536
537
538 string const GuiApplication::hexName(ColorCode col)
539 {
540         return ltrim(fromqstr(color_cache_.get(col).name()), "#");
541 }
542
543
544 void GuiApplication::updateColor(ColorCode)
545 {
546         // FIXME: Bleh, can't we just clear them all at once ?
547         color_cache_.clear();
548 }
549
550
551 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
552 {
553         SocketNotifier * sn = new SocketNotifier(this, fd, func);
554         socket_notifiers_[fd] = sn;
555         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
556 }
557
558
559 void GuiApplication::socketDataReceived(int fd)
560 {
561         socket_notifiers_[fd]->func_();
562 }
563
564
565 void GuiApplication::unregisterSocketCallback(int fd)
566 {
567         socket_notifiers_.erase(fd);
568 }
569
570
571 void GuiApplication::commitData(QSessionManager & sm)
572 {
573         /// The implementation is required to avoid an application exit
574         /// when session state save is triggered by session manager.
575         /// The default implementation sends a close event to all
576         /// visible top level widgets when session managment allows
577         /// interaction.
578         /// We are changing that to close all wiew one by one.
579         /// FIXME: verify if the default implementation is enough now.
580         if (sm.allowsInteraction() && !closeAllViews())
581                 sm.cancel();
582 }
583
584
585 void GuiApplication::addMenuTranslator()
586 {
587         installTranslator(new MenuTranslator(this));
588 }
589
590
591 bool GuiApplication::unregisterView(int id)
592 {
593         updateIds(views_, view_ids_);
594         BOOST_ASSERT(views_.find(id) != views_.end());
595         BOOST_ASSERT(views_[id]);
596
597         map<int, GuiView *>::iterator it;
598         for (it = views_.begin(); it != views_.end(); ++it) {
599                 if (it->first == id) {
600                         views_.erase(id);
601                         break;
602                 }
603         }
604         updateIds(views_, view_ids_);
605         return true;
606 }
607
608
609 bool GuiApplication::closeAllViews()
610 {
611         updateIds(views_, view_ids_);
612         if (views_.empty())
613                 return true;
614
615         map<int, GuiView*> const cmap = views_;
616         map<int, GuiView*>::const_iterator it;
617         for (it = cmap.begin(); it != cmap.end(); ++it) {
618                 if (!it->second->close())
619                         return false;
620         }
621
622         views_.clear();
623         view_ids_.clear();
624         return true;
625 }
626
627
628 GuiView & GuiApplication::view(int id) const
629 {
630         BOOST_ASSERT(views_.find(id) != views_.end());
631         return *views_.find(id)->second;
632 }
633
634
635 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
636 {
637         vector<int>::const_iterator it = view_ids_.begin();
638         vector<int>::const_iterator const end = view_ids_.end();
639         for (; it != end; ++it)
640                 view(*it).hideDialog(name, inset);
641 }
642
643
644 Buffer const * GuiApplication::updateInset(Inset const * inset) const
645 {
646         Buffer const * buffer_ = 0;
647         vector<int>::const_iterator it = view_ids_.begin();
648         vector<int>::const_iterator const end = view_ids_.end();
649         for (; it != end; ++it) {
650                 Buffer const * ptr = view(*it).updateInset(inset);
651                 if (ptr)
652                         buffer_ = ptr;
653         }
654         return buffer_;
655 }
656
657
658 void GuiApplication::readMenus(Lexer & lex)
659 {
660         menus().read(lex);
661 }
662
663
664 bool GuiApplication::searchMenu(FuncRequest const & func,
665         vector<docstring> & names) const
666 {
667         return menus().searchMenu(func, names);
668 }
669
670
671 ////////////////////////////////////////////////////////////////////////
672 // X11 specific stuff goes here...
673 #ifdef Q_WS_X11
674 bool GuiApplication::x11EventFilter(XEvent * xev)
675 {
676         if (!current_view_)
677                 return false;
678
679         switch (xev->type) {
680         case SelectionRequest: {
681                 if (xev->xselectionrequest.selection != XA_PRIMARY)
682                         break;
683                 LYXERR(Debug::GUI, "X requested selection.");
684                 BufferView * bv = current_view_->view();
685                 if (bv) {
686                         docstring const sel = bv->requestSelection();
687                         if (!sel.empty())
688                                 selection_.put(sel);
689                 }
690                 break;
691         }
692         case SelectionClear: {
693                 if (xev->xselectionclear.selection != XA_PRIMARY)
694                         break;
695                 LYXERR(Debug::GUI, "Lost selection.");
696                 BufferView * bv = current_view_->view();
697                 if (bv)
698                         bv->clearSelection();
699                 break;
700         }
701         }
702         return false;
703 }
704 #endif
705
706 } // namespace frontend
707
708
709 ////////////////////////////////////////////////////////////////////
710 //
711 // Font stuff
712 //
713 ////////////////////////////////////////////////////////////////////
714
715 frontend::FontLoader & theFontLoader()
716 {
717         BOOST_ASSERT(frontend::guiApp);
718         return frontend::guiApp->fontLoader();
719 }
720
721
722 frontend::FontMetrics const & theFontMetrics(Font const & f)
723 {
724         return theFontMetrics(f.fontInfo());
725 }
726
727
728 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
729 {
730         BOOST_ASSERT(frontend::guiApp);
731         return frontend::guiApp->fontLoader().metrics(f);
732 }
733
734
735 frontend::Clipboard & theClipboard()
736 {
737         BOOST_ASSERT(frontend::guiApp);
738         return frontend::guiApp->clipboard();
739 }
740
741
742 frontend::Selection & theSelection()
743 {
744         BOOST_ASSERT(frontend::guiApp);
745         return frontend::guiApp->selection();
746 }
747
748 } // namespace lyx
749
750 #include "GuiApplication_moc.cpp"