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