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