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