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