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