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>
47 #include <QSessionManager>
48 #include <QSocketNotifier>
51 #include <QTranslator>
55 #include <X11/Xatom.h>
61 #include <boost/bind.hpp>
71 frontend::Application * createApplication(int & argc, char * argv[])
73 return new frontend::GuiApplication(argc, argv);
79 class SocketNotifier : public QSocketNotifier
82 /// connect a connection notification from the LyXServerSocket
83 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
84 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
88 /// The callback function
89 Application::SocketCallback func_;
93 ////////////////////////////////////////////////////////////////////////
94 // Mac specific stuff goes here...
96 class MenuTranslator : public QTranslator
99 MenuTranslator(QObject * parent)
100 : QTranslator(parent)
103 QString translate(const char * /*context*/,
104 const char * sourceText,
105 const char * /*comment*/ = 0)
107 string const s = sourceText;
108 if (s == N_("About %1") || s == N_("Preferences")
109 || s == N_("Reconfigure") || s == N_("Quit %1"))
117 ///////////////////////////////////////////////////////////////
118 // You can find more platform specific stuff
119 // at the end of this file...
120 ///////////////////////////////////////////////////////////////
123 using support::FileName;
125 GuiApplication * guiApp;
128 GuiApplication::GuiApplication(int & argc, char ** argv)
129 : QApplication(argc, argv), Application(argc, argv)
131 QCoreApplication::setOrganizationName("The LyX Community");
132 QCoreApplication::setOrganizationDomain("lyx.org");
133 QCoreApplication::setApplicationName("LyX");
135 // Qt bug? setQuitOnLastWindowClosed(true); does not work
136 setQuitOnLastWindowClosed(false);
139 // doubleClickInterval() is 400 ms on X11 which is just too long.
140 // On Windows and Mac OS X, the operating system's value is used.
141 // On Microsoft Windows, calling this function sets the double
142 // click interval for all applications. So we don't!
143 QApplication::setDoubleClickInterval(300);
146 // install translation file for Qt built-in dialogs
147 QString language_name = QString("qt_") + QLocale::system().name();
149 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
150 // Short-named translator can be loaded from a long name, but not the
151 // opposite. Therefore, long name should be used without truncation.
152 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
153 if (qt_trans_.load(language_name,
154 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
156 installTranslator(&qt_trans_);
157 // even if the language calls for RtL, don't do that
158 setLayoutDirection(Qt::LeftToRight);
160 << "Successfully installed Qt translations for locale "
161 << fromqstr(language_name) << std::endl;
164 << "Could not find Qt translations for locale "
165 << fromqstr(language_name) << std::endl;
168 // This allows to translate the strings that appear in the LyX menu.
172 using namespace lyx::graphics;
174 Image::newImage = boost::bind(&GuiImage::newImage);
175 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
177 // needs to be done before reading lyxrc
179 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
181 LoaderQueue::setPriority(10,100);
185 // Set the cache to 5120 kilobytes which corresponds to screen size of
186 // 1280 by 1024 pixels with a color depth of 32 bits.
187 QPixmapCache::setCacheLimit(5120);
191 GuiApplication::~GuiApplication()
193 socket_notifiers_.clear();
197 LyXView & GuiApplication::createView(unsigned int width,
201 unsigned int iconSizeXY,
202 const std::string & geometryArg)
204 int const id = gui_.createRegisteredView();
205 GuiView & view = static_cast<GuiView &>(gui_.view(id));
206 theLyXFunc().setLyXView(&view);
209 view.setGeometry(width, height, posx, posy, GuiView::Maximized(maximized),
210 iconSizeXY, geometryArg);
214 setCurrentView(view);
222 Clipboard & GuiApplication::clipboard()
228 Selection & GuiApplication::selection()
234 int GuiApplication::exec()
236 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
237 return QApplication::exec();
241 void GuiApplication::exit(int status)
243 QApplication::exit(status);
247 void GuiApplication::execBatchCommands()
249 LyX::ref().execBatchCommands();
253 string const GuiApplication::romanFontName()
256 font.setKerning(false);
257 font.setStyleHint(QFont::Serif);
258 font.setFamily("serif");
260 return fromqstr(QFontInfo(font).family());
264 string const GuiApplication::sansFontName()
267 font.setKerning(false);
268 font.setStyleHint(QFont::SansSerif);
269 font.setFamily("sans");
271 return fromqstr(QFontInfo(font).family());
275 string const GuiApplication::typewriterFontName()
278 font.setKerning(false);
279 font.setStyleHint(QFont::TypeWriter);
280 font.setFamily("monospace");
282 return fromqstr(QFontInfo(font).family());
286 bool GuiApplication::event(QEvent * e)
289 case QEvent::FileOpen: {
290 // Open a file; this happens only on Mac OS X for now
291 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
293 if (!currentView() || !currentView()->view())
294 // The application is not properly initialized yet.
295 // So we acknowledge the event and delay the file opening
296 // until LyX is ready.
297 // FIXME UNICODE: FileName accept an utf8 encoded string.
298 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
300 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
301 qstring_to_ucs4(foe->file())));
307 return QApplication::event(e);
312 bool GuiApplication::notify(QObject * receiver, QEvent * event)
314 bool return_value = false;
316 return_value = QApplication::notify(receiver, event);
318 catch (support::ExceptionMessage const & e) {
319 if (e.type_ == support::ErrorException) {
320 Alert::error(e.title_, e.details_);
321 LyX::cref().emergencyCleanup();
322 QApplication::exit(1);
323 } else if (e.type_ == support::WarningException) {
324 Alert::warning(e.title_, e.details_);
328 catch (std::exception const & e) {
329 docstring s = _("LyX has caught an exception, it will now "
330 "attemp to save all unsaved documents and exit."
332 s += from_ascii(e.what());
333 Alert::error(_("Software exception Detected"), s);
334 LyX::cref().emergencyCleanup();
335 QApplication::exit(1);
338 docstring s = _("LyX has caught some really weird exception, it will "
339 "now attemp to save all unsaved documents and exit.");
340 Alert::error(_("Software exception Detected"), s);
341 LyX::cref().emergencyCleanup();
342 QApplication::exit(1);
349 void GuiApplication::syncEvents()
351 // This is the ONLY place where processEvents may be called.
352 // During screen update/ redraw, this method is disabled to
353 // prevent keyboard events being handed to the LyX core, where
354 // they could cause re-entrant calls to screen update.
355 processEvents(QEventLoop::ExcludeUserInputEvents);
359 bool GuiApplication::getRgbColor(ColorCode col,
362 QColor const & qcol = color_cache_.get(col);
363 if (!qcol.isValid()) {
369 rgbcol.r = qcol.red();
370 rgbcol.g = qcol.green();
371 rgbcol.b = qcol.blue();
376 string const GuiApplication::hexName(ColorCode col)
378 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
382 void GuiApplication::updateColor(ColorCode)
384 // FIXME: Bleh, can't we just clear them all at once ?
385 color_cache_.clear();
389 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
391 SocketNotifier * sn = new SocketNotifier(this, fd, func);
392 socket_notifiers_[fd] = sn;
393 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
397 void GuiApplication::socketDataReceived(int fd)
399 socket_notifiers_[fd]->func_();
403 void GuiApplication::unregisterSocketCallback(int fd)
405 socket_notifiers_.erase(fd);
409 void GuiApplication::commitData(QSessionManager & sm)
411 /// The implementation is required to avoid an application exit
412 /// when session state save is triggered by session manager.
413 /// The default implementation sends a close event to all
414 /// visible top level widgets when session managment allows
416 /// We are changing that to write all unsaved buffers...
417 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
422 ////////////////////////////////////////////////////////////////////////
423 // X11 specific stuff goes here...
425 bool GuiApplication::x11EventFilter(XEvent * xev)
431 case SelectionRequest: {
432 if (xev->xselectionrequest.selection != XA_PRIMARY)
434 LYXERR(Debug::GUI) << "X requested selection." << endl;
435 BufferView * bv = currentView()->view();
437 docstring const sel = bv->requestSelection();
443 case SelectionClear: {
444 if (xev->xselectionclear.selection != XA_PRIMARY)
446 LYXERR(Debug::GUI) << "Lost selection." << endl;
447 BufferView * bv = currentView()->view();
449 bv->clearSelection();
457 void GuiApplication::addMenuTranslator()
459 installTranslator(new MenuTranslator(this));
463 } // namespace frontend
466 #include "GuiApplication_moc.cpp"