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 <QStandardItemModel>
63 #include <QTranslator>
67 #include <X11/Xatom.h>
73 #include <boost/bind.hpp>
78 using namespace lyx::support;
82 frontend::Application * createApplication(int & argc, char * argv[])
84 return new frontend::GuiApplication(argc, argv);
90 class SocketNotifier : public QSocketNotifier
93 /// connect a connection notification from the LyXServerSocket
94 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
95 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
99 /// The callback function
100 Application::SocketCallback func_;
104 ////////////////////////////////////////////////////////////////////////
105 // Mac specific stuff goes here...
107 class MenuTranslator : public QTranslator
110 MenuTranslator(QObject * parent)
111 : QTranslator(parent)
114 QString translate(const char * /*context*/,
115 const char * sourceText,
116 const char * /*comment*/ = 0)
118 string const s = sourceText;
119 if (s == N_("About %1") || s == N_("Preferences")
120 || s == N_("Reconfigure") || s == N_("Quit %1"))
127 class GlobalMenuBar : public QMenuBar
131 GlobalMenuBar() : QMenuBar(0) {}
134 bool event(QEvent * e)
136 if (e->type() == QEvent::ShortcutOverride) {
137 // && activeWindow() == 0) {
138 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
140 setKeySymbol(&sym, ke);
141 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
149 ///////////////////////////////////////////////////////////////
150 // You can find more platform specific stuff
151 // at the end of this file...
152 ///////////////////////////////////////////////////////////////
155 GuiApplication * guiApp;
158 GuiApplication::GuiApplication(int & argc, char ** argv)
159 : QApplication(argc, argv), Application(), current_view_(0), global_menubar_(0)
161 QString app_name = "LyX";
162 QCoreApplication::setOrganizationName(app_name);
163 QCoreApplication::setOrganizationDomain("lyx.org");
164 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
166 // FIXME: quitOnLastWindowClosed is true by default. We should have a
167 // lyxrc setting for this in order to let the application stay resident.
168 // But then we need some kind of dock icon, at least on Windows.
170 if (lyxrc.quit_on_last_window_closed)
171 setQuitOnLastWindowClosed(false);
174 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
175 // seems to be the default case for applications like LyX.
176 setQuitOnLastWindowClosed(false);
180 // doubleClickInterval() is 400 ms on X11 which is just too long.
181 // On Windows and Mac OS X, the operating system's value is used.
182 // On Microsoft Windows, calling this function sets the double
183 // click interval for all applications. So we don't!
184 QApplication::setDoubleClickInterval(300);
187 // install translation file for Qt built-in dialogs
188 QString language_name = QString("qt_") + QLocale::system().name();
190 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
191 // Short-named translator can be loaded from a long name, but not the
192 // opposite. Therefore, long name should be used without truncation.
193 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
194 if (qt_trans_.load(language_name,
195 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
197 installTranslator(&qt_trans_);
198 // even if the language calls for RtL, don't do that
199 setLayoutDirection(Qt::LeftToRight);
200 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
203 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
207 // This allows to translate the strings that appear in the LyX menu.
210 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
212 using namespace lyx::graphics;
214 Image::newImage = boost::bind(&GuiImage::newImage);
215 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
217 // needs to be done before reading lyxrc
219 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
223 // Set the cache to 5120 kilobytes which corresponds to screen size of
224 // 1280 by 1024 pixels with a color depth of 32 bits.
225 QPixmapCache::setCacheLimit(5120);
227 // Initialize RC Fonts
228 if (lyxrc.roman_font_name.empty())
229 lyxrc.roman_font_name = fromqstr(romanFontName());
231 if (lyxrc.sans_font_name.empty())
232 lyxrc.sans_font_name = fromqstr(sansFontName());
234 if (lyxrc.typewriter_font_name.empty())
235 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
237 general_timer_.setInterval(500);
238 connect(&general_timer_, SIGNAL(timeout()),
239 this, SLOT(handleRegularEvents()));
240 general_timer_.start();
244 if (global_menubar_ == 0) {
245 // Create the global default menubar which is shown for the dialogs
246 // and if no GuiView is visible.
247 global_menubar_ = new GlobalMenuBar();
253 GuiApplication::~GuiApplication()
255 socket_notifiers_.clear();
259 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
266 case LFUN_WINDOW_CLOSE:
267 enable = view_ids_.size() > 0;
271 if (!current_view_) {
284 bool GuiApplication::dispatch(FuncRequest const & cmd)
288 case LFUN_WINDOW_NEW:
289 createView(toqstr(cmd.argument()));
292 case LFUN_WINDOW_CLOSE:
293 // update bookmark pit of the current buffer before window close
294 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
295 theLyXFunc().gotoBookmark(i+1, false, false);
296 current_view_->close();
300 // quitting is triggered by the gui code
301 // (leaving the event loop).
303 current_view_->message(from_utf8(N_("Exiting.")));
308 case LFUN_SCREEN_FONT_UPDATE: {
309 // handle the screen font changes.
310 font_loader_.update();
311 // Backup current_view_
312 GuiView * view = current_view_;
313 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
314 // to skip the refresh.
316 BufferList::iterator it = theBufferList().begin();
317 BufferList::iterator const end = theBufferList().end();
318 for (; it != end; ++it)
320 // Restore current_view_
321 current_view_ = view;
325 case LFUN_BUFFER_NEW:
327 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
328 createView(QString(), false); // keep hidden
329 current_view_->newDocument(to_utf8(cmd.argument()), false);
330 current_view_->show();
331 setActiveWindow(current_view_);
333 current_view_->newDocument(to_utf8(cmd.argument()), false);
336 case LFUN_BUFFER_NEW_TEMPLATE:
338 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
340 current_view_->newDocument(to_utf8(cmd.argument()), true);
341 if (!current_view_->buffer())
342 current_view_->close();
344 current_view_->newDocument(to_utf8(cmd.argument()), true);
349 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
351 current_view_->openDocument(to_utf8(cmd.argument()));
352 if (!current_view_->buffer())
353 current_view_->close();
355 current_view_->openDocument(to_utf8(cmd.argument()));
359 // Notify the caller that the action has not been dispatched.
363 // The action has been dispatched.
368 void GuiApplication::resetGui()
370 map<int, GuiView *>::iterator it;
371 for (it = views_.begin(); it != views_.end(); ++it)
372 it->second->resetDialogs();
374 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
378 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
381 map<int, GuiView *>::const_iterator it;
382 for (it = stdmap.begin(); it != stdmap.end(); ++it)
383 ids.push_back(it->first);
387 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
389 // release the keyboard which might have been grabed by the global
390 // menubar on Mac to catch shortcuts even without any GuiView.
392 global_menubar_->releaseKeyboard();
395 updateIds(views_, view_ids_);
397 while (views_.find(id) != views_.end())
399 GuiView * view = new GuiView(id);
401 // copy the icon size from old view
403 view->setIconSize(current_view_->iconSize());
407 updateIds(views_, view_ids_);
411 setActiveWindow(view);
414 if (!geometry_arg.isEmpty()) {
418 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
419 re.indexIn(geometry_arg);
420 w = re.cap(1).toInt();
421 h = re.cap(2).toInt();
422 x = re.cap(3).toInt();
423 y = re.cap(4).toInt();
424 view->setGeometry(x, y, w, h);
428 setCurrentView(view);
434 Clipboard & GuiApplication::clipboard()
440 Selection & GuiApplication::selection()
446 int GuiApplication::exec()
448 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
449 return QApplication::exec();
453 void GuiApplication::exit(int status)
455 QApplication::exit(status);
459 void GuiApplication::execBatchCommands()
461 LyX::ref().execBatchCommands();
463 language_model_ = new QStandardItemModel(this);
464 language_model_->insertColumns(0, 1);
466 Languages::const_iterator it = languages.begin();
467 Languages::const_iterator end = languages.end();
468 for (; it != end; ++it) {
469 current_row = language_model_->rowCount();
470 language_model_->insertRows(current_row, 1);
471 QModelIndex item = language_model_->index(current_row, 0);
472 language_model_->setData(item, qt_(it->second.display()), Qt::DisplayRole);
473 language_model_->setData(item, toqstr(it->second.lang()), Qt::UserRole);
478 void GuiApplication::restoreGuiSession()
480 if (!lyxrc.load_session)
483 Session & session = LyX::ref().session();
484 vector<FileName> const & lastopened = session.lastOpened().getfiles();
485 // do not add to the lastfile list since these files are restored from
486 // last session, and should be already there (regular files), or should
487 // not be added at all (help files).
488 for_each(lastopened.begin(), lastopened.end(),
489 bind(&GuiView::loadDocument, current_view_, _1, false));
491 // clear this list to save a few bytes of RAM
492 session.lastOpened().clear();
496 QString const GuiApplication::romanFontName()
499 font.setKerning(false);
500 font.setStyleHint(QFont::Serif);
501 font.setFamily("serif");
503 return QFontInfo(font).family();
507 QString const GuiApplication::sansFontName()
510 font.setKerning(false);
511 font.setStyleHint(QFont::SansSerif);
512 font.setFamily("sans");
514 return QFontInfo(font).family();
518 QString const GuiApplication::typewriterFontName()
521 font.setKerning(false);
522 font.setStyleHint(QFont::TypeWriter);
523 font.setFamily("monospace");
525 return QFontInfo(font).family();
529 void GuiApplication::handleRegularEvents()
531 ForkedCallsController::handleCompletedProcesses();
535 bool GuiApplication::event(QEvent * e)
538 case QEvent::FileOpen: {
539 // Open a file; this happens only on Mac OS X for now
540 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
542 if (!current_view_ || !current_view_->view())
543 // The application is not properly initialized yet.
544 // So we acknowledge the event and delay the file opening
545 // until LyX is ready.
546 // FIXME UNICODE: FileName accept an utf8 encoded string.
547 LyX::ref().addFileToLoad(fromqstr(foe->file()));
549 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
550 qstring_to_ucs4(foe->file())));
556 return QApplication::event(e);
561 bool GuiApplication::notify(QObject * receiver, QEvent * event)
564 return QApplication::notify(receiver, event);
566 catch (ExceptionMessage const & e) {
569 LyX::cref().emergencyCleanup();
570 setQuitOnLastWindowClosed(false);
572 Alert::error(e.title_, e.details_);
574 // Properly crash in debug mode in order to get a useful backtrace.
577 // In release mode, try to exit gracefully.
580 case BufferException: {
581 Buffer * buf = current_view_->buffer();
582 docstring details = e.details_ + '\n';
583 details += theBufferList().emergencyWrite(buf);
584 theBufferList().release(buf);
585 details += "\n" + _("The current document was closed.");
586 Alert::error(e.title_, details);
589 case WarningException:
590 Alert::warning(e.title_, e.details_);
594 catch (exception const & e) {
595 docstring s = _("LyX has caught an exception, it will now "
596 "attempt to save all unsaved documents and exit."
598 s += from_ascii(e.what());
599 Alert::error(_("Software exception Detected"), s);
603 docstring s = _("LyX has caught some really weird exception, it will "
604 "now attempt to save all unsaved documents and exit.");
605 Alert::error(_("Software exception Detected"), s);
613 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
615 QColor const & qcol = color_cache_.get(col);
616 if (!qcol.isValid()) {
622 rgbcol.r = qcol.red();
623 rgbcol.g = qcol.green();
624 rgbcol.b = qcol.blue();
629 string const GuiApplication::hexName(ColorCode col)
631 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
635 void GuiApplication::updateColor(ColorCode)
637 // FIXME: Bleh, can't we just clear them all at once ?
638 color_cache_.clear();
642 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
644 SocketNotifier * sn = new SocketNotifier(this, fd, func);
645 socket_notifiers_[fd] = sn;
646 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
650 void GuiApplication::socketDataReceived(int fd)
652 socket_notifiers_[fd]->func_();
656 void GuiApplication::unregisterSocketCallback(int fd)
658 socket_notifiers_.erase(fd);
662 void GuiApplication::commitData(QSessionManager & sm)
664 /// The implementation is required to avoid an application exit
665 /// when session state save is triggered by session manager.
666 /// The default implementation sends a close event to all
667 /// visible top level widgets when session managment allows
669 /// We are changing that to close all wiew one by one.
670 /// FIXME: verify if the default implementation is enough now.
671 if (sm.allowsInteraction() && !closeAllViews())
676 void GuiApplication::addMenuTranslator()
678 installTranslator(new MenuTranslator(this));
682 bool GuiApplication::unregisterView(int id)
684 updateIds(views_, view_ids_);
685 LASSERT(views_.find(id) != views_.end(), /**/);
686 LASSERT(views_[id], /**/);
688 map<int, GuiView *>::iterator it;
689 for (it = views_.begin(); it != views_.end(); ++it) {
690 if (it->first == id) {
695 updateIds(views_, view_ids_);
700 bool GuiApplication::closeAllViews()
702 updateIds(views_, view_ids_);
706 map<int, GuiView*> const cmap = views_;
707 map<int, GuiView*>::const_iterator it;
708 for (it = cmap.begin(); it != cmap.end(); ++it) {
709 if (!it->second->close())
719 GuiView & GuiApplication::view(int id) const
721 LASSERT(views_.find(id) != views_.end(), /**/);
722 return *views_.find(id)->second;
726 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
728 vector<int>::const_iterator it = view_ids_.begin();
729 vector<int>::const_iterator const end = view_ids_.end();
730 for (; it != end; ++it)
731 view(*it).hideDialog(name, inset);
735 Buffer const * GuiApplication::updateInset(Inset const * inset) const
737 Buffer const * buffer_ = 0;
738 vector<int>::const_iterator it = view_ids_.begin();
739 vector<int>::const_iterator const end = view_ids_.end();
740 for (; it != end; ++it) {
741 Buffer const * ptr = view(*it).updateInset(inset);
749 void GuiApplication::readMenus(Lexer & lex)
755 bool GuiApplication::searchMenu(FuncRequest const & func,
756 vector<docstring> & names) const
758 return menus().searchMenu(func, names);
762 void GuiApplication::initGlobalMenu()
765 menus().fillMenuBar(global_menubar_, 0, true);
769 void GuiApplication::onLastWindowClosed()
772 global_menubar_->grabKeyboard();
776 ////////////////////////////////////////////////////////////////////////
778 // X11 specific stuff goes here...
781 bool GuiApplication::x11EventFilter(XEvent * xev)
787 case SelectionRequest: {
788 if (xev->xselectionrequest.selection != XA_PRIMARY)
790 LYXERR(Debug::GUI, "X requested selection.");
791 BufferView * bv = current_view_->view();
793 docstring const sel = bv->requestSelection();
799 case SelectionClear: {
800 if (xev->xselectionclear.selection != XA_PRIMARY)
802 LYXERR(Debug::GUI, "Lost selection.");
803 BufferView * bv = current_view_->view();
805 bv->clearSelection();
813 } // namespace frontend
816 void hideDialogs(std::string const & name, Inset * inset)
819 theApp()->hideDialogs(name, inset);
823 ////////////////////////////////////////////////////////////////////
827 ////////////////////////////////////////////////////////////////////
829 frontend::FontLoader & theFontLoader()
831 LASSERT(frontend::guiApp, /**/);
832 return frontend::guiApp->fontLoader();
836 frontend::FontMetrics const & theFontMetrics(Font const & f)
838 return theFontMetrics(f.fontInfo());
842 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
844 LASSERT(frontend::guiApp, /**/);
845 return frontend::guiApp->fontLoader().metrics(f);
849 ////////////////////////////////////////////////////////////////////
853 ////////////////////////////////////////////////////////////////////
855 frontend::Clipboard & theClipboard()
857 LASSERT(frontend::guiApp, /**/);
858 return frontend::guiApp->clipboard();
862 frontend::Selection & theSelection()
864 LASSERT(frontend::guiApp, /**/);
865 return frontend::guiApp->selection();
870 #include "GuiApplication_moc.cpp"