]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
small refactoring
[lyx.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "GuiImplementation.h"
19 #include "GuiWorkArea.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiMenubar.h"
22 #include "GuiToolbar.h"
23 #include "GuiToolbars.h"
24 #include "Dialogs.h"
25 #include "WorkArea.h"
26 #include "Gui.h"
27
28 #include "qt_helpers.h"
29
30 #include "frontends/Application.h"
31 #include "frontends/Dialogs.h"
32 #include "frontends/Gui.h"
33 #include "frontends/WorkArea.h"
34
35 #include "support/filetools.h"
36 #include "support/convert.h"
37 #include "support/lstrings.h"
38 #include "support/os.h"
39
40 #include "buffer_funcs.h"
41 #include "Buffer.h"
42 #include "BufferList.h"
43 #include "BufferParams.h"
44 #include "BufferView.h"
45 #include "Cursor.h"
46 #include "debug.h"
47 #include "ErrorList.h"
48 #include "FuncRequest.h"
49 #include "gettext.h"
50 #include "Intl.h"
51 #include "Layout.h"
52 #include "LyXFunc.h"
53 #include "LyX.h"
54 #include "LyXRC.h"
55 #include "MenuBackend.h"
56 #include "Paragraph.h"
57 #include "Session.h"
58 #include "TextClass.h"
59 #include "Text.h"
60 #include "ToolbarBackend.h"
61 #include "version.h"
62
63 #include "support/lstrings.h"
64 #include "support/filetools.h" // OnlyFilename()
65 #include "support/Timeout.h"
66
67 #include <QAction>
68 #include <QApplication>
69 #include <QCloseEvent>
70 #include <QDesktopWidget>
71 #include <QDragEnterEvent>
72 #include <QDropEvent>
73 #include <QList>
74 #include <QMenu>
75 #include <QPainter>
76 #include <QPixmap>
77 #include <QPushButton>
78 #include <QSplitter>
79 #include <QStackedWidget>
80 #include <QStatusBar>
81 #include <QToolBar>
82 #include <QUrl>
83
84 #include <boost/bind.hpp>
85 #include <boost/current_function.hpp>
86
87 #ifdef HAVE_SYS_TIME_H
88 # include <sys/time.h>
89 #endif
90 #ifdef HAVE_UNISTD_H
91 # include <unistd.h>
92 #endif
93
94 using std::endl;
95 using std::string;
96 using std::vector;
97
98 namespace lyx {
99
100 extern bool quitting;
101
102 namespace frontend {
103
104 using support::bformat;
105 using support::FileName;
106 using support::makeDisplayPath;
107 using support::onlyFilename;
108
109 namespace {
110
111 int const statusbar_timer_value = 3000;
112
113 class BackgroundWidget : public QWidget
114 {
115 public:
116         BackgroundWidget(QString const & file, QString const & text)
117         {
118                 splash_ = new QPixmap(file);
119                 if (!splash_) {
120                         lyxerr << "could not load splash screen: '" << fromqstr(file) << "'" << endl;
121                         return;
122                 }
123
124                 QPainter pain(splash_);
125                 pain.setPen(QColor(255, 255, 0));
126                 QFont font;
127                 // The font used to display the version info
128                 font.setStyleHint(QFont::SansSerif);
129                 font.setWeight(QFont::Bold);
130                 font.setPointSize(convert<int>(lyxrc.font_sizes[FONT_SIZE_LARGE]));
131                 pain.setFont(font);
132                 pain.drawText(260, 270, text);
133         }
134
135         void paintEvent(QPaintEvent *)
136         {
137                 if (!splash_)
138                         return;
139
140                 int x = (width() - splash_->width()) / 2;
141                 int y = (height() - splash_->height()) / 2;
142                 QPainter pain(this);
143                 pain.drawPixmap(x, y, *splash_);
144         }
145
146 private:
147         QPixmap * splash_;
148 };
149
150 } // namespace anon
151
152
153 struct GuiView::GuiViewPrivate
154 {
155         GuiViewPrivate()
156                 : current_work_area_(0), posx_offset(0), posy_offset(0)
157         {}
158
159         ~GuiViewPrivate()
160         {
161                 delete splitter_;
162                 delete bg_widget_;
163                 delete stack_widget_;
164                 delete menubar_;
165                 delete toolbars_;
166         }
167
168         unsigned int smallIconSize;
169         unsigned int normalIconSize;
170         unsigned int bigIconSize;
171         // static needed by "New Window"
172         static unsigned int lastIconSize;
173
174         QMenu * toolBarPopup(GuiView * parent)
175         {
176                 // FIXME: translation
177                 QMenu * menu = new QMenu(parent);
178                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
179
180                 QAction * smallIcons = new QAction(iconSizeGroup);
181                 smallIcons->setText(qt_("Small-sized icons"));
182                 smallIcons->setCheckable(true);
183                 QObject::connect(smallIcons, SIGNAL(triggered()),
184                         parent, SLOT(smallSizedIcons()));
185                 menu->addAction(smallIcons);
186
187                 QAction * normalIcons = new QAction(iconSizeGroup);
188                 normalIcons->setText(qt_("Normal-sized icons"));
189                 normalIcons->setCheckable(true);
190                 QObject::connect(normalIcons, SIGNAL(triggered()),
191                         parent, SLOT(normalSizedIcons()));
192                 menu->addAction(normalIcons);
193
194                 QAction * bigIcons = new QAction(iconSizeGroup);
195                 bigIcons->setText(qt_("Big-sized icons"));
196                 bigIcons->setCheckable(true);
197                 QObject::connect(bigIcons, SIGNAL(triggered()),
198                         parent, SLOT(bigSizedIcons()));
199                 menu->addAction(bigIcons);
200
201                 unsigned int cur = parent->iconSize().width();
202                 if ( cur == parent->d.smallIconSize)
203                         smallIcons->setChecked(true);
204                 else if (cur == parent->d.normalIconSize)
205                         normalIcons->setChecked(true);
206                 else if (cur == parent->d.bigIconSize)
207                         bigIcons->setChecked(true);
208
209                 return menu;
210         }
211
212         void initBackground()
213         {
214                 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
215                 /// The text to be written on top of the pixmap
216                 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
217                 bg_widget_ = new BackgroundWidget(":/images/banner.png", text);
218         }
219
220         void setBackground()
221         {
222                 stack_widget_->setCurrentWidget(bg_widget_);
223                 bg_widget_->setUpdatesEnabled(true);
224         }
225
226         TabWorkArea * tabWorkArea(int i)
227         {
228                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
229         }
230
231         TabWorkArea * currentTabWorkArea()
232         {
233                 if (splitter_->count() == 1)
234                         // The first TabWorkArea is always the first one, if any.
235                         return tabWorkArea(0);
236
237                 TabWorkArea * tab_widget = 0;
238                 for (int i = 0; i != splitter_->count(); ++i) {
239                         QWidget * w = splitter_->widget(i);
240                         if (!w->hasFocus())
241                                 continue;
242                         tab_widget = dynamic_cast<TabWorkArea *>(w);
243                         if (tab_widget)
244                                 break;
245                 }
246
247                 return tab_widget;
248         }
249
250 public:
251         ///
252         string cur_title;
253
254         GuiWorkArea * current_work_area_;
255         int posx_offset;
256         int posy_offset;
257
258         QSplitter * splitter_;
259         QStackedWidget * stack_widget_;
260         BackgroundWidget * bg_widget_;
261         /// view's menubar
262         GuiMenubar * menubar_;
263         /// view's toolbars
264         GuiToolbars * toolbars_;
265         ///
266         docstring current_layout;
267 };
268
269
270 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
271
272
273 /// FIXME
274 LyXView::~LyXView() {}
275
276
277 GuiView::GuiView(int id)
278         : QMainWindow(), LyXView(id),
279           d(*new GuiViewPrivate),
280                 quitting_by_menu_(false),
281                 autosave_timeout_(new Timeout(5000)),
282           dialogs_(new Dialogs(*this))
283 {
284         // Start autosave timer
285         if (lyxrc.autosave) {
286                 autosave_timeout_->timeout.connect(boost::bind(&GuiView::autoSave, this));
287                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
288                 autosave_timeout_->start();
289         }
290
291         // Qt bug? signal lastWindowClosed does not work
292         setAttribute(Qt::WA_QuitOnClose, false);
293         setAttribute(Qt::WA_DeleteOnClose, true);
294
295         // hardcode here the platform specific icon size
296         d.smallIconSize = 14;   // scaling problems
297         d.normalIconSize = 20;  // ok, default
298         d.bigIconSize = 26;             // better for some math icons
299
300 #ifndef Q_WS_MACX
301         // assign an icon to main form. We do not do it under Qt/Mac,
302         // since the icon is provided in the application bundle.
303         setWindowIcon(QPixmap(":/images/lyx.png"));
304 #endif
305
306
307         d.splitter_ = new QSplitter;
308
309         d.initBackground();
310         LYXERR(Debug::GUI) << "stack widget!" << endl;
311         d.stack_widget_ = new QStackedWidget;
312         d.stack_widget_->addWidget(d.bg_widget_);
313         d.stack_widget_->addWidget(d.splitter_);
314         setCentralWidget(d.stack_widget_);
315
316         // For Drag&Drop.
317         setAcceptDrops(true);
318 }
319
320
321 GuiView::~GuiView()
322 {
323         delete dialogs_;
324         delete autosave_timeout_;
325         delete &d;
326 }
327
328
329 void GuiView::close()
330 {
331         quitting_by_menu_ = true;
332         d.current_work_area_ = 0;
333         for (int i = 0; i != d.splitter_->count(); ++i) {
334                 TabWorkArea * twa = d.tabWorkArea(i);
335                 if (twa)
336                         twa->closeAll();
337         }
338         QMainWindow::close();
339         quitting_by_menu_ = false;
340 }
341
342
343 void GuiView::setFocus()
344 {
345         if (d.current_work_area_)
346                 d.current_work_area_->setFocus();
347         else
348                 QWidget::setFocus();
349 }
350
351
352 QMenu* GuiView::createPopupMenu()
353 {
354         return d.toolBarPopup(this);
355 }
356
357
358 void GuiView::init()
359 {
360         // GuiToolbars *must* be initialised before GuiMenubar.
361         d.toolbars_ = new GuiToolbars(*this);
362         // FIXME: GuiToolbars::init() cannot be integrated in the ctor
363         // because LyXFunc::getStatus() needs a properly initialized
364         // GuiToolbars object (for LFUN_TOOLBAR_TOGGLE).
365         d.toolbars_->init();
366         d.menubar_ = new GuiMenubar(this, menubackend);
367
368         statusBar()->setSizeGripEnabled(true);
369
370         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
371                 this, SLOT(update_view_state_qt()));
372
373         d.setBackground();
374 }
375
376
377 void GuiView::closeEvent(QCloseEvent * close_event)
378 {
379         // we may have been called through the close window button
380         // which bypasses the LFUN machinery.
381         if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
382                 if (!theBufferList().quitWriteAll()) {
383                         close_event->ignore();
384                         return;
385                 }
386         }
387
388         // Make sure that no LFUN use this close to be closed View.
389         theLyXFunc().setLyXView(0);
390         // Make sure the timer time out will not trigger a statusbar update.
391         statusbar_timer_.stop();
392
393         theApp()->gui().unregisterView(id());
394         if (!theApp()->gui().viewIds().empty()) {
395                 // Just close the window and do nothing else if this is not the
396                 // last window.
397                 close_event->accept();
398                 return;
399         }
400
401         quitting = true;
402
403         // this is the place where we leave the frontend.
404         // it is the only point at which we start quitting.
405         saveGeometry();
406         close_event->accept();
407         // quit the event loop
408         qApp->quit();
409 }
410
411
412 void GuiView::dragEnterEvent(QDragEnterEvent * event)
413 {
414         if (event->mimeData()->hasUrls())
415                 event->accept();
416         /// \todo Ask lyx-devel is this is enough:
417         /// if (event->mimeData()->hasFormat("text/plain"))
418         ///     event->acceptProposedAction();
419 }
420
421
422 void GuiView::dropEvent(QDropEvent* event)
423 {
424         QList<QUrl> files = event->mimeData()->urls();
425         if (files.isEmpty())
426                 return;
427
428         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
429                 << " got URLs!" << endl;
430         for (int i = 0; i != files.size(); ++i) {
431                 string const file = support::os::internal_path(fromqstr(
432                         files.at(i).toLocalFile()));
433                 if (!file.empty())
434                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
435         }
436 }
437
438
439 void GuiView::saveGeometry()
440 {
441         static bool done = false;
442         if (done)
443                 return;
444         else
445                 done = true;
446
447         // FIXME:
448         // change the ifdef to 'geometry = normalGeometry();' only
449         // when Trolltech has fixed the broken normalGeometry on X11:
450         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
451         // Then also the moveEvent, resizeEvent, and the
452         // code for floatingGeometry_ can be removed;
453         // adjust GuiView::setGeometry()
454
455         QRect normal_geometry;
456         int maximized;
457 #ifdef Q_WS_WIN
458         normal_geometry = normalGeometry();
459         if (isMaximized()) {
460                 maximized = CompletelyMaximized;
461         } else {
462                 maximized = NotMaximized;
463         }
464 #else
465         normal_geometry = updateFloatingGeometry();
466
467         QDesktopWidget& dw = *qApp->desktop();
468         QRect desk = dw.availableGeometry(dw.primaryScreen());
469         // Qt bug on Linux: load completely maximized, vert max. save-> frameGeometry().height() is wrong
470         if (isMaximized() && desk.width() <= frameGeometry().width() && desk.height() <= frameGeometry().height()) {
471                 maximized = CompletelyMaximized;
472                 // maximizing does not work when the window is allready hor. or vert. maximized
473                 // Tested only on KDE
474                 int dh = frameGeometry().height() - height();
475                 if (desk.height() <= normal_geometry.height() + dh)
476                         normal_geometry.setHeight(normal_geometry.height() - 1);
477                 int dw = frameGeometry().width() - width();
478                 if (desk.width() <= normal_geometry.width() + dw)
479                         normal_geometry.setWidth(normal_geometry.width() - 1);
480         } else if (desk.height() <= frameGeometry().height()) {
481                 maximized = VerticallyMaximized;
482         } else if (desk.width() <= frameGeometry().width()) {
483                 maximized = HorizontallyMaximized;
484         } else {
485                 maximized = NotMaximized;
486         }
487 #endif
488
489         // save windows size and position
490         SessionInfoSection & info = LyX::ref().session().sessionInfo();
491         info.save("WindowWidth", convert<string>(normal_geometry.width()));
492         info.save("WindowHeight", convert<string>(normal_geometry.height()));
493         info.save("WindowMaximized", convert<string>(maximized));
494         info.save("IconSizeXY", convert<string>(iconSize().width()));
495         if (lyxrc.geometry_xysaved) {
496                 info.save("WindowPosX", convert<string>(normal_geometry.x() + d.posx_offset));
497                 info.save("WindowPosY", convert<string>(normal_geometry.y() + d.posy_offset));
498         }
499         d.toolbars_->saveToolbarInfo();
500 }
501
502
503 void GuiView::setGeometry(unsigned int width,
504                           unsigned int height,
505                           int posx, int posy,
506                           int maximized,
507                           unsigned int iconSizeXY,
508                           const string & geometryArg)
509 {
510         // use last value (not at startup)
511         if (d.lastIconSize != 0)
512                 setIconSize(d.lastIconSize);
513         else if (iconSizeXY != 0)
514                 setIconSize(iconSizeXY);
515         else
516                 setIconSize(d.normalIconSize);
517
518         // only true when the -geometry option was NOT used
519         if (width != 0 && height != 0) {
520                 if (posx != -1 && posy != -1) {
521                         // if there are startup positioning problems:
522                         // http://doc.trolltech.com/4.2/qdesktopwidget.html
523                         QDesktopWidget& dw = *qApp->desktop();
524                         if (dw.isVirtualDesktop()) {
525                                 if(!dw.geometry().contains(posx, posy)) {
526                                         posx = 50;
527                                         posy = 50;
528                                 }
529                         } else {
530                                 // Which system doesn't use a virtual desktop?
531                                 // TODO save also last screen number and check if it is still availabe.
532                         }
533 #ifdef Q_WS_WIN
534                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
535                         QWidget::setGeometry(posx, posy, width, height);
536 #else
537                         resize(width, height);
538                         move(posx, posy);
539 #endif
540                 } else {
541                         resize(width, height);
542                 }
543
544                 // remember original size
545                 floatingGeometry_ = QRect(posx, posy, width, height);
546
547                 if (maximized != NotMaximized) {
548                         if (maximized == CompletelyMaximized) {
549                                 setWindowState(Qt::WindowMaximized);
550                         } else {
551 #ifndef Q_WS_WIN
552                                 // TODO How to set by the window manager?
553                                 //      setWindowState(Qt::WindowVerticallyMaximized);
554                                 //      is not possible
555                                 QDesktopWidget& dw = *qApp->desktop();
556                                 QRect desk = dw.availableGeometry(dw.primaryScreen());
557                                 if (maximized == VerticallyMaximized)
558                                         resize(width, desk.height());
559                                 if (maximized == HorizontallyMaximized)
560                                         resize(desk.width(), height);
561 #endif
562                         }
563                 }
564         }
565         else
566         {
567                 // FIXME: move this code into parse_geometry() (LyX.cpp)
568 #ifdef Q_WS_WIN
569                 int x, y;
570                 int w, h;
571                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
572                 re.indexIn(toqstr(geometryArg.c_str()));
573                 w = re.cap(1).toInt();
574                 h = re.cap(2).toInt();
575                 x = re.cap(3).toInt();
576                 y = re.cap(4).toInt();
577                 QWidget::setGeometry( x, y, w, h );
578 #else
579                 // silence warning
580                 (void)geometryArg;
581 #endif
582         }
583         
584         d.setBackground();
585         
586         show();
587
588         // after show geometry() has changed (Qt bug?)
589         // we compensate the drift when storing the position
590         d.posx_offset = 0;
591         d.posy_offset = 0;
592         if (width != 0 && height != 0)
593                 if (posx != -1 && posy != -1) {
594 #ifdef Q_WS_WIN
595                         d.posx_offset = posx - normalGeometry().x();
596                         d.posy_offset = posy - normalGeometry().y();
597 #else
598 #ifndef Q_WS_MACX
599                         if (maximized == NotMaximized) {
600                                 d.posx_offset = posx - geometry().x();
601                                 d.posy_offset = posy - geometry().y();
602                         }
603 #endif
604 #endif
605                 }
606 }
607
608
609 void GuiView::message(docstring const & str)
610 {
611         statusBar()->showMessage(toqstr(str));
612         statusbar_timer_.stop();
613         statusbar_timer_.start(statusbar_timer_value);
614 }
615
616
617 void GuiView::clearMessage()
618 {
619         update_view_state_qt();
620 }
621
622
623 void GuiView::setIconSize(unsigned int size)
624 {
625         d.lastIconSize = size;
626         QMainWindow::setIconSize(QSize(size, size));
627 }
628
629
630 void GuiView::smallSizedIcons()
631 {
632         setIconSize(d.smallIconSize);
633 }
634
635
636 void GuiView::normalSizedIcons()
637 {
638         setIconSize(d.normalIconSize);
639 }
640
641
642 void GuiView::bigSizedIcons()
643 {
644         setIconSize(d.bigIconSize);
645 }
646
647
648 void GuiView::update_view_state_qt()
649 {
650         if (!hasFocus())
651                 return;
652         theLyXFunc().setLyXView(this);
653         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
654         statusbar_timer_.stop();
655 }
656
657
658 void GuiView::updateWindowTitle(GuiWorkArea * wa)
659 {
660         if (wa != d.current_work_area_)
661                 return;
662         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
663         setWindowIconText(wa->windowIconText());
664 }
665
666
667 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
668 {
669         disconnectBuffer();
670         disconnectBufferView();
671         connectBufferView(wa->bufferView());
672         connectBuffer(wa->bufferView().buffer());
673         d.current_work_area_ = wa;
674         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
675                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
676         updateWindowTitle(wa);
677
678         updateToc();
679         // Buffer-dependent dialogs should be updated or
680         // hidden. This should go here because some dialogs (eg ToC)
681         // require bv_->text.
682         getDialogs().updateBufferDependent(true);
683         updateToolbars();
684         updateLayoutChoice(false);
685         updateStatusBar();
686 }
687
688
689 void GuiView::updateStatusBar()
690 {
691         // let the user see the explicit message
692         if (statusbar_timer_.isActive())
693                 return;
694
695         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
696 }
697
698
699 void GuiView::activated(FuncRequest const & func)
700 {
701         dispatch(func);
702 }
703
704
705 bool GuiView::hasFocus() const
706 {
707         return qApp->activeWindow() == this;
708 }
709
710
711 QRect  GuiView::updateFloatingGeometry()
712 {
713         QDesktopWidget& dw = *qApp->desktop();
714         QRect desk = dw.availableGeometry(dw.primaryScreen());
715         // remember only non-maximized sizes
716         if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
717                 floatingGeometry_ = QRect(x(), y(), width(), height());
718         }
719         return floatingGeometry_;
720 }
721
722
723 void GuiView::resizeEvent(QResizeEvent *)
724 {
725         updateFloatingGeometry();
726 }
727
728
729 void GuiView::moveEvent(QMoveEvent *)
730 {
731         updateFloatingGeometry();
732 }
733
734
735 bool GuiView::event(QEvent * e)
736 {
737         switch (e->type())
738         {
739         // Useful debug code:
740         //case QEvent::ActivationChange:
741         //case QEvent::WindowDeactivate:
742         //case QEvent::Paint:
743         //case QEvent::Enter:
744         //case QEvent::Leave:
745         //case QEvent::HoverEnter:
746         //case QEvent::HoverLeave:
747         //case QEvent::HoverMove:
748         //case QEvent::StatusTip:
749         //case QEvent::DragEnter:
750         //case QEvent::DragLeave:
751         //case QEvent::Drop:
752         //      break;
753
754         case QEvent::WindowActivate: {
755                 theApp()->setCurrentView(*this);
756                 if (d.current_work_area_) {
757                         BufferView & bv = d.current_work_area_->bufferView();
758                         connectBufferView(bv);
759                         connectBuffer(bv.buffer());
760                         // The document structure, name and dialogs might have
761                         // changed in another view.
762                         getDialogs().updateBufferDependent(true);
763                 } else {
764                         setWindowTitle(qt_("LyX"));
765                         setWindowIconText(qt_("LyX"));
766                 }
767                 return QMainWindow::event(e);
768         }
769         case QEvent::ShortcutOverride: {
770                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
771                 if (!d.current_work_area_) {
772                         theLyXFunc().setLyXView(this);
773                         KeySymbol sym;
774                         setKeySymbol(&sym, ke);
775                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
776                         e->accept();
777                         return true;
778                 }
779                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
780                         KeySymbol sym;
781                         setKeySymbol(&sym, ke);
782                         d.current_work_area_->processKeySym(sym, NoModifier);
783                         e->accept();
784                         return true;
785                 }
786         }
787         default:
788                 return QMainWindow::event(e);
789         }
790 }
791
792
793 bool GuiView::focusNextPrevChild(bool /*next*/)
794 {
795         setFocus();
796         return true;
797 }
798
799
800 void GuiView::showView()
801 {
802         setWindowTitle(qt_("LyX"));
803         show();
804         updateFloatingGeometry();
805 }
806
807
808 void GuiView::setBusy(bool yes)
809 {
810         if (d.current_work_area_) {
811                 d.current_work_area_->setUpdatesEnabled(!yes);
812                 if (yes)
813                         d.current_work_area_->stopBlinkingCursor();
814                 else
815                         d.current_work_area_->startBlinkingCursor();
816         }
817
818         if (yes)
819                 QApplication::setOverrideCursor(Qt::WaitCursor);
820         else
821                 QApplication::restoreOverrideCursor();
822 }
823
824
825 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
826 {
827         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
828
829         if (tbinfo.flags & ToolbarInfo::TOP) {
830                 if (newline)
831                         addToolBarBreak(Qt::TopToolBarArea);
832                 addToolBar(Qt::TopToolBarArea, toolBar);
833         }
834
835         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
836 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
837 #if (QT_VERSION >= 0x040202)
838                 if (newline)
839                         addToolBarBreak(Qt::BottomToolBarArea);
840 #endif
841                 addToolBar(Qt::BottomToolBarArea, toolBar);
842         }
843
844         if (tbinfo.flags & ToolbarInfo::LEFT) {
845 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
846 #if (QT_VERSION >= 0x040202)
847                 if (newline)
848                         addToolBarBreak(Qt::LeftToolBarArea);
849 #endif
850                 addToolBar(Qt::LeftToolBarArea, toolBar);
851         }
852
853         if (tbinfo.flags & ToolbarInfo::RIGHT) {
854 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
855 #if (QT_VERSION >= 0x040202)
856                 if (newline)
857                         addToolBarBreak(Qt::RightToolBarArea);
858 #endif
859                 addToolBar(Qt::RightToolBarArea, toolBar);
860         }
861
862         // The following does not work so I cannot restore to exact toolbar location
863         /*
864         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
865         toolBar->move(tbinfo.posx, tbinfo.posy);
866         */
867
868         return toolBar;
869 }
870
871
872 WorkArea * GuiView::workArea(Buffer & buffer)
873 {
874         for (int i = 0; i != d.splitter_->count(); ++i) {
875                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
876                 if (wa)
877                         return wa;
878         }
879         return 0;
880 }
881
882
883 WorkArea * GuiView::addWorkArea(Buffer & buffer)
884 {
885         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
886         wa->setUpdatesEnabled(false);
887
888         // Automatically create a TabWorkArea if there are none yet.
889         if (!d.splitter_->count())
890                 addTabWorkArea();
891
892         TabWorkArea * tab_widget = d.currentTabWorkArea();
893         tab_widget->addTab(wa, wa->windowTitle());
894         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
895                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
896
897         wa->bufferView().updateMetrics();
898
899         // Hide tabbar if there's only one tab.
900         tab_widget->showBar(tab_widget->count() > 1);
901         return wa;
902 }
903
904
905 void GuiView::addTabWorkArea()
906 {
907         TabWorkArea * twa = new TabWorkArea;
908         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
909                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
910         d.splitter_->addWidget(twa);
911         d.stack_widget_->setCurrentWidget(d.splitter_);
912 }
913
914
915 WorkArea * GuiView::currentWorkArea()
916 {
917         return d.current_work_area_;
918 }
919
920
921 WorkArea const * GuiView::currentWorkArea() const
922 {
923         return d.current_work_area_;
924 }
925
926
927 void GuiView::setCurrentWorkArea(WorkArea * work_area)
928 {
929         BOOST_ASSERT(work_area);
930
931         // Changing work area can result from opening a file so
932         // update the toc in any case.
933         updateToc();
934
935         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
936         d.current_work_area_ = wa;
937         for (int i = 0; i != d.splitter_->count(); ++i) {
938                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
939                         return;
940         }
941 }
942
943
944 void GuiView::removeWorkArea(WorkArea * work_area)
945 {
946         BOOST_ASSERT(work_area);
947         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
948         if (gwa == d.current_work_area_) {
949                 disconnectBuffer();
950                 disconnectBufferView();
951                 getDialogs().hideBufferDependent();
952                 d.current_work_area_ = 0;
953         }
954
955         // removing a work area often results from closing a file so
956         // update the toc in any case.
957         updateToc();
958
959         for (int i = 0; i != d.splitter_->count(); ++i) {
960                 TabWorkArea * twa = d.tabWorkArea(i);
961                 if (!twa->removeWorkArea(gwa))
962                         // Not found in this tab group.
963                         continue;
964
965                 // We found and removed the WorkArea.
966                 if (twa->count()) {
967                         // No more WorkAreas in this tab group, so delete it.
968                         delete twa;
969                         break;
970                 }
971
972                 if (d.current_work_area_)
973                         // This means that we are not closing the current WorkArea;
974                         break;
975
976                 // Switch to the next WorkArea in the found TabWorkArea.
977                 d.current_work_area_ = twa->currentWorkArea();
978                 break;
979         }
980
981         if (d.splitter_->count() == 0)
982                 // No more work area, switch to the background widget.
983                 d.setBackground();
984 }
985
986
987 void GuiView::showMiniBuffer(bool visible)
988 {
989         d.toolbars_->showCommandBuffer(visible);
990 }
991
992
993 void GuiView::openMenu(docstring const & name)
994 {
995         d.menubar_->openByName(toqstr(name));
996 }
997
998
999 void GuiView::openLayoutList()
1000 {
1001         d.toolbars_->openLayoutList();
1002 }
1003
1004
1005 void GuiView::updateLayoutChoice(bool force)
1006 {
1007         // Don't show any layouts without a buffer
1008         if (!buffer()) {
1009                 d.toolbars_->clearLayoutList();
1010                 return;
1011         }
1012
1013         // Update the layout display
1014         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
1015                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
1016         }
1017
1018         docstring const & layout = d.current_work_area_->bufferView().cursor().
1019                 innerParagraph().layout()->name();
1020
1021         if (layout != d.current_layout) {
1022                 d.toolbars_->setLayout(layout);
1023                 d.current_layout = layout;
1024         }
1025 }
1026
1027
1028 bool GuiView::isToolbarVisible(std::string const & id)
1029 {
1030         return d.toolbars_->visible(id);
1031 }
1032
1033 void GuiView::updateToolbars()
1034 {
1035         if (d.current_work_area_) {
1036                 bool const math =
1037                         d.current_work_area_->bufferView().cursor().inMathed();
1038                 bool const table =
1039                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1040                 bool const review =
1041                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1042                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1043
1044                 d.toolbars_->update(math, table, review);
1045         } else
1046                 d.toolbars_->update(false, false, false);
1047
1048         // update read-only status of open dialogs.
1049         getDialogs().checkStatus();
1050 }
1051
1052
1053 ToolbarInfo * GuiView::getToolbarInfo(string const & name)
1054 {
1055         return d.toolbars_->getToolbarInfo(name);
1056 }
1057
1058
1059 void GuiView::toggleToolbarState(string const & name, bool allowauto)
1060 {
1061         // it is possible to get current toolbar status like this,...
1062         // but I decide to obey the order of ToolbarBackend::flags
1063         // and disregard real toolbar status.
1064         // toolbars_->saveToolbarInfo();
1065         //
1066         // toggle state on/off/auto
1067         d.toolbars_->toggleToolbarState(name, allowauto);
1068         // update toolbar
1069         updateToolbars();
1070 }
1071
1072
1073 Buffer * GuiView::buffer()
1074 {
1075         WorkArea * work_area = currentWorkArea();
1076         if (work_area)
1077                 return &work_area->bufferView().buffer();
1078         return 0;
1079 }
1080
1081
1082 Buffer const * GuiView::buffer() const
1083 {
1084         WorkArea const * work_area = currentWorkArea();
1085         if (work_area)
1086                 return &work_area->bufferView().buffer();
1087         return 0;
1088 }
1089
1090
1091 void GuiView::setBuffer(Buffer * newBuffer)
1092 {
1093         BOOST_ASSERT(newBuffer);
1094         setBusy(true);
1095
1096         WorkArea * wa = workArea(*newBuffer);
1097         if (wa == 0) {
1098                 updateLabels(*newBuffer->masterBuffer());
1099                 wa = addWorkArea(*newBuffer);
1100         } else {
1101                 //Disconnect the old buffer...there's no new one.
1102                 disconnectBuffer();
1103         }
1104         connectBuffer(*newBuffer);
1105         connectBufferView(wa->bufferView());
1106         setCurrentWorkArea(wa);
1107
1108         setBusy(false);
1109 }
1110
1111
1112 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
1113 {
1114         setBusy(true);
1115
1116         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1117
1118         if (!newBuffer) {
1119                 message(_("Document not loaded."));
1120                 updateStatusBar();
1121                 setBusy(false);
1122                 return 0;
1123         }
1124
1125         WorkArea * wa = workArea(*newBuffer);
1126         if (wa == 0)
1127                 wa = addWorkArea(*newBuffer);
1128
1129         // scroll to the position when the file was last closed
1130         if (lyxrc.use_lastfilepos) {
1131                 LastFilePosSection::FilePos filepos =
1132                         LyX::ref().session().lastFilePos().load(filename);
1133                 // if successfully move to pit (returned par_id is not zero),
1134                 // update metrics and reset font
1135                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1136         }
1137
1138         if (tolastfiles)
1139                 LyX::ref().session().lastFiles().add(filename);
1140
1141         setBusy(false);
1142         return newBuffer;
1143 }
1144
1145
1146 void GuiView::connectBuffer(Buffer & buf)
1147 {
1148         buf.setGuiDelegate(this);
1149 }
1150
1151
1152 void GuiView::disconnectBuffer()
1153 {
1154         if (WorkArea * work_area = currentWorkArea())
1155                 work_area->bufferView().setGuiDelegate(0);
1156 }
1157
1158
1159 void GuiView::connectBufferView(BufferView & bv)
1160 {
1161         bv.setGuiDelegate(this);
1162 }
1163
1164
1165 void GuiView::disconnectBufferView()
1166 {
1167         if (WorkArea * work_area = currentWorkArea())
1168                 work_area->bufferView().setGuiDelegate(0);
1169 }
1170
1171
1172 void GuiView::showErrorList(string const & error_type)
1173 {
1174         ErrorList & el = buffer()->errorList(error_type);
1175         if (!el.empty())
1176                 getDialogs().show("errorlist", error_type);
1177 }
1178
1179
1180 void GuiView::showDialog(string const & name)
1181 {
1182         getDialogs().show(name);
1183 }
1184
1185
1186 void GuiView::showDialogWithData(string const & name, string const & data)
1187 {
1188         getDialogs().show(name, data);
1189 }
1190
1191
1192 void GuiView::showInsetDialog(string const & name, string const & data,
1193                 Inset * inset)
1194 {
1195         getDialogs().show(name, data, inset);
1196 }
1197
1198
1199 void GuiView::updateDialog(string const & name, string const & data)
1200 {
1201         if (getDialogs().visible(name))
1202                 getDialogs().update(name, data);
1203 }
1204
1205
1206 BufferView * GuiView::view()
1207 {
1208         WorkArea * wa = currentWorkArea();
1209         return wa ? &wa->bufferView() : 0;
1210 }
1211
1212
1213 void GuiView::updateToc()
1214 {
1215         updateDialog("toc", "");
1216 }
1217
1218
1219 void GuiView::updateEmbeddedFiles()
1220 {
1221         updateDialog("embedding", "");
1222 }
1223
1224
1225 void GuiView::autoSave()
1226 {
1227         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
1228
1229         if (buffer())
1230                 view()->buffer().autoSave();
1231 }
1232
1233
1234 void GuiView::resetAutosaveTimer()
1235 {
1236         if (lyxrc.autosave)
1237                 autosave_timeout_->restart();
1238 }
1239
1240
1241 void GuiView::dispatch(FuncRequest const & cmd)
1242 {
1243         string const argument = to_utf8(cmd.argument());
1244         switch(cmd.action) {
1245                 case LFUN_BUFFER_SWITCH:
1246                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1247                         break;
1248                 default:
1249                         theLyXFunc().setLyXView(this);
1250                         lyx::dispatch(cmd);
1251         }
1252 }
1253
1254
1255 Buffer const * GuiView::updateInset(Inset const * inset)
1256 {
1257         WorkArea * work_area = currentWorkArea();
1258         if (!work_area)
1259                 return 0;
1260
1261         if (inset) {
1262                 BOOST_ASSERT(work_area);
1263                 work_area->scheduleRedraw();
1264         }
1265         return &work_area->bufferView().buffer();
1266 }
1267
1268 } // namespace frontend
1269 } // namespace lyx
1270
1271 #include "GuiView_moc.cpp"