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