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"
18 #include "qt_helpers.h"
21 #include "frontends/alert.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>
48 #include <QSessionManager>
49 #include <QSocketNotifier>
52 #include <QTranslator>
56 #include <X11/Xatom.h>
62 #include <boost/bind.hpp>
72 frontend::Application * createApplication(int & argc, char * argv[])
74 return new frontend::GuiApplication(argc, argv);
80 class SocketNotifier : public QSocketNotifier
83 /// connect a connection notification from the LyXServerSocket
84 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
85 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
89 /// The callback function
90 Application::SocketCallback func_;
94 ////////////////////////////////////////////////////////////////////////
95 // Mac specific stuff goes here...
97 class MenuTranslator : public QTranslator
100 MenuTranslator(QObject * parent)
101 : QTranslator(parent)
104 QString translate(const char * /*context*/,
105 const char * sourceText,
106 const char * /*comment*/ = 0)
108 string const s = sourceText;
109 if (s == N_("About %1") || s == N_("Preferences")
110 || s == N_("Reconfigure") || s == N_("Quit %1"))
118 ///////////////////////////////////////////////////////////////
119 // You can find more platform specific stuff
120 // at the end of this file...
121 ///////////////////////////////////////////////////////////////
124 using support::FileName;
126 GuiApplication * guiApp;
129 GuiApplication::GuiApplication(int & argc, char ** argv)
130 : QApplication(argc, argv), Application()
132 QCoreApplication::setOrganizationName("The LyX Community");
133 QCoreApplication::setOrganizationDomain("lyx.org");
134 QCoreApplication::setApplicationName("LyX");
136 // Qt bug? setQuitOnLastWindowClosed(true); does not work
137 setQuitOnLastWindowClosed(false);
140 // doubleClickInterval() is 400 ms on X11 which is just too long.
141 // On Windows and Mac OS X, the operating system's value is used.
142 // On Microsoft Windows, calling this function sets the double
143 // click interval for all applications. So we don't!
144 QApplication::setDoubleClickInterval(300);
147 // install translation file for Qt built-in dialogs
148 QString language_name = QString("qt_") + QLocale::system().name();
150 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
151 // Short-named translator can be loaded from a long name, but not the
152 // opposite. Therefore, long name should be used without truncation.
153 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
154 if (qt_trans_.load(language_name,
155 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
157 installTranslator(&qt_trans_);
158 // even if the language calls for RtL, don't do that
159 setLayoutDirection(Qt::LeftToRight);
161 << "Successfully installed Qt translations for locale "
162 << fromqstr(language_name) << std::endl;
165 << "Could not find Qt translations for locale "
166 << fromqstr(language_name) << std::endl;
169 // This allows to translate the strings that appear in the LyX menu.
173 using namespace lyx::graphics;
175 Image::newImage = boost::bind(&GuiImage::newImage);
176 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
178 // needs to be done before reading lyxrc
180 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
182 LoaderQueue::setPriority(10,100);
186 // Set the cache to 5120 kilobytes which corresponds to screen size of
187 // 1280 by 1024 pixels with a color depth of 32 bits.
188 QPixmapCache::setCacheLimit(5120);
192 GuiApplication::~GuiApplication()
194 socket_notifiers_.clear();
198 LyXView & GuiApplication::createView(string const & geometry_arg)
200 int const id = gui_.createRegisteredView();
201 GuiView & view = static_cast<GuiView &>(gui_.view(id));
202 theLyXFunc().setLyXView(&view);
206 if (!geometry_arg.empty()) {
210 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
211 re.indexIn(toqstr(geometry_arg.c_str()));
212 w = re.cap(1).toInt();
213 h = re.cap(2).toInt();
214 x = re.cap(3).toInt();
215 y = re.cap(4).toInt();
216 view.setGeometry(x, y, w, h);
221 setCurrentView(view);
229 Clipboard & GuiApplication::clipboard()
235 Selection & GuiApplication::selection()
241 int GuiApplication::exec()
243 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
244 return QApplication::exec();
248 void GuiApplication::exit(int status)
250 QApplication::exit(status);
254 void GuiApplication::execBatchCommands()
256 LyX::ref().execBatchCommands();
260 string const GuiApplication::romanFontName()
263 font.setKerning(false);
264 font.setStyleHint(QFont::Serif);
265 font.setFamily("serif");
267 return fromqstr(QFontInfo(font).family());
271 string const GuiApplication::sansFontName()
274 font.setKerning(false);
275 font.setStyleHint(QFont::SansSerif);
276 font.setFamily("sans");
278 return fromqstr(QFontInfo(font).family());
282 string const GuiApplication::typewriterFontName()
285 font.setKerning(false);
286 font.setStyleHint(QFont::TypeWriter);
287 font.setFamily("monospace");
289 return fromqstr(QFontInfo(font).family());
293 bool GuiApplication::event(QEvent * e)
296 case QEvent::FileOpen: {
297 // Open a file; this happens only on Mac OS X for now
298 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
300 if (!currentView() || !currentView()->view())
301 // The application is not properly initialized yet.
302 // So we acknowledge the event and delay the file opening
303 // until LyX is ready.
304 // FIXME UNICODE: FileName accept an utf8 encoded string.
305 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
307 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
308 qstring_to_ucs4(foe->file())));
314 return QApplication::event(e);
319 bool GuiApplication::notify(QObject * receiver, QEvent * event)
322 return QApplication::notify(receiver, event);
324 catch (support::ExceptionMessage const & e) {
325 if (e.type_ == support::ErrorException) {
326 Alert::error(e.title_, e.details_);
327 LyX::cref().emergencyCleanup();
328 QApplication::exit(1);
329 } else if (e.type_ == support::WarningException) {
330 Alert::warning(e.title_, e.details_);
334 catch (std::exception const & e) {
335 docstring s = _("LyX has caught an exception, it will now "
336 "attemp to save all unsaved documents and exit."
338 s += from_ascii(e.what());
339 Alert::error(_("Software exception Detected"), s);
340 LyX::cref().emergencyCleanup();
341 QApplication::exit(1);
344 docstring s = _("LyX has caught some really weird exception, it will "
345 "now attemp to save all unsaved documents and exit.");
346 Alert::error(_("Software exception Detected"), s);
347 LyX::cref().emergencyCleanup();
348 QApplication::exit(1);
355 void GuiApplication::syncEvents()
357 // This is the ONLY place where processEvents may be called.
358 // During screen update/ redraw, this method is disabled to
359 // prevent keyboard events being handed to the LyX core, where
360 // they could cause re-entrant calls to screen update.
361 processEvents(QEventLoop::ExcludeUserInputEvents);
365 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
367 QColor const & qcol = color_cache_.get(col);
368 if (!qcol.isValid()) {
374 rgbcol.r = qcol.red();
375 rgbcol.g = qcol.green();
376 rgbcol.b = qcol.blue();
381 string const GuiApplication::hexName(ColorCode col)
383 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
387 void GuiApplication::updateColor(ColorCode)
389 // FIXME: Bleh, can't we just clear them all at once ?
390 color_cache_.clear();
394 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
396 SocketNotifier * sn = new SocketNotifier(this, fd, func);
397 socket_notifiers_[fd] = sn;
398 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
402 void GuiApplication::socketDataReceived(int fd)
404 socket_notifiers_[fd]->func_();
408 void GuiApplication::unregisterSocketCallback(int fd)
410 socket_notifiers_.erase(fd);
414 void GuiApplication::commitData(QSessionManager & sm)
416 /// The implementation is required to avoid an application exit
417 /// when session state save is triggered by session manager.
418 /// The default implementation sends a close event to all
419 /// visible top level widgets when session managment allows
421 /// We are changing that to write all unsaved buffers...
422 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
427 ////////////////////////////////////////////////////////////////////////
428 // X11 specific stuff goes here...
430 bool GuiApplication::x11EventFilter(XEvent * xev)
436 case SelectionRequest: {
437 if (xev->xselectionrequest.selection != XA_PRIMARY)
439 LYXERR(Debug::GUI) << "X requested selection." << endl;
440 BufferView * bv = currentView()->view();
442 docstring const sel = bv->requestSelection();
448 case SelectionClear: {
449 if (xev->xselectionclear.selection != XA_PRIMARY)
451 LYXERR(Debug::GUI) << "Lost selection." << endl;
452 BufferView * bv = currentView()->view();
454 bv->clearSelection();
462 void GuiApplication::addMenuTranslator()
464 installTranslator(new MenuTranslator(this));
468 } // namespace frontend
471 #include "GuiApplication_moc.cpp"