2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "qt_helpers.h"
20 #include "frontends/alert.h"
21 #include "frontends/LyXView.h"
23 #include "graphics/LoaderQueue.h"
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"
31 #include "BufferList.h"
32 #include "BufferView.h"
35 #include "FuncRequest.h"
41 #include <QApplication>
44 #include <QFileOpenEvent>
46 #include <QLibraryInfo>
47 #include <QPixmapCache>
48 #include <QSessionManager>
49 #include <QSocketNotifier>
52 #include <QTranslator>
56 #include <X11/Xatom.h>
60 #include <boost/bind.hpp>
70 frontend::Application * createApplication(int & argc, char * argv[])
72 return new frontend::GuiApplication(argc, argv);
78 class SocketNotifier : public QSocketNotifier
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)
87 /// The callback function
88 Application::SocketCallback func_;
92 ////////////////////////////////////////////////////////////////////////
93 // Mac specific stuff goes here...
95 class MenuTranslator : public QTranslator
98 MenuTranslator(QObject * parent)
102 QString translate(const char * /*context*/,
103 const char * sourceText,
104 const char * /*comment*/ = 0)
106 string const s = sourceText;
107 if (s == N_("About %1") || s == N_("Preferences")
108 || s == N_("Reconfigure") || s == N_("Quit %1"))
116 ///////////////////////////////////////////////////////////////
117 // You can find more platform specific stuff
118 // at the end of this file...
119 ///////////////////////////////////////////////////////////////
122 using support::FileName;
124 GuiApplication * guiApp;
127 GuiApplication::GuiApplication(int & argc, char ** argv)
128 : QApplication(argc, argv), Application(argc, argv)
130 QCoreApplication::setOrganizationName("The LyX Community");
131 QCoreApplication::setOrganizationDomain("lyx.org");
132 QCoreApplication::setApplicationName("LyX");
134 // Qt bug? setQuitOnLastWindowClosed(true); does not work
135 setQuitOnLastWindowClosed(false);
138 // doubleClickInterval() is 400 ms on X11 which is just too long.
139 // On Windows and Mac OS X, the operating system's value is used.
140 // On Microsoft Windows, calling this function sets the double
141 // click interval for all applications. So we don't!
142 QApplication::setDoubleClickInterval(300);
145 // install translation file for Qt built-in dialogs
146 QString language_name = QString("qt_") + QLocale::system().name();
148 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
149 // Short-named translator can be loaded from a long name, but not the
150 // opposite. Therefore, long name should be used without truncation.
151 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
152 if (qt_trans_.load(language_name,
153 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
155 installTranslator(&qt_trans_);
156 // even if the language calls for RtL, don't do that
157 setLayoutDirection(Qt::LeftToRight);
159 << "Successfully installed Qt translations for locale "
160 << fromqstr(language_name) << std::endl;
163 << "Could not find Qt translations for locale "
164 << fromqstr(language_name) << std::endl;
167 // This allows to translate the strings that appear in the LyX menu.
171 using namespace lyx::graphics;
173 Image::newImage = boost::bind(&GuiImage::newImage);
174 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
176 // needs to be done before reading lyxrc
178 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
180 LoaderQueue::setPriority(10,100);
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);
190 GuiApplication::~GuiApplication()
192 socket_notifiers_.clear();
196 Clipboard & GuiApplication::clipboard()
202 Selection & GuiApplication::selection()
208 int GuiApplication::exec()
210 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
211 return QApplication::exec();
215 void GuiApplication::exit(int status)
217 QApplication::exit(status);
221 void GuiApplication::execBatchCommands()
223 LyX::ref().execBatchCommands();
227 string const GuiApplication::romanFontName()
230 font.setKerning(false);
231 font.setStyleHint(QFont::Serif);
232 font.setFamily("serif");
234 return fromqstr(QFontInfo(font).family());
238 string const GuiApplication::sansFontName()
241 font.setKerning(false);
242 font.setStyleHint(QFont::SansSerif);
243 font.setFamily("sans");
245 return fromqstr(QFontInfo(font).family());
249 string const GuiApplication::typewriterFontName()
252 font.setKerning(false);
253 font.setStyleHint(QFont::TypeWriter);
254 font.setFamily("monospace");
256 return fromqstr(QFontInfo(font).family());
260 bool GuiApplication::event(QEvent * e)
263 case QEvent::FileOpen: {
264 // Open a file; this happens only on Mac OS X for now
265 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
267 if (!currentView() || !currentView()->view())
268 // The application is not properly initialized yet.
269 // So we acknowledge the event and delay the file opening
270 // until LyX is ready.
271 // FIXME UNICODE: FileName accept an utf8 encoded string.
272 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
274 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
275 qstring_to_ucs4(foe->file())));
281 return QApplication::event(e);
286 bool GuiApplication::notify(QObject * receiver, QEvent * event)
288 bool return_value = false;
290 return_value = QApplication::notify(receiver, event);
292 catch (support::ExceptionMessage const & e) {
293 if (e.type_ == support::ErrorException) {
294 Alert::error(e.title_, e.details_);
295 LyX::cref().emergencyCleanup();
296 QApplication::exit(1);
297 } else if (e.type_ == support::WarningException) {
298 Alert::warning(e.title_, e.details_);
302 catch (std::exception const & e) {
303 docstring s = _("LyX has caught an exception, it will now "
304 "attemp to save all unsaved documents and exit."
306 s += from_ascii(e.what());
307 Alert::error(_("Software exception Detected"), s);
308 LyX::cref().emergencyCleanup();
309 QApplication::exit(1);
312 docstring s = _("LyX has caught some really weird exception, it will "
313 "now attemp to save all unsaved documents and exit.");
314 Alert::error(_("Software exception Detected"), s);
315 LyX::cref().emergencyCleanup();
316 QApplication::exit(1);
323 void GuiApplication::syncEvents()
325 // This is the ONLY place where processEvents may be called.
326 // During screen update/ redraw, this method is disabled to
327 // prevent keyboard events being handed to the LyX core, where
328 // they could cause re-entrant calls to screen update.
329 processEvents(QEventLoop::ExcludeUserInputEvents);
333 bool GuiApplication::getRgbColor(ColorCode col,
336 QColor const & qcol = color_cache_.get(col);
337 if (!qcol.isValid()) {
343 rgbcol.r = qcol.red();
344 rgbcol.g = qcol.green();
345 rgbcol.b = qcol.blue();
350 string const GuiApplication::hexName(ColorCode col)
352 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
356 void GuiApplication::updateColor(ColorCode)
358 // FIXME: Bleh, can't we just clear them all at once ?
359 color_cache_.clear();
363 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
365 SocketNotifier * sn = new SocketNotifier(this, fd, func);
366 socket_notifiers_[fd] = sn;
367 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
371 void GuiApplication::socketDataReceived(int fd)
373 socket_notifiers_[fd]->func_();
377 void GuiApplication::unregisterSocketCallback(int fd)
379 socket_notifiers_.erase(fd);
383 void GuiApplication::commitData(QSessionManager & sm)
385 /// The implementation is required to avoid an application exit
386 /// when session state save is triggered by session manager.
387 /// The default implementation sends a close event to all
388 /// visible top level widgets when session managment allows
390 /// We are changing that to write all unsaved buffers...
391 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
396 ////////////////////////////////////////////////////////////////////////
397 // X11 specific stuff goes here...
399 bool GuiApplication::x11EventFilter(XEvent * xev)
405 case SelectionRequest: {
406 if (xev->xselectionrequest.selection != XA_PRIMARY)
408 LYXERR(Debug::GUI) << "X requested selection." << endl;
409 BufferView * bv = currentView()->view();
411 docstring const sel = bv->requestSelection();
417 case SelectionClear: {
418 if (xev->xselectionclear.selection != XA_PRIMARY)
420 LYXERR(Debug::GUI) << "Lost selection." << endl;
421 BufferView * bv = currentView()->view();
423 bv->clearSelection();
431 void GuiApplication::addMenuTranslator()
433 installTranslator(new MenuTranslator(this));
437 } // namespace frontend
440 #include "GuiApplication_moc.cpp"