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