]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
merge GuiView/Dialogs
[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()
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
199
200 GuiApplication::~GuiApplication()
201 {
202         socket_notifiers_.clear();
203 }
204
205
206 LyXView & GuiApplication::createView(string const & geometry_arg)
207 {
208         int const id = createRegisteredView();
209         GuiView * view  = views_[id];
210         theLyXFunc().setLyXView(view);
211
212         view->init();
213         view->show();
214         if (!geometry_arg.empty()) {
215 #ifdef Q_WS_WIN
216                 int x, y;
217                 int w, h;
218                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
219                 re.indexIn(toqstr(geometry_arg.c_str()));
220                 w = re.cap(1).toInt();
221                 h = re.cap(2).toInt();
222                 x = re.cap(3).toInt();
223                 y = re.cap(4).toInt();
224                 view->setGeometry(x, y, w, h);
225 #endif
226         }
227         view->setFocus();
228
229         setCurrentView(*view);
230
231         return *view;
232 }
233
234
235
236
237 Clipboard & GuiApplication::clipboard()
238 {
239         return clipboard_;
240 }
241
242
243 Selection & GuiApplication::selection()
244 {
245         return selection_;
246 }
247
248
249 int GuiApplication::exec()
250 {
251         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
252         return QApplication::exec();
253 }
254
255
256 void GuiApplication::exit(int status)
257 {
258         QApplication::exit(status);
259 }
260
261
262 void GuiApplication::execBatchCommands()
263 {
264         LyX::ref().execBatchCommands();
265 }
266
267
268 string const GuiApplication::romanFontName()
269 {
270         QFont font;
271         font.setKerning(false);
272         font.setStyleHint(QFont::Serif);
273         font.setFamily("serif");
274
275         return fromqstr(QFontInfo(font).family());
276 }
277
278
279 string const GuiApplication::sansFontName()
280 {
281         QFont font;
282         font.setKerning(false);
283         font.setStyleHint(QFont::SansSerif);
284         font.setFamily("sans");
285
286         return fromqstr(QFontInfo(font).family());
287 }
288
289
290 string const GuiApplication::typewriterFontName()
291 {
292         QFont font;
293         font.setKerning(false);
294         font.setStyleHint(QFont::TypeWriter);
295         font.setFamily("monospace");
296
297         return fromqstr(QFontInfo(font).family());
298 }
299
300
301 bool GuiApplication::event(QEvent * e)
302 {
303         switch(e->type()) {
304         case QEvent::FileOpen: {
305                 // Open a file; this happens only on Mac OS X for now
306                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
307
308                 if (!currentView() || !currentView()->view())
309                         // The application is not properly initialized yet.
310                         // So we acknowledge the event and delay the file opening
311                         // until LyX is ready.
312                         // FIXME UNICODE: FileName accept an utf8 encoded string.
313                         LyX::ref().addFileToLoad(FileName(fromqstr(foe->file())));
314                 else
315                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
316                                 qstring_to_ucs4(foe->file())));
317
318                 e->accept();
319                 return true;
320         }
321         default:
322                 return QApplication::event(e);
323         }
324 }
325
326
327 bool GuiApplication::notify(QObject * receiver, QEvent * event)
328 {
329         try {
330                 return QApplication::notify(receiver, event);
331         }
332         catch (support::ExceptionMessage const & e) {
333                 if (e.type_ == support::ErrorException) {
334                         Alert::error(e.title_, e.details_);
335                         LyX::cref().emergencyCleanup();
336                         QApplication::exit(1);
337                 } else if (e.type_ == support::WarningException) {
338                         Alert::warning(e.title_, e.details_);
339                         return false;
340                 }
341         }
342         catch (std::exception const & e) {
343                 docstring s = _("LyX has caught an exception, it will now "
344                         "attemp to save all unsaved documents and exit."
345                         "\n\nException: ");
346                 s += from_ascii(e.what());
347                 Alert::error(_("Software exception Detected"), s);
348                 LyX::cref().emergencyCleanup();
349                 QApplication::exit(1);
350         }
351         catch (...) {
352                 docstring s = _("LyX has caught some really weird exception, it will "
353                         "now attemp to save all unsaved documents and exit.");
354                 Alert::error(_("Software exception Detected"), s);
355                 LyX::cref().emergencyCleanup();
356                 QApplication::exit(1);
357         }
358
359         return false;
360 }
361
362
363 void GuiApplication::syncEvents()
364 {
365         // This is the ONLY place where processEvents may be called.
366         // During screen update/ redraw, this method is disabled to
367         // prevent keyboard events being handed to the LyX core, where
368         // they could cause re-entrant calls to screen update.
369         processEvents(QEventLoop::ExcludeUserInputEvents);
370 }
371
372
373 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
374 {
375         QColor const & qcol = color_cache_.get(col);
376         if (!qcol.isValid()) {
377                 rgbcol.r = 0;
378                 rgbcol.g = 0;
379                 rgbcol.b = 0;
380                 return false;
381         }
382         rgbcol.r = qcol.red();
383         rgbcol.g = qcol.green();
384         rgbcol.b = qcol.blue();
385         return true;
386 }
387
388
389 string const GuiApplication::hexName(ColorCode col)
390 {
391         return support::ltrim(fromqstr(color_cache_.get(col).name()), "#");
392 }
393
394
395 void GuiApplication::updateColor(ColorCode)
396 {
397         // FIXME: Bleh, can't we just clear them all at once ?
398         color_cache_.clear();
399 }
400
401
402 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
403 {
404         SocketNotifier * sn = new SocketNotifier(this, fd, func);
405         socket_notifiers_[fd] = sn;
406         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
407 }
408
409
410 void GuiApplication::socketDataReceived(int fd)
411 {
412         socket_notifiers_[fd]->func_();
413 }
414
415
416 void GuiApplication::unregisterSocketCallback(int fd)
417 {
418         socket_notifiers_.erase(fd);
419 }
420
421
422 void GuiApplication::commitData(QSessionManager & sm)
423 {
424         /// The implementation is required to avoid an application exit
425         /// when session state save is triggered by session manager.
426         /// The default implementation sends a close event to all
427         /// visible top level widgets when session managment allows
428         /// interaction.
429         /// We are changing that to write all unsaved buffers...
430         if (sm.allowsInteraction() && !theBufferList().quitWriteAll())
431                 sm.cancel();
432 }
433
434
435 void GuiApplication::addMenuTranslator()
436 {
437         installTranslator(new MenuTranslator(this));
438 }
439
440
441 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
442 {
443         ids.clear();
444         map<int, GuiView *>::const_iterator it;
445         for (it = stdmap.begin(); it != stdmap.end(); ++it)
446                 ids.push_back(it->first);
447 }
448
449
450 int GuiApplication::createRegisteredView()
451 {
452         updateIds(views_, view_ids_);
453         int id = 0;
454         while (views_.find(id) != views_.end())
455                 id++;
456         views_[id] = new GuiView(id);
457         updateIds(views_, view_ids_);
458         return id;
459 }
460
461
462 bool GuiApplication::unregisterView(int id)
463 {
464         updateIds(views_, view_ids_);
465         BOOST_ASSERT(views_.find(id) != views_.end());
466         BOOST_ASSERT(views_[id]);
467
468         map<int, GuiView *>::iterator it;
469         for (it = views_.begin(); it != views_.end(); ++it) {
470                 if (it->first == id) {
471                         views_.erase(id);
472                         break;
473                 }
474         }
475         updateIds(views_, view_ids_);
476         return true;
477 }
478
479
480 bool GuiApplication::closeAllViews()
481 {
482         updateIds(views_, view_ids_);
483         if (views_.empty()) {
484                 // quit in CloseEvent will not be triggert
485                 qApp->quit();
486                 return true;
487         }
488
489         map<int, GuiView*> const cmap = views_;
490         map<int, GuiView*>::const_iterator it;
491         for (it = cmap.begin(); it != cmap.end(); ++it) {
492                 // TODO: return false when close event was ignored
493                 //       e.g. quitWriteAll()->'Cancel'
494                 //       maybe we need something like 'bool closeView()'
495                 it->second->close();
496                 // unregisterd by the CloseEvent
497         }
498
499         views_.clear();
500         view_ids_.clear();
501         return true;
502 }
503
504
505 LyXView & GuiApplication::view(int id) const
506 {
507         BOOST_ASSERT(views_.find(id) != views_.end());
508         return *views_.find(id)->second;
509 }
510
511
512 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
513 {
514         vector<int>::const_iterator it = view_ids_.begin();
515         vector<int>::const_iterator const end = view_ids_.end();
516         for (; it != end; ++it)
517                 view(*it).hideDialog(name, inset);
518 }
519
520
521 Buffer const * GuiApplication::updateInset(Inset const * inset) const
522 {
523         Buffer const * buffer_ = 0;
524         vector<int>::const_iterator it = view_ids_.begin();
525         vector<int>::const_iterator const end = view_ids_.end();
526         for (; it != end; ++it) {
527                 Buffer const * ptr = view(*it).updateInset(inset);
528                 if (ptr)
529                         buffer_ = ptr;
530         }
531         return buffer_;
532 }
533
534
535 ////////////////////////////////////////////////////////////////////////
536 // X11 specific stuff goes here...
537 #ifdef Q_WS_X11
538 bool GuiApplication::x11EventFilter(XEvent * xev)
539 {
540         if (!currentView())
541                 return false;
542
543         switch (xev->type) {
544         case SelectionRequest: {
545                 if (xev->xselectionrequest.selection != XA_PRIMARY)
546                         break;
547                 LYXERR(Debug::GUI, "X requested selection.");
548                 BufferView * bv = currentView()->view();
549                 if (bv) {
550                         docstring const sel = bv->requestSelection();
551                         if (!sel.empty())
552                                 selection_.put(sel);
553                 }
554                 break;
555         }
556         case SelectionClear: {
557                 if (xev->xselectionclear.selection != XA_PRIMARY)
558                         break;
559                 LYXERR(Debug::GUI, "Lost selection.");
560                 BufferView * bv = currentView()->view();
561                 if (bv)
562                         bv->clearSelection();
563                 break;
564         }
565         }
566         return false;
567 }
568 #endif
569
570 } // namespace frontend
571
572
573 ////////////////////////////////////////////////////////////////////
574 //
575 // Font stuff
576 //
577 ////////////////////////////////////////////////////////////////////
578
579 frontend::FontLoader & theFontLoader()
580 {
581         static frontend::NoGuiFontLoader no_gui_font_loader;
582
583         if (!use_gui)
584                 return no_gui_font_loader;
585
586         BOOST_ASSERT(theApp());
587         return theApp()->fontLoader();
588 }
589
590
591 frontend::FontMetrics const & theFontMetrics(Font const & f)
592 {
593         return theFontMetrics(f.fontInfo());
594 }
595
596
597 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
598 {
599         static frontend::NoGuiFontMetrics no_gui_font_metrics;
600
601         if (!use_gui)
602                 return no_gui_font_metrics;
603
604         BOOST_ASSERT(theApp());
605         return theApp()->fontLoader().metrics(f);
606 }
607
608
609 frontend::Clipboard & theClipboard()
610 {
611         BOOST_ASSERT(frontend::guiApp);
612         return frontend::guiApp->clipboard();
613 }
614
615
616 frontend::Selection & theSelection()
617 {
618         BOOST_ASSERT(frontend::guiApp);
619         return frontend::guiApp->selection();
620 }
621
622 } // namespace lyx
623
624 #include "GuiApplication_moc.cpp"