]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
9dcc95429d925850f15012ae86cad2dd696ec684
[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 "Dialog.h"
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
29 #include "Menus.h"
30 #include "TocModel.h"
31
32 #include "qt_helpers.h"
33
34 #include "frontends/alert.h"
35
36 #include "buffer_funcs.h"
37 #include "Buffer.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
42 #include "Cursor.h"
43 #include "CutAndPaste.h"
44 #include "Encoding.h"
45 #include "ErrorList.h"
46 #include "Format.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
49 #include "Intl.h"
50 #include "Layout.h"
51 #include "Lexer.h"
52 #include "LyXAction.h"
53 #include "LyXFunc.h"
54 #include "LyX.h"
55 #include "LyXRC.h"
56 #include "LyXVC.h"
57 #include "Paragraph.h"
58 #include "SpellChecker.h"
59 #include "TextClass.h"
60 #include "Text.h"
61 #include "Toolbars.h"
62 #include "version.h"
63
64 #include "support/convert.h"
65 #include "support/debug.h"
66 #include "support/ExceptionMessage.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/gettext.h"
70 #include "support/filetools.h"
71 #include "support/ForkedCalls.h"
72 #include "support/lassert.h"
73 #include "support/lstrings.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/Path.h"
77 #include "support/Systemcall.h"
78 #include "support/Timeout.h"
79
80 #include <QAction>
81 #include <QApplication>
82 #include <QCloseEvent>
83 #include <QDebug>
84 #include <QDesktopWidget>
85 #include <QDragEnterEvent>
86 #include <QDropEvent>
87 #include <QList>
88 #include <QMenu>
89 #include <QMenuBar>
90 #include <QPainter>
91 #include <QPixmap>
92 #include <QPixmapCache>
93 #include <QPoint>
94 #include <QPushButton>
95 #include <QSettings>
96 #include <QShowEvent>
97 #include <QSplitter>
98 #include <QStackedWidget>
99 #include <QStatusBar>
100 #include <QTimer>
101 #include <QToolBar>
102 #include <QUrl>
103 #include <QScrollBar>
104
105 #include <boost/bind.hpp>
106
107 #ifdef HAVE_SYS_TIME_H
108 # include <sys/time.h>
109 #endif
110 #ifdef HAVE_UNISTD_H
111 # include <unistd.h>
112 #endif
113
114 using namespace std;
115 using namespace lyx::support;
116
117 namespace lyx {
118 namespace frontend {
119
120 namespace {
121
122 class BackgroundWidget : public QWidget
123 {
124 public:
125         BackgroundWidget()
126         {
127                 LYXERR(Debug::GUI, "show banner: " << lyxrc.show_banner);
128                 /// The text to be written on top of the pixmap
129                 QString const text = lyx_version ?
130                         qt_("version ") + lyx_version : qt_("unknown version");
131                 splash_ = getPixmap("images/", "banner", "png");
132
133                 QPainter pain(&splash_);
134                 pain.setPen(QColor(0, 0, 0));
135                 QFont font;
136                 // The font used to display the version info
137                 font.setStyleHint(QFont::SansSerif);
138                 font.setWeight(QFont::Bold);
139                 font.setPointSize(int(toqstr(lyxrc.font_sizes[FONT_SIZE_LARGE]).toDouble()));
140                 pain.setFont(font);
141                 pain.drawText(260, 15, text);
142         }
143
144         void paintEvent(QPaintEvent *)
145         {
146                 int x = (width() - splash_.width()) / 2;
147                 int y = (height() - splash_.height()) / 2;
148                 QPainter pain(this);
149                 pain.drawPixmap(x, y, splash_);
150         }
151
152 private:
153         QPixmap splash_;
154 };
155
156
157 /// Toolbar store providing access to individual toolbars by name.
158 typedef std::map<std::string, GuiToolbar *> ToolbarMap;
159
160 typedef boost::shared_ptr<Dialog> DialogPtr;
161
162 } // namespace anon
163
164
165 struct GuiView::GuiViewPrivate
166 {
167         GuiViewPrivate()
168                 : current_work_area_(0), current_main_work_area_(0),
169                 layout_(0), autosave_timeout_(5000),
170                 in_show_(false)
171         {
172                 // hardcode here the platform specific icon size
173                 smallIconSize = 14;  // scaling problems
174                 normalIconSize = 20; // ok, default
175                 bigIconSize = 26;    // better for some math icons
176
177                 splitter_ = new QSplitter;
178                 bg_widget_ = new BackgroundWidget;
179                 stack_widget_ = new QStackedWidget;
180                 stack_widget_->addWidget(bg_widget_);
181                 stack_widget_->addWidget(splitter_);
182                 setBackground();
183         }
184
185         ~GuiViewPrivate()
186         {
187                 delete splitter_;
188                 delete bg_widget_;
189                 delete stack_widget_;
190         }
191
192         QMenu * toolBarPopup(GuiView * parent)
193         {
194                 // FIXME: translation
195                 QMenu * menu = new QMenu(parent);
196                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
197
198                 QAction * smallIcons = new QAction(iconSizeGroup);
199                 smallIcons->setText(qt_("Small-sized icons"));
200                 smallIcons->setCheckable(true);
201                 QObject::connect(smallIcons, SIGNAL(triggered()),
202                         parent, SLOT(smallSizedIcons()));
203                 menu->addAction(smallIcons);
204
205                 QAction * normalIcons = new QAction(iconSizeGroup);
206                 normalIcons->setText(qt_("Normal-sized icons"));
207                 normalIcons->setCheckable(true);
208                 QObject::connect(normalIcons, SIGNAL(triggered()),
209                         parent, SLOT(normalSizedIcons()));
210                 menu->addAction(normalIcons);
211
212                 QAction * bigIcons = new QAction(iconSizeGroup);
213                 bigIcons->setText(qt_("Big-sized icons"));
214                 bigIcons->setCheckable(true);
215                 QObject::connect(bigIcons, SIGNAL(triggered()),
216                         parent, SLOT(bigSizedIcons()));
217                 menu->addAction(bigIcons);
218
219                 unsigned int cur = parent->iconSize().width();
220                 if ( cur == parent->d.smallIconSize)
221                         smallIcons->setChecked(true);
222                 else if (cur == parent->d.normalIconSize)
223                         normalIcons->setChecked(true);
224                 else if (cur == parent->d.bigIconSize)
225                         bigIcons->setChecked(true);
226
227                 return menu;
228         }
229
230         void setBackground()
231         {
232                 stack_widget_->setCurrentWidget(bg_widget_);
233                 bg_widget_->setUpdatesEnabled(true);
234         }
235
236         TabWorkArea * tabWorkArea(int i)
237         {
238                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
239         }
240
241         TabWorkArea * currentTabWorkArea()
242         {
243                 if (splitter_->count() == 1)
244                         // The first TabWorkArea is always the first one, if any.
245                         return tabWorkArea(0);
246
247                 for (int i = 0; i != splitter_->count(); ++i) {
248                         TabWorkArea * twa = tabWorkArea(i);
249                         if (current_main_work_area_ == twa->currentWorkArea())
250                                 return twa;
251                 }
252
253                 // None has the focus so we just take the first one.
254                 return tabWorkArea(0);
255         }
256
257 public:
258         GuiWorkArea * current_work_area_;
259         GuiWorkArea * current_main_work_area_;
260         QSplitter * splitter_;
261         QStackedWidget * stack_widget_;
262         BackgroundWidget * bg_widget_;
263         /// view's toolbars
264         ToolbarMap toolbars_;
265         /// The main layout box.
266         /** 
267          * \warning Don't Delete! The layout box is actually owned by
268          * whichever toolbar contains it. All the GuiView class needs is a
269          * means of accessing it.
270          *
271          * FIXME: replace that with a proper model so that we are not limited
272          * to only one dialog.
273          */
274         LayoutBox * layout_;
275
276         ///
277         map<string, Inset *> open_insets_;
278
279         ///
280         map<string, DialogPtr> dialogs_;
281
282         unsigned int smallIconSize;
283         unsigned int normalIconSize;
284         unsigned int bigIconSize;
285         ///
286         QTimer statusbar_timer_;
287         /// auto-saving of buffers
288         Timeout autosave_timeout_;
289         /// flag against a race condition due to multiclicks, see bug #1119
290         bool in_show_;
291
292         ///
293         TocModels toc_models_;
294 };
295
296
297 GuiView::GuiView(int id)
298         : d(*new GuiViewPrivate), id_(id), closing_(false)
299 {
300         // GuiToolbars *must* be initialised before the menu bar.
301         normalSizedIcons(); // at least on Mac the default is 32 otherwise, which is huge
302         constructToolbars();
303
304         // set ourself as the current view. This is needed for the menu bar
305         // filling, at least for the static special menu item on Mac. Otherwise
306         // they are greyed out.
307         guiApp->setCurrentView(this);
308         
309         // Fill up the menu bar.
310         guiApp->menus().fillMenuBar(menuBar(), this, true);
311
312         setCentralWidget(d.stack_widget_);
313
314         // Start autosave timer
315         if (lyxrc.autosave) {
316                 d.autosave_timeout_.timeout.connect(boost::bind(&GuiView::autoSave, this));
317                 d.autosave_timeout_.setTimeout(lyxrc.autosave * 1000);
318                 d.autosave_timeout_.start();
319         }
320         connect(&d.statusbar_timer_, SIGNAL(timeout()),
321                 this, SLOT(clearMessage()));
322
323         // We don't want to keep the window in memory if it is closed.
324         setAttribute(Qt::WA_DeleteOnClose, true);
325
326 #if (!defined(Q_WS_WIN) && !defined(Q_WS_MACX))
327         // assign an icon to main form. We do not do it under Qt/Win or Qt/Mac,
328         // since the icon is provided in the application bundle.
329         setWindowIcon(getPixmap("images/", "lyx", "png"));
330 #endif
331
332         // For Drag&Drop.
333         setAcceptDrops(true);
334
335         statusBar()->setSizeGripEnabled(true);
336
337         // Forbid too small unresizable window because it can happen
338         // with some window manager under X11.
339         setMinimumSize(300, 200);
340
341         if (lyxrc.allow_geometry_session) {
342                 // Now take care of session management.
343                 if (restoreLayout())
344                         return;
345         }
346
347         // no session handling, default to a sane size.
348         setGeometry(50, 50, 690, 510);
349         initToolbars();
350
351         // clear session data if any.
352         QSettings settings;
353         settings.remove("views");
354 }
355
356
357 GuiView::~GuiView()
358 {
359         delete &d;
360 }
361
362
363 void GuiView::saveLayout() const
364 {
365         QSettings settings;
366         settings.beginGroup("views");
367         settings.beginGroup(QString::number(id_));
368 #ifdef Q_WS_X11
369         settings.setValue("pos", pos());
370         settings.setValue("size", size());
371 #else
372         settings.setValue("geometry", saveGeometry());
373 #endif
374         settings.setValue("layout", saveState(0));
375         settings.setValue("icon_size", iconSize());
376 }
377
378
379 bool GuiView::restoreLayout()
380 {
381         QSettings settings;
382         settings.beginGroup("views");
383         settings.beginGroup(QString::number(id_));
384         QString const icon_key = "icon_size";
385         if (!settings.contains(icon_key))
386                 return false;
387
388         //code below is skipped when when ~/.config/LyX is (re)created
389         setIconSize(settings.value(icon_key).toSize());
390 #ifdef Q_WS_X11
391         QPoint pos = settings.value("pos", QPoint(50, 50)).toPoint();
392         QSize size = settings.value("size", QSize(690, 510)).toSize();
393         resize(size);
394         move(pos);
395 #else
396         // Work-around for bug #6034: the window ends up in an undetermined
397         // state when trying to restore a maximized window when it is
398         // already maximized.
399         if (!(windowState() & Qt::WindowMaximized))
400                 if (!restoreGeometry(settings.value("geometry").toByteArray()))
401                         setGeometry(50, 50, 690, 510);
402 #endif
403         // Make sure layout is correctly oriented.
404         setLayoutDirection(qApp->layoutDirection());
405
406         // Allow the toc and view-source dock widget to be restored if needed.
407         Dialog * dialog;
408         if ((dialog = findOrBuild("toc", true)))
409                 // see bug 5082. At least setup title and enabled state.
410                 // Visibility will be adjusted by restoreState below.
411                 dialog->prepareView();
412         if ((dialog = findOrBuild("view-source", true)))
413                 dialog->prepareView();
414
415         if (!restoreState(settings.value("layout").toByteArray(), 0))
416                 initToolbars();
417         updateDialogs();
418         return true;
419 }
420
421
422 GuiToolbar * GuiView::toolbar(string const & name)
423 {
424         ToolbarMap::iterator it = d.toolbars_.find(name);
425         if (it != d.toolbars_.end())
426                 return it->second;
427
428         LYXERR(Debug::GUI, "Toolbar::display: no toolbar named " << name);
429         message(bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name)));
430         return 0;
431 }
432
433
434 void GuiView::constructToolbars()
435 {
436         ToolbarMap::iterator it = d.toolbars_.begin();
437         for (; it != d.toolbars_.end(); ++it)
438                 delete it->second;
439         d.toolbars_.clear();
440
441         // I don't like doing this here, but the standard toolbar
442         // destroys this object when it's destroyed itself (vfr)
443         d.layout_ = new LayoutBox(*this);
444         d.stack_widget_->addWidget(d.layout_);
445         d.layout_->move(0,0);
446
447         // extracts the toolbars from the backend
448         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
449         Toolbars::Infos::iterator end = guiApp->toolbars().end();
450         for (; cit != end; ++cit)
451                 d.toolbars_[cit->name] =  new GuiToolbar(*cit, *this);
452 }
453
454
455 void GuiView::initToolbars()
456 {
457         // extracts the toolbars from the backend
458         Toolbars::Infos::iterator cit = guiApp->toolbars().begin();
459         Toolbars::Infos::iterator end = guiApp->toolbars().end();
460         for (; cit != end; ++cit) {
461                 GuiToolbar * tb = toolbar(cit->name);
462                 if (!tb)
463                         continue;
464                 int const visibility = guiApp->toolbars().defaultVisibility(cit->name);
465                 bool newline = true;
466                 tb->setVisible(false);
467                 tb->setVisibility(visibility);
468
469                 if (visibility & Toolbars::TOP) {
470                         if (newline)
471                                 addToolBarBreak(Qt::TopToolBarArea);
472                         addToolBar(Qt::TopToolBarArea, tb);
473                 }
474
475                 if (visibility & Toolbars::BOTTOM) {
476                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
477 #if (QT_VERSION >= 0x040202)
478                         addToolBarBreak(Qt::BottomToolBarArea);
479 #endif
480                         addToolBar(Qt::BottomToolBarArea, tb);
481                 }
482
483                 if (visibility & Toolbars::LEFT) {
484                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
485 #if (QT_VERSION >= 0x040202)
486                         addToolBarBreak(Qt::LeftToolBarArea);
487 #endif
488                         addToolBar(Qt::LeftToolBarArea, tb);
489                 }
490
491                 if (visibility & Toolbars::RIGHT) {
492                         // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
493 #if (QT_VERSION >= 0x040202)
494                         addToolBarBreak(Qt::RightToolBarArea);
495 #endif
496                         addToolBar(Qt::RightToolBarArea, tb);
497                 }
498
499                 if (visibility & Toolbars::ON)
500                         tb->setVisible(true);
501         }
502 }
503
504
505 TocModels & GuiView::tocModels()
506 {
507         return d.toc_models_;
508 }
509
510
511 void GuiView::setFocus()
512 {
513         LYXERR(Debug::DEBUG, "GuiView::setFocus()" << this);
514         // Make sure LyXFunc points to the correct view.
515         guiApp->setCurrentView(this);
516         QMainWindow::setFocus();
517         if (d.current_work_area_)
518                 d.current_work_area_->setFocus();
519 }
520
521
522 QMenu * GuiView::createPopupMenu()
523 {
524         return d.toolBarPopup(this);
525 }
526
527
528 void GuiView::showEvent(QShowEvent * e)
529 {
530         LYXERR(Debug::GUI, "Passed Geometry "
531                 << size().height() << "x" << size().width()
532                 << "+" << pos().x() << "+" << pos().y());
533
534         if (d.splitter_->count() == 0)
535                 // No work area, switch to the background widget.
536                 d.setBackground();
537
538         QMainWindow::showEvent(e);
539 }
540
541
542 /** Destroy only all tabbed WorkAreas. Destruction of other WorkAreas
543  ** is responsibility of the container (e.g., dialog)
544  **/
545 void GuiView::closeEvent(QCloseEvent * close_event)
546 {
547         LYXERR(Debug::DEBUG, "GuiView::closeEvent()");
548         closing_ = true;
549
550         writeSession();
551
552         // it can happen that this event arrives without selecting the view,
553         // e.g. when clicking the close button on a background window.
554         setFocus();
555         if (!closeWorkAreaAll()) {
556                 closing_ = false;
557                 close_event->ignore();
558                 return;
559         }
560
561         // Make sure that nothing will use this to be closed View.
562         guiApp->unregisterView(this);
563
564         if (isFullScreen()) {
565                 // Switch off fullscreen before closing.
566                 toggleFullScreen();
567                 updateDialogs();
568         }
569
570         // Make sure the timer time out will not trigger a statusbar update.
571         d.statusbar_timer_.stop();
572
573         // Saving fullscreen requires additional tweaks in the toolbar code.
574         // It wouldn't also work under linux natively.
575         if (lyxrc.allow_geometry_session) {
576                 // Save this window geometry and layout.
577                 saveLayout();
578                 // Then the toolbar private states.
579                 ToolbarMap::iterator end = d.toolbars_.end();
580                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
581                         it->second->saveSession();
582                 // Now take care of all other dialogs:
583                 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
584                 for (; it!= d.dialogs_.end(); ++it)
585                         it->second->saveSession();
586         }
587
588         close_event->accept();
589 }
590
591
592 void GuiView::dragEnterEvent(QDragEnterEvent * event)
593 {
594         if (event->mimeData()->hasUrls())
595                 event->accept();
596         /// \todo Ask lyx-devel is this is enough:
597         /// if (event->mimeData()->hasFormat("text/plain"))
598         ///     event->acceptProposedAction();
599 }
600
601
602 void GuiView::dropEvent(QDropEvent * event)
603 {
604         QList<QUrl> files = event->mimeData()->urls();
605         if (files.isEmpty())
606                 return;
607
608         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
609         for (int i = 0; i != files.size(); ++i) {
610                 string const file = os::internal_path(fromqstr(
611                         files.at(i).toLocalFile()));
612                 if (!file.empty()) {
613                         // Asynchronously post the event. DropEvent usually come
614                         // from the BufferView. But reloading a file might close
615                         // the BufferView from within its own event handler.
616                         guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
617                         event->accept();
618                 }
619         }
620 }
621
622
623 void GuiView::message(docstring const & str)
624 {
625         if (ForkedProcess::iAmAChild())
626                 return;
627
628         statusBar()->showMessage(toqstr(str));
629         d.statusbar_timer_.stop();
630         d.statusbar_timer_.start(3000);
631 }
632
633
634 void GuiView::smallSizedIcons()
635 {
636         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
637 }
638
639
640 void GuiView::normalSizedIcons()
641 {
642         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
643 }
644
645
646 void GuiView::bigSizedIcons()
647 {
648         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
649 }
650
651
652 void GuiView::clearMessage()
653 {
654         if (!hasFocus())
655                 return;
656         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
657         d.statusbar_timer_.stop();
658 }
659
660
661 void GuiView::updateWindowTitle(GuiWorkArea * wa)
662 {
663         if (wa != d.current_work_area_)
664                 return;
665         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
666         setWindowIconText(wa->windowIconText());
667 }
668
669
670 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
671 {
672         disconnectBuffer();
673         disconnectBufferView();
674         connectBufferView(wa->bufferView());
675         connectBuffer(wa->bufferView().buffer());
676         d.current_work_area_ = wa;
677         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
678                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
679         updateWindowTitle(wa);
680
681         structureChanged();
682
683         // The document settings needs to be reinitialised.
684         updateDialog("document", "");
685
686         // Buffer-dependent dialogs must be updated. This is done here because
687         // some dialogs require buffer()->text.
688         updateDialogs();
689 }
690
691
692 void GuiView::on_lastWorkAreaRemoved()
693 {
694         if (closing_)
695                 // We already are in a close event. Nothing more to do.
696                 return;
697
698         if (d.splitter_->count() > 1)
699                 // We have a splitter so don't close anything.
700                 return;
701
702         // Reset and updates the dialogs.
703         d.toc_models_.reset(0);
704         updateDialog("document", "");
705         updateDialogs();
706
707         resetWindowTitleAndIconText();
708
709         if (lyxrc.open_buffers_in_tabs)
710                 // Nothing more to do, the window should stay open.
711                 return;
712
713         if (guiApp->viewIds().size() > 1) {
714                 close();
715                 return;
716         }
717
718 #ifdef Q_WS_MACX
719         // On Mac we also close the last window because the application stay
720         // resident in memory. On other platforms we don't close the last
721         // window because this would quit the application.
722         close();
723 #endif
724 }
725
726
727 void GuiView::updateStatusBar()
728 {
729         // let the user see the explicit message
730         if (d.statusbar_timer_.isActive())
731                 return;
732
733         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
734 }
735
736
737 bool GuiView::hasFocus() const
738 {
739         return qApp->activeWindow() == this;
740 }
741
742
743 bool GuiView::event(QEvent * e)
744 {
745         switch (e->type())
746         {
747         // Useful debug code:
748         //case QEvent::ActivationChange:
749         //case QEvent::WindowDeactivate:
750         //case QEvent::Paint:
751         //case QEvent::Enter:
752         //case QEvent::Leave:
753         //case QEvent::HoverEnter:
754         //case QEvent::HoverLeave:
755         //case QEvent::HoverMove:
756         //case QEvent::StatusTip:
757         //case QEvent::DragEnter:
758         //case QEvent::DragLeave:
759         //case QEvent::Drop:
760         //      break;
761
762         case QEvent::WindowActivate: {
763                 GuiView * old_view = guiApp->currentView();
764                 if (this == old_view) {
765                         setFocus();
766                         return QMainWindow::event(e);
767                 }
768                 if (old_view && old_view->currentBufferView()) {
769                         // save current selection to the selection buffer to allow
770                         // middle-button paste in this window.
771                         cap::saveSelection(old_view->currentBufferView()->cursor());
772                 }
773                 guiApp->setCurrentView(this);
774                 if (d.current_work_area_) {
775                         BufferView & bv = d.current_work_area_->bufferView();
776                         connectBufferView(bv);
777                         connectBuffer(bv.buffer());
778                         // The document structure, name and dialogs might have
779                         // changed in another view.
780                         structureChanged();
781                         // The document settings needs to be reinitialised.
782                         updateDialog("document", "");
783                         updateDialogs();
784                 } else {
785                         resetWindowTitleAndIconText();
786                 }
787                 setFocus();
788                 return QMainWindow::event(e);
789         }
790
791         case QEvent::ShortcutOverride: {
792
793 // See bug 4888
794 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
795                 if (isFullScreen() && menuBar()->isHidden()) {
796                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
797                         // FIXME: we should also try to detect special LyX shortcut such as
798                         // Alt-P and Alt-M. Right now there is a hack in
799                         // GuiWorkArea::processKeySym() that hides again the menubar for
800                         // those cases.
801                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
802                                 menuBar()->show();
803                                 return QMainWindow::event(e);
804                         }
805                 }
806 #endif
807
808                 if (d.current_work_area_)
809                         // Nothing special to do.
810                         return QMainWindow::event(e);
811
812                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
813                 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
814                 // between controls.
815                 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab 
816                         || ke->key() == Qt::Key_Backtab)
817                         return QMainWindow::event(e);
818
819                 // Allow processing of shortcuts that are allowed even when no Buffer
820                 // is viewed.
821                 KeySymbol sym;
822                 setKeySymbol(&sym, ke);
823                 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
824                 e->accept();
825                 return true;
826         }
827
828         default:
829                 return QMainWindow::event(e);
830         }
831 }
832
833 void GuiView::resetWindowTitleAndIconText()
834 {
835     setWindowTitle(qt_("LyX"));
836     setWindowIconText(qt_("LyX"));
837 }
838
839 bool GuiView::focusNextPrevChild(bool /*next*/)
840 {
841         setFocus();
842         return true;
843 }
844
845
846 void GuiView::setBusy(bool busy)
847 {
848         if (d.current_work_area_) {
849                 d.current_work_area_->setUpdatesEnabled(!busy);
850                 if (busy)
851                         d.current_work_area_->stopBlinkingCursor();
852                 else
853                         d.current_work_area_->startBlinkingCursor();
854         }
855
856         if (busy)
857                 QApplication::setOverrideCursor(Qt::WaitCursor);
858         else
859                 QApplication::restoreOverrideCursor();
860 }
861
862
863 GuiWorkArea * GuiView::workArea(Buffer & buffer)
864 {
865         if (currentWorkArea()
866             && &currentWorkArea()->bufferView().buffer() == &buffer)
867                 return (GuiWorkArea *) currentWorkArea();
868         if (TabWorkArea * twa = d.currentTabWorkArea())
869                 return twa->workArea(buffer);
870         return 0;
871 }
872
873
874 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
875 {
876         // Automatically create a TabWorkArea if there are none yet.
877         TabWorkArea * tab_widget = d.splitter_->count() 
878                 ? d.currentTabWorkArea() : addTabWorkArea();
879         return tab_widget->addWorkArea(buffer, *this);
880 }
881
882
883 TabWorkArea * GuiView::addTabWorkArea()
884 {
885         TabWorkArea * twa = new TabWorkArea;
886         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
887                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
888         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
889                          this, SLOT(on_lastWorkAreaRemoved()));
890
891         d.splitter_->addWidget(twa);
892         d.stack_widget_->setCurrentWidget(d.splitter_);
893         return twa;
894 }
895
896
897 GuiWorkArea const * GuiView::currentWorkArea() const
898 {
899         return d.current_work_area_;
900 }
901
902
903 GuiWorkArea * GuiView::currentWorkArea()
904 {
905         return d.current_work_area_;
906 }
907
908
909 GuiWorkArea const * GuiView::currentMainWorkArea() const
910 {
911         if (d.currentTabWorkArea() == NULL)
912                 return NULL;
913         return d.currentTabWorkArea()->currentWorkArea();
914 }
915
916
917 GuiWorkArea * GuiView::currentMainWorkArea()
918 {
919         if (d.currentTabWorkArea() == NULL)
920                 return NULL;
921         return d.currentTabWorkArea()->currentWorkArea();
922 }
923
924
925 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
926 {
927         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
928         if (wa == NULL) {
929                 d.current_work_area_ = NULL;
930                 d.setBackground();
931                 return;
932         }
933         GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
934         if (old_gwa == wa)
935                 return;
936
937         if (currentBufferView())
938                 cap::saveSelection(currentBufferView()->cursor());
939
940         theGuiApp()->setCurrentView(this);
941         d.current_work_area_ = wa;
942         for (int i = 0; i != d.splitter_->count(); ++i) {
943                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
944                         //if (d.current_main_work_area_)
945                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
946                         d.current_main_work_area_ = wa;
947                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
948                         //d.current_main_work_area_->setLineWidth(2);
949                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
950                         return;
951                 }
952         }
953         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
954         on_currentWorkAreaChanged(wa);
955         BufferView & bv = wa->bufferView();
956         bv.cursor().fixIfBroken();
957         bv.updateMetrics();
958         wa->setUpdatesEnabled(true);
959         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
960 }
961
962
963 void GuiView::removeWorkArea(GuiWorkArea * wa)
964 {
965         LASSERT(wa, return);
966         if (wa == d.current_work_area_) {
967                 disconnectBuffer();
968                 disconnectBufferView();
969                 d.current_work_area_ = 0;
970                 d.current_main_work_area_ = 0;
971         }
972
973         bool found_twa = false;
974         for (int i = 0; i != d.splitter_->count(); ++i) {
975                 TabWorkArea * twa = d.tabWorkArea(i);
976                 if (twa->removeWorkArea(wa)) {
977                         // Found in this tab group, and deleted the GuiWorkArea.
978                         found_twa = true;
979                         if (twa->count() != 0) {
980                                 if (d.current_work_area_ == 0)
981                                         // This means that we are closing the current GuiWorkArea, so
982                                         // switch to the next GuiWorkArea in the found TabWorkArea.
983                                         setCurrentWorkArea(twa->currentWorkArea());
984                         } else {
985                                 // No more WorkAreas in this tab group, so delete it.
986                                 delete twa;
987                         }
988                         break;
989                 }
990         }
991
992         // It is not a tabbed work area (i.e., the search work area), so it
993         // should be deleted by other means.
994         LASSERT(found_twa, /* */);
995
996         if (d.current_work_area_ == 0) {
997                 if (d.splitter_->count() != 0) {
998                         TabWorkArea * twa = d.currentTabWorkArea();
999                         setCurrentWorkArea(twa->currentWorkArea());
1000                 } else {
1001                         // No more work areas, switch to the background widget.
1002                         setCurrentWorkArea(0);
1003                 }
1004         }
1005 }
1006
1007
1008 LayoutBox * GuiView::getLayoutDialog() const
1009 {
1010         return d.layout_;
1011 }
1012
1013
1014 void GuiView::updateLayoutList()
1015 {
1016         if (d.layout_)
1017                 d.layout_->updateContents(false);
1018 }
1019
1020
1021 void GuiView::updateToolbars()
1022 {
1023         ToolbarMap::iterator end = d.toolbars_.end();
1024         if (d.current_work_area_) {
1025                 bool const math =
1026                         d.current_work_area_->bufferView().cursor().inMathed();
1027                 bool const table =
1028                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1029                 bool const review =
1030                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1031                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1032                 bool const mathmacrotemplate =
1033                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1034
1035                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1036                         it->second->update(math, table, review, mathmacrotemplate);
1037         } else
1038                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1039                         it->second->update(false, false, false, false);
1040 }
1041
1042
1043 void GuiView::setBuffer(Buffer * newBuffer)
1044 {
1045         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1046         LASSERT(newBuffer, return);
1047         setBusy(true);
1048
1049         GuiWorkArea * wa = workArea(*newBuffer);
1050         if (wa == 0) {
1051                 newBuffer->masterBuffer()->updateLabels();
1052                 wa = addWorkArea(*newBuffer);
1053         } else {
1054                 //Disconnect the old buffer...there's no new one.
1055                 disconnectBuffer();
1056         }
1057         connectBuffer(*newBuffer);
1058         connectBufferView(wa->bufferView());
1059         setCurrentWorkArea(wa);
1060
1061         setBusy(false);
1062 }
1063
1064
1065 void GuiView::connectBuffer(Buffer & buf)
1066 {
1067         buf.setGuiDelegate(this);
1068 }
1069
1070
1071 void GuiView::disconnectBuffer()
1072 {
1073         if (d.current_work_area_)
1074                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1075 }
1076
1077
1078 void GuiView::connectBufferView(BufferView & bv)
1079 {
1080         bv.setGuiDelegate(this);
1081 }
1082
1083
1084 void GuiView::disconnectBufferView()
1085 {
1086         if (d.current_work_area_)
1087                 d.current_work_area_->bufferView().setGuiDelegate(0);
1088 }
1089
1090
1091 void GuiView::errors(string const & error_type, bool from_master)
1092 {
1093         ErrorList & el = from_master ? 
1094                 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1095                 : documentBufferView()->buffer().errorList(error_type);
1096         string data = error_type;
1097         if (from_master)
1098                 data = "from_master|" + error_type;
1099         if (!el.empty())
1100                 showDialog("errorlist", data);
1101 }
1102
1103
1104 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1105 {
1106         d.toc_models_.updateItem(toqstr(type), dit);
1107 }
1108
1109
1110 void GuiView::structureChanged()
1111 {
1112         d.toc_models_.reset(documentBufferView());
1113         // Navigator needs more than a simple update in this case. It needs to be
1114         // rebuilt.
1115         updateDialog("toc", "");
1116 }
1117
1118
1119 void GuiView::updateDialog(string const & name, string const & data)
1120 {
1121         if (!isDialogVisible(name))
1122                 return;
1123
1124         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1125         if (it == d.dialogs_.end())
1126                 return;
1127
1128         Dialog * const dialog = it->second.get();
1129         if (dialog->isVisibleView())
1130                 dialog->initialiseParams(data);
1131 }
1132
1133
1134 BufferView * GuiView::documentBufferView()
1135 {
1136         return currentMainWorkArea()
1137                 ? &currentMainWorkArea()->bufferView()
1138                 : 0;
1139 }
1140
1141
1142 BufferView const * GuiView::documentBufferView() const 
1143 {
1144         return currentMainWorkArea()
1145                 ? &currentMainWorkArea()->bufferView()
1146                 : 0;
1147 }
1148
1149
1150 BufferView * GuiView::currentBufferView()
1151 {
1152         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1153 }
1154
1155
1156 BufferView const * GuiView::currentBufferView() const
1157 {
1158         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1159 }
1160
1161
1162 void GuiView::autoSave()
1163 {
1164         LYXERR(Debug::INFO, "Running autoSave()");
1165
1166         if (documentBufferView())
1167                 documentBufferView()->buffer().autoSave();
1168 }
1169
1170
1171 void GuiView::resetAutosaveTimers()
1172 {
1173         if (lyxrc.autosave)
1174                 d.autosave_timeout_.restart();
1175 }
1176
1177
1178 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1179 {
1180         bool enable = true;
1181         Buffer * buf = currentBufferView()
1182                 ? &currentBufferView()->buffer() : 0;
1183         Buffer * doc_buffer = documentBufferView()
1184                 ? &(documentBufferView()->buffer()) : 0;
1185
1186         // Check whether we need a buffer
1187         if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
1188                 // no, exit directly
1189                 flag.message(from_utf8(N_("Command not allowed with"
1190                                     "out any document open")));
1191                 flag.setEnabled(false);
1192                 return true;
1193         }
1194
1195         if (cmd.origin == FuncRequest::TOC) {
1196                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1197                 FuncStatus fs;
1198                 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1199                         flag |= fs;
1200                 else
1201                         flag.setEnabled(false);
1202                 return true;
1203         }
1204
1205         switch(cmd.action) {
1206         case LFUN_BUFFER_IMPORT:
1207                 break;
1208
1209         case LFUN_BUFFER_RELOAD:
1210                 enable = doc_buffer && !doc_buffer->isUnnamed()
1211                         && doc_buffer->fileName().exists()
1212                         && (!doc_buffer->isClean()
1213                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1214                 break;
1215
1216         case LFUN_BUFFER_CHILD_OPEN:
1217                 enable = doc_buffer;
1218                 break;
1219
1220         case LFUN_BUFFER_WRITE:
1221                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1222                 break;
1223
1224         //FIXME: This LFUN should be moved to GuiApplication.
1225         case LFUN_BUFFER_WRITE_ALL: {
1226                 // We enable the command only if there are some modified buffers
1227                 Buffer * first = theBufferList().first();
1228                 enable = false;
1229                 if (!first)
1230                         break;
1231                 Buffer * b = first;
1232                 // We cannot use a for loop as the buffer list is a cycle.
1233                 do {
1234                         if (!b->isClean()) {
1235                                 enable = true;
1236                                 break;
1237                         }
1238                         b = theBufferList().next(b);
1239                 } while (b != first); 
1240                 break;
1241         }
1242
1243         case LFUN_BUFFER_WRITE_AS:
1244                 enable = doc_buffer;
1245                 break;
1246
1247         case LFUN_BUFFER_CLOSE:
1248                 enable = doc_buffer;
1249                 break;
1250
1251         case LFUN_BUFFER_CLOSE_ALL:
1252                 enable = theBufferList().last() != theBufferList().first();
1253                 break;
1254
1255         case LFUN_SPLIT_VIEW:
1256                 if (cmd.getArg(0) == "vertical")
1257                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1258                                          d.splitter_->orientation() == Qt::Vertical);
1259                 else
1260                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1261                                          d.splitter_->orientation() == Qt::Horizontal);
1262                 break;
1263
1264         case LFUN_CLOSE_TAB_GROUP:
1265                 enable = d.currentTabWorkArea();
1266                 break;
1267
1268         case LFUN_TOOLBAR_TOGGLE:
1269                 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1270                         flag.setOnOff(t->isVisible());
1271                 break;
1272
1273         case LFUN_UI_TOGGLE:
1274                 flag.setOnOff(isFullScreen());
1275                 break;
1276
1277         case LFUN_DIALOG_DISCONNECT_INSET:
1278                 break;
1279
1280         case LFUN_DIALOG_HIDE:
1281                 // FIXME: should we check if the dialog is shown?
1282                 break;
1283
1284         case LFUN_DIALOG_TOGGLE:
1285                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1286                 // fall through to set "enable"
1287         case LFUN_DIALOG_SHOW: {
1288                 string const name = cmd.getArg(0);
1289                 if (!doc_buffer)
1290                         enable = name == "aboutlyx"
1291                                 || name == "file" //FIXME: should be removed.
1292                                 || name == "prefs"
1293                                 || name == "texinfo";
1294                 else if (name == "print")
1295                         enable = doc_buffer->isExportable("dvi")
1296                                 && lyxrc.print_command != "none";
1297                 else if (name == "character" || name == "symbols") {
1298                         if (!buf || buf->isReadonly()
1299                                 || !currentBufferView()->cursor().inTexted())
1300                                 enable = false;
1301                         else {
1302                                 // FIXME we should consider passthru
1303                                 // paragraphs too.
1304                                 Inset const & in = currentBufferView()->cursor().inset();
1305                                 enable = !in.getLayout().isPassThru();
1306                         }
1307                 }
1308                 else if (name == "latexlog")
1309                         enable = FileName(doc_buffer->logName()).isReadableFile();
1310                 else if (name == "spellchecker")
1311                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1312                 else if (name == "vclog")
1313                         enable = doc_buffer->lyxvc().inUse();
1314                 break;
1315         }
1316
1317         case LFUN_DIALOG_UPDATE: {
1318                 string const name = cmd.getArg(0);
1319                 if (!buf)
1320                         enable = name == "prefs";
1321                 break;
1322         }
1323
1324         case LFUN_COMMAND_EXECUTE:
1325         case LFUN_MESSAGE:
1326         case LFUN_MENU_OPEN:
1327                 // Nothing to check.
1328                 break;
1329
1330         case LFUN_INSET_APPLY: {
1331                 string const name = cmd.getArg(0);
1332                 Inset * inset = getOpenInset(name);
1333                 if (inset) {
1334                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1335                         FuncStatus fs;
1336                         if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1337                                 // Every inset is supposed to handle this
1338                                 LASSERT(false, break);
1339                         }
1340                         flag |= fs;
1341                 } else {
1342                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1343                         flag |= lyx::getStatus(fr);
1344                 }
1345                 enable = flag.enabled();
1346                 break;
1347         }
1348
1349         case LFUN_COMPLETION_INLINE:
1350                 if (!d.current_work_area_
1351                     || !d.current_work_area_->completer().inlinePossible(
1352                         currentBufferView()->cursor()))
1353                     enable = false;
1354                 break;
1355
1356         case LFUN_COMPLETION_POPUP:
1357                 if (!d.current_work_area_
1358                     || !d.current_work_area_->completer().popupPossible(
1359                         currentBufferView()->cursor()))
1360                     enable = false;
1361                 break;
1362
1363         case LFUN_COMPLETION_COMPLETE:
1364                 if (!d.current_work_area_
1365                         || !d.current_work_area_->completer().inlinePossible(
1366                         currentBufferView()->cursor()))
1367                     enable = false;
1368                 break;
1369
1370         case LFUN_COMPLETION_ACCEPT:
1371                 if (!d.current_work_area_
1372                     || (!d.current_work_area_->completer().popupVisible()
1373                         && !d.current_work_area_->completer().inlineVisible()
1374                         && !d.current_work_area_->completer().completionAvailable()))
1375                         enable = false;
1376                 break;
1377
1378         case LFUN_COMPLETION_CANCEL:
1379                 if (!d.current_work_area_
1380                     || (!d.current_work_area_->completer().popupVisible()
1381                         && !d.current_work_area_->completer().inlineVisible()))
1382                         enable = false;
1383                 break;
1384
1385         case LFUN_BUFFER_ZOOM_OUT:
1386                 enable = doc_buffer && lyxrc.zoom > 10;
1387                 break;
1388
1389         case LFUN_BUFFER_ZOOM_IN:
1390                 enable = doc_buffer;
1391                 break;
1392         
1393         case LFUN_BUFFER_NEXT:
1394         case LFUN_BUFFER_PREVIOUS:
1395                 // FIXME: should we check is there is an previous or next buffer?
1396                 break;
1397         case LFUN_BUFFER_SWITCH:
1398                 // toggle on the current buffer, but do not toggle off
1399                 // the other ones (is that a good idea?)
1400                 if (doc_buffer
1401                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1402                         flag.setOnOff(true);
1403                 break;
1404
1405         case LFUN_VC_REGISTER:
1406                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1407                 break;
1408         case LFUN_VC_CHECK_IN:
1409                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1410                 break;
1411         case LFUN_VC_CHECK_OUT:
1412                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1413                 break;
1414         case LFUN_VC_LOCKING_TOGGLE:
1415                 enable = doc_buffer && !doc_buffer->isReadonly()
1416                         && doc_buffer->lyxvc().lockingToggleEnabled();
1417                 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1418                 break;
1419         case LFUN_VC_REVERT:
1420                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1421                 break;
1422         case LFUN_VC_UNDO_LAST:
1423                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1424                 break;
1425         case LFUN_VC_COMMAND: {
1426                 if (cmd.argument().empty())
1427                         enable = false;
1428                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1429                         enable = false;
1430                 break;
1431         }
1432
1433         default:
1434                 return false;
1435         }
1436
1437         if (!enable)
1438                 flag.setEnabled(false);
1439
1440         return true;
1441 }
1442
1443
1444 static FileName selectTemplateFile()
1445 {
1446         FileDialog dlg(qt_("Select template file"));
1447         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1448         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1449
1450         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1451                              QStringList(qt_("LyX Documents (*.lyx)")));
1452
1453         if (result.first == FileDialog::Later)
1454                 return FileName();
1455         if (result.second.isEmpty())
1456                 return FileName();
1457         return FileName(fromqstr(result.second));
1458 }
1459
1460
1461 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1462 {
1463         setBusy(true);
1464
1465         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1466
1467         if (!newBuffer) {
1468                 message(_("Document not loaded."));
1469                 setBusy(false);
1470                 return 0;
1471         }
1472         
1473         setBuffer(newBuffer);
1474
1475         // scroll to the position when the file was last closed
1476         if (lyxrc.use_lastfilepos) {
1477                 LastFilePosSection::FilePos filepos =
1478                         theSession().lastFilePos().load(filename);
1479                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1480         }
1481
1482         if (tolastfiles)
1483                 theSession().lastFiles().add(filename);
1484
1485         setBusy(false);
1486         return newBuffer;
1487 }
1488
1489
1490 void GuiView::openDocument(string const & fname)
1491 {
1492         string initpath = lyxrc.document_path;
1493
1494         if (documentBufferView()) {
1495                 string const trypath = documentBufferView()->buffer().filePath();
1496                 // If directory is writeable, use this as default.
1497                 if (FileName(trypath).isDirWritable())
1498                         initpath = trypath;
1499         }
1500
1501         string filename;
1502
1503         if (fname.empty()) {
1504                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1505                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1506                 dlg.setButton2(qt_("Examples|#E#e"),
1507                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1508
1509                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1510                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1511                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1512                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1513                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1514                 FileDialog::Result result =
1515                         dlg.open(toqstr(initpath), filter);
1516
1517                 if (result.first == FileDialog::Later)
1518                         return;
1519
1520                 filename = fromqstr(result.second);
1521
1522                 // check selected filename
1523                 if (filename.empty()) {
1524                         message(_("Canceled."));
1525                         return;
1526                 }
1527         } else
1528                 filename = fname;
1529
1530         // get absolute path of file and add ".lyx" to the filename if
1531         // necessary. 
1532         FileName const fullname = 
1533                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1534         if (!fullname.empty())
1535                 filename = fullname.absFilename();
1536
1537         if (!fullname.onlyPath().isDirectory()) {
1538                 Alert::warning(_("Invalid filename"),
1539                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1540                                 from_utf8(fullname.absFilename())));
1541                 return;
1542         }
1543         // if the file doesn't exist, let the user create one
1544         if (!fullname.exists()) {
1545                 // the user specifically chose this name. Believe him.
1546                 Buffer * const b = newFile(filename, string(), true);
1547                 if (b)
1548                         setBuffer(b);
1549                 return;
1550         }
1551
1552         docstring const disp_fn = makeDisplayPath(filename);
1553         message(bformat(_("Opening document %1$s..."), disp_fn));
1554
1555         docstring str2;
1556         Buffer * buf = loadDocument(fullname);
1557         if (buf) {
1558                 buf->updateLabels();
1559                 setBuffer(buf);
1560                 buf->errors("Parse");
1561                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1562                 if (buf->lyxvc().inUse())
1563                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1564                                 " " + _("Version control detected.");
1565         } else {
1566                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1567         }
1568         message(str2);
1569 }
1570
1571 // FIXME: clean that
1572 static bool import(GuiView * lv, FileName const & filename,
1573         string const & format, ErrorList & errorList)
1574 {
1575         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1576
1577         string loader_format;
1578         vector<string> loaders = theConverters().loaders();
1579         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1580                 for (vector<string>::const_iterator it = loaders.begin();
1581                      it != loaders.end(); ++it) {
1582                         if (!theConverters().isReachable(format, *it))
1583                                 continue;
1584
1585                         string const tofile =
1586                                 support::changeExtension(filename.absFilename(),
1587                                 formats.extension(*it));
1588                         if (!theConverters().convert(0, filename, FileName(tofile),
1589                                 filename, format, *it, errorList))
1590                                 return false;
1591                         loader_format = *it;
1592                         break;
1593                 }
1594                 if (loader_format.empty()) {
1595                         frontend::Alert::error(_("Couldn't import file"),
1596                                      bformat(_("No information for importing the format %1$s."),
1597                                          formats.prettyName(format)));
1598                         return false;
1599                 }
1600         } else
1601                 loader_format = format;
1602
1603         if (loader_format == "lyx") {
1604                 Buffer * buf = lv->loadDocument(lyxfile);
1605                 if (!buf)
1606                         return false;
1607                 buf->updateLabels();
1608                 lv->setBuffer(buf);
1609                 buf->errors("Parse");
1610         } else {
1611                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1612                 if (!b)
1613                         return false;
1614                 lv->setBuffer(b);
1615                 bool as_paragraphs = loader_format == "textparagraph";
1616                 string filename2 = (loader_format == format) ? filename.absFilename()
1617                         : support::changeExtension(filename.absFilename(),
1618                                           formats.extension(loader_format));
1619                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1620                         as_paragraphs);
1621                 guiApp->setCurrentView(lv);
1622                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1623         }
1624
1625         return true;
1626 }
1627
1628
1629 void GuiView::importDocument(string const & argument)
1630 {
1631         string format;
1632         string filename = split(argument, format, ' ');
1633
1634         LYXERR(Debug::INFO, format << " file: " << filename);
1635
1636         // need user interaction
1637         if (filename.empty()) {
1638                 string initpath = lyxrc.document_path;
1639                 if (documentBufferView()) {
1640                         string const trypath = documentBufferView()->buffer().filePath();
1641                         // If directory is writeable, use this as default.
1642                         if (FileName(trypath).isDirWritable())
1643                                 initpath = trypath;
1644                 }
1645
1646                 docstring const text = bformat(_("Select %1$s file to import"),
1647                         formats.prettyName(format));
1648
1649                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1650                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1651                 dlg.setButton2(qt_("Examples|#E#e"),
1652                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1653
1654                 docstring filter = formats.prettyName(format);
1655                 filter += " (*.";
1656                 // FIXME UNICODE
1657                 filter += from_utf8(formats.extension(format));
1658                 filter += ')';
1659
1660                 FileDialog::Result result =
1661                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1662
1663                 if (result.first == FileDialog::Later)
1664                         return;
1665
1666                 filename = fromqstr(result.second);
1667
1668                 // check selected filename
1669                 if (filename.empty())
1670                         message(_("Canceled."));
1671         }
1672
1673         if (filename.empty())
1674                 return;
1675
1676         // get absolute path of file
1677         FileName const fullname(support::makeAbsPath(filename));
1678
1679         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1680
1681         // Check if the document already is open
1682         Buffer * buf = theBufferList().getBuffer(lyxfile);
1683         if (buf) {
1684                 setBuffer(buf);
1685                 if (!closeBuffer()) {
1686                         message(_("Canceled."));
1687                         return;
1688                 }
1689         }
1690
1691         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1692
1693         // if the file exists already, and we didn't do
1694         // -i lyx thefile.lyx, warn
1695         if (lyxfile.exists() && fullname != lyxfile) {
1696
1697                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1698                         "Do you want to overwrite that document?"), displaypath);
1699                 int const ret = Alert::prompt(_("Overwrite document?"),
1700                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1701
1702                 if (ret == 1) {
1703                         message(_("Canceled."));
1704                         return;
1705                 }
1706         }
1707
1708         message(bformat(_("Importing %1$s..."), displaypath));
1709         ErrorList errorList;
1710         if (import(this, fullname, format, errorList))
1711                 message(_("imported."));
1712         else
1713                 message(_("file not imported!"));
1714
1715         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1716 }
1717
1718
1719 void GuiView::newDocument(string const & filename, bool from_template)
1720 {
1721         FileName initpath(lyxrc.document_path);
1722         if (documentBufferView()) {
1723                 FileName const trypath(documentBufferView()->buffer().filePath());
1724                 // If directory is writeable, use this as default.
1725                 if (trypath.isDirWritable())
1726                         initpath = trypath;
1727         }
1728
1729         string templatefile;
1730         if (from_template) {
1731                 templatefile = selectTemplateFile().absFilename();
1732                 if (templatefile.empty())
1733                         return;
1734         }
1735         
1736         Buffer * b;
1737         if (filename.empty())
1738                 b = newUnnamedFile(templatefile, initpath);
1739         else
1740                 b = newFile(filename, templatefile, true);
1741
1742         if (b)
1743                 setBuffer(b);
1744
1745         // If no new document could be created, it is unsure 
1746         // whether there is a valid BufferView.
1747         if (currentBufferView())
1748                 // Ensure the cursor is correctly positioned on screen.
1749                 currentBufferView()->showCursor();
1750 }
1751
1752
1753 void GuiView::insertLyXFile(docstring const & fname)
1754 {
1755         BufferView * bv = documentBufferView();
1756         if (!bv)
1757                 return;
1758
1759         // FIXME UNICODE
1760         FileName filename(to_utf8(fname));
1761         
1762         if (!filename.empty()) {
1763                 bv->insertLyXFile(filename);
1764                 return;
1765         }
1766
1767         // Launch a file browser
1768         // FIXME UNICODE
1769         string initpath = lyxrc.document_path;
1770         string const trypath = bv->buffer().filePath();
1771         // If directory is writeable, use this as default.
1772         if (FileName(trypath).isDirWritable())
1773                 initpath = trypath;
1774
1775         // FIXME UNICODE
1776         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1777         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1778         dlg.setButton2(qt_("Examples|#E#e"),
1779                 toqstr(addPath(package().system_support().absFilename(),
1780                 "examples")));
1781
1782         FileDialog::Result result = dlg.open(toqstr(initpath),
1783                              QStringList(qt_("LyX Documents (*.lyx)")));
1784
1785         if (result.first == FileDialog::Later)
1786                 return;
1787
1788         // FIXME UNICODE
1789         filename.set(fromqstr(result.second));
1790
1791         // check selected filename
1792         if (filename.empty()) {
1793                 // emit message signal.
1794                 message(_("Canceled."));
1795                 return;
1796         }
1797
1798         bv->insertLyXFile(filename);
1799 }
1800
1801
1802 void GuiView::insertPlaintextFile(docstring const & fname,
1803         bool asParagraph)
1804 {
1805         BufferView * bv = documentBufferView();
1806         if (!bv)
1807                 return;
1808
1809         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1810                 message(_("Absolute filename expected."));
1811                 return;
1812         }
1813
1814         // FIXME UNICODE
1815         FileName filename(to_utf8(fname));
1816         
1817         if (!filename.empty()) {
1818                 bv->insertPlaintextFile(filename, asParagraph);
1819                 return;
1820         }
1821
1822         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1823                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1824
1825         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1826                 QStringList(qt_("All Files (*)")));
1827
1828         if (result.first == FileDialog::Later)
1829                 return;
1830
1831         // FIXME UNICODE
1832         filename.set(fromqstr(result.second));
1833
1834         // check selected filename
1835         if (filename.empty()) {
1836                 // emit message signal.
1837                 message(_("Canceled."));
1838                 return;
1839         }
1840
1841         bv->insertPlaintextFile(filename, asParagraph);
1842 }
1843
1844
1845 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1846 {
1847         FileName fname = b.fileName();
1848         FileName const oldname = fname;
1849
1850         if (!newname.empty()) {
1851                 // FIXME UNICODE
1852                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1853         } else {
1854                 // Switch to this Buffer.
1855                 setBuffer(&b);
1856
1857                 // No argument? Ask user through dialog.
1858                 // FIXME UNICODE
1859                 FileDialog dlg(qt_("Choose a filename to save document as"),
1860                                    LFUN_BUFFER_WRITE_AS);
1861                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1862                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1863
1864                 if (!isLyXFilename(fname.absFilename()))
1865                         fname.changeExtension(".lyx");
1866
1867                 FileDialog::Result result =
1868                         dlg.save(toqstr(fname.onlyPath().absFilename()),
1869                                QStringList(qt_("LyX Documents (*.lyx)")),
1870                                      toqstr(fname.onlyFileName()));
1871
1872                 if (result.first == FileDialog::Later)
1873                         return false;
1874
1875                 fname.set(fromqstr(result.second));
1876
1877                 if (fname.empty())
1878                         return false;
1879
1880                 if (!isLyXFilename(fname.absFilename()))
1881                         fname.changeExtension(".lyx");
1882         }
1883
1884         if (FileName(fname).exists()) {
1885                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1886                 docstring text = bformat(_("The document %1$s already "
1887                                            "exists.\n\nDo you want to "
1888                                            "overwrite that document?"), 
1889                                          file);
1890                 int const ret = Alert::prompt(_("Overwrite document?"),
1891                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1892                 switch (ret) {
1893                 case 0: break;
1894                 case 1: return renameBuffer(b, docstring());
1895                 case 2: return false;
1896                 }
1897         }
1898
1899         FileName oldauto = b.getAutosaveFilename();
1900
1901         // Ok, change the name of the buffer
1902         b.setFileName(fname.absFilename());
1903         b.markDirty();
1904         bool unnamed = b.isUnnamed();
1905         b.setUnnamed(false);
1906         b.saveCheckSum(fname);
1907
1908         // bring the autosave file with us, just in case.
1909         b.moveAutosaveFile(oldauto);
1910         
1911         if (!saveBuffer(b)) {
1912                 oldauto = b.getAutosaveFilename();
1913                 b.setFileName(oldname.absFilename());
1914                 b.setUnnamed(unnamed);
1915                 b.saveCheckSum(oldname);
1916                 b.moveAutosaveFile(oldauto);
1917                 return false;
1918         }
1919
1920         return true;
1921 }
1922
1923
1924 bool GuiView::saveBuffer(Buffer & b)
1925 {
1926         if (workArea(b) && workArea(b)->inDialogMode())
1927                 return true;
1928
1929         if (b.isUnnamed())
1930                 return renameBuffer(b, docstring());
1931
1932         if (b.save()) {
1933                 theSession().lastFiles().add(b.fileName());
1934                 return true;
1935         }
1936
1937         // Switch to this Buffer.
1938         setBuffer(&b);
1939
1940         // FIXME: we don't tell the user *WHY* the save failed !!
1941         docstring const file = makeDisplayPath(b.absFileName(), 30);
1942         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1943                                    "Do you want to rename the document and "
1944                                    "try again?"), file);
1945         int const ret = Alert::prompt(_("Rename and save?"),
1946                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1947         switch (ret) {
1948         case 0:
1949                 if (!renameBuffer(b, docstring()))
1950                         return false;
1951                 break;
1952         case 1:
1953                 break;
1954         case 2:
1955                 return false;
1956         }
1957
1958         return saveBuffer(b);
1959 }
1960
1961
1962 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1963 {
1964         return closeWorkArea(wa, false);
1965 }
1966
1967
1968 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1969 {
1970         Buffer & buf = wa->bufferView().buffer();
1971         return closeWorkArea(wa, !buf.parent());
1972 }
1973
1974
1975 bool GuiView::closeBuffer()
1976 {
1977         GuiWorkArea * wa = currentMainWorkArea();
1978         Buffer & buf = wa->bufferView().buffer();
1979         return wa && closeWorkArea(wa, !buf.parent());
1980 }
1981
1982
1983 void GuiView::writeSession() const {
1984         GuiWorkArea const * active_wa = currentMainWorkArea();
1985         for (int i = 0; i < d.splitter_->count(); ++i) {
1986                 TabWorkArea * twa = d.tabWorkArea(i);
1987                 for (int j = 0; j < twa->count(); ++j) {
1988                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1989                         Buffer & buf = wa->bufferView().buffer();
1990                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1991                 }
1992         }
1993 }
1994
1995
1996 bool GuiView::closeBufferAll()
1997 {
1998         // Close the workareas in all other views
1999         QList<int> const ids = guiApp->viewIds();
2000         for (int i = 0; i != ids.size(); ++i) {
2001                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2002                         return false;
2003         }
2004
2005         // Close our own workareas
2006         if (!closeWorkAreaAll())
2007                 return false;
2008
2009         // Now close the hidden buffers. We prevent hidden buffers from being
2010         // dirty, so we can just close them.
2011         theBufferList().closeAll();
2012         return true;
2013 }
2014
2015
2016 bool GuiView::closeWorkAreaAll()
2017 {
2018         setCurrentWorkArea(currentMainWorkArea());
2019
2020         // We might be in a situation that there is still a tabWorkArea, but
2021         // there are no tabs anymore. This can happen when we get here after a 
2022         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2023         // many TabWorkArea's have no documents anymore.
2024         int empty_twa = 0;
2025
2026         // We have to call count() each time, because it can happen that
2027         // more than one splitter will disappear in one iteration (bug 5998).
2028         for (; d.splitter_->count() > empty_twa; ) {
2029                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2030
2031                 if (twa->count() == 0)
2032                         ++empty_twa;
2033                 else {
2034                         setCurrentWorkArea(twa->currentWorkArea());
2035                         if (!closeTabWorkArea(twa))
2036                                 return false;
2037                 }
2038         }
2039         return true;
2040 }
2041
2042
2043 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2044 {
2045         Buffer & buf = wa->bufferView().buffer();
2046
2047         // If we are in a close_event all children will be closed in some time,
2048         // so no need to do it here. This will ensure that the children end up
2049         // in the session file in the correct order. If we close the master
2050         // buffer, we can close or release the child buffers here too.
2051         if (close_buffer && !closing_) {
2052                 vector<Buffer *> clist = buf.getChildren();
2053                 for (vector<Buffer *>::const_iterator it = clist.begin();
2054                          it != clist.end(); ++it) {
2055                         // If a child is dirty, do not close
2056                         // without user intervention
2057                         //FIXME: should we look in other tabworkareas?
2058                         Buffer * child_buf = *it;
2059                         GuiWorkArea * child_wa = workArea(*child_buf);
2060                         if (child_wa) {
2061                                 if (!closeWorkArea(child_wa, true))
2062                                         return false;
2063                         } else
2064                                 theBufferList().releaseChild(&buf, child_buf);
2065                 }
2066         }
2067         // goto bookmark to update bookmark pit.
2068         //FIXME: we should update only the bookmarks related to this buffer!
2069         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2070         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2071                 theLyXFunc().gotoBookmark(i+1, false, false);
2072
2073         // if we are only hiding the buffer and there are multiple views
2074         // of the buffer, then we do not need to ensure a clean buffer.
2075         bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2076
2077         if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2078                 // save in sessions if requested
2079                 // do not save childs if their master
2080                 // is opened as well
2081                 if (!close_buffer)
2082                         removeWorkArea(wa);
2083                 else
2084                         theBufferList().release(&buf);
2085                 return true;
2086         }
2087         return false;
2088 }
2089
2090
2091 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2092 {
2093         while (twa == d.currentTabWorkArea()) {
2094                 twa->setCurrentIndex(twa->count()-1);
2095
2096                 GuiWorkArea * wa = twa->currentWorkArea();
2097                 Buffer & b = wa->bufferView().buffer();
2098
2099                 // We only want to close the buffer if the same buffer is not visible
2100                 // in another view, and if this is not a child and if we are closing
2101                 // a view (not a tabgroup).
2102                 bool const close_buffer = 
2103                         !inMultiViews(wa) && !b.parent() && closing_;
2104
2105                 if (!closeWorkArea(wa, close_buffer))
2106                         return false;
2107         }
2108         return true;
2109 }
2110
2111
2112 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2113 {
2114         if (buf.isClean() || buf.paragraphs().empty())
2115                 return true;
2116
2117         // Switch to this Buffer.
2118         setBuffer(&buf);
2119
2120         docstring file;
2121         // FIXME: Unicode?
2122         if (buf.isUnnamed())
2123                 file = from_utf8(buf.fileName().onlyFileName());
2124         else
2125                 file = buf.fileName().displayName(30);
2126
2127         // Bring this window to top before asking questions.
2128         raise();
2129         activateWindow();
2130
2131         int ret;
2132         if (hiding && buf.isUnnamed()) {
2133                 docstring const text = bformat(_("The document %1$s has not been "
2134                                              "saved yet.\n\nDo you want to save "
2135                                              "the document?"), file);
2136                 ret = Alert::prompt(_("Save new document?"), 
2137                         text, 0, 1, _("&Save"), _("&Cancel"));
2138                 if (ret == 1)
2139                         ++ret;
2140         } else {
2141                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2142                         "\n\nDo you want to save the document or discard the changes?"), file);
2143                 ret = Alert::prompt(_("Save changed document?"),
2144                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2145         }
2146
2147         switch (ret) {
2148         case 0:
2149                 if (!saveBuffer(buf))
2150                         return false;
2151                 break;
2152         case 1:
2153                 // if we crash after this we could
2154                 // have no autosave file but I guess
2155                 // this is really improbable (Jug)
2156                 buf.removeAutosaveFile();
2157                 if (hiding)
2158                         // revert all changes
2159                         buf.loadLyXFile(buf.fileName());
2160                 buf.markClean();
2161                 break;
2162         case 2:
2163                 return false;
2164         }
2165         return true;
2166 }
2167
2168
2169 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2170 {
2171         Buffer & buf = wa->bufferView().buffer();
2172
2173         for (int i = 0; i != d.splitter_->count(); ++i) {
2174                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2175                 if (wa_ && wa_ != wa)
2176                         return true;
2177         }
2178         return inMultiViews(wa);
2179 }
2180
2181
2182 bool GuiView::inMultiViews(GuiWorkArea * wa)
2183 {
2184         QList<int> const ids = guiApp->viewIds();
2185         Buffer & buf = wa->bufferView().buffer();
2186
2187         int found_twa = 0;
2188         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2189                 if (id_ == ids[i])
2190                         continue;
2191                 
2192                 if (guiApp->view(ids[i]).workArea(buf))
2193                         return true;
2194         }
2195         return false;
2196 }
2197
2198
2199 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2200 {
2201         Buffer * const curbuf = documentBufferView()
2202                 ? &documentBufferView()->buffer() : 0;
2203         Buffer * nextbuf = curbuf;
2204         while (true) {
2205                 if (np == NEXTBUFFER)
2206                         nextbuf = theBufferList().next(nextbuf);
2207                 else
2208                         nextbuf = theBufferList().previous(nextbuf);
2209                 if (nextbuf == curbuf)
2210                         break;
2211                 if (nextbuf == 0) {
2212                         nextbuf = curbuf;
2213                         break;
2214                 }
2215                 if (workArea(*nextbuf))
2216                         break;
2217         }
2218         setBuffer(nextbuf);
2219 }
2220
2221
2222 /// make sure the document is saved
2223 static bool ensureBufferClean(Buffer * buffer)
2224 {
2225         LASSERT(buffer, return false);
2226         if (buffer->isClean() && !buffer->isUnnamed())
2227                 return true;
2228
2229         docstring const file = buffer->fileName().displayName(30);
2230         docstring title;
2231         docstring text;
2232         if (!buffer->isUnnamed()) {
2233                 text = bformat(_("The document %1$s has unsaved "
2234                                              "changes.\n\nDo you want to save "
2235                                              "the document?"), file);
2236                 title = _("Save changed document?");
2237                 
2238         } else {
2239                 text = bformat(_("The document %1$s has not been "
2240                                              "saved yet.\n\nDo you want to save "
2241                                              "the document?"), file);
2242                 title = _("Save new document?");
2243         }
2244         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2245
2246         if (ret == 0)
2247                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2248
2249         return buffer->isClean() && !buffer->isUnnamed();
2250 }
2251
2252
2253 void GuiView::reloadBuffer()
2254 {
2255         Buffer * buf = &documentBufferView()->buffer();
2256         FileName filename = buf->fileName();
2257         // The user has already confirmed that the changes, if any, should
2258         // be discarded. So we just release the Buffer and don't call closeBuffer();
2259         theBufferList().release(buf);
2260         buf = loadDocument(filename);
2261         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2262         docstring str;
2263         if (buf) {
2264                 buf->updateLabels();
2265                 setBuffer(buf);
2266                 buf->errors("Parse");
2267                 str = bformat(_("Document %1$s reloaded."), disp_fn);
2268         } else {
2269                 str = bformat(_("Could not reload document %1$s"), disp_fn);
2270         }
2271         message(str);
2272 }
2273
2274
2275 void GuiView::dispatchVC(FuncRequest const & cmd)
2276 {
2277         Buffer * buffer = documentBufferView()
2278                 ? &(documentBufferView()->buffer()) : 0;
2279
2280         switch (cmd.action) {
2281         case LFUN_VC_REGISTER:
2282                 if (!buffer || !ensureBufferClean(buffer))
2283                         break;
2284                 if (!buffer->lyxvc().inUse()) {
2285                         if (buffer->lyxvc().registrer())
2286                                 reloadBuffer();
2287                 }
2288                 break;
2289
2290         case LFUN_VC_CHECK_IN:
2291                 if (!buffer || !ensureBufferClean(buffer))
2292                         break;
2293                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2294                         message(from_utf8(buffer->lyxvc().checkIn()));
2295                         reloadBuffer();
2296                 }
2297                 break;
2298
2299         case LFUN_VC_CHECK_OUT:
2300                 if (!buffer || !ensureBufferClean(buffer))
2301                         break;
2302                 if (buffer->lyxvc().inUse()) {
2303                         message(from_utf8(buffer->lyxvc().checkOut()));
2304                         reloadBuffer();
2305                 }
2306                 break;
2307
2308         case LFUN_VC_LOCKING_TOGGLE:
2309                 LASSERT(buffer, return);
2310                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2311                         break;
2312                 if (buffer->lyxvc().inUse()) {
2313                         string res = buffer->lyxvc().lockingToggle();
2314                         if (res.empty()) {
2315                                 frontend::Alert::error(_("Revision control error."),
2316                                 _("Error when setting the locking property."));
2317                         } else {
2318                                 message(from_utf8(res));
2319                                 reloadBuffer();
2320                         }
2321                 }
2322                 break;
2323
2324         case LFUN_VC_REVERT:
2325                 LASSERT(buffer, return);
2326                 buffer->lyxvc().revert();
2327                 reloadBuffer();
2328                 break;
2329
2330         case LFUN_VC_UNDO_LAST:
2331                 LASSERT(buffer, return);
2332                 buffer->lyxvc().undoLast();
2333                 reloadBuffer();
2334                 break;
2335
2336         case LFUN_VC_COMMAND: {
2337                 string flag = cmd.getArg(0);
2338                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2339                         break;
2340                 docstring message;
2341                 if (contains(flag, 'M')) {
2342                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2343                                 break;
2344                 }
2345                 string path = cmd.getArg(1);
2346                 if (contains(path, "$$p") && buffer)
2347                         path = subst(path, "$$p", buffer->filePath());
2348                 LYXERR(Debug::LYXVC, "Directory: " << path);
2349                 FileName pp(path);
2350                 if (!pp.isReadableDirectory()) {
2351                         lyxerr << _("Directory is not accessible.") << endl;
2352                         break;
2353                 }
2354                 support::PathChanger p(pp);
2355
2356                 string command = cmd.getArg(2);
2357                 if (command.empty())
2358                         break;
2359                 if (buffer) {
2360                         command = subst(command, "$$i", buffer->absFileName());
2361                         command = subst(command, "$$p", buffer->filePath());
2362                 }
2363                 command = subst(command, "$$m", to_utf8(message));
2364                 LYXERR(Debug::LYXVC, "Command: " << command);
2365                 Systemcall one;
2366                 one.startscript(Systemcall::Wait, command);
2367
2368                 if (!buffer)
2369                         break;
2370                 if (contains(flag, 'I'))
2371                         buffer->markDirty();
2372                 if (contains(flag, 'R'))
2373                         reloadBuffer();
2374
2375                 break;
2376                 }
2377         default:
2378                 break;
2379         }
2380 }
2381
2382
2383 void GuiView::openChildDocument(string const & fname)
2384 {
2385         LASSERT(documentBufferView(), return);
2386         Buffer & buffer = documentBufferView()->buffer();
2387         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2388         documentBufferView()->saveBookmark(false);
2389         Buffer * child = 0;
2390         bool parsed = false;
2391         if (theBufferList().exists(filename)) {
2392                 child = theBufferList().getBuffer(filename);
2393         } else {
2394                 message(bformat(_("Opening child document %1$s..."),
2395                 makeDisplayPath(filename.absFilename())));
2396                 child = loadDocument(filename, false);
2397                 parsed = true;
2398         }
2399         if (!child)
2400                 return;
2401
2402         // Set the parent name of the child document.
2403         // This makes insertion of citations and references in the child work,
2404         // when the target is in the parent or another child document.
2405         child->setParent(&buffer);
2406         child->masterBuffer()->updateLabels();
2407         setBuffer(child);
2408         if (parsed)
2409                 child->errors("Parse");
2410 }
2411
2412
2413 bool GuiView::dispatch(FuncRequest const & cmd)
2414 {
2415         BufferView * bv = currentBufferView();
2416         // By default we won't need any update.
2417         if (bv)
2418                 bv->cursor().updateFlags(Update::None);
2419
2420         Buffer * doc_buffer = documentBufferView()
2421                 ? &(documentBufferView()->buffer()) : 0;
2422
2423         bool dispatched = true;
2424
2425         if (cmd.origin == FuncRequest::TOC) {
2426                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2427                 toc->doDispatch(bv->cursor(), cmd);
2428                 return true;
2429         }
2430
2431         switch(cmd.action) {
2432                 case LFUN_BUFFER_CHILD_OPEN:
2433                         openChildDocument(to_utf8(cmd.argument()));
2434                         break;
2435
2436                 case LFUN_BUFFER_IMPORT:
2437                         importDocument(to_utf8(cmd.argument()));
2438                         break;
2439
2440                 case LFUN_BUFFER_SWITCH:
2441                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2442                                 Buffer * buffer = 
2443                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2444                                 if (buffer)
2445                                         setBuffer(buffer);
2446                                 else
2447                                         bv->cursor().message(_("Document not loaded"));
2448                         }
2449                         break;
2450
2451                 case LFUN_BUFFER_NEXT:
2452                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2453                         break;
2454
2455                 case LFUN_BUFFER_PREVIOUS:
2456                         gotoNextOrPreviousBuffer(PREVBUFFER);
2457                         break;
2458
2459                 case LFUN_COMMAND_EXECUTE: {
2460                         bool const show_it = cmd.argument() != "off";
2461                         // FIXME: this is a hack, "minibuffer" should not be
2462                         // hardcoded.
2463                         if (GuiToolbar * t = toolbar("minibuffer")) {
2464                                 t->setVisible(show_it);
2465                                 if (show_it && t->commandBuffer())
2466                                         t->commandBuffer()->setFocus();
2467                         }
2468                         break;
2469                 }
2470                 case LFUN_DROP_LAYOUTS_CHOICE:
2471                         d.layout_->showPopup();
2472                         break;
2473
2474                 case LFUN_MENU_OPEN:
2475                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2476                                 menu->exec(QCursor::pos());
2477                         break;
2478
2479                 case LFUN_FILE_INSERT:
2480                         insertLyXFile(cmd.argument());
2481                         break;
2482                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2483                         insertPlaintextFile(cmd.argument(), true);
2484                         break;
2485
2486                 case LFUN_FILE_INSERT_PLAINTEXT:
2487                         insertPlaintextFile(cmd.argument(), false);
2488                         break;
2489
2490                 case LFUN_BUFFER_RELOAD: {
2491                         LASSERT(doc_buffer, break);
2492                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2493                         docstring text = bformat(_("Any changes will be lost. Are you sure "
2494                                                              "you want to revert to the saved version of the document %1$s?"), file);
2495                         int const ret = Alert::prompt(_("Revert to saved document?"),
2496                                 text, 1, 1, _("&Revert"), _("&Cancel"));
2497
2498                         if (ret == 0)
2499                                 reloadBuffer();
2500                         break;
2501                 }
2502
2503                 case LFUN_BUFFER_WRITE:
2504                         LASSERT(doc_buffer, break);
2505                         saveBuffer(*doc_buffer);
2506                         break;
2507
2508                 case LFUN_BUFFER_WRITE_AS:
2509                         LASSERT(doc_buffer, break);
2510                         renameBuffer(*doc_buffer, cmd.argument());
2511                         break;
2512
2513                 case LFUN_BUFFER_WRITE_ALL: {
2514                         Buffer * first = theBufferList().first();
2515                         if (!first)
2516                                 break;
2517                         message(_("Saving all documents..."));
2518                         // We cannot use a for loop as the buffer list cycles.
2519                         Buffer * b = first;
2520                         do {
2521                                 if (!b->isClean()) {
2522                                         saveBuffer(*b);
2523                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2524                                 }
2525                                 b = theBufferList().next(b);
2526                         } while (b != first); 
2527                         message(_("All documents saved."));
2528                         break;
2529                 }
2530
2531                 case LFUN_BUFFER_CLOSE:
2532                         closeBuffer();
2533                         break;
2534
2535                 case LFUN_BUFFER_CLOSE_ALL:
2536                         closeBufferAll();
2537                         break;
2538
2539                 case LFUN_TOOLBAR_TOGGLE: {
2540                         string const name = cmd.getArg(0);
2541                         if (GuiToolbar * t = toolbar(name))
2542                                 t->toggle();
2543                         break;
2544                 }
2545
2546                 case LFUN_DIALOG_UPDATE: {
2547                         string const name = to_utf8(cmd.argument());
2548                         // Can only update a dialog connected to an existing inset
2549                         Inset * inset = getOpenInset(name);
2550                         if (inset) {
2551                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2552                                 inset->dispatch(currentBufferView()->cursor(), fr);
2553                         } else if (name == "paragraph") {
2554                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2555                         } else if (name == "prefs" || name == "document") {
2556                                 updateDialog(name, string());
2557                         }
2558                         break;
2559                 }
2560
2561                 case LFUN_DIALOG_TOGGLE: {
2562                         if (isDialogVisible(cmd.getArg(0)))
2563                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2564                         else
2565                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2566                         break;
2567                 }
2568
2569                 case LFUN_DIALOG_DISCONNECT_INSET:
2570                         disconnectDialog(to_utf8(cmd.argument()));
2571                         break;
2572
2573                 case LFUN_DIALOG_HIDE: {
2574                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2575                         break;
2576                 }
2577
2578                 case LFUN_DIALOG_SHOW: {
2579                         string const name = cmd.getArg(0);
2580                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2581
2582                         if (name == "character") {
2583                                 data = freefont2string();
2584                                 if (!data.empty())
2585                                         showDialog("character", data);
2586                         } else if (name == "latexlog") {
2587                                 Buffer::LogType type; 
2588                                 string const logfile = doc_buffer->logName(&type);
2589                                 switch (type) {
2590                                 case Buffer::latexlog:
2591                                         data = "latex ";
2592                                         break;
2593                                 case Buffer::buildlog:
2594                                         data = "literate ";
2595                                         break;
2596                                 }
2597                                 data += Lexer::quoteString(logfile);
2598                                 showDialog("log", data);
2599                         } else if (name == "vclog") {
2600                                 string const data = "vc " +
2601                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2602                                 showDialog("log", data);
2603                         } else if (name == "symbols") {
2604                                 data = bv->cursor().getEncoding()->name();
2605                                 if (!data.empty())
2606                                         showDialog("symbols", data);
2607                         // bug 5274
2608                         } else if (name == "prefs" && isFullScreen()) {
2609                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2610                                 lfunUiToggle(fr);
2611                                 showDialog("prefs", data);
2612                         } else
2613                                 showDialog(name, data);
2614                         break;
2615                 }
2616
2617                 case LFUN_MESSAGE:
2618                         message(cmd.argument());
2619                         break;
2620
2621                 case LFUN_INSET_APPLY: {
2622                         string const name = cmd.getArg(0);
2623                         Inset * inset = getOpenInset(name);
2624                         if (inset) {
2625                                 // put cursor in front of inset.
2626                                 if (!currentBufferView()->setCursorFromInset(inset)) {
2627                                         LASSERT(false, break);
2628                                 }
2629                                 BufferView * bv = currentBufferView();
2630                                 // useful if we are called from a dialog.
2631                                 bv->cursor().beginUndoGroup();
2632                                 bv->cursor().recordUndo();
2633                                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2634                                 inset->dispatch(bv->cursor(), fr);
2635                                 bv->cursor().endUndoGroup();
2636                         } else {
2637                                 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2638                                 lyx::dispatch(fr);
2639                         }
2640                         break;
2641                 }
2642
2643                 case LFUN_UI_TOGGLE:
2644                         lfunUiToggle(cmd);
2645                         // Make sure the keyboard focus stays in the work area.
2646                         setFocus();
2647                         break;
2648
2649                 case LFUN_SPLIT_VIEW: {
2650                         LASSERT(doc_buffer, break);
2651                         string const orientation = cmd.getArg(0);
2652                         d.splitter_->setOrientation(orientation == "vertical"
2653                                 ? Qt::Vertical : Qt::Horizontal);
2654                         TabWorkArea * twa = addTabWorkArea();
2655                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2656                         setCurrentWorkArea(wa);
2657                         break;
2658                 }
2659                 case LFUN_CLOSE_TAB_GROUP:
2660                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2661                                 closeTabWorkArea(twa);
2662                                 d.current_work_area_ = 0;
2663                                 twa = d.currentTabWorkArea();
2664                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2665                                 if (twa) {
2666                                         // Make sure the work area is up to date.
2667                                         setCurrentWorkArea(twa->currentWorkArea());
2668                                 } else {
2669                                         setCurrentWorkArea(0);
2670                                 }
2671                         }
2672                         break;
2673                         
2674                 case LFUN_COMPLETION_INLINE:
2675                         if (d.current_work_area_)
2676                                 d.current_work_area_->completer().showInline();
2677                         break;
2678
2679                 case LFUN_COMPLETION_POPUP:
2680                         if (d.current_work_area_)
2681                                 d.current_work_area_->completer().showPopup();
2682                         break;
2683
2684
2685                 case LFUN_COMPLETION_COMPLETE:
2686                         if (d.current_work_area_)
2687                                 d.current_work_area_->completer().tab();
2688                         break;
2689
2690                 case LFUN_COMPLETION_CANCEL:
2691                         if (d.current_work_area_) {
2692                                 if (d.current_work_area_->completer().popupVisible())
2693                                         d.current_work_area_->completer().hidePopup();
2694                                 else
2695                                         d.current_work_area_->completer().hideInline();
2696                         }
2697                         break;
2698
2699                 case LFUN_COMPLETION_ACCEPT:
2700                         if (d.current_work_area_)
2701                                 d.current_work_area_->completer().activate();
2702                         break;
2703
2704                 case LFUN_BUFFER_ZOOM_IN:
2705                 case LFUN_BUFFER_ZOOM_OUT:
2706                         if (cmd.argument().empty()) {
2707                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2708                                         lyxrc.zoom += 20;
2709                                 else
2710                                         lyxrc.zoom -= 20;
2711                         } else
2712                                 lyxrc.zoom += convert<int>(cmd.argument());
2713
2714                         if (lyxrc.zoom < 10)
2715                                 lyxrc.zoom = 10;
2716                                 
2717                         // The global QPixmapCache is used in GuiPainter to cache text
2718                         // painting so we must reset it.
2719                         QPixmapCache::clear();
2720                         guiApp->fontLoader().update();
2721                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2722                         break;
2723
2724                 case LFUN_VC_REGISTER:
2725                 case LFUN_VC_CHECK_IN:
2726                 case LFUN_VC_CHECK_OUT:
2727                 case LFUN_VC_LOCKING_TOGGLE:
2728                 case LFUN_VC_REVERT:
2729                 case LFUN_VC_UNDO_LAST:
2730                 case LFUN_VC_COMMAND:
2731                         dispatchVC(cmd);
2732                         break;
2733
2734                 default:
2735                         dispatched = false;
2736                         break;
2737         }
2738
2739         // Part of automatic menu appearance feature.
2740         if (isFullScreen()) {
2741                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2742                         menuBar()->hide();
2743                 if (statusBar()->isVisible())
2744                         statusBar()->hide();
2745         }
2746
2747         return dispatched;
2748 }
2749
2750
2751 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2752 {
2753         string const arg = cmd.getArg(0);
2754         if (arg == "scrollbar") {
2755                 // hide() is of no help
2756                 if (d.current_work_area_->verticalScrollBarPolicy() ==
2757                         Qt::ScrollBarAlwaysOff)
2758
2759                         d.current_work_area_->setVerticalScrollBarPolicy(
2760                                 Qt::ScrollBarAsNeeded);
2761                 else
2762                         d.current_work_area_->setVerticalScrollBarPolicy(
2763                                 Qt::ScrollBarAlwaysOff);
2764                 return;
2765         }
2766         if (arg == "statusbar") {
2767                 statusBar()->setVisible(!statusBar()->isVisible());
2768                 return;
2769         }
2770         if (arg == "menubar") {
2771                 menuBar()->setVisible(!menuBar()->isVisible());
2772                 return;
2773         }
2774 #if QT_VERSION >= 0x040300
2775         if (arg == "frame") {
2776                 int l, t, r, b;
2777                 getContentsMargins(&l, &t, &r, &b);
2778                 //are the frames in default state?
2779                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2780                 if (l == 0) {
2781                         setContentsMargins(-2, -2, -2, -2);
2782                 } else {
2783                         setContentsMargins(0, 0, 0, 0);
2784                 }
2785                 return;
2786         }
2787 #endif
2788         if (arg == "fullscreen") {
2789                 toggleFullScreen();
2790                 return;
2791         }
2792
2793         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2794 }
2795
2796
2797 void GuiView::toggleFullScreen()
2798 {
2799         if (isFullScreen()) {
2800                 for (int i = 0; i != d.splitter_->count(); ++i)
2801                         d.tabWorkArea(i)->setFullScreen(false);
2802 #if QT_VERSION >= 0x040300
2803                 setContentsMargins(0, 0, 0, 0);
2804 #endif
2805                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2806                 restoreLayout();
2807                 menuBar()->show();
2808                 statusBar()->show();
2809         } else {
2810                 // bug 5274
2811                 hideDialogs("prefs", 0);
2812                 for (int i = 0; i != d.splitter_->count(); ++i)
2813                         d.tabWorkArea(i)->setFullScreen(true);
2814 #if QT_VERSION >= 0x040300
2815                 setContentsMargins(-2, -2, -2, -2);
2816 #endif
2817                 saveLayout();
2818                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2819                 statusBar()->hide();
2820                 if (lyxrc.full_screen_menubar)
2821                         menuBar()->hide();
2822                 if (lyxrc.full_screen_toolbars) {
2823                         ToolbarMap::iterator end = d.toolbars_.end();
2824                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2825                                 it->second->hide();
2826                 }
2827         }
2828
2829         // give dialogs like the TOC a chance to adapt
2830         updateDialogs();
2831 }
2832
2833
2834 Buffer const * GuiView::updateInset(Inset const * inset)
2835 {
2836         if (!d.current_work_area_)
2837                 return 0;
2838
2839         if (inset)
2840                 d.current_work_area_->scheduleRedraw();
2841
2842         return &d.current_work_area_->bufferView().buffer();
2843 }
2844
2845
2846 void GuiView::restartCursor()
2847 {
2848         /* When we move around, or type, it's nice to be able to see
2849          * the cursor immediately after the keypress.
2850          */
2851         if (d.current_work_area_)
2852                 d.current_work_area_->startBlinkingCursor();
2853
2854         // Take this occasion to update the other GUI elements.
2855         updateDialogs();
2856         updateStatusBar();
2857 }
2858
2859
2860 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2861 {
2862         if (d.current_work_area_)
2863                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2864 }
2865
2866 namespace {
2867
2868 // This list should be kept in sync with the list of insets in
2869 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
2870 // dialog should have the same name as the inset.
2871 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2872 // docs in LyXAction.cpp.
2873
2874 char const * const dialognames[] = {
2875 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2876 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2877 "findreplaceadv", "float", "graphics", "href", "include", "index",
2878 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2879 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2880 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2881 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2882 "toc", "view-source", "vspace", "wrap" };
2883
2884 char const * const * const end_dialognames =
2885         dialognames + (sizeof(dialognames) / sizeof(char *));
2886
2887 class cmpCStr {
2888 public:
2889         cmpCStr(char const * name) : name_(name) {}
2890         bool operator()(char const * other) {
2891                 return strcmp(other, name_) == 0;
2892         }
2893 private:
2894         char const * name_;
2895 };
2896
2897
2898 bool isValidName(string const & name)
2899 {
2900         return find_if(dialognames, end_dialognames,
2901                             cmpCStr(name.c_str())) != end_dialognames;
2902 }
2903
2904 } // namespace anon
2905
2906
2907 void GuiView::resetDialogs()
2908 {
2909         // Make sure that no LFUN uses any LyXView.
2910         guiApp->setCurrentView(0);
2911         saveLayout();
2912         menuBar()->clear();
2913         constructToolbars();
2914         guiApp->menus().fillMenuBar(menuBar(), this, false);
2915         d.layout_->updateContents(true);
2916         // Now update controls with current buffer.
2917         guiApp->setCurrentView(this);
2918         restoreLayout();
2919         restartCursor();
2920 }
2921
2922
2923 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2924 {
2925         if (!isValidName(name))
2926                 return 0;
2927
2928         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2929
2930         if (it != d.dialogs_.end()) {
2931                 if (hide_it)
2932                         it->second->hideView();
2933                 return it->second.get();
2934         }
2935
2936         Dialog * dialog = build(name);
2937         d.dialogs_[name].reset(dialog);
2938         if (lyxrc.allow_geometry_session)
2939                 dialog->restoreSession();
2940         if (hide_it)
2941                 dialog->hideView();
2942         return dialog;
2943 }
2944
2945
2946 void GuiView::showDialog(string const & name, string const & data,
2947         Inset * inset)
2948 {
2949         if (d.in_show_)
2950                 return;
2951
2952         d.in_show_ = true;
2953         try {
2954                 Dialog * dialog = findOrBuild(name, false);
2955                 if (dialog) {
2956                         dialog->showData(data);
2957                         if (inset)
2958                                 d.open_insets_[name] = inset;
2959                 }
2960         }
2961         catch (ExceptionMessage const & ex) {
2962                 d.in_show_ = false;
2963                 throw ex;
2964         }
2965         d.in_show_ = false;
2966 }
2967
2968
2969 bool GuiView::isDialogVisible(string const & name) const
2970 {
2971         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2972         if (it == d.dialogs_.end())
2973                 return false;
2974         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2975 }
2976
2977
2978 void GuiView::hideDialog(string const & name, Inset * inset)
2979 {
2980         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2981         if (it == d.dialogs_.end())
2982                 return;
2983
2984         if (inset && inset != getOpenInset(name))
2985                 return;
2986
2987         Dialog * const dialog = it->second.get();
2988         if (dialog->isVisibleView())
2989                 dialog->hideView();
2990         d.open_insets_[name] = 0;
2991 }
2992
2993
2994 void GuiView::disconnectDialog(string const & name)
2995 {
2996         if (!isValidName(name))
2997                 return;
2998
2999         if (d.open_insets_.find(name) != d.open_insets_.end())
3000                 d.open_insets_[name] = 0;
3001 }
3002
3003
3004 Inset * GuiView::getOpenInset(string const & name) const
3005 {
3006         if (!isValidName(name))
3007                 return 0;
3008
3009         map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
3010         return it == d.open_insets_.end() ? 0 : it->second;
3011 }
3012
3013
3014 void GuiView::hideAll() const
3015 {
3016         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3017         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3018
3019         for(; it != end; ++it)
3020                 it->second->hideView();
3021 }
3022
3023
3024 void GuiView::updateDialogs()
3025 {
3026         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3027         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3028
3029         for(; it != end; ++it) {
3030                 Dialog * dialog = it->second.get();
3031                 if (dialog && dialog->isVisibleView())
3032                         dialog->checkStatus();
3033         }
3034         updateToolbars();
3035         updateLayoutList();
3036 }
3037
3038
3039 // will be replaced by a proper factory...
3040 Dialog * createGuiAbout(GuiView & lv);
3041 Dialog * createGuiBibitem(GuiView & lv);
3042 Dialog * createGuiBibtex(GuiView & lv);
3043 Dialog * createGuiBox(GuiView & lv);
3044 Dialog * createGuiBranch(GuiView & lv);
3045 Dialog * createGuiChanges(GuiView & lv);
3046 Dialog * createGuiCharacter(GuiView & lv);
3047 Dialog * createGuiCitation(GuiView & lv);
3048 Dialog * createGuiDelimiter(GuiView & lv);
3049 Dialog * createGuiDocument(GuiView & lv);
3050 Dialog * createGuiErrorList(GuiView & lv);
3051 Dialog * createGuiERT(GuiView & lv);
3052 Dialog * createGuiExternal(GuiView & lv);
3053 Dialog * createGuiFloat(GuiView & lv);
3054 Dialog * createGuiGraphics(GuiView & lv);
3055 Dialog * createGuiInclude(GuiView & lv);
3056 Dialog * createGuiIndex(GuiView & lv);
3057 Dialog * createGuiInfo(GuiView & lv);
3058 Dialog * createGuiLabel(GuiView & lv);
3059 Dialog * createGuiListings(GuiView & lv);
3060 Dialog * createGuiLog(GuiView & lv);
3061 Dialog * createGuiMathHSpace(GuiView & lv);
3062 Dialog * createGuiMathMatrix(GuiView & lv);
3063 Dialog * createGuiNomenclature(GuiView & lv);
3064 Dialog * createGuiNote(GuiView & lv);
3065 Dialog * createGuiParagraph(GuiView & lv);
3066 Dialog * createGuiPhantom(GuiView & lv);
3067 Dialog * createGuiPreferences(GuiView & lv);
3068 Dialog * createGuiPrint(GuiView & lv);
3069 Dialog * createGuiPrintindex(GuiView & lv);
3070 Dialog * createGuiPrintNomencl(GuiView & lv);
3071 Dialog * createGuiRef(GuiView & lv);
3072 Dialog * createGuiSearch(GuiView & lv);
3073 Dialog * createGuiSearchAdv(GuiView & lv);
3074 Dialog * createGuiSendTo(GuiView & lv);
3075 Dialog * createGuiShowFile(GuiView & lv);
3076 Dialog * createGuiSpellchecker(GuiView & lv);
3077 Dialog * createGuiSymbols(GuiView & lv);
3078 Dialog * createGuiTabularCreate(GuiView & lv);
3079 Dialog * createGuiTabular(GuiView & lv);
3080 Dialog * createGuiTexInfo(GuiView & lv);
3081 Dialog * createGuiTextHSpace(GuiView & lv);
3082 Dialog * createGuiToc(GuiView & lv);
3083 Dialog * createGuiThesaurus(GuiView & lv);
3084 Dialog * createGuiHyperlink(GuiView & lv);
3085 Dialog * createGuiVSpace(GuiView & lv);
3086 Dialog * createGuiViewSource(GuiView & lv);
3087 Dialog * createGuiWrap(GuiView & lv);
3088
3089
3090 Dialog * GuiView::build(string const & name)
3091 {
3092         LASSERT(isValidName(name), return 0);
3093
3094         if (name == "aboutlyx")
3095                 return createGuiAbout(*this);
3096         if (name == "bibitem")
3097                 return createGuiBibitem(*this);
3098         if (name == "bibtex")
3099                 return createGuiBibtex(*this);
3100         if (name == "box")
3101                 return createGuiBox(*this);
3102         if (name == "branch")
3103                 return createGuiBranch(*this);
3104         if (name == "changes")
3105                 return createGuiChanges(*this);
3106         if (name == "character")
3107                 return createGuiCharacter(*this);
3108         if (name == "citation")
3109                 return createGuiCitation(*this);
3110         if (name == "document")
3111                 return createGuiDocument(*this);
3112         if (name == "errorlist")
3113                 return createGuiErrorList(*this);
3114         if (name == "ert")
3115                 return createGuiERT(*this);
3116         if (name == "external")
3117                 return createGuiExternal(*this);
3118         if (name == "file")
3119                 return createGuiShowFile(*this);
3120         if (name == "findreplace")
3121                 return createGuiSearch(*this);
3122         if (name == "findreplaceadv")
3123                 return createGuiSearchAdv(*this);
3124         if (name == "float")
3125                 return createGuiFloat(*this);
3126         if (name == "graphics")
3127                 return createGuiGraphics(*this);
3128         if (name == "href")
3129                 return createGuiHyperlink(*this);
3130         if (name == "include")
3131                 return createGuiInclude(*this);
3132         if (name == "index")
3133                 return createGuiIndex(*this);
3134         if (name == "index_print")
3135                 return createGuiPrintindex(*this);
3136         if (name == "info")
3137                 return createGuiInfo(*this);
3138         if (name == "label")
3139                 return createGuiLabel(*this);
3140         if (name == "listings")
3141                 return createGuiListings(*this);
3142         if (name == "log")
3143                 return createGuiLog(*this);
3144         if (name == "mathdelimiter")
3145                 return createGuiDelimiter(*this);
3146         if (name == "mathspace")
3147                 return createGuiMathHSpace(*this);
3148         if (name == "mathmatrix")
3149                 return createGuiMathMatrix(*this);
3150         if (name == "nomenclature")
3151                 return createGuiNomenclature(*this);
3152         if (name == "nomencl_print")
3153                 return createGuiPrintNomencl(*this);
3154         if (name == "note")
3155                 return createGuiNote(*this);
3156         if (name == "paragraph")
3157                 return createGuiParagraph(*this);
3158         if (name == "phantom")
3159                 return createGuiPhantom(*this);
3160         if (name == "prefs")
3161                 return createGuiPreferences(*this);
3162         if (name == "print")
3163                 return createGuiPrint(*this);
3164         if (name == "ref")
3165                 return createGuiRef(*this);
3166         if (name == "sendto")
3167                 return createGuiSendTo(*this);
3168         if (name == "space")
3169                 return createGuiTextHSpace(*this);
3170         if (name == "spellchecker")
3171                 return createGuiSpellchecker(*this);
3172         if (name == "symbols")
3173                 return createGuiSymbols(*this);
3174         if (name == "tabular")
3175                 return createGuiTabular(*this);
3176         if (name == "tabularcreate")
3177                 return createGuiTabularCreate(*this);
3178         if (name == "texinfo")
3179                 return createGuiTexInfo(*this);
3180         if (name == "thesaurus")
3181                 return createGuiThesaurus(*this);
3182         if (name == "toc")
3183                 return createGuiToc(*this);
3184         if (name == "view-source")
3185                 return createGuiViewSource(*this);
3186         if (name == "vspace")
3187                 return createGuiVSpace(*this);
3188         if (name == "wrap")
3189                 return createGuiWrap(*this);
3190
3191         return 0;
3192 }
3193
3194
3195 } // namespace frontend
3196 } // namespace lyx
3197
3198 #include "moc_GuiView.cpp"