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/NoGuiFontLoader.h"
24 #include "frontends/NoGuiFontMetrics.h"
25 #include "frontends/FontLoader.h"
26 #include "frontends/FontMetrics.h"
28 #include "support/ExceptionMessage.h"
29 #include "support/FileName.h"
30 #include "support/ForkedCalls.h"
31 #include "support/lstrings.h"
32 #include "support/os.h"
33 #include "support/Package.h"
36 #include "BufferList.h"
37 #include "BufferView.h"
38 #include "support/debug.h"
40 #include "FuncRequest.h"
41 #include "FuncStatus.h"
42 #include "support/gettext.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"))
127 ///////////////////////////////////////////////////////////////
128 // You can find more platform specific stuff
129 // at the end of this file...
130 ///////////////////////////////////////////////////////////////
133 GuiApplication * guiApp;
136 GuiApplication::GuiApplication(int & argc, char ** argv)
137 : QApplication(argc, argv), Application(), current_view_(0)
139 QString app_name = "LyX";
140 QCoreApplication::setOrganizationName(app_name);
141 QCoreApplication::setOrganizationDomain("lyx.org");
142 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
144 // Qt bug? setQuitOnLastWindowClosed(true); does not work
145 setQuitOnLastWindowClosed(false);
148 // doubleClickInterval() is 400 ms on X11 which is just too long.
149 // On Windows and Mac OS X, the operating system's value is used.
150 // On Microsoft Windows, calling this function sets the double
151 // click interval for all applications. So we don't!
152 QApplication::setDoubleClickInterval(300);
155 // install translation file for Qt built-in dialogs
156 QString language_name = QString("qt_") + QLocale::system().name();
158 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
159 // Short-named translator can be loaded from a long name, but not the
160 // opposite. Therefore, long name should be used without truncation.
161 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
162 if (qt_trans_.load(language_name,
163 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
165 installTranslator(&qt_trans_);
166 // even if the language calls for RtL, don't do that
167 setLayoutDirection(Qt::LeftToRight);
168 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
169 << fromqstr(language_name));
171 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
172 << fromqstr(language_name));
175 // all windows in a Mac application share the same menu bar.
176 QMenuBar *menuBar = new QMenuBar(0);
177 // This allows to translate the strings that appear in the LyX menu.
181 using namespace lyx::graphics;
183 Image::newImage = boost::bind(&GuiImage::newImage);
184 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
186 // needs to be done before reading lyxrc
188 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
192 // Set the cache to 5120 kilobytes which corresponds to screen size of
193 // 1280 by 1024 pixels with a color depth of 32 bits.
194 QPixmapCache::setCacheLimit(5120);
196 // Initialize RC Fonts
197 if (lyxrc.roman_font_name.empty())
198 lyxrc.roman_font_name = fromqstr(romanFontName());
200 if (lyxrc.sans_font_name.empty())
201 lyxrc.sans_font_name = fromqstr(sansFontName());
203 if (lyxrc.typewriter_font_name.empty())
204 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
206 general_timer_.setInterval(500);
207 connect(&general_timer_, SIGNAL(timeout()),
208 this, SLOT(handleRegularEvents()));
209 general_timer_.start();
213 GuiApplication::~GuiApplication()
215 socket_notifiers_.clear();
219 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
226 case LFUN_WINDOW_CLOSE:
227 enable = view_ids_.size() > 0;
231 if (!current_view_) {
244 bool GuiApplication::dispatch(FuncRequest const & cmd)
248 case LFUN_WINDOW_NEW:
249 createView(toqstr(cmd.argument()));
252 case LFUN_WINDOW_CLOSE:
253 // update bookmark pit of the current buffer before window close
254 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
255 theLyXFunc().gotoBookmark(i+1, false, false);
256 // ask the user for saving changes or cancel quit
257 if (!current_view_->quitWriteAll())
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.")));
266 if (current_view_->quitWriteAll())
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;
288 // Notify the caller that the action has not been dispatched.
292 // The action has been dispatched.
297 void GuiApplication::resetGui()
299 map<int, GuiView *>::iterator it;
300 for (it = views_.begin(); it != views_.end(); ++it)
301 it->second->resetDialogs();
303 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
307 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
310 map<int, GuiView *>::const_iterator it;
311 for (it = stdmap.begin(); it != stdmap.end(); ++it)
312 ids.push_back(it->first);
316 void GuiApplication::createView(QString const & geometry_arg)
318 updateIds(views_, view_ids_);
320 while (views_.find(id) != views_.end())
322 views_[id] = new GuiView(id);
323 updateIds(views_, view_ids_);
325 GuiView * view = views_[id];
326 theLyXFunc().setLyXView(view);
329 if (!geometry_arg.isEmpty()) {
333 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
334 re.indexIn(geometry_arg);
335 w = re.cap(1).toInt();
336 h = re.cap(2).toInt();
337 x = re.cap(3).toInt();
338 y = re.cap(4).toInt();
339 view->setGeometry(x, y, w, h);
344 setCurrentView(*view);
350 Clipboard & GuiApplication::clipboard()
356 Selection & GuiApplication::selection()
362 int GuiApplication::exec()
364 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
365 return QApplication::exec();
369 void GuiApplication::exit(int status)
371 QApplication::exit(status);
375 void GuiApplication::execBatchCommands()
377 LyX::ref().execBatchCommands();
381 void GuiApplication::restoreGuiSession()
383 if (!lyxrc.load_session)
386 Session & session = LyX::ref().session();
387 vector<FileName> const & lastopened = session.lastOpened().getfiles();
388 // do not add to the lastfile list since these files are restored from
389 // last session, and should be already there (regular files), or should
390 // not be added at all (help files).
391 for_each(lastopened.begin(), lastopened.end(),
392 bind(&GuiView::loadDocument, current_view_, _1, false));
394 // clear this list to save a few bytes of RAM
395 session.lastOpened().clear();
399 QString const GuiApplication::romanFontName()
402 font.setKerning(false);
403 font.setStyleHint(QFont::Serif);
404 font.setFamily("serif");
406 return QFontInfo(font).family();
410 QString const GuiApplication::sansFontName()
413 font.setKerning(false);
414 font.setStyleHint(QFont::SansSerif);
415 font.setFamily("sans");
417 return QFontInfo(font).family();
421 QString const GuiApplication::typewriterFontName()
424 font.setKerning(false);
425 font.setStyleHint(QFont::TypeWriter);
426 font.setFamily("monospace");
428 return QFontInfo(font).family();
432 void GuiApplication::handleRegularEvents()
434 ForkedCallsController::handleCompletedProcesses();
438 bool GuiApplication::event(QEvent * e)
441 case QEvent::FileOpen: {
442 // Open a file; this happens only on Mac OS X for now
443 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
445 if (!current_view_ || !current_view_->view())
446 // The application is not properly initialized yet.
447 // So we acknowledge the event and delay the file opening
448 // until LyX is ready.
449 // FIXME UNICODE: FileName accept an utf8 encoded string.
450 LyX::ref().addFileToLoad(fromqstr(foe->file()));
452 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
453 qstring_to_ucs4(foe->file())));
459 return QApplication::event(e);
464 bool GuiApplication::notify(QObject * receiver, QEvent * event)
467 return QApplication::notify(receiver, event);
469 catch (ExceptionMessage const & e) {
470 if (e.type_ == ErrorException) {
471 Alert::error(e.title_, e.details_);
473 } else if (e.type_ == WarningException) {
474 Alert::warning(e.title_, e.details_);
478 catch (exception const & e) {
479 docstring s = _("LyX has caught an exception, it will now "
480 "attempt to save all unsaved documents and exit."
482 s += from_ascii(e.what());
483 Alert::error(_("Software exception Detected"), s);
487 docstring s = _("LyX has caught some really weird exception, it will "
488 "now attempt to save all unsaved documents and exit.");
489 Alert::error(_("Software exception Detected"), s);
497 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
499 QColor const & qcol = color_cache_.get(col);
500 if (!qcol.isValid()) {
506 rgbcol.r = qcol.red();
507 rgbcol.g = qcol.green();
508 rgbcol.b = qcol.blue();
513 string const GuiApplication::hexName(ColorCode col)
515 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
519 void GuiApplication::updateColor(ColorCode)
521 // FIXME: Bleh, can't we just clear them all at once ?
522 color_cache_.clear();
526 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
528 SocketNotifier * sn = new SocketNotifier(this, fd, func);
529 socket_notifiers_[fd] = sn;
530 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
534 void GuiApplication::socketDataReceived(int fd)
536 socket_notifiers_[fd]->func_();
540 void GuiApplication::unregisterSocketCallback(int fd)
542 socket_notifiers_.erase(fd);
546 void GuiApplication::commitData(QSessionManager & sm)
548 /// The implementation is required to avoid an application exit
549 /// when session state save is triggered by session manager.
550 /// The default implementation sends a close event to all
551 /// visible top level widgets when session managment allows
553 /// We are changing that to write all unsaved buffers...
554 if (sm.allowsInteraction() && !current_view_->quitWriteAll())
559 void GuiApplication::addMenuTranslator()
561 installTranslator(new MenuTranslator(this));
565 bool GuiApplication::unregisterView(int id)
567 updateIds(views_, view_ids_);
568 BOOST_ASSERT(views_.find(id) != views_.end());
569 BOOST_ASSERT(views_[id]);
571 map<int, GuiView *>::iterator it;
572 for (it = views_.begin(); it != views_.end(); ++it) {
573 if (it->first == id) {
578 updateIds(views_, view_ids_);
583 bool GuiApplication::closeAllViews()
585 updateIds(views_, view_ids_);
586 if (views_.empty()) {
587 // quit in CloseEvent will not be triggert
592 map<int, GuiView*> const cmap = views_;
593 map<int, GuiView*>::const_iterator it;
594 for (it = cmap.begin(); it != cmap.end(); ++it) {
595 // TODO: return false when close event was ignored
596 // e.g. quitWriteAll()->'Cancel'
597 // maybe we need something like 'bool closeView()'
599 // unregisterd by the CloseEvent
608 GuiView & GuiApplication::view(int id) const
610 BOOST_ASSERT(views_.find(id) != views_.end());
611 return *views_.find(id)->second;
615 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
617 vector<int>::const_iterator it = view_ids_.begin();
618 vector<int>::const_iterator const end = view_ids_.end();
619 for (; it != end; ++it)
620 view(*it).hideDialog(name, inset);
624 Buffer const * GuiApplication::updateInset(Inset const * inset) const
626 Buffer const * buffer_ = 0;
627 vector<int>::const_iterator it = view_ids_.begin();
628 vector<int>::const_iterator const end = view_ids_.end();
629 for (; it != end; ++it) {
630 Buffer const * ptr = view(*it).updateInset(inset);
638 ////////////////////////////////////////////////////////////////////////
639 // X11 specific stuff goes here...
641 bool GuiApplication::x11EventFilter(XEvent * xev)
647 case SelectionRequest: {
648 if (xev->xselectionrequest.selection != XA_PRIMARY)
650 LYXERR(Debug::GUI, "X requested selection.");
651 BufferView * bv = current_view_->view();
653 docstring const sel = bv->requestSelection();
659 case SelectionClear: {
660 if (xev->xselectionclear.selection != XA_PRIMARY)
662 LYXERR(Debug::GUI, "Lost selection.");
663 BufferView * bv = current_view_->view();
665 bv->clearSelection();
673 } // namespace frontend
676 ////////////////////////////////////////////////////////////////////
680 ////////////////////////////////////////////////////////////////////
682 frontend::FontLoader & theFontLoader()
684 static frontend::NoGuiFontLoader no_gui_font_loader;
687 return no_gui_font_loader;
689 BOOST_ASSERT(frontend::guiApp);
690 return frontend::guiApp->fontLoader();
694 frontend::FontMetrics const & theFontMetrics(Font const & f)
696 return theFontMetrics(f.fontInfo());
700 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
702 static frontend::NoGuiFontMetrics no_gui_font_metrics;
705 return no_gui_font_metrics;
707 BOOST_ASSERT(frontend::guiApp);
708 return frontend::guiApp->fontLoader().metrics(f);
712 frontend::Clipboard & theClipboard()
714 BOOST_ASSERT(frontend::guiApp);
715 return frontend::guiApp->clipboard();
719 frontend::Selection & theSelection()
721 BOOST_ASSERT(frontend::guiApp);
722 return frontend::guiApp->selection();
727 #include "GuiApplication_moc.cpp"