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);
160 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
161 << fromqstr(language_name));
163 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
164 << fromqstr(language_name));
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 LyXView & GuiApplication::createView(string const & geometry_arg)
198 int const id = gui_.createRegisteredView();
199 GuiView & view = static_cast<GuiView &>(gui_.view(id));
200 theLyXFunc().setLyXView(&view);
204 if (!geometry_arg.empty()) {
208 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
209 re.indexIn(toqstr(geometry_arg.c_str()));
210 w = re.cap(1).toInt();
211 h = re.cap(2).toInt();
212 x = re.cap(3).toInt();
213 y = re.cap(4).toInt();
214 view.setGeometry(x, y, w, h);
219 setCurrentView(view);
227 Clipboard & GuiApplication::clipboard()
233 Selection & GuiApplication::selection()
239 int GuiApplication::exec()
241 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
242 return QApplication::exec();
246 void GuiApplication::exit(int status)
248 QApplication::exit(status);
252 void GuiApplication::execBatchCommands()
254 LyX::ref().execBatchCommands();
258 string const GuiApplication::romanFontName()
261 font.setKerning(false);
262 font.setStyleHint(QFont::Serif);
263 font.setFamily("serif");
265 return fromqstr(QFontInfo(font).family());
269 string const GuiApplication::sansFontName()
272 font.setKerning(false);
273 font.setStyleHint(QFont::SansSerif);
274 font.setFamily("sans");
276 return fromqstr(QFontInfo(font).family());
280 string const GuiApplication::typewriterFontName()
283 font.setKerning(false);
284 font.setStyleHint(QFont::TypeWriter);
285 font.setFamily("monospace");
287 return fromqstr(QFontInfo(font).family());
291 bool GuiApplication::event(QEvent * e)
294 case QEvent::FileOpen: {
295 // Open a file; this happens only on Mac OS X for now
296 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
298 if (!currentView() || !currentView()->view())
299 // The application is not properly initialized yet.
300 // So we acknowledge the event and delay the file opening
301 // until LyX is ready.
302 // FIXME UNICODE: FileName accept an utf8 encoded string.
303 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
305 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
306 qstring_to_ucs4(foe->file())));
312 return QApplication::event(e);
317 bool GuiApplication::notify(QObject * receiver, QEvent * event)
320 return QApplication::notify(receiver, event);
322 catch (support::ExceptionMessage const & e) {
323 if (e.type_ == support::ErrorException) {
324 Alert::error(e.title_, e.details_);
325 LyX::cref().emergencyCleanup();
326 QApplication::exit(1);
327 } else if (e.type_ == support::WarningException) {
328 Alert::warning(e.title_, e.details_);
332 catch (std::exception const & e) {
333 docstring s = _("LyX has caught an exception, it will now "
334 "attemp to save all unsaved documents and exit."
336 s += from_ascii(e.what());
337 Alert::error(_("Software exception Detected"), s);
338 LyX::cref().emergencyCleanup();
339 QApplication::exit(1);
342 docstring s = _("LyX has caught some really weird exception, it will "
343 "now attemp to save all unsaved documents and exit.");
344 Alert::error(_("Software exception Detected"), s);
345 LyX::cref().emergencyCleanup();
346 QApplication::exit(1);
353 void GuiApplication::syncEvents()
355 // This is the ONLY place where processEvents may be called.
356 // During screen update/ redraw, this method is disabled to
357 // prevent keyboard events being handed to the LyX core, where
358 // they could cause re-entrant calls to screen update.
359 processEvents(QEventLoop::ExcludeUserInputEvents);
363 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
365 QColor const & qcol = color_cache_.get(col);
366 if (!qcol.isValid()) {
372 rgbcol.r = qcol.red();
373 rgbcol.g = qcol.green();
374 rgbcol.b = qcol.blue();
379 string const GuiApplication::hexName(ColorCode col)
381 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
385 void GuiApplication::updateColor(ColorCode)
387 // FIXME: Bleh, can't we just clear them all at once ?
388 color_cache_.clear();
392 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
394 SocketNotifier * sn = new SocketNotifier(this, fd, func);
395 socket_notifiers_[fd] = sn;
396 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
400 void GuiApplication::socketDataReceived(int fd)
402 socket_notifiers_[fd]->func_();
406 void GuiApplication::unregisterSocketCallback(int fd)
408 socket_notifiers_.erase(fd);
412 void GuiApplication::commitData(QSessionManager & sm)
414 /// The implementation is required to avoid an application exit
415 /// when session state save is triggered by session manager.
416 /// The default implementation sends a close event to all
417 /// visible top level widgets when session managment allows
419 /// We are changing that to write all unsaved buffers...
420 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
425 ////////////////////////////////////////////////////////////////////////
426 // X11 specific stuff goes here...
428 bool GuiApplication::x11EventFilter(XEvent * xev)
434 case SelectionRequest: {
435 if (xev->xselectionrequest.selection != XA_PRIMARY)
437 LYXERR(Debug::GUI, "X requested selection.");
438 BufferView * bv = currentView()->view();
440 docstring const sel = bv->requestSelection();
446 case SelectionClear: {
447 if (xev->xselectionclear.selection != XA_PRIMARY)
449 LYXERR(Debug::GUI, "Lost selection.");
450 BufferView * bv = currentView()->view();
452 bv->clearSelection();
460 void GuiApplication::addMenuTranslator()
462 installTranslator(new MenuTranslator(this));
466 } // namespace frontend
469 #include "GuiApplication_moc.cpp"