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