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"
32 #include "support/gettext.h"
39 #include "support/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/FileName.h"
42 #include "support/ForkedCalls.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;
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 close all wiew one by one.
554 /// FIXME: verify if the default implementation is enough now.
555 if (sm.allowsInteraction() && !closeAllViews())
560 void GuiApplication::addMenuTranslator()
562 installTranslator(new MenuTranslator(this));
566 bool GuiApplication::unregisterView(int id)
568 updateIds(views_, view_ids_);
569 BOOST_ASSERT(views_.find(id) != views_.end());
570 BOOST_ASSERT(views_[id]);
572 map<int, GuiView *>::iterator it;
573 for (it = views_.begin(); it != views_.end(); ++it) {
574 if (it->first == id) {
579 updateIds(views_, view_ids_);
584 bool GuiApplication::closeAllViews()
586 updateIds(views_, view_ids_);
590 map<int, GuiView*> const cmap = views_;
591 map<int, GuiView*>::const_iterator it;
592 for (it = cmap.begin(); it != cmap.end(); ++it) {
593 if (!it->second->close())
603 GuiView & GuiApplication::view(int id) const
605 BOOST_ASSERT(views_.find(id) != views_.end());
606 return *views_.find(id)->second;
610 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
612 vector<int>::const_iterator it = view_ids_.begin();
613 vector<int>::const_iterator const end = view_ids_.end();
614 for (; it != end; ++it)
615 view(*it).hideDialog(name, inset);
619 Buffer const * GuiApplication::updateInset(Inset const * inset) const
621 Buffer const * buffer_ = 0;
622 vector<int>::const_iterator it = view_ids_.begin();
623 vector<int>::const_iterator const end = view_ids_.end();
624 for (; it != end; ++it) {
625 Buffer const * ptr = view(*it).updateInset(inset);
633 ////////////////////////////////////////////////////////////////////////
634 // X11 specific stuff goes here...
636 bool GuiApplication::x11EventFilter(XEvent * xev)
642 case SelectionRequest: {
643 if (xev->xselectionrequest.selection != XA_PRIMARY)
645 LYXERR(Debug::GUI, "X requested selection.");
646 BufferView * bv = current_view_->view();
648 docstring const sel = bv->requestSelection();
654 case SelectionClear: {
655 if (xev->xselectionclear.selection != XA_PRIMARY)
657 LYXERR(Debug::GUI, "Lost selection.");
658 BufferView * bv = current_view_->view();
660 bv->clearSelection();
668 } // namespace frontend
671 ////////////////////////////////////////////////////////////////////
675 ////////////////////////////////////////////////////////////////////
677 frontend::FontLoader & theFontLoader()
679 BOOST_ASSERT(frontend::guiApp);
680 return frontend::guiApp->fontLoader();
684 frontend::FontMetrics const & theFontMetrics(Font const & f)
686 return theFontMetrics(f.fontInfo());
690 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
692 BOOST_ASSERT(frontend::guiApp);
693 return frontend::guiApp->fontLoader().metrics(f);
697 frontend::Clipboard & theClipboard()
699 BOOST_ASSERT(frontend::guiApp);
700 return frontend::guiApp->clipboard();
704 frontend::Selection & theSelection()
706 BOOST_ASSERT(frontend::guiApp);
707 return frontend::guiApp->selection();
712 #include "GuiApplication_moc.cpp"