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/lstrings.h"
31 #include "support/os.h"
32 #include "support/Package.h"
35 #include "BufferList.h"
36 #include "BufferView.h"
37 #include "support/debug.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "support/gettext.h"
48 #include <QApplication>
51 #include <QFileOpenEvent>
53 #include <QLibraryInfo>
55 #include <QPixmapCache>
57 #include <QSessionManager>
58 #include <QSocketNotifier>
61 #include <QTranslator>
65 #include <X11/Xatom.h>
71 #include <boost/bind.hpp>
76 using namespace lyx::support;
80 frontend::Application * createApplication(int & argc, char * argv[])
82 return new frontend::GuiApplication(argc, argv);
88 class SocketNotifier : public QSocketNotifier
91 /// connect a connection notification from the LyXServerSocket
92 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
93 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
97 /// The callback function
98 Application::SocketCallback func_;
102 ////////////////////////////////////////////////////////////////////////
103 // Mac specific stuff goes here...
105 class MenuTranslator : public QTranslator
108 MenuTranslator(QObject * parent)
109 : QTranslator(parent)
112 QString translate(const char * /*context*/,
113 const char * sourceText,
114 const char * /*comment*/ = 0)
116 string const s = sourceText;
117 if (s == N_("About %1") || s == N_("Preferences")
118 || s == N_("Reconfigure") || s == N_("Quit %1"))
126 ///////////////////////////////////////////////////////////////
127 // You can find more platform specific stuff
128 // at the end of this file...
129 ///////////////////////////////////////////////////////////////
132 GuiApplication * guiApp;
135 GuiApplication::GuiApplication(int & argc, char ** argv)
136 : QApplication(argc, argv), Application(), current_view_(0)
138 QString app_name = "LyX";
139 QCoreApplication::setOrganizationName(app_name);
140 QCoreApplication::setOrganizationDomain("lyx.org");
141 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
143 // Qt bug? setQuitOnLastWindowClosed(true); does not work
144 setQuitOnLastWindowClosed(false);
147 // doubleClickInterval() is 400 ms on X11 which is just too long.
148 // On Windows and Mac OS X, the operating system's value is used.
149 // On Microsoft Windows, calling this function sets the double
150 // click interval for all applications. So we don't!
151 QApplication::setDoubleClickInterval(300);
154 // install translation file for Qt built-in dialogs
155 QString language_name = QString("qt_") + QLocale::system().name();
157 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
158 // Short-named translator can be loaded from a long name, but not the
159 // opposite. Therefore, long name should be used without truncation.
160 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
161 if (qt_trans_.load(language_name,
162 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
164 installTranslator(&qt_trans_);
165 // even if the language calls for RtL, don't do that
166 setLayoutDirection(Qt::LeftToRight);
167 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
168 << fromqstr(language_name));
170 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
171 << fromqstr(language_name));
174 // all windows in a Mac application share the same menu bar.
175 QMenuBar *menuBar = new QMenuBar(0);
176 // This allows to translate the strings that appear in the LyX menu.
180 using namespace lyx::graphics;
182 Image::newImage = boost::bind(&GuiImage::newImage);
183 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
185 // needs to be done before reading lyxrc
187 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
191 // Set the cache to 5120 kilobytes which corresponds to screen size of
192 // 1280 by 1024 pixels with a color depth of 32 bits.
193 QPixmapCache::setCacheLimit(5120);
195 // Initialize RC Fonts
196 if (lyxrc.roman_font_name.empty())
197 lyxrc.roman_font_name = fromqstr(romanFontName());
199 if (lyxrc.sans_font_name.empty())
200 lyxrc.sans_font_name = fromqstr(sansFontName());
202 if (lyxrc.typewriter_font_name.empty())
203 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
207 GuiApplication::~GuiApplication()
209 socket_notifiers_.clear();
213 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
220 case LFUN_WINDOW_CLOSE:
221 enable = view_ids_.size() > 0;
225 if (!current_view_) {
238 bool GuiApplication::dispatch(FuncRequest const & cmd)
242 case LFUN_WINDOW_NEW:
243 createView(toqstr(cmd.argument()));
246 case LFUN_WINDOW_CLOSE:
247 // update bookmark pit of the current buffer before window close
248 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
249 theLyXFunc().gotoBookmark(i+1, false, false);
250 // ask the user for saving changes or cancel quit
251 if (!current_view_->quitWriteAll())
253 current_view_->close();
257 // quitting is triggered by the gui code
258 // (leaving the event loop).
259 current_view_->message(from_utf8(N_("Exiting.")));
260 if (current_view_->quitWriteAll())
264 case LFUN_SCREEN_FONT_UPDATE: {
265 // handle the screen font changes.
266 font_loader_.update();
267 // Backup current_view_
268 GuiView * view = current_view_;
269 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
270 // to skip the refresh.
272 BufferList::iterator it = theBufferList().begin();
273 BufferList::iterator const end = theBufferList().end();
274 for (; it != end; ++it)
276 // Restore current_view_
277 current_view_ = view;
282 // Notify the caller that the action has not been dispatched.
286 // The action has been dispatched.
291 void GuiApplication::resetGui()
293 map<int, GuiView *>::iterator it;
294 for (it = views_.begin(); it != views_.end(); ++it)
295 it->second->resetDialogs();
297 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
301 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
304 map<int, GuiView *>::const_iterator it;
305 for (it = stdmap.begin(); it != stdmap.end(); ++it)
306 ids.push_back(it->first);
310 void GuiApplication::createView(QString const & geometry_arg)
312 updateIds(views_, view_ids_);
314 while (views_.find(id) != views_.end())
316 views_[id] = new GuiView(id);
317 updateIds(views_, view_ids_);
319 GuiView * view = views_[id];
320 theLyXFunc().setLyXView(view);
323 if (!geometry_arg.isEmpty()) {
327 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
328 re.indexIn(geometry_arg);
329 w = re.cap(1).toInt();
330 h = re.cap(2).toInt();
331 x = re.cap(3).toInt();
332 y = re.cap(4).toInt();
333 view->setGeometry(x, y, w, h);
338 setCurrentView(*view);
344 Clipboard & GuiApplication::clipboard()
350 Selection & GuiApplication::selection()
356 int GuiApplication::exec()
358 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
359 return QApplication::exec();
363 void GuiApplication::exit(int status)
365 QApplication::exit(status);
369 void GuiApplication::execBatchCommands()
371 LyX::ref().execBatchCommands();
375 QString const GuiApplication::romanFontName()
378 font.setKerning(false);
379 font.setStyleHint(QFont::Serif);
380 font.setFamily("serif");
382 return QFontInfo(font).family();
386 QString const GuiApplication::sansFontName()
389 font.setKerning(false);
390 font.setStyleHint(QFont::SansSerif);
391 font.setFamily("sans");
393 return QFontInfo(font).family();
397 QString const GuiApplication::typewriterFontName()
400 font.setKerning(false);
401 font.setStyleHint(QFont::TypeWriter);
402 font.setFamily("monospace");
404 return QFontInfo(font).family();
408 bool GuiApplication::event(QEvent * e)
411 case QEvent::FileOpen: {
412 // Open a file; this happens only on Mac OS X for now
413 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
415 if (!current_view_ || !current_view_->view())
416 // The application is not properly initialized yet.
417 // So we acknowledge the event and delay the file opening
418 // until LyX is ready.
419 // FIXME UNICODE: FileName accept an utf8 encoded string.
420 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
422 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
423 qstring_to_ucs4(foe->file())));
429 return QApplication::event(e);
434 bool GuiApplication::notify(QObject * receiver, QEvent * event)
437 return QApplication::notify(receiver, event);
439 catch (ExceptionMessage const & e) {
440 if (e.type_ == ErrorException) {
441 Alert::error(e.title_, e.details_);
443 } else if (e.type_ == WarningException) {
444 Alert::warning(e.title_, e.details_);
448 catch (exception const & e) {
449 docstring s = _("LyX has caught an exception, it will now "
450 "attempt to save all unsaved documents and exit."
452 s += from_ascii(e.what());
453 Alert::error(_("Software exception Detected"), s);
457 docstring s = _("LyX has caught some really weird exception, it will "
458 "now attempt to save all unsaved documents and exit.");
459 Alert::error(_("Software exception Detected"), s);
467 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
469 QColor const & qcol = color_cache_.get(col);
470 if (!qcol.isValid()) {
476 rgbcol.r = qcol.red();
477 rgbcol.g = qcol.green();
478 rgbcol.b = qcol.blue();
483 string const GuiApplication::hexName(ColorCode col)
485 return ltrim(fromqstr(color_cache_.get(col).name()), "#");
489 void GuiApplication::updateColor(ColorCode)
491 // FIXME: Bleh, can't we just clear them all at once ?
492 color_cache_.clear();
496 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
498 SocketNotifier * sn = new SocketNotifier(this, fd, func);
499 socket_notifiers_[fd] = sn;
500 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
504 void GuiApplication::socketDataReceived(int fd)
506 socket_notifiers_[fd]->func_();
510 void GuiApplication::unregisterSocketCallback(int fd)
512 socket_notifiers_.erase(fd);
516 void GuiApplication::commitData(QSessionManager & sm)
518 /// The implementation is required to avoid an application exit
519 /// when session state save is triggered by session manager.
520 /// The default implementation sends a close event to all
521 /// visible top level widgets when session managment allows
523 /// We are changing that to write all unsaved buffers...
524 if (sm.allowsInteraction() && !current_view_->quitWriteAll())
529 void GuiApplication::addMenuTranslator()
531 installTranslator(new MenuTranslator(this));
535 bool GuiApplication::unregisterView(int id)
537 updateIds(views_, view_ids_);
538 BOOST_ASSERT(views_.find(id) != views_.end());
539 BOOST_ASSERT(views_[id]);
541 map<int, GuiView *>::iterator it;
542 for (it = views_.begin(); it != views_.end(); ++it) {
543 if (it->first == id) {
548 updateIds(views_, view_ids_);
553 bool GuiApplication::closeAllViews()
555 updateIds(views_, view_ids_);
556 if (views_.empty()) {
557 // quit in CloseEvent will not be triggert
562 map<int, GuiView*> const cmap = views_;
563 map<int, GuiView*>::const_iterator it;
564 for (it = cmap.begin(); it != cmap.end(); ++it) {
565 // TODO: return false when close event was ignored
566 // e.g. quitWriteAll()->'Cancel'
567 // maybe we need something like 'bool closeView()'
569 // unregisterd by the CloseEvent
578 GuiView & GuiApplication::view(int id) const
580 BOOST_ASSERT(views_.find(id) != views_.end());
581 return *views_.find(id)->second;
585 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
587 vector<int>::const_iterator it = view_ids_.begin();
588 vector<int>::const_iterator const end = view_ids_.end();
589 for (; it != end; ++it)
590 view(*it).hideDialog(name, inset);
594 Buffer const * GuiApplication::updateInset(Inset const * inset) const
596 Buffer const * buffer_ = 0;
597 vector<int>::const_iterator it = view_ids_.begin();
598 vector<int>::const_iterator const end = view_ids_.end();
599 for (; it != end; ++it) {
600 Buffer const * ptr = view(*it).updateInset(inset);
608 ////////////////////////////////////////////////////////////////////////
609 // X11 specific stuff goes here...
611 bool GuiApplication::x11EventFilter(XEvent * xev)
617 case SelectionRequest: {
618 if (xev->xselectionrequest.selection != XA_PRIMARY)
620 LYXERR(Debug::GUI, "X requested selection.");
621 BufferView * bv = current_view_->view();
623 docstring const sel = bv->requestSelection();
629 case SelectionClear: {
630 if (xev->xselectionclear.selection != XA_PRIMARY)
632 LYXERR(Debug::GUI, "Lost selection.");
633 BufferView * bv = current_view_->view();
635 bv->clearSelection();
643 } // namespace frontend
646 ////////////////////////////////////////////////////////////////////
650 ////////////////////////////////////////////////////////////////////
652 frontend::FontLoader & theFontLoader()
654 static frontend::NoGuiFontLoader no_gui_font_loader;
657 return no_gui_font_loader;
659 BOOST_ASSERT(frontend::guiApp);
660 return frontend::guiApp->fontLoader();
664 frontend::FontMetrics const & theFontMetrics(Font const & f)
666 return theFontMetrics(f.fontInfo());
670 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
672 static frontend::NoGuiFontMetrics no_gui_font_metrics;
675 return no_gui_font_metrics;
677 BOOST_ASSERT(frontend::guiApp);
678 return frontend::guiApp->fontLoader().metrics(f);
682 frontend::Clipboard & theClipboard()
684 BOOST_ASSERT(frontend::guiApp);
685 return frontend::guiApp->clipboard();
689 frontend::Selection & theSelection()
691 BOOST_ASSERT(frontend::guiApp);
692 return frontend::guiApp->selection();
697 #include "GuiApplication_moc.cpp"