]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
remove #includes; cosmetics
[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 "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 <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()
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 LyXView & GuiApplication::createView(unsigned int width,
198                                   unsigned int height,
199                                   int posx, int posy,
200                                   int maximized,
201                                   unsigned int iconSizeXY,
202                                   const std::string & geometryArg)
203 {
204         int const id = gui_.createRegisteredView();
205         GuiView & view = static_cast<GuiView &>(gui_.view(id));
206         theLyXFunc().setLyXView(&view);
207
208         view.init();
209         view.setGeometry(width, height, posx, posy, GuiView::Maximized(maximized),
210                 iconSizeXY, geometryArg);
211
212         view.setFocus();
213
214         setCurrentView(view);
215
216         return view;
217 }
218
219
220
221
222 Clipboard & GuiApplication::clipboard()
223 {
224         return clipboard_;
225 }
226
227
228 Selection & GuiApplication::selection()
229 {
230         return selection_;
231 }
232
233
234 int GuiApplication::exec()
235 {
236         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
237         return QApplication::exec();
238 }
239
240
241 void GuiApplication::exit(int status)
242 {
243         QApplication::exit(status);
244 }
245
246
247 void GuiApplication::execBatchCommands()
248 {
249         LyX::ref().execBatchCommands();
250 }
251
252
253 string const GuiApplication::romanFontName()
254 {
255         QFont font;
256         font.setKerning(false);
257         font.setStyleHint(QFont::Serif);
258         font.setFamily("serif");
259
260         return fromqstr(QFontInfo(font).family());
261 }
262
263
264 string const GuiApplication::sansFontName()
265 {
266         QFont font;
267         font.setKerning(false);
268         font.setStyleHint(QFont::SansSerif);
269         font.setFamily("sans");
270
271         return fromqstr(QFontInfo(font).family());
272 }
273
274
275 string const GuiApplication::typewriterFontName()
276 {
277         QFont font;
278         font.setKerning(false);
279         font.setStyleHint(QFont::TypeWriter);
280         font.setFamily("monospace");
281
282         return fromqstr(QFontInfo(font).family());
283 }
284
285
286 bool GuiApplication::event(QEvent * e)
287 {
288         switch(e->type()) {
289         case QEvent::FileOpen: {
290                 // Open a file; this happens only on Mac OS X for now
291                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
292
293                 if (!currentView() || !currentView()->view())
294                         // The application is not properly initialized yet.
295                         // So we acknowledge the event and delay the file opening
296                         // until LyX is ready.
297                         // FIXME UNICODE: FileName accept an utf8 encoded string.
298                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
299                 else
300                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
301                                 qstring_to_ucs4(foe->file())));
302
303                 e->accept();
304                 return true;
305         }
306         default:
307                 return QApplication::event(e);
308         }
309 }
310
311
312 bool GuiApplication::notify(QObject * receiver, QEvent * event)
313 {
314         try {
315                 return QApplication::notify(receiver, event);
316         }
317         catch (support::ExceptionMessage const & e) {
318                 if (e.type_ == support::ErrorException) {
319                         Alert::error(e.title_, e.details_);
320                         LyX::cref().emergencyCleanup();
321                         QApplication::exit(1);
322                 } else if (e.type_ == support::WarningException) {
323                         Alert::warning(e.title_, e.details_);
324                         return false;
325                 }
326         }
327         catch (std::exception const & e) {
328                 docstring s = _("LyX has caught an exception, it will now "
329                         "attemp to save all unsaved documents and exit."
330                         "\n\nException: ");
331                 s += from_ascii(e.what());
332                 Alert::error(_("Software exception Detected"), s);
333                 LyX::cref().emergencyCleanup();
334                 QApplication::exit(1);
335         }
336         catch (...) {
337                 docstring s = _("LyX has caught some really weird exception, it will "
338                         "now attemp to save all unsaved documents and exit.");
339                 Alert::error(_("Software exception Detected"), s);
340                 LyX::cref().emergencyCleanup();
341                 QApplication::exit(1);
342         }
343
344         return false;
345 }
346
347
348 void GuiApplication::syncEvents()
349 {
350         // This is the ONLY place where processEvents may be called.
351         // During screen update/ redraw, this method is disabled to
352         // prevent keyboard events being handed to the LyX core, where
353         // they could cause re-entrant calls to screen update.
354         processEvents(QEventLoop::ExcludeUserInputEvents);
355 }
356
357
358 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
359 {
360         QColor const & qcol = color_cache_.get(col);
361         if (!qcol.isValid()) {
362                 rgbcol.r = 0;
363                 rgbcol.g = 0;
364                 rgbcol.b = 0;
365                 return false;
366         }
367         rgbcol.r = qcol.red();
368         rgbcol.g = qcol.green();
369         rgbcol.b = qcol.blue();
370         return true;
371 }
372
373
374 string const GuiApplication::hexName(ColorCode col)
375 {
376         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
377 }
378
379
380 void GuiApplication::updateColor(ColorCode)
381 {
382         // FIXME: Bleh, can't we just clear them all at once ?
383         color_cache_.clear();
384 }
385
386
387 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
388 {
389         SocketNotifier * sn = new SocketNotifier(this, fd, func);
390         socket_notifiers_[fd] = sn;
391         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
392 }
393
394
395 void GuiApplication::socketDataReceived(int fd)
396 {
397         socket_notifiers_[fd]->func_();
398 }
399
400
401 void GuiApplication::unregisterSocketCallback(int fd)
402 {
403         socket_notifiers_.erase(fd);
404 }
405
406
407 void GuiApplication::commitData(QSessionManager & sm)
408 {
409         /// The implementation is required to avoid an application exit
410         /// when session state save is triggered by session manager.
411         /// The default implementation sends a close event to all
412         /// visible top level widgets when session managment allows
413         /// interaction.
414         /// We are changing that to write all unsaved buffers...
415         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
416                 sm.cancel();
417 }
418
419
420 ////////////////////////////////////////////////////////////////////////
421 // X11 specific stuff goes here...
422 #ifdef Q_WS_X11
423 bool GuiApplication::x11EventFilter(XEvent * xev)
424 {
425         if (!currentView())
426                 return false;
427
428         switch (xev->type) {
429         case SelectionRequest: {
430                 if (xev->xselectionrequest.selection != XA_PRIMARY)
431                         break;
432                 LYXERR(Debug::GUI) << "X requested selection." << endl;
433                 BufferView * bv = currentView()->view();
434                 if (bv) {
435                         docstring const sel = bv->requestSelection();
436                         if (!sel.empty())
437                                 selection_.put(sel);
438                 }
439                 break;
440         }
441         case SelectionClear: {
442                 if (xev->xselectionclear.selection != XA_PRIMARY)
443                         break;
444                 LYXERR(Debug::GUI) << "Lost selection." << endl;
445                 BufferView * bv = currentView()->view();
446                 if (bv)
447                         bv->clearSelection();
448                 break;
449         }
450         }
451         return false;
452 }
453 #endif
454
455 void GuiApplication::addMenuTranslator()
456 {
457         installTranslator(new MenuTranslator(this));
458 }
459
460
461 } // namespace frontend
462 } // namespace lyx
463
464 #include "GuiApplication_moc.cpp"