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"
21 #include "frontends/alert.h"
22 #include "frontends/Application.h"
23 #include "frontends/FontLoader.h"
24 #include "frontends/FontMetrics.h"
27 #include "BufferList.h"
28 #include "BufferView.h"
30 #include "FuncRequest.h"
31 #include "FuncStatus.h"
38 #include "support/debug.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/FileName.h"
41 #include "support/ForkedCalls.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/os.h"
45 #include "support/Package.h"
47 #include <QApplication>
50 #include <QFileOpenEvent>
52 #include <QLibraryInfo>
54 #include <QPixmapCache>
56 #include <QSessionManager>
57 #include <QSocketNotifier>
60 #include <QTranslator>
64 #include <X11/Xatom.h>
70 #include <boost/bind.hpp>
75 using namespace lyx::support;
79 frontend::Application * createApplication(int & argc, char * argv[])
81 return new frontend::GuiApplication(argc, argv);
87 class SocketNotifier : public QSocketNotifier
90 /// connect a connection notification from the LyXServerSocket
91 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
92 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
96 /// The callback function
97 Application::SocketCallback func_;
101 ////////////////////////////////////////////////////////////////////////
102 // Mac specific stuff goes here...
104 class MenuTranslator : public QTranslator
107 MenuTranslator(QObject * parent)
108 : QTranslator(parent)
111 QString translate(const char * /*context*/,
112 const char * sourceText,
113 const char * /*comment*/ = 0)
115 string const s = sourceText;
116 if (s == N_("About %1") || s == N_("Preferences")
117 || s == N_("Reconfigure") || s == N_("Quit %1"))
125 ///////////////////////////////////////////////////////////////
126 // You can find more platform specific stuff
127 // at the end of this file...
128 ///////////////////////////////////////////////////////////////
131 GuiApplication * guiApp;
134 GuiApplication::GuiApplication(int & argc, char ** argv)
135 : QApplication(argc, argv), Application(), current_view_(0)
137 QString app_name = "LyX";
138 QCoreApplication::setOrganizationName(app_name);
139 QCoreApplication::setOrganizationDomain("lyx.org");
140 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
142 //FIXME: quitOnLastWindowClosed is true by default, at least on Windows and
143 // X11 platforms. We should have a lyxrc setting for this in order to let the
144 // application stay resident.
146 if (lyxrc.quit_on_last_window_closed)
147 setQuitOnLastWindowClosed(false);
151 // doubleClickInterval() is 400 ms on X11 which is just too long.
152 // On Windows and Mac OS X, the operating system's value is used.
153 // On Microsoft Windows, calling this function sets the double
154 // click interval for all applications. So we don't!
155 QApplication::setDoubleClickInterval(300);
158 // install translation file for Qt built-in dialogs
159 QString language_name = QString("qt_") + QLocale::system().name();
161 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
162 // Short-named translator can be loaded from a long name, but not the
163 // opposite. Therefore, long name should be used without truncation.
164 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
165 if (qt_trans_.load(language_name,
166 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
168 installTranslator(&qt_trans_);
169 // even if the language calls for RtL, don't do that
170 setLayoutDirection(Qt::LeftToRight);
171 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
172 << fromqstr(language_name));
174 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
175 << fromqstr(language_name));
178 // all windows in a Mac application share the same menu bar.
179 QMenuBar *menuBar = new QMenuBar(0);
180 // This allows to translate the strings that appear in the LyX menu.
184 using namespace lyx::graphics;
186 Image::newImage = boost::bind(&GuiImage::newImage);
187 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
189 // needs to be done before reading lyxrc
191 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
195 // Set the cache to 5120 kilobytes which corresponds to screen size of
196 // 1280 by 1024 pixels with a color depth of 32 bits.
197 QPixmapCache::setCacheLimit(5120);
199 // Initialize RC Fonts
200 if (lyxrc.roman_font_name.empty())
201 lyxrc.roman_font_name = fromqstr(romanFontName());
203 if (lyxrc.sans_font_name.empty())
204 lyxrc.sans_font_name = fromqstr(sansFontName());
206 if (lyxrc.typewriter_font_name.empty())
207 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
209 general_timer_.setInterval(500);
210 connect(&general_timer_, SIGNAL(timeout()),
211 this, SLOT(handleRegularEvents()));
212 general_timer_.start();
216 GuiApplication::~GuiApplication()
218 socket_notifiers_.clear();
222 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
229 case LFUN_WINDOW_CLOSE:
230 enable = view_ids_.size() > 0;
234 if (!current_view_) {
247 bool GuiApplication::dispatch(FuncRequest const & cmd)
251 case LFUN_WINDOW_NEW:
252 createView(toqstr(cmd.argument()));
255 case LFUN_WINDOW_CLOSE:
256 // update bookmark pit of the current buffer before window close
257 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
258 theLyXFunc().gotoBookmark(i+1, false, false);
259 current_view_->close();
263 // quitting is triggered by the gui code
264 // (leaving the event loop).
265 current_view_->message(from_utf8(N_("Exiting.")));
270 case LFUN_SCREEN_FONT_UPDATE: {
271 // handle the screen font changes.
272 font_loader_.update();
273 // Backup current_view_
274 GuiView * view = current_view_;
275 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
276 // to skip the refresh.
278 BufferList::iterator it = theBufferList().begin();
279 BufferList::iterator const end = theBufferList().end();
280 for (; it != end; ++it)
282 // Restore current_view_
283 current_view_ = view;
287 case LFUN_BUFFER_NEW:
289 || (!lyxrc.single_window && current_view_->buffer() != 0))
291 current_view_->newDocument(to_utf8(cmd.argument()), false);
294 case LFUN_BUFFER_NEW_TEMPLATE:
296 || (!lyxrc.single_window && current_view_->buffer() != 0)) {
298 current_view_->newDocument(to_utf8(cmd.argument()), true);
299 if (!current_view_->buffer())
300 current_view_->close();
302 current_view_->newDocument(to_utf8(cmd.argument()), true);
307 || (!lyxrc.single_window && current_view_->buffer() != 0)) {
309 current_view_->openDocument(to_utf8(cmd.argument()));
310 if (!current_view_->buffer())
311 current_view_->close();
313 current_view_->openDocument(to_utf8(cmd.argument()));
317 // Notify the caller that the action has not been dispatched.
321 // The action has been dispatched.
326 void GuiApplication::resetGui()
328 map<int, GuiView *>::iterator it;
329 for (it = views_.begin(); it != views_.end(); ++it)
330 it->second->resetDialogs();
332 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
336 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
339 map<int, GuiView *>::const_iterator it;
340 for (it = stdmap.begin(); it != stdmap.end(); ++it)
341 ids.push_back(it->first);
345 void GuiApplication::createView(QString const & geometry_arg)
348 updateIds(views_, view_ids_);
350 while (views_.find(id) != views_.end())
352 GuiView * view = new GuiView(id);
354 // copy the icon size from old view
356 view->setIconSize(current_view_->iconSize());
360 updateIds(views_, view_ids_);
362 theLyXFunc().setLyXView(view);
364 if (!geometry_arg.isEmpty()) {
368 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
369 re.indexIn(geometry_arg);
370 w = re.cap(1).toInt();
371 h = re.cap(2).toInt();
372 x = re.cap(3).toInt();
373 y = re.cap(4).toInt();
374 view->setGeometry(x, y, w, h);
378 setActiveWindow(view);
379 setCurrentView(*view);
385 Clipboard & GuiApplication::clipboard()
391 Selection & GuiApplication::selection()
397 int GuiApplication::exec()
399 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
400 return QApplication::exec();
404 void GuiApplication::exit(int status)
406 QApplication::exit(status);
410 void GuiApplication::execBatchCommands()
412 LyX::ref().execBatchCommands();
416 void GuiApplication::restoreGuiSession()
418 if (!lyxrc.load_session)
421 Session & session = LyX::ref().session();
422 vector<FileName> const & lastopened = session.lastOpened().getfiles();
423 // do not add to the lastfile list since these files are restored from
424 // last session, and should be already there (regular files), or should
425 // not be added at all (help files).
426 for_each(lastopened.begin(), lastopened.end(),
427 bind(&GuiView::loadDocument, current_view_, _1, false));
429 // clear this list to save a few bytes of RAM
430 session.lastOpened().clear();
434 QString const GuiApplication::romanFontName()
437 font.setKerning(false);
438 font.setStyleHint(QFont::Serif);
439 font.setFamily("serif");
441 return QFontInfo(font).family();
445 QString const GuiApplication::sansFontName()
448 font.setKerning(false);
449 font.setStyleHint(QFont::SansSerif);
450 font.setFamily("sans");
452 return QFontInfo(font).family();
456 QString const GuiApplication::typewriterFontName()
459 font.setKerning(false);
460 font.setStyleHint(QFont::TypeWriter);
461 font.setFamily("monospace");
463 return QFontInfo(font).family();
467 void GuiApplication::handleRegularEvents()
469 ForkedCallsController::handleCompletedProcesses();
473 bool GuiApplication::event(QEvent * e)
476 case QEvent::FileOpen: {
477 // Open a file; this happens only on Mac OS X for now
478 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
480 if (!current_view_ || !current_view_->view())
481 // The application is not properly initialized yet.
482 // So we acknowledge the event and delay the file opening
483 // until LyX is ready.
484 // FIXME UNICODE: FileName accept an utf8 encoded string.
485 LyX::ref().addFileToLoad(fromqstr(foe->file()));
487 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
488 qstring_to_ucs4(foe->file())));
494 return QApplication::event(e);
499 bool GuiApplication::notify(QObject * receiver, QEvent * event)
502 return QApplication::notify(receiver, event);
504 catch (ExceptionMessage const & e) {
507 LyX::cref().emergencyCleanup();
508 setQuitOnLastWindowClosed(false);
510 Alert::error(e.title_, e.details_);
512 // Properly crash in debug mode in order to get a useful backtrace.
515 // In release mode, try to exit gracefully.
518 case BufferException: {
519 Buffer * buf = current_view_->buffer();
520 docstring details = e.details_ + '\n';
521 details += theBufferList().emergencyWrite(buf);
522 theBufferList().release(buf);
523 details += _("\nThe current document was closed.");
524 Alert::error(e.title_, details);
527 case WarningException:
528 Alert::warning(e.title_, e.details_);
532 catch (exception const & e) {
533 docstring s = _("LyX has caught an exception, it will now "
534 "attempt to save all unsaved documents and exit."
536 s += from_ascii(e.what());
537 Alert::error(_("Software exception Detected"), s);
541 docstring s = _("LyX has caught some really weird exception, it will "
542 "now attempt to save all unsaved documents and exit.");
543 Alert::error(_("Software exception Detected"), s);
551 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
553 QColor const & qcol = color_cache_.get(col);
554 if (!qcol.isValid()) {
560 rgbcol.r = qcol.red();
561 rgbcol.g = qcol.green();
562 rgbcol.b = qcol.blue();
567 string const GuiApplication::hexName(ColorCode col)
569 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
573 void GuiApplication::updateColor(ColorCode)
575 // FIXME: Bleh, can't we just clear them all at once ?
576 color_cache_.clear();
580 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
582 SocketNotifier * sn = new SocketNotifier(this, fd, func);
583 socket_notifiers_[fd] = sn;
584 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
588 void GuiApplication::socketDataReceived(int fd)
590 socket_notifiers_[fd]->func_();
594 void GuiApplication::unregisterSocketCallback(int fd)
596 socket_notifiers_.erase(fd);
600 void GuiApplication::commitData(QSessionManager & sm)
602 /// The implementation is required to avoid an application exit
603 /// when session state save is triggered by session manager.
604 /// The default implementation sends a close event to all
605 /// visible top level widgets when session managment allows
607 /// We are changing that to close all wiew one by one.
608 /// FIXME: verify if the default implementation is enough now.
609 if (sm.allowsInteraction() && !closeAllViews())
614 void GuiApplication::addMenuTranslator()
616 installTranslator(new MenuTranslator(this));
620 bool GuiApplication::unregisterView(int id)
622 updateIds(views_, view_ids_);
623 BOOST_ASSERT(views_.find(id) != views_.end());
624 BOOST_ASSERT(views_[id]);
626 map<int, GuiView *>::iterator it;
627 for (it = views_.begin(); it != views_.end(); ++it) {
628 if (it->first == id) {
633 updateIds(views_, view_ids_);
638 bool GuiApplication::closeAllViews()
640 updateIds(views_, view_ids_);
644 map<int, GuiView*> const cmap = views_;
645 map<int, GuiView*>::const_iterator it;
646 for (it = cmap.begin(); it != cmap.end(); ++it) {
647 if (!it->second->close())
657 GuiView & GuiApplication::view(int id) const
659 BOOST_ASSERT(views_.find(id) != views_.end());
660 return *views_.find(id)->second;
664 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
666 vector<int>::const_iterator it = view_ids_.begin();
667 vector<int>::const_iterator const end = view_ids_.end();
668 for (; it != end; ++it)
669 view(*it).hideDialog(name, inset);
673 Buffer const * GuiApplication::updateInset(Inset const * inset) const
675 Buffer const * buffer_ = 0;
676 vector<int>::const_iterator it = view_ids_.begin();
677 vector<int>::const_iterator const end = view_ids_.end();
678 for (; it != end; ++it) {
679 Buffer const * ptr = view(*it).updateInset(inset);
687 void GuiApplication::readMenus(Lexer & lex)
693 bool GuiApplication::searchMenu(FuncRequest const & func,
694 vector<docstring> & names) const
696 return menus().searchMenu(func, names);
700 ////////////////////////////////////////////////////////////////////////
701 // X11 specific stuff goes here...
703 bool GuiApplication::x11EventFilter(XEvent * xev)
709 case SelectionRequest: {
710 if (xev->xselectionrequest.selection != XA_PRIMARY)
712 LYXERR(Debug::GUI, "X requested selection.");
713 BufferView * bv = current_view_->view();
715 docstring const sel = bv->requestSelection();
721 case SelectionClear: {
722 if (xev->xselectionclear.selection != XA_PRIMARY)
724 LYXERR(Debug::GUI, "Lost selection.");
725 BufferView * bv = current_view_->view();
727 bv->clearSelection();
735 } // namespace frontend
738 ////////////////////////////////////////////////////////////////////
742 ////////////////////////////////////////////////////////////////////
744 frontend::FontLoader & theFontLoader()
746 BOOST_ASSERT(frontend::guiApp);
747 return frontend::guiApp->fontLoader();
751 frontend::FontMetrics const & theFontMetrics(Font const & f)
753 return theFontMetrics(f.fontInfo());
757 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
759 BOOST_ASSERT(frontend::guiApp);
760 return frontend::guiApp->fontLoader().metrics(f);
764 frontend::Clipboard & theClipboard()
766 BOOST_ASSERT(frontend::guiApp);
767 return frontend::guiApp->clipboard();
771 frontend::Selection & theSelection()
773 BOOST_ASSERT(frontend::guiApp);
774 return frontend::guiApp->selection();
779 #include "GuiApplication_moc.cpp"