]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiView.cpp
re-add view for progress, cleanup follows
[features.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 #if (QT_VERSION >= 0x040400)
368         connect(&d.autosave_watcher_, SIGNAL(finished()), this,
369                 SLOT(threadFinished()));
370 #endif
371
372         connect(this, SIGNAL(triggerShowDialog(QString const &, QString const &, Inset *)),
373                 SLOT(doShowDialog(QString const &, QString const &, Inset *)));
374
375         // Forbid too small unresizable window because it can happen
376         // with some window manager under X11.
377         setMinimumSize(300, 200);
378
379         if (lyxrc.allow_geometry_session) {
380                 // Now take care of session management.
381                 if (restoreLayout())
382                         return;
383         }
384
385         // no session handling, default to a sane size.
386         setGeometry(50, 50, 690, 510);
387         initToolbars();
388
389         // clear session data if any.
390         QSettings settings;
391         settings.remove("views");
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 == "progress"
1439                                 || name == "compare";
1440                 else if (name == "print")
1441                         enable = doc_buffer->isExportable("dvi")
1442                                 && lyxrc.print_command != "none";
1443                 else if (name == "character" || name == "symbols") {
1444                         if (!buf || buf->isReadonly()
1445                                 || !currentBufferView()->cursor().inTexted())
1446                                 enable = false;
1447                         else {
1448                                 // FIXME we should consider passthru
1449                                 // paragraphs too.
1450                                 Inset const & in = currentBufferView()->cursor().inset();
1451                                 enable = !in.getLayout().isPassThru();
1452                         }
1453                 }
1454                 else if (name == "latexlog")
1455                         enable = FileName(doc_buffer->logName()).isReadableFile();
1456                 else if (name == "spellchecker")
1457                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1458                 else if (name == "vclog")
1459                         enable = doc_buffer->lyxvc().inUse();
1460                 break;
1461         }
1462
1463         case LFUN_DIALOG_UPDATE: {
1464                 string const name = cmd.getArg(0);
1465                 if (!buf)
1466                         enable = name == "prefs";
1467                 break;
1468         }
1469
1470         case LFUN_COMMAND_EXECUTE:
1471         case LFUN_MESSAGE:
1472         case LFUN_MENU_OPEN:
1473                 // Nothing to check.
1474                 break;
1475
1476         case LFUN_COMPLETION_INLINE:
1477                 if (!d.current_work_area_
1478                     || !d.current_work_area_->completer().inlinePossible(
1479                         currentBufferView()->cursor()))
1480                     enable = false;
1481                 break;
1482
1483         case LFUN_COMPLETION_POPUP:
1484                 if (!d.current_work_area_
1485                     || !d.current_work_area_->completer().popupPossible(
1486                         currentBufferView()->cursor()))
1487                     enable = false;
1488                 break;
1489
1490         case LFUN_COMPLETION_COMPLETE:
1491                 if (!d.current_work_area_
1492                         || !d.current_work_area_->completer().inlinePossible(
1493                         currentBufferView()->cursor()))
1494                     enable = false;
1495                 break;
1496
1497         case LFUN_COMPLETION_ACCEPT:
1498                 if (!d.current_work_area_
1499                     || (!d.current_work_area_->completer().popupVisible()
1500                         && !d.current_work_area_->completer().inlineVisible()
1501                         && !d.current_work_area_->completer().completionAvailable()))
1502                         enable = false;
1503                 break;
1504
1505         case LFUN_COMPLETION_CANCEL:
1506                 if (!d.current_work_area_
1507                     || (!d.current_work_area_->completer().popupVisible()
1508                         && !d.current_work_area_->completer().inlineVisible()))
1509                         enable = false;
1510                 break;
1511
1512         case LFUN_BUFFER_ZOOM_OUT:
1513                 enable = doc_buffer && lyxrc.zoom > 10;
1514                 break;
1515
1516         case LFUN_BUFFER_ZOOM_IN:
1517                 enable = doc_buffer;
1518                 break;
1519         
1520         case LFUN_BUFFER_NEXT:
1521         case LFUN_BUFFER_PREVIOUS:
1522                 // FIXME: should we check is there is an previous or next buffer?
1523                 break;
1524         case LFUN_BUFFER_SWITCH:
1525                 // toggle on the current buffer, but do not toggle off
1526                 // the other ones (is that a good idea?)
1527                 if (doc_buffer
1528                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1529                         flag.setOnOff(true);
1530                 break;
1531
1532         case LFUN_VC_REGISTER:
1533                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1534                 break;
1535         case LFUN_VC_CHECK_IN:
1536                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1537                 break;
1538         case LFUN_VC_CHECK_OUT:
1539                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1540                 break;
1541         case LFUN_VC_LOCKING_TOGGLE:
1542                 enable = doc_buffer && !doc_buffer->isReadonly()
1543                         && doc_buffer->lyxvc().lockingToggleEnabled();
1544                 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1545                 break;
1546         case LFUN_VC_REVERT:
1547                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1548                 break;
1549         case LFUN_VC_UNDO_LAST:
1550                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1551                 break;
1552         case LFUN_VC_REPO_UPDATE:
1553                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1554                 break;
1555         case LFUN_VC_COMMAND: {
1556                 if (cmd.argument().empty())
1557                         enable = false;
1558                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1559                         enable = false;
1560                 break;
1561         }
1562
1563         case LFUN_SERVER_GOTO_FILE_ROW:
1564                 break;
1565
1566         default:
1567                 return false;
1568         }
1569
1570         if (!enable)
1571                 flag.setEnabled(false);
1572
1573         return true;
1574 }
1575
1576
1577 static FileName selectTemplateFile()
1578 {
1579         FileDialog dlg(qt_("Select template file"));
1580         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1581         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1582
1583         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1584                              QStringList(qt_("LyX Documents (*.lyx)")));
1585
1586         if (result.first == FileDialog::Later)
1587                 return FileName();
1588         if (result.second.isEmpty())
1589                 return FileName();
1590         return FileName(fromqstr(result.second));
1591 }
1592
1593
1594 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1595 {
1596         setBusy(true);
1597
1598         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1599
1600         if (!newBuffer) {
1601                 message(_("Document not loaded."));
1602                 setBusy(false);
1603                 return 0;
1604         }
1605         
1606         setBuffer(newBuffer);
1607
1608         // scroll to the position when the file was last closed
1609         if (lyxrc.use_lastfilepos) {
1610                 LastFilePosSection::FilePos filepos =
1611                         theSession().lastFilePos().load(filename);
1612                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1613         }
1614
1615         if (tolastfiles)
1616                 theSession().lastFiles().add(filename);
1617
1618         setBusy(false);
1619         return newBuffer;
1620 }
1621
1622
1623 void GuiView::openDocument(string const & fname)
1624 {
1625         string initpath = lyxrc.document_path;
1626
1627         if (documentBufferView()) {
1628                 string const trypath = documentBufferView()->buffer().filePath();
1629                 // If directory is writeable, use this as default.
1630                 if (FileName(trypath).isDirWritable())
1631                         initpath = trypath;
1632         }
1633
1634         string filename;
1635
1636         if (fname.empty()) {
1637                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1638                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1639                 dlg.setButton2(qt_("Examples|#E#e"),
1640                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1641
1642                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1643                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1644                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1645                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1646                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1647                 FileDialog::Result result =
1648                         dlg.open(toqstr(initpath), filter);
1649
1650                 if (result.first == FileDialog::Later)
1651                         return;
1652
1653                 filename = fromqstr(result.second);
1654
1655                 // check selected filename
1656                 if (filename.empty()) {
1657                         message(_("Canceled."));
1658                         return;
1659                 }
1660         } else
1661                 filename = fname;
1662
1663         // get absolute path of file and add ".lyx" to the filename if
1664         // necessary. 
1665         FileName const fullname = 
1666                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1667         if (!fullname.empty())
1668                 filename = fullname.absFilename();
1669
1670         if (!fullname.onlyPath().isDirectory()) {
1671                 Alert::warning(_("Invalid filename"),
1672                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1673                                 from_utf8(fullname.absFilename())));
1674                 return;
1675         }
1676         // if the file doesn't exist, let the user create one
1677         if (!fullname.exists()) {
1678                 // the user specifically chose this name. Believe him.
1679                 Buffer * const b = newFile(filename, string(), true);
1680                 if (b)
1681                         setBuffer(b);
1682                 return;
1683         }
1684
1685         docstring const disp_fn = makeDisplayPath(filename);
1686         message(bformat(_("Opening document %1$s..."), disp_fn));
1687
1688         docstring str2;
1689         Buffer * buf = loadDocument(fullname);
1690         if (buf) {
1691                 buf->updateLabels();
1692                 setBuffer(buf);
1693                 buf->errors("Parse");
1694                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1695                 if (buf->lyxvc().inUse())
1696                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1697                                 " " + _("Version control detected.");
1698         } else {
1699                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1700         }
1701         message(str2);
1702 }
1703
1704 // FIXME: clean that
1705 static bool import(GuiView * lv, FileName const & filename,
1706         string const & format, ErrorList & errorList)
1707 {
1708         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1709
1710         string loader_format;
1711         vector<string> loaders = theConverters().loaders();
1712         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1713                 for (vector<string>::const_iterator it = loaders.begin();
1714                      it != loaders.end(); ++it) {
1715                         if (!theConverters().isReachable(format, *it))
1716                                 continue;
1717
1718                         string const tofile =
1719                                 support::changeExtension(filename.absFilename(),
1720                                 formats.extension(*it));
1721                         if (!theConverters().convert(0, filename, FileName(tofile),
1722                                 filename, format, *it, errorList))
1723                                 return false;
1724                         loader_format = *it;
1725                         break;
1726                 }
1727                 if (loader_format.empty()) {
1728                         frontend::Alert::error(_("Couldn't import file"),
1729                                      bformat(_("No information for importing the format %1$s."),
1730                                          formats.prettyName(format)));
1731                         return false;
1732                 }
1733         } else
1734                 loader_format = format;
1735
1736         if (loader_format == "lyx") {
1737                 Buffer * buf = lv->loadDocument(lyxfile);
1738                 if (!buf)
1739                         return false;
1740                 buf->updateLabels();
1741                 lv->setBuffer(buf);
1742                 buf->errors("Parse");
1743         } else {
1744                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1745                 if (!b)
1746                         return false;
1747                 lv->setBuffer(b);
1748                 bool as_paragraphs = loader_format == "textparagraph";
1749                 string filename2 = (loader_format == format) ? filename.absFilename()
1750                         : support::changeExtension(filename.absFilename(),
1751                                           formats.extension(loader_format));
1752                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1753                         as_paragraphs);
1754                 guiApp->setCurrentView(lv);
1755                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1756         }
1757
1758         return true;
1759 }
1760
1761
1762 void GuiView::importDocument(string const & argument)
1763 {
1764         string format;
1765         string filename = split(argument, format, ' ');
1766
1767         LYXERR(Debug::INFO, format << " file: " << filename);
1768
1769         // need user interaction
1770         if (filename.empty()) {
1771                 string initpath = lyxrc.document_path;
1772                 if (documentBufferView()) {
1773                         string const trypath = documentBufferView()->buffer().filePath();
1774                         // If directory is writeable, use this as default.
1775                         if (FileName(trypath).isDirWritable())
1776                                 initpath = trypath;
1777                 }
1778
1779                 docstring const text = bformat(_("Select %1$s file to import"),
1780                         formats.prettyName(format));
1781
1782                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1783                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1784                 dlg.setButton2(qt_("Examples|#E#e"),
1785                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1786
1787                 docstring filter = formats.prettyName(format);
1788                 filter += " (*.";
1789                 // FIXME UNICODE
1790                 filter += from_utf8(formats.extension(format));
1791                 filter += ')';
1792
1793                 FileDialog::Result result =
1794                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1795
1796                 if (result.first == FileDialog::Later)
1797                         return;
1798
1799                 filename = fromqstr(result.second);
1800
1801                 // check selected filename
1802                 if (filename.empty())
1803                         message(_("Canceled."));
1804         }
1805
1806         if (filename.empty())
1807                 return;
1808
1809         // get absolute path of file
1810         FileName const fullname(support::makeAbsPath(filename));
1811
1812         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1813
1814         // Check if the document already is open
1815         Buffer * buf = theBufferList().getBuffer(lyxfile);
1816         if (buf) {
1817                 setBuffer(buf);
1818                 if (!closeBuffer()) {
1819                         message(_("Canceled."));
1820                         return;
1821                 }
1822         }
1823
1824         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1825
1826         // if the file exists already, and we didn't do
1827         // -i lyx thefile.lyx, warn
1828         if (lyxfile.exists() && fullname != lyxfile) {
1829
1830                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1831                         "Do you want to overwrite that document?"), displaypath);
1832                 int const ret = Alert::prompt(_("Overwrite document?"),
1833                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1834
1835                 if (ret == 1) {
1836                         message(_("Canceled."));
1837                         return;
1838                 }
1839         }
1840
1841         message(bformat(_("Importing %1$s..."), displaypath));
1842         ErrorList errorList;
1843         if (import(this, fullname, format, errorList))
1844                 message(_("imported."));
1845         else
1846                 message(_("file not imported!"));
1847
1848         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1849 }
1850
1851
1852 void GuiView::newDocument(string const & filename, bool from_template)
1853 {
1854         FileName initpath(lyxrc.document_path);
1855         if (documentBufferView()) {
1856                 FileName const trypath(documentBufferView()->buffer().filePath());
1857                 // If directory is writeable, use this as default.
1858                 if (trypath.isDirWritable())
1859                         initpath = trypath;
1860         }
1861
1862         string templatefile;
1863         if (from_template) {
1864                 templatefile = selectTemplateFile().absFilename();
1865                 if (templatefile.empty())
1866                         return;
1867         }
1868         
1869         Buffer * b;
1870         if (filename.empty())
1871                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
1872         else
1873                 b = newFile(filename, templatefile, true);
1874
1875         if (b)
1876                 setBuffer(b);
1877
1878         // If no new document could be created, it is unsure 
1879         // whether there is a valid BufferView.
1880         if (currentBufferView())
1881                 // Ensure the cursor is correctly positioned on screen.
1882                 currentBufferView()->showCursor();
1883 }
1884
1885
1886 void GuiView::insertLyXFile(docstring const & fname)
1887 {
1888         BufferView * bv = documentBufferView();
1889         if (!bv)
1890                 return;
1891
1892         // FIXME UNICODE
1893         FileName filename(to_utf8(fname));
1894         
1895         if (!filename.empty()) {
1896                 bv->insertLyXFile(filename);
1897                 return;
1898         }
1899
1900         // Launch a file browser
1901         // FIXME UNICODE
1902         string initpath = lyxrc.document_path;
1903         string const trypath = bv->buffer().filePath();
1904         // If directory is writeable, use this as default.
1905         if (FileName(trypath).isDirWritable())
1906                 initpath = trypath;
1907
1908         // FIXME UNICODE
1909         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1910         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1911         dlg.setButton2(qt_("Examples|#E#e"),
1912                 toqstr(addPath(package().system_support().absFilename(),
1913                 "examples")));
1914
1915         FileDialog::Result result = dlg.open(toqstr(initpath),
1916                              QStringList(qt_("LyX Documents (*.lyx)")));
1917
1918         if (result.first == FileDialog::Later)
1919                 return;
1920
1921         // FIXME UNICODE
1922         filename.set(fromqstr(result.second));
1923
1924         // check selected filename
1925         if (filename.empty()) {
1926                 // emit message signal.
1927                 message(_("Canceled."));
1928                 return;
1929         }
1930
1931         bv->insertLyXFile(filename);
1932 }
1933
1934
1935 void GuiView::insertPlaintextFile(docstring const & fname,
1936         bool asParagraph)
1937 {
1938         BufferView * bv = documentBufferView();
1939         if (!bv)
1940                 return;
1941
1942         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1943                 message(_("Absolute filename expected."));
1944                 return;
1945         }
1946
1947         // FIXME UNICODE
1948         FileName filename(to_utf8(fname));
1949         
1950         if (!filename.empty()) {
1951                 bv->insertPlaintextFile(filename, asParagraph);
1952                 return;
1953         }
1954
1955         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1956                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1957
1958         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1959                 QStringList(qt_("All Files (*)")));
1960
1961         if (result.first == FileDialog::Later)
1962                 return;
1963
1964         // FIXME UNICODE
1965         filename.set(fromqstr(result.second));
1966
1967         // check selected filename
1968         if (filename.empty()) {
1969                 // emit message signal.
1970                 message(_("Canceled."));
1971                 return;
1972         }
1973
1974         bv->insertPlaintextFile(filename, asParagraph);
1975 }
1976
1977
1978 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1979 {
1980         FileName fname = b.fileName();
1981         FileName const oldname = fname;
1982
1983         if (!newname.empty()) {
1984                 // FIXME UNICODE
1985                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1986         } else {
1987                 // Switch to this Buffer.
1988                 setBuffer(&b);
1989
1990                 // No argument? Ask user through dialog.
1991                 // FIXME UNICODE
1992                 FileDialog dlg(qt_("Choose a filename to save document as"),
1993                                    LFUN_BUFFER_WRITE_AS);
1994                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1995                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1996
1997                 if (!isLyXFilename(fname.absFilename()))
1998                         fname.changeExtension(".lyx");
1999
2000                 FileDialog::Result result =
2001                         dlg.save(toqstr(fname.onlyPath().absFilename()),
2002                                QStringList(qt_("LyX Documents (*.lyx)")),
2003                                      toqstr(fname.onlyFileName()));
2004
2005                 if (result.first == FileDialog::Later)
2006                         return false;
2007
2008                 fname.set(fromqstr(result.second));
2009
2010                 if (fname.empty())
2011                         return false;
2012
2013                 if (!isLyXFilename(fname.absFilename()))
2014                         fname.changeExtension(".lyx");
2015         }
2016
2017         if (FileName(fname).exists()) {
2018                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
2019                 docstring text = bformat(_("The document %1$s already "
2020                                            "exists.\n\nDo you want to "
2021                                            "overwrite that document?"), 
2022                                          file);
2023                 int const ret = Alert::prompt(_("Overwrite document?"),
2024                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2025                 switch (ret) {
2026                 case 0: break;
2027                 case 1: return renameBuffer(b, docstring());
2028                 case 2: return false;
2029                 }
2030         }
2031
2032         FileName oldauto = b.getAutosaveFilename();
2033
2034         // Ok, change the name of the buffer
2035         b.setFileName(fname.absFilename());
2036         b.markDirty();
2037         bool unnamed = b.isUnnamed();
2038         b.setUnnamed(false);
2039         b.saveCheckSum(fname);
2040
2041         // bring the autosave file with us, just in case.
2042         b.moveAutosaveFile(oldauto);
2043         
2044         if (!saveBuffer(b)) {
2045                 oldauto = b.getAutosaveFilename();
2046                 b.setFileName(oldname.absFilename());
2047                 b.setUnnamed(unnamed);
2048                 b.saveCheckSum(oldname);
2049                 b.moveAutosaveFile(oldauto);
2050                 return false;
2051         }
2052
2053         return true;
2054 }
2055
2056
2057 bool GuiView::saveBuffer(Buffer & b)
2058 {
2059         if (workArea(b) && workArea(b)->inDialogMode())
2060                 return true;
2061
2062         if (b.isUnnamed())
2063                 return renameBuffer(b, docstring());
2064
2065         if (b.save()) {
2066                 theSession().lastFiles().add(b.fileName());
2067                 return true;
2068         }
2069
2070         // Switch to this Buffer.
2071         setBuffer(&b);
2072
2073         // FIXME: we don't tell the user *WHY* the save failed !!
2074         docstring const file = makeDisplayPath(b.absFileName(), 30);
2075         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2076                                    "Do you want to rename the document and "
2077                                    "try again?"), file);
2078         int const ret = Alert::prompt(_("Rename and save?"),
2079                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2080         switch (ret) {
2081         case 0:
2082                 if (!renameBuffer(b, docstring()))
2083                         return false;
2084                 break;
2085         case 1:
2086                 break;
2087         case 2:
2088                 return false;
2089         }
2090
2091         return saveBuffer(b);
2092 }
2093
2094
2095 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2096 {
2097         return closeWorkArea(wa, false);
2098 }
2099
2100
2101 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2102 {
2103         Buffer & buf = wa->bufferView().buffer();
2104         return closeWorkArea(wa, !buf.parent());
2105 }
2106
2107
2108 bool GuiView::closeBuffer()
2109 {
2110         GuiWorkArea * wa = currentMainWorkArea();
2111         Buffer & buf = wa->bufferView().buffer();
2112         return wa && closeWorkArea(wa, !buf.parent());
2113 }
2114
2115
2116 void GuiView::writeSession() const {
2117         GuiWorkArea const * active_wa = currentMainWorkArea();
2118         for (int i = 0; i < d.splitter_->count(); ++i) {
2119                 TabWorkArea * twa = d.tabWorkArea(i);
2120                 for (int j = 0; j < twa->count(); ++j) {
2121                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2122                         Buffer & buf = wa->bufferView().buffer();
2123                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2124                 }
2125         }
2126 }
2127
2128
2129 bool GuiView::closeBufferAll()
2130 {
2131         // Close the workareas in all other views
2132         QList<int> const ids = guiApp->viewIds();
2133         for (int i = 0; i != ids.size(); ++i) {
2134                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2135                         return false;
2136         }
2137
2138         // Close our own workareas
2139         if (!closeWorkAreaAll())
2140                 return false;
2141
2142         // Now close the hidden buffers. We prevent hidden buffers from being
2143         // dirty, so we can just close them.
2144         theBufferList().closeAll();
2145         return true;
2146 }
2147
2148
2149 bool GuiView::closeWorkAreaAll()
2150 {
2151         setCurrentWorkArea(currentMainWorkArea());
2152
2153         // We might be in a situation that there is still a tabWorkArea, but
2154         // there are no tabs anymore. This can happen when we get here after a 
2155         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2156         // many TabWorkArea's have no documents anymore.
2157         int empty_twa = 0;
2158
2159         // We have to call count() each time, because it can happen that
2160         // more than one splitter will disappear in one iteration (bug 5998).
2161         for (; d.splitter_->count() > empty_twa; ) {
2162                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2163
2164                 if (twa->count() == 0)
2165                         ++empty_twa;
2166                 else {
2167                         setCurrentWorkArea(twa->currentWorkArea());
2168                         if (!closeTabWorkArea(twa))
2169                                 return false;
2170                 }
2171         }
2172         return true;
2173 }
2174
2175
2176 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2177 {
2178         if (!wa)
2179                 return false;
2180
2181         Buffer & buf = wa->bufferView().buffer();
2182
2183         if (close_buffer)
2184                 return closeBuffer(buf);
2185         else {
2186                 if (!inMultiTabs(wa))
2187                         if (!saveBufferIfNeeded(buf, true))
2188                                 return false;
2189                 removeWorkArea(wa);
2190                 return true;
2191         }
2192 }
2193
2194
2195 bool GuiView::closeBuffer(Buffer & buf)
2196 {
2197         // If we are in a close_event all children will be closed in some time,
2198         // so no need to do it here. This will ensure that the children end up
2199         // in the session file in the correct order. If we close the master
2200         // buffer, we can close or release the child buffers here too.
2201         if (!closing_) {
2202                 vector<Buffer *> clist = buf.getChildren(false);
2203                 for (vector<Buffer *>::const_iterator it = clist.begin();
2204                          it != clist.end(); ++it) {
2205                         // If a child is dirty, do not close
2206                         // without user intervention
2207                         //FIXME: should we look in other tabworkareas?
2208                         Buffer * child_buf = *it;
2209                         GuiWorkArea * child_wa = workArea(*child_buf);
2210                         if (child_wa) {
2211                                 if (!closeWorkArea(child_wa, true))
2212                                         return false;
2213                         } else
2214                                 theBufferList().releaseChild(&buf, child_buf);
2215                 }
2216         }
2217         // goto bookmark to update bookmark pit.
2218         //FIXME: we should update only the bookmarks related to this buffer!
2219         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2220         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2221                 theLyXFunc().gotoBookmark(i+1, false, false);
2222
2223         if (saveBufferIfNeeded(buf, false)) {
2224                 theBufferList().release(&buf);
2225                 return true;
2226         }
2227         return false;
2228 }
2229
2230
2231 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2232 {
2233         while (twa == d.currentTabWorkArea()) {
2234                 twa->setCurrentIndex(twa->count()-1);
2235
2236                 GuiWorkArea * wa = twa->currentWorkArea();
2237                 Buffer & b = wa->bufferView().buffer();
2238
2239                 // We only want to close the buffer if the same buffer is not visible
2240                 // in another view, and if this is not a child and if we are closing
2241                 // a view (not a tabgroup).
2242                 bool const close_buffer = 
2243                         !inMultiViews(wa) && !b.parent() && closing_;
2244
2245                 if (!closeWorkArea(wa, close_buffer))
2246                         return false;
2247         }
2248         return true;
2249 }
2250
2251
2252 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2253 {
2254         if (buf.isClean() || buf.paragraphs().empty())
2255                 return true;
2256
2257         // Switch to this Buffer.
2258         setBuffer(&buf);
2259
2260         docstring file;
2261         // FIXME: Unicode?
2262         if (buf.isUnnamed())
2263                 file = from_utf8(buf.fileName().onlyFileName());
2264         else
2265                 file = buf.fileName().displayName(30);
2266
2267         // Bring this window to top before asking questions.
2268         raise();
2269         activateWindow();
2270
2271         int ret;
2272         if (hiding && buf.isUnnamed()) {
2273                 docstring const text = bformat(_("The document %1$s has not been "
2274                                              "saved yet.\n\nDo you want to save "
2275                                              "the document?"), file);
2276                 ret = Alert::prompt(_("Save new document?"), 
2277                         text, 0, 1, _("&Save"), _("&Cancel"));
2278                 if (ret == 1)
2279                         ++ret;
2280         } else {
2281                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2282                         "\n\nDo you want to save the document or discard the changes?"), file);
2283                 ret = Alert::prompt(_("Save changed document?"),
2284                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2285         }
2286
2287         switch (ret) {
2288         case 0:
2289                 if (!saveBuffer(buf))
2290                         return false;
2291                 break;
2292         case 1:
2293                 // if we crash after this we could
2294                 // have no autosave file but I guess
2295                 // this is really improbable (Jug)
2296                 buf.removeAutosaveFile();
2297                 if (hiding)
2298                         // revert all changes
2299                         buf.loadLyXFile(buf.fileName());
2300                 buf.markClean();
2301                 break;
2302         case 2:
2303                 return false;
2304         }
2305         return true;
2306 }
2307
2308
2309 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2310 {
2311         Buffer & buf = wa->bufferView().buffer();
2312
2313         for (int i = 0; i != d.splitter_->count(); ++i) {
2314                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2315                 if (wa_ && wa_ != wa)
2316                         return true;
2317         }
2318         return inMultiViews(wa);
2319 }
2320
2321
2322 bool GuiView::inMultiViews(GuiWorkArea * wa)
2323 {
2324         QList<int> const ids = guiApp->viewIds();
2325         Buffer & buf = wa->bufferView().buffer();
2326
2327         int found_twa = 0;
2328         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2329                 if (id_ == ids[i])
2330                         continue;
2331                 
2332                 if (guiApp->view(ids[i]).workArea(buf))
2333                         return true;
2334         }
2335         return false;
2336 }
2337
2338
2339 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2340 {
2341         Buffer * const curbuf = documentBufferView()
2342                 ? &documentBufferView()->buffer() : 0;
2343         Buffer * nextbuf = curbuf;
2344         while (true) {
2345                 if (np == NEXTBUFFER)
2346                         nextbuf = theBufferList().next(nextbuf);
2347                 else
2348                         nextbuf = theBufferList().previous(nextbuf);
2349                 if (nextbuf == curbuf)
2350                         break;
2351                 if (nextbuf == 0) {
2352                         nextbuf = curbuf;
2353                         break;
2354                 }
2355                 if (workArea(*nextbuf))
2356                         break;
2357         }
2358         setBuffer(nextbuf);
2359 }
2360
2361
2362 /// make sure the document is saved
2363 static bool ensureBufferClean(Buffer * buffer)
2364 {
2365         LASSERT(buffer, return false);
2366         if (buffer->isClean() && !buffer->isUnnamed())
2367                 return true;
2368
2369         docstring const file = buffer->fileName().displayName(30);
2370         docstring title;
2371         docstring text;
2372         if (!buffer->isUnnamed()) {
2373                 text = bformat(_("The document %1$s has unsaved "
2374                                              "changes.\n\nDo you want to save "
2375                                              "the document?"), file);
2376                 title = _("Save changed document?");
2377                 
2378         } else {
2379                 text = bformat(_("The document %1$s has not been "
2380                                              "saved yet.\n\nDo you want to save "
2381                                              "the document?"), file);
2382                 title = _("Save new document?");
2383         }
2384         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2385
2386         if (ret == 0)
2387                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2388
2389         return buffer->isClean() && !buffer->isUnnamed();
2390 }
2391
2392
2393 void GuiView::reloadBuffer()
2394 {
2395         Buffer * buf = &documentBufferView()->buffer();
2396         reloadBuffer(buf);
2397 }
2398
2399
2400 void GuiView::reloadBuffer(Buffer * buf)
2401 {
2402         FileName filename = buf->fileName();
2403         Buffer const * master = buf->masterBuffer();
2404         bool const is_child = master != buf;
2405         // The user has already confirmed that the changes, if any, should
2406         // be discarded. So we just release the Buffer and don't call closeBuffer();
2407         theBufferList().release(buf);
2408         buf = loadDocument(filename);
2409         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2410         docstring str;
2411         if (buf) {
2412                 // re-allocate master if necessary
2413                 if (is_child && theBufferList().isLoaded(master)
2414                     && buf->masterBuffer() != master)
2415                         buf->setParent(master);
2416                 buf->updateLabels();
2417                 setBuffer(buf);
2418                 buf->errors("Parse");
2419                 str = bformat(_("Document %1$s reloaded."), disp_fn);
2420         } else {
2421                 str = bformat(_("Could not reload document %1$s"), disp_fn);
2422         }
2423         message(str);
2424 }
2425
2426
2427 void GuiView::checkExternallyModifiedBuffers()
2428 {
2429         BufferList::iterator bit = theBufferList().begin();
2430         BufferList::iterator const bend = theBufferList().end();
2431         for (; bit != bend; ++bit) {
2432                 if ((*bit)->isExternallyModified(Buffer::checksum_method)) {
2433                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2434                                         " Reload now? Any local changes will be lost."),
2435                                         from_utf8((*bit)->absFileName()));
2436                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2437                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2438                         if (!ret)
2439                                 reloadBuffer(*bit);
2440                 }
2441         }
2442 }
2443
2444
2445 void GuiView::dispatchVC(FuncRequest const & cmd)
2446 {
2447         Buffer * buffer = documentBufferView()
2448                 ? &(documentBufferView()->buffer()) : 0;
2449
2450         switch (cmd.action) {
2451         case LFUN_VC_REGISTER:
2452                 if (!buffer || !ensureBufferClean(buffer))
2453                         break;
2454                 if (!buffer->lyxvc().inUse()) {
2455                         if (buffer->lyxvc().registrer())
2456                                 reloadBuffer();
2457                 }
2458                 break;
2459
2460         case LFUN_VC_CHECK_IN:
2461                 if (!buffer || !ensureBufferClean(buffer))
2462                         break;
2463                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2464                         message(from_utf8(buffer->lyxvc().checkIn()));
2465                         reloadBuffer();
2466                 }
2467                 break;
2468
2469         case LFUN_VC_CHECK_OUT:
2470                 if (!buffer || !ensureBufferClean(buffer))
2471                         break;
2472                 if (buffer->lyxvc().inUse()) {
2473                         message(from_utf8(buffer->lyxvc().checkOut()));
2474                         reloadBuffer();
2475                 }
2476                 break;
2477
2478         case LFUN_VC_LOCKING_TOGGLE:
2479                 LASSERT(buffer, return);
2480                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2481                         break;
2482                 if (buffer->lyxvc().inUse()) {
2483                         string res = buffer->lyxvc().lockingToggle();
2484                         if (res.empty()) {
2485                                 frontend::Alert::error(_("Revision control error."),
2486                                 _("Error when setting the locking property."));
2487                         } else {
2488                                 message(from_utf8(res));
2489                                 reloadBuffer();
2490                         }
2491                 }
2492                 break;
2493
2494         case LFUN_VC_REVERT:
2495                 LASSERT(buffer, return);
2496                 buffer->lyxvc().revert();
2497                 reloadBuffer();
2498                 break;
2499
2500         case LFUN_VC_UNDO_LAST:
2501                 LASSERT(buffer, return);
2502                 buffer->lyxvc().undoLast();
2503                 reloadBuffer();
2504                 break;
2505
2506         case LFUN_VC_REPO_UPDATE:
2507                 LASSERT(buffer, return);
2508                 if (ensureBufferClean(buffer)) {
2509                         string res = buffer->lyxvc().repoUpdate();
2510                         message(from_utf8(res));
2511                         checkExternallyModifiedBuffers();
2512                 }
2513                 break;
2514
2515         case LFUN_VC_COMMAND: {
2516                 string flag = cmd.getArg(0);
2517                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2518                         break;
2519                 docstring message;
2520                 if (contains(flag, 'M')) {
2521                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2522                                 break;
2523                 }
2524                 string path = cmd.getArg(1);
2525                 if (contains(path, "$$p") && buffer)
2526                         path = subst(path, "$$p", buffer->filePath());
2527                 LYXERR(Debug::LYXVC, "Directory: " << path);
2528                 FileName pp(path);
2529                 if (!pp.isReadableDirectory()) {
2530                         lyxerr << _("Directory is not accessible.") << endl;
2531                         break;
2532                 }
2533                 support::PathChanger p(pp);
2534
2535                 string command = cmd.getArg(2);
2536                 if (command.empty())
2537                         break;
2538                 if (buffer) {
2539                         command = subst(command, "$$i", buffer->absFileName());
2540                         command = subst(command, "$$p", buffer->filePath());
2541                 }
2542                 command = subst(command, "$$m", to_utf8(message));
2543                 LYXERR(Debug::LYXVC, "Command: " << command);
2544                 Systemcall one;
2545                 one.startscript(Systemcall::Wait, command);
2546
2547                 if (!buffer)
2548                         break;
2549                 if (contains(flag, 'I'))
2550                         buffer->markDirty();
2551                 if (contains(flag, 'R'))
2552                         reloadBuffer();
2553
2554                 break;
2555                 }
2556         default:
2557                 break;
2558         }
2559 }
2560
2561
2562 void GuiView::openChildDocument(string const & fname)
2563 {
2564         LASSERT(documentBufferView(), return);
2565         Buffer & buffer = documentBufferView()->buffer();
2566         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2567         documentBufferView()->saveBookmark(false);
2568         Buffer * child = 0;
2569         bool parsed = false;
2570         if (theBufferList().exists(filename)) {
2571                 child = theBufferList().getBuffer(filename);
2572         } else {
2573                 message(bformat(_("Opening child document %1$s..."),
2574                 makeDisplayPath(filename.absFilename())));
2575                 child = loadDocument(filename, false);
2576                 parsed = true;
2577         }
2578         if (!child)
2579                 return;
2580
2581         // Set the parent name of the child document.
2582         // This makes insertion of citations and references in the child work,
2583         // when the target is in the parent or another child document.
2584         child->setParent(&buffer);
2585         child->masterBuffer()->updateLabels();
2586         setBuffer(child);
2587         if (parsed)
2588                 child->errors("Parse");
2589 }
2590
2591
2592 bool GuiView::goToFileRow(string const & argument)
2593 {
2594         string file_name;
2595         int row;
2596         istringstream is(argument);
2597         is >> file_name >> row;
2598         file_name = os::internal_path(file_name);
2599         Buffer * buf = 0;
2600         string const abstmp = package().temp_dir().absFilename();
2601         string const realtmp = package().temp_dir().realPath();
2602         // We have to use os::path_prefix_is() here, instead of
2603         // simply prefixIs(), because the file name comes from
2604         // an external application and may need case adjustment.
2605         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2606                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2607                 // Needed by inverse dvi search. If it is a file
2608                 // in tmpdir, call the apropriated function.
2609                 // If tmpdir is a symlink, we may have the real
2610                 // path passed back, so we correct for that.
2611                 if (!prefixIs(file_name, abstmp))
2612                         file_name = subst(file_name, realtmp, abstmp);
2613                 buf = theBufferList().getBufferFromTmp(file_name);
2614         } else {
2615                 // Must replace extension of the file to be .lyx
2616                 // and get full path
2617                 FileName const s = fileSearch(string(),
2618                                               support::changeExtension(file_name, ".lyx"), "lyx");
2619                 // Either change buffer or load the file
2620                 if (theBufferList().exists(s))
2621                         buf = theBufferList().getBuffer(s);
2622                 else if (s.exists()) {
2623                         buf = loadDocument(s);
2624                         buf->updateLabels();
2625                         buf->errors("Parse");
2626                 } else {
2627                         message(bformat(
2628                                         _("File does not exist: %1$s"),
2629                                         makeDisplayPath(file_name)));
2630                         return false;
2631                 }
2632         }
2633         setBuffer(buf);
2634         documentBufferView()->setCursorFromRow(row);
2635         return true;
2636 }
2637
2638
2639 static docstring exportAndDestroy(Buffer * buffer, string const & format)
2640 {
2641         bool const success = buffer->doExport(format, true);
2642         delete buffer;
2643         return success
2644                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
2645                 : bformat(_("Error exporting to format: %1$s"), from_utf8(format));
2646 }
2647
2648
2649 static docstring previewAndDestroy(Buffer * buffer, string const & format)
2650 {
2651         bool const success = buffer->preview(format);
2652         delete buffer;
2653         return success
2654                 ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
2655                 : bformat(_("Error previewing format: %1$s"), from_utf8(format));
2656 }
2657
2658
2659 bool GuiView::dispatch(FuncRequest const & cmd)
2660 {
2661         BufferView * bv = currentBufferView();
2662         // By default we won't need any update.
2663         if (bv)
2664                 bv->cursor().updateFlags(Update::None);
2665
2666         Buffer * doc_buffer = documentBufferView()
2667                 ? &(documentBufferView()->buffer()) : 0;
2668
2669         bool dispatched = true;
2670
2671         if (cmd.origin == FuncRequest::TOC) {
2672                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2673                 toc->doDispatch(bv->cursor(), cmd);
2674                 return true;
2675         }
2676
2677         string const argument = to_utf8(cmd.argument());
2678
2679         switch(cmd.action) {
2680                 case LFUN_BUFFER_CHILD_OPEN:
2681                         openChildDocument(to_utf8(cmd.argument()));
2682                         break;
2683
2684                 case LFUN_BUFFER_IMPORT:
2685                         importDocument(to_utf8(cmd.argument()));
2686                         break;
2687
2688                 case LFUN_BUFFER_EXPORT: {
2689                         if (!doc_buffer)
2690                                 break;
2691                         if (cmd.argument() == "custom") {
2692                                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"));
2693                                 break;
2694                         }
2695                         if (doc_buffer->doExport(argument, false)) {
2696                                 message(bformat(_("Error exporting to format: %1$s."),
2697                                         cmd.argument()));
2698                         }
2699                         break;
2700                 }
2701
2702                 case LFUN_BUFFER_UPDATE: {
2703                         if (!doc_buffer)
2704                                 break;
2705                         string format = argument;
2706                         if (argument.empty())
2707                                 format = doc_buffer->getDefaultOutputFormat();
2708 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2709                         ProgressInterface::instance()->clearMessages();
2710                         QString time = QTime::currentTime().toString();
2711                         ProgressInterface::instance()->appendMessage(time + ": Exporting ...\n");
2712                         QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2713                                 doc_buffer->clone(), format);
2714                         d.setPreviewFuture(f);
2715 #else
2716                         doc_buffer->doExport(format, true);
2717 #endif
2718                         break;
2719                 }
2720                 case LFUN_BUFFER_VIEW: {
2721                         if (!doc_buffer)
2722                                 break;
2723                         string format = argument;
2724                         if (argument.empty())
2725                                 format = doc_buffer->getDefaultOutputFormat();
2726 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2727                         ProgressInterface::instance()->clearMessages();
2728                         QString time = QTime::currentTime().toString();
2729                         ProgressInterface::instance()->appendMessage(time + ": Previewing ...\n");
2730                         QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2731                                 doc_buffer->clone(), format);
2732                         d.setPreviewFuture(f);
2733 #else
2734                         doc_buffer->preview(format);
2735 #endif
2736                         break;
2737                 }
2738                 case LFUN_MASTER_BUFFER_UPDATE: {
2739                         if (!doc_buffer)
2740                                 break;
2741                         string format = argument;
2742                         Buffer const * master = doc_buffer->masterBuffer();
2743                         if (argument.empty())
2744                                 format = master->getDefaultOutputFormat();
2745 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2746                         QFuture<docstring> f = QtConcurrent::run(exportAndDestroy,
2747                                 master->clone(), format);
2748                         d.setPreviewFuture(f);
2749 #else
2750                         master->doExport(format, true);
2751 #endif
2752                         break;
2753                 }
2754                 case LFUN_MASTER_BUFFER_VIEW: {
2755                         string format = argument;
2756                         Buffer const * master = doc_buffer->masterBuffer();
2757                         if (argument.empty())
2758                                 format = master->getDefaultOutputFormat();
2759 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
2760                         QFuture<docstring> f = QtConcurrent::run(previewAndDestroy,
2761                                 master->clone(), format);
2762                         d.setPreviewFuture(f);
2763 #else
2764                         master->preview(format);
2765 #endif
2766                         break;
2767                 }
2768                 case LFUN_BUFFER_SWITCH:
2769                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2770                                 Buffer * buffer = 
2771                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2772                                 if (buffer)
2773                                         setBuffer(buffer);
2774                                 else
2775                                         message(_("Document not loaded"));
2776                         }
2777                         break;
2778
2779                 case LFUN_BUFFER_NEXT:
2780                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2781                         break;
2782
2783                 case LFUN_BUFFER_PREVIOUS:
2784                         gotoNextOrPreviousBuffer(PREVBUFFER);
2785                         break;
2786
2787                 case LFUN_COMMAND_EXECUTE: {
2788                         bool const show_it = cmd.argument() != "off";
2789                         // FIXME: this is a hack, "minibuffer" should not be
2790                         // hardcoded.
2791                         if (GuiToolbar * t = toolbar("minibuffer")) {
2792                                 t->setVisible(show_it);
2793                                 if (show_it && t->commandBuffer())
2794                                         t->commandBuffer()->setFocus();
2795                         }
2796                         break;
2797                 }
2798                 case LFUN_DROP_LAYOUTS_CHOICE:
2799                         d.layout_->showPopup();
2800                         break;
2801
2802                 case LFUN_MENU_OPEN:
2803                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2804                                 menu->exec(QCursor::pos());
2805                         break;
2806
2807                 case LFUN_FILE_INSERT:
2808                         insertLyXFile(cmd.argument());
2809                         break;
2810                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2811                         insertPlaintextFile(cmd.argument(), true);
2812                         break;
2813
2814                 case LFUN_FILE_INSERT_PLAINTEXT:
2815                         insertPlaintextFile(cmd.argument(), false);
2816                         break;
2817
2818                 case LFUN_BUFFER_RELOAD: {
2819                         LASSERT(doc_buffer, break);
2820                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2821                         docstring text = bformat(_("Any changes will be lost. Are you sure "
2822                                                              "you want to revert to the saved version of the document %1$s?"), file);
2823                         int const ret = Alert::prompt(_("Revert to saved document?"),
2824                                 text, 1, 1, _("&Revert"), _("&Cancel"));
2825
2826                         if (ret == 0) {
2827                                 doc_buffer->markClean();
2828                                 reloadBuffer();
2829                         }
2830                         break;
2831                 }
2832
2833                 case LFUN_BUFFER_WRITE:
2834                         LASSERT(doc_buffer, break);
2835                         saveBuffer(*doc_buffer);
2836                         break;
2837
2838                 case LFUN_BUFFER_WRITE_AS:
2839                         LASSERT(doc_buffer, break);
2840                         renameBuffer(*doc_buffer, cmd.argument());
2841                         break;
2842
2843                 case LFUN_BUFFER_WRITE_ALL: {
2844                         Buffer * first = theBufferList().first();
2845                         if (!first)
2846                                 break;
2847                         message(_("Saving all documents..."));
2848                         // We cannot use a for loop as the buffer list cycles.
2849                         Buffer * b = first;
2850                         do {
2851                                 if (!b->isClean()) {
2852                                         saveBuffer(*b);
2853                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2854                                 }
2855                                 b = theBufferList().next(b);
2856                         } while (b != first); 
2857                         message(_("All documents saved."));
2858                         break;
2859                 }
2860
2861                 case LFUN_BUFFER_CLOSE:
2862                         closeBuffer();
2863                         break;
2864
2865                 case LFUN_BUFFER_CLOSE_ALL:
2866                         closeBufferAll();
2867                         break;
2868
2869                 case LFUN_TOOLBAR_TOGGLE: {
2870                         string const name = cmd.getArg(0);
2871                         if (GuiToolbar * t = toolbar(name))
2872                                 t->toggle();
2873                         break;
2874                 }
2875
2876                 case LFUN_DIALOG_UPDATE: {
2877                         string const name = to_utf8(cmd.argument());
2878                         if (currentBufferView()) {
2879                                 Inset * inset = currentBufferView()->editedInset(name);
2880                                 // Can only update a dialog connected to an existing inset
2881                                 if (!inset)
2882                                         break;
2883                                 // FIXME: get rid of this indirection; GuiView ask the inset
2884                                 // if he is kind enough to update itself...
2885                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2886                                 inset->dispatch(currentBufferView()->cursor(), fr);
2887                         } else if (name == "paragraph") {
2888                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2889                         } else if (name == "prefs" || name == "document") {
2890                                 updateDialog(name, string());
2891                         }
2892                         break;
2893                 }
2894
2895                 case LFUN_DIALOG_TOGGLE: {
2896                         if (isDialogVisible(cmd.getArg(0)))
2897                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2898                         else
2899                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2900                         break;
2901                 }
2902
2903                 case LFUN_DIALOG_DISCONNECT_INSET:
2904                         disconnectDialog(to_utf8(cmd.argument()));
2905                         break;
2906
2907                 case LFUN_DIALOG_HIDE: {
2908                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2909                         break;
2910                 }
2911
2912                 case LFUN_DIALOG_SHOW: {
2913                         string const name = cmd.getArg(0);
2914                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2915
2916                         if (name == "character") {
2917                                 data = freefont2string();
2918                                 if (!data.empty())
2919                                         showDialog("character", data);
2920                         } else if (name == "latexlog") {
2921                                 Buffer::LogType type; 
2922                                 string const logfile = doc_buffer->logName(&type);
2923                                 switch (type) {
2924                                 case Buffer::latexlog:
2925                                         data = "latex ";
2926                                         break;
2927                                 case Buffer::buildlog:
2928                                         data = "literate ";
2929                                         break;
2930                                 }
2931                                 data += Lexer::quoteString(logfile);
2932                                 showDialog("log", data);
2933                         } else if (name == "vclog") {
2934                                 string const data = "vc " +
2935                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2936                                 showDialog("log", data);
2937                         } else if (name == "symbols") {
2938                                 data = bv->cursor().getEncoding()->name();
2939                                 if (!data.empty())
2940                                         showDialog("symbols", data);
2941                         // bug 5274
2942                         } else if (name == "prefs" && isFullScreen()) {
2943                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2944                                 lfunUiToggle(fr);
2945                                 showDialog("prefs", data);
2946                         } else
2947                                 showDialog(name, data);
2948                         break;
2949                 }
2950
2951                 case LFUN_MESSAGE:
2952                         message(cmd.argument());
2953                         break;
2954
2955                 case LFUN_UI_TOGGLE:
2956                         lfunUiToggle(cmd);
2957                         // Make sure the keyboard focus stays in the work area.
2958                         setFocus();
2959                         break;
2960
2961                 case LFUN_SPLIT_VIEW: {
2962                         LASSERT(doc_buffer, break);
2963                         string const orientation = cmd.getArg(0);
2964                         d.splitter_->setOrientation(orientation == "vertical"
2965                                 ? Qt::Vertical : Qt::Horizontal);
2966                         TabWorkArea * twa = addTabWorkArea();
2967                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2968                         setCurrentWorkArea(wa);
2969                         break;
2970                 }
2971                 case LFUN_CLOSE_TAB_GROUP:
2972                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2973                                 closeTabWorkArea(twa);
2974                                 d.current_work_area_ = 0;
2975                                 twa = d.currentTabWorkArea();
2976                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2977                                 if (twa) {
2978                                         // Make sure the work area is up to date.
2979                                         setCurrentWorkArea(twa->currentWorkArea());
2980                                 } else {
2981                                         setCurrentWorkArea(0);
2982                                 }
2983                         }
2984                         break;
2985                         
2986                 case LFUN_COMPLETION_INLINE:
2987                         if (d.current_work_area_)
2988                                 d.current_work_area_->completer().showInline();
2989                         break;
2990
2991                 case LFUN_COMPLETION_POPUP:
2992                         if (d.current_work_area_)
2993                                 d.current_work_area_->completer().showPopup();
2994                         break;
2995
2996
2997                 case LFUN_COMPLETION_COMPLETE:
2998                         if (d.current_work_area_)
2999                                 d.current_work_area_->completer().tab();
3000                         break;
3001
3002                 case LFUN_COMPLETION_CANCEL:
3003                         if (d.current_work_area_) {
3004                                 if (d.current_work_area_->completer().popupVisible())
3005                                         d.current_work_area_->completer().hidePopup();
3006                                 else
3007                                         d.current_work_area_->completer().hideInline();
3008                         }
3009                         break;
3010
3011                 case LFUN_COMPLETION_ACCEPT:
3012                         if (d.current_work_area_)
3013                                 d.current_work_area_->completer().activate();
3014                         break;
3015
3016                 case LFUN_BUFFER_ZOOM_IN:
3017                 case LFUN_BUFFER_ZOOM_OUT:
3018                         if (cmd.argument().empty()) {
3019                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
3020                                         lyxrc.zoom += 20;
3021                                 else
3022                                         lyxrc.zoom -= 20;
3023                         } else
3024                                 lyxrc.zoom += convert<int>(cmd.argument());
3025
3026                         if (lyxrc.zoom < 10)
3027                                 lyxrc.zoom = 10;
3028                                 
3029                         // The global QPixmapCache is used in GuiPainter to cache text
3030                         // painting so we must reset it.
3031                         QPixmapCache::clear();
3032                         guiApp->fontLoader().update();
3033                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3034                         break;
3035
3036                 case LFUN_VC_REGISTER:
3037                 case LFUN_VC_CHECK_IN:
3038                 case LFUN_VC_CHECK_OUT:
3039                 case LFUN_VC_REPO_UPDATE:
3040                 case LFUN_VC_LOCKING_TOGGLE:
3041                 case LFUN_VC_REVERT:
3042                 case LFUN_VC_UNDO_LAST:
3043                 case LFUN_VC_COMMAND:
3044                         dispatchVC(cmd);
3045                         break;
3046
3047                 case LFUN_SERVER_GOTO_FILE_ROW:
3048                         goToFileRow(to_utf8(cmd.argument()));
3049                         break;
3050
3051                 default:
3052                         dispatched = false;
3053                         break;
3054         }
3055
3056         // Part of automatic menu appearance feature.
3057         if (isFullScreen()) {
3058                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3059                         menuBar()->hide();
3060                 if (statusBar()->isVisible())
3061                         statusBar()->hide();
3062         }
3063
3064         return dispatched;
3065 }
3066
3067
3068 void GuiView::lfunUiToggle(FuncRequest const & cmd)
3069 {
3070         string const arg = cmd.getArg(0);
3071         if (arg == "scrollbar") {
3072                 // hide() is of no help
3073                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3074                         Qt::ScrollBarAlwaysOff)
3075
3076                         d.current_work_area_->setVerticalScrollBarPolicy(
3077                                 Qt::ScrollBarAsNeeded);
3078                 else
3079                         d.current_work_area_->setVerticalScrollBarPolicy(
3080                                 Qt::ScrollBarAlwaysOff);
3081                 return;
3082         }
3083         if (arg == "statusbar") {
3084                 statusBar()->setVisible(!statusBar()->isVisible());
3085                 return;
3086         }
3087         if (arg == "menubar") {
3088                 menuBar()->setVisible(!menuBar()->isVisible());
3089                 return;
3090         }
3091 #if QT_VERSION >= 0x040300
3092         if (arg == "frame") {
3093                 int l, t, r, b;
3094                 getContentsMargins(&l, &t, &r, &b);
3095                 //are the frames in default state?
3096                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3097                 if (l == 0) {
3098                         setContentsMargins(-2, -2, -2, -2);
3099                 } else {
3100                         setContentsMargins(0, 0, 0, 0);
3101                 }
3102                 return;
3103         }
3104 #endif
3105         if (arg == "fullscreen") {
3106                 toggleFullScreen();
3107                 return;
3108         }
3109
3110         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
3111 }
3112
3113
3114 void GuiView::toggleFullScreen()
3115 {
3116         if (isFullScreen()) {
3117                 for (int i = 0; i != d.splitter_->count(); ++i)
3118                         d.tabWorkArea(i)->setFullScreen(false);
3119 #if QT_VERSION >= 0x040300
3120                 setContentsMargins(0, 0, 0, 0);
3121 #endif
3122                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3123                 restoreLayout();
3124                 menuBar()->show();
3125                 statusBar()->show();
3126         } else {
3127                 // bug 5274
3128                 hideDialogs("prefs", 0);
3129                 for (int i = 0; i != d.splitter_->count(); ++i)
3130                         d.tabWorkArea(i)->setFullScreen(true);
3131 #if QT_VERSION >= 0x040300
3132                 setContentsMargins(-2, -2, -2, -2);
3133 #endif
3134                 saveLayout();
3135                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3136                 statusBar()->hide();
3137                 if (lyxrc.full_screen_menubar)
3138                         menuBar()->hide();
3139                 if (lyxrc.full_screen_toolbars) {
3140                         ToolbarMap::iterator end = d.toolbars_.end();
3141                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3142                                 it->second->hide();
3143                 }
3144         }
3145
3146         // give dialogs like the TOC a chance to adapt
3147         updateDialogs();
3148 }
3149
3150
3151 Buffer const * GuiView::updateInset(Inset const * inset)
3152 {
3153         if (!d.current_work_area_)
3154                 return 0;
3155
3156         if (inset)
3157                 d.current_work_area_->scheduleRedraw();
3158
3159         return &d.current_work_area_->bufferView().buffer();
3160 }
3161
3162
3163 void GuiView::restartCursor()
3164 {
3165         /* When we move around, or type, it's nice to be able to see
3166          * the cursor immediately after the keypress.
3167          */
3168         if (d.current_work_area_)
3169                 d.current_work_area_->startBlinkingCursor();
3170
3171         // Take this occasion to update the other GUI elements.
3172         updateDialogs();
3173         updateStatusBar();
3174 }
3175
3176
3177 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3178 {
3179         if (d.current_work_area_)
3180                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3181 }
3182
3183 namespace {
3184
3185 // This list should be kept in sync with the list of insets in
3186 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3187 // dialog should have the same name as the inset.
3188 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3189 // docs in LyXAction.cpp.
3190
3191 char const * const dialognames[] = {
3192 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3193 "citation", "compare", "document", "errorlist", "ert", "external", "file",
3194 "findreplace", "findreplaceadv", "float", "graphics", "href", "include",
3195 "index", "index_print", "info", "listings", "label", "log", "mathdelimiter",
3196 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
3197 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
3198 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
3199 "toc", "view-source", "vspace", "wrap", "progress"};
3200
3201 char const * const * const end_dialognames =
3202         dialognames + (sizeof(dialognames) / sizeof(char *));
3203
3204 class cmpCStr {
3205 public:
3206         cmpCStr(char const * name) : name_(name) {}
3207         bool operator()(char const * other) {
3208                 return strcmp(other, name_) == 0;
3209         }
3210 private:
3211         char const * name_;
3212 };
3213
3214
3215 bool isValidName(string const & name)
3216 {
3217         return find_if(dialognames, end_dialognames,
3218                             cmpCStr(name.c_str())) != end_dialognames;
3219 }
3220
3221 } // namespace anon
3222
3223
3224 void GuiView::resetDialogs()
3225 {
3226         // Make sure that no LFUN uses any LyXView.
3227         guiApp->setCurrentView(0);
3228         saveLayout();
3229         menuBar()->clear();
3230         constructToolbars();
3231         guiApp->menus().fillMenuBar(menuBar(), this, false);
3232         d.layout_->updateContents(true);
3233         // Now update controls with current buffer.
3234         guiApp->setCurrentView(this);
3235         restoreLayout();
3236         restartCursor();
3237 }
3238
3239
3240 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3241 {
3242         if (!isValidName(name))
3243                 return 0;
3244
3245         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3246
3247         if (it != d.dialogs_.end()) {
3248                 if (hide_it)
3249                         it->second->hideView();
3250                 return it->second.get();
3251         }
3252
3253         Dialog * dialog = build(name);
3254         d.dialogs_[name].reset(dialog);
3255         if (lyxrc.allow_geometry_session)
3256                 dialog->restoreSession();
3257         if (hide_it)
3258                 dialog->hideView();
3259         return dialog;
3260 }
3261
3262
3263 void GuiView::showDialog(string const & name, string const & data,
3264         Inset * inset)
3265 {
3266         triggerShowDialog(toqstr(name), toqstr(data), inset);
3267 }
3268
3269
3270 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3271         Inset * inset)
3272 {
3273         if (d.in_show_)
3274                 return;
3275
3276         const string name = fromqstr(qname);
3277         const string data = fromqstr(qdata);
3278
3279         d.in_show_ = true;
3280         try {
3281                 Dialog * dialog = findOrBuild(name, false);
3282                 if (dialog) {
3283                         dialog->showData(data);
3284                         if (inset && currentBufferView())
3285                                 currentBufferView()->editInset(name, inset);
3286                 }
3287         }
3288         catch (ExceptionMessage const & ex) {
3289                 d.in_show_ = false;
3290                 throw ex;
3291         }
3292         d.in_show_ = false;
3293 }
3294
3295
3296 bool GuiView::isDialogVisible(string const & name) const
3297 {
3298         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3299         if (it == d.dialogs_.end())
3300                 return false;
3301         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3302 }
3303
3304
3305 void GuiView::hideDialog(string const & name, Inset * inset)
3306 {
3307         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3308         if (it == d.dialogs_.end())
3309                 return;
3310
3311         if (inset && currentBufferView()
3312                 && inset != currentBufferView()->editedInset(name))
3313                 return;
3314
3315         Dialog * const dialog = it->second.get();
3316         if (dialog->isVisibleView())
3317                 dialog->hideView();
3318         if (currentBufferView())
3319                 currentBufferView()->editInset(name, 0);
3320 }
3321
3322
3323 void GuiView::disconnectDialog(string const & name)
3324 {
3325         if (!isValidName(name))
3326                 return;
3327         if (currentBufferView())
3328                 currentBufferView()->editInset(name, 0);
3329 }
3330
3331
3332 void GuiView::hideAll() const
3333 {
3334         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3335         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3336
3337         for(; it != end; ++it)
3338                 it->second->hideView();
3339 }
3340
3341
3342 void GuiView::updateDialogs()
3343 {
3344         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3345         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3346
3347         for(; it != end; ++it) {
3348                 Dialog * dialog = it->second.get();
3349                 if (dialog && dialog->isVisibleView())
3350                         dialog->checkStatus();
3351         }
3352         updateToolbars();
3353         updateLayoutList();
3354 }
3355
3356
3357 // will be replaced by a proper factory...
3358 Dialog * createGuiAbout(GuiView & lv);
3359 Dialog * createGuiBibitem(GuiView & lv);
3360 Dialog * createGuiBibtex(GuiView & lv);
3361 Dialog * createGuiBox(GuiView & lv);
3362 Dialog * createGuiBranch(GuiView & lv);
3363 Dialog * createGuiChanges(GuiView & lv);
3364 Dialog * createGuiCharacter(GuiView & lv);
3365 Dialog * createGuiCitation(GuiView & lv);
3366 Dialog * createGuiCompare(GuiView & lv);
3367 Dialog * createGuiDelimiter(GuiView & lv);
3368 Dialog * createGuiDocument(GuiView & lv);
3369 Dialog * createGuiErrorList(GuiView & lv);
3370 Dialog * createGuiERT(GuiView & lv);
3371 Dialog * createGuiExternal(GuiView & lv);
3372 Dialog * createGuiFloat(GuiView & lv);
3373 Dialog * createGuiGraphics(GuiView & lv);
3374 Dialog * createGuiInclude(GuiView & lv);
3375 Dialog * createGuiIndex(GuiView & lv);
3376 Dialog * createGuiInfo(GuiView & lv);
3377 Dialog * createGuiLabel(GuiView & lv);
3378 Dialog * createGuiListings(GuiView & lv);
3379 Dialog * createGuiLog(GuiView & lv);
3380 Dialog * createGuiMathHSpace(GuiView & lv);
3381 Dialog * createGuiMathMatrix(GuiView & lv);
3382 Dialog * createGuiNomenclature(GuiView & lv);
3383 Dialog * createGuiNote(GuiView & lv);
3384 Dialog * createGuiParagraph(GuiView & lv);
3385 Dialog * createGuiPhantom(GuiView & lv);
3386 Dialog * createGuiPreferences(GuiView & lv);
3387 Dialog * createGuiPrint(GuiView & lv);
3388 Dialog * createGuiPrintindex(GuiView & lv);
3389 Dialog * createGuiPrintNomencl(GuiView & lv);
3390 Dialog * createGuiRef(GuiView & lv);
3391 Dialog * createGuiSearch(GuiView & lv);
3392 Dialog * createGuiSearchAdv(GuiView & lv);
3393 Dialog * createGuiSendTo(GuiView & lv);
3394 Dialog * createGuiShowFile(GuiView & lv);
3395 Dialog * createGuiSpellchecker(GuiView & lv);
3396 Dialog * createGuiSymbols(GuiView & lv);
3397 Dialog * createGuiTabularCreate(GuiView & lv);
3398 Dialog * createGuiTabular(GuiView & lv);
3399 Dialog * createGuiTexInfo(GuiView & lv);
3400 Dialog * createGuiTextHSpace(GuiView & lv);
3401 Dialog * createGuiToc(GuiView & lv);
3402 Dialog * createGuiThesaurus(GuiView & lv);
3403 Dialog * createGuiHyperlink(GuiView & lv);
3404 Dialog * createGuiVSpace(GuiView & lv);
3405 Dialog * createGuiViewSource(GuiView & lv);
3406 Dialog * createGuiWrap(GuiView & lv);
3407 Dialog * createGuiProgressView(GuiView & lv);
3408
3409
3410
3411 Dialog * GuiView::build(string const & name)
3412 {
3413         LASSERT(isValidName(name), return 0);
3414
3415         if (name == "aboutlyx")
3416                 return createGuiAbout(*this);
3417         if (name == "bibitem")
3418                 return createGuiBibitem(*this);
3419         if (name == "bibtex")
3420                 return createGuiBibtex(*this);
3421         if (name == "box")
3422                 return createGuiBox(*this);
3423         if (name == "branch")
3424                 return createGuiBranch(*this);
3425         if (name == "changes")
3426                 return createGuiChanges(*this);
3427         if (name == "character")
3428                 return createGuiCharacter(*this);
3429         if (name == "citation")
3430                 return createGuiCitation(*this);
3431         if (name == "compare")
3432                 return createGuiCompare(*this);
3433         if (name == "document")
3434                 return createGuiDocument(*this);
3435         if (name == "errorlist")
3436                 return createGuiErrorList(*this);
3437         if (name == "ert")
3438                 return createGuiERT(*this);
3439         if (name == "external")
3440                 return createGuiExternal(*this);
3441         if (name == "file")
3442                 return createGuiShowFile(*this);
3443         if (name == "findreplace")
3444                 return createGuiSearch(*this);
3445         if (name == "findreplaceadv")
3446                 return createGuiSearchAdv(*this);
3447         if (name == "float")
3448                 return createGuiFloat(*this);
3449         if (name == "graphics")
3450                 return createGuiGraphics(*this);
3451         if (name == "href")
3452                 return createGuiHyperlink(*this);
3453         if (name == "include")
3454                 return createGuiInclude(*this);
3455         if (name == "index")
3456                 return createGuiIndex(*this);
3457         if (name == "index_print")
3458                 return createGuiPrintindex(*this);
3459         if (name == "info")
3460                 return createGuiInfo(*this);
3461         if (name == "label")
3462                 return createGuiLabel(*this);
3463         if (name == "listings")
3464                 return createGuiListings(*this);
3465         if (name == "log")
3466                 return createGuiLog(*this);
3467         if (name == "mathdelimiter")
3468                 return createGuiDelimiter(*this);
3469         if (name == "mathspace")
3470                 return createGuiMathHSpace(*this);
3471         if (name == "mathmatrix")
3472                 return createGuiMathMatrix(*this);
3473         if (name == "nomenclature")
3474                 return createGuiNomenclature(*this);
3475         if (name == "nomencl_print")
3476                 return createGuiPrintNomencl(*this);
3477         if (name == "note")
3478                 return createGuiNote(*this);
3479         if (name == "paragraph")
3480                 return createGuiParagraph(*this);
3481         if (name == "phantom")
3482                 return createGuiPhantom(*this);
3483         if (name == "prefs")
3484                 return createGuiPreferences(*this);
3485         if (name == "print")
3486                 return createGuiPrint(*this);
3487         if (name == "ref")
3488                 return createGuiRef(*this);
3489         if (name == "sendto")
3490                 return createGuiSendTo(*this);
3491         if (name == "space")
3492                 return createGuiTextHSpace(*this);
3493         if (name == "spellchecker")
3494                 return createGuiSpellchecker(*this);
3495         if (name == "symbols")
3496                 return createGuiSymbols(*this);
3497         if (name == "tabular")
3498                 return createGuiTabular(*this);
3499         if (name == "tabularcreate")
3500                 return createGuiTabularCreate(*this);
3501         if (name == "texinfo")
3502                 return createGuiTexInfo(*this);
3503         if (name == "thesaurus")
3504                 return createGuiThesaurus(*this);
3505         if (name == "toc")
3506                 return createGuiToc(*this);
3507         if (name == "view-source")
3508                 return createGuiViewSource(*this);
3509         if (name == "vspace")
3510                 return createGuiVSpace(*this);
3511         if (name == "wrap")
3512                 return createGuiWrap(*this);
3513         if (name == "progress")
3514                 return createGuiProgressView(*this);
3515
3516         return 0;
3517 }
3518
3519
3520 } // namespace frontend
3521 } // namespace lyx
3522
3523 #include "moc_GuiView.cpp"