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