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 & geometryArg)
200 int const id = gui_.createRegisteredView();
201 GuiView & view = static_cast<GuiView &>(gui_.view(id));
202 theLyXFunc().setLyXView(&view);
206 if (!geometryArg.empty())
211 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
212 re.indexIn(toqstr(geometryArg.c_str()));
213 w = re.cap(1).toInt();
214 h = re.cap(2).toInt();
215 x = re.cap(3).toInt();
216 y = re.cap(4).toInt();
217 view.setGeometry(x, y, w, h);
222 setCurrentView(view);
230 Clipboard & GuiApplication::clipboard()
236 Selection & GuiApplication::selection()
242 int GuiApplication::exec()
244 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
245 return QApplication::exec();
249 void GuiApplication::exit(int status)
251 QApplication::exit(status);
255 void GuiApplication::execBatchCommands()
257 LyX::ref().execBatchCommands();
261 string const GuiApplication::romanFontName()
264 font.setKerning(false);
265 font.setStyleHint(QFont::Serif);
266 font.setFamily("serif");
268 return fromqstr(QFontInfo(font).family());
272 string const GuiApplication::sansFontName()
275 font.setKerning(false);
276 font.setStyleHint(QFont::SansSerif);
277 font.setFamily("sans");
279 return fromqstr(QFontInfo(font).family());
283 string const GuiApplication::typewriterFontName()
286 font.setKerning(false);
287 font.setStyleHint(QFont::TypeWriter);
288 font.setFamily("monospace");
290 return fromqstr(QFontInfo(font).family());
294 bool GuiApplication::event(QEvent * e)
297 case QEvent::FileOpen: {
298 // Open a file; this happens only on Mac OS X for now
299 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
301 if (!currentView() || !currentView()->view())
302 // The application is not properly initialized yet.
303 // So we acknowledge the event and delay the file opening
304 // until LyX is ready.
305 // FIXME UNICODE: FileName accept an utf8 encoded string.
306 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
308 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
309 qstring_to_ucs4(foe->file())));
315 return QApplication::event(e);
320 bool GuiApplication::notify(QObject * receiver, QEvent * event)
323 return QApplication::notify(receiver, event);
325 catch (support::ExceptionMessage const & e) {
326 if (e.type_ == support::ErrorException) {
327 Alert::error(e.title_, e.details_);
328 LyX::cref().emergencyCleanup();
329 QApplication::exit(1);
330 } else if (e.type_ == support::WarningException) {
331 Alert::warning(e.title_, e.details_);
335 catch (std::exception const & e) {
336 docstring s = _("LyX has caught an exception, it will now "
337 "attemp to save all unsaved documents and exit."
339 s += from_ascii(e.what());
340 Alert::error(_("Software exception Detected"), s);
341 LyX::cref().emergencyCleanup();
342 QApplication::exit(1);
345 docstring s = _("LyX has caught some really weird exception, it will "
346 "now attemp to save all unsaved documents and exit.");
347 Alert::error(_("Software exception Detected"), s);
348 LyX::cref().emergencyCleanup();
349 QApplication::exit(1);
356 void GuiApplication::syncEvents()
358 // This is the ONLY place where processEvents may be called.
359 // During screen update/ redraw, this method is disabled to
360 // prevent keyboard events being handed to the LyX core, where
361 // they could cause re-entrant calls to screen update.
362 processEvents(QEventLoop::ExcludeUserInputEvents);
366 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
368 QColor const & qcol = color_cache_.get(col);
369 if (!qcol.isValid()) {
375 rgbcol.r = qcol.red();
376 rgbcol.g = qcol.green();
377 rgbcol.b = qcol.blue();
382 string const GuiApplication::hexName(ColorCode col)
384 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
388 void GuiApplication::updateColor(ColorCode)
390 // FIXME: Bleh, can't we just clear them all at once ?
391 color_cache_.clear();
395 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
397 SocketNotifier * sn = new SocketNotifier(this, fd, func);
398 socket_notifiers_[fd] = sn;
399 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
403 void GuiApplication::socketDataReceived(int fd)
405 socket_notifiers_[fd]->func_();
409 void GuiApplication::unregisterSocketCallback(int fd)
411 socket_notifiers_.erase(fd);
415 void GuiApplication::commitData(QSessionManager & sm)
417 /// The implementation is required to avoid an application exit
418 /// when session state save is triggered by session manager.
419 /// The default implementation sends a close event to all
420 /// visible top level widgets when session managment allows
422 /// We are changing that to write all unsaved buffers...
423 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
428 ////////////////////////////////////////////////////////////////////////
429 // X11 specific stuff goes here...
431 bool GuiApplication::x11EventFilter(XEvent * xev)
437 case SelectionRequest: {
438 if (xev->xselectionrequest.selection != XA_PRIMARY)
440 LYXERR(Debug::GUI) << "X requested selection." << endl;
441 BufferView * bv = currentView()->view();
443 docstring const sel = bv->requestSelection();
449 case SelectionClear: {
450 if (xev->xselectionclear.selection != XA_PRIMARY)
452 LYXERR(Debug::GUI) << "Lost selection." << endl;
453 BufferView * bv = currentView()->view();
455 bv->clearSelection();
463 void GuiApplication::addMenuTranslator()
465 installTranslator(new MenuTranslator(this));
469 } // namespace frontend
472 #include "GuiApplication_moc.cpp"