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"
39 #include "FuncRequest.h"
40 #include "FuncStatus.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 void GuiApplication::dispatch(FuncRequest const & cmd)
244 case LFUN_WINDOW_NEW:
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;
289 void GuiApplication::resetGui()
291 map<int, GuiView *>::iterator it;
292 for (it = views_.begin(); it != views_.end(); ++it)
293 it->second->resetDialogs();
295 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
299 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
302 map<int, GuiView *>::const_iterator it;
303 for (it = stdmap.begin(); it != stdmap.end(); ++it)
304 ids.push_back(it->first);
308 void GuiApplication::createView(string const & geometry_arg)
310 updateIds(views_, view_ids_);
312 while (views_.find(id) != views_.end())
314 views_[id] = new GuiView(id);
315 updateIds(views_, view_ids_);
317 GuiView * view = views_[id];
318 theLyXFunc().setLyXView(view);
321 if (!geometry_arg.empty()) {
325 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
326 re.indexIn(toqstr(geometry_arg.c_str()));
327 w = re.cap(1).toInt();
328 h = re.cap(2).toInt();
329 x = re.cap(3).toInt();
330 y = re.cap(4).toInt();
331 view->setGeometry(x, y, w, h);
336 setCurrentView(*view);
342 Clipboard & GuiApplication::clipboard()
348 Selection & GuiApplication::selection()
354 int GuiApplication::exec()
356 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
357 return QApplication::exec();
361 void GuiApplication::exit(int status)
363 QApplication::exit(status);
367 void GuiApplication::execBatchCommands()
369 LyX::ref().execBatchCommands();
373 QString const GuiApplication::romanFontName()
376 font.setKerning(false);
377 font.setStyleHint(QFont::Serif);
378 font.setFamily("serif");
380 return QFontInfo(font).family();
384 QString const GuiApplication::sansFontName()
387 font.setKerning(false);
388 font.setStyleHint(QFont::SansSerif);
389 font.setFamily("sans");
391 return QFontInfo(font).family();
395 QString const GuiApplication::typewriterFontName()
398 font.setKerning(false);
399 font.setStyleHint(QFont::TypeWriter);
400 font.setFamily("monospace");
402 return QFontInfo(font).family();
406 bool GuiApplication::event(QEvent * e)
409 case QEvent::FileOpen: {
410 // Open a file; this happens only on Mac OS X for now
411 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
413 if (!current_view_ || !current_view_->view())
414 // The application is not properly initialized yet.
415 // So we acknowledge the event and delay the file opening
416 // until LyX is ready.
417 // FIXME UNICODE: FileName accept an utf8 encoded string.
418 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
420 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
421 qstring_to_ucs4(foe->file())));
427 return QApplication::event(e);
432 bool GuiApplication::notify(QObject * receiver, QEvent * event)
435 return QApplication::notify(receiver, event);
437 catch (support::ExceptionMessage const & e) {
438 if (e.type_ == support::ErrorException) {
439 Alert::error(e.title_, e.details_);
440 LyX::cref().emergencyCleanup();
441 QApplication::exit(1);
442 } else if (e.type_ == support::WarningException) {
443 Alert::warning(e.title_, e.details_);
447 catch (std::exception const & e) {
448 docstring s = _("LyX has caught an exception, it will now "
449 "attemp to save all unsaved documents and exit."
451 s += from_ascii(e.what());
452 Alert::error(_("Software exception Detected"), s);
453 LyX::cref().emergencyCleanup();
454 QApplication::exit(1);
457 docstring s = _("LyX has caught some really weird exception, it will "
458 "now attemp to save all unsaved documents and exit.");
459 Alert::error(_("Software exception Detected"), s);
460 LyX::cref().emergencyCleanup();
461 QApplication::exit(1);
468 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
470 QColor const & qcol = color_cache_.get(col);
471 if (!qcol.isValid()) {
477 rgbcol.r = qcol.red();
478 rgbcol.g = qcol.green();
479 rgbcol.b = qcol.blue();
484 string const GuiApplication::hexName(ColorCode col)
486 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
490 void GuiApplication::updateColor(ColorCode)
492 // FIXME: Bleh, can't we just clear them all at once ?
493 color_cache_.clear();
497 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
499 SocketNotifier * sn = new SocketNotifier(this, fd, func);
500 socket_notifiers_[fd] = sn;
501 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
505 void GuiApplication::socketDataReceived(int fd)
507 socket_notifiers_[fd]->func_();
511 void GuiApplication::unregisterSocketCallback(int fd)
513 socket_notifiers_.erase(fd);
517 void GuiApplication::commitData(QSessionManager & sm)
519 /// The implementation is required to avoid an application exit
520 /// when session state save is triggered by session manager.
521 /// The default implementation sends a close event to all
522 /// visible top level widgets when session managment allows
524 /// We are changing that to write all unsaved buffers...
525 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
530 void GuiApplication::addMenuTranslator()
532 installTranslator(new MenuTranslator(this));
536 bool GuiApplication::unregisterView(int id)
538 updateIds(views_, view_ids_);
539 BOOST_ASSERT(views_.find(id) != views_.end());
540 BOOST_ASSERT(views_[id]);
542 map<int, GuiView *>::iterator it;
543 for (it = views_.begin(); it != views_.end(); ++it) {
544 if (it->first == id) {
549 updateIds(views_, view_ids_);
554 bool GuiApplication::closeAllViews()
556 updateIds(views_, view_ids_);
557 if (views_.empty()) {
558 // quit in CloseEvent will not be triggert
563 map<int, GuiView*> const cmap = views_;
564 map<int, GuiView*>::const_iterator it;
565 for (it = cmap.begin(); it != cmap.end(); ++it) {
566 // TODO: return false when close event was ignored
567 // e.g. quitWriteAll()->'Cancel'
568 // maybe we need something like 'bool closeView()'
570 // unregisterd by the CloseEvent
579 GuiView & GuiApplication::view(int id) const
581 BOOST_ASSERT(views_.find(id) != views_.end());
582 return *views_.find(id)->second;
586 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
588 vector<int>::const_iterator it = view_ids_.begin();
589 vector<int>::const_iterator const end = view_ids_.end();
590 for (; it != end; ++it)
591 view(*it).hideDialog(name, inset);
595 Buffer const * GuiApplication::updateInset(Inset const * inset) const
597 Buffer const * buffer_ = 0;
598 vector<int>::const_iterator it = view_ids_.begin();
599 vector<int>::const_iterator const end = view_ids_.end();
600 for (; it != end; ++it) {
601 Buffer const * ptr = view(*it).updateInset(inset);
609 ////////////////////////////////////////////////////////////////////////
610 // X11 specific stuff goes here...
612 bool GuiApplication::x11EventFilter(XEvent * xev)
618 case SelectionRequest: {
619 if (xev->xselectionrequest.selection != XA_PRIMARY)
621 LYXERR(Debug::GUI, "X requested selection.");
622 BufferView * bv = current_view_->view();
624 docstring const sel = bv->requestSelection();
630 case SelectionClear: {
631 if (xev->xselectionclear.selection != XA_PRIMARY)
633 LYXERR(Debug::GUI, "Lost selection.");
634 BufferView * bv = current_view_->view();
636 bv->clearSelection();
644 } // namespace frontend
647 ////////////////////////////////////////////////////////////////////
651 ////////////////////////////////////////////////////////////////////
653 frontend::FontLoader & theFontLoader()
655 static frontend::NoGuiFontLoader no_gui_font_loader;
658 return no_gui_font_loader;
660 BOOST_ASSERT(frontend::guiApp);
661 return frontend::guiApp->fontLoader();
665 frontend::FontMetrics const & theFontMetrics(Font const & f)
667 return theFontMetrics(f.fontInfo());
671 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
673 static frontend::NoGuiFontMetrics no_gui_font_metrics;
676 return no_gui_font_metrics;
678 BOOST_ASSERT(frontend::guiApp);
679 return frontend::guiApp->fontLoader().metrics(f);
683 frontend::Clipboard & theClipboard()
685 BOOST_ASSERT(frontend::guiApp);
686 return frontend::guiApp->clipboard();
690 frontend::Selection & theSelection()
692 BOOST_ASSERT(frontend::guiApp);
693 return frontend::guiApp->selection();
698 #include "GuiApplication_moc.cpp"