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