]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Spoiling some fun from Andre': put Application on a diet and remove unnecessary strin...
[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->init();
238         view->show();
239         if (!geometry_arg.empty()) {
240 #ifdef Q_WS_WIN
241                 int x, y;
242                 int w, h;
243                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
244                 re.indexIn(toqstr(geometry_arg.c_str()));
245                 w = re.cap(1).toInt();
246                 h = re.cap(2).toInt();
247                 x = re.cap(3).toInt();
248                 y = re.cap(4).toInt();
249                 view->setGeometry(x, y, w, h);
250 #endif
251         }
252         view->setFocus();
253
254         setCurrentView(*view);
255
256         return *view;
257 }
258
259
260
261
262 Clipboard & GuiApplication::clipboard()
263 {
264         return clipboard_;
265 }
266
267
268 Selection & GuiApplication::selection()
269 {
270         return selection_;
271 }
272
273
274 int GuiApplication::exec()
275 {
276         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
277         return QApplication::exec();
278 }
279
280
281 void GuiApplication::exit(int status)
282 {
283         QApplication::exit(status);
284 }
285
286
287 void GuiApplication::execBatchCommands()
288 {
289         LyX::ref().execBatchCommands();
290 }
291
292
293 QString const GuiApplication::romanFontName()
294 {
295         QFont font;
296         font.setKerning(false);
297         font.setStyleHint(QFont::Serif);
298         font.setFamily("serif");
299
300         return QFontInfo(font).family();
301 }
302
303
304 QString const GuiApplication::sansFontName()
305 {
306         QFont font;
307         font.setKerning(false);
308         font.setStyleHint(QFont::SansSerif);
309         font.setFamily("sans");
310
311         return QFontInfo(font).family();
312 }
313
314
315 QString const GuiApplication::typewriterFontName()
316 {
317         QFont font;
318         font.setKerning(false);
319         font.setStyleHint(QFont::TypeWriter);
320         font.setFamily("monospace");
321
322         return QFontInfo(font).family();
323 }
324
325
326 bool GuiApplication::event(QEvent * e)
327 {
328         switch(e->type()) {
329         case QEvent::FileOpen: {
330                 // Open a file; this happens only on Mac OS X for now
331                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
332
333                 if (!current_view_ || !current_view_->view())
334                         // The application is not properly initialized yet.
335                         // So we acknowledge the event and delay the file opening
336                         // until LyX is ready.
337                         // FIXME UNICODE: FileName accept an utf8 encoded string.
338                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
339                 else
340                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
341                                 qstring_to_ucs4(foe->file())));
342
343                 e->accept();
344                 return true;
345         }
346         default:
347                 return QApplication::event(e);
348         }
349 }
350
351
352 bool GuiApplication::notify(QObject * receiver, QEvent * event)
353 {
354         try {
355                 return QApplication::notify(receiver, event);
356         }
357         catch (support::ExceptionMessage const & e) {
358                 if (e.type_ == support::ErrorException) {
359                         Alert::error(e.title_, e.details_);
360                         LyX::cref().emergencyCleanup();
361                         QApplication::exit(1);
362                 } else if (e.type_ == support::WarningException) {
363                         Alert::warning(e.title_, e.details_);
364                         return false;
365                 }
366         }
367         catch (std::exception const & e) {
368                 docstring s = _("LyX has caught an exception, it will now "
369                         "attemp to save all unsaved documents and exit."
370                         "\n\nException: ");
371                 s += from_ascii(e.what());
372                 Alert::error(_("Software exception Detected"), s);
373                 LyX::cref().emergencyCleanup();
374                 QApplication::exit(1);
375         }
376         catch (...) {
377                 docstring s = _("LyX has caught some really weird exception, it will "
378                         "now attemp to save all unsaved documents and exit.");
379                 Alert::error(_("Software exception Detected"), s);
380                 LyX::cref().emergencyCleanup();
381                 QApplication::exit(1);
382         }
383
384         return false;
385 }
386
387
388 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
389 {
390         QColor const & qcol = color_cache_.get(col);
391         if (!qcol.isValid()) {
392                 rgbcol.r = 0;
393                 rgbcol.g = 0;
394                 rgbcol.b = 0;
395                 return false;
396         }
397         rgbcol.r = qcol.red();
398         rgbcol.g = qcol.green();
399         rgbcol.b = qcol.blue();
400         return true;
401 }
402
403
404 string const GuiApplication::hexName(ColorCode col)
405 {
406         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
407 }
408
409
410 void GuiApplication::updateColor(ColorCode)
411 {
412         // FIXME: Bleh, can't we just clear them all at once ?
413         color_cache_.clear();
414 }
415
416
417 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
418 {
419         SocketNotifier * sn = new SocketNotifier(this, fd, func);
420         socket_notifiers_[fd] = sn;
421         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
422 }
423
424
425 void GuiApplication::socketDataReceived(int fd)
426 {
427         socket_notifiers_[fd]->func_();
428 }
429
430
431 void GuiApplication::unregisterSocketCallback(int fd)
432 {
433         socket_notifiers_.erase(fd);
434 }
435
436
437 void GuiApplication::commitData(QSessionManager & sm)
438 {
439         /// The implementation is required to avoid an application exit
440         /// when session state save is triggered by session manager.
441         /// The default implementation sends a close event to all
442         /// visible top level widgets when session managment allows
443         /// interaction.
444         /// We are changing that to write all unsaved buffers...
445         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
446                 sm.cancel();
447 }
448
449
450 void GuiApplication::addMenuTranslator()
451 {
452         installTranslator(new MenuTranslator(this));
453 }
454
455
456 bool GuiApplication::unregisterView(int id)
457 {
458         updateIds(views_, view_ids_);
459         BOOST_ASSERT(views_.find(id) != views_.end());
460         BOOST_ASSERT(views_[id]);
461
462         map<int, GuiView *>::iterator it;
463         for (it = views_.begin(); it != views_.end(); ++it) {
464                 if (it->first == id) {
465                         views_.erase(id);
466                         break;
467                 }
468         }
469         updateIds(views_, view_ids_);
470         return true;
471 }
472
473
474 bool GuiApplication::closeAllViews()
475 {
476         updateIds(views_, view_ids_);
477         if (views_.empty()) {
478                 // quit in CloseEvent will not be triggert
479                 qApp->quit();
480                 return true;
481         }
482
483         map<int, GuiView*> const cmap = views_;
484         map<int, GuiView*>::const_iterator it;
485         for (it = cmap.begin(); it != cmap.end(); ++it) {
486                 // TODO: return false when close event was ignored
487                 //       e.g. quitWriteAll()->'Cancel'
488                 //       maybe we need something like 'bool closeView()'
489                 it->second->close();
490                 // unregisterd by the CloseEvent
491         }
492
493         views_.clear();
494         view_ids_.clear();
495         return true;
496 }
497
498
499 LyXView & GuiApplication::view(int id) const
500 {
501         BOOST_ASSERT(views_.find(id) != views_.end());
502         return *views_.find(id)->second;
503 }
504
505
506 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
507 {
508         vector<int>::const_iterator it = view_ids_.begin();
509         vector<int>::const_iterator const end = view_ids_.end();
510         for (; it != end; ++it)
511                 view(*it).hideDialog(name, inset);
512 }
513
514
515 Buffer const * GuiApplication::updateInset(Inset const * inset) const
516 {
517         Buffer const * buffer_ = 0;
518         vector<int>::const_iterator it = view_ids_.begin();
519         vector<int>::const_iterator const end = view_ids_.end();
520         for (; it != end; ++it) {
521                 Buffer const * ptr = view(*it).updateInset(inset);
522                 if (ptr)
523                         buffer_ = ptr;
524         }
525         return buffer_;
526 }
527
528
529 ////////////////////////////////////////////////////////////////////////
530 // X11 specific stuff goes here...
531 #ifdef Q_WS_X11
532 bool GuiApplication::x11EventFilter(XEvent * xev)
533 {
534         if (!current_view_)
535                 return false;
536
537         switch (xev->type) {
538         case SelectionRequest: {
539                 if (xev->xselectionrequest.selection != XA_PRIMARY)
540                         break;
541                 LYXERR(Debug::GUI, "X requested selection.");
542                 BufferView * bv = current_view_->view();
543                 if (bv) {
544                         docstring const sel = bv->requestSelection();
545                         if (!sel.empty())
546                                 selection_.put(sel);
547                 }
548                 break;
549         }
550         case SelectionClear: {
551                 if (xev->xselectionclear.selection != XA_PRIMARY)
552                         break;
553                 LYXERR(Debug::GUI, "Lost selection.");
554                 BufferView * bv = current_view_->view();
555                 if (bv)
556                         bv->clearSelection();
557                 break;
558         }
559         }
560         return false;
561 }
562 #endif
563
564 } // namespace frontend
565
566
567 ////////////////////////////////////////////////////////////////////
568 //
569 // Font stuff
570 //
571 ////////////////////////////////////////////////////////////////////
572
573 frontend::FontLoader & theFontLoader()
574 {
575         static frontend::NoGuiFontLoader no_gui_font_loader;
576
577         if (!use_gui)
578                 return no_gui_font_loader;
579
580         BOOST_ASSERT(frontend::guiApp);
581         return frontend::guiApp->fontLoader();
582 }
583
584
585 frontend::FontMetrics const & theFontMetrics(Font const & f)
586 {
587         return theFontMetrics(f.fontInfo());
588 }
589
590
591 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
592 {
593         static frontend::NoGuiFontMetrics no_gui_font_metrics;
594
595         if (!use_gui)
596                 return no_gui_font_metrics;
597
598         BOOST_ASSERT(frontend::guiApp);
599         return frontend::guiApp->fontLoader().metrics(f);
600 }
601
602
603 frontend::Clipboard & theClipboard()
604 {
605         BOOST_ASSERT(frontend::guiApp);
606         return frontend::guiApp->clipboard();
607 }
608
609
610 frontend::Selection & theSelection()
611 {
612         BOOST_ASSERT(frontend::guiApp);
613         return frontend::guiApp->selection();
614 }
615
616 } // namespace lyx
617
618 #include "GuiApplication_moc.cpp"