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