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/assert.h"
40 #include "support/debug.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/FileName.h"
43 #include "support/ForkedCalls.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/os.h"
47 #include "support/Package.h"
49 #include <QApplication>
52 #include <QFileOpenEvent>
54 #include <QLibraryInfo>
56 #include <QPixmapCache>
58 #include <QSessionManager>
59 #include <QSocketNotifier>
62 #include <QTranslator>
66 #include <X11/Xatom.h>
72 #include <boost/bind.hpp>
77 using namespace lyx::support;
81 frontend::Application * createApplication(int & argc, char * argv[])
83 return new frontend::GuiApplication(argc, argv);
89 class SocketNotifier : public QSocketNotifier
92 /// connect a connection notification from the LyXServerSocket
93 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
94 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
98 /// The callback function
99 Application::SocketCallback func_;
103 ////////////////////////////////////////////////////////////////////////
104 // Mac specific stuff goes here...
106 class MenuTranslator : public QTranslator
109 MenuTranslator(QObject * parent)
110 : QTranslator(parent)
113 QString translate(const char * /*context*/,
114 const char * sourceText,
115 const char * /*comment*/ = 0)
117 string const s = sourceText;
118 if (s == N_("About %1") || s == N_("Preferences")
119 || s == N_("Reconfigure") || s == N_("Quit %1"))
126 class GlobalMenuBar : public QMenuBar
130 GlobalMenuBar() : QMenuBar(0) {}
133 bool event(QEvent * e)
135 if (e->type() == QEvent::ShortcutOverride) {
136 // && activeWindow() == 0) {
137 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
139 setKeySymbol(&sym, ke);
140 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
148 ///////////////////////////////////////////////////////////////
149 // You can find more platform specific stuff
150 // at the end of this file...
151 ///////////////////////////////////////////////////////////////
154 GuiApplication * guiApp;
157 GuiApplication::GuiApplication(int & argc, char ** argv)
158 : QApplication(argc, argv), Application(), current_view_(0), global_menubar_(0)
160 QString app_name = "LyX";
161 QCoreApplication::setOrganizationName(app_name);
162 QCoreApplication::setOrganizationDomain("lyx.org");
163 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
165 // FIXME: quitOnLastWindowClosed is true by default. We should have a
166 // lyxrc setting for this in order to let the application stay resident.
167 // But then we need some kind of dock icon, at least on Windows.
169 if (lyxrc.quit_on_last_window_closed)
170 setQuitOnLastWindowClosed(false);
173 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
174 // seems to be the default case for applications like LyX.
175 setQuitOnLastWindowClosed(false);
179 // doubleClickInterval() is 400 ms on X11 which is just too long.
180 // On Windows and Mac OS X, the operating system's value is used.
181 // On Microsoft Windows, calling this function sets the double
182 // click interval for all applications. So we don't!
183 QApplication::setDoubleClickInterval(300);
186 // install translation file for Qt built-in dialogs
187 QString language_name = QString("qt_") + QLocale::system().name();
189 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
190 // Short-named translator can be loaded from a long name, but not the
191 // opposite. Therefore, long name should be used without truncation.
192 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
193 if (qt_trans_.load(language_name,
194 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
196 installTranslator(&qt_trans_);
197 // even if the language calls for RtL, don't do that
198 setLayoutDirection(Qt::LeftToRight);
199 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
202 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
206 // This allows to translate the strings that appear in the LyX menu.
209 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
211 using namespace lyx::graphics;
213 Image::newImage = boost::bind(&GuiImage::newImage);
214 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
216 // needs to be done before reading lyxrc
218 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
222 // Set the cache to 5120 kilobytes which corresponds to screen size of
223 // 1280 by 1024 pixels with a color depth of 32 bits.
224 QPixmapCache::setCacheLimit(5120);
226 // Initialize RC Fonts
227 if (lyxrc.roman_font_name.empty())
228 lyxrc.roman_font_name = fromqstr(romanFontName());
230 if (lyxrc.sans_font_name.empty())
231 lyxrc.sans_font_name = fromqstr(sansFontName());
233 if (lyxrc.typewriter_font_name.empty())
234 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
236 general_timer_.setInterval(500);
237 connect(&general_timer_, SIGNAL(timeout()),
238 this, SLOT(handleRegularEvents()));
239 general_timer_.start();
242 if (global_menubar_ == 0) {
243 // Create the global default menubar which is shown for the dialogs
244 // and if no GuiView is visible.
245 global_menubar_ = new GlobalMenuBar();
251 GuiApplication::~GuiApplication()
253 socket_notifiers_.clear();
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();
463 void GuiApplication::restoreGuiSession()
465 if (!lyxrc.load_session)
468 Session & session = LyX::ref().session();
469 vector<FileName> const & lastopened = session.lastOpened().getfiles();
470 // do not add to the lastfile list since these files are restored from
471 // last session, and should be already there (regular files), or should
472 // not be added at all (help files).
473 for_each(lastopened.begin(), lastopened.end(),
474 bind(&GuiView::loadDocument, current_view_, _1, false));
476 // clear this list to save a few bytes of RAM
477 session.lastOpened().clear();
481 QString const GuiApplication::romanFontName()
484 font.setKerning(false);
485 font.setStyleHint(QFont::Serif);
486 font.setFamily("serif");
488 return QFontInfo(font).family();
492 QString const GuiApplication::sansFontName()
495 font.setKerning(false);
496 font.setStyleHint(QFont::SansSerif);
497 font.setFamily("sans");
499 return QFontInfo(font).family();
503 QString const GuiApplication::typewriterFontName()
506 font.setKerning(false);
507 font.setStyleHint(QFont::TypeWriter);
508 font.setFamily("monospace");
510 return QFontInfo(font).family();
514 void GuiApplication::handleRegularEvents()
516 ForkedCallsController::handleCompletedProcesses();
520 bool GuiApplication::event(QEvent * e)
523 case QEvent::FileOpen: {
524 // Open a file; this happens only on Mac OS X for now
525 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
527 if (!current_view_ || !current_view_->view())
528 // The application is not properly initialized yet.
529 // So we acknowledge the event and delay the file opening
530 // until LyX is ready.
531 // FIXME UNICODE: FileName accept an utf8 encoded string.
532 LyX::ref().addFileToLoad(fromqstr(foe->file()));
534 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
535 qstring_to_ucs4(foe->file())));
541 return QApplication::event(e);
546 bool GuiApplication::notify(QObject * receiver, QEvent * event)
549 return QApplication::notify(receiver, event);
551 catch (ExceptionMessage const & e) {
554 LyX::cref().emergencyCleanup();
555 setQuitOnLastWindowClosed(false);
557 Alert::error(e.title_, e.details_);
559 // Properly crash in debug mode in order to get a useful backtrace.
562 // In release mode, try to exit gracefully.
565 case BufferException: {
566 Buffer * buf = current_view_->buffer();
567 docstring details = e.details_ + '\n';
568 details += theBufferList().emergencyWrite(buf);
569 theBufferList().release(buf);
570 details += "\n" + _("The current document was closed.");
571 Alert::error(e.title_, details);
574 case WarningException:
575 Alert::warning(e.title_, e.details_);
579 catch (exception const & e) {
580 docstring s = _("LyX has caught an exception, it will now "
581 "attempt to save all unsaved documents and exit."
583 s += from_ascii(e.what());
584 Alert::error(_("Software exception Detected"), s);
588 docstring s = _("LyX has caught some really weird exception, it will "
589 "now attempt to save all unsaved documents and exit.");
590 Alert::error(_("Software exception Detected"), s);
598 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
600 QColor const & qcol = color_cache_.get(col);
601 if (!qcol.isValid()) {
607 rgbcol.r = qcol.red();
608 rgbcol.g = qcol.green();
609 rgbcol.b = qcol.blue();
614 string const GuiApplication::hexName(ColorCode col)
616 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
620 void GuiApplication::updateColor(ColorCode)
622 // FIXME: Bleh, can't we just clear them all at once ?
623 color_cache_.clear();
627 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
629 SocketNotifier * sn = new SocketNotifier(this, fd, func);
630 socket_notifiers_[fd] = sn;
631 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
635 void GuiApplication::socketDataReceived(int fd)
637 socket_notifiers_[fd]->func_();
641 void GuiApplication::unregisterSocketCallback(int fd)
643 socket_notifiers_.erase(fd);
647 void GuiApplication::commitData(QSessionManager & sm)
649 /// The implementation is required to avoid an application exit
650 /// when session state save is triggered by session manager.
651 /// The default implementation sends a close event to all
652 /// visible top level widgets when session managment allows
654 /// We are changing that to close all wiew one by one.
655 /// FIXME: verify if the default implementation is enough now.
656 if (sm.allowsInteraction() && !closeAllViews())
661 void GuiApplication::addMenuTranslator()
663 installTranslator(new MenuTranslator(this));
667 bool GuiApplication::unregisterView(int id)
669 updateIds(views_, view_ids_);
670 LASSERT(views_.find(id) != views_.end(), /**/);
671 LASSERT(views_[id], /**/);
673 map<int, GuiView *>::iterator it;
674 for (it = views_.begin(); it != views_.end(); ++it) {
675 if (it->first == id) {
680 updateIds(views_, view_ids_);
685 bool GuiApplication::closeAllViews()
687 updateIds(views_, view_ids_);
691 map<int, GuiView*> const cmap = views_;
692 map<int, GuiView*>::const_iterator it;
693 for (it = cmap.begin(); it != cmap.end(); ++it) {
694 if (!it->second->close())
704 GuiView & GuiApplication::view(int id) const
706 LASSERT(views_.find(id) != views_.end(), /**/);
707 return *views_.find(id)->second;
711 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
713 vector<int>::const_iterator it = view_ids_.begin();
714 vector<int>::const_iterator const end = view_ids_.end();
715 for (; it != end; ++it)
716 view(*it).hideDialog(name, inset);
720 Buffer const * GuiApplication::updateInset(Inset const * inset) const
722 Buffer const * buffer_ = 0;
723 vector<int>::const_iterator it = view_ids_.begin();
724 vector<int>::const_iterator const end = view_ids_.end();
725 for (; it != end; ++it) {
726 Buffer const * ptr = view(*it).updateInset(inset);
734 void GuiApplication::readMenus(Lexer & lex)
740 bool GuiApplication::searchMenu(FuncRequest const & func,
741 vector<docstring> & names) const
743 return menus().searchMenu(func, names);
747 void GuiApplication::initGlobalMenu()
750 menus().fillMenuBar(global_menubar_, 0, true);
754 void GuiApplication::onLastWindowClosed()
757 global_menubar_->grabKeyboard();
761 ////////////////////////////////////////////////////////////////////////
763 // X11 specific stuff goes here...
766 bool GuiApplication::x11EventFilter(XEvent * xev)
772 case SelectionRequest: {
773 if (xev->xselectionrequest.selection != XA_PRIMARY)
775 LYXERR(Debug::GUI, "X requested selection.");
776 BufferView * bv = current_view_->view();
778 docstring const sel = bv->requestSelection();
784 case SelectionClear: {
785 if (xev->xselectionclear.selection != XA_PRIMARY)
787 LYXERR(Debug::GUI, "Lost selection.");
788 BufferView * bv = current_view_->view();
790 bv->clearSelection();
798 } // namespace frontend
801 void hideDialogs(std::string const & name, Inset * inset)
804 theApp()->hideDialogs(name, inset);
808 ////////////////////////////////////////////////////////////////////
812 ////////////////////////////////////////////////////////////////////
814 frontend::FontLoader & theFontLoader()
816 LASSERT(frontend::guiApp, /**/);
817 return frontend::guiApp->fontLoader();
821 frontend::FontMetrics const & theFontMetrics(Font const & f)
823 return theFontMetrics(f.fontInfo());
827 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
829 LASSERT(frontend::guiApp, /**/);
830 return frontend::guiApp->fontLoader().metrics(f);
834 ////////////////////////////////////////////////////////////////////
838 ////////////////////////////////////////////////////////////////////
840 frontend::Clipboard & theClipboard()
842 LASSERT(frontend::guiApp, /**/);
843 return frontend::guiApp->clipboard();
847 frontend::Selection & theSelection()
849 LASSERT(frontend::guiApp, /**/);
850 return frontend::guiApp->selection();
855 #include "GuiApplication_moc.cpp"