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(), language_model_(0),
161 current_view_(0), global_menubar_(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 #if QT_VERSION >= 0x040300
480 language_model_->setSortLocaleAware(true);
482 return language_model_;
486 void GuiApplication::restoreGuiSession()
488 if (!lyxrc.load_session)
491 Session & session = LyX::ref().session();
492 vector<FileName> const & lastopened = session.lastOpened().getfiles();
493 // do not add to the lastfile list since these files are restored from
494 // last session, and should be already there (regular files), or should
495 // not be added at all (help files).
496 for_each(lastopened.begin(), lastopened.end(),
497 bind(&GuiView::loadDocument, current_view_, _1, false));
499 // clear this list to save a few bytes of RAM
500 session.lastOpened().clear();
504 QString const GuiApplication::romanFontName()
507 font.setKerning(false);
508 font.setStyleHint(QFont::Serif);
509 font.setFamily("serif");
511 return QFontInfo(font).family();
515 QString const GuiApplication::sansFontName()
518 font.setKerning(false);
519 font.setStyleHint(QFont::SansSerif);
520 font.setFamily("sans");
522 return QFontInfo(font).family();
526 QString const GuiApplication::typewriterFontName()
529 font.setKerning(false);
530 font.setStyleHint(QFont::TypeWriter);
531 font.setFamily("monospace");
533 return QFontInfo(font).family();
537 void GuiApplication::handleRegularEvents()
539 ForkedCallsController::handleCompletedProcesses();
543 bool GuiApplication::event(QEvent * e)
546 case QEvent::FileOpen: {
547 // Open a file; this happens only on Mac OS X for now
548 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
550 if (!current_view_ || !current_view_->view())
551 // The application is not properly initialized yet.
552 // So we acknowledge the event and delay the file opening
553 // until LyX is ready.
554 // FIXME UNICODE: FileName accept an utf8 encoded string.
555 LyX::ref().addFileToLoad(fromqstr(foe->file()));
557 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
558 qstring_to_ucs4(foe->file())));
564 return QApplication::event(e);
569 bool GuiApplication::notify(QObject * receiver, QEvent * event)
572 return QApplication::notify(receiver, event);
574 catch (ExceptionMessage const & e) {
577 LyX::cref().emergencyCleanup();
578 setQuitOnLastWindowClosed(false);
580 Alert::error(e.title_, e.details_);
582 // Properly crash in debug mode in order to get a useful backtrace.
585 // In release mode, try to exit gracefully.
588 case BufferException: {
589 Buffer * buf = current_view_->buffer();
590 docstring details = e.details_ + '\n';
591 details += theBufferList().emergencyWrite(buf);
592 theBufferList().release(buf);
593 details += "\n" + _("The current document was closed.");
594 Alert::error(e.title_, details);
597 case WarningException:
598 Alert::warning(e.title_, e.details_);
602 catch (exception const & e) {
603 docstring s = _("LyX has caught an exception, it will now "
604 "attempt to save all unsaved documents and exit."
606 s += from_ascii(e.what());
607 Alert::error(_("Software exception Detected"), s);
611 docstring s = _("LyX has caught some really weird exception, it will "
612 "now attempt to save all unsaved documents and exit.");
613 Alert::error(_("Software exception Detected"), s);
621 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
623 QColor const & qcol = color_cache_.get(col);
624 if (!qcol.isValid()) {
630 rgbcol.r = qcol.red();
631 rgbcol.g = qcol.green();
632 rgbcol.b = qcol.blue();
637 string const GuiApplication::hexName(ColorCode col)
639 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
643 void GuiApplication::updateColor(ColorCode)
645 // FIXME: Bleh, can't we just clear them all at once ?
646 color_cache_.clear();
650 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
652 SocketNotifier * sn = new SocketNotifier(this, fd, func);
653 socket_notifiers_[fd] = sn;
654 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
658 void GuiApplication::socketDataReceived(int fd)
660 socket_notifiers_[fd]->func_();
664 void GuiApplication::unregisterSocketCallback(int fd)
666 socket_notifiers_.erase(fd);
670 void GuiApplication::commitData(QSessionManager & sm)
672 /// The implementation is required to avoid an application exit
673 /// when session state save is triggered by session manager.
674 /// The default implementation sends a close event to all
675 /// visible top level widgets when session managment allows
677 /// We are changing that to close all wiew one by one.
678 /// FIXME: verify if the default implementation is enough now.
679 if (sm.allowsInteraction() && !closeAllViews())
684 void GuiApplication::addMenuTranslator()
686 installTranslator(new MenuTranslator(this));
690 bool GuiApplication::unregisterView(int id)
692 updateIds(views_, view_ids_);
693 LASSERT(views_.find(id) != views_.end(), /**/);
694 LASSERT(views_[id], /**/);
696 map<int, GuiView *>::iterator it;
697 for (it = views_.begin(); it != views_.end(); ++it) {
698 if (it->first == id) {
703 updateIds(views_, view_ids_);
708 bool GuiApplication::closeAllViews()
710 updateIds(views_, view_ids_);
714 map<int, GuiView*> const cmap = views_;
715 map<int, GuiView*>::const_iterator it;
716 for (it = cmap.begin(); it != cmap.end(); ++it) {
717 if (!it->second->close())
727 GuiView & GuiApplication::view(int id) const
729 LASSERT(views_.find(id) != views_.end(), /**/);
730 return *views_.find(id)->second;
734 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
736 vector<int>::const_iterator it = view_ids_.begin();
737 vector<int>::const_iterator const end = view_ids_.end();
738 for (; it != end; ++it)
739 view(*it).hideDialog(name, inset);
743 Buffer const * GuiApplication::updateInset(Inset const * inset) const
745 Buffer const * buffer_ = 0;
746 vector<int>::const_iterator it = view_ids_.begin();
747 vector<int>::const_iterator const end = view_ids_.end();
748 for (; it != end; ++it) {
749 Buffer const * ptr = view(*it).updateInset(inset);
757 void GuiApplication::readMenus(Lexer & lex)
763 bool GuiApplication::searchMenu(FuncRequest const & func,
764 vector<docstring> & names) const
766 return menus().searchMenu(func, names);
770 void GuiApplication::initGlobalMenu()
773 menus().fillMenuBar(global_menubar_, 0, true);
777 void GuiApplication::onLastWindowClosed()
780 global_menubar_->grabKeyboard();
784 ////////////////////////////////////////////////////////////////////////
786 // X11 specific stuff goes here...
789 bool GuiApplication::x11EventFilter(XEvent * xev)
795 case SelectionRequest: {
796 if (xev->xselectionrequest.selection != XA_PRIMARY)
798 LYXERR(Debug::GUI, "X requested selection.");
799 BufferView * bv = current_view_->view();
801 docstring const sel = bv->requestSelection();
807 case SelectionClear: {
808 if (xev->xselectionclear.selection != XA_PRIMARY)
810 LYXERR(Debug::GUI, "Lost selection.");
811 BufferView * bv = current_view_->view();
813 bv->clearSelection();
821 } // namespace frontend
824 void hideDialogs(std::string const & name, Inset * inset)
827 theApp()->hideDialogs(name, inset);
831 ////////////////////////////////////////////////////////////////////
835 ////////////////////////////////////////////////////////////////////
837 frontend::FontLoader & theFontLoader()
839 LASSERT(frontend::guiApp, /**/);
840 return frontend::guiApp->fontLoader();
844 frontend::FontMetrics const & theFontMetrics(Font const & f)
846 return theFontMetrics(f.fontInfo());
850 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
852 LASSERT(frontend::guiApp, /**/);
853 return frontend::guiApp->fontLoader().metrics(f);
857 ////////////////////////////////////////////////////////////////////
861 ////////////////////////////////////////////////////////////////////
863 frontend::Clipboard & theClipboard()
865 LASSERT(frontend::guiApp, /**/);
866 return frontend::guiApp->clipboard();
870 frontend::Selection & theSelection()
872 LASSERT(frontend::guiApp, /**/);
873 return frontend::guiApp->selection();
878 #include "GuiApplication_moc.cpp"