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