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