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