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 // Qt bug? setQuitOnLastWindowClosed(true); does not work
131 setQuitOnLastWindowClosed(false);
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);
141 // install translation file for Qt built-in dialogs
142 QString language_name = QString("qt_") + QLocale::system().name();
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)))
151 installTranslator(&qt_trans_);
152 // even if the language calls for RtL, don't do that
153 setLayoutDirection(Qt::LeftToRight);
155 << "Successfully installed Qt translations for locale "
156 << fromqstr(language_name) << std::endl;
159 << "Could not find Qt translations for locale "
160 << fromqstr(language_name) << std::endl;
163 // This allows to translate the strings that appear in the LyX menu.
167 using namespace lyx::graphics;
169 Image::newImage = boost::bind(&GuiImage::newImage);
170 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
172 // needs to be done before reading lyxrc
174 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
176 LoaderQueue::setPriority(10,100);
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);
186 GuiApplication::~GuiApplication()
188 socket_notifiers_.clear();
192 Clipboard & GuiApplication::clipboard()
198 Selection & GuiApplication::selection()
204 int GuiApplication::exec()
206 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
207 return QApplication::exec();
211 void GuiApplication::exit(int status)
213 QApplication::exit(status);
217 void GuiApplication::execBatchCommands()
219 LyX::ref().execBatchCommands();
223 string const GuiApplication::romanFontName()
226 font.setKerning(false);
227 font.setStyleHint(QFont::Serif);
228 font.setFamily("serif");
230 return fromqstr(QFontInfo(font).family());
234 string const GuiApplication::sansFontName()
237 font.setKerning(false);
238 font.setStyleHint(QFont::SansSerif);
239 font.setFamily("sans");
241 return fromqstr(QFontInfo(font).family());
245 string const GuiApplication::typewriterFontName()
248 font.setKerning(false);
249 font.setStyleHint(QFont::TypeWriter);
250 font.setFamily("monospace");
252 return fromqstr(QFontInfo(font).family());
256 bool GuiApplication::event(QEvent * e)
259 case QEvent::FileOpen: {
260 // Open a file; this happens only on Mac OS X for now
261 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
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())));
270 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
271 qstring_to_ucs4(foe->file())));
277 return QApplication::event(e);
282 bool GuiApplication::notify(QObject * receiver, QEvent * event)
284 bool return_value = false;
286 return_value = QApplication::notify(receiver, event);
288 catch (support::ExceptionMessage const & e) {
289 if (e.type_ == support::ErrorException) {
290 Alert::error(e.title_, e.details_);
291 LyX::cref().emergencyCleanup();
292 QApplication::exit(1);
293 } else if (e.type_ == support::WarningException) {
294 Alert::warning(e.title_, e.details_);
298 catch (std::exception const & e) {
299 docstring s = _("LyX has caught an exception, it will now "
300 "attemp to save all unsaved documents and exit."
302 s += from_ascii(e.what());
303 Alert::error(_("Software exception Detected"), s);
304 LyX::cref().emergencyCleanup();
305 QApplication::exit(1);
308 docstring s = _("LyX has caught some really weird exception, it will "
309 "now attemp to save all unsaved documents and exit.");
310 Alert::error(_("Software exception Detected"), s);
311 LyX::cref().emergencyCleanup();
312 QApplication::exit(1);
319 void GuiApplication::syncEvents()
321 // This is the ONLY place where processEvents may be called.
322 // During screen update/ redraw, this method is disabled to
323 // prevent keyboard events being handed to the LyX core, where
324 // they could cause re-entrant calls to screen update.
325 processEvents(QEventLoop::ExcludeUserInputEvents);
329 bool GuiApplication::getRgbColor(Color_color col,
332 QColor const & qcol = color_cache_.get(col);
333 if (!qcol.isValid()) {
339 rgbcol.r = qcol.red();
340 rgbcol.g = qcol.green();
341 rgbcol.b = qcol.blue();
346 string const GuiApplication::hexName(Color_color col)
348 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
352 void GuiApplication::updateColor(Color_color)
354 // FIXME: Bleh, can't we just clear them all at once ?
355 color_cache_.clear();
359 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
361 SocketNotifier * sn = new SocketNotifier(this, fd, func);
362 socket_notifiers_[fd] = sn;
363 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
367 void GuiApplication::socketDataReceived(int fd)
369 socket_notifiers_[fd]->func_();
373 void GuiApplication::unregisterSocketCallback(int fd)
375 socket_notifiers_.erase(fd);
379 void GuiApplication::commitData(QSessionManager & sm)
381 /// The implementation is required to avoid an application exit
382 /// when session state save is triggered by session manager.
383 /// The default implementation sends a close event to all
384 /// visible top level widgets when session managment allows
386 /// We are changing that to write all unsaved buffers...
387 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
392 ////////////////////////////////////////////////////////////////////////
393 // X11 specific stuff goes here...
395 bool GuiApplication::x11EventFilter(XEvent * xev)
401 case SelectionRequest: {
402 if (xev->xselectionrequest.selection != XA_PRIMARY)
404 LYXERR(Debug::GUI) << "X requested selection." << endl;
405 BufferView * bv = currentView()->view();
407 docstring const sel = bv->requestSelection();
413 case SelectionClear: {
414 if (xev->xselectionclear.selection != XA_PRIMARY)
416 LYXERR(Debug::GUI) << "Lost selection." << endl;
417 BufferView * bv = currentView()->view();
419 bv->clearSelection();
427 void GuiApplication::addMenuTranslator()
429 installTranslator(new MenuTranslator(this));
433 } // namespace frontend
436 #include "GuiApplication_moc.cpp"