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