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"
22 #include "frontends/alert.h"
23 #include "frontends/Application.h"
24 #include "frontends/NoGuiFontLoader.h"
25 #include "frontends/NoGuiFontMetrics.h"
26 #include "frontends/FontLoader.h"
27 #include "frontends/FontMetrics.h"
29 #include "graphics/LoaderQueue.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/FileName.h"
33 #include "support/lstrings.h"
34 #include "support/os.h"
35 #include "support/Package.h"
37 #include "BufferList.h"
38 #include "BufferView.h"
41 #include "FuncRequest.h"
48 #include <QApplication>
51 #include <QFileOpenEvent>
53 #include <QLibraryInfo>
54 #include <QPixmapCache>
56 #include <QSessionManager>
57 #include <QSocketNotifier>
60 #include <QTranslator>
64 #include <X11/Xatom.h>
70 #include <boost/bind.hpp>
82 frontend::Application * createApplication(int & argc, char * argv[])
84 return new frontend::GuiApplication(argc, argv);
90 class SocketNotifier : public QSocketNotifier
93 /// connect a connection notification from the LyXServerSocket
94 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
95 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
99 /// The callback function
100 Application::SocketCallback func_;
104 ////////////////////////////////////////////////////////////////////////
105 // Mac specific stuff goes here...
107 class MenuTranslator : public QTranslator
110 MenuTranslator(QObject * parent)
111 : QTranslator(parent)
114 QString translate(const char * /*context*/,
115 const char * sourceText,
116 const char * /*comment*/ = 0)
118 string const s = sourceText;
119 if (s == N_("About %1") || s == N_("Preferences")
120 || s == N_("Reconfigure") || s == N_("Quit %1"))
128 ///////////////////////////////////////////////////////////////
129 // You can find more platform specific stuff
130 // at the end of this file...
131 ///////////////////////////////////////////////////////////////
134 using support::FileName;
136 GuiApplication * guiApp;
139 GuiApplication::GuiApplication(int & argc, char ** argv)
140 : QApplication(argc, argv), Application()
142 QString app_name = "LyX";
143 QCoreApplication::setOrganizationName(app_name);
144 QCoreApplication::setOrganizationDomain("lyx.org");
145 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
147 // Qt bug? setQuitOnLastWindowClosed(true); does not work
148 setQuitOnLastWindowClosed(false);
151 // doubleClickInterval() is 400 ms on X11 which is just too long.
152 // On Windows and Mac OS X, the operating system's value is used.
153 // On Microsoft Windows, calling this function sets the double
154 // click interval for all applications. So we don't!
155 QApplication::setDoubleClickInterval(300);
158 // install translation file for Qt built-in dialogs
159 QString language_name = QString("qt_") + QLocale::system().name();
161 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
162 // Short-named translator can be loaded from a long name, but not the
163 // opposite. Therefore, long name should be used without truncation.
164 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
165 if (qt_trans_.load(language_name,
166 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
168 installTranslator(&qt_trans_);
169 // even if the language calls for RtL, don't do that
170 setLayoutDirection(Qt::LeftToRight);
171 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
172 << fromqstr(language_name));
174 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
175 << fromqstr(language_name));
178 // This allows to translate the strings that appear in the LyX menu.
182 using namespace lyx::graphics;
184 Image::newImage = boost::bind(&GuiImage::newImage);
185 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
187 // needs to be done before reading lyxrc
189 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
191 LoaderQueue::setPriority(10,100);
195 // Set the cache to 5120 kilobytes which corresponds to screen size of
196 // 1280 by 1024 pixels with a color depth of 32 bits.
197 QPixmapCache::setCacheLimit(5120);
201 GuiApplication::~GuiApplication()
203 socket_notifiers_.clear();
207 LyXView & GuiApplication::createView(string const & geometry_arg)
209 int const id = createRegisteredView();
210 GuiView * view = views_[id];
211 theLyXFunc().setLyXView(view);
215 if (!geometry_arg.empty()) {
219 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
220 re.indexIn(toqstr(geometry_arg.c_str()));
221 w = re.cap(1).toInt();
222 h = re.cap(2).toInt();
223 x = re.cap(3).toInt();
224 y = re.cap(4).toInt();
225 view->setGeometry(x, y, w, h);
230 setCurrentView(*view);
238 Clipboard & GuiApplication::clipboard()
244 Selection & GuiApplication::selection()
250 int GuiApplication::exec()
252 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
253 return QApplication::exec();
257 void GuiApplication::exit(int status)
259 QApplication::exit(status);
263 void GuiApplication::execBatchCommands()
265 LyX::ref().execBatchCommands();
269 string const GuiApplication::romanFontName()
272 font.setKerning(false);
273 font.setStyleHint(QFont::Serif);
274 font.setFamily("serif");
276 return fromqstr(QFontInfo(font).family());
280 string const GuiApplication::sansFontName()
283 font.setKerning(false);
284 font.setStyleHint(QFont::SansSerif);
285 font.setFamily("sans");
287 return fromqstr(QFontInfo(font).family());
291 string const GuiApplication::typewriterFontName()
294 font.setKerning(false);
295 font.setStyleHint(QFont::TypeWriter);
296 font.setFamily("monospace");
298 return fromqstr(QFontInfo(font).family());
302 bool GuiApplication::event(QEvent * e)
305 case QEvent::FileOpen: {
306 // Open a file; this happens only on Mac OS X for now
307 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
309 if (!currentView() || !currentView()->view())
310 // The application is not properly initialized yet.
311 // So we acknowledge the event and delay the file opening
312 // until LyX is ready.
313 // FIXME UNICODE: FileName accept an utf8 encoded string.
314 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
316 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
317 qstring_to_ucs4(foe->file())));
323 return QApplication::event(e);
328 bool GuiApplication::notify(QObject * receiver, QEvent * event)
331 return QApplication::notify(receiver, event);
333 catch (support::ExceptionMessage const & e) {
334 if (e.type_ == support::ErrorException) {
335 Alert::error(e.title_, e.details_);
336 LyX::cref().emergencyCleanup();
337 QApplication::exit(1);
338 } else if (e.type_ == support::WarningException) {
339 Alert::warning(e.title_, e.details_);
343 catch (std::exception const & e) {
344 docstring s = _("LyX has caught an exception, it will now "
345 "attemp to save all unsaved documents and exit."
347 s += from_ascii(e.what());
348 Alert::error(_("Software exception Detected"), s);
349 LyX::cref().emergencyCleanup();
350 QApplication::exit(1);
353 docstring s = _("LyX has caught some really weird exception, it will "
354 "now attemp to save all unsaved documents and exit.");
355 Alert::error(_("Software exception Detected"), s);
356 LyX::cref().emergencyCleanup();
357 QApplication::exit(1);
364 void GuiApplication::syncEvents()
366 // This is the ONLY place where processEvents may be called.
367 // During screen update/ redraw, this method is disabled to
368 // prevent keyboard events being handed to the LyX core, where
369 // they could cause re-entrant calls to screen update.
370 processEvents(QEventLoop::ExcludeUserInputEvents);
374 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
376 QColor const & qcol = color_cache_.get(col);
377 if (!qcol.isValid()) {
383 rgbcol.r = qcol.red();
384 rgbcol.g = qcol.green();
385 rgbcol.b = qcol.blue();
390 string const GuiApplication::hexName(ColorCode col)
392 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
396 void GuiApplication::updateColor(ColorCode)
398 // FIXME: Bleh, can't we just clear them all at once ?
399 color_cache_.clear();
403 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
405 SocketNotifier * sn = new SocketNotifier(this, fd, func);
406 socket_notifiers_[fd] = sn;
407 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
411 void GuiApplication::socketDataReceived(int fd)
413 socket_notifiers_[fd]->func_();
417 void GuiApplication::unregisterSocketCallback(int fd)
419 socket_notifiers_.erase(fd);
423 void GuiApplication::commitData(QSessionManager & sm)
425 /// The implementation is required to avoid an application exit
426 /// when session state save is triggered by session manager.
427 /// The default implementation sends a close event to all
428 /// visible top level widgets when session managment allows
430 /// We are changing that to write all unsaved buffers...
431 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
436 void GuiApplication::addMenuTranslator()
438 installTranslator(new MenuTranslator(this));
442 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
445 map<int, GuiView *>::const_iterator it;
446 for (it = stdmap.begin(); it != stdmap.end(); ++it)
447 ids.push_back(it->first);
451 int GuiApplication::createRegisteredView()
453 updateIds(views_, view_ids_);
455 while (views_.find(id) != views_.end())
457 views_[id] = new GuiView(id);
458 updateIds(views_, view_ids_);
463 bool GuiApplication::unregisterView(int id)
465 updateIds(views_, view_ids_);
466 BOOST_ASSERT(views_.find(id) != views_.end());
467 BOOST_ASSERT(views_[id]);
469 map<int, GuiView *>::iterator it;
470 for (it = views_.begin(); it != views_.end(); ++it) {
471 if (it->first == id) {
476 updateIds(views_, view_ids_);
481 bool GuiApplication::closeAllViews()
483 updateIds(views_, view_ids_);
484 if (views_.empty()) {
485 // quit in CloseEvent will not be triggert
490 map<int, GuiView*> const cmap = views_;
491 map<int, GuiView*>::const_iterator it;
492 for (it = cmap.begin(); it != cmap.end(); ++it) {
493 // TODO: return false when close event was ignored
494 // e.g. quitWriteAll()->'Cancel'
495 // maybe we need something like 'bool closeView()'
497 // unregisterd by the CloseEvent
506 LyXView & GuiApplication::view(int id) const
508 BOOST_ASSERT(views_.find(id) != views_.end());
509 return *views_.find(id)->second;
513 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
515 vector<int>::const_iterator it = view_ids_.begin();
516 vector<int>::const_iterator const end = view_ids_.end();
517 for (; it != end; ++it)
518 view(*it).getDialogs().hide(name, inset);
522 Buffer const * GuiApplication::updateInset(Inset const * inset) const
524 Buffer const * buffer_ = 0;
525 vector<int>::const_iterator it = view_ids_.begin();
526 vector<int>::const_iterator const end = view_ids_.end();
527 for (; it != end; ++it) {
528 Buffer const * ptr = view(*it).updateInset(inset);
536 ////////////////////////////////////////////////////////////////////////
537 // X11 specific stuff goes here...
539 bool GuiApplication::x11EventFilter(XEvent * xev)
545 case SelectionRequest: {
546 if (xev->xselectionrequest.selection != XA_PRIMARY)
548 LYXERR(Debug::GUI, "X requested selection.");
549 BufferView * bv = currentView()->view();
551 docstring const sel = bv->requestSelection();
557 case SelectionClear: {
558 if (xev->xselectionclear.selection != XA_PRIMARY)
560 LYXERR(Debug::GUI, "Lost selection.");
561 BufferView * bv = currentView()->view();
563 bv->clearSelection();
571 } // namespace frontend
574 ////////////////////////////////////////////////////////////////////
578 ////////////////////////////////////////////////////////////////////
580 frontend::FontLoader & theFontLoader()
582 static frontend::NoGuiFontLoader no_gui_font_loader;
585 return no_gui_font_loader;
587 BOOST_ASSERT(theApp());
588 return theApp()->fontLoader();
592 frontend::FontMetrics const & theFontMetrics(Font const & f)
594 return theFontMetrics(f.fontInfo());
598 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
600 static frontend::NoGuiFontMetrics no_gui_font_metrics;
603 return no_gui_font_metrics;
605 BOOST_ASSERT(theApp());
606 return theApp()->fontLoader().metrics(f);
610 frontend::Clipboard & theClipboard()
612 BOOST_ASSERT(frontend::guiApp);
613 return frontend::guiApp->clipboard();
617 frontend::Selection & theSelection()
619 BOOST_ASSERT(frontend::guiApp);
620 return frontend::guiApp->selection();
625 #include "GuiApplication_moc.cpp"