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>
54 #include <QPixmapCache>
56 #include <QSessionManager>
57 #include <QSocketNotifier>
60 #include <QTranslator>
64 #include <X11/Xatom.h>
70 #include <boost/bind.hpp>
82 frontend::Application * createApplication(int & argc, char * argv[])
84 return new frontend::GuiApplication(argc, argv);
90 class SocketNotifier : public QSocketNotifier
93 /// connect a connection notification from the LyXServerSocket
94 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
95 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
99 /// The callback function
100 Application::SocketCallback func_;
104 ////////////////////////////////////////////////////////////////////////
105 // Mac specific stuff goes here...
107 class MenuTranslator : public QTranslator
110 MenuTranslator(QObject * parent)
111 : QTranslator(parent)
114 QString translate(const char * /*context*/,
115 const char * sourceText,
116 const char * /*comment*/ = 0)
118 string const s = sourceText;
119 if (s == N_("About %1") || s == N_("Preferences")
120 || s == N_("Reconfigure") || s == N_("Quit %1"))
128 ///////////////////////////////////////////////////////////////
129 // You can find more platform specific stuff
130 // at the end of this file...
131 ///////////////////////////////////////////////////////////////
134 using support::FileName;
136 GuiApplication * guiApp;
139 GuiApplication::GuiApplication(int & argc, char ** argv)
140 : QApplication(argc, argv), Application(), current_view_(0)
142 QString app_name = "LyX";
143 QCoreApplication::setOrganizationName(app_name);
144 QCoreApplication::setOrganizationDomain("lyx.org");
145 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
147 // Qt bug? setQuitOnLastWindowClosed(true); does not work
148 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 // This allows to translate the strings that appear in the LyX menu.
182 using namespace lyx::graphics;
184 Image::newImage = boost::bind(&GuiImage::newImage);
185 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
187 // needs to be done before reading lyxrc
189 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
193 // Set the cache to 5120 kilobytes which corresponds to screen size of
194 // 1280 by 1024 pixels with a color depth of 32 bits.
195 QPixmapCache::setCacheLimit(5120);
197 // Initialize RC Fonts
198 if (lyxrc.roman_font_name.empty())
199 lyxrc.roman_font_name = fromqstr(romanFontName());
201 if (lyxrc.sans_font_name.empty())
202 lyxrc.sans_font_name = fromqstr(sansFontName());
204 if (lyxrc.typewriter_font_name.empty())
205 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
209 GuiApplication::~GuiApplication()
211 socket_notifiers_.clear();
215 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
222 case LFUN_WINDOW_CLOSE:
223 enable = view_ids_.size() > 0;
227 if (!current_view_) {
240 bool GuiApplication::dispatch(FuncRequest const & cmd)
244 case LFUN_WINDOW_NEW:
245 createView(toqstr(cmd.argument()));
248 case LFUN_WINDOW_CLOSE:
249 // update bookmark pit of the current buffer before window close
250 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
251 theLyXFunc().gotoBookmark(i+1, false, false);
252 // ask the user for saving changes or cancel quit
253 if (!theBufferList().quitWriteAll())
255 current_view_->close();
259 // quitting is triggered by the gui code
260 // (leaving the event loop).
261 current_view_->message(from_utf8(N_("Exiting.")));
262 if (theBufferList().quitWriteAll())
266 case LFUN_SCREEN_FONT_UPDATE: {
267 // handle the screen font changes.
268 font_loader_.update();
269 // Backup current_view_
270 GuiView * view = current_view_;
271 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
272 // to skip the refresh.
274 BufferList::iterator it = theBufferList().begin();
275 BufferList::iterator const end = theBufferList().end();
276 for (; it != end; ++it)
278 // Restore current_view_
279 current_view_ = view;
284 // Notify the caller that the action has not been dispatched.
288 // The action has been dispatched.
293 void GuiApplication::resetGui()
295 map<int, GuiView *>::iterator it;
296 for (it = views_.begin(); it != views_.end(); ++it)
297 it->second->resetDialogs();
299 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
303 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
306 map<int, GuiView *>::const_iterator it;
307 for (it = stdmap.begin(); it != stdmap.end(); ++it)
308 ids.push_back(it->first);
312 void GuiApplication::createView(QString const & geometry_arg)
314 updateIds(views_, view_ids_);
316 while (views_.find(id) != views_.end())
318 views_[id] = new GuiView(id);
319 updateIds(views_, view_ids_);
321 GuiView * view = views_[id];
322 theLyXFunc().setLyXView(view);
325 if (!geometry_arg.isEmpty()) {
329 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
330 re.indexIn(geometry_arg);
331 w = re.cap(1).toInt();
332 h = re.cap(2).toInt();
333 x = re.cap(3).toInt();
334 y = re.cap(4).toInt();
335 view->setGeometry(x, y, w, h);
340 setCurrentView(*view);
346 Clipboard & GuiApplication::clipboard()
352 Selection & GuiApplication::selection()
358 int GuiApplication::exec()
360 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
361 return QApplication::exec();
365 void GuiApplication::exit(int status)
367 QApplication::exit(status);
371 void GuiApplication::execBatchCommands()
373 LyX::ref().execBatchCommands();
377 QString const GuiApplication::romanFontName()
380 font.setKerning(false);
381 font.setStyleHint(QFont::Serif);
382 font.setFamily("serif");
384 return QFontInfo(font).family();
388 QString const GuiApplication::sansFontName()
391 font.setKerning(false);
392 font.setStyleHint(QFont::SansSerif);
393 font.setFamily("sans");
395 return QFontInfo(font).family();
399 QString const GuiApplication::typewriterFontName()
402 font.setKerning(false);
403 font.setStyleHint(QFont::TypeWriter);
404 font.setFamily("monospace");
406 return QFontInfo(font).family();
410 bool GuiApplication::event(QEvent * e)
413 case QEvent::FileOpen: {
414 // Open a file; this happens only on Mac OS X for now
415 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
417 if (!current_view_ || !current_view_->view())
418 // The application is not properly initialized yet.
419 // So we acknowledge the event and delay the file opening
420 // until LyX is ready.
421 // FIXME UNICODE: FileName accept an utf8 encoded string.
422 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
424 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
425 qstring_to_ucs4(foe->file())));
431 return QApplication::event(e);
436 bool GuiApplication::notify(QObject * receiver, QEvent * event)
439 return QApplication::notify(receiver, event);
441 catch (support::ExceptionMessage const & e) {
442 if (e.type_ == support::ErrorException) {
443 Alert::error(e.title_, e.details_);
444 LyX::cref().emergencyCleanup();
445 QApplication::exit(1);
446 } else if (e.type_ == support::WarningException) {
447 Alert::warning(e.title_, e.details_);
451 catch (std::exception const & e) {
452 docstring s = _("LyX has caught an exception, it will now "
453 "attemp to save all unsaved documents and exit."
455 s += from_ascii(e.what());
456 Alert::error(_("Software exception Detected"), s);
457 LyX::cref().emergencyCleanup();
458 QApplication::exit(1);
461 docstring s = _("LyX has caught some really weird exception, it will "
462 "now attemp to save all unsaved documents and exit.");
463 Alert::error(_("Software exception Detected"), s);
464 LyX::cref().emergencyCleanup();
465 QApplication::exit(1);
472 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
474 QColor const & qcol = color_cache_.get(col);
475 if (!qcol.isValid()) {
481 rgbcol.r = qcol.red();
482 rgbcol.g = qcol.green();
483 rgbcol.b = qcol.blue();
488 string const GuiApplication::hexName(ColorCode col)
490 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
494 void GuiApplication::updateColor(ColorCode)
496 // FIXME: Bleh, can't we just clear them all at once ?
497 color_cache_.clear();
501 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
503 SocketNotifier * sn = new SocketNotifier(this, fd, func);
504 socket_notifiers_[fd] = sn;
505 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
509 void GuiApplication::socketDataReceived(int fd)
511 socket_notifiers_[fd]->func_();
515 void GuiApplication::unregisterSocketCallback(int fd)
517 socket_notifiers_.erase(fd);
521 void GuiApplication::commitData(QSessionManager & sm)
523 /// The implementation is required to avoid an application exit
524 /// when session state save is triggered by session manager.
525 /// The default implementation sends a close event to all
526 /// visible top level widgets when session managment allows
528 /// We are changing that to write all unsaved buffers...
529 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
534 void GuiApplication::addMenuTranslator()
536 installTranslator(new MenuTranslator(this));
540 bool GuiApplication::unregisterView(int id)
542 updateIds(views_, view_ids_);
543 BOOST_ASSERT(views_.find(id) != views_.end());
544 BOOST_ASSERT(views_[id]);
546 map<int, GuiView *>::iterator it;
547 for (it = views_.begin(); it != views_.end(); ++it) {
548 if (it->first == id) {
553 updateIds(views_, view_ids_);
558 bool GuiApplication::closeAllViews()
560 updateIds(views_, view_ids_);
561 if (views_.empty()) {
562 // quit in CloseEvent will not be triggert
567 map<int, GuiView*> const cmap = views_;
568 map<int, GuiView*>::const_iterator it;
569 for (it = cmap.begin(); it != cmap.end(); ++it) {
570 // TODO: return false when close event was ignored
571 // e.g. quitWriteAll()->'Cancel'
572 // maybe we need something like 'bool closeView()'
574 // unregisterd by the CloseEvent
583 GuiView & GuiApplication::view(int id) const
585 BOOST_ASSERT(views_.find(id) != views_.end());
586 return *views_.find(id)->second;
590 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
592 vector<int>::const_iterator it = view_ids_.begin();
593 vector<int>::const_iterator const end = view_ids_.end();
594 for (; it != end; ++it)
595 view(*it).hideDialog(name, inset);
599 Buffer const * GuiApplication::updateInset(Inset const * inset) const
601 Buffer const * buffer_ = 0;
602 vector<int>::const_iterator it = view_ids_.begin();
603 vector<int>::const_iterator const end = view_ids_.end();
604 for (; it != end; ++it) {
605 Buffer const * ptr = view(*it).updateInset(inset);
613 ////////////////////////////////////////////////////////////////////////
614 // X11 specific stuff goes here...
616 bool GuiApplication::x11EventFilter(XEvent * xev)
622 case SelectionRequest: {
623 if (xev->xselectionrequest.selection != XA_PRIMARY)
625 LYXERR(Debug::GUI, "X requested selection.");
626 BufferView * bv = current_view_->view();
628 docstring const sel = bv->requestSelection();
634 case SelectionClear: {
635 if (xev->xselectionclear.selection != XA_PRIMARY)
637 LYXERR(Debug::GUI, "Lost selection.");
638 BufferView * bv = current_view_->view();
640 bv->clearSelection();
648 } // namespace frontend
651 ////////////////////////////////////////////////////////////////////
655 ////////////////////////////////////////////////////////////////////
657 frontend::FontLoader & theFontLoader()
659 static frontend::NoGuiFontLoader no_gui_font_loader;
662 return no_gui_font_loader;
664 BOOST_ASSERT(frontend::guiApp);
665 return frontend::guiApp->fontLoader();
669 frontend::FontMetrics const & theFontMetrics(Font const & f)
671 return theFontMetrics(f.fontInfo());
675 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
677 static frontend::NoGuiFontMetrics no_gui_font_metrics;
680 return no_gui_font_metrics;
682 BOOST_ASSERT(frontend::guiApp);
683 return frontend::guiApp->fontLoader().metrics(f);
687 frontend::Clipboard & theClipboard()
689 BOOST_ASSERT(frontend::guiApp);
690 return frontend::guiApp->clipboard();
694 frontend::Selection & theSelection()
696 BOOST_ASSERT(frontend::guiApp);
697 return frontend::guiApp->selection();
702 #include "GuiApplication_moc.cpp"