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 // Qt bug? setQuitOnLastWindowClosed(true); does not work
143 setQuitOnLastWindowClosed(false);
146 // doubleClickInterval() is 400 ms on X11 which is just too long.
147 // On Windows and Mac OS X, the operating system's value is used.
148 // On Microsoft Windows, calling this function sets the double
149 // click interval for all applications. So we don't!
150 QApplication::setDoubleClickInterval(300);
153 // install translation file for Qt built-in dialogs
154 QString language_name = QString("qt_") + QLocale::system().name();
156 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
157 // Short-named translator can be loaded from a long name, but not the
158 // opposite. Therefore, long name should be used without truncation.
159 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
160 if (qt_trans_.load(language_name,
161 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
163 installTranslator(&qt_trans_);
164 // even if the language calls for RtL, don't do that
165 setLayoutDirection(Qt::LeftToRight);
166 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
167 << fromqstr(language_name));
169 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
170 << fromqstr(language_name));
173 // all windows in a Mac application share the same menu bar.
174 QMenuBar *menuBar = new QMenuBar(0);
175 // This allows to translate the strings that appear in the LyX menu.
179 using namespace lyx::graphics;
181 Image::newImage = boost::bind(&GuiImage::newImage);
182 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
184 // needs to be done before reading lyxrc
186 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
190 // Set the cache to 5120 kilobytes which corresponds to screen size of
191 // 1280 by 1024 pixels with a color depth of 32 bits.
192 QPixmapCache::setCacheLimit(5120);
194 // Initialize RC Fonts
195 if (lyxrc.roman_font_name.empty())
196 lyxrc.roman_font_name = fromqstr(romanFontName());
198 if (lyxrc.sans_font_name.empty())
199 lyxrc.sans_font_name = fromqstr(sansFontName());
201 if (lyxrc.typewriter_font_name.empty())
202 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
204 general_timer_.setInterval(500);
205 connect(&general_timer_, SIGNAL(timeout()),
206 this, SLOT(handleRegularEvents()));
207 general_timer_.start();
211 GuiApplication::~GuiApplication()
213 socket_notifiers_.clear();
217 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
224 case LFUN_WINDOW_CLOSE:
225 enable = view_ids_.size() > 0;
229 if (!current_view_) {
242 bool GuiApplication::dispatch(FuncRequest const & cmd)
246 case LFUN_WINDOW_NEW:
247 createView(toqstr(cmd.argument()));
250 case LFUN_WINDOW_CLOSE:
251 // update bookmark pit of the current buffer before window close
252 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
253 theLyXFunc().gotoBookmark(i+1, false, false);
254 current_view_->close();
258 // quitting is triggered by the gui code
259 // (leaving the event loop).
260 current_view_->message(from_utf8(N_("Exiting.")));
265 case LFUN_SCREEN_FONT_UPDATE: {
266 // handle the screen font changes.
267 font_loader_.update();
268 // Backup current_view_
269 GuiView * view = current_view_;
270 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
271 // to skip the refresh.
273 BufferList::iterator it = theBufferList().begin();
274 BufferList::iterator const end = theBufferList().end();
275 for (; it != end; ++it)
277 // Restore current_view_
278 current_view_ = view;
283 // Notify the caller that the action has not been dispatched.
287 // The action has been dispatched.
292 void GuiApplication::resetGui()
294 map<int, GuiView *>::iterator it;
295 for (it = views_.begin(); it != views_.end(); ++it)
296 it->second->resetDialogs();
298 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
302 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
305 map<int, GuiView *>::const_iterator it;
306 for (it = stdmap.begin(); it != stdmap.end(); ++it)
307 ids.push_back(it->first);
311 void GuiApplication::createView(QString const & geometry_arg)
313 updateIds(views_, view_ids_);
315 while (views_.find(id) != views_.end())
317 views_[id] = new GuiView(id);
318 updateIds(views_, view_ids_);
320 GuiView * view = views_[id];
321 theLyXFunc().setLyXView(view);
324 if (!geometry_arg.isEmpty()) {
328 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
329 re.indexIn(geometry_arg);
330 w = re.cap(1).toInt();
331 h = re.cap(2).toInt();
332 x = re.cap(3).toInt();
333 y = re.cap(4).toInt();
334 view->setGeometry(x, y, w, h);
339 setCurrentView(*view);
345 Clipboard & GuiApplication::clipboard()
351 Selection & GuiApplication::selection()
357 int GuiApplication::exec()
359 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
360 return QApplication::exec();
364 void GuiApplication::exit(int status)
366 QApplication::exit(status);
370 void GuiApplication::execBatchCommands()
372 LyX::ref().execBatchCommands();
376 void GuiApplication::restoreGuiSession()
378 if (!lyxrc.load_session)
381 Session & session = LyX::ref().session();
382 vector<FileName> const & lastopened = session.lastOpened().getfiles();
383 // do not add to the lastfile list since these files are restored from
384 // last session, and should be already there (regular files), or should
385 // not be added at all (help files).
386 for_each(lastopened.begin(), lastopened.end(),
387 bind(&GuiView::loadDocument, current_view_, _1, false));
389 // clear this list to save a few bytes of RAM
390 session.lastOpened().clear();
394 QString const GuiApplication::romanFontName()
397 font.setKerning(false);
398 font.setStyleHint(QFont::Serif);
399 font.setFamily("serif");
401 return QFontInfo(font).family();
405 QString const GuiApplication::sansFontName()
408 font.setKerning(false);
409 font.setStyleHint(QFont::SansSerif);
410 font.setFamily("sans");
412 return QFontInfo(font).family();
416 QString const GuiApplication::typewriterFontName()
419 font.setKerning(false);
420 font.setStyleHint(QFont::TypeWriter);
421 font.setFamily("monospace");
423 return QFontInfo(font).family();
427 void GuiApplication::handleRegularEvents()
429 ForkedCallsController::handleCompletedProcesses();
433 bool GuiApplication::event(QEvent * e)
436 case QEvent::FileOpen: {
437 // Open a file; this happens only on Mac OS X for now
438 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
440 if (!current_view_ || !current_view_->view())
441 // The application is not properly initialized yet.
442 // So we acknowledge the event and delay the file opening
443 // until LyX is ready.
444 // FIXME UNICODE: FileName accept an utf8 encoded string.
445 LyX::ref().addFileToLoad(fromqstr(foe->file()));
447 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
448 qstring_to_ucs4(foe->file())));
454 return QApplication::event(e);
459 bool GuiApplication::notify(QObject * receiver, QEvent * event)
462 return QApplication::notify(receiver, event);
464 catch (ExceptionMessage const & e) {
465 if (e.type_ == ErrorException) {
466 Alert::error(e.title_, e.details_);
468 } else if (e.type_ == WarningException) {
469 Alert::warning(e.title_, e.details_);
473 catch (exception const & e) {
474 docstring s = _("LyX has caught an exception, it will now "
475 "attempt to save all unsaved documents and exit."
477 s += from_ascii(e.what());
478 Alert::error(_("Software exception Detected"), s);
482 docstring s = _("LyX has caught some really weird exception, it will "
483 "now attempt to save all unsaved documents and exit.");
484 Alert::error(_("Software exception Detected"), s);
492 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
494 QColor const & qcol = color_cache_.get(col);
495 if (!qcol.isValid()) {
501 rgbcol.r = qcol.red();
502 rgbcol.g = qcol.green();
503 rgbcol.b = qcol.blue();
508 string const GuiApplication::hexName(ColorCode col)
510 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
514 void GuiApplication::updateColor(ColorCode)
516 // FIXME: Bleh, can't we just clear them all at once ?
517 color_cache_.clear();
521 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
523 SocketNotifier * sn = new SocketNotifier(this, fd, func);
524 socket_notifiers_[fd] = sn;
525 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
529 void GuiApplication::socketDataReceived(int fd)
531 socket_notifiers_[fd]->func_();
535 void GuiApplication::unregisterSocketCallback(int fd)
537 socket_notifiers_.erase(fd);
541 void GuiApplication::commitData(QSessionManager & sm)
543 /// The implementation is required to avoid an application exit
544 /// when session state save is triggered by session manager.
545 /// The default implementation sends a close event to all
546 /// visible top level widgets when session managment allows
548 /// We are changing that to close all wiew one by one.
549 /// FIXME: verify if the default implementation is enough now.
550 if (sm.allowsInteraction() && !closeAllViews())
555 void GuiApplication::addMenuTranslator()
557 installTranslator(new MenuTranslator(this));
561 bool GuiApplication::unregisterView(int id)
563 updateIds(views_, view_ids_);
564 BOOST_ASSERT(views_.find(id) != views_.end());
565 BOOST_ASSERT(views_[id]);
567 map<int, GuiView *>::iterator it;
568 for (it = views_.begin(); it != views_.end(); ++it) {
569 if (it->first == id) {
574 updateIds(views_, view_ids_);
579 bool GuiApplication::closeAllViews()
581 updateIds(views_, view_ids_);
585 map<int, GuiView*> const cmap = views_;
586 map<int, GuiView*>::const_iterator it;
587 for (it = cmap.begin(); it != cmap.end(); ++it) {
588 if (!it->second->close())
598 GuiView & GuiApplication::view(int id) const
600 BOOST_ASSERT(views_.find(id) != views_.end());
601 return *views_.find(id)->second;
605 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
607 vector<int>::const_iterator it = view_ids_.begin();
608 vector<int>::const_iterator const end = view_ids_.end();
609 for (; it != end; ++it)
610 view(*it).hideDialog(name, inset);
614 Buffer const * GuiApplication::updateInset(Inset const * inset) const
616 Buffer const * buffer_ = 0;
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 Buffer const * ptr = view(*it).updateInset(inset);
628 ////////////////////////////////////////////////////////////////////////
629 // X11 specific stuff goes here...
631 bool GuiApplication::x11EventFilter(XEvent * xev)
637 case SelectionRequest: {
638 if (xev->xselectionrequest.selection != XA_PRIMARY)
640 LYXERR(Debug::GUI, "X requested selection.");
641 BufferView * bv = current_view_->view();
643 docstring const sel = bv->requestSelection();
649 case SelectionClear: {
650 if (xev->xselectionclear.selection != XA_PRIMARY)
652 LYXERR(Debug::GUI, "Lost selection.");
653 BufferView * bv = current_view_->view();
655 bv->clearSelection();
663 } // namespace frontend
666 ////////////////////////////////////////////////////////////////////
670 ////////////////////////////////////////////////////////////////////
672 frontend::FontLoader & theFontLoader()
674 BOOST_ASSERT(frontend::guiApp);
675 return frontend::guiApp->fontLoader();
679 frontend::FontMetrics const & theFontMetrics(Font const & f)
681 return theFontMetrics(f.fontInfo());
685 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
687 BOOST_ASSERT(frontend::guiApp);
688 return frontend::guiApp->fontLoader().metrics(f);
692 frontend::Clipboard & theClipboard()
694 BOOST_ASSERT(frontend::guiApp);
695 return frontend::guiApp->clipboard();
699 frontend::Selection & theSelection()
701 BOOST_ASSERT(frontend::guiApp);
702 return frontend::guiApp->selection();
707 #include "GuiApplication_moc.cpp"