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"
21 #include "frontends/alert.h"
22 #include "frontends/Application.h"
23 #include "frontends/NoGuiFontLoader.h"
24 #include "frontends/NoGuiFontMetrics.h"
25 #include "frontends/FontLoader.h"
26 #include "frontends/FontMetrics.h"
28 #include "graphics/LoaderQueue.h"
30 #include "support/ExceptionMessage.h"
31 #include "support/FileName.h"
32 #include "support/lstrings.h"
33 #include "support/os.h"
34 #include "support/Package.h"
36 #include "BufferList.h"
37 #include "BufferView.h"
40 #include "FuncRequest.h"
47 #include <QApplication>
50 #include <QFileOpenEvent>
52 #include <QLibraryInfo>
53 #include <QPixmapCache>
55 #include <QSessionManager>
56 #include <QSocketNotifier>
59 #include <QTranslator>
63 #include <X11/Xatom.h>
69 #include <boost/bind.hpp>
81 frontend::Application * createApplication(int & argc, char * argv[])
83 return new frontend::GuiApplication(argc, argv);
89 class SocketNotifier : public QSocketNotifier
92 /// connect a connection notification from the LyXServerSocket
93 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
94 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
98 /// The callback function
99 Application::SocketCallback func_;
103 ////////////////////////////////////////////////////////////////////////
104 // Mac specific stuff goes here...
106 class MenuTranslator : public QTranslator
109 MenuTranslator(QObject * parent)
110 : QTranslator(parent)
113 QString translate(const char * /*context*/,
114 const char * sourceText,
115 const char * /*comment*/ = 0)
117 string const s = sourceText;
118 if (s == N_("About %1") || s == N_("Preferences")
119 || s == N_("Reconfigure") || s == N_("Quit %1"))
127 ///////////////////////////////////////////////////////////////
128 // You can find more platform specific stuff
129 // at the end of this file...
130 ///////////////////////////////////////////////////////////////
133 using support::FileName;
135 GuiApplication * guiApp;
138 GuiApplication::GuiApplication(int & argc, char ** argv)
139 : QApplication(argc, argv), Application()
141 QString app_name = "LyX";
142 QCoreApplication::setOrganizationName(app_name);
143 QCoreApplication::setOrganizationDomain("lyx.org");
144 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
146 // Qt bug? setQuitOnLastWindowClosed(true); does not work
147 setQuitOnLastWindowClosed(false);
150 // doubleClickInterval() is 400 ms on X11 which is just too long.
151 // On Windows and Mac OS X, the operating system's value is used.
152 // On Microsoft Windows, calling this function sets the double
153 // click interval for all applications. So we don't!
154 QApplication::setDoubleClickInterval(300);
157 // install translation file for Qt built-in dialogs
158 QString language_name = QString("qt_") + QLocale::system().name();
160 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
161 // Short-named translator can be loaded from a long name, but not the
162 // opposite. Therefore, long name should be used without truncation.
163 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
164 if (qt_trans_.load(language_name,
165 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
167 installTranslator(&qt_trans_);
168 // even if the language calls for RtL, don't do that
169 setLayoutDirection(Qt::LeftToRight);
170 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
171 << fromqstr(language_name));
173 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
174 << fromqstr(language_name));
177 // This allows to translate the strings that appear in the LyX menu.
181 using namespace lyx::graphics;
183 Image::newImage = boost::bind(&GuiImage::newImage);
184 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
186 // needs to be done before reading lyxrc
188 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
190 LoaderQueue::setPriority(10,100);
194 // Set the cache to 5120 kilobytes which corresponds to screen size of
195 // 1280 by 1024 pixels with a color depth of 32 bits.
196 QPixmapCache::setCacheLimit(5120);
200 GuiApplication::~GuiApplication()
202 socket_notifiers_.clear();
206 LyXView & GuiApplication::createView(string const & geometry_arg)
208 int const id = createRegisteredView();
209 GuiView * view = views_[id];
210 theLyXFunc().setLyXView(view);
214 if (!geometry_arg.empty()) {
218 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
219 re.indexIn(toqstr(geometry_arg.c_str()));
220 w = re.cap(1).toInt();
221 h = re.cap(2).toInt();
222 x = re.cap(3).toInt();
223 y = re.cap(4).toInt();
224 view->setGeometry(x, y, w, h);
229 setCurrentView(*view);
237 Clipboard & GuiApplication::clipboard()
243 Selection & GuiApplication::selection()
249 int GuiApplication::exec()
251 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
252 return QApplication::exec();
256 void GuiApplication::exit(int status)
258 QApplication::exit(status);
262 void GuiApplication::execBatchCommands()
264 LyX::ref().execBatchCommands();
268 string const GuiApplication::romanFontName()
271 font.setKerning(false);
272 font.setStyleHint(QFont::Serif);
273 font.setFamily("serif");
275 return fromqstr(QFontInfo(font).family());
279 string const GuiApplication::sansFontName()
282 font.setKerning(false);
283 font.setStyleHint(QFont::SansSerif);
284 font.setFamily("sans");
286 return fromqstr(QFontInfo(font).family());
290 string const GuiApplication::typewriterFontName()
293 font.setKerning(false);
294 font.setStyleHint(QFont::TypeWriter);
295 font.setFamily("monospace");
297 return fromqstr(QFontInfo(font).family());
301 bool GuiApplication::event(QEvent * e)
304 case QEvent::FileOpen: {
305 // Open a file; this happens only on Mac OS X for now
306 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
308 if (!currentView() || !currentView()->view())
309 // The application is not properly initialized yet.
310 // So we acknowledge the event and delay the file opening
311 // until LyX is ready.
312 // FIXME UNICODE: FileName accept an utf8 encoded string.
313 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
315 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
316 qstring_to_ucs4(foe->file())));
322 return QApplication::event(e);
327 bool GuiApplication::notify(QObject * receiver, QEvent * event)
330 return QApplication::notify(receiver, event);
332 catch (support::ExceptionMessage const & e) {
333 if (e.type_ == support::ErrorException) {
334 Alert::error(e.title_, e.details_);
335 LyX::cref().emergencyCleanup();
336 QApplication::exit(1);
337 } else if (e.type_ == support::WarningException) {
338 Alert::warning(e.title_, e.details_);
342 catch (std::exception const & e) {
343 docstring s = _("LyX has caught an exception, it will now "
344 "attemp to save all unsaved documents and exit."
346 s += from_ascii(e.what());
347 Alert::error(_("Software exception Detected"), s);
348 LyX::cref().emergencyCleanup();
349 QApplication::exit(1);
352 docstring s = _("LyX has caught some really weird exception, it will "
353 "now attemp to save all unsaved documents and exit.");
354 Alert::error(_("Software exception Detected"), s);
355 LyX::cref().emergencyCleanup();
356 QApplication::exit(1);
363 void GuiApplication::syncEvents()
365 // This is the ONLY place where processEvents may be called.
366 // During screen update/ redraw, this method is disabled to
367 // prevent keyboard events being handed to the LyX core, where
368 // they could cause re-entrant calls to screen update.
369 processEvents(QEventLoop::ExcludeUserInputEvents);
373 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
375 QColor const & qcol = color_cache_.get(col);
376 if (!qcol.isValid()) {
382 rgbcol.r = qcol.red();
383 rgbcol.g = qcol.green();
384 rgbcol.b = qcol.blue();
389 string const GuiApplication::hexName(ColorCode col)
391 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
395 void GuiApplication::updateColor(ColorCode)
397 // FIXME: Bleh, can't we just clear them all at once ?
398 color_cache_.clear();
402 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
404 SocketNotifier * sn = new SocketNotifier(this, fd, func);
405 socket_notifiers_[fd] = sn;
406 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
410 void GuiApplication::socketDataReceived(int fd)
412 socket_notifiers_[fd]->func_();
416 void GuiApplication::unregisterSocketCallback(int fd)
418 socket_notifiers_.erase(fd);
422 void GuiApplication::commitData(QSessionManager & sm)
424 /// The implementation is required to avoid an application exit
425 /// when session state save is triggered by session manager.
426 /// The default implementation sends a close event to all
427 /// visible top level widgets when session managment allows
429 /// We are changing that to write all unsaved buffers...
430 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
435 void GuiApplication::addMenuTranslator()
437 installTranslator(new MenuTranslator(this));
441 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
444 map<int, GuiView *>::const_iterator it;
445 for (it = stdmap.begin(); it != stdmap.end(); ++it)
446 ids.push_back(it->first);
450 int GuiApplication::createRegisteredView()
452 updateIds(views_, view_ids_);
454 while (views_.find(id) != views_.end())
456 views_[id] = new GuiView(id);
457 updateIds(views_, view_ids_);
462 bool GuiApplication::unregisterView(int id)
464 updateIds(views_, view_ids_);
465 BOOST_ASSERT(views_.find(id) != views_.end());
466 BOOST_ASSERT(views_[id]);
468 map<int, GuiView *>::iterator it;
469 for (it = views_.begin(); it != views_.end(); ++it) {
470 if (it->first == id) {
475 updateIds(views_, view_ids_);
480 bool GuiApplication::closeAllViews()
482 updateIds(views_, view_ids_);
483 if (views_.empty()) {
484 // quit in CloseEvent will not be triggert
489 map<int, GuiView*> const cmap = views_;
490 map<int, GuiView*>::const_iterator it;
491 for (it = cmap.begin(); it != cmap.end(); ++it) {
492 // TODO: return false when close event was ignored
493 // e.g. quitWriteAll()->'Cancel'
494 // maybe we need something like 'bool closeView()'
496 // unregisterd by the CloseEvent
505 LyXView & GuiApplication::view(int id) const
507 BOOST_ASSERT(views_.find(id) != views_.end());
508 return *views_.find(id)->second;
512 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
514 vector<int>::const_iterator it = view_ids_.begin();
515 vector<int>::const_iterator const end = view_ids_.end();
516 for (; it != end; ++it)
517 view(*it).hideDialog(name, inset);
521 Buffer const * GuiApplication::updateInset(Inset const * inset) const
523 Buffer const * buffer_ = 0;
524 vector<int>::const_iterator it = view_ids_.begin();
525 vector<int>::const_iterator const end = view_ids_.end();
526 for (; it != end; ++it) {
527 Buffer const * ptr = view(*it).updateInset(inset);
535 ////////////////////////////////////////////////////////////////////////
536 // X11 specific stuff goes here...
538 bool GuiApplication::x11EventFilter(XEvent * xev)
544 case SelectionRequest: {
545 if (xev->xselectionrequest.selection != XA_PRIMARY)
547 LYXERR(Debug::GUI, "X requested selection.");
548 BufferView * bv = currentView()->view();
550 docstring const sel = bv->requestSelection();
556 case SelectionClear: {
557 if (xev->xselectionclear.selection != XA_PRIMARY)
559 LYXERR(Debug::GUI, "Lost selection.");
560 BufferView * bv = currentView()->view();
562 bv->clearSelection();
570 } // namespace frontend
573 ////////////////////////////////////////////////////////////////////
577 ////////////////////////////////////////////////////////////////////
579 frontend::FontLoader & theFontLoader()
581 static frontend::NoGuiFontLoader no_gui_font_loader;
584 return no_gui_font_loader;
586 BOOST_ASSERT(theApp());
587 return theApp()->fontLoader();
591 frontend::FontMetrics const & theFontMetrics(Font const & f)
593 return theFontMetrics(f.fontInfo());
597 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
599 static frontend::NoGuiFontMetrics no_gui_font_metrics;
602 return no_gui_font_metrics;
604 BOOST_ASSERT(theApp());
605 return theApp()->fontLoader().metrics(f);
609 frontend::Clipboard & theClipboard()
611 BOOST_ASSERT(frontend::guiApp);
612 return frontend::guiApp->clipboard();
616 frontend::Selection & theSelection()
618 BOOST_ASSERT(frontend::guiApp);
619 return frontend::guiApp->selection();
624 #include "GuiApplication_moc.cpp"