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