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