]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiApplication.cpp
merge frontend::Gui and frontend::Application
[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
24 #include "graphics/LoaderQueue.h"
25
26 #include "support/ExceptionMessage.h"
27 #include "support/FileName.h"
28 #include "support/lstrings.h"
29 #include "support/os.h"
30 #include "support/Package.h"
31
32 #include "BufferList.h"
33 #include "BufferView.h"
34 #include "debug.h"
35 #include "FuncRequest.h"
36 #include "gettext.h"
37 #include "LyX.h"
38 #include "LyXFunc.h"
39 #include "LyXRC.h"
40 #include "version.h"
41
42 #include <QApplication>
43 #include <QClipboard>
44 #include <QEventLoop>
45 #include <QFileOpenEvent>
46 #include <QLocale>
47 #include <QLibraryInfo>
48 #include <QPixmapCache>
49 #include <QRegExp>
50 #include <QSessionManager>
51 #include <QSocketNotifier>
52 #include <QTextCodec>
53 #include <QTimer>
54 #include <QTranslator>
55 #include <QWidget>
56
57 #ifdef Q_WS_X11
58 #include <X11/Xatom.h>
59 #include <X11/Xlib.h>
60 #undef CursorShape
61 #undef None
62 #endif
63
64 #include <boost/bind.hpp>
65
66 #include <exception>
67
68 using std::endl;
69 using std::map;
70 using std::string;
71 using std::vector;
72
73
74 namespace lyx {
75
76 frontend::Application * createApplication(int & argc, char * argv[])
77 {
78         return new frontend::GuiApplication(argc, argv);
79 }
80
81
82 namespace frontend {
83
84 class SocketNotifier : public QSocketNotifier
85 {
86 public:
87         /// connect a connection notification from the LyXServerSocket
88         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
89                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
90         {}
91
92 public:
93         /// The callback function
94         Application::SocketCallback func_;
95 };
96
97
98 ////////////////////////////////////////////////////////////////////////
99 // Mac specific stuff goes here...
100
101 class MenuTranslator : public QTranslator
102 {
103 public:
104         MenuTranslator(QObject * parent)
105                 : QTranslator(parent)
106         {}
107
108         QString translate(const char * /*context*/, 
109           const char * sourceText, 
110           const char * /*comment*/ = 0) 
111         {
112                 string const s = sourceText;
113                 if (s == N_("About %1") || s == N_("Preferences") 
114                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
115                         return qt_(s);
116                 else 
117                         return QString();
118         }
119 };
120
121
122 ///////////////////////////////////////////////////////////////
123 // You can find more platform specific stuff
124 // at the end of this file...
125 ///////////////////////////////////////////////////////////////
126
127
128 using support::FileName;
129
130 GuiApplication * guiApp;
131
132
133 GuiApplication::GuiApplication(int & argc, char ** argv)
134         : QApplication(argc, argv), Application()
135 {
136         QString app_name = "LyX";
137         QCoreApplication::setOrganizationName(app_name);
138         QCoreApplication::setOrganizationDomain("lyx.org");
139         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
140
141         // Qt bug? setQuitOnLastWindowClosed(true); does not work
142         setQuitOnLastWindowClosed(false);
143
144 #ifdef Q_WS_X11
145         // doubleClickInterval() is 400 ms on X11 which is just too long.
146         // On Windows and Mac OS X, the operating system's value is used.
147         // On Microsoft Windows, calling this function sets the double
148         // click interval for all applications. So we don't!
149         QApplication::setDoubleClickInterval(300);
150 #endif
151
152         // install translation file for Qt built-in dialogs
153         QString language_name = QString("qt_") + QLocale::system().name();
154         
155         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
156         // Short-named translator can be loaded from a long name, but not the
157         // opposite. Therefore, long name should be used without truncation.
158         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
159         if (qt_trans_.load(language_name,
160                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
161         {
162                 installTranslator(&qt_trans_);
163                 // even if the language calls for RtL, don't do that
164                 setLayoutDirection(Qt::LeftToRight);
165                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
166                         << fromqstr(language_name));
167         } else
168                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
169                         << fromqstr(language_name));
170
171 #ifdef Q_WS_MACX
172         // This allows to translate the strings that appear in the LyX menu.
173         addMenuTranslator();
174 #endif
175
176         using namespace lyx::graphics;
177
178         Image::newImage = boost::bind(&GuiImage::newImage);
179         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
180
181         // needs to be done before reading lyxrc
182         QWidget w;
183         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
184
185         LoaderQueue::setPriority(10,100);
186
187         guiApp = this;
188
189         // Set the cache to 5120 kilobytes which corresponds to screen size of
190         // 1280 by 1024 pixels with a color depth of 32 bits.
191         QPixmapCache::setCacheLimit(5120);
192 }
193
194
195 GuiApplication::~GuiApplication()
196 {
197         socket_notifiers_.clear();
198 }
199
200
201 LyXView & GuiApplication::createView(string const & geometry_arg)
202 {
203         int const id = createRegisteredView();
204         GuiView * view  = views_[id];
205         theLyXFunc().setLyXView(view);
206
207         view->init();
208         view->show();
209         if (!geometry_arg.empty()) {
210 #ifdef Q_WS_WIN
211                 int x, y;
212                 int w, h;
213                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
214                 re.indexIn(toqstr(geometry_arg.c_str()));
215                 w = re.cap(1).toInt();
216                 h = re.cap(2).toInt();
217                 x = re.cap(3).toInt();
218                 y = re.cap(4).toInt();
219                 view->setGeometry(x, y, w, h);
220 #endif
221         }
222         view->setFocus();
223
224         setCurrentView(*view);
225
226         return *view;
227 }
228
229
230
231
232 Clipboard & GuiApplication::clipboard()
233 {
234         return clipboard_;
235 }
236
237
238 Selection & GuiApplication::selection()
239 {
240         return selection_;
241 }
242
243
244 int GuiApplication::exec()
245 {
246         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
247         return QApplication::exec();
248 }
249
250
251 void GuiApplication::exit(int status)
252 {
253         QApplication::exit(status);
254 }
255
256
257 void GuiApplication::execBatchCommands()
258 {
259         LyX::ref().execBatchCommands();
260 }
261
262
263 string const GuiApplication::romanFontName()
264 {
265         QFont font;
266         font.setKerning(false);
267         font.setStyleHint(QFont::Serif);
268         font.setFamily("serif");
269
270         return fromqstr(QFontInfo(font).family());
271 }
272
273
274 string const GuiApplication::sansFontName()
275 {
276         QFont font;
277         font.setKerning(false);
278         font.setStyleHint(QFont::SansSerif);
279         font.setFamily("sans");
280
281         return fromqstr(QFontInfo(font).family());
282 }
283
284
285 string const GuiApplication::typewriterFontName()
286 {
287         QFont font;
288         font.setKerning(false);
289         font.setStyleHint(QFont::TypeWriter);
290         font.setFamily("monospace");
291
292         return fromqstr(QFontInfo(font).family());
293 }
294
295
296 bool GuiApplication::event(QEvent * e)
297 {
298         switch(e->type()) {
299         case QEvent::FileOpen: {
300                 // Open a file; this happens only on Mac OS X for now
301                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
302
303                 if (!currentView() || !currentView()->view())
304                         // The application is not properly initialized yet.
305                         // So we acknowledge the event and delay the file opening
306                         // until LyX is ready.
307                         // FIXME UNICODE: FileName accept an utf8 encoded string.
308                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
309                 else
310                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
311                                 qstring_to_ucs4(foe->file())));
312
313                 e->accept();
314                 return true;
315         }
316         default:
317                 return QApplication::event(e);
318         }
319 }
320
321
322 bool GuiApplication::notify(QObject * receiver, QEvent * event)
323 {
324         try {
325                 return QApplication::notify(receiver, event);
326         }
327         catch (support::ExceptionMessage const & e) {
328                 if (e.type_ == support::ErrorException) {
329                         Alert::error(e.title_, e.details_);
330                         LyX::cref().emergencyCleanup();
331                         QApplication::exit(1);
332                 } else if (e.type_ == support::WarningException) {
333                         Alert::warning(e.title_, e.details_);
334                         return false;
335                 }
336         }
337         catch (std::exception const & e) {
338                 docstring s = _("LyX has caught an exception, it will now "
339                         "attemp to save all unsaved documents and exit."
340                         "\n\nException: ");
341                 s += from_ascii(e.what());
342                 Alert::error(_("Software exception Detected"), s);
343                 LyX::cref().emergencyCleanup();
344                 QApplication::exit(1);
345         }
346         catch (...) {
347                 docstring s = _("LyX has caught some really weird exception, it will "
348                         "now attemp to save all unsaved documents and exit.");
349                 Alert::error(_("Software exception Detected"), s);
350                 LyX::cref().emergencyCleanup();
351                 QApplication::exit(1);
352         }
353
354         return false;
355 }
356
357
358 void GuiApplication::syncEvents()
359 {
360         // This is the ONLY place where processEvents may be called.
361         // During screen update/ redraw, this method is disabled to
362         // prevent keyboard events being handed to the LyX core, where
363         // they could cause re-entrant calls to screen update.
364         processEvents(QEventLoop::ExcludeUserInputEvents);
365 }
366
367
368 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
369 {
370         QColor const & qcol = color_cache_.get(col);
371         if (!qcol.isValid()) {
372                 rgbcol.r = 0;
373                 rgbcol.g = 0;
374                 rgbcol.b = 0;
375                 return false;
376         }
377         rgbcol.r = qcol.red();
378         rgbcol.g = qcol.green();
379         rgbcol.b = qcol.blue();
380         return true;
381 }
382
383
384 string const GuiApplication::hexName(ColorCode col)
385 {
386         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
387 }
388
389
390 void GuiApplication::updateColor(ColorCode)
391 {
392         // FIXME: Bleh, can't we just clear them all at once ?
393         color_cache_.clear();
394 }
395
396
397 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
398 {
399         SocketNotifier * sn = new SocketNotifier(this, fd, func);
400         socket_notifiers_[fd] = sn;
401         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
402 }
403
404
405 void GuiApplication::socketDataReceived(int fd)
406 {
407         socket_notifiers_[fd]->func_();
408 }
409
410
411 void GuiApplication::unregisterSocketCallback(int fd)
412 {
413         socket_notifiers_.erase(fd);
414 }
415
416
417 void GuiApplication::commitData(QSessionManager & sm)
418 {
419         /// The implementation is required to avoid an application exit
420         /// when session state save is triggered by session manager.
421         /// The default implementation sends a close event to all
422         /// visible top level widgets when session managment allows
423         /// interaction.
424         /// We are changing that to write all unsaved buffers...
425         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
426                 sm.cancel();
427 }
428
429
430 void GuiApplication::addMenuTranslator()
431 {
432         installTranslator(new MenuTranslator(this));
433 }
434
435
436 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
437 {
438         ids.clear();
439         map<int, GuiView *>::const_iterator it;
440         for (it = stdmap.begin(); it != stdmap.end(); ++it)
441                 ids.push_back(it->first);
442 }
443
444
445 int GuiApplication::createRegisteredView()
446 {
447         updateIds(views_, view_ids_);
448         int id = 0;
449         while (views_.find(id) != views_.end())
450                 id++;
451         views_[id] = new GuiView(id);
452         updateIds(views_, view_ids_);
453         return id;
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 LyXView & 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).getDialogs().hide(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 (!currentView())
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 = currentView()->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 = currentView()->view();
556                 if (bv)
557                         bv->clearSelection();
558                 break;
559         }
560         }
561         return false;
562 }
563 #endif
564
565 } // namespace frontend
566 } // namespace lyx
567
568 #include "GuiApplication_moc.cpp"