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"
34 #include "FuncRequest.h"
40 #include <QApplication>
43 #include <QFileOpenEvent>
45 #include <QLibraryInfo>
46 #include <QPixmapCache>
47 #include <QSessionManager>
48 #include <QSocketNotifier>
51 #include <QTranslator>
55 #include <X11/Xatom.h>
59 #include <boost/bind.hpp>
69 frontend::Application * createApplication(int & argc, char * argv[])
71 return new frontend::GuiApplication(argc, argv);
77 class SocketNotifier : public QSocketNotifier
80 /// connect a connection notification from the LyXServerSocket
81 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
82 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
86 /// The callback function
87 Application::SocketCallback func_;
91 ////////////////////////////////////////////////////////////////////////
92 // Mac specific stuff goes here...
94 class MenuTranslator : public QTranslator
97 MenuTranslator(QObject * parent)
101 QString translate(const char * /*context*/,
102 const char * sourceText,
103 const char * /*comment*/ = 0)
105 string const s = sourceText;
106 if (s == N_("About %1") || s == N_("Preferences")
107 || s == N_("Reconfigure") || s == N_("Quit %1"))
115 ///////////////////////////////////////////////////////////////
116 // You can find more platform specific stuff
117 // at the end of this file...
118 ///////////////////////////////////////////////////////////////
121 using support::FileName;
123 GuiApplication * guiApp;
126 GuiApplication::GuiApplication(int & argc, char ** argv)
127 : QApplication(argc, argv), Application(argc, argv)
129 QCoreApplication::setOrganizationName("The LyX Community");
130 QCoreApplication::setOrganizationDomain("lyx.org");
131 QCoreApplication::setApplicationName("LyX");
133 // Qt bug? setQuitOnLastWindowClosed(true); does not work
134 setQuitOnLastWindowClosed(false);
137 // doubleClickInterval() is 400 ms on X11 which is just too long.
138 // On Windows and Mac OS X, the operating system's value is used.
139 // On Microsoft Windows, calling this function sets the double
140 // click interval for all applications. So we don't!
141 QApplication::setDoubleClickInterval(300);
144 // install translation file for Qt built-in dialogs
145 QString language_name = QString("qt_") + QLocale::system().name();
147 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
148 // Short-named translator can be loaded from a long name, but not the
149 // opposite. Therefore, long name should be used without truncation.
150 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
151 if (qt_trans_.load(language_name,
152 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
154 installTranslator(&qt_trans_);
155 // even if the language calls for RtL, don't do that
156 setLayoutDirection(Qt::LeftToRight);
158 << "Successfully installed Qt translations for locale "
159 << fromqstr(language_name) << std::endl;
162 << "Could not find Qt translations for locale "
163 << fromqstr(language_name) << std::endl;
166 // This allows to translate the strings that appear in the LyX menu.
170 using namespace lyx::graphics;
172 Image::newImage = boost::bind(&GuiImage::newImage);
173 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
175 // needs to be done before reading lyxrc
177 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
179 LoaderQueue::setPriority(10,100);
183 // Set the cache to 5120 kilobytes which corresponds to screen size of
184 // 1280 by 1024 pixels with a color depth of 32 bits.
185 QPixmapCache::setCacheLimit(5120);
189 GuiApplication::~GuiApplication()
191 socket_notifiers_.clear();
195 Clipboard & GuiApplication::clipboard()
201 Selection & GuiApplication::selection()
207 int GuiApplication::exec()
209 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
210 return QApplication::exec();
214 void GuiApplication::exit(int status)
216 QApplication::exit(status);
220 void GuiApplication::execBatchCommands()
222 LyX::ref().execBatchCommands();
226 string const GuiApplication::romanFontName()
229 font.setKerning(false);
230 font.setStyleHint(QFont::Serif);
231 font.setFamily("serif");
233 return fromqstr(QFontInfo(font).family());
237 string const GuiApplication::sansFontName()
240 font.setKerning(false);
241 font.setStyleHint(QFont::SansSerif);
242 font.setFamily("sans");
244 return fromqstr(QFontInfo(font).family());
248 string const GuiApplication::typewriterFontName()
251 font.setKerning(false);
252 font.setStyleHint(QFont::TypeWriter);
253 font.setFamily("monospace");
255 return fromqstr(QFontInfo(font).family());
259 bool GuiApplication::event(QEvent * e)
262 case QEvent::FileOpen: {
263 // Open a file; this happens only on Mac OS X for now
264 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
266 if (!currentView() || !currentView()->view())
267 // The application is not properly initialized yet.
268 // So we acknowledge the event and delay the file opening
269 // until LyX is ready.
270 // FIXME UNICODE: FileName accept an utf8 encoded string.
271 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
273 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
274 qstring_to_ucs4(foe->file())));
280 return QApplication::event(e);
285 bool GuiApplication::notify(QObject * receiver, QEvent * event)
287 bool return_value = false;
289 return_value = QApplication::notify(receiver, event);
291 catch (support::ExceptionMessage const & e) {
292 if (e.type_ == support::ErrorException) {
293 Alert::error(e.title_, e.details_);
294 LyX::cref().emergencyCleanup();
295 QApplication::exit(1);
296 } else if (e.type_ == support::WarningException) {
297 Alert::warning(e.title_, e.details_);
301 catch (std::exception const & e) {
302 docstring s = _("LyX has caught an exception, it will now "
303 "attemp to save all unsaved documents and exit."
305 s += from_ascii(e.what());
306 Alert::error(_("Software exception Detected"), s);
307 LyX::cref().emergencyCleanup();
308 QApplication::exit(1);
311 docstring s = _("LyX has caught some really weird exception, it will "
312 "now attemp to save all unsaved documents and exit.");
313 Alert::error(_("Software exception Detected"), s);
314 LyX::cref().emergencyCleanup();
315 QApplication::exit(1);
322 void GuiApplication::syncEvents()
324 // This is the ONLY place where processEvents may be called.
325 // During screen update/ redraw, this method is disabled to
326 // prevent keyboard events being handed to the LyX core, where
327 // they could cause re-entrant calls to screen update.
328 processEvents(QEventLoop::ExcludeUserInputEvents);
332 bool GuiApplication::getRgbColor(ColorCode col,
335 QColor const & qcol = color_cache_.get(col);
336 if (!qcol.isValid()) {
342 rgbcol.r = qcol.red();
343 rgbcol.g = qcol.green();
344 rgbcol.b = qcol.blue();
349 string const GuiApplication::hexName(ColorCode col)
351 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
355 void GuiApplication::updateColor(ColorCode)
357 // FIXME: Bleh, can't we just clear them all at once ?
358 color_cache_.clear();
362 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
364 SocketNotifier * sn = new SocketNotifier(this, fd, func);
365 socket_notifiers_[fd] = sn;
366 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
370 void GuiApplication::socketDataReceived(int fd)
372 socket_notifiers_[fd]->func_();
376 void GuiApplication::unregisterSocketCallback(int fd)
378 socket_notifiers_.erase(fd);
382 void GuiApplication::commitData(QSessionManager & sm)
384 /// The implementation is required to avoid an application exit
385 /// when session state save is triggered by session manager.
386 /// The default implementation sends a close event to all
387 /// visible top level widgets when session managment allows
389 /// We are changing that to write all unsaved buffers...
390 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
395 ////////////////////////////////////////////////////////////////////////
396 // X11 specific stuff goes here...
398 bool GuiApplication::x11EventFilter(XEvent * xev)
404 case SelectionRequest: {
405 if (xev->xselectionrequest.selection != XA_PRIMARY)
407 LYXERR(Debug::GUI) << "X requested selection." << endl;
408 BufferView * bv = currentView()->view();
410 docstring const sel = bv->requestSelection();
416 case SelectionClear: {
417 if (xev->xselectionclear.selection != XA_PRIMARY)
419 LYXERR(Debug::GUI) << "Lost selection." << endl;
420 BufferView * bv = currentView()->view();
422 bv->clearSelection();
430 void GuiApplication::addMenuTranslator()
432 installTranslator(new MenuTranslator(this));
436 } // namespace frontend
439 #include "GuiApplication_moc.cpp"