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 "support/ExceptionMessage.h"
29 #include "support/FileName.h"
30 #include "support/lstrings.h"
31 #include "support/os.h"
32 #include "support/Package.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
38 #include "FuncRequest.h"
45 #include <QApplication>
48 #include <QFileOpenEvent>
50 #include <QLibraryInfo>
51 #include <QPixmapCache>
53 #include <QSessionManager>
54 #include <QSocketNotifier>
57 #include <QTranslator>
61 #include <X11/Xatom.h>
67 #include <boost/bind.hpp>
79 frontend::Application * createApplication(int & argc, char * argv[])
81 return new frontend::GuiApplication(argc, argv);
87 class SocketNotifier : public QSocketNotifier
90 /// connect a connection notification from the LyXServerSocket
91 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
92 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
96 /// The callback function
97 Application::SocketCallback func_;
101 ////////////////////////////////////////////////////////////////////////
102 // Mac specific stuff goes here...
104 class MenuTranslator : public QTranslator
107 MenuTranslator(QObject * parent)
108 : QTranslator(parent)
111 QString translate(const char * /*context*/,
112 const char * sourceText,
113 const char * /*comment*/ = 0)
115 string const s = sourceText;
116 if (s == N_("About %1") || s == N_("Preferences")
117 || s == N_("Reconfigure") || s == N_("Quit %1"))
125 ///////////////////////////////////////////////////////////////
126 // You can find more platform specific stuff
127 // at the end of this file...
128 ///////////////////////////////////////////////////////////////
131 using support::FileName;
133 GuiApplication * guiApp;
136 GuiApplication::GuiApplication(int & argc, char ** argv)
137 : QApplication(argc, argv), Application(), current_view_(0)
139 QString app_name = "LyX";
140 QCoreApplication::setOrganizationName(app_name);
141 QCoreApplication::setOrganizationDomain("lyx.org");
142 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
144 // Qt bug? setQuitOnLastWindowClosed(true); does not work
145 setQuitOnLastWindowClosed(false);
148 // doubleClickInterval() is 400 ms on X11 which is just too long.
149 // On Windows and Mac OS X, the operating system's value is used.
150 // On Microsoft Windows, calling this function sets the double
151 // click interval for all applications. So we don't!
152 QApplication::setDoubleClickInterval(300);
155 // install translation file for Qt built-in dialogs
156 QString language_name = QString("qt_") + QLocale::system().name();
158 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
159 // Short-named translator can be loaded from a long name, but not the
160 // opposite. Therefore, long name should be used without truncation.
161 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
162 if (qt_trans_.load(language_name,
163 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
165 installTranslator(&qt_trans_);
166 // even if the language calls for RtL, don't do that
167 setLayoutDirection(Qt::LeftToRight);
168 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
169 << fromqstr(language_name));
171 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
172 << fromqstr(language_name));
175 // This allows to translate the strings that appear in the LyX menu.
179 using namespace lyx::graphics;
181 Image::newImage = boost::bind(&GuiImage::newImage);
182 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
184 // needs to be done before reading lyxrc
186 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
190 // Set the cache to 5120 kilobytes which corresponds to screen size of
191 // 1280 by 1024 pixels with a color depth of 32 bits.
192 QPixmapCache::setCacheLimit(5120);
194 // Initialize RC Fonts
195 if (lyxrc.roman_font_name.empty())
196 lyxrc.roman_font_name = fromqstr(romanFontName());
198 if (lyxrc.sans_font_name.empty())
199 lyxrc.sans_font_name = fromqstr(sansFontName());
201 if (lyxrc.typewriter_font_name.empty())
202 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
206 GuiApplication::~GuiApplication()
208 socket_notifiers_.clear();
212 void GuiApplication::resetGui()
214 map<int, GuiView *>::iterator it;
215 for (it = views_.begin(); it != views_.end(); ++it)
216 it->second->resetDialogs();
220 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
223 map<int, GuiView *>::const_iterator it;
224 for (it = stdmap.begin(); it != stdmap.end(); ++it)
225 ids.push_back(it->first);
229 void GuiApplication::createView(string const & geometry_arg)
231 updateIds(views_, view_ids_);
233 while (views_.find(id) != views_.end())
235 views_[id] = new GuiView(id);
236 updateIds(views_, view_ids_);
238 GuiView * view = views_[id];
239 theLyXFunc().setLyXView(view);
242 if (!geometry_arg.empty()) {
246 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
247 re.indexIn(toqstr(geometry_arg.c_str()));
248 w = re.cap(1).toInt();
249 h = re.cap(2).toInt();
250 x = re.cap(3).toInt();
251 y = re.cap(4).toInt();
252 view->setGeometry(x, y, w, h);
257 setCurrentView(*view);
263 Clipboard & GuiApplication::clipboard()
269 Selection & GuiApplication::selection()
275 int GuiApplication::exec()
277 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
278 return QApplication::exec();
282 void GuiApplication::exit(int status)
284 QApplication::exit(status);
288 void GuiApplication::execBatchCommands()
290 LyX::ref().execBatchCommands();
294 QString const GuiApplication::romanFontName()
297 font.setKerning(false);
298 font.setStyleHint(QFont::Serif);
299 font.setFamily("serif");
301 return QFontInfo(font).family();
305 QString const GuiApplication::sansFontName()
308 font.setKerning(false);
309 font.setStyleHint(QFont::SansSerif);
310 font.setFamily("sans");
312 return QFontInfo(font).family();
316 QString const GuiApplication::typewriterFontName()
319 font.setKerning(false);
320 font.setStyleHint(QFont::TypeWriter);
321 font.setFamily("monospace");
323 return QFontInfo(font).family();
327 bool GuiApplication::event(QEvent * e)
330 case QEvent::FileOpen: {
331 // Open a file; this happens only on Mac OS X for now
332 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
334 if (!current_view_ || !current_view_->view())
335 // The application is not properly initialized yet.
336 // So we acknowledge the event and delay the file opening
337 // until LyX is ready.
338 // FIXME UNICODE: FileName accept an utf8 encoded string.
339 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
341 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
342 qstring_to_ucs4(foe->file())));
348 return QApplication::event(e);
353 bool GuiApplication::notify(QObject * receiver, QEvent * event)
356 return QApplication::notify(receiver, event);
358 catch (support::ExceptionMessage const & e) {
359 if (e.type_ == support::ErrorException) {
360 Alert::error(e.title_, e.details_);
361 LyX::cref().emergencyCleanup();
362 QApplication::exit(1);
363 } else if (e.type_ == support::WarningException) {
364 Alert::warning(e.title_, e.details_);
368 catch (std::exception const & e) {
369 docstring s = _("LyX has caught an exception, it will now "
370 "attemp to save all unsaved documents and exit."
372 s += from_ascii(e.what());
373 Alert::error(_("Software exception Detected"), s);
374 LyX::cref().emergencyCleanup();
375 QApplication::exit(1);
378 docstring s = _("LyX has caught some really weird exception, it will "
379 "now attemp to save all unsaved documents and exit.");
380 Alert::error(_("Software exception Detected"), s);
381 LyX::cref().emergencyCleanup();
382 QApplication::exit(1);
389 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
391 QColor const & qcol = color_cache_.get(col);
392 if (!qcol.isValid()) {
398 rgbcol.r = qcol.red();
399 rgbcol.g = qcol.green();
400 rgbcol.b = qcol.blue();
405 string const GuiApplication::hexName(ColorCode col)
407 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
411 void GuiApplication::updateColor(ColorCode)
413 // FIXME: Bleh, can't we just clear them all at once ?
414 color_cache_.clear();
418 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
420 SocketNotifier * sn = new SocketNotifier(this, fd, func);
421 socket_notifiers_[fd] = sn;
422 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
426 void GuiApplication::socketDataReceived(int fd)
428 socket_notifiers_[fd]->func_();
432 void GuiApplication::unregisterSocketCallback(int fd)
434 socket_notifiers_.erase(fd);
438 void GuiApplication::commitData(QSessionManager & sm)
440 /// The implementation is required to avoid an application exit
441 /// when session state save is triggered by session manager.
442 /// The default implementation sends a close event to all
443 /// visible top level widgets when session managment allows
445 /// We are changing that to write all unsaved buffers...
446 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
451 void GuiApplication::addMenuTranslator()
453 installTranslator(new MenuTranslator(this));
457 bool GuiApplication::unregisterView(int id)
459 updateIds(views_, view_ids_);
460 BOOST_ASSERT(views_.find(id) != views_.end());
461 BOOST_ASSERT(views_[id]);
463 map<int, GuiView *>::iterator it;
464 for (it = views_.begin(); it != views_.end(); ++it) {
465 if (it->first == id) {
470 updateIds(views_, view_ids_);
475 bool GuiApplication::closeAllViews()
477 updateIds(views_, view_ids_);
478 if (views_.empty()) {
479 // quit in CloseEvent will not be triggert
484 map<int, GuiView*> const cmap = views_;
485 map<int, GuiView*>::const_iterator it;
486 for (it = cmap.begin(); it != cmap.end(); ++it) {
487 // TODO: return false when close event was ignored
488 // e.g. quitWriteAll()->'Cancel'
489 // maybe we need something like 'bool closeView()'
491 // unregisterd by the CloseEvent
500 GuiView & GuiApplication::view(int id) const
502 BOOST_ASSERT(views_.find(id) != views_.end());
503 return *views_.find(id)->second;
507 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
509 vector<int>::const_iterator it = view_ids_.begin();
510 vector<int>::const_iterator const end = view_ids_.end();
511 for (; it != end; ++it)
512 view(*it).hideDialog(name, inset);
516 Buffer const * GuiApplication::updateInset(Inset const * inset) const
518 Buffer const * buffer_ = 0;
519 vector<int>::const_iterator it = view_ids_.begin();
520 vector<int>::const_iterator const end = view_ids_.end();
521 for (; it != end; ++it) {
522 Buffer const * ptr = view(*it).updateInset(inset);
530 ////////////////////////////////////////////////////////////////////////
531 // X11 specific stuff goes here...
533 bool GuiApplication::x11EventFilter(XEvent * xev)
539 case SelectionRequest: {
540 if (xev->xselectionrequest.selection != XA_PRIMARY)
542 LYXERR(Debug::GUI, "X requested selection.");
543 BufferView * bv = current_view_->view();
545 docstring const sel = bv->requestSelection();
551 case SelectionClear: {
552 if (xev->xselectionclear.selection != XA_PRIMARY)
554 LYXERR(Debug::GUI, "Lost selection.");
555 BufferView * bv = current_view_->view();
557 bv->clearSelection();
565 } // namespace frontend
568 ////////////////////////////////////////////////////////////////////
572 ////////////////////////////////////////////////////////////////////
574 frontend::FontLoader & theFontLoader()
576 static frontend::NoGuiFontLoader no_gui_font_loader;
579 return no_gui_font_loader;
581 BOOST_ASSERT(frontend::guiApp);
582 return frontend::guiApp->fontLoader();
586 frontend::FontMetrics const & theFontMetrics(Font const & f)
588 return theFontMetrics(f.fontInfo());
592 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
594 static frontend::NoGuiFontMetrics no_gui_font_metrics;
597 return no_gui_font_metrics;
599 BOOST_ASSERT(frontend::guiApp);
600 return frontend::guiApp->fontLoader().metrics(f);
604 frontend::Clipboard & theClipboard()
606 BOOST_ASSERT(frontend::guiApp);
607 return frontend::guiApp->clipboard();
611 frontend::Selection & theSelection()
613 BOOST_ASSERT(frontend::guiApp);
614 return frontend::guiApp->selection();
619 #include "GuiApplication_moc.cpp"