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