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