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"
19 #include "GuiKeySymbol.h"
22 #include "frontends/alert.h"
23 #include "frontends/Application.h"
24 #include "frontends/FontLoader.h"
25 #include "frontends/FontMetrics.h"
28 #include "BufferList.h"
29 #include "BufferView.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
39 #include "support/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/FileName.h"
42 #include "support/ForkedCalls.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45 #include "support/os.h"
46 #include "support/Package.h"
48 #include <QApplication>
51 #include <QFileOpenEvent>
53 #include <QLibraryInfo>
55 #include <QPixmapCache>
57 #include <QSessionManager>
58 #include <QSocketNotifier>
61 #include <QTranslator>
65 #include <X11/Xatom.h>
71 #include <boost/bind.hpp>
76 using namespace lyx::support;
80 frontend::Application * createApplication(int & argc, char * argv[])
82 return new frontend::GuiApplication(argc, argv);
88 class SocketNotifier : public QSocketNotifier
91 /// connect a connection notification from the LyXServerSocket
92 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
93 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
97 /// The callback function
98 Application::SocketCallback func_;
102 ////////////////////////////////////////////////////////////////////////
103 // Mac specific stuff goes here...
105 class MenuTranslator : public QTranslator
108 MenuTranslator(QObject * parent)
109 : QTranslator(parent)
112 QString translate(const char * /*context*/,
113 const char * sourceText,
114 const char * /*comment*/ = 0)
116 string const s = sourceText;
117 if (s == N_("About %1") || s == N_("Preferences")
118 || s == N_("Reconfigure") || s == N_("Quit %1"))
125 class GlobalMenuBar : public QMenuBar
129 GlobalMenuBar() : QMenuBar(0) {}
132 bool event(QEvent * e)
134 if (e->type() == QEvent::ShortcutOverride) {
135 // && activeWindow() == 0) {
136 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
138 setKeySymbol(&sym, ke);
139 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
147 ///////////////////////////////////////////////////////////////
148 // You can find more platform specific stuff
149 // at the end of this file...
150 ///////////////////////////////////////////////////////////////
153 GuiApplication * guiApp;
156 GuiApplication::GuiApplication(int & argc, char ** argv)
157 : QApplication(argc, argv), Application(), current_view_(0), global_menubar_(0)
159 QString app_name = "LyX";
160 QCoreApplication::setOrganizationName(app_name);
161 QCoreApplication::setOrganizationDomain("lyx.org");
162 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
164 // FIXME: quitOnLastWindowClosed is true by default. We should have a
165 // lyxrc setting for this in order to let the application stay resident.
166 // But then we need some kind of dock icon, at least on Windows.
168 if (lyxrc.quit_on_last_window_closed)
169 setQuitOnLastWindowClosed(false);
172 setQuitOnLastWindowClosed(false);
176 // doubleClickInterval() is 400 ms on X11 which is just too long.
177 // On Windows and Mac OS X, the operating system's value is used.
178 // On Microsoft Windows, calling this function sets the double
179 // click interval for all applications. So we don't!
180 QApplication::setDoubleClickInterval(300);
183 // install translation file for Qt built-in dialogs
184 QString language_name = QString("qt_") + QLocale::system().name();
186 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
187 // Short-named translator can be loaded from a long name, but not the
188 // opposite. Therefore, long name should be used without truncation.
189 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
190 if (qt_trans_.load(language_name,
191 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
193 installTranslator(&qt_trans_);
194 // even if the language calls for RtL, don't do that
195 setLayoutDirection(Qt::LeftToRight);
196 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
197 << fromqstr(language_name));
199 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
200 << fromqstr(language_name));
203 // This allows to translate the strings that appear in the LyX menu.
206 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
208 using namespace lyx::graphics;
210 Image::newImage = boost::bind(&GuiImage::newImage);
211 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
213 // needs to be done before reading lyxrc
215 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
219 // Set the cache to 5120 kilobytes which corresponds to screen size of
220 // 1280 by 1024 pixels with a color depth of 32 bits.
221 QPixmapCache::setCacheLimit(5120);
223 // Initialize RC Fonts
224 if (lyxrc.roman_font_name.empty())
225 lyxrc.roman_font_name = fromqstr(romanFontName());
227 if (lyxrc.sans_font_name.empty())
228 lyxrc.sans_font_name = fromqstr(sansFontName());
230 if (lyxrc.typewriter_font_name.empty())
231 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
233 general_timer_.setInterval(500);
234 connect(&general_timer_, SIGNAL(timeout()),
235 this, SLOT(handleRegularEvents()));
236 general_timer_.start();
239 if (global_menubar_ == 0) {
240 // Create the global default menubar which is shown for the dialogs
241 // and if no GuiView is visible.
242 global_menubar_ = new GlobalMenuBar();
248 GuiApplication::~GuiApplication()
250 socket_notifiers_.clear();
254 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
261 case LFUN_WINDOW_CLOSE:
262 enable = view_ids_.size() > 0;
266 if (!current_view_) {
279 bool GuiApplication::dispatch(FuncRequest const & cmd)
283 case LFUN_WINDOW_NEW:
284 createView(toqstr(cmd.argument()));
287 case LFUN_WINDOW_CLOSE:
288 // update bookmark pit of the current buffer before window close
289 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
290 theLyXFunc().gotoBookmark(i+1, false, false);
291 current_view_->close();
295 // quitting is triggered by the gui code
296 // (leaving the event loop).
297 current_view_->message(from_utf8(N_("Exiting.")));
302 case LFUN_SCREEN_FONT_UPDATE: {
303 // handle the screen font changes.
304 font_loader_.update();
305 // Backup current_view_
306 GuiView * view = current_view_;
307 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
308 // to skip the refresh.
310 BufferList::iterator it = theBufferList().begin();
311 BufferList::iterator const end = theBufferList().end();
312 for (; it != end; ++it)
314 // Restore current_view_
315 current_view_ = view;
319 case LFUN_BUFFER_NEW:
321 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0))
323 current_view_->newDocument(to_utf8(cmd.argument()), false);
326 case LFUN_BUFFER_NEW_TEMPLATE:
328 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
330 current_view_->newDocument(to_utf8(cmd.argument()), true);
331 if (!current_view_->buffer())
332 current_view_->close();
334 current_view_->newDocument(to_utf8(cmd.argument()), true);
339 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
341 current_view_->openDocument(to_utf8(cmd.argument()));
342 if (!current_view_->buffer())
343 current_view_->close();
345 current_view_->openDocument(to_utf8(cmd.argument()));
349 // Notify the caller that the action has not been dispatched.
353 // The action has been dispatched.
358 void GuiApplication::resetGui()
360 map<int, GuiView *>::iterator it;
361 for (it = views_.begin(); it != views_.end(); ++it)
362 it->second->resetDialogs();
364 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
368 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
371 map<int, GuiView *>::const_iterator it;
372 for (it = stdmap.begin(); it != stdmap.end(); ++it)
373 ids.push_back(it->first);
377 void GuiApplication::createView(QString const & geometry_arg)
380 global_menubar_->releaseKeyboard();
383 updateIds(views_, view_ids_);
385 while (views_.find(id) != views_.end())
387 GuiView * view = new GuiView(id);
389 // copy the icon size from old view
391 view->setIconSize(current_view_->iconSize());
395 updateIds(views_, view_ids_);
397 theLyXFunc().setLyXView(view);
399 if (!geometry_arg.isEmpty()) {
403 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
404 re.indexIn(geometry_arg);
405 w = re.cap(1).toInt();
406 h = re.cap(2).toInt();
407 x = re.cap(3).toInt();
408 y = re.cap(4).toInt();
409 view->setGeometry(x, y, w, h);
413 setActiveWindow(view);
414 setCurrentView(*view);
420 Clipboard & GuiApplication::clipboard()
426 Selection & GuiApplication::selection()
432 int GuiApplication::exec()
434 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
435 return QApplication::exec();
439 void GuiApplication::exit(int status)
441 QApplication::exit(status);
445 void GuiApplication::execBatchCommands()
447 LyX::ref().execBatchCommands();
451 void GuiApplication::restoreGuiSession()
453 if (!lyxrc.load_session)
456 Session & session = LyX::ref().session();
457 vector<FileName> const & lastopened = session.lastOpened().getfiles();
458 // do not add to the lastfile list since these files are restored from
459 // last session, and should be already there (regular files), or should
460 // not be added at all (help files).
461 for_each(lastopened.begin(), lastopened.end(),
462 bind(&GuiView::loadDocument, current_view_, _1, false));
464 // clear this list to save a few bytes of RAM
465 session.lastOpened().clear();
469 QString const GuiApplication::romanFontName()
472 font.setKerning(false);
473 font.setStyleHint(QFont::Serif);
474 font.setFamily("serif");
476 return QFontInfo(font).family();
480 QString const GuiApplication::sansFontName()
483 font.setKerning(false);
484 font.setStyleHint(QFont::SansSerif);
485 font.setFamily("sans");
487 return QFontInfo(font).family();
491 QString const GuiApplication::typewriterFontName()
494 font.setKerning(false);
495 font.setStyleHint(QFont::TypeWriter);
496 font.setFamily("monospace");
498 return QFontInfo(font).family();
502 void GuiApplication::handleRegularEvents()
504 ForkedCallsController::handleCompletedProcesses();
508 bool GuiApplication::event(QEvent * e)
511 case QEvent::FileOpen: {
512 // Open a file; this happens only on Mac OS X for now
513 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
515 if (!current_view_ || !current_view_->view())
516 // The application is not properly initialized yet.
517 // So we acknowledge the event and delay the file opening
518 // until LyX is ready.
519 // FIXME UNICODE: FileName accept an utf8 encoded string.
520 LyX::ref().addFileToLoad(fromqstr(foe->file()));
522 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
523 qstring_to_ucs4(foe->file())));
529 return QApplication::event(e);
534 bool GuiApplication::notify(QObject * receiver, QEvent * event)
537 return QApplication::notify(receiver, event);
539 catch (ExceptionMessage const & e) {
542 LyX::cref().emergencyCleanup();
543 setQuitOnLastWindowClosed(false);
545 Alert::error(e.title_, e.details_);
547 // Properly crash in debug mode in order to get a useful backtrace.
550 // In release mode, try to exit gracefully.
553 case BufferException: {
554 Buffer * buf = current_view_->buffer();
555 docstring details = e.details_ + '\n';
556 details += theBufferList().emergencyWrite(buf);
557 theBufferList().release(buf);
558 details += _("\nThe current document was closed.");
559 Alert::error(e.title_, details);
562 case WarningException:
563 Alert::warning(e.title_, e.details_);
567 catch (exception const & e) {
568 docstring s = _("LyX has caught an exception, it will now "
569 "attempt to save all unsaved documents and exit."
571 s += from_ascii(e.what());
572 Alert::error(_("Software exception Detected"), s);
576 docstring s = _("LyX has caught some really weird exception, it will "
577 "now attempt to save all unsaved documents and exit.");
578 Alert::error(_("Software exception Detected"), s);
586 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
588 QColor const & qcol = color_cache_.get(col);
589 if (!qcol.isValid()) {
595 rgbcol.r = qcol.red();
596 rgbcol.g = qcol.green();
597 rgbcol.b = qcol.blue();
602 string const GuiApplication::hexName(ColorCode col)
604 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
608 void GuiApplication::updateColor(ColorCode)
610 // FIXME: Bleh, can't we just clear them all at once ?
611 color_cache_.clear();
615 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
617 SocketNotifier * sn = new SocketNotifier(this, fd, func);
618 socket_notifiers_[fd] = sn;
619 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
623 void GuiApplication::socketDataReceived(int fd)
625 socket_notifiers_[fd]->func_();
629 void GuiApplication::unregisterSocketCallback(int fd)
631 socket_notifiers_.erase(fd);
635 void GuiApplication::commitData(QSessionManager & sm)
637 /// The implementation is required to avoid an application exit
638 /// when session state save is triggered by session manager.
639 /// The default implementation sends a close event to all
640 /// visible top level widgets when session managment allows
642 /// We are changing that to close all wiew one by one.
643 /// FIXME: verify if the default implementation is enough now.
644 if (sm.allowsInteraction() && !closeAllViews())
649 void GuiApplication::addMenuTranslator()
651 installTranslator(new MenuTranslator(this));
655 bool GuiApplication::unregisterView(int id)
657 updateIds(views_, view_ids_);
658 BOOST_ASSERT(views_.find(id) != views_.end());
659 BOOST_ASSERT(views_[id]);
661 map<int, GuiView *>::iterator it;
662 for (it = views_.begin(); it != views_.end(); ++it) {
663 if (it->first == id) {
668 updateIds(views_, view_ids_);
673 bool GuiApplication::closeAllViews()
675 updateIds(views_, view_ids_);
679 map<int, GuiView*> const cmap = views_;
680 map<int, GuiView*>::const_iterator it;
681 for (it = cmap.begin(); it != cmap.end(); ++it) {
682 if (!it->second->close())
692 GuiView & GuiApplication::view(int id) const
694 BOOST_ASSERT(views_.find(id) != views_.end());
695 return *views_.find(id)->second;
699 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
701 vector<int>::const_iterator it = view_ids_.begin();
702 vector<int>::const_iterator const end = view_ids_.end();
703 for (; it != end; ++it)
704 view(*it).hideDialog(name, inset);
708 Buffer const * GuiApplication::updateInset(Inset const * inset) const
710 Buffer const * buffer_ = 0;
711 vector<int>::const_iterator it = view_ids_.begin();
712 vector<int>::const_iterator const end = view_ids_.end();
713 for (; it != end; ++it) {
714 Buffer const * ptr = view(*it).updateInset(inset);
722 void GuiApplication::readMenus(Lexer & lex)
728 bool GuiApplication::searchMenu(FuncRequest const & func,
729 vector<docstring> & names) const
731 return menus().searchMenu(func, names);
735 void GuiApplication::initGlobalMenu()
738 menus().fillMenuBar(global_menubar_, 0);
742 void GuiApplication::onLastWindowClosed()
745 global_menubar_->grabKeyboard();
748 ////////////////////////////////////////////////////////////////////////
749 // X11 specific stuff goes here...
751 bool GuiApplication::x11EventFilter(XEvent * xev)
757 case SelectionRequest: {
758 if (xev->xselectionrequest.selection != XA_PRIMARY)
760 LYXERR(Debug::GUI, "X requested selection.");
761 BufferView * bv = current_view_->view();
763 docstring const sel = bv->requestSelection();
769 case SelectionClear: {
770 if (xev->xselectionclear.selection != XA_PRIMARY)
772 LYXERR(Debug::GUI, "Lost selection.");
773 BufferView * bv = current_view_->view();
775 bv->clearSelection();
783 } // namespace frontend
786 ////////////////////////////////////////////////////////////////////
790 ////////////////////////////////////////////////////////////////////
792 frontend::FontLoader & theFontLoader()
794 BOOST_ASSERT(frontend::guiApp);
795 return frontend::guiApp->fontLoader();
799 frontend::FontMetrics const & theFontMetrics(Font const & f)
801 return theFontMetrics(f.fontInfo());
805 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
807 BOOST_ASSERT(frontend::guiApp);
808 return frontend::guiApp->fontLoader().metrics(f);
812 frontend::Clipboard & theClipboard()
814 BOOST_ASSERT(frontend::guiApp);
815 return frontend::guiApp->clipboard();
819 frontend::Selection & theSelection()
821 BOOST_ASSERT(frontend::guiApp);
822 return frontend::guiApp->selection();
827 #include "GuiApplication_moc.cpp"