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