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);
475 language_model_->sort(0);
479 void GuiApplication::restoreGuiSession()
481 if (!lyxrc.load_session)
484 Session & session = LyX::ref().session();
485 vector<FileName> const & lastopened = session.lastOpened().getfiles();
486 // do not add to the lastfile list since these files are restored from
487 // last session, and should be already there (regular files), or should
488 // not be added at all (help files).
489 for_each(lastopened.begin(), lastopened.end(),
490 bind(&GuiView::loadDocument, current_view_, _1, false));
492 // clear this list to save a few bytes of RAM
493 session.lastOpened().clear();
497 QString const GuiApplication::romanFontName()
500 font.setKerning(false);
501 font.setStyleHint(QFont::Serif);
502 font.setFamily("serif");
504 return QFontInfo(font).family();
508 QString const GuiApplication::sansFontName()
511 font.setKerning(false);
512 font.setStyleHint(QFont::SansSerif);
513 font.setFamily("sans");
515 return QFontInfo(font).family();
519 QString const GuiApplication::typewriterFontName()
522 font.setKerning(false);
523 font.setStyleHint(QFont::TypeWriter);
524 font.setFamily("monospace");
526 return QFontInfo(font).family();
530 void GuiApplication::handleRegularEvents()
532 ForkedCallsController::handleCompletedProcesses();
536 bool GuiApplication::event(QEvent * e)
539 case QEvent::FileOpen: {
540 // Open a file; this happens only on Mac OS X for now
541 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
543 if (!current_view_ || !current_view_->view())
544 // The application is not properly initialized yet.
545 // So we acknowledge the event and delay the file opening
546 // until LyX is ready.
547 // FIXME UNICODE: FileName accept an utf8 encoded string.
548 LyX::ref().addFileToLoad(fromqstr(foe->file()));
550 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
551 qstring_to_ucs4(foe->file())));
557 return QApplication::event(e);
562 bool GuiApplication::notify(QObject * receiver, QEvent * event)
565 return QApplication::notify(receiver, event);
567 catch (ExceptionMessage const & e) {
570 LyX::cref().emergencyCleanup();
571 setQuitOnLastWindowClosed(false);
573 Alert::error(e.title_, e.details_);
575 // Properly crash in debug mode in order to get a useful backtrace.
578 // In release mode, try to exit gracefully.
581 case BufferException: {
582 Buffer * buf = current_view_->buffer();
583 docstring details = e.details_ + '\n';
584 details += theBufferList().emergencyWrite(buf);
585 theBufferList().release(buf);
586 details += "\n" + _("The current document was closed.");
587 Alert::error(e.title_, details);
590 case WarningException:
591 Alert::warning(e.title_, e.details_);
595 catch (exception const & e) {
596 docstring s = _("LyX has caught an exception, it will now "
597 "attempt to save all unsaved documents and exit."
599 s += from_ascii(e.what());
600 Alert::error(_("Software exception Detected"), s);
604 docstring s = _("LyX has caught some really weird exception, it will "
605 "now attempt to save all unsaved documents and exit.");
606 Alert::error(_("Software exception Detected"), s);
614 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
616 QColor const & qcol = color_cache_.get(col);
617 if (!qcol.isValid()) {
623 rgbcol.r = qcol.red();
624 rgbcol.g = qcol.green();
625 rgbcol.b = qcol.blue();
630 string const GuiApplication::hexName(ColorCode col)
632 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
636 void GuiApplication::updateColor(ColorCode)
638 // FIXME: Bleh, can't we just clear them all at once ?
639 color_cache_.clear();
643 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
645 SocketNotifier * sn = new SocketNotifier(this, fd, func);
646 socket_notifiers_[fd] = sn;
647 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
651 void GuiApplication::socketDataReceived(int fd)
653 socket_notifiers_[fd]->func_();
657 void GuiApplication::unregisterSocketCallback(int fd)
659 socket_notifiers_.erase(fd);
663 void GuiApplication::commitData(QSessionManager & sm)
665 /// The implementation is required to avoid an application exit
666 /// when session state save is triggered by session manager.
667 /// The default implementation sends a close event to all
668 /// visible top level widgets when session managment allows
670 /// We are changing that to close all wiew one by one.
671 /// FIXME: verify if the default implementation is enough now.
672 if (sm.allowsInteraction() && !closeAllViews())
677 void GuiApplication::addMenuTranslator()
679 installTranslator(new MenuTranslator(this));
683 bool GuiApplication::unregisterView(int id)
685 updateIds(views_, view_ids_);
686 LASSERT(views_.find(id) != views_.end(), /**/);
687 LASSERT(views_[id], /**/);
689 map<int, GuiView *>::iterator it;
690 for (it = views_.begin(); it != views_.end(); ++it) {
691 if (it->first == id) {
696 updateIds(views_, view_ids_);
701 bool GuiApplication::closeAllViews()
703 updateIds(views_, view_ids_);
707 map<int, GuiView*> const cmap = views_;
708 map<int, GuiView*>::const_iterator it;
709 for (it = cmap.begin(); it != cmap.end(); ++it) {
710 if (!it->second->close())
720 GuiView & GuiApplication::view(int id) const
722 LASSERT(views_.find(id) != views_.end(), /**/);
723 return *views_.find(id)->second;
727 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
729 vector<int>::const_iterator it = view_ids_.begin();
730 vector<int>::const_iterator const end = view_ids_.end();
731 for (; it != end; ++it)
732 view(*it).hideDialog(name, inset);
736 Buffer const * GuiApplication::updateInset(Inset const * inset) const
738 Buffer const * buffer_ = 0;
739 vector<int>::const_iterator it = view_ids_.begin();
740 vector<int>::const_iterator const end = view_ids_.end();
741 for (; it != end; ++it) {
742 Buffer const * ptr = view(*it).updateInset(inset);
750 void GuiApplication::readMenus(Lexer & lex)
756 bool GuiApplication::searchMenu(FuncRequest const & func,
757 vector<docstring> & names) const
759 return menus().searchMenu(func, names);
763 void GuiApplication::initGlobalMenu()
766 menus().fillMenuBar(global_menubar_, 0, true);
770 void GuiApplication::onLastWindowClosed()
773 global_menubar_->grabKeyboard();
777 ////////////////////////////////////////////////////////////////////////
779 // X11 specific stuff goes here...
782 bool GuiApplication::x11EventFilter(XEvent * xev)
788 case SelectionRequest: {
789 if (xev->xselectionrequest.selection != XA_PRIMARY)
791 LYXERR(Debug::GUI, "X requested selection.");
792 BufferView * bv = current_view_->view();
794 docstring const sel = bv->requestSelection();
800 case SelectionClear: {
801 if (xev->xselectionclear.selection != XA_PRIMARY)
803 LYXERR(Debug::GUI, "Lost selection.");
804 BufferView * bv = current_view_->view();
806 bv->clearSelection();
814 } // namespace frontend
817 void hideDialogs(std::string const & name, Inset * inset)
820 theApp()->hideDialogs(name, inset);
824 ////////////////////////////////////////////////////////////////////
828 ////////////////////////////////////////////////////////////////////
830 frontend::FontLoader & theFontLoader()
832 LASSERT(frontend::guiApp, /**/);
833 return frontend::guiApp->fontLoader();
837 frontend::FontMetrics const & theFontMetrics(Font const & f)
839 return theFontMetrics(f.fontInfo());
843 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
845 LASSERT(frontend::guiApp, /**/);
846 return frontend::guiApp->fontLoader().metrics(f);
850 ////////////////////////////////////////////////////////////////////
854 ////////////////////////////////////////////////////////////////////
856 frontend::Clipboard & theClipboard()
858 LASSERT(frontend::guiApp, /**/);
859 return frontend::guiApp->clipboard();
863 frontend::Selection & theSelection()
865 LASSERT(frontend::guiApp, /**/);
866 return frontend::guiApp->selection();
871 #include "GuiApplication_moc.cpp"