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