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