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(), current_view_(0)
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);
198 // Initialize RC Fonts
199 if (lyxrc.roman_font_name.empty())
200 lyxrc.roman_font_name = fromqstr(romanFontName());
202 if (lyxrc.sans_font_name.empty())
203 lyxrc.sans_font_name = fromqstr(sansFontName());
205 if (lyxrc.typewriter_font_name.empty())
206 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
210 GuiApplication::~GuiApplication()
212 socket_notifiers_.clear();
216 void GuiApplication::resetGui()
218 map<int, GuiView *>::iterator it;
219 for (it = views_.begin(); it != views_.end(); ++it)
220 it->second->resetDialogs();
224 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
227 map<int, GuiView *>::const_iterator it;
228 for (it = stdmap.begin(); it != stdmap.end(); ++it)
229 ids.push_back(it->first);
233 void GuiApplication::createView(string const & geometry_arg)
235 updateIds(views_, view_ids_);
237 while (views_.find(id) != views_.end())
239 views_[id] = new GuiView(id);
240 updateIds(views_, view_ids_);
242 GuiView * view = views_[id];
243 theLyXFunc().setLyXView(view);
246 if (!geometry_arg.empty()) {
250 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
251 re.indexIn(toqstr(geometry_arg.c_str()));
252 w = re.cap(1).toInt();
253 h = re.cap(2).toInt();
254 x = re.cap(3).toInt();
255 y = re.cap(4).toInt();
256 view->setGeometry(x, y, w, h);
261 setCurrentView(*view);
267 Clipboard & GuiApplication::clipboard()
273 Selection & GuiApplication::selection()
279 int GuiApplication::exec()
281 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
282 return QApplication::exec();
286 void GuiApplication::exit(int status)
288 QApplication::exit(status);
292 void GuiApplication::execBatchCommands()
294 LyX::ref().execBatchCommands();
298 QString const GuiApplication::romanFontName()
301 font.setKerning(false);
302 font.setStyleHint(QFont::Serif);
303 font.setFamily("serif");
305 return QFontInfo(font).family();
309 QString const GuiApplication::sansFontName()
312 font.setKerning(false);
313 font.setStyleHint(QFont::SansSerif);
314 font.setFamily("sans");
316 return QFontInfo(font).family();
320 QString const GuiApplication::typewriterFontName()
323 font.setKerning(false);
324 font.setStyleHint(QFont::TypeWriter);
325 font.setFamily("monospace");
327 return QFontInfo(font).family();
331 bool GuiApplication::event(QEvent * e)
334 case QEvent::FileOpen: {
335 // Open a file; this happens only on Mac OS X for now
336 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
338 if (!current_view_ || !current_view_->view())
339 // The application is not properly initialized yet.
340 // So we acknowledge the event and delay the file opening
341 // until LyX is ready.
342 // FIXME UNICODE: FileName accept an utf8 encoded string.
343 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
345 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
346 qstring_to_ucs4(foe->file())));
352 return QApplication::event(e);
357 bool GuiApplication::notify(QObject * receiver, QEvent * event)
360 return QApplication::notify(receiver, event);
362 catch (support::ExceptionMessage const & e) {
363 if (e.type_ == support::ErrorException) {
364 Alert::error(e.title_, e.details_);
365 LyX::cref().emergencyCleanup();
366 QApplication::exit(1);
367 } else if (e.type_ == support::WarningException) {
368 Alert::warning(e.title_, e.details_);
372 catch (std::exception const & e) {
373 docstring s = _("LyX has caught an exception, it will now "
374 "attemp to save all unsaved documents and exit."
376 s += from_ascii(e.what());
377 Alert::error(_("Software exception Detected"), s);
378 LyX::cref().emergencyCleanup();
379 QApplication::exit(1);
382 docstring s = _("LyX has caught some really weird exception, it will "
383 "now attemp to save all unsaved documents and exit.");
384 Alert::error(_("Software exception Detected"), s);
385 LyX::cref().emergencyCleanup();
386 QApplication::exit(1);
393 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
395 QColor const & qcol = color_cache_.get(col);
396 if (!qcol.isValid()) {
402 rgbcol.r = qcol.red();
403 rgbcol.g = qcol.green();
404 rgbcol.b = qcol.blue();
409 string const GuiApplication::hexName(ColorCode col)
411 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
415 void GuiApplication::updateColor(ColorCode)
417 // FIXME: Bleh, can't we just clear them all at once ?
418 color_cache_.clear();
422 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
424 SocketNotifier * sn = new SocketNotifier(this, fd, func);
425 socket_notifiers_[fd] = sn;
426 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
430 void GuiApplication::socketDataReceived(int fd)
432 socket_notifiers_[fd]->func_();
436 void GuiApplication::unregisterSocketCallback(int fd)
438 socket_notifiers_.erase(fd);
442 void GuiApplication::commitData(QSessionManager & sm)
444 /// The implementation is required to avoid an application exit
445 /// when session state save is triggered by session manager.
446 /// The default implementation sends a close event to all
447 /// visible top level widgets when session managment allows
449 /// We are changing that to write all unsaved buffers...
450 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
455 void GuiApplication::addMenuTranslator()
457 installTranslator(new MenuTranslator(this));
461 bool GuiApplication::unregisterView(int id)
463 updateIds(views_, view_ids_);
464 BOOST_ASSERT(views_.find(id) != views_.end());
465 BOOST_ASSERT(views_[id]);
467 map<int, GuiView *>::iterator it;
468 for (it = views_.begin(); it != views_.end(); ++it) {
469 if (it->first == id) {
474 updateIds(views_, view_ids_);
479 bool GuiApplication::closeAllViews()
481 updateIds(views_, view_ids_);
482 if (views_.empty()) {
483 // quit in CloseEvent will not be triggert
488 map<int, GuiView*> const cmap = views_;
489 map<int, GuiView*>::const_iterator it;
490 for (it = cmap.begin(); it != cmap.end(); ++it) {
491 // TODO: return false when close event was ignored
492 // e.g. quitWriteAll()->'Cancel'
493 // maybe we need something like 'bool closeView()'
495 // unregisterd by the CloseEvent
504 GuiView & GuiApplication::view(int id) const
506 BOOST_ASSERT(views_.find(id) != views_.end());
507 return *views_.find(id)->second;
511 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
513 vector<int>::const_iterator it = view_ids_.begin();
514 vector<int>::const_iterator const end = view_ids_.end();
515 for (; it != end; ++it)
516 view(*it).hideDialog(name, inset);
520 Buffer const * GuiApplication::updateInset(Inset const * inset) const
522 Buffer const * buffer_ = 0;
523 vector<int>::const_iterator it = view_ids_.begin();
524 vector<int>::const_iterator const end = view_ids_.end();
525 for (; it != end; ++it) {
526 Buffer const * ptr = view(*it).updateInset(inset);
534 ////////////////////////////////////////////////////////////////////////
535 // X11 specific stuff goes here...
537 bool GuiApplication::x11EventFilter(XEvent * xev)
543 case SelectionRequest: {
544 if (xev->xselectionrequest.selection != XA_PRIMARY)
546 LYXERR(Debug::GUI, "X requested selection.");
547 BufferView * bv = current_view_->view();
549 docstring const sel = bv->requestSelection();
555 case SelectionClear: {
556 if (xev->xselectionclear.selection != XA_PRIMARY)
558 LYXERR(Debug::GUI, "Lost selection.");
559 BufferView * bv = current_view_->view();
561 bv->clearSelection();
569 } // namespace frontend
572 ////////////////////////////////////////////////////////////////////
576 ////////////////////////////////////////////////////////////////////
578 frontend::FontLoader & theFontLoader()
580 static frontend::NoGuiFontLoader no_gui_font_loader;
583 return no_gui_font_loader;
585 BOOST_ASSERT(frontend::guiApp);
586 return frontend::guiApp->fontLoader();
590 frontend::FontMetrics const & theFontMetrics(Font const & f)
592 return theFontMetrics(f.fontInfo());
596 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
598 static frontend::NoGuiFontMetrics no_gui_font_metrics;
601 return no_gui_font_metrics;
603 BOOST_ASSERT(frontend::guiApp);
604 return frontend::guiApp->fontLoader().metrics(f);
608 frontend::Clipboard & theClipboard()
610 BOOST_ASSERT(frontend::guiApp);
611 return frontend::guiApp->clipboard();
615 frontend::Selection & theSelection()
617 BOOST_ASSERT(frontend::guiApp);
618 return frontend::guiApp->selection();
623 #include "GuiApplication_moc.cpp"