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/FontLoader.h"
24 #include "frontends/FontMetrics.h"
27 #include "BufferList.h"
28 #include "BufferView.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
32 #include "support/gettext.h"
39 #include "support/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/FileName.h"
42 #include "support/ForkedCalls.h"
43 #include "support/lstrings.h"
44 #include "support/os.h"
45 #include "support/Package.h"
47 #include <QApplication>
50 #include <QFileOpenEvent>
52 #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 // all windows in a Mac application share the same menu bar.
174 QMenuBar *menuBar = new QMenuBar(0);
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());
204 general_timer_.setInterval(500);
205 connect(&general_timer_, SIGNAL(timeout()),
206 this, SLOT(handleRegularEvents()));
207 general_timer_.start();
211 GuiApplication::~GuiApplication()
213 socket_notifiers_.clear();
217 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
224 case LFUN_WINDOW_CLOSE:
225 enable = view_ids_.size() > 0;
229 if (!current_view_) {
242 bool GuiApplication::dispatch(FuncRequest const & cmd)
246 case LFUN_WINDOW_NEW:
247 createView(toqstr(cmd.argument()));
250 case LFUN_WINDOW_CLOSE:
251 // update bookmark pit of the current buffer before window close
252 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
253 theLyXFunc().gotoBookmark(i+1, false, false);
254 // ask the user for saving changes or cancel quit
255 if (!current_view_->quitWriteAll())
257 current_view_->close();
261 // quitting is triggered by the gui code
262 // (leaving the event loop).
263 current_view_->message(from_utf8(N_("Exiting.")));
264 if (current_view_->quitWriteAll())
268 case LFUN_SCREEN_FONT_UPDATE: {
269 // handle the screen font changes.
270 font_loader_.update();
271 // Backup current_view_
272 GuiView * view = current_view_;
273 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
274 // to skip the refresh.
276 BufferList::iterator it = theBufferList().begin();
277 BufferList::iterator const end = theBufferList().end();
278 for (; it != end; ++it)
280 // Restore current_view_
281 current_view_ = view;
286 // Notify the caller that the action has not been dispatched.
290 // The action has been dispatched.
295 void GuiApplication::resetGui()
297 map<int, GuiView *>::iterator it;
298 for (it = views_.begin(); it != views_.end(); ++it)
299 it->second->resetDialogs();
301 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
305 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
308 map<int, GuiView *>::const_iterator it;
309 for (it = stdmap.begin(); it != stdmap.end(); ++it)
310 ids.push_back(it->first);
314 void GuiApplication::createView(QString const & geometry_arg)
316 updateIds(views_, view_ids_);
318 while (views_.find(id) != views_.end())
320 views_[id] = new GuiView(id);
321 updateIds(views_, view_ids_);
323 GuiView * view = views_[id];
324 theLyXFunc().setLyXView(view);
327 if (!geometry_arg.isEmpty()) {
331 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
332 re.indexIn(geometry_arg);
333 w = re.cap(1).toInt();
334 h = re.cap(2).toInt();
335 x = re.cap(3).toInt();
336 y = re.cap(4).toInt();
337 view->setGeometry(x, y, w, h);
342 setCurrentView(*view);
348 Clipboard & GuiApplication::clipboard()
354 Selection & GuiApplication::selection()
360 int GuiApplication::exec()
362 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
363 return QApplication::exec();
367 void GuiApplication::exit(int status)
369 QApplication::exit(status);
373 void GuiApplication::execBatchCommands()
375 LyX::ref().execBatchCommands();
379 void GuiApplication::restoreGuiSession()
381 if (!lyxrc.load_session)
384 Session & session = LyX::ref().session();
385 vector<FileName> const & lastopened = session.lastOpened().getfiles();
386 // do not add to the lastfile list since these files are restored from
387 // last session, and should be already there (regular files), or should
388 // not be added at all (help files).
389 for_each(lastopened.begin(), lastopened.end(),
390 bind(&GuiView::loadDocument, current_view_, _1, false));
392 // clear this list to save a few bytes of RAM
393 session.lastOpened().clear();
397 QString const GuiApplication::romanFontName()
400 font.setKerning(false);
401 font.setStyleHint(QFont::Serif);
402 font.setFamily("serif");
404 return QFontInfo(font).family();
408 QString const GuiApplication::sansFontName()
411 font.setKerning(false);
412 font.setStyleHint(QFont::SansSerif);
413 font.setFamily("sans");
415 return QFontInfo(font).family();
419 QString const GuiApplication::typewriterFontName()
422 font.setKerning(false);
423 font.setStyleHint(QFont::TypeWriter);
424 font.setFamily("monospace");
426 return QFontInfo(font).family();
430 void GuiApplication::handleRegularEvents()
432 ForkedCallsController::handleCompletedProcesses();
436 bool GuiApplication::event(QEvent * e)
439 case QEvent::FileOpen: {
440 // Open a file; this happens only on Mac OS X for now
441 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
443 if (!current_view_ || !current_view_->view())
444 // The application is not properly initialized yet.
445 // So we acknowledge the event and delay the file opening
446 // until LyX is ready.
447 // FIXME UNICODE: FileName accept an utf8 encoded string.
448 LyX::ref().addFileToLoad(fromqstr(foe->file()));
450 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
451 qstring_to_ucs4(foe->file())));
457 return QApplication::event(e);
462 bool GuiApplication::notify(QObject * receiver, QEvent * event)
465 return QApplication::notify(receiver, event);
467 catch (ExceptionMessage const & e) {
468 if (e.type_ == ErrorException) {
469 Alert::error(e.title_, e.details_);
471 } else if (e.type_ == WarningException) {
472 Alert::warning(e.title_, e.details_);
476 catch (exception const & e) {
477 docstring s = _("LyX has caught an exception, it will now "
478 "attempt to save all unsaved documents and exit."
480 s += from_ascii(e.what());
481 Alert::error(_("Software exception Detected"), s);
485 docstring s = _("LyX has caught some really weird exception, it will "
486 "now attempt to save all unsaved documents and exit.");
487 Alert::error(_("Software exception Detected"), s);
495 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
497 QColor const & qcol = color_cache_.get(col);
498 if (!qcol.isValid()) {
504 rgbcol.r = qcol.red();
505 rgbcol.g = qcol.green();
506 rgbcol.b = qcol.blue();
511 string const GuiApplication::hexName(ColorCode col)
513 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
517 void GuiApplication::updateColor(ColorCode)
519 // FIXME: Bleh, can't we just clear them all at once ?
520 color_cache_.clear();
524 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
526 SocketNotifier * sn = new SocketNotifier(this, fd, func);
527 socket_notifiers_[fd] = sn;
528 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
532 void GuiApplication::socketDataReceived(int fd)
534 socket_notifiers_[fd]->func_();
538 void GuiApplication::unregisterSocketCallback(int fd)
540 socket_notifiers_.erase(fd);
544 void GuiApplication::commitData(QSessionManager & sm)
546 /// The implementation is required to avoid an application exit
547 /// when session state save is triggered by session manager.
548 /// The default implementation sends a close event to all
549 /// visible top level widgets when session managment allows
551 /// We are changing that to write all unsaved buffers...
552 if (sm.allowsInteraction() && !current_view_->quitWriteAll())
557 void GuiApplication::addMenuTranslator()
559 installTranslator(new MenuTranslator(this));
563 bool GuiApplication::unregisterView(int id)
565 updateIds(views_, view_ids_);
566 BOOST_ASSERT(views_.find(id) != views_.end());
567 BOOST_ASSERT(views_[id]);
569 map<int, GuiView *>::iterator it;
570 for (it = views_.begin(); it != views_.end(); ++it) {
571 if (it->first == id) {
576 updateIds(views_, view_ids_);
581 bool GuiApplication::closeAllViews()
583 updateIds(views_, view_ids_);
584 if (views_.empty()) {
585 // quit in CloseEvent will not be triggert
590 map<int, GuiView*> const cmap = views_;
591 map<int, GuiView*>::const_iterator it;
592 for (it = cmap.begin(); it != cmap.end(); ++it) {
593 // TODO: return false when close event was ignored
594 // e.g. quitWriteAll()->'Cancel'
595 // maybe we need something like 'bool closeView()'
597 // unregisterd by the CloseEvent
606 GuiView & GuiApplication::view(int id) const
608 BOOST_ASSERT(views_.find(id) != views_.end());
609 return *views_.find(id)->second;
613 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
615 vector<int>::const_iterator it = view_ids_.begin();
616 vector<int>::const_iterator const end = view_ids_.end();
617 for (; it != end; ++it)
618 view(*it).hideDialog(name, inset);
622 Buffer const * GuiApplication::updateInset(Inset const * inset) const
624 Buffer const * buffer_ = 0;
625 vector<int>::const_iterator it = view_ids_.begin();
626 vector<int>::const_iterator const end = view_ids_.end();
627 for (; it != end; ++it) {
628 Buffer const * ptr = view(*it).updateInset(inset);
636 ////////////////////////////////////////////////////////////////////////
637 // X11 specific stuff goes here...
639 bool GuiApplication::x11EventFilter(XEvent * xev)
645 case SelectionRequest: {
646 if (xev->xselectionrequest.selection != XA_PRIMARY)
648 LYXERR(Debug::GUI, "X requested selection.");
649 BufferView * bv = current_view_->view();
651 docstring const sel = bv->requestSelection();
657 case SelectionClear: {
658 if (xev->xselectionclear.selection != XA_PRIMARY)
660 LYXERR(Debug::GUI, "Lost selection.");
661 BufferView * bv = current_view_->view();
663 bv->clearSelection();
671 } // namespace frontend
674 ////////////////////////////////////////////////////////////////////
678 ////////////////////////////////////////////////////////////////////
680 frontend::FontLoader & theFontLoader()
682 BOOST_ASSERT(frontend::guiApp);
683 return frontend::guiApp->fontLoader();
687 frontend::FontMetrics const & theFontMetrics(Font const & f)
689 return theFontMetrics(f.fontInfo());
693 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
695 BOOST_ASSERT(frontend::guiApp);
696 return frontend::guiApp->fontLoader().metrics(f);
700 frontend::Clipboard & theClipboard()
702 BOOST_ASSERT(frontend::guiApp);
703 return frontend::guiApp->clipboard();
707 frontend::Selection & theSelection()
709 BOOST_ASSERT(frontend::guiApp);
710 return frontend::guiApp->selection();
715 #include "GuiApplication_moc.cpp"