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