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