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/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/FileName.h"
42 #include "support/ForkedCalls.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45 #include "support/os.h"
46 #include "support/Package.h"
48 #include <QApplication>
51 #include <QFileOpenEvent>
53 #include <QLibraryInfo>
55 #include <QPixmapCache>
57 #include <QSessionManager>
58 #include <QSocketNotifier>
61 #include <QTranslator>
65 #include <X11/Xatom.h>
71 #include <boost/bind.hpp>
76 using namespace lyx::support;
80 frontend::Application * createApplication(int & argc, char * argv[])
82 return new frontend::GuiApplication(argc, argv);
88 class SocketNotifier : public QSocketNotifier
91 /// connect a connection notification from the LyXServerSocket
92 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
93 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
97 /// The callback function
98 Application::SocketCallback func_;
102 ////////////////////////////////////////////////////////////////////////
103 // Mac specific stuff goes here...
105 class MenuTranslator : public QTranslator
108 MenuTranslator(QObject * parent)
109 : QTranslator(parent)
112 QString translate(const char * /*context*/,
113 const char * sourceText,
114 const char * /*comment*/ = 0)
116 string const s = sourceText;
117 if (s == N_("About %1") || s == N_("Preferences")
118 || s == N_("Reconfigure") || s == N_("Quit %1"))
125 class GlobalMenuBar : public QMenuBar
129 GlobalMenuBar() : QMenuBar(0) {}
132 bool event(QEvent * e)
134 if (e->type() == QEvent::ShortcutOverride) {
135 // && activeWindow() == 0) {
136 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
138 setKeySymbol(&sym, ke);
139 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
147 ///////////////////////////////////////////////////////////////
148 // You can find more platform specific stuff
149 // at the end of this file...
150 ///////////////////////////////////////////////////////////////
153 GuiApplication * guiApp;
156 GuiApplication::GuiApplication(int & argc, char ** argv)
157 : QApplication(argc, argv), Application(), current_view_(0), global_menubar_(0)
159 QString app_name = "LyX";
160 QCoreApplication::setOrganizationName(app_name);
161 QCoreApplication::setOrganizationDomain("lyx.org");
162 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
164 // FIXME: quitOnLastWindowClosed is true by default. We should have a
165 // lyxrc setting for this in order to let the application stay resident.
166 // But then we need some kind of dock icon, at least on Windows.
168 if (lyxrc.quit_on_last_window_closed)
169 setQuitOnLastWindowClosed(false);
172 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
173 // seems to be the default case for applications like LyX.
174 setQuitOnLastWindowClosed(false);
178 // doubleClickInterval() is 400 ms on X11 which is just too long.
179 // On Windows and Mac OS X, the operating system's value is used.
180 // On Microsoft Windows, calling this function sets the double
181 // click interval for all applications. So we don't!
182 QApplication::setDoubleClickInterval(300);
185 // install translation file for Qt built-in dialogs
186 QString language_name = QString("qt_") + QLocale::system().name();
188 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
189 // Short-named translator can be loaded from a long name, but not the
190 // opposite. Therefore, long name should be used without truncation.
191 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
192 if (qt_trans_.load(language_name,
193 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
195 installTranslator(&qt_trans_);
196 // even if the language calls for RtL, don't do that
197 setLayoutDirection(Qt::LeftToRight);
198 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
199 << fromqstr(language_name));
201 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
202 << fromqstr(language_name));
205 // This allows to translate the strings that appear in the LyX menu.
208 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
210 using namespace lyx::graphics;
212 Image::newImage = boost::bind(&GuiImage::newImage);
213 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
215 // needs to be done before reading lyxrc
217 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
221 // Set the cache to 5120 kilobytes which corresponds to screen size of
222 // 1280 by 1024 pixels with a color depth of 32 bits.
223 QPixmapCache::setCacheLimit(5120);
225 // Initialize RC Fonts
226 if (lyxrc.roman_font_name.empty())
227 lyxrc.roman_font_name = fromqstr(romanFontName());
229 if (lyxrc.sans_font_name.empty())
230 lyxrc.sans_font_name = fromqstr(sansFontName());
232 if (lyxrc.typewriter_font_name.empty())
233 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
235 general_timer_.setInterval(500);
236 connect(&general_timer_, SIGNAL(timeout()),
237 this, SLOT(handleRegularEvents()));
238 general_timer_.start();
241 if (global_menubar_ == 0) {
242 // Create the global default menubar which is shown for the dialogs
243 // and if no GuiView is visible.
244 global_menubar_ = new GlobalMenuBar();
250 GuiApplication::~GuiApplication()
252 socket_notifiers_.clear();
256 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
263 case LFUN_WINDOW_CLOSE:
264 enable = view_ids_.size() > 0;
268 if (!current_view_) {
281 bool GuiApplication::dispatch(FuncRequest const & cmd)
285 case LFUN_WINDOW_NEW:
286 createView(toqstr(cmd.argument()));
289 case LFUN_WINDOW_CLOSE:
290 // update bookmark pit of the current buffer before window close
291 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
292 theLyXFunc().gotoBookmark(i+1, false, false);
293 current_view_->close();
297 // quitting is triggered by the gui code
298 // (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();
461 void GuiApplication::restoreGuiSession()
463 if (!lyxrc.load_session)
466 Session & session = LyX::ref().session();
467 vector<FileName> const & lastopened = session.lastOpened().getfiles();
468 // do not add to the lastfile list since these files are restored from
469 // last session, and should be already there (regular files), or should
470 // not be added at all (help files).
471 for_each(lastopened.begin(), lastopened.end(),
472 bind(&GuiView::loadDocument, current_view_, _1, false));
474 // clear this list to save a few bytes of RAM
475 session.lastOpened().clear();
479 QString const GuiApplication::romanFontName()
482 font.setKerning(false);
483 font.setStyleHint(QFont::Serif);
484 font.setFamily("serif");
486 return QFontInfo(font).family();
490 QString const GuiApplication::sansFontName()
493 font.setKerning(false);
494 font.setStyleHint(QFont::SansSerif);
495 font.setFamily("sans");
497 return QFontInfo(font).family();
501 QString const GuiApplication::typewriterFontName()
504 font.setKerning(false);
505 font.setStyleHint(QFont::TypeWriter);
506 font.setFamily("monospace");
508 return QFontInfo(font).family();
512 void GuiApplication::handleRegularEvents()
514 ForkedCallsController::handleCompletedProcesses();
518 bool GuiApplication::event(QEvent * e)
521 case QEvent::FileOpen: {
522 // Open a file; this happens only on Mac OS X for now
523 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
525 if (!current_view_ || !current_view_->view())
526 // The application is not properly initialized yet.
527 // So we acknowledge the event and delay the file opening
528 // until LyX is ready.
529 // FIXME UNICODE: FileName accept an utf8 encoded string.
530 LyX::ref().addFileToLoad(fromqstr(foe->file()));
532 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
533 qstring_to_ucs4(foe->file())));
539 return QApplication::event(e);
544 bool GuiApplication::notify(QObject * receiver, QEvent * event)
547 return QApplication::notify(receiver, event);
549 catch (ExceptionMessage const & e) {
552 LyX::cref().emergencyCleanup();
553 setQuitOnLastWindowClosed(false);
555 Alert::error(e.title_, e.details_);
557 // Properly crash in debug mode in order to get a useful backtrace.
560 // In release mode, try to exit gracefully.
563 case BufferException: {
564 Buffer * buf = current_view_->buffer();
565 docstring details = e.details_ + '\n';
566 details += theBufferList().emergencyWrite(buf);
567 theBufferList().release(buf);
568 details += _("\nThe current document was closed.");
569 Alert::error(e.title_, details);
572 case WarningException:
573 Alert::warning(e.title_, e.details_);
577 catch (exception const & e) {
578 docstring s = _("LyX has caught an exception, it will now "
579 "attempt to save all unsaved documents and exit."
581 s += from_ascii(e.what());
582 Alert::error(_("Software exception Detected"), s);
586 docstring s = _("LyX has caught some really weird exception, it will "
587 "now attempt to save all unsaved documents and exit.");
588 Alert::error(_("Software exception Detected"), s);
596 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
598 QColor const & qcol = color_cache_.get(col);
599 if (!qcol.isValid()) {
605 rgbcol.r = qcol.red();
606 rgbcol.g = qcol.green();
607 rgbcol.b = qcol.blue();
612 string const GuiApplication::hexName(ColorCode col)
614 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
618 void GuiApplication::updateColor(ColorCode)
620 // FIXME: Bleh, can't we just clear them all at once ?
621 color_cache_.clear();
625 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
627 SocketNotifier * sn = new SocketNotifier(this, fd, func);
628 socket_notifiers_[fd] = sn;
629 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
633 void GuiApplication::socketDataReceived(int fd)
635 socket_notifiers_[fd]->func_();
639 void GuiApplication::unregisterSocketCallback(int fd)
641 socket_notifiers_.erase(fd);
645 void GuiApplication::commitData(QSessionManager & sm)
647 /// The implementation is required to avoid an application exit
648 /// when session state save is triggered by session manager.
649 /// The default implementation sends a close event to all
650 /// visible top level widgets when session managment allows
652 /// We are changing that to close all wiew one by one.
653 /// FIXME: verify if the default implementation is enough now.
654 if (sm.allowsInteraction() && !closeAllViews())
659 void GuiApplication::addMenuTranslator()
661 installTranslator(new MenuTranslator(this));
665 bool GuiApplication::unregisterView(int id)
667 updateIds(views_, view_ids_);
668 BOOST_ASSERT(views_.find(id) != views_.end());
669 BOOST_ASSERT(views_[id]);
671 map<int, GuiView *>::iterator it;
672 for (it = views_.begin(); it != views_.end(); ++it) {
673 if (it->first == id) {
678 updateIds(views_, view_ids_);
683 bool GuiApplication::closeAllViews()
685 updateIds(views_, view_ids_);
689 map<int, GuiView*> const cmap = views_;
690 map<int, GuiView*>::const_iterator it;
691 for (it = cmap.begin(); it != cmap.end(); ++it) {
692 if (!it->second->close())
702 GuiView & GuiApplication::view(int id) const
704 BOOST_ASSERT(views_.find(id) != views_.end());
705 return *views_.find(id)->second;
709 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
711 vector<int>::const_iterator it = view_ids_.begin();
712 vector<int>::const_iterator const end = view_ids_.end();
713 for (; it != end; ++it)
714 view(*it).hideDialog(name, inset);
718 Buffer const * GuiApplication::updateInset(Inset const * inset) const
720 Buffer const * buffer_ = 0;
721 vector<int>::const_iterator it = view_ids_.begin();
722 vector<int>::const_iterator const end = view_ids_.end();
723 for (; it != end; ++it) {
724 Buffer const * ptr = view(*it).updateInset(inset);
732 void GuiApplication::readMenus(Lexer & lex)
738 bool GuiApplication::searchMenu(FuncRequest const & func,
739 vector<docstring> & names) const
741 return menus().searchMenu(func, names);
745 void GuiApplication::initGlobalMenu()
748 menus().fillMenuBar(global_menubar_, 0);
752 void GuiApplication::onLastWindowClosed()
755 global_menubar_->grabKeyboard();
758 ////////////////////////////////////////////////////////////////////////
759 // X11 specific stuff goes here...
761 bool GuiApplication::x11EventFilter(XEvent * xev)
767 case SelectionRequest: {
768 if (xev->xselectionrequest.selection != XA_PRIMARY)
770 LYXERR(Debug::GUI, "X requested selection.");
771 BufferView * bv = current_view_->view();
773 docstring const sel = bv->requestSelection();
779 case SelectionClear: {
780 if (xev->xselectionclear.selection != XA_PRIMARY)
782 LYXERR(Debug::GUI, "Lost selection.");
783 BufferView * bv = current_view_->view();
785 bv->clearSelection();
793 } // namespace frontend
796 ////////////////////////////////////////////////////////////////////
800 ////////////////////////////////////////////////////////////////////
802 frontend::FontLoader & theFontLoader()
804 BOOST_ASSERT(frontend::guiApp);
805 return frontend::guiApp->fontLoader();
809 frontend::FontMetrics const & theFontMetrics(Font const & f)
811 return theFontMetrics(f.fontInfo());
815 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
817 BOOST_ASSERT(frontend::guiApp);
818 return frontend::guiApp->fontLoader().metrics(f);
822 frontend::Clipboard & theClipboard()
824 BOOST_ASSERT(frontend::guiApp);
825 return frontend::guiApp->clipboard();
829 frontend::Selection & theSelection()
831 BOOST_ASSERT(frontend::guiApp);
832 return frontend::guiApp->selection();
837 #include "GuiApplication_moc.cpp"