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