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