]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Introducing Application::resetGui() that will reset all dialogs in all lyx windows...
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "qt_helpers.h"
18 #include "GuiImage.h"
19 #include "GuiView.h"
20
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"
27
28 #include "graphics/LoaderQueue.h"
29
30 #include "support/ExceptionMessage.h"
31 #include "support/FileName.h"
32 #include "support/lstrings.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35
36 #include "BufferList.h"
37 #include "BufferView.h"
38 #include "debug.h"
39 #include "Font.h"
40 #include "FuncRequest.h"
41 #include "gettext.h"
42 #include "LyX.h"
43 #include "LyXFunc.h"
44 #include "LyXRC.h"
45 #include "version.h"
46
47 #include <QApplication>
48 #include <QClipboard>
49 #include <QEventLoop>
50 #include <QFileOpenEvent>
51 #include <QLocale>
52 #include <QLibraryInfo>
53 #include <QPixmapCache>
54 #include <QRegExp>
55 #include <QSessionManager>
56 #include <QSocketNotifier>
57 #include <QTextCodec>
58 #include <QTimer>
59 #include <QTranslator>
60 #include <QWidget>
61
62 #ifdef Q_WS_X11
63 #include <X11/Xatom.h>
64 #include <X11/Xlib.h>
65 #undef CursorShape
66 #undef None
67 #endif
68
69 #include <boost/bind.hpp>
70
71 #include <exception>
72
73 using std::endl;
74 using std::map;
75 using std::string;
76 using std::vector;
77
78
79 namespace lyx {
80
81 frontend::Application * createApplication(int & argc, char * argv[])
82 {
83         return new frontend::GuiApplication(argc, argv);
84 }
85
86
87 namespace frontend {
88
89 class SocketNotifier : public QSocketNotifier
90 {
91 public:
92         /// connect a connection notification from the LyXServerSocket
93         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
94                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
95         {}
96
97 public:
98         /// The callback function
99         Application::SocketCallback func_;
100 };
101
102
103 ////////////////////////////////////////////////////////////////////////
104 // Mac specific stuff goes here...
105
106 class MenuTranslator : public QTranslator
107 {
108 public:
109         MenuTranslator(QObject * parent)
110                 : QTranslator(parent)
111         {}
112
113         QString translate(const char * /*context*/, 
114           const char * sourceText, 
115           const char * /*comment*/ = 0) 
116         {
117                 string const s = sourceText;
118                 if (s == N_("About %1") || s == N_("Preferences") 
119                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
120                         return qt_(s);
121                 else 
122                         return QString();
123         }
124 };
125
126
127 ///////////////////////////////////////////////////////////////
128 // You can find more platform specific stuff
129 // at the end of this file...
130 ///////////////////////////////////////////////////////////////
131
132
133 using support::FileName;
134
135 GuiApplication * guiApp;
136
137
138 GuiApplication::GuiApplication(int & argc, char ** argv)
139         : QApplication(argc, argv), Application(), current_view_(0)
140 {
141         QString app_name = "LyX";
142         QCoreApplication::setOrganizationName(app_name);
143         QCoreApplication::setOrganizationDomain("lyx.org");
144         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
145
146         // Qt bug? setQuitOnLastWindowClosed(true); does not work
147         setQuitOnLastWindowClosed(false);
148
149 #ifdef Q_WS_X11
150         // doubleClickInterval() is 400 ms on X11 which is just too long.
151         // On Windows and Mac OS X, the operating system's value is used.
152         // On Microsoft Windows, calling this function sets the double
153         // click interval for all applications. So we don't!
154         QApplication::setDoubleClickInterval(300);
155 #endif
156
157         // install translation file for Qt built-in dialogs
158         QString language_name = QString("qt_") + QLocale::system().name();
159         
160         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
161         // Short-named translator can be loaded from a long name, but not the
162         // opposite. Therefore, long name should be used without truncation.
163         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
164         if (qt_trans_.load(language_name,
165                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
166         {
167                 installTranslator(&qt_trans_);
168                 // even if the language calls for RtL, don't do that
169                 setLayoutDirection(Qt::LeftToRight);
170                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
171                         << fromqstr(language_name));
172         } else
173                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
174                         << fromqstr(language_name));
175
176 #ifdef Q_WS_MACX
177         // This allows to translate the strings that appear in the LyX menu.
178         addMenuTranslator();
179 #endif
180
181         using namespace lyx::graphics;
182
183         Image::newImage = boost::bind(&GuiImage::newImage);
184         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
185
186         // needs to be done before reading lyxrc
187         QWidget w;
188         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
189
190         LoaderQueue::setPriority(10,100);
191
192         guiApp = this;
193
194         // Set the cache to 5120 kilobytes which corresponds to screen size of
195         // 1280 by 1024 pixels with a color depth of 32 bits.
196         QPixmapCache::setCacheLimit(5120);
197
198         // Initialize RC Fonts
199         if (lyxrc.roman_font_name.empty())
200                 lyxrc.roman_font_name = fromqstr(romanFontName());
201
202         if (lyxrc.sans_font_name.empty())
203                 lyxrc.sans_font_name = fromqstr(sansFontName());
204
205         if (lyxrc.typewriter_font_name.empty())
206                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
207 }
208
209
210 GuiApplication::~GuiApplication()
211 {
212         socket_notifiers_.clear();
213 }
214
215
216 void GuiApplication::resetGui()
217 {
218         map<int, GuiView *>::iterator it;
219         for (it = views_.begin(); it != views_.end(); ++it)
220                 it->second->resetDialogs();
221 }
222
223
224 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
225 {
226         ids.clear();
227         map<int, GuiView *>::const_iterator it;
228         for (it = stdmap.begin(); it != stdmap.end(); ++it)
229                 ids.push_back(it->first);
230 }
231
232
233 LyXView & GuiApplication::createView(string const & geometry_arg)
234 {
235         updateIds(views_, view_ids_);
236         int id = 0;
237         while (views_.find(id) != views_.end())
238                 id++;
239         views_[id] = new GuiView(id);
240         updateIds(views_, view_ids_);
241
242         GuiView * view  = views_[id];
243         theLyXFunc().setLyXView(view);
244
245         view->show();
246         if (!geometry_arg.empty()) {
247 #ifdef Q_WS_WIN
248                 int x, y;
249                 int w, h;
250                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
251                 re.indexIn(toqstr(geometry_arg.c_str()));
252                 w = re.cap(1).toInt();
253                 h = re.cap(2).toInt();
254                 x = re.cap(3).toInt();
255                 y = re.cap(4).toInt();
256                 view->setGeometry(x, y, w, h);
257 #endif
258         }
259         view->setFocus();
260
261         setCurrentView(*view);
262
263         return *view;
264 }
265
266
267
268
269 Clipboard & GuiApplication::clipboard()
270 {
271         return clipboard_;
272 }
273
274
275 Selection & GuiApplication::selection()
276 {
277         return selection_;
278 }
279
280
281 int GuiApplication::exec()
282 {
283         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
284         return QApplication::exec();
285 }
286
287
288 void GuiApplication::exit(int status)
289 {
290         QApplication::exit(status);
291 }
292
293
294 void GuiApplication::execBatchCommands()
295 {
296         LyX::ref().execBatchCommands();
297 }
298
299
300 QString const GuiApplication::romanFontName()
301 {
302         QFont font;
303         font.setKerning(false);
304         font.setStyleHint(QFont::Serif);
305         font.setFamily("serif");
306
307         return QFontInfo(font).family();
308 }
309
310
311 QString const GuiApplication::sansFontName()
312 {
313         QFont font;
314         font.setKerning(false);
315         font.setStyleHint(QFont::SansSerif);
316         font.setFamily("sans");
317
318         return QFontInfo(font).family();
319 }
320
321
322 QString const GuiApplication::typewriterFontName()
323 {
324         QFont font;
325         font.setKerning(false);
326         font.setStyleHint(QFont::TypeWriter);
327         font.setFamily("monospace");
328
329         return QFontInfo(font).family();
330 }
331
332
333 bool GuiApplication::event(QEvent * e)
334 {
335         switch(e->type()) {
336         case QEvent::FileOpen: {
337                 // Open a file; this happens only on Mac OS X for now
338                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
339
340                 if (!current_view_ || !current_view_->view())
341                         // The application is not properly initialized yet.
342                         // So we acknowledge the event and delay the file opening
343                         // until LyX is ready.
344                         // FIXME UNICODE: FileName accept an utf8 encoded string.
345                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
346                 else
347                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
348                                 qstring_to_ucs4(foe->file())));
349
350                 e->accept();
351                 return true;
352         }
353         default:
354                 return QApplication::event(e);
355         }
356 }
357
358
359 bool GuiApplication::notify(QObject * receiver, QEvent * event)
360 {
361         try {
362                 return QApplication::notify(receiver, event);
363         }
364         catch (support::ExceptionMessage const & e) {
365                 if (e.type_ == support::ErrorException) {
366                         Alert::error(e.title_, e.details_);
367                         LyX::cref().emergencyCleanup();
368                         QApplication::exit(1);
369                 } else if (e.type_ == support::WarningException) {
370                         Alert::warning(e.title_, e.details_);
371                         return false;
372                 }
373         }
374         catch (std::exception const & e) {
375                 docstring s = _("LyX has caught an exception, it will now "
376                         "attemp to save all unsaved documents and exit."
377                         "\n\nException: ");
378                 s += from_ascii(e.what());
379                 Alert::error(_("Software exception Detected"), s);
380                 LyX::cref().emergencyCleanup();
381                 QApplication::exit(1);
382         }
383         catch (...) {
384                 docstring s = _("LyX has caught some really weird exception, it will "
385                         "now attemp to save all unsaved documents and exit.");
386                 Alert::error(_("Software exception Detected"), s);
387                 LyX::cref().emergencyCleanup();
388                 QApplication::exit(1);
389         }
390
391         return false;
392 }
393
394
395 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
396 {
397         QColor const & qcol = color_cache_.get(col);
398         if (!qcol.isValid()) {
399                 rgbcol.r = 0;
400                 rgbcol.g = 0;
401                 rgbcol.b = 0;
402                 return false;
403         }
404         rgbcol.r = qcol.red();
405         rgbcol.g = qcol.green();
406         rgbcol.b = qcol.blue();
407         return true;
408 }
409
410
411 string const GuiApplication::hexName(ColorCode col)
412 {
413         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
414 }
415
416
417 void GuiApplication::updateColor(ColorCode)
418 {
419         // FIXME: Bleh, can't we just clear them all at once ?
420         color_cache_.clear();
421 }
422
423
424 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
425 {
426         SocketNotifier * sn = new SocketNotifier(this, fd, func);
427         socket_notifiers_[fd] = sn;
428         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
429 }
430
431
432 void GuiApplication::socketDataReceived(int fd)
433 {
434         socket_notifiers_[fd]->func_();
435 }
436
437
438 void GuiApplication::unregisterSocketCallback(int fd)
439 {
440         socket_notifiers_.erase(fd);
441 }
442
443
444 void GuiApplication::commitData(QSessionManager & sm)
445 {
446         /// The implementation is required to avoid an application exit
447         /// when session state save is triggered by session manager.
448         /// The default implementation sends a close event to all
449         /// visible top level widgets when session managment allows
450         /// interaction.
451         /// We are changing that to write all unsaved buffers...
452         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
453                 sm.cancel();
454 }
455
456
457 void GuiApplication::addMenuTranslator()
458 {
459         installTranslator(new MenuTranslator(this));
460 }
461
462
463 bool GuiApplication::unregisterView(int id)
464 {
465         updateIds(views_, view_ids_);
466         BOOST_ASSERT(views_.find(id) != views_.end());
467         BOOST_ASSERT(views_[id]);
468
469         map<int, GuiView *>::iterator it;
470         for (it = views_.begin(); it != views_.end(); ++it) {
471                 if (it->first == id) {
472                         views_.erase(id);
473                         break;
474                 }
475         }
476         updateIds(views_, view_ids_);
477         return true;
478 }
479
480
481 bool GuiApplication::closeAllViews()
482 {
483         updateIds(views_, view_ids_);
484         if (views_.empty()) {
485                 // quit in CloseEvent will not be triggert
486                 qApp->quit();
487                 return true;
488         }
489
490         map<int, GuiView*> const cmap = views_;
491         map<int, GuiView*>::const_iterator it;
492         for (it = cmap.begin(); it != cmap.end(); ++it) {
493                 // TODO: return false when close event was ignored
494                 //       e.g. quitWriteAll()->'Cancel'
495                 //       maybe we need something like 'bool closeView()'
496                 it->second->close();
497                 // unregisterd by the CloseEvent
498         }
499
500         views_.clear();
501         view_ids_.clear();
502         return true;
503 }
504
505
506 GuiView & GuiApplication::view(int id) const
507 {
508         BOOST_ASSERT(views_.find(id) != views_.end());
509         return *views_.find(id)->second;
510 }
511
512
513 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
514 {
515         vector<int>::const_iterator it = view_ids_.begin();
516         vector<int>::const_iterator const end = view_ids_.end();
517         for (; it != end; ++it)
518                 view(*it).hideDialog(name, inset);
519 }
520
521
522 Buffer const * GuiApplication::updateInset(Inset const * inset) const
523 {
524         Buffer const * buffer_ = 0;
525         vector<int>::const_iterator it = view_ids_.begin();
526         vector<int>::const_iterator const end = view_ids_.end();
527         for (; it != end; ++it) {
528                 Buffer const * ptr = view(*it).updateInset(inset);
529                 if (ptr)
530                         buffer_ = ptr;
531         }
532         return buffer_;
533 }
534
535
536 ////////////////////////////////////////////////////////////////////////
537 // X11 specific stuff goes here...
538 #ifdef Q_WS_X11
539 bool GuiApplication::x11EventFilter(XEvent * xev)
540 {
541         if (!current_view_)
542                 return false;
543
544         switch (xev->type) {
545         case SelectionRequest: {
546                 if (xev->xselectionrequest.selection != XA_PRIMARY)
547                         break;
548                 LYXERR(Debug::GUI, "X requested selection.");
549                 BufferView * bv = current_view_->view();
550                 if (bv) {
551                         docstring const sel = bv->requestSelection();
552                         if (!sel.empty())
553                                 selection_.put(sel);
554                 }
555                 break;
556         }
557         case SelectionClear: {
558                 if (xev->xselectionclear.selection != XA_PRIMARY)
559                         break;
560                 LYXERR(Debug::GUI, "Lost selection.");
561                 BufferView * bv = current_view_->view();
562                 if (bv)
563                         bv->clearSelection();
564                 break;
565         }
566         }
567         return false;
568 }
569 #endif
570
571 } // namespace frontend
572
573
574 ////////////////////////////////////////////////////////////////////
575 //
576 // Font stuff
577 //
578 ////////////////////////////////////////////////////////////////////
579
580 frontend::FontLoader & theFontLoader()
581 {
582         static frontend::NoGuiFontLoader no_gui_font_loader;
583
584         if (!use_gui)
585                 return no_gui_font_loader;
586
587         BOOST_ASSERT(frontend::guiApp);
588         return frontend::guiApp->fontLoader();
589 }
590
591
592 frontend::FontMetrics const & theFontMetrics(Font const & f)
593 {
594         return theFontMetrics(f.fontInfo());
595 }
596
597
598 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
599 {
600         static frontend::NoGuiFontMetrics no_gui_font_metrics;
601
602         if (!use_gui)
603                 return no_gui_font_metrics;
604
605         BOOST_ASSERT(frontend::guiApp);
606         return frontend::guiApp->fontLoader().metrics(f);
607 }
608
609
610 frontend::Clipboard & theClipboard()
611 {
612         BOOST_ASSERT(frontend::guiApp);
613         return frontend::guiApp->clipboard();
614 }
615
616
617 frontend::Selection & theSelection()
618 {
619         BOOST_ASSERT(frontend::guiApp);
620         return frontend::guiApp->selection();
621 }
622
623 } // namespace lyx
624
625 #include "GuiApplication_moc.cpp"