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"
22 #include "frontends/alert.h"
24 #include "graphics/LoaderQueue.h"
26 #include "support/ExceptionMessage.h"
27 #include "support/FileName.h"
28 #include "support/lstrings.h"
29 #include "support/os.h"
30 #include "support/Package.h"
32 #include "BufferList.h"
33 #include "BufferView.h"
35 #include "FuncRequest.h"
42 #include <QApplication>
45 #include <QFileOpenEvent>
47 #include <QLibraryInfo>
48 #include <QPixmapCache>
50 #include <QSessionManager>
51 #include <QSocketNotifier>
54 #include <QTranslator>
58 #include <X11/Xatom.h>
64 #include <boost/bind.hpp>
76 frontend::Application * createApplication(int & argc, char * argv[])
78 return new frontend::GuiApplication(argc, argv);
84 class SocketNotifier : public QSocketNotifier
87 /// connect a connection notification from the LyXServerSocket
88 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
89 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
93 /// The callback function
94 Application::SocketCallback func_;
98 ////////////////////////////////////////////////////////////////////////
99 // Mac specific stuff goes here...
101 class MenuTranslator : public QTranslator
104 MenuTranslator(QObject * parent)
105 : QTranslator(parent)
108 QString translate(const char * /*context*/,
109 const char * sourceText,
110 const char * /*comment*/ = 0)
112 string const s = sourceText;
113 if (s == N_("About %1") || s == N_("Preferences")
114 || s == N_("Reconfigure") || s == N_("Quit %1"))
122 ///////////////////////////////////////////////////////////////
123 // You can find more platform specific stuff
124 // at the end of this file...
125 ///////////////////////////////////////////////////////////////
128 using support::FileName;
130 GuiApplication * guiApp;
133 GuiApplication::GuiApplication(int & argc, char ** argv)
134 : QApplication(argc, argv), Application()
136 QString app_name = "LyX";
137 QCoreApplication::setOrganizationName(app_name);
138 QCoreApplication::setOrganizationDomain("lyx.org");
139 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
141 // Qt bug? setQuitOnLastWindowClosed(true); does not work
142 setQuitOnLastWindowClosed(false);
145 // doubleClickInterval() is 400 ms on X11 which is just too long.
146 // On Windows and Mac OS X, the operating system's value is used.
147 // On Microsoft Windows, calling this function sets the double
148 // click interval for all applications. So we don't!
149 QApplication::setDoubleClickInterval(300);
152 // install translation file for Qt built-in dialogs
153 QString language_name = QString("qt_") + QLocale::system().name();
155 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
156 // Short-named translator can be loaded from a long name, but not the
157 // opposite. Therefore, long name should be used without truncation.
158 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
159 if (qt_trans_.load(language_name,
160 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
162 installTranslator(&qt_trans_);
163 // even if the language calls for RtL, don't do that
164 setLayoutDirection(Qt::LeftToRight);
165 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
166 << fromqstr(language_name));
168 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
169 << fromqstr(language_name));
172 // This allows to translate the strings that appear in the LyX menu.
176 using namespace lyx::graphics;
178 Image::newImage = boost::bind(&GuiImage::newImage);
179 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
181 // needs to be done before reading lyxrc
183 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
185 LoaderQueue::setPriority(10,100);
189 // Set the cache to 5120 kilobytes which corresponds to screen size of
190 // 1280 by 1024 pixels with a color depth of 32 bits.
191 QPixmapCache::setCacheLimit(5120);
195 GuiApplication::~GuiApplication()
197 socket_notifiers_.clear();
201 LyXView & GuiApplication::createView(string const & geometry_arg)
203 int const id = createRegisteredView();
204 GuiView * view = views_[id];
205 theLyXFunc().setLyXView(view);
209 if (!geometry_arg.empty()) {
213 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
214 re.indexIn(toqstr(geometry_arg.c_str()));
215 w = re.cap(1).toInt();
216 h = re.cap(2).toInt();
217 x = re.cap(3).toInt();
218 y = re.cap(4).toInt();
219 view->setGeometry(x, y, w, h);
224 setCurrentView(*view);
232 Clipboard & GuiApplication::clipboard()
238 Selection & GuiApplication::selection()
244 int GuiApplication::exec()
246 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
247 return QApplication::exec();
251 void GuiApplication::exit(int status)
253 QApplication::exit(status);
257 void GuiApplication::execBatchCommands()
259 LyX::ref().execBatchCommands();
263 string const GuiApplication::romanFontName()
266 font.setKerning(false);
267 font.setStyleHint(QFont::Serif);
268 font.setFamily("serif");
270 return fromqstr(QFontInfo(font).family());
274 string const GuiApplication::sansFontName()
277 font.setKerning(false);
278 font.setStyleHint(QFont::SansSerif);
279 font.setFamily("sans");
281 return fromqstr(QFontInfo(font).family());
285 string const GuiApplication::typewriterFontName()
288 font.setKerning(false);
289 font.setStyleHint(QFont::TypeWriter);
290 font.setFamily("monospace");
292 return fromqstr(QFontInfo(font).family());
296 bool GuiApplication::event(QEvent * e)
299 case QEvent::FileOpen: {
300 // Open a file; this happens only on Mac OS X for now
301 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
303 if (!currentView() || !currentView()->view())
304 // The application is not properly initialized yet.
305 // So we acknowledge the event and delay the file opening
306 // until LyX is ready.
307 // FIXME UNICODE: FileName accept an utf8 encoded string.
308 LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
310 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
311 qstring_to_ucs4(foe->file())));
317 return QApplication::event(e);
322 bool GuiApplication::notify(QObject * receiver, QEvent * event)
325 return QApplication::notify(receiver, event);
327 catch (support::ExceptionMessage const & e) {
328 if (e.type_ == support::ErrorException) {
329 Alert::error(e.title_, e.details_);
330 LyX::cref().emergencyCleanup();
331 QApplication::exit(1);
332 } else if (e.type_ == support::WarningException) {
333 Alert::warning(e.title_, e.details_);
337 catch (std::exception const & e) {
338 docstring s = _("LyX has caught an exception, it will now "
339 "attemp to save all unsaved documents and exit."
341 s += from_ascii(e.what());
342 Alert::error(_("Software exception Detected"), s);
343 LyX::cref().emergencyCleanup();
344 QApplication::exit(1);
347 docstring s = _("LyX has caught some really weird exception, it will "
348 "now attemp to save all unsaved documents and exit.");
349 Alert::error(_("Software exception Detected"), s);
350 LyX::cref().emergencyCleanup();
351 QApplication::exit(1);
358 void GuiApplication::syncEvents()
360 // This is the ONLY place where processEvents may be called.
361 // During screen update/ redraw, this method is disabled to
362 // prevent keyboard events being handed to the LyX core, where
363 // they could cause re-entrant calls to screen update.
364 processEvents(QEventLoop::ExcludeUserInputEvents);
368 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
370 QColor const & qcol = color_cache_.get(col);
371 if (!qcol.isValid()) {
377 rgbcol.r = qcol.red();
378 rgbcol.g = qcol.green();
379 rgbcol.b = qcol.blue();
384 string const GuiApplication::hexName(ColorCode col)
386 return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
390 void GuiApplication::updateColor(ColorCode)
392 // FIXME: Bleh, can't we just clear them all at once ?
393 color_cache_.clear();
397 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
399 SocketNotifier * sn = new SocketNotifier(this, fd, func);
400 socket_notifiers_[fd] = sn;
401 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
405 void GuiApplication::socketDataReceived(int fd)
407 socket_notifiers_[fd]->func_();
411 void GuiApplication::unregisterSocketCallback(int fd)
413 socket_notifiers_.erase(fd);
417 void GuiApplication::commitData(QSessionManager & sm)
419 /// The implementation is required to avoid an application exit
420 /// when session state save is triggered by session manager.
421 /// The default implementation sends a close event to all
422 /// visible top level widgets when session managment allows
424 /// We are changing that to write all unsaved buffers...
425 if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
430 void GuiApplication::addMenuTranslator()
432 installTranslator(new MenuTranslator(this));
436 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
439 map<int, GuiView *>::const_iterator it;
440 for (it = stdmap.begin(); it != stdmap.end(); ++it)
441 ids.push_back(it->first);
445 int GuiApplication::createRegisteredView()
447 updateIds(views_, view_ids_);
449 while (views_.find(id) != views_.end())
451 views_[id] = new GuiView(id);
452 updateIds(views_, view_ids_);
457 bool GuiApplication::unregisterView(int id)
459 updateIds(views_, view_ids_);
460 BOOST_ASSERT(views_.find(id) != views_.end());
461 BOOST_ASSERT(views_[id]);
463 map<int, GuiView *>::iterator it;
464 for (it = views_.begin(); it != views_.end(); ++it) {
465 if (it->first == id) {
470 updateIds(views_, view_ids_);
475 bool GuiApplication::closeAllViews()
477 updateIds(views_, view_ids_);
478 if (views_.empty()) {
479 // quit in CloseEvent will not be triggert
484 map<int, GuiView*> const cmap = views_;
485 map<int, GuiView*>::const_iterator it;
486 for (it = cmap.begin(); it != cmap.end(); ++it) {
487 // TODO: return false when close event was ignored
488 // e.g. quitWriteAll()->'Cancel'
489 // maybe we need something like 'bool closeView()'
491 // unregisterd by the CloseEvent
500 LyXView & GuiApplication::view(int id) const
502 BOOST_ASSERT(views_.find(id) != views_.end());
503 return *views_.find(id)->second;
507 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
509 vector<int>::const_iterator it = view_ids_.begin();
510 vector<int>::const_iterator const end = view_ids_.end();
511 for (; it != end; ++it)
512 view(*it).getDialogs().hide(name, inset);
516 Buffer const * GuiApplication::updateInset(Inset const * inset) const
518 Buffer const * buffer_ = 0;
519 vector<int>::const_iterator it = view_ids_.begin();
520 vector<int>::const_iterator const end = view_ids_.end();
521 for (; it != end; ++it) {
522 Buffer const * ptr = view(*it).updateInset(inset);
530 ////////////////////////////////////////////////////////////////////////
531 // X11 specific stuff goes here...
533 bool GuiApplication::x11EventFilter(XEvent * xev)
539 case SelectionRequest: {
540 if (xev->xselectionrequest.selection != XA_PRIMARY)
542 LYXERR(Debug::GUI, "X requested selection.");
543 BufferView * bv = currentView()->view();
545 docstring const sel = bv->requestSelection();
551 case SelectionClear: {
552 if (xev->xselectionclear.selection != XA_PRIMARY)
554 LYXERR(Debug::GUI, "Lost selection.");
555 BufferView * bv = currentView()->view();
557 bv->clearSelection();
565 } // namespace frontend
568 #include "GuiApplication_moc.cpp"