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