]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
932e52b1aa192bc41bec3151a3b1c522a7b509b9
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "qt_helpers.h"
18 #include "GuiImage.h"
19 #include "GuiView.h"
20
21 #include "frontends/alert.h"
22 #include "frontends/Application.h"
23 #include "frontends/NoGuiFontLoader.h"
24 #include "frontends/NoGuiFontMetrics.h"
25 #include "frontends/FontLoader.h"
26 #include "frontends/FontMetrics.h"
27
28 #include "support/ExceptionMessage.h"
29 #include "support/FileName.h"
30 #include "support/ForkedCalls.h"
31 #include "support/lstrings.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34
35 #include "Buffer.h"
36 #include "BufferList.h"
37 #include "BufferView.h"
38 #include "support/debug.h"
39 #include "Font.h"
40 #include "FuncRequest.h"
41 #include "FuncStatus.h"
42 #include "support/gettext.h"
43 #include "LyX.h"
44 #include "LyXFunc.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "version.h"
48
49 #include <QApplication>
50 #include <QClipboard>
51 #include <QEventLoop>
52 #include <QFileOpenEvent>
53 #include <QLocale>
54 #include <QLibraryInfo>
55 #include <QMenuBar>
56 #include <QPixmapCache>
57 #include <QRegExp>
58 #include <QSessionManager>
59 #include <QSocketNotifier>
60 #include <QTextCodec>
61 #include <QTimer>
62 #include <QTranslator>
63 #include <QWidget>
64
65 #ifdef Q_WS_X11
66 #include <X11/Xatom.h>
67 #include <X11/Xlib.h>
68 #undef CursorShape
69 #undef None
70 #endif
71
72 #include <boost/bind.hpp>
73
74 #include <exception>
75
76 using namespace std;
77 using namespace lyx::support;
78
79 namespace lyx {
80
81 frontend::Application * createApplication(int & argc, char * argv[])
82 {
83         return new frontend::GuiApplication(argc, argv);
84 }
85
86
87 namespace frontend {
88
89 class SocketNotifier : public QSocketNotifier
90 {
91 public:
92         /// connect a connection notification from the LyXServerSocket
93         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
94                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
95         {}
96
97 public:
98         /// The callback function
99         Application::SocketCallback func_;
100 };
101
102
103 ////////////////////////////////////////////////////////////////////////
104 // Mac specific stuff goes here...
105
106 class MenuTranslator : public QTranslator
107 {
108 public:
109         MenuTranslator(QObject * parent)
110                 : QTranslator(parent)
111         {}
112
113         QString translate(const char * /*context*/, 
114           const char * sourceText, 
115           const char * /*comment*/ = 0) 
116         {
117                 string const s = sourceText;
118                 if (s == N_("About %1") || s == N_("Preferences") 
119                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
120                         return qt_(s);
121                 else 
122                         return QString();
123         }
124 };
125
126
127 ///////////////////////////////////////////////////////////////
128 // You can find more platform specific stuff
129 // at the end of this file...
130 ///////////////////////////////////////////////////////////////
131
132
133 GuiApplication * guiApp;
134
135
136 GuiApplication::GuiApplication(int & argc, char ** argv)
137         : QApplication(argc, argv), Application(), current_view_(0)
138 {
139         QString app_name = "LyX";
140         QCoreApplication::setOrganizationName(app_name);
141         QCoreApplication::setOrganizationDomain("lyx.org");
142         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
143
144         // Qt bug? setQuitOnLastWindowClosed(true); does not work
145         setQuitOnLastWindowClosed(false);
146
147 #ifdef Q_WS_X11
148         // doubleClickInterval() is 400 ms on X11 which is just too long.
149         // On Windows and Mac OS X, the operating system's value is used.
150         // On Microsoft Windows, calling this function sets the double
151         // click interval for all applications. So we don't!
152         QApplication::setDoubleClickInterval(300);
153 #endif
154
155         // install translation file for Qt built-in dialogs
156         QString language_name = QString("qt_") + QLocale::system().name();
157         
158         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
159         // Short-named translator can be loaded from a long name, but not the
160         // opposite. Therefore, long name should be used without truncation.
161         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
162         if (qt_trans_.load(language_name,
163                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
164         {
165                 installTranslator(&qt_trans_);
166                 // even if the language calls for RtL, don't do that
167                 setLayoutDirection(Qt::LeftToRight);
168                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
169                         << fromqstr(language_name));
170         } else
171                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
172                         << fromqstr(language_name));
173
174 #ifdef Q_WS_MACX
175         // all windows in a Mac application share the same menu bar.
176         QMenuBar *menuBar = new QMenuBar(0);
177         // This allows to translate the strings that appear in the LyX menu.
178         addMenuTranslator();
179 #endif
180
181         using namespace lyx::graphics;
182
183         Image::newImage = boost::bind(&GuiImage::newImage);
184         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
185
186         // needs to be done before reading lyxrc
187         QWidget w;
188         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
189
190         guiApp = this;
191
192         // Set the cache to 5120 kilobytes which corresponds to screen size of
193         // 1280 by 1024 pixels with a color depth of 32 bits.
194         QPixmapCache::setCacheLimit(5120);
195
196         // Initialize RC Fonts
197         if (lyxrc.roman_font_name.empty())
198                 lyxrc.roman_font_name = fromqstr(romanFontName());
199
200         if (lyxrc.sans_font_name.empty())
201                 lyxrc.sans_font_name = fromqstr(sansFontName());
202
203         if (lyxrc.typewriter_font_name.empty())
204                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
205
206         general_timer_.setInterval(500);
207         connect(&general_timer_, SIGNAL(timeout()),
208                 this, SLOT(handleRegularEvents()));
209         general_timer_.start();
210 }
211
212
213 GuiApplication::~GuiApplication()
214 {
215         socket_notifiers_.clear();
216 }
217
218
219 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
220 {
221         FuncStatus flag;
222         bool enable = true;
223
224         switch(cmd.action) {
225
226         case LFUN_WINDOW_CLOSE:
227                 enable = view_ids_.size() > 0;
228                 break;
229
230         default:
231                 if (!current_view_) {
232                         enable = false;
233                         break;
234                 }
235         }
236
237         if (!enable)
238                 flag.enabled(false);
239
240         return flag;
241 }
242
243         
244 bool GuiApplication::dispatch(FuncRequest const & cmd)
245 {
246         switch(cmd.action) {
247
248         case LFUN_WINDOW_NEW:
249                 createView(toqstr(cmd.argument()));
250                 break;
251
252         case LFUN_WINDOW_CLOSE:
253                 // update bookmark pit of the current buffer before window close
254                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
255                         theLyXFunc().gotoBookmark(i+1, false, false);
256                 // ask the user for saving changes or cancel quit
257                 if (!current_view_->quitWriteAll())
258                         break;
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 (current_view_->quitWriteAll())
267                         closeAllViews();
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 QString const GuiApplication::romanFontName()
382 {
383         QFont font;
384         font.setKerning(false);
385         font.setStyleHint(QFont::Serif);
386         font.setFamily("serif");
387
388         return QFontInfo(font).family();
389 }
390
391
392 QString const GuiApplication::sansFontName()
393 {
394         QFont font;
395         font.setKerning(false);
396         font.setStyleHint(QFont::SansSerif);
397         font.setFamily("sans");
398
399         return QFontInfo(font).family();
400 }
401
402
403 QString const GuiApplication::typewriterFontName()
404 {
405         QFont font;
406         font.setKerning(false);
407         font.setStyleHint(QFont::TypeWriter);
408         font.setFamily("monospace");
409
410         return QFontInfo(font).family();
411 }
412
413
414 void GuiApplication::handleRegularEvents()
415 {
416         ForkedCallsController::handleCompletedProcesses();
417 }
418
419
420 bool GuiApplication::event(QEvent * e)
421 {
422         switch(e->type()) {
423         case QEvent::FileOpen: {
424                 // Open a file; this happens only on Mac OS X for now
425                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
426
427                 if (!current_view_ || !current_view_->view())
428                         // The application is not properly initialized yet.
429                         // So we acknowledge the event and delay the file opening
430                         // until LyX is ready.
431                         // FIXME UNICODE: FileName accept an utf8 encoded string.
432                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
433                 else
434                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
435                                 qstring_to_ucs4(foe->file())));
436
437                 e->accept();
438                 return true;
439         }
440         default:
441                 return QApplication::event(e);
442         }
443 }
444
445
446 bool GuiApplication::notify(QObject * receiver, QEvent * event)
447 {
448         try {
449                 return QApplication::notify(receiver, event);
450         }
451         catch (ExceptionMessage const & e) {
452                 if (e.type_ == ErrorException) {
453                         Alert::error(e.title_, e.details_);
454                         LyX::cref().exit(1);
455                 } else if (e.type_ == WarningException) {
456                         Alert::warning(e.title_, e.details_);
457                         return false;
458                 }
459         }
460         catch (exception const & e) {
461                 docstring s = _("LyX has caught an exception, it will now "
462                         "attempt to save all unsaved documents and exit."
463                         "\n\nException: ");
464                 s += from_ascii(e.what());
465                 Alert::error(_("Software exception Detected"), s);
466                 LyX::cref().exit(1);
467         }
468         catch (...) {
469                 docstring s = _("LyX has caught some really weird exception, it will "
470                         "now attempt to save all unsaved documents and exit.");
471                 Alert::error(_("Software exception Detected"), s);
472                 LyX::cref().exit(1);
473         }
474
475         return false;
476 }
477
478
479 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
480 {
481         QColor const & qcol = color_cache_.get(col);
482         if (!qcol.isValid()) {
483                 rgbcol.r = 0;
484                 rgbcol.g = 0;
485                 rgbcol.b = 0;
486                 return false;
487         }
488         rgbcol.r = qcol.red();
489         rgbcol.g = qcol.green();
490         rgbcol.b = qcol.blue();
491         return true;
492 }
493
494
495 string const GuiApplication::hexName(ColorCode col)
496 {
497         return ltrim(fromqstr(color_cache_.get(col).name()), "#");
498 }
499
500
501 void GuiApplication::updateColor(ColorCode)
502 {
503         // FIXME: Bleh, can't we just clear them all at once ?
504         color_cache_.clear();
505 }
506
507
508 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
509 {
510         SocketNotifier * sn = new SocketNotifier(this, fd, func);
511         socket_notifiers_[fd] = sn;
512         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
513 }
514
515
516 void GuiApplication::socketDataReceived(int fd)
517 {
518         socket_notifiers_[fd]->func_();
519 }
520
521
522 void GuiApplication::unregisterSocketCallback(int fd)
523 {
524         socket_notifiers_.erase(fd);
525 }
526
527
528 void GuiApplication::commitData(QSessionManager & sm)
529 {
530         /// The implementation is required to avoid an application exit
531         /// when session state save is triggered by session manager.
532         /// The default implementation sends a close event to all
533         /// visible top level widgets when session managment allows
534         /// interaction.
535         /// We are changing that to write all unsaved buffers...
536         if (sm.allowsInteraction() && !current_view_->quitWriteAll())
537                 sm.cancel();
538 }
539
540
541 void GuiApplication::addMenuTranslator()
542 {
543         installTranslator(new MenuTranslator(this));
544 }
545
546
547 bool GuiApplication::unregisterView(int id)
548 {
549         updateIds(views_, view_ids_);
550         BOOST_ASSERT(views_.find(id) != views_.end());
551         BOOST_ASSERT(views_[id]);
552
553         map<int, GuiView *>::iterator it;
554         for (it = views_.begin(); it != views_.end(); ++it) {
555                 if (it->first == id) {
556                         views_.erase(id);
557                         break;
558                 }
559         }
560         updateIds(views_, view_ids_);
561         return true;
562 }
563
564
565 bool GuiApplication::closeAllViews()
566 {
567         updateIds(views_, view_ids_);
568         if (views_.empty()) {
569                 // quit in CloseEvent will not be triggert
570                 qApp->quit();
571                 return true;
572         }
573
574         map<int, GuiView*> const cmap = views_;
575         map<int, GuiView*>::const_iterator it;
576         for (it = cmap.begin(); it != cmap.end(); ++it) {
577                 // TODO: return false when close event was ignored
578                 //       e.g. quitWriteAll()->'Cancel'
579                 //       maybe we need something like 'bool closeView()'
580                 it->second->close();
581                 // unregisterd by the CloseEvent
582         }
583
584         views_.clear();
585         view_ids_.clear();
586         return true;
587 }
588
589
590 GuiView & GuiApplication::view(int id) const
591 {
592         BOOST_ASSERT(views_.find(id) != views_.end());
593         return *views_.find(id)->second;
594 }
595
596
597 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
598 {
599         vector<int>::const_iterator it = view_ids_.begin();
600         vector<int>::const_iterator const end = view_ids_.end();
601         for (; it != end; ++it)
602                 view(*it).hideDialog(name, inset);
603 }
604
605
606 Buffer const * GuiApplication::updateInset(Inset const * inset) const
607 {
608         Buffer const * buffer_ = 0;
609         vector<int>::const_iterator it = view_ids_.begin();
610         vector<int>::const_iterator const end = view_ids_.end();
611         for (; it != end; ++it) {
612                 Buffer const * ptr = view(*it).updateInset(inset);
613                 if (ptr)
614                         buffer_ = ptr;
615         }
616         return buffer_;
617 }
618
619
620 ////////////////////////////////////////////////////////////////////////
621 // X11 specific stuff goes here...
622 #ifdef Q_WS_X11
623 bool GuiApplication::x11EventFilter(XEvent * xev)
624 {
625         if (!current_view_)
626                 return false;
627
628         switch (xev->type) {
629         case SelectionRequest: {
630                 if (xev->xselectionrequest.selection != XA_PRIMARY)
631                         break;
632                 LYXERR(Debug::GUI, "X requested selection.");
633                 BufferView * bv = current_view_->view();
634                 if (bv) {
635                         docstring const sel = bv->requestSelection();
636                         if (!sel.empty())
637                                 selection_.put(sel);
638                 }
639                 break;
640         }
641         case SelectionClear: {
642                 if (xev->xselectionclear.selection != XA_PRIMARY)
643                         break;
644                 LYXERR(Debug::GUI, "Lost selection.");
645                 BufferView * bv = current_view_->view();
646                 if (bv)
647                         bv->clearSelection();
648                 break;
649         }
650         }
651         return false;
652 }
653 #endif
654
655 } // namespace frontend
656
657
658 ////////////////////////////////////////////////////////////////////
659 //
660 // Font stuff
661 //
662 ////////////////////////////////////////////////////////////////////
663
664 frontend::FontLoader & theFontLoader()
665 {
666         static frontend::NoGuiFontLoader no_gui_font_loader;
667
668         if (!use_gui)
669                 return no_gui_font_loader;
670
671         BOOST_ASSERT(frontend::guiApp);
672         return frontend::guiApp->fontLoader();
673 }
674
675
676 frontend::FontMetrics const & theFontMetrics(Font const & f)
677 {
678         return theFontMetrics(f.fontInfo());
679 }
680
681
682 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
683 {
684         static frontend::NoGuiFontMetrics no_gui_font_metrics;
685
686         if (!use_gui)
687                 return no_gui_font_metrics;
688
689         BOOST_ASSERT(frontend::guiApp);
690         return frontend::guiApp->fontLoader().metrics(f);
691 }
692
693
694 frontend::Clipboard & theClipboard()
695 {
696         BOOST_ASSERT(frontend::guiApp);
697         return frontend::guiApp->clipboard();
698 }
699
700
701 frontend::Selection & theSelection()
702 {
703         BOOST_ASSERT(frontend::guiApp);
704         return frontend::guiApp->selection();
705 }
706
707 } // namespace lyx
708
709 #include "GuiApplication_moc.cpp"