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