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