]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Hopefully fix the ignored -geometry option under X11.
[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 <QPoint>
75 #include <QPushButton>
76 #include <QSettings>
77 #include <QShowEvent>
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);
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 GuiView::GuiView(int id)
274         : QMainWindow(), LyXView(id),
275           d(*new GuiViewPrivate),
276                 quitting_by_menu_(false),
277                 autosave_timeout_(new Timeout(5000)),
278           dialogs_(new Dialogs(*this))
279 {
280         // Start autosave timer
281         if (lyxrc.autosave) {
282                 autosave_timeout_->timeout.connect(boost::bind(&GuiView::autoSave, this));
283                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
284                 autosave_timeout_->start();
285         }
286
287         // Qt bug? signal lastWindowClosed does not work
288         setAttribute(Qt::WA_QuitOnClose, false);
289         setAttribute(Qt::WA_DeleteOnClose, true);
290
291         // hardcode here the platform specific icon size
292         d.smallIconSize = 14;   // scaling problems
293         d.normalIconSize = 20;  // ok, default
294         d.bigIconSize = 26;             // better for some math icons
295
296 #ifndef Q_WS_MACX
297         // assign an icon to main form. We do not do it under Qt/Mac,
298         // since the icon is provided in the application bundle.
299         setWindowIcon(QPixmap(":/images/lyx.png"));
300 #endif
301
302
303         d.splitter_ = new QSplitter;
304
305         d.initBackground();
306         LYXERR(Debug::GUI, "stack widget!");
307         d.stack_widget_ = new QStackedWidget;
308         d.stack_widget_->addWidget(d.bg_widget_);
309         d.stack_widget_->addWidget(d.splitter_);
310         setCentralWidget(d.stack_widget_);
311
312         // For Drag&Drop.
313         setAcceptDrops(true);
314 }
315
316
317 GuiView::~GuiView()
318 {
319         delete dialogs_;
320         delete autosave_timeout_;
321         delete &d;
322 }
323
324
325 void GuiView::close()
326 {
327         quitting_by_menu_ = true;
328         d.current_work_area_ = 0;
329         for (int i = 0; i != d.splitter_->count(); ++i) {
330                 TabWorkArea * twa = d.tabWorkArea(i);
331                 if (twa)
332                         twa->closeAll();
333         }
334         QMainWindow::close();
335         quitting_by_menu_ = false;
336 }
337
338
339 void GuiView::setFocus()
340 {
341         if (d.current_work_area_)
342                 d.current_work_area_->setFocus();
343         else
344                 QWidget::setFocus();
345 }
346
347
348 QMenu* GuiView::createPopupMenu()
349 {
350         return d.toolBarPopup(this);
351 }
352
353
354 void GuiView::init()
355 {
356         setMinimumSize(300, 200);
357         // GuiToolbars *must* be initialised before GuiMenubar.
358         d.toolbars_ = new GuiToolbars(*this);
359         // FIXME: GuiToolbars::init() cannot be integrated in the ctor
360         // because LyXFunc::getStatus() needs a properly initialized
361         // GuiToolbars object (for LFUN_TOOLBAR_TOGGLE).
362         d.toolbars_->init();
363         d.menubar_ = new GuiMenubar(this, menubackend);
364
365         statusBar()->setSizeGripEnabled(true);
366
367         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
368                 this, SLOT(clearMessage()));
369
370         d.setBackground();
371
372         if (!lyxrc.allow_geometry_session)
373                 setGeometry(50, 50, 690, 510);
374
375         // Now take care of session management.
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 }
389
390
391 void GuiView::showEvent(QShowEvent * e)
392 {
393         LYXERR(Debug::GUI, "Passed Geometry "
394                 << size().height() << "x" << size().width()
395                 << "+" << pos().x() << "+" << pos().y());
396
397         if (d.splitter_->count() == 0)
398                 // No work area, switch to the background widget.
399                 d.setBackground();
400
401         QMainWindow::showEvent(e);
402 }
403
404
405 void GuiView::closeEvent(QCloseEvent * close_event)
406 {
407         // we may have been called through the close window button
408         // which bypasses the LFUN machinery.
409         if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
410                 if (!theBufferList().quitWriteAll()) {
411                         close_event->ignore();
412                         return;
413                 }
414         }
415
416         // Make sure that no LFUN use this close to be closed View.
417         theLyXFunc().setLyXView(0);
418         // Make sure the timer time out will not trigger a statusbar update.
419         statusbar_timer_.stop();
420
421         if (lyxrc.allow_geometry_session) {
422                 QSettings settings;
423                 QString const key = "view-" + QString::number(id());
424 #ifdef Q_WS_X11
425                 settings.setValue(key + "/pos", pos());
426                 settings.setValue(key + "/size", size());
427 #else
428                 settings.setValue(key + "/geometry", saveGeometry());
429 #endif
430                 settings.setValue(key + "/icon_size", iconSize());
431                 d.toolbars_->saveToolbarInfo();
432         }
433
434         theApp()->gui().unregisterView(id());
435         if (!theApp()->gui().viewIds().empty()) {
436                 // Just close the window and do nothing else if this is not the
437                 // last window.
438                 close_event->accept();
439                 return;
440         }
441
442         quitting = true;
443
444         // this is the place where we leave the frontend.
445         // it is the only point at which we start quitting.
446         close_event->accept();
447         // quit the event loop
448         qApp->quit();
449 }
450
451
452 void GuiView::dragEnterEvent(QDragEnterEvent * event)
453 {
454         if (event->mimeData()->hasUrls())
455                 event->accept();
456         /// \todo Ask lyx-devel is this is enough:
457         /// if (event->mimeData()->hasFormat("text/plain"))
458         ///     event->acceptProposedAction();
459 }
460
461
462 void GuiView::dropEvent(QDropEvent* event)
463 {
464         QList<QUrl> files = event->mimeData()->urls();
465         if (files.isEmpty())
466                 return;
467
468         LYXERR(Debug::GUI, BOOST_CURRENT_FUNCTION << " got URLs!");
469         for (int i = 0; i != files.size(); ++i) {
470                 string const file = support::os::internal_path(fromqstr(
471                         files.at(i).toLocalFile()));
472                 if (!file.empty())
473                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
474         }
475 }
476
477
478 void GuiView::message(docstring const & str)
479 {
480         statusBar()->showMessage(toqstr(str));
481         statusbar_timer_.stop();
482         statusbar_timer_.start(statusbar_timer_value);
483 }
484
485
486 void GuiView::smallSizedIcons()
487 {
488         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
489 }
490
491
492 void GuiView::normalSizedIcons()
493 {
494         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
495 }
496
497
498 void GuiView::bigSizedIcons()
499 {
500         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
501 }
502
503
504 void GuiView::clearMessage()
505 {
506         if (!hasFocus())
507                 return;
508         theLyXFunc().setLyXView(this);
509         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
510         statusbar_timer_.stop();
511 }
512
513
514 void GuiView::updateWindowTitle(GuiWorkArea * wa)
515 {
516         if (wa != d.current_work_area_)
517                 return;
518         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
519         setWindowIconText(wa->windowIconText());
520 }
521
522
523 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
524 {
525         disconnectBuffer();
526         disconnectBufferView();
527         connectBufferView(wa->bufferView());
528         connectBuffer(wa->bufferView().buffer());
529         d.current_work_area_ = wa;
530         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
531                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
532         updateWindowTitle(wa);
533
534         updateToc();
535         // Buffer-dependent dialogs should be updated or
536         // hidden. This should go here because some dialogs (eg ToC)
537         // require bv_->text.
538         dialogs_->updateBufferDependent(true);
539         updateToolbars();
540         updateLayoutChoice(false);
541         updateStatusBar();
542 }
543
544
545 void GuiView::updateStatusBar()
546 {
547         // let the user see the explicit message
548         if (statusbar_timer_.isActive())
549                 return;
550
551         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
552 }
553
554
555 bool GuiView::hasFocus() const
556 {
557         return qApp->activeWindow() == this;
558 }
559
560
561 bool GuiView::event(QEvent * e)
562 {
563         switch (e->type())
564         {
565         // Useful debug code:
566         //case QEvent::ActivationChange:
567         //case QEvent::WindowDeactivate:
568         //case QEvent::Paint:
569         //case QEvent::Enter:
570         //case QEvent::Leave:
571         //case QEvent::HoverEnter:
572         //case QEvent::HoverLeave:
573         //case QEvent::HoverMove:
574         //case QEvent::StatusTip:
575         //case QEvent::DragEnter:
576         //case QEvent::DragLeave:
577         //case QEvent::Drop:
578         //      break;
579
580         case QEvent::WindowActivate: {
581                 theApp()->setCurrentView(*this);
582                 if (d.current_work_area_) {
583                         BufferView & bv = d.current_work_area_->bufferView();
584                         connectBufferView(bv);
585                         connectBuffer(bv.buffer());
586                         // The document structure, name and dialogs might have
587                         // changed in another view.
588                         dialogs_->updateBufferDependent(true);
589                 } else {
590                         setWindowTitle(qt_("LyX"));
591                         setWindowIconText(qt_("LyX"));
592                 }
593                 return QMainWindow::event(e);
594         }
595         case QEvent::ShortcutOverride: {
596                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
597                 if (!d.current_work_area_) {
598                         theLyXFunc().setLyXView(this);
599                         KeySymbol sym;
600                         setKeySymbol(&sym, ke);
601                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
602                         e->accept();
603                         return true;
604                 }
605                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
606                         KeySymbol sym;
607                         setKeySymbol(&sym, ke);
608                         d.current_work_area_->processKeySym(sym, NoModifier);
609                         e->accept();
610                         return true;
611                 }
612         }
613         default:
614                 return QMainWindow::event(e);
615         }
616 }
617
618
619 bool GuiView::focusNextPrevChild(bool /*next*/)
620 {
621         setFocus();
622         return true;
623 }
624
625
626 void GuiView::setBusy(bool yes)
627 {
628         if (d.current_work_area_) {
629                 d.current_work_area_->setUpdatesEnabled(!yes);
630                 if (yes)
631                         d.current_work_area_->stopBlinkingCursor();
632                 else
633                         d.current_work_area_->startBlinkingCursor();
634         }
635
636         if (yes)
637                 QApplication::setOverrideCursor(Qt::WaitCursor);
638         else
639                 QApplication::restoreOverrideCursor();
640 }
641
642
643 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
644 {
645         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
646
647         if (tbinfo.flags & ToolbarInfo::TOP) {
648                 if (newline)
649                         addToolBarBreak(Qt::TopToolBarArea);
650                 addToolBar(Qt::TopToolBarArea, toolBar);
651         }
652
653         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
654 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
655 #if (QT_VERSION >= 0x040202)
656                 if (newline)
657                         addToolBarBreak(Qt::BottomToolBarArea);
658 #endif
659                 addToolBar(Qt::BottomToolBarArea, toolBar);
660         }
661
662         if (tbinfo.flags & ToolbarInfo::LEFT) {
663 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
664 #if (QT_VERSION >= 0x040202)
665                 if (newline)
666                         addToolBarBreak(Qt::LeftToolBarArea);
667 #endif
668                 addToolBar(Qt::LeftToolBarArea, toolBar);
669         }
670
671         if (tbinfo.flags & ToolbarInfo::RIGHT) {
672 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
673 #if (QT_VERSION >= 0x040202)
674                 if (newline)
675                         addToolBarBreak(Qt::RightToolBarArea);
676 #endif
677                 addToolBar(Qt::RightToolBarArea, toolBar);
678         }
679
680         // The following does not work so I cannot restore to exact toolbar location
681         /*
682         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
683         toolBar->move(tbinfo.posx, tbinfo.posy);
684         */
685
686         return toolBar;
687 }
688
689
690 GuiWorkArea * GuiView::workArea(Buffer & buffer)
691 {
692         for (int i = 0; i != d.splitter_->count(); ++i) {
693                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
694                 if (wa)
695                         return wa;
696         }
697         return 0;
698 }
699
700
701 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
702 {
703         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
704         wa->setUpdatesEnabled(false);
705
706         // Automatically create a TabWorkArea if there are none yet.
707         if (!d.splitter_->count())
708                 addTabWorkArea();
709
710         TabWorkArea * tab_widget = d.currentTabWorkArea();
711         tab_widget->addTab(wa, wa->windowTitle());
712         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
713                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
714
715         wa->bufferView().updateMetrics();
716
717         // Hide tabbar if there's only one tab.
718         tab_widget->showBar(tab_widget->count() > 1);
719         return wa;
720 }
721
722
723 void GuiView::addTabWorkArea()
724 {
725         TabWorkArea * twa = new TabWorkArea;
726         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
727                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
728         d.splitter_->addWidget(twa);
729         d.stack_widget_->setCurrentWidget(d.splitter_);
730 }
731
732
733 GuiWorkArea const * GuiView::currentWorkArea() const
734 {
735         return d.current_work_area_;
736 }
737
738
739 void GuiView::setCurrentWorkArea(GuiWorkArea * work_area)
740 {
741         BOOST_ASSERT(work_area);
742
743         // Changing work area can result from opening a file so
744         // update the toc in any case.
745         updateToc();
746
747         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
748         d.current_work_area_ = wa;
749         for (int i = 0; i != d.splitter_->count(); ++i) {
750                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
751                         return;
752         }
753 }
754
755
756 void GuiView::removeWorkArea(GuiWorkArea * work_area)
757 {
758         BOOST_ASSERT(work_area);
759         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
760         if (gwa == d.current_work_area_) {
761                 disconnectBuffer();
762                 disconnectBufferView();
763                 dialogs_->hideBufferDependent();
764                 d.current_work_area_ = 0;
765         }
766
767         // removing a work area often results from closing a file so
768         // update the toc in any case.
769         updateToc();
770
771         for (int i = 0; i != d.splitter_->count(); ++i) {
772                 TabWorkArea * twa = d.tabWorkArea(i);
773                 if (!twa->removeWorkArea(gwa))
774                         // Not found in this tab group.
775                         continue;
776
777                 // We found and removed the GuiWorkArea.
778                 if (!twa->count()) {
779                         // No more WorkAreas in this tab group, so delete it.
780                         delete twa;
781                         break;
782                 }
783
784                 if (d.current_work_area_)
785                         // This means that we are not closing the current GuiWorkArea;
786                         break;
787
788                 // Switch to the next GuiWorkArea in the found TabWorkArea.
789                 d.current_work_area_ = twa->currentWorkArea();
790                 break;
791         }
792
793         if (d.splitter_->count() == 0)
794                 // No more work area, switch to the background widget.
795                 d.setBackground();
796 }
797
798
799 void GuiView::updateLayoutChoice(bool force)
800 {
801         // Don't show any layouts without a buffer
802         if (!buffer()) {
803                 d.toolbars_->clearLayoutList();
804                 return;
805         }
806
807         // Update the layout display
808         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
809                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
810         }
811
812         docstring const & layout = d.current_work_area_->bufferView().cursor().
813                 innerParagraph().layout()->name();
814
815         if (layout != d.current_layout) {
816                 d.toolbars_->setLayout(layout);
817                 d.current_layout = layout;
818         }
819 }
820
821
822 bool GuiView::isToolbarVisible(std::string const & id)
823 {
824         return d.toolbars_->visible(id);
825 }
826
827 void GuiView::updateToolbars()
828 {
829         if (d.current_work_area_) {
830                 bool const math =
831                         d.current_work_area_->bufferView().cursor().inMathed();
832                 bool const table =
833                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
834                 bool const review =
835                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
836                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
837
838                 d.toolbars_->update(math, table, review);
839         } else
840                 d.toolbars_->update(false, false, false);
841
842         // update read-only status of open dialogs.
843         dialogs_->checkStatus();
844 }
845
846
847 Buffer * GuiView::buffer()
848 {
849         if (d.current_work_area_)
850                 return &d.current_work_area_->bufferView().buffer();
851         return 0;
852 }
853
854
855 Buffer const * GuiView::buffer() const
856 {
857         if (d.current_work_area_)
858                 return &d.current_work_area_->bufferView().buffer();
859         return 0;
860 }
861
862
863 void GuiView::setBuffer(Buffer * newBuffer)
864 {
865         BOOST_ASSERT(newBuffer);
866         setBusy(true);
867
868         GuiWorkArea * wa = workArea(*newBuffer);
869         if (wa == 0) {
870                 updateLabels(*newBuffer->masterBuffer());
871                 wa = addWorkArea(*newBuffer);
872         } else {
873                 //Disconnect the old buffer...there's no new one.
874                 disconnectBuffer();
875         }
876         connectBuffer(*newBuffer);
877         connectBufferView(wa->bufferView());
878         setCurrentWorkArea(wa);
879
880         setBusy(false);
881 }
882
883
884 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
885 {
886         setBusy(true);
887
888         Buffer * newBuffer = checkAndLoadLyXFile(filename);
889
890         if (!newBuffer) {
891                 message(_("Document not loaded."));
892                 updateStatusBar();
893                 setBusy(false);
894                 return 0;
895         }
896
897         GuiWorkArea * wa = workArea(*newBuffer);
898         if (wa == 0)
899                 wa = addWorkArea(*newBuffer);
900
901         // scroll to the position when the file was last closed
902         if (lyxrc.use_lastfilepos) {
903                 LastFilePosSection::FilePos filepos =
904                         LyX::ref().session().lastFilePos().load(filename);
905                 // if successfully move to pit (returned par_id is not zero),
906                 // update metrics and reset font
907                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
908         }
909
910         if (tolastfiles)
911                 LyX::ref().session().lastFiles().add(filename);
912
913         setBusy(false);
914         return newBuffer;
915 }
916
917
918 void GuiView::connectBuffer(Buffer & buf)
919 {
920         buf.setGuiDelegate(this);
921 }
922
923
924 void GuiView::disconnectBuffer()
925 {
926         if (d.current_work_area_)
927                 d.current_work_area_->bufferView().setGuiDelegate(0);
928 }
929
930
931 void GuiView::connectBufferView(BufferView & bv)
932 {
933         bv.setGuiDelegate(this);
934 }
935
936
937 void GuiView::disconnectBufferView()
938 {
939         if (d.current_work_area_)
940                 d.current_work_area_->bufferView().setGuiDelegate(0);
941 }
942
943
944 void GuiView::errors(string const & error_type)
945 {
946         ErrorList & el = buffer()->errorList(error_type);
947         if (!el.empty())
948                 dialogs_->show("errorlist", error_type);
949 }
950
951
952 void GuiView::showDialog(string const & name)
953 {
954         dialogs_->show(name);
955 }
956
957
958 void GuiView::showDialogWithData(string const & name, string const & data)
959 {
960         dialogs_->show(name, data);
961 }
962
963
964 void GuiView::showInsetDialog(string const & name, string const & data,
965                 Inset * inset)
966 {
967         dialogs_->show(name, data, inset);
968 }
969
970
971 void GuiView::updateDialog(string const & name, string const & data)
972 {
973         if (dialogs_->visible(name))
974                 dialogs_->update(name, data);
975 }
976
977
978 BufferView * GuiView::view()
979 {
980         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
981 }
982
983
984 void GuiView::updateToc()
985 {
986         updateDialog("toc", "");
987 }
988
989
990 void GuiView::updateEmbeddedFiles()
991 {
992         updateDialog("embedding", "");
993 }
994
995
996 void GuiView::autoSave()
997 {
998         LYXERR(Debug::INFO, "Running autoSave()");
999
1000         if (buffer())
1001                 view()->buffer().autoSave();
1002 }
1003
1004
1005 void GuiView::resetAutosaveTimers()
1006 {
1007         if (lyxrc.autosave)
1008                 autosave_timeout_->restart();
1009 }
1010
1011
1012 void GuiView::dispatch(FuncRequest const & cmd)
1013 {
1014         switch(cmd.action) {
1015                 case LFUN_BUFFER_SWITCH:
1016                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1017                         break;
1018
1019                 case LFUN_COMMAND_EXECUTE: {
1020                         bool const show_it = cmd.argument() != "off";
1021                         d.toolbars_->showCommandBuffer(show_it);
1022                         break;
1023                 }
1024                 case LFUN_DROP_LAYOUTS_CHOICE:
1025                         d.toolbars_->openLayoutList();
1026                         break;
1027
1028                 case LFUN_MENU_OPEN:
1029                         d.menubar_->openByName(toqstr(cmd.argument()));
1030                         break;
1031
1032                 case LFUN_TOOLBAR_TOGGLE: {
1033                         string const name = cmd.getArg(0);
1034                         bool const allowauto = cmd.getArg(1) == "allowauto";
1035                         // it is possible to get current toolbar status like this,...
1036                         // but I decide to obey the order of ToolbarBackend::flags
1037                         // and disregard real toolbar status.
1038                         // toolbars_->saveToolbarInfo();
1039                         //
1040                         // toggle state on/off/auto
1041                         d.toolbars_->toggleToolbarState(name, allowauto);
1042                         // update toolbar
1043                         updateToolbars();
1044
1045                         ToolbarInfo * tbi = d.toolbars_->getToolbarInfo(name);
1046                         if (!tbi) {
1047                                 message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
1048                                 break;
1049                         }
1050                         docstring state;
1051                         if (tbi->flags & ToolbarInfo::ON)
1052                                 state = _("on");
1053                         else if (tbi->flags & ToolbarInfo::OFF)
1054                                 state = _("off");
1055                         else if (tbi->flags & ToolbarInfo::AUTO)
1056                                 state = _("auto");
1057
1058                         message(bformat(_("Toolbar \"%1$s\" state set to %2$s"), 
1059                                            _(tbi->gui_name), state));
1060                         break;
1061                 }
1062
1063                 default:
1064                         theLyXFunc().setLyXView(this);
1065                         lyx::dispatch(cmd);
1066         }
1067 }
1068
1069
1070 Buffer const * GuiView::updateInset(Inset const * inset)
1071 {
1072         if (!d.current_work_area_)
1073                 return 0;
1074
1075         if (inset)
1076                 d.current_work_area_->scheduleRedraw();
1077
1078         return &d.current_work_area_->bufferView().buffer();
1079 }
1080
1081
1082 void GuiView::restartCursor()
1083 {
1084         /* When we move around, or type, it's nice to be able to see
1085          * the cursor immediately after the keypress.
1086          */
1087         if (d.current_work_area_)
1088                 d.current_work_area_->startBlinkingCursor();
1089 }
1090
1091 } // namespace frontend
1092 } // namespace lyx
1093
1094 #include "GuiView_moc.cpp"