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"
40 #include "support/lassert.h"
41 #include "support/debug.h"
42 #include "support/ExceptionMessage.h"
43 #include "support/FileName.h"
44 #include "support/ForkedCalls.h"
45 #include "support/gettext.h"
46 #include "support/lstrings.h"
47 #include "support/os.h"
48 #include "support/Package.h"
52 #include <QFileOpenEvent>
54 #include <QLibraryInfo>
56 #include <QPixmapCache>
58 #include <QSessionManager>
59 #include <QSocketNotifier>
60 #include <QSortFilterProxyModel>
61 #include <QStandardItemModel>
64 #include <QTranslator>
68 #include <X11/Xatom.h>
74 #include <boost/bind.hpp>
79 using namespace lyx::support;
83 frontend::Application * createApplication(int & argc, char * argv[])
85 return new frontend::GuiApplication(argc, argv);
91 class SocketNotifier : public QSocketNotifier
94 /// connect a connection notification from the LyXServerSocket
95 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
96 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
100 /// The callback function
101 Application::SocketCallback func_;
105 ////////////////////////////////////////////////////////////////////////
106 // Mac specific stuff goes here...
108 class MenuTranslator : public QTranslator
111 MenuTranslator(QObject * parent)
112 : QTranslator(parent)
115 QString translate(const char * /*context*/,
116 const char * sourceText,
117 const char * /*comment*/ = 0)
119 string const s = sourceText;
120 if (s == N_("About %1") || s == N_("Preferences")
121 || s == N_("Reconfigure") || s == N_("Quit %1"))
128 class GlobalMenuBar : public QMenuBar
132 GlobalMenuBar() : QMenuBar(0) {}
135 bool event(QEvent * e)
137 if (e->type() == QEvent::ShortcutOverride) {
138 // && activeWindow() == 0) {
139 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
141 setKeySymbol(&sym, ke);
142 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
150 ///////////////////////////////////////////////////////////////
151 // You can find more platform specific stuff
152 // at the end of this file...
153 ///////////////////////////////////////////////////////////////
156 GuiApplication * guiApp;
159 GuiApplication::GuiApplication(int & argc, char ** argv)
160 : QApplication(argc, argv), Application(), current_view_(0),
161 global_menubar_(0), language_model_(0)
163 QString app_name = "LyX";
164 QCoreApplication::setOrganizationName(app_name);
165 QCoreApplication::setOrganizationDomain("lyx.org");
166 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
168 // FIXME: quitOnLastWindowClosed is true by default. We should have a
169 // lyxrc setting for this in order to let the application stay resident.
170 // But then we need some kind of dock icon, at least on Windows.
172 if (lyxrc.quit_on_last_window_closed)
173 setQuitOnLastWindowClosed(false);
176 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
177 // seems to be the default case for applications like LyX.
178 setQuitOnLastWindowClosed(false);
182 // doubleClickInterval() is 400 ms on X11 which is just too long.
183 // On Windows and Mac OS X, the operating system's value is used.
184 // On Microsoft Windows, calling this function sets the double
185 // click interval for all applications. So we don't!
186 QApplication::setDoubleClickInterval(300);
189 // install translation file for Qt built-in dialogs
190 QString language_name = QString("qt_") + QLocale::system().name();
192 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
193 // Short-named translator can be loaded from a long name, but not the
194 // opposite. Therefore, long name should be used without truncation.
195 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
196 if (qt_trans_.load(language_name,
197 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
199 installTranslator(&qt_trans_);
200 // even if the language calls for RtL, don't do that
201 setLayoutDirection(Qt::LeftToRight);
202 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
205 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
209 // This allows to translate the strings that appear in the LyX menu.
212 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
214 using namespace lyx::graphics;
216 Image::newImage = boost::bind(&GuiImage::newImage);
217 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
219 // needs to be done before reading lyxrc
221 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
225 // Set the cache to 5120 kilobytes which corresponds to screen size of
226 // 1280 by 1024 pixels with a color depth of 32 bits.
227 QPixmapCache::setCacheLimit(5120);
229 // Initialize RC Fonts
230 if (lyxrc.roman_font_name.empty())
231 lyxrc.roman_font_name = fromqstr(romanFontName());
233 if (lyxrc.sans_font_name.empty())
234 lyxrc.sans_font_name = fromqstr(sansFontName());
236 if (lyxrc.typewriter_font_name.empty())
237 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
239 general_timer_.setInterval(500);
240 connect(&general_timer_, SIGNAL(timeout()),
241 this, SLOT(handleRegularEvents()));
242 general_timer_.start();
246 if (global_menubar_ == 0) {
247 // Create the global default menubar which is shown for the dialogs
248 // and if no GuiView is visible.
249 global_menubar_ = new GlobalMenuBar();
255 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
262 case LFUN_WINDOW_CLOSE:
263 enable = view_ids_.size() > 0;
267 if (!current_view_) {
280 bool GuiApplication::dispatch(FuncRequest const & cmd)
284 case LFUN_WINDOW_NEW:
285 createView(toqstr(cmd.argument()));
288 case LFUN_WINDOW_CLOSE:
289 // update bookmark pit of the current buffer before window close
290 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
291 theLyXFunc().gotoBookmark(i+1, false, false);
292 current_view_->close();
296 // quitting is triggered by the gui code
297 // (leaving the event loop).
299 current_view_->message(from_utf8(N_("Exiting.")));
304 case LFUN_SCREEN_FONT_UPDATE: {
305 // handle the screen font changes.
306 font_loader_.update();
307 // Backup current_view_
308 GuiView * view = current_view_;
309 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
310 // to skip the refresh.
312 BufferList::iterator it = theBufferList().begin();
313 BufferList::iterator const end = theBufferList().end();
314 for (; it != end; ++it)
316 // Restore current_view_
317 current_view_ = view;
321 case LFUN_BUFFER_NEW:
323 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
324 createView(QString(), false); // keep hidden
325 current_view_->newDocument(to_utf8(cmd.argument()), false);
326 current_view_->show();
327 setActiveWindow(current_view_);
329 current_view_->newDocument(to_utf8(cmd.argument()), false);
332 case LFUN_BUFFER_NEW_TEMPLATE:
334 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
336 current_view_->newDocument(to_utf8(cmd.argument()), true);
337 if (!current_view_->buffer())
338 current_view_->close();
340 current_view_->newDocument(to_utf8(cmd.argument()), true);
345 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
347 current_view_->openDocument(to_utf8(cmd.argument()));
348 if (!current_view_->buffer())
349 current_view_->close();
351 current_view_->openDocument(to_utf8(cmd.argument()));
355 // Notify the caller that the action has not been dispatched.
359 // The action has been dispatched.
364 void GuiApplication::resetGui()
366 map<int, GuiView *>::iterator it;
367 for (it = views_.begin(); it != views_.end(); ++it)
368 it->second->resetDialogs();
370 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
374 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
377 map<int, GuiView *>::const_iterator it;
378 for (it = stdmap.begin(); it != stdmap.end(); ++it)
379 ids.push_back(it->first);
383 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
385 // release the keyboard which might have been grabed by the global
386 // menubar on Mac to catch shortcuts even without any GuiView.
388 global_menubar_->releaseKeyboard();
391 updateIds(views_, view_ids_);
393 while (views_.find(id) != views_.end())
395 GuiView * view = new GuiView(id);
397 // copy the icon size from old view
399 view->setIconSize(current_view_->iconSize());
403 updateIds(views_, view_ids_);
407 setActiveWindow(view);
410 if (!geometry_arg.isEmpty()) {
414 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
415 re.indexIn(geometry_arg);
416 w = re.cap(1).toInt();
417 h = re.cap(2).toInt();
418 x = re.cap(3).toInt();
419 y = re.cap(4).toInt();
420 view->setGeometry(x, y, w, h);
424 setCurrentView(view);
430 Clipboard & GuiApplication::clipboard()
436 Selection & GuiApplication::selection()
442 int GuiApplication::exec()
444 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
445 return QApplication::exec();
449 void GuiApplication::exit(int status)
451 QApplication::exit(status);
455 void GuiApplication::execBatchCommands()
457 LyX::ref().execBatchCommands();
460 QAbstractItemModel * GuiApplication::languageModel()
463 return language_model_;
465 QStandardItemModel * lang_model = new QStandardItemModel(this);
466 lang_model->insertColumns(0, 1);
468 Languages::const_iterator it = languages.begin();
469 Languages::const_iterator end = languages.end();
470 for (; it != end; ++it) {
471 current_row = lang_model->rowCount();
472 lang_model->insertRows(current_row, 1);
473 QModelIndex item = lang_model->index(current_row, 0);
474 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
475 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
477 language_model_ = new QSortFilterProxyModel(this);
478 language_model_->setSourceModel(lang_model);
479 language_model_->setSortLocaleAware(true);
480 return language_model_;
484 void GuiApplication::restoreGuiSession()
486 if (!lyxrc.load_session)
489 Session & session = LyX::ref().session();
490 vector<FileName> const & lastopened = session.lastOpened().getfiles();
491 // do not add to the lastfile list since these files are restored from
492 // last session, and should be already there (regular files), or should
493 // not be added at all (help files).
494 for_each(lastopened.begin(), lastopened.end(),
495 bind(&GuiView::loadDocument, current_view_, _1, false));
497 // clear this list to save a few bytes of RAM
498 session.lastOpened().clear();
502 QString const GuiApplication::romanFontName()
505 font.setKerning(false);
506 font.setStyleHint(QFont::Serif);
507 font.setFamily("serif");
509 return QFontInfo(font).family();
513 QString const GuiApplication::sansFontName()
516 font.setKerning(false);
517 font.setStyleHint(QFont::SansSerif);
518 font.setFamily("sans");
520 return QFontInfo(font).family();
524 QString const GuiApplication::typewriterFontName()
527 font.setKerning(false);
528 font.setStyleHint(QFont::TypeWriter);
529 font.setFamily("monospace");
531 return QFontInfo(font).family();
535 void GuiApplication::handleRegularEvents()
537 ForkedCallsController::handleCompletedProcesses();
541 bool GuiApplication::event(QEvent * e)
544 case QEvent::FileOpen: {
545 // Open a file; this happens only on Mac OS X for now
546 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
548 if (!current_view_ || !current_view_->view())
549 // The application is not properly initialized yet.
550 // So we acknowledge the event and delay the file opening
551 // until LyX is ready.
552 // FIXME UNICODE: FileName accept an utf8 encoded string.
553 LyX::ref().addFileToLoad(fromqstr(foe->file()));
555 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
556 qstring_to_ucs4(foe->file())));
562 return QApplication::event(e);
567 bool GuiApplication::notify(QObject * receiver, QEvent * event)
570 return QApplication::notify(receiver, event);
572 catch (ExceptionMessage const & e) {
575 LyX::cref().emergencyCleanup();
576 setQuitOnLastWindowClosed(false);
578 Alert::error(e.title_, e.details_);
580 // Properly crash in debug mode in order to get a useful backtrace.
583 // In release mode, try to exit gracefully.
586 case BufferException: {
587 Buffer * buf = current_view_->buffer();
588 docstring details = e.details_ + '\n';
589 details += theBufferList().emergencyWrite(buf);
590 theBufferList().release(buf);
591 details += "\n" + _("The current document was closed.");
592 Alert::error(e.title_, details);
595 case WarningException:
596 Alert::warning(e.title_, e.details_);
600 catch (exception const & e) {
601 docstring s = _("LyX has caught an exception, it will now "
602 "attempt to save all unsaved documents and exit."
604 s += from_ascii(e.what());
605 Alert::error(_("Software exception Detected"), s);
609 docstring s = _("LyX has caught some really weird exception, it will "
610 "now attempt to save all unsaved documents and exit.");
611 Alert::error(_("Software exception Detected"), s);
619 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
621 QColor const & qcol = color_cache_.get(col);
622 if (!qcol.isValid()) {
628 rgbcol.r = qcol.red();
629 rgbcol.g = qcol.green();
630 rgbcol.b = qcol.blue();
635 string const GuiApplication::hexName(ColorCode col)
637 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
641 void GuiApplication::updateColor(ColorCode)
643 // FIXME: Bleh, can't we just clear them all at once ?
644 color_cache_.clear();
648 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
650 SocketNotifier * sn = new SocketNotifier(this, fd, func);
651 socket_notifiers_[fd] = sn;
652 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
656 void GuiApplication::socketDataReceived(int fd)
658 socket_notifiers_[fd]->func_();
662 void GuiApplication::unregisterSocketCallback(int fd)
664 socket_notifiers_.erase(fd);
668 void GuiApplication::commitData(QSessionManager & sm)
670 /// The implementation is required to avoid an application exit
671 /// when session state save is triggered by session manager.
672 /// The default implementation sends a close event to all
673 /// visible top level widgets when session managment allows
675 /// We are changing that to close all wiew one by one.
676 /// FIXME: verify if the default implementation is enough now.
677 if (sm.allowsInteraction() && !closeAllViews())
682 void GuiApplication::addMenuTranslator()
684 installTranslator(new MenuTranslator(this));
688 bool GuiApplication::unregisterView(int id)
690 updateIds(views_, view_ids_);
691 LASSERT(views_.find(id) != views_.end(), /**/);
692 LASSERT(views_[id], /**/);
694 map<int, GuiView *>::iterator it;
695 for (it = views_.begin(); it != views_.end(); ++it) {
696 if (it->first == id) {
701 updateIds(views_, view_ids_);
706 bool GuiApplication::closeAllViews()
708 updateIds(views_, view_ids_);
712 map<int, GuiView*> const cmap = views_;
713 map<int, GuiView*>::const_iterator it;
714 for (it = cmap.begin(); it != cmap.end(); ++it) {
715 if (!it->second->close())
725 GuiView & GuiApplication::view(int id) const
727 LASSERT(views_.find(id) != views_.end(), /**/);
728 return *views_.find(id)->second;
732 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
734 vector<int>::const_iterator it = view_ids_.begin();
735 vector<int>::const_iterator const end = view_ids_.end();
736 for (; it != end; ++it)
737 view(*it).hideDialog(name, inset);
741 Buffer const * GuiApplication::updateInset(Inset const * inset) const
743 Buffer const * buffer_ = 0;
744 vector<int>::const_iterator it = view_ids_.begin();
745 vector<int>::const_iterator const end = view_ids_.end();
746 for (; it != end; ++it) {
747 Buffer const * ptr = view(*it).updateInset(inset);
755 void GuiApplication::readMenus(Lexer & lex)
761 bool GuiApplication::searchMenu(FuncRequest const & func,
762 vector<docstring> & names) const
764 return menus().searchMenu(func, names);
768 void GuiApplication::initGlobalMenu()
771 menus().fillMenuBar(global_menubar_, 0, true);
775 void GuiApplication::onLastWindowClosed()
778 global_menubar_->grabKeyboard();
782 ////////////////////////////////////////////////////////////////////////
784 // X11 specific stuff goes here...
787 bool GuiApplication::x11EventFilter(XEvent * xev)
793 case SelectionRequest: {
794 if (xev->xselectionrequest.selection != XA_PRIMARY)
796 LYXERR(Debug::GUI, "X requested selection.");
797 BufferView * bv = current_view_->view();
799 docstring const sel = bv->requestSelection();
805 case SelectionClear: {
806 if (xev->xselectionclear.selection != XA_PRIMARY)
808 LYXERR(Debug::GUI, "Lost selection.");
809 BufferView * bv = current_view_->view();
811 bv->clearSelection();
819 } // namespace frontend
822 void hideDialogs(std::string const & name, Inset * inset)
825 theApp()->hideDialogs(name, inset);
829 ////////////////////////////////////////////////////////////////////
833 ////////////////////////////////////////////////////////////////////
835 frontend::FontLoader & theFontLoader()
837 LASSERT(frontend::guiApp, /**/);
838 return frontend::guiApp->fontLoader();
842 frontend::FontMetrics const & theFontMetrics(Font const & f)
844 return theFontMetrics(f.fontInfo());
848 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
850 LASSERT(frontend::guiApp, /**/);
851 return frontend::guiApp->fontLoader().metrics(f);
855 ////////////////////////////////////////////////////////////////////
859 ////////////////////////////////////////////////////////////////////
861 frontend::Clipboard & theClipboard()
863 LASSERT(frontend::guiApp, /**/);
864 return frontend::guiApp->clipboard();
868 frontend::Selection & theSelection()
870 LASSERT(frontend::guiApp, /**/);
871 return frontend::guiApp->selection();
876 #include "GuiApplication_moc.cpp"