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