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 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
219 map<int, GuiView *>::const_iterator it;
220 for (it = stdmap.begin(); it != stdmap.end(); ++it)
221 ids.push_back(it->first);
225 LyXView & GuiApplication::createView(string const & geometry_arg)
227 updateIds(views_, view_ids_);
229 while (views_.find(id) != views_.end())
231 views_[id] = new GuiView(id);
232 updateIds(views_, view_ids_);
234 GuiView * view = views_[id];
235 theLyXFunc().setLyXView(view);
238 if (!geometry_arg.empty()) {
242 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
243 re.indexIn(toqstr(geometry_arg.c_str()));
244 w = re.cap(1).toInt();
245 h = re.cap(2).toInt();
246 x = re.cap(3).toInt();
247 y = re.cap(4).toInt();
248 view->setGeometry(x, y, w, h);
253 setCurrentView(*view);
261 Clipboard & GuiApplication::clipboard()
267 Selection & GuiApplication::selection()
273 int GuiApplication::exec()
275 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
276 return QApplication::exec();
280 void GuiApplication::exit(int status)
282 QApplication::exit(status);
286 void GuiApplication::execBatchCommands()
288 LyX::ref().execBatchCommands();
292 QString const GuiApplication::romanFontName()
295 font.setKerning(false);
296 font.setStyleHint(QFont::Serif);
297 font.setFamily("serif");
299 return QFontInfo(font).family();
303 QString const GuiApplication::sansFontName()
306 font.setKerning(false);
307 font.setStyleHint(QFont::SansSerif);
308 font.setFamily("sans");
310 return QFontInfo(font).family();
314 QString const GuiApplication::typewriterFontName()
317 font.setKerning(false);
318 font.setStyleHint(QFont::TypeWriter);
319 font.setFamily("monospace");
321 return QFontInfo(font).family();
325 bool GuiApplication::event(QEvent * e)
328 case QEvent::FileOpen: {
329 // Open a file; this happens only on Mac OS X for now
330 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
332 if (!current_view_ || !current_view_->view())
333 // The application is not properly initialized yet.
334 // So we acknowledge the event and delay the file opening
335 // until LyX is ready.
336 // FIXME UNICODE: FileName accept an utf8 encoded string.
337 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
339 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
340 qstring_to_ucs4(foe->file())));
346 return QApplication::event(e);
351 bool GuiApplication::notify(QObject * receiver, QEvent * event)
354 return QApplication::notify(receiver, event);
356 catch (support::ExceptionMessage const & e) {
357 if (e.type_ == support::ErrorException) {
358 Alert::error(e.title_, e.details_);
359 LyX::cref().emergencyCleanup();
360 QApplication::exit(1);
361 } else if (e.type_ == support::WarningException) {
362 Alert::warning(e.title_, e.details_);
366 catch (std::exception const & e) {
367 docstring s = _("LyX has caught an exception, it will now "
368 "attemp to save all unsaved documents and exit."
370 s += from_ascii(e.what());
371 Alert::error(_("Software exception Detected"), s);
372 LyX::cref().emergencyCleanup();
373 QApplication::exit(1);
376 docstring s = _("LyX has caught some really weird exception, it will "
377 "now attemp to save all unsaved documents and exit.");
378 Alert::error(_("Software exception Detected"), s);
379 LyX::cref().emergencyCleanup();
380 QApplication::exit(1);
387 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
389 QColor const & qcol = color_cache_.get(col);
390 if (!qcol.isValid()) {
396 rgbcol.r = qcol.red();
397 rgbcol.g = qcol.green();
398 rgbcol.b = qcol.blue();
403 string const GuiApplication::hexName(ColorCode col)
405 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
409 void GuiApplication::updateColor(ColorCode)
411 // FIXME: Bleh, can't we just clear them all at once ?
412 color_cache_.clear();
416 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
418 SocketNotifier * sn = new SocketNotifier(this, fd, func);
419 socket_notifiers_[fd] = sn;
420 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
424 void GuiApplication::socketDataReceived(int fd)
426 socket_notifiers_[fd]->func_();
430 void GuiApplication::unregisterSocketCallback(int fd)
432 socket_notifiers_.erase(fd);
436 void GuiApplication::commitData(QSessionManager & sm)
438 /// The implementation is required to avoid an application exit
439 /// when session state save is triggered by session manager.
440 /// The default implementation sends a close event to all
441 /// visible top level widgets when session managment allows
443 /// We are changing that to write all unsaved buffers...
444 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
449 void GuiApplication::addMenuTranslator()
451 installTranslator(new MenuTranslator(this));
455 bool GuiApplication::unregisterView(int id)
457 updateIds(views_, view_ids_);
458 BOOST_ASSERT(views_.find(id) != views_.end());
459 BOOST_ASSERT(views_[id]);
461 map<int, GuiView *>::iterator it;
462 for (it = views_.begin(); it != views_.end(); ++it) {
463 if (it->first == id) {
468 updateIds(views_, view_ids_);
473 bool GuiApplication::closeAllViews()
475 updateIds(views_, view_ids_);
476 if (views_.empty()) {
477 // quit in CloseEvent will not be triggert
482 map<int, GuiView*> const cmap = views_;
483 map<int, GuiView*>::const_iterator it;
484 for (it = cmap.begin(); it != cmap.end(); ++it) {
485 // TODO: return false when close event was ignored
486 // e.g. quitWriteAll()->'Cancel'
487 // maybe we need something like 'bool closeView()'
489 // unregisterd by the CloseEvent
498 GuiView & GuiApplication::view(int id) const
500 BOOST_ASSERT(views_.find(id) != views_.end());
501 return *views_.find(id)->second;
505 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
507 vector<int>::const_iterator it = view_ids_.begin();
508 vector<int>::const_iterator const end = view_ids_.end();
509 for (; it != end; ++it)
510 view(*it).hideDialog(name, inset);
514 Buffer const * GuiApplication::updateInset(Inset const * inset) const
516 Buffer const * buffer_ = 0;
517 vector<int>::const_iterator it = view_ids_.begin();
518 vector<int>::const_iterator const end = view_ids_.end();
519 for (; it != end; ++it) {
520 Buffer const * ptr = view(*it).updateInset(inset);
528 ////////////////////////////////////////////////////////////////////////
529 // X11 specific stuff goes here...
531 bool GuiApplication::x11EventFilter(XEvent * xev)
537 case SelectionRequest: {
538 if (xev->xselectionrequest.selection != XA_PRIMARY)
540 LYXERR(Debug::GUI, "X requested selection.");
541 BufferView * bv = current_view_->view();
543 docstring const sel = bv->requestSelection();
549 case SelectionClear: {
550 if (xev->xselectionclear.selection != XA_PRIMARY)
552 LYXERR(Debug::GUI, "Lost selection.");
553 BufferView * bv = current_view_->view();
555 bv->clearSelection();
563 } // namespace frontend
566 ////////////////////////////////////////////////////////////////////
570 ////////////////////////////////////////////////////////////////////
572 frontend::FontLoader & theFontLoader()
574 static frontend::NoGuiFontLoader no_gui_font_loader;
577 return no_gui_font_loader;
579 BOOST_ASSERT(frontend::guiApp);
580 return frontend::guiApp->fontLoader();
584 frontend::FontMetrics const & theFontMetrics(Font const & f)
586 return theFontMetrics(f.fontInfo());
590 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
592 static frontend::NoGuiFontMetrics no_gui_font_metrics;
595 return no_gui_font_metrics;
597 BOOST_ASSERT(frontend::guiApp);
598 return frontend::guiApp->fontLoader().metrics(f);
602 frontend::Clipboard & theClipboard()
604 BOOST_ASSERT(frontend::guiApp);
605 return frontend::guiApp->clipboard();
609 frontend::Selection & theSelection()
611 BOOST_ASSERT(frontend::guiApp);
612 return frontend::guiApp->selection();
617 #include "GuiApplication_moc.cpp"