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