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