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"
35 #include "BufferList.h"
36 #include "BufferView.h"
37 #include "support/debug.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "support/gettext.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>
75 using namespace lyx::support;
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 GuiApplication * guiApp;
134 GuiApplication::GuiApplication(int & argc, char ** argv)
135 : QApplication(argc, argv), Application(), current_view_(0)
137 QString app_name = "LyX";
138 QCoreApplication::setOrganizationName(app_name);
139 QCoreApplication::setOrganizationDomain("lyx.org");
140 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
142 // Qt bug? setQuitOnLastWindowClosed(true); does not work
143 setQuitOnLastWindowClosed(false);
146 // doubleClickInterval() is 400 ms on X11 which is just too long.
147 // On Windows and Mac OS X, the operating system's value is used.
148 // On Microsoft Windows, calling this function sets the double
149 // click interval for all applications. So we don't!
150 QApplication::setDoubleClickInterval(300);
153 // install translation file for Qt built-in dialogs
154 QString language_name = QString("qt_") + QLocale::system().name();
156 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
157 // Short-named translator can be loaded from a long name, but not the
158 // opposite. Therefore, long name should be used without truncation.
159 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
160 if (qt_trans_.load(language_name,
161 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
163 installTranslator(&qt_trans_);
164 // even if the language calls for RtL, don't do that
165 setLayoutDirection(Qt::LeftToRight);
166 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
167 << fromqstr(language_name));
169 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
170 << fromqstr(language_name));
173 // This allows to translate the strings that appear in the LyX menu.
177 using namespace lyx::graphics;
179 Image::newImage = boost::bind(&GuiImage::newImage);
180 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
182 // needs to be done before reading lyxrc
184 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
188 // Set the cache to 5120 kilobytes which corresponds to screen size of
189 // 1280 by 1024 pixels with a color depth of 32 bits.
190 QPixmapCache::setCacheLimit(5120);
192 // Initialize RC Fonts
193 if (lyxrc.roman_font_name.empty())
194 lyxrc.roman_font_name = fromqstr(romanFontName());
196 if (lyxrc.sans_font_name.empty())
197 lyxrc.sans_font_name = fromqstr(sansFontName());
199 if (lyxrc.typewriter_font_name.empty())
200 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
204 GuiApplication::~GuiApplication()
206 socket_notifiers_.clear();
210 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
217 case LFUN_WINDOW_CLOSE:
218 enable = view_ids_.size() > 0;
222 if (!current_view_) {
235 bool GuiApplication::dispatch(FuncRequest const & cmd)
239 case LFUN_WINDOW_NEW:
240 createView(toqstr(cmd.argument()));
243 case LFUN_WINDOW_CLOSE:
244 // update bookmark pit of the current buffer before window close
245 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
246 theLyXFunc().gotoBookmark(i+1, false, false);
247 // ask the user for saving changes or cancel quit
248 if (!current_view_->quitWriteAll())
250 current_view_->close();
254 // quitting is triggered by the gui code
255 // (leaving the event loop).
256 current_view_->message(from_utf8(N_("Exiting.")));
257 if (current_view_->quitWriteAll())
261 case LFUN_SCREEN_FONT_UPDATE: {
262 // handle the screen font changes.
263 font_loader_.update();
264 // Backup current_view_
265 GuiView * view = current_view_;
266 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
267 // to skip the refresh.
269 BufferList::iterator it = theBufferList().begin();
270 BufferList::iterator const end = theBufferList().end();
271 for (; it != end; ++it)
273 // Restore current_view_
274 current_view_ = view;
279 // Notify the caller that the action has not been dispatched.
283 // The action has been dispatched.
288 void GuiApplication::resetGui()
290 map<int, GuiView *>::iterator it;
291 for (it = views_.begin(); it != views_.end(); ++it)
292 it->second->resetDialogs();
294 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
298 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
301 map<int, GuiView *>::const_iterator it;
302 for (it = stdmap.begin(); it != stdmap.end(); ++it)
303 ids.push_back(it->first);
307 void GuiApplication::createView(QString const & geometry_arg)
309 updateIds(views_, view_ids_);
311 while (views_.find(id) != views_.end())
313 views_[id] = new GuiView(id);
314 updateIds(views_, view_ids_);
316 GuiView * view = views_[id];
317 theLyXFunc().setLyXView(view);
320 if (!geometry_arg.isEmpty()) {
324 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
325 re.indexIn(geometry_arg);
326 w = re.cap(1).toInt();
327 h = re.cap(2).toInt();
328 x = re.cap(3).toInt();
329 y = re.cap(4).toInt();
330 view->setGeometry(x, y, w, h);
335 setCurrentView(*view);
341 Clipboard & GuiApplication::clipboard()
347 Selection & GuiApplication::selection()
353 int GuiApplication::exec()
355 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
356 return QApplication::exec();
360 void GuiApplication::exit(int status)
362 QApplication::exit(status);
366 void GuiApplication::execBatchCommands()
368 LyX::ref().execBatchCommands();
372 QString const GuiApplication::romanFontName()
375 font.setKerning(false);
376 font.setStyleHint(QFont::Serif);
377 font.setFamily("serif");
379 return QFontInfo(font).family();
383 QString const GuiApplication::sansFontName()
386 font.setKerning(false);
387 font.setStyleHint(QFont::SansSerif);
388 font.setFamily("sans");
390 return QFontInfo(font).family();
394 QString const GuiApplication::typewriterFontName()
397 font.setKerning(false);
398 font.setStyleHint(QFont::TypeWriter);
399 font.setFamily("monospace");
401 return QFontInfo(font).family();
405 bool GuiApplication::event(QEvent * e)
408 case QEvent::FileOpen: {
409 // Open a file; this happens only on Mac OS X for now
410 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
412 if (!current_view_ || !current_view_->view())
413 // The application is not properly initialized yet.
414 // So we acknowledge the event and delay the file opening
415 // until LyX is ready.
416 // FIXME UNICODE: FileName accept an utf8 encoded string.
417 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
419 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
420 qstring_to_ucs4(foe->file())));
426 return QApplication::event(e);
431 bool GuiApplication::notify(QObject * receiver, QEvent * event)
434 return QApplication::notify(receiver, event);
436 catch (ExceptionMessage const & e) {
437 if (e.type_ == ErrorException) {
438 Alert::error(e.title_, e.details_);
440 } else if (e.type_ == WarningException) {
441 Alert::warning(e.title_, e.details_);
445 catch (exception const & e) {
446 docstring s = _("LyX has caught an exception, it will now "
447 "attempt to save all unsaved documents and exit."
449 s += from_ascii(e.what());
450 Alert::error(_("Software exception Detected"), s);
454 docstring s = _("LyX has caught some really weird exception, it will "
455 "now attempt to save all unsaved documents and exit.");
456 Alert::error(_("Software exception Detected"), s);
464 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
466 QColor const & qcol = color_cache_.get(col);
467 if (!qcol.isValid()) {
473 rgbcol.r = qcol.red();
474 rgbcol.g = qcol.green();
475 rgbcol.b = qcol.blue();
480 string const GuiApplication::hexName(ColorCode col)
482 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
486 void GuiApplication::updateColor(ColorCode)
488 // FIXME: Bleh, can't we just clear them all at once ?
489 color_cache_.clear();
493 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
495 SocketNotifier * sn = new SocketNotifier(this, fd, func);
496 socket_notifiers_[fd] = sn;
497 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
501 void GuiApplication::socketDataReceived(int fd)
503 socket_notifiers_[fd]->func_();
507 void GuiApplication::unregisterSocketCallback(int fd)
509 socket_notifiers_.erase(fd);
513 void GuiApplication::commitData(QSessionManager & sm)
515 /// The implementation is required to avoid an application exit
516 /// when session state save is triggered by session manager.
517 /// The default implementation sends a close event to all
518 /// visible top level widgets when session managment allows
520 /// We are changing that to write all unsaved buffers...
521 if (sm.allowsInteraction() && !current_view_->quitWriteAll())
526 void GuiApplication::addMenuTranslator()
528 installTranslator(new MenuTranslator(this));
532 bool GuiApplication::unregisterView(int id)
534 updateIds(views_, view_ids_);
535 BOOST_ASSERT(views_.find(id) != views_.end());
536 BOOST_ASSERT(views_[id]);
538 map<int, GuiView *>::iterator it;
539 for (it = views_.begin(); it != views_.end(); ++it) {
540 if (it->first == id) {
545 updateIds(views_, view_ids_);
550 bool GuiApplication::closeAllViews()
552 updateIds(views_, view_ids_);
553 if (views_.empty()) {
554 // quit in CloseEvent will not be triggert
559 map<int, GuiView*> const cmap = views_;
560 map<int, GuiView*>::const_iterator it;
561 for (it = cmap.begin(); it != cmap.end(); ++it) {
562 // TODO: return false when close event was ignored
563 // e.g. quitWriteAll()->'Cancel'
564 // maybe we need something like 'bool closeView()'
566 // unregisterd by the CloseEvent
575 GuiView & GuiApplication::view(int id) const
577 BOOST_ASSERT(views_.find(id) != views_.end());
578 return *views_.find(id)->second;
582 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
584 vector<int>::const_iterator it = view_ids_.begin();
585 vector<int>::const_iterator const end = view_ids_.end();
586 for (; it != end; ++it)
587 view(*it).hideDialog(name, inset);
591 Buffer const * GuiApplication::updateInset(Inset const * inset) const
593 Buffer const * buffer_ = 0;
594 vector<int>::const_iterator it = view_ids_.begin();
595 vector<int>::const_iterator const end = view_ids_.end();
596 for (; it != end; ++it) {
597 Buffer const * ptr = view(*it).updateInset(inset);
605 ////////////////////////////////////////////////////////////////////////
606 // X11 specific stuff goes here...
608 bool GuiApplication::x11EventFilter(XEvent * xev)
614 case SelectionRequest: {
615 if (xev->xselectionrequest.selection != XA_PRIMARY)
617 LYXERR(Debug::GUI, "X requested selection.");
618 BufferView * bv = current_view_->view();
620 docstring const sel = bv->requestSelection();
626 case SelectionClear: {
627 if (xev->xselectionclear.selection != XA_PRIMARY)
629 LYXERR(Debug::GUI, "Lost selection.");
630 BufferView * bv = current_view_->view();
632 bv->clearSelection();
640 } // namespace frontend
643 ////////////////////////////////////////////////////////////////////
647 ////////////////////////////////////////////////////////////////////
649 frontend::FontLoader & theFontLoader()
651 static frontend::NoGuiFontLoader no_gui_font_loader;
654 return no_gui_font_loader;
656 BOOST_ASSERT(frontend::guiApp);
657 return frontend::guiApp->fontLoader();
661 frontend::FontMetrics const & theFontMetrics(Font const & f)
663 return theFontMetrics(f.fontInfo());
667 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
669 static frontend::NoGuiFontMetrics no_gui_font_metrics;
672 return no_gui_font_metrics;
674 BOOST_ASSERT(frontend::guiApp);
675 return frontend::guiApp->fontLoader().metrics(f);
679 frontend::Clipboard & theClipboard()
681 BOOST_ASSERT(frontend::guiApp);
682 return frontend::guiApp->clipboard();
686 frontend::Selection & theSelection()
688 BOOST_ASSERT(frontend::guiApp);
689 return frontend::guiApp->selection();
694 #include "GuiApplication_moc.cpp"