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