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()
257 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
264 case LFUN_WINDOW_CLOSE:
265 enable = view_ids_.size() > 0;
269 if (!current_view_) {
282 bool GuiApplication::dispatch(FuncRequest const & cmd)
286 case LFUN_WINDOW_NEW:
287 createView(toqstr(cmd.argument()));
290 case LFUN_WINDOW_CLOSE:
291 // update bookmark pit of the current buffer before window close
292 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
293 theLyXFunc().gotoBookmark(i+1, false, false);
294 current_view_->close();
298 // quitting is triggered by the gui code
299 // (leaving the event loop).
301 current_view_->message(from_utf8(N_("Exiting.")));
306 case LFUN_SCREEN_FONT_UPDATE: {
307 // handle the screen font changes.
308 font_loader_.update();
309 // Backup current_view_
310 GuiView * view = current_view_;
311 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
312 // to skip the refresh.
314 BufferList::iterator it = theBufferList().begin();
315 BufferList::iterator const end = theBufferList().end();
316 for (; it != end; ++it)
318 // Restore current_view_
319 current_view_ = view;
323 case LFUN_BUFFER_NEW:
325 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
326 createView(QString(), false); // keep hidden
327 current_view_->newDocument(to_utf8(cmd.argument()), false);
328 current_view_->show();
329 setActiveWindow(current_view_);
331 current_view_->newDocument(to_utf8(cmd.argument()), false);
334 case LFUN_BUFFER_NEW_TEMPLATE:
336 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
338 current_view_->newDocument(to_utf8(cmd.argument()), true);
339 if (!current_view_->buffer())
340 current_view_->close();
342 current_view_->newDocument(to_utf8(cmd.argument()), true);
347 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
349 current_view_->openDocument(to_utf8(cmd.argument()));
350 if (!current_view_->buffer())
351 current_view_->close();
353 current_view_->openDocument(to_utf8(cmd.argument()));
357 // Notify the caller that the action has not been dispatched.
361 // The action has been dispatched.
366 void GuiApplication::resetGui()
368 map<int, GuiView *>::iterator it;
369 for (it = views_.begin(); it != views_.end(); ++it)
370 it->second->resetDialogs();
372 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
376 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
379 map<int, GuiView *>::const_iterator it;
380 for (it = stdmap.begin(); it != stdmap.end(); ++it)
381 ids.push_back(it->first);
385 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
387 // release the keyboard which might have been grabed by the global
388 // menubar on Mac to catch shortcuts even without any GuiView.
390 global_menubar_->releaseKeyboard();
393 updateIds(views_, view_ids_);
395 while (views_.find(id) != views_.end())
397 GuiView * view = new GuiView(id);
399 // copy the icon size from old view
401 view->setIconSize(current_view_->iconSize());
405 updateIds(views_, view_ids_);
409 setActiveWindow(view);
412 if (!geometry_arg.isEmpty()) {
416 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
417 re.indexIn(geometry_arg);
418 w = re.cap(1).toInt();
419 h = re.cap(2).toInt();
420 x = re.cap(3).toInt();
421 y = re.cap(4).toInt();
422 view->setGeometry(x, y, w, h);
426 setCurrentView(view);
432 Clipboard & GuiApplication::clipboard()
438 Selection & GuiApplication::selection()
444 int GuiApplication::exec()
446 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
447 return QApplication::exec();
451 void GuiApplication::exit(int status)
453 QApplication::exit(status);
457 void GuiApplication::execBatchCommands()
459 LyX::ref().execBatchCommands();
461 language_model_ = new QStandardItemModel(this);
462 language_model_->insertColumns(0, 1);
464 Languages::const_iterator it = languages.begin();
465 Languages::const_iterator end = languages.end();
466 for (; it != end; ++it) {
467 current_row = language_model_->rowCount();
468 language_model_->insertRows(current_row, 1);
469 QModelIndex item = language_model_->index(current_row, 0);
470 language_model_->setData(item, qt_(it->second.display()), Qt::DisplayRole);
471 language_model_->setData(item, toqstr(it->second.lang()), Qt::UserRole);
473 language_model_->sort(0);
477 void GuiApplication::restoreGuiSession()
479 if (!lyxrc.load_session)
482 Session & session = LyX::ref().session();
483 vector<FileName> const & lastopened = session.lastOpened().getfiles();
484 // do not add to the lastfile list since these files are restored from
485 // last session, and should be already there (regular files), or should
486 // not be added at all (help files).
487 for_each(lastopened.begin(), lastopened.end(),
488 bind(&GuiView::loadDocument, current_view_, _1, false));
490 // clear this list to save a few bytes of RAM
491 session.lastOpened().clear();
495 QString const GuiApplication::romanFontName()
498 font.setKerning(false);
499 font.setStyleHint(QFont::Serif);
500 font.setFamily("serif");
502 return QFontInfo(font).family();
506 QString const GuiApplication::sansFontName()
509 font.setKerning(false);
510 font.setStyleHint(QFont::SansSerif);
511 font.setFamily("sans");
513 return QFontInfo(font).family();
517 QString const GuiApplication::typewriterFontName()
520 font.setKerning(false);
521 font.setStyleHint(QFont::TypeWriter);
522 font.setFamily("monospace");
524 return QFontInfo(font).family();
528 void GuiApplication::handleRegularEvents()
530 ForkedCallsController::handleCompletedProcesses();
534 bool GuiApplication::event(QEvent * e)
537 case QEvent::FileOpen: {
538 // Open a file; this happens only on Mac OS X for now
539 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
541 if (!current_view_ || !current_view_->view())
542 // The application is not properly initialized yet.
543 // So we acknowledge the event and delay the file opening
544 // until LyX is ready.
545 // FIXME UNICODE: FileName accept an utf8 encoded string.
546 LyX::ref().addFileToLoad(fromqstr(foe->file()));
548 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
549 qstring_to_ucs4(foe->file())));
555 return QApplication::event(e);
560 bool GuiApplication::notify(QObject * receiver, QEvent * event)
563 return QApplication::notify(receiver, event);
565 catch (ExceptionMessage const & e) {
568 LyX::cref().emergencyCleanup();
569 setQuitOnLastWindowClosed(false);
571 Alert::error(e.title_, e.details_);
573 // Properly crash in debug mode in order to get a useful backtrace.
576 // In release mode, try to exit gracefully.
579 case BufferException: {
580 Buffer * buf = current_view_->buffer();
581 docstring details = e.details_ + '\n';
582 details += theBufferList().emergencyWrite(buf);
583 theBufferList().release(buf);
584 details += "\n" + _("The current document was closed.");
585 Alert::error(e.title_, details);
588 case WarningException:
589 Alert::warning(e.title_, e.details_);
593 catch (exception const & e) {
594 docstring s = _("LyX has caught an exception, it will now "
595 "attempt to save all unsaved documents and exit."
597 s += from_ascii(e.what());
598 Alert::error(_("Software exception Detected"), s);
602 docstring s = _("LyX has caught some really weird exception, it will "
603 "now attempt to save all unsaved documents and exit.");
604 Alert::error(_("Software exception Detected"), s);
612 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
614 QColor const & qcol = color_cache_.get(col);
615 if (!qcol.isValid()) {
621 rgbcol.r = qcol.red();
622 rgbcol.g = qcol.green();
623 rgbcol.b = qcol.blue();
628 string const GuiApplication::hexName(ColorCode col)
630 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
634 void GuiApplication::updateColor(ColorCode)
636 // FIXME: Bleh, can't we just clear them all at once ?
637 color_cache_.clear();
641 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
643 SocketNotifier * sn = new SocketNotifier(this, fd, func);
644 socket_notifiers_[fd] = sn;
645 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
649 void GuiApplication::socketDataReceived(int fd)
651 socket_notifiers_[fd]->func_();
655 void GuiApplication::unregisterSocketCallback(int fd)
657 socket_notifiers_.erase(fd);
661 void GuiApplication::commitData(QSessionManager & sm)
663 /// The implementation is required to avoid an application exit
664 /// when session state save is triggered by session manager.
665 /// The default implementation sends a close event to all
666 /// visible top level widgets when session managment allows
668 /// We are changing that to close all wiew one by one.
669 /// FIXME: verify if the default implementation is enough now.
670 if (sm.allowsInteraction() && !closeAllViews())
675 void GuiApplication::addMenuTranslator()
677 installTranslator(new MenuTranslator(this));
681 bool GuiApplication::unregisterView(int id)
683 updateIds(views_, view_ids_);
684 LASSERT(views_.find(id) != views_.end(), /**/);
685 LASSERT(views_[id], /**/);
687 map<int, GuiView *>::iterator it;
688 for (it = views_.begin(); it != views_.end(); ++it) {
689 if (it->first == id) {
694 updateIds(views_, view_ids_);
699 bool GuiApplication::closeAllViews()
701 updateIds(views_, view_ids_);
705 map<int, GuiView*> const cmap = views_;
706 map<int, GuiView*>::const_iterator it;
707 for (it = cmap.begin(); it != cmap.end(); ++it) {
708 if (!it->second->close())
718 GuiView & GuiApplication::view(int id) const
720 LASSERT(views_.find(id) != views_.end(), /**/);
721 return *views_.find(id)->second;
725 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
727 vector<int>::const_iterator it = view_ids_.begin();
728 vector<int>::const_iterator const end = view_ids_.end();
729 for (; it != end; ++it)
730 view(*it).hideDialog(name, inset);
734 Buffer const * GuiApplication::updateInset(Inset const * inset) const
736 Buffer const * buffer_ = 0;
737 vector<int>::const_iterator it = view_ids_.begin();
738 vector<int>::const_iterator const end = view_ids_.end();
739 for (; it != end; ++it) {
740 Buffer const * ptr = view(*it).updateInset(inset);
748 void GuiApplication::readMenus(Lexer & lex)
754 bool GuiApplication::searchMenu(FuncRequest const & func,
755 vector<docstring> & names) const
757 return menus().searchMenu(func, names);
761 void GuiApplication::initGlobalMenu()
764 menus().fillMenuBar(global_menubar_, 0, true);
768 void GuiApplication::onLastWindowClosed()
771 global_menubar_->grabKeyboard();
775 ////////////////////////////////////////////////////////////////////////
777 // X11 specific stuff goes here...
780 bool GuiApplication::x11EventFilter(XEvent * xev)
786 case SelectionRequest: {
787 if (xev->xselectionrequest.selection != XA_PRIMARY)
789 LYXERR(Debug::GUI, "X requested selection.");
790 BufferView * bv = current_view_->view();
792 docstring const sel = bv->requestSelection();
798 case SelectionClear: {
799 if (xev->xselectionclear.selection != XA_PRIMARY)
801 LYXERR(Debug::GUI, "Lost selection.");
802 BufferView * bv = current_view_->view();
804 bv->clearSelection();
812 } // namespace frontend
815 void hideDialogs(std::string const & name, Inset * inset)
818 theApp()->hideDialogs(name, inset);
822 ////////////////////////////////////////////////////////////////////
826 ////////////////////////////////////////////////////////////////////
828 frontend::FontLoader & theFontLoader()
830 LASSERT(frontend::guiApp, /**/);
831 return frontend::guiApp->fontLoader();
835 frontend::FontMetrics const & theFontMetrics(Font const & f)
837 return theFontMetrics(f.fontInfo());
841 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
843 LASSERT(frontend::guiApp, /**/);
844 return frontend::guiApp->fontLoader().metrics(f);
848 ////////////////////////////////////////////////////////////////////
852 ////////////////////////////////////////////////////////////////////
854 frontend::Clipboard & theClipboard()
856 LASSERT(frontend::guiApp, /**/);
857 return frontend::guiApp->clipboard();
861 frontend::Selection & theSelection()
863 LASSERT(frontend::guiApp, /**/);
864 return frontend::guiApp->selection();
869 #include "GuiApplication_moc.cpp"