]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiApplication.cpp
08817607a737bc6a80c1d61c30913d438bf4e2f5
[features.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 #include "Dialogs.h"
21
22 #include "frontends/alert.h"
23 #include "frontends/Application.h"
24 #include "frontends/NoGuiFontLoader.h"
25 #include "frontends/NoGuiFontMetrics.h"
26 #include "frontends/FontLoader.h"
27 #include "frontends/FontMetrics.h"
28
29 #include "graphics/LoaderQueue.h"
30
31 #include "support/ExceptionMessage.h"
32 #include "support/FileName.h"
33 #include "support/lstrings.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36
37 #include "BufferList.h"
38 #include "BufferView.h"
39 #include "debug.h"
40 #include "Font.h"
41 #include "FuncRequest.h"
42 #include "gettext.h"
43 #include "LyX.h"
44 #include "LyXFunc.h"
45 #include "LyXRC.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 std::endl;
75 using std::map;
76 using std::string;
77 using std::vector;
78
79
80 namespace lyx {
81
82 frontend::Application * createApplication(int & argc, char * argv[])
83 {
84         return new frontend::GuiApplication(argc, argv);
85 }
86
87
88 namespace frontend {
89
90 class SocketNotifier : public QSocketNotifier
91 {
92 public:
93         /// connect a connection notification from the LyXServerSocket
94         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
95                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
96         {}
97
98 public:
99         /// The callback function
100         Application::SocketCallback func_;
101 };
102
103
104 ////////////////////////////////////////////////////////////////////////
105 // Mac specific stuff goes here...
106
107 class MenuTranslator : public QTranslator
108 {
109 public:
110         MenuTranslator(QObject * parent)
111                 : QTranslator(parent)
112         {}
113
114         QString translate(const char * /*context*/, 
115           const char * sourceText, 
116           const char * /*comment*/ = 0) 
117         {
118                 string const s = sourceText;
119                 if (s == N_("About %1") || s == N_("Preferences") 
120                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
121                         return qt_(s);
122                 else 
123                         return QString();
124         }
125 };
126
127
128 ///////////////////////////////////////////////////////////////
129 // You can find more platform specific stuff
130 // at the end of this file...
131 ///////////////////////////////////////////////////////////////
132
133
134 using support::FileName;
135
136 GuiApplication * guiApp;
137
138
139 GuiApplication::GuiApplication(int & argc, char ** argv)
140         : QApplication(argc, argv), Application()
141 {
142         QString app_name = "LyX";
143         QCoreApplication::setOrganizationName(app_name);
144         QCoreApplication::setOrganizationDomain("lyx.org");
145         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
146
147         // Qt bug? setQuitOnLastWindowClosed(true); does not work
148         setQuitOnLastWindowClosed(false);
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         // This allows to translate the strings that appear in the LyX menu.
179         addMenuTranslator();
180 #endif
181
182         using namespace lyx::graphics;
183
184         Image::newImage = boost::bind(&GuiImage::newImage);
185         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
186
187         // needs to be done before reading lyxrc
188         QWidget w;
189         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
190
191         LoaderQueue::setPriority(10,100);
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
200
201 GuiApplication::~GuiApplication()
202 {
203         socket_notifiers_.clear();
204 }
205
206
207 LyXView & GuiApplication::createView(string const & geometry_arg)
208 {
209         int const id = createRegisteredView();
210         GuiView * view  = views_[id];
211         theLyXFunc().setLyXView(view);
212
213         view->init();
214         view->show();
215         if (!geometry_arg.empty()) {
216 #ifdef Q_WS_WIN
217                 int x, y;
218                 int w, h;
219                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
220                 re.indexIn(toqstr(geometry_arg.c_str()));
221                 w = re.cap(1).toInt();
222                 h = re.cap(2).toInt();
223                 x = re.cap(3).toInt();
224                 y = re.cap(4).toInt();
225                 view->setGeometry(x, y, w, h);
226 #endif
227         }
228         view->setFocus();
229
230         setCurrentView(*view);
231
232         return *view;
233 }
234
235
236
237
238 Clipboard & GuiApplication::clipboard()
239 {
240         return clipboard_;
241 }
242
243
244 Selection & GuiApplication::selection()
245 {
246         return selection_;
247 }
248
249
250 int GuiApplication::exec()
251 {
252         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
253         return QApplication::exec();
254 }
255
256
257 void GuiApplication::exit(int status)
258 {
259         QApplication::exit(status);
260 }
261
262
263 void GuiApplication::execBatchCommands()
264 {
265         LyX::ref().execBatchCommands();
266 }
267
268
269 string const GuiApplication::romanFontName()
270 {
271         QFont font;
272         font.setKerning(false);
273         font.setStyleHint(QFont::Serif);
274         font.setFamily("serif");
275
276         return fromqstr(QFontInfo(font).family());
277 }
278
279
280 string const GuiApplication::sansFontName()
281 {
282         QFont font;
283         font.setKerning(false);
284         font.setStyleHint(QFont::SansSerif);
285         font.setFamily("sans");
286
287         return fromqstr(QFontInfo(font).family());
288 }
289
290
291 string const GuiApplication::typewriterFontName()
292 {
293         QFont font;
294         font.setKerning(false);
295         font.setStyleHint(QFont::TypeWriter);
296         font.setFamily("monospace");
297
298         return fromqstr(QFontInfo(font).family());
299 }
300
301
302 bool GuiApplication::event(QEvent * e)
303 {
304         switch(e->type()) {
305         case QEvent::FileOpen: {
306                 // Open a file; this happens only on Mac OS X for now
307                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
308
309                 if (!currentView() || !currentView()->view())
310                         // The application is not properly initialized yet.
311                         // So we acknowledge the event and delay the file opening
312                         // until LyX is ready.
313                         // FIXME UNICODE: FileName accept an utf8 encoded string.
314                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
315                 else
316                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
317                                 qstring_to_ucs4(foe->file())));
318
319                 e->accept();
320                 return true;
321         }
322         default:
323                 return QApplication::event(e);
324         }
325 }
326
327
328 bool GuiApplication::notify(QObject * receiver, QEvent * event)
329 {
330         try {
331                 return QApplication::notify(receiver, event);
332         }
333         catch (support::ExceptionMessage const & e) {
334                 if (e.type_ == support::ErrorException) {
335                         Alert::error(e.title_, e.details_);
336                         LyX::cref().emergencyCleanup();
337                         QApplication::exit(1);
338                 } else if (e.type_ == support::WarningException) {
339                         Alert::warning(e.title_, e.details_);
340                         return false;
341                 }
342         }
343         catch (std::exception const & e) {
344                 docstring s = _("LyX has caught an exception, it will now "
345                         "attemp to save all unsaved documents and exit."
346                         "\n\nException: ");
347                 s += from_ascii(e.what());
348                 Alert::error(_("Software exception Detected"), s);
349                 LyX::cref().emergencyCleanup();
350                 QApplication::exit(1);
351         }
352         catch (...) {
353                 docstring s = _("LyX has caught some really weird exception, it will "
354                         "now attemp to save all unsaved documents and exit.");
355                 Alert::error(_("Software exception Detected"), s);
356                 LyX::cref().emergencyCleanup();
357                 QApplication::exit(1);
358         }
359
360         return false;
361 }
362
363
364 void GuiApplication::syncEvents()
365 {
366         // This is the ONLY place where processEvents may be called.
367         // During screen update/ redraw, this method is disabled to
368         // prevent keyboard events being handed to the LyX core, where
369         // they could cause re-entrant calls to screen update.
370         processEvents(QEventLoop::ExcludeUserInputEvents);
371 }
372
373
374 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
375 {
376         QColor const & qcol = color_cache_.get(col);
377         if (!qcol.isValid()) {
378                 rgbcol.r = 0;
379                 rgbcol.g = 0;
380                 rgbcol.b = 0;
381                 return false;
382         }
383         rgbcol.r = qcol.red();
384         rgbcol.g = qcol.green();
385         rgbcol.b = qcol.blue();
386         return true;
387 }
388
389
390 string const GuiApplication::hexName(ColorCode col)
391 {
392         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
393 }
394
395
396 void GuiApplication::updateColor(ColorCode)
397 {
398         // FIXME: Bleh, can't we just clear them all at once ?
399         color_cache_.clear();
400 }
401
402
403 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
404 {
405         SocketNotifier * sn = new SocketNotifier(this, fd, func);
406         socket_notifiers_[fd] = sn;
407         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
408 }
409
410
411 void GuiApplication::socketDataReceived(int fd)
412 {
413         socket_notifiers_[fd]->func_();
414 }
415
416
417 void GuiApplication::unregisterSocketCallback(int fd)
418 {
419         socket_notifiers_.erase(fd);
420 }
421
422
423 void GuiApplication::commitData(QSessionManager & sm)
424 {
425         /// The implementation is required to avoid an application exit
426         /// when session state save is triggered by session manager.
427         /// The default implementation sends a close event to all
428         /// visible top level widgets when session managment allows
429         /// interaction.
430         /// We are changing that to write all unsaved buffers...
431         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
432                 sm.cancel();
433 }
434
435
436 void GuiApplication::addMenuTranslator()
437 {
438         installTranslator(new MenuTranslator(this));
439 }
440
441
442 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
443 {
444         ids.clear();
445         map<int, GuiView *>::const_iterator it;
446         for (it = stdmap.begin(); it != stdmap.end(); ++it)
447                 ids.push_back(it->first);
448 }
449
450
451 int GuiApplication::createRegisteredView()
452 {
453         updateIds(views_, view_ids_);
454         int id = 0;
455         while (views_.find(id) != views_.end())
456                 id++;
457         views_[id] = new GuiView(id);
458         updateIds(views_, view_ids_);
459         return id;
460 }
461
462
463 bool GuiApplication::unregisterView(int id)
464 {
465         updateIds(views_, view_ids_);
466         BOOST_ASSERT(views_.find(id) != views_.end());
467         BOOST_ASSERT(views_[id]);
468
469         map<int, GuiView *>::iterator it;
470         for (it = views_.begin(); it != views_.end(); ++it) {
471                 if (it->first == id) {
472                         views_.erase(id);
473                         break;
474                 }
475         }
476         updateIds(views_, view_ids_);
477         return true;
478 }
479
480
481 bool GuiApplication::closeAllViews()
482 {
483         updateIds(views_, view_ids_);
484         if (views_.empty()) {
485                 // quit in CloseEvent will not be triggert
486                 qApp->quit();
487                 return true;
488         }
489
490         map<int, GuiView*> const cmap = views_;
491         map<int, GuiView*>::const_iterator it;
492         for (it = cmap.begin(); it != cmap.end(); ++it) {
493                 // TODO: return false when close event was ignored
494                 //       e.g. quitWriteAll()->'Cancel'
495                 //       maybe we need something like 'bool closeView()'
496                 it->second->close();
497                 // unregisterd by the CloseEvent
498         }
499
500         views_.clear();
501         view_ids_.clear();
502         return true;
503 }
504
505
506 LyXView & GuiApplication::view(int id) const
507 {
508         BOOST_ASSERT(views_.find(id) != views_.end());
509         return *views_.find(id)->second;
510 }
511
512
513 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
514 {
515         vector<int>::const_iterator it = view_ids_.begin();
516         vector<int>::const_iterator const end = view_ids_.end();
517         for (; it != end; ++it)
518                 view(*it).getDialogs().hide(name, inset);
519 }
520
521
522 Buffer const * GuiApplication::updateInset(Inset const * inset) const
523 {
524         Buffer const * buffer_ = 0;
525         vector<int>::const_iterator it = view_ids_.begin();
526         vector<int>::const_iterator const end = view_ids_.end();
527         for (; it != end; ++it) {
528                 Buffer const * ptr = view(*it).updateInset(inset);
529                 if (ptr)
530                         buffer_ = ptr;
531         }
532         return buffer_;
533 }
534
535
536 ////////////////////////////////////////////////////////////////////////
537 // X11 specific stuff goes here...
538 #ifdef Q_WS_X11
539 bool GuiApplication::x11EventFilter(XEvent * xev)
540 {
541         if (!currentView())
542                 return false;
543
544         switch (xev->type) {
545         case SelectionRequest: {
546                 if (xev->xselectionrequest.selection != XA_PRIMARY)
547                         break;
548                 LYXERR(Debug::GUI, "X requested selection.");
549                 BufferView * bv = currentView()->view();
550                 if (bv) {
551                         docstring const sel = bv->requestSelection();
552                         if (!sel.empty())
553                                 selection_.put(sel);
554                 }
555                 break;
556         }
557         case SelectionClear: {
558                 if (xev->xselectionclear.selection != XA_PRIMARY)
559                         break;
560                 LYXERR(Debug::GUI, "Lost selection.");
561                 BufferView * bv = currentView()->view();
562                 if (bv)
563                         bv->clearSelection();
564                 break;
565         }
566         }
567         return false;
568 }
569 #endif
570
571 } // namespace frontend
572
573
574 ////////////////////////////////////////////////////////////////////
575 //
576 // Font stuff
577 //
578 ////////////////////////////////////////////////////////////////////
579
580 frontend::FontLoader & theFontLoader()
581 {
582         static frontend::NoGuiFontLoader no_gui_font_loader;
583
584         if (!use_gui)
585                 return no_gui_font_loader;
586
587         BOOST_ASSERT(theApp());
588         return theApp()->fontLoader();
589 }
590
591
592 frontend::FontMetrics const & theFontMetrics(Font const & f)
593 {
594         return theFontMetrics(f.fontInfo());
595 }
596
597
598 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
599 {
600         static frontend::NoGuiFontMetrics no_gui_font_metrics;
601
602         if (!use_gui)
603                 return no_gui_font_metrics;
604
605         BOOST_ASSERT(theApp());
606         return theApp()->fontLoader().metrics(f);
607 }
608
609
610 frontend::Clipboard & theClipboard()
611 {
612         BOOST_ASSERT(frontend::guiApp);
613         return frontend::guiApp->clipboard();
614 }
615
616
617 frontend::Selection & theSelection()
618 {
619         BOOST_ASSERT(frontend::guiApp);
620         return frontend::guiApp->selection();
621 }
622
623 } // namespace lyx
624
625 #include "GuiApplication_moc.cpp"