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