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