]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiView.cpp
5b7601ea53285eae77c62eebca8fa1f1ffac5635
[features.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "Dialog.h"
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
29 #include "Menus.h"
30 #include "TocModel.h"
31
32 #include "qt_helpers.h"
33
34 #include "frontends/alert.h"
35
36 #include "buffer_funcs.h"
37 #include "Buffer.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
42 #include "Cursor.h"
43 #include "CutAndPaste.h"
44 #include "Encoding.h"
45 #include "ErrorList.h"
46 #include "Format.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
49 #include "Intl.h"
50 #include "Layout.h"
51 #include "Lexer.h"
52 #include "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         writeSession();
548
549         // it can happen that this event arrives without selecting the view,
550         // e.g. when clicking the close button on a background window.
551         setFocus();
552         if (!closeWorkAreaAll()) {
553                 closing_ = false;
554                 close_event->ignore();
555                 return;
556         }
557
558         // Make sure that nothing will use this to be closed View.
559         guiApp->unregisterView(this);
560
561         if (isFullScreen()) {
562                 // Switch off fullscreen before closing.
563                 toggleFullScreen();
564                 updateDialogs();
565         }
566
567         // Make sure the timer time out will not trigger a statusbar update.
568         d.statusbar_timer_.stop();
569
570         // Saving fullscreen requires additional tweaks in the toolbar code.
571         // It wouldn't also work under linux natively.
572         if (lyxrc.allow_geometry_session) {
573                 // Save this window geometry and layout.
574                 saveLayout();
575                 // Then the toolbar private states.
576                 ToolbarMap::iterator end = d.toolbars_.end();
577                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
578                         it->second->saveSession();
579                 // Now take care of all other dialogs:
580                 map<string, DialogPtr>::const_iterator it = d.dialogs_.begin();
581                 for (; it!= d.dialogs_.end(); ++it)
582                         it->second->saveSession();
583         }
584
585         close_event->accept();
586 }
587
588
589 void GuiView::dragEnterEvent(QDragEnterEvent * event)
590 {
591         if (event->mimeData()->hasUrls())
592                 event->accept();
593         /// \todo Ask lyx-devel is this is enough:
594         /// if (event->mimeData()->hasFormat("text/plain"))
595         ///     event->acceptProposedAction();
596 }
597
598
599 void GuiView::dropEvent(QDropEvent * event)
600 {
601         QList<QUrl> files = event->mimeData()->urls();
602         if (files.isEmpty())
603                 return;
604
605         LYXERR(Debug::GUI, "GuiView::dropEvent: got URLs!");
606         for (int i = 0; i != files.size(); ++i) {
607                 string const file = os::internal_path(fromqstr(
608                         files.at(i).toLocalFile()));
609                 if (!file.empty()) {
610                         // Asynchronously post the event. DropEvent usually come
611                         // from the BufferView. But reloading a file might close
612                         // the BufferView from within its own event handler.
613                         guiApp->dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, file));
614                         event->accept();
615                 }
616         }
617 }
618
619
620 void GuiView::message(docstring const & str)
621 {
622         if (ForkedProcess::iAmAChild())
623                 return;
624
625         statusBar()->showMessage(toqstr(str));
626         d.statusbar_timer_.stop();
627         d.statusbar_timer_.start(3000);
628 }
629
630
631 void GuiView::smallSizedIcons()
632 {
633         setIconSize(QSize(d.smallIconSize, d.smallIconSize));
634 }
635
636
637 void GuiView::normalSizedIcons()
638 {
639         setIconSize(QSize(d.normalIconSize, d.normalIconSize));
640 }
641
642
643 void GuiView::bigSizedIcons()
644 {
645         setIconSize(QSize(d.bigIconSize, d.bigIconSize));
646 }
647
648
649 void GuiView::clearMessage()
650 {
651         if (!hasFocus())
652                 return;
653         theLyXFunc().setLyXView(this);
654         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
655         d.statusbar_timer_.stop();
656 }
657
658
659 void GuiView::updateWindowTitle(GuiWorkArea * wa)
660 {
661         if (wa != d.current_work_area_)
662                 return;
663         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
664         setWindowIconText(wa->windowIconText());
665 }
666
667
668 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
669 {
670         disconnectBuffer();
671         disconnectBufferView();
672         connectBufferView(wa->bufferView());
673         connectBuffer(wa->bufferView().buffer());
674         d.current_work_area_ = wa;
675         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
676                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
677         updateWindowTitle(wa);
678
679         structureChanged();
680
681         // The document settings needs to be reinitialised.
682         updateDialog("document", "");
683
684         // Buffer-dependent dialogs must be updated. This is done here because
685         // some dialogs require buffer()->text.
686         updateDialogs();
687 }
688
689
690 void GuiView::on_lastWorkAreaRemoved()
691 {
692         if (closing_)
693                 // We already are in a close event. Nothing more to do.
694                 return;
695
696         if (d.splitter_->count() > 1)
697                 // We have a splitter so don't close anything.
698                 return;
699
700         // Reset and updates the dialogs.
701         d.toc_models_.reset(0);
702         updateDialog("document", "");
703         updateDialogs();
704
705         resetWindowTitleAndIconText();
706
707         if (lyxrc.open_buffers_in_tabs)
708                 // Nothing more to do, the window should stay open.
709                 return;
710
711         if (guiApp->viewIds().size() > 1) {
712                 close();
713                 return;
714         }
715
716 #ifdef Q_WS_MACX
717         // On Mac we also close the last window because the application stay
718         // resident in memory. On other platforms we don't close the last
719         // window because this would quit the application.
720         close();
721 #endif
722 }
723
724
725 void GuiView::updateStatusBar()
726 {
727         // let the user see the explicit message
728         if (d.statusbar_timer_.isActive())
729                 return;
730
731         theLyXFunc().setLyXView(this);
732         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
733 }
734
735
736 bool GuiView::hasFocus() const
737 {
738         return qApp->activeWindow() == this;
739 }
740
741
742 bool GuiView::event(QEvent * e)
743 {
744         switch (e->type())
745         {
746         // Useful debug code:
747         //case QEvent::ActivationChange:
748         //case QEvent::WindowDeactivate:
749         //case QEvent::Paint:
750         //case QEvent::Enter:
751         //case QEvent::Leave:
752         //case QEvent::HoverEnter:
753         //case QEvent::HoverLeave:
754         //case QEvent::HoverMove:
755         //case QEvent::StatusTip:
756         //case QEvent::DragEnter:
757         //case QEvent::DragLeave:
758         //case QEvent::Drop:
759         //      break;
760
761         case QEvent::WindowActivate: {
762                 if (this == guiApp->currentView()) {
763                         setFocus();
764                         return QMainWindow::event(e);
765                 }
766                 guiApp->setCurrentView(this);
767                 theLyXFunc().setLyXView(this);
768                 if (d.current_work_area_) {
769                         BufferView & bv = d.current_work_area_->bufferView();
770                         connectBufferView(bv);
771                         connectBuffer(bv.buffer());
772                         // The document structure, name and dialogs might have
773                         // changed in another view.
774                         structureChanged();
775                         // The document settings needs to be reinitialised.
776                         updateDialog("document", "");
777                         updateDialogs();
778                 } else {
779                         resetWindowTitleAndIconText();
780                 }
781                 setFocus();
782                 return QMainWindow::event(e);
783         }
784
785         case QEvent::ShortcutOverride: {
786
787 // See bug 4888
788 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
789                 if (isFullScreen() && menuBar()->isHidden()) {
790                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
791                         // FIXME: we should also try to detect special LyX shortcut such as
792                         // Alt-P and Alt-M. Right now there is a hack in
793                         // GuiWorkArea::processKeySym() that hides again the menubar for
794                         // those cases.
795                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
796                                 menuBar()->show();
797                                 return QMainWindow::event(e);
798                         }
799                 }
800 #endif
801
802                 if (d.current_work_area_)
803                         // Nothing special to do.
804                         return QMainWindow::event(e);
805
806                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
807                 // Let Qt handle menu access and the Tab keys to navigate keys to navigate
808                 // between controls.
809                 if (ke->modifiers() & Qt::AltModifier || ke->key() == Qt::Key_Tab 
810                         || ke->key() == Qt::Key_Backtab)
811                         return QMainWindow::event(e);
812
813                 // Allow processing of shortcuts that are allowed even when no Buffer
814                 // is viewed.
815                 theLyXFunc().setLyXView(this);
816                 KeySymbol sym;
817                 setKeySymbol(&sym, ke);
818                 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
819                 e->accept();
820                 return true;
821         }
822
823         default:
824                 return QMainWindow::event(e);
825         }
826 }
827
828 void GuiView::resetWindowTitleAndIconText()
829 {
830     setWindowTitle(qt_("LyX"));
831     setWindowIconText(qt_("LyX"));
832 }
833
834 bool GuiView::focusNextPrevChild(bool /*next*/)
835 {
836         setFocus();
837         return true;
838 }
839
840
841 void GuiView::setBusy(bool busy)
842 {
843         if (d.current_work_area_) {
844                 d.current_work_area_->setUpdatesEnabled(!busy);
845                 if (busy)
846                         d.current_work_area_->stopBlinkingCursor();
847                 else
848                         d.current_work_area_->startBlinkingCursor();
849         }
850
851         if (busy)
852                 QApplication::setOverrideCursor(Qt::WaitCursor);
853         else
854                 QApplication::restoreOverrideCursor();
855 }
856
857
858 GuiWorkArea * GuiView::workArea(Buffer & buffer)
859 {
860         if (currentWorkArea()
861             && &currentWorkArea()->bufferView().buffer() == &buffer)
862                 return (GuiWorkArea *) currentWorkArea();
863         if (TabWorkArea * twa = d.currentTabWorkArea())
864                 return twa->workArea(buffer);
865         return 0;
866 }
867
868
869 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
870 {
871         // Automatically create a TabWorkArea if there are none yet.
872         TabWorkArea * tab_widget = d.splitter_->count() 
873                 ? d.currentTabWorkArea() : addTabWorkArea();
874         return tab_widget->addWorkArea(buffer, *this);
875 }
876
877
878 TabWorkArea * GuiView::addTabWorkArea()
879 {
880         TabWorkArea * twa = new TabWorkArea;
881         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
882                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
883         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
884                          this, SLOT(on_lastWorkAreaRemoved()));
885
886         d.splitter_->addWidget(twa);
887         d.stack_widget_->setCurrentWidget(d.splitter_);
888         return twa;
889 }
890
891
892 GuiWorkArea const * GuiView::currentWorkArea() const
893 {
894         return d.current_work_area_;
895 }
896
897
898 GuiWorkArea * GuiView::currentWorkArea()
899 {
900         return d.current_work_area_;
901 }
902
903
904 GuiWorkArea const * GuiView::currentMainWorkArea() const
905 {
906         if (d.currentTabWorkArea() == NULL)
907                 return NULL;
908         return d.currentTabWorkArea()->currentWorkArea();
909 }
910
911
912 GuiWorkArea * GuiView::currentMainWorkArea()
913 {
914         if (d.currentTabWorkArea() == NULL)
915                 return NULL;
916         return d.currentTabWorkArea()->currentWorkArea();
917 }
918
919
920 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
921 {
922         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
923         if (wa == NULL) {
924                 d.current_work_area_ = NULL;
925                 d.setBackground();
926                 return;
927         }
928         GuiWorkArea * old_gwa = theGuiApp()->currentView()->currentWorkArea();
929         if (old_gwa == wa)
930                 return;
931
932         if (currentBufferView())
933                 cap::saveSelection(currentBufferView()->cursor());
934
935         theGuiApp()->setCurrentView(this);
936         d.current_work_area_ = wa;
937         for (int i = 0; i != d.splitter_->count(); ++i) {
938                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
939                         //if (d.current_main_work_area_)
940                         //      d.current_main_work_area_->setFrameStyle(QFrame::NoFrame);
941                         d.current_main_work_area_ = wa;
942                         //d.current_main_work_area_->setFrameStyle(QFrame::Box | QFrame::Plain);
943                         //d.current_main_work_area_->setLineWidth(2);
944                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
945                         return;
946                 }
947         }
948         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
949         on_currentWorkAreaChanged(wa);
950         BufferView & bv = wa->bufferView();
951         bv.cursor().fixIfBroken();
952         bv.updateMetrics();
953         wa->setUpdatesEnabled(true);
954         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
955 }
956
957
958 void GuiView::removeWorkArea(GuiWorkArea * wa)
959 {
960         LASSERT(wa, return);
961         if (wa == d.current_work_area_) {
962                 disconnectBuffer();
963                 disconnectBufferView();
964                 d.current_work_area_ = 0;
965                 d.current_main_work_area_ = 0;
966         }
967
968         bool found_twa = false;
969         for (int i = 0; i != d.splitter_->count(); ++i) {
970                 TabWorkArea * twa = d.tabWorkArea(i);
971                 if (twa->removeWorkArea(wa)) {
972                         // Found in this tab group, and deleted the GuiWorkArea.
973                         found_twa = true;
974                         if (twa->count() != 0) {
975                                 if (d.current_work_area_ == 0)
976                                         // This means that we are closing the current GuiWorkArea, so
977                                         // switch to the next GuiWorkArea in the found TabWorkArea.
978                                         setCurrentWorkArea(twa->currentWorkArea());
979                         } else {
980                                 // No more WorkAreas in this tab group, so delete it.
981                                 delete twa;
982                         }
983                         break;
984                 }
985         }
986
987         // It is not a tabbed work area (i.e., the search work area), so it
988         // should be deleted by other means.
989         LASSERT(found_twa, /* */);
990
991         if (d.current_work_area_ == 0) {
992                 if (d.splitter_->count() != 0) {
993                         TabWorkArea * twa = d.currentTabWorkArea();
994                         setCurrentWorkArea(twa->currentWorkArea());
995                 } else {
996                         // No more work areas, switch to the background widget.
997                         setCurrentWorkArea(0);
998                 }
999         }
1000 }
1001
1002
1003 LayoutBox * GuiView::getLayoutDialog() const
1004 {
1005         return d.layout_;
1006 }
1007
1008
1009 void GuiView::updateLayoutList()
1010 {
1011         if (d.layout_)
1012                 d.layout_->updateContents(false);
1013 }
1014
1015
1016 void GuiView::updateToolbars()
1017 {
1018         ToolbarMap::iterator end = d.toolbars_.end();
1019         if (d.current_work_area_) {
1020                 bool const math =
1021                         d.current_work_area_->bufferView().cursor().inMathed();
1022                 bool const table =
1023                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1024                 bool const review =
1025                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1026                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1027                 bool const mathmacrotemplate =
1028                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1029
1030                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1031                         it->second->update(math, table, review, mathmacrotemplate);
1032         } else
1033                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1034                         it->second->update(false, false, false, false);
1035 }
1036
1037
1038 void GuiView::setBuffer(Buffer * newBuffer)
1039 {
1040         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << std::endl);
1041         LASSERT(newBuffer, return);
1042         setBusy(true);
1043
1044         GuiWorkArea * wa = workArea(*newBuffer);
1045         if (wa == 0) {
1046                 newBuffer->masterBuffer()->updateLabels();
1047                 wa = addWorkArea(*newBuffer);
1048         } else {
1049                 //Disconnect the old buffer...there's no new one.
1050                 disconnectBuffer();
1051         }
1052         connectBuffer(*newBuffer);
1053         connectBufferView(wa->bufferView());
1054         setCurrentWorkArea(wa);
1055
1056         setBusy(false);
1057 }
1058
1059
1060 void GuiView::connectBuffer(Buffer & buf)
1061 {
1062         buf.setGuiDelegate(this);
1063 }
1064
1065
1066 void GuiView::disconnectBuffer()
1067 {
1068         if (d.current_work_area_)
1069                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1070 }
1071
1072
1073 void GuiView::connectBufferView(BufferView & bv)
1074 {
1075         bv.setGuiDelegate(this);
1076 }
1077
1078
1079 void GuiView::disconnectBufferView()
1080 {
1081         if (d.current_work_area_)
1082                 d.current_work_area_->bufferView().setGuiDelegate(0);
1083 }
1084
1085
1086 void GuiView::errors(string const & error_type, bool from_master)
1087 {
1088         ErrorList & el = from_master ? 
1089                 documentBufferView()->buffer().masterBuffer()->errorList(error_type)
1090                 : documentBufferView()->buffer().errorList(error_type);
1091         string data = error_type;
1092         if (from_master)
1093                 data = "from_master|" + error_type;
1094         if (!el.empty())
1095                 showDialog("errorlist", data);
1096 }
1097
1098
1099 void GuiView::updateTocItem(std::string const & type, DocIterator const & dit)
1100 {
1101         d.toc_models_.updateItem(toqstr(type), dit);
1102 }
1103
1104
1105 void GuiView::structureChanged()
1106 {
1107         d.toc_models_.reset(documentBufferView());
1108         // Navigator needs more than a simple update in this case. It needs to be
1109         // rebuilt.
1110         updateDialog("toc", "");
1111 }
1112
1113
1114 void GuiView::updateDialog(string const & name, string const & data)
1115 {
1116         if (!isDialogVisible(name))
1117                 return;
1118
1119         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1120         if (it == d.dialogs_.end())
1121                 return;
1122
1123         Dialog * const dialog = it->second.get();
1124         if (dialog->isVisibleView())
1125                 dialog->initialiseParams(data);
1126 }
1127
1128
1129 BufferView * GuiView::documentBufferView()
1130 {
1131         return currentMainWorkArea()
1132                 ? &currentMainWorkArea()->bufferView()
1133                 : 0;
1134 }
1135
1136
1137 BufferView const * GuiView::documentBufferView() const 
1138 {
1139         return currentMainWorkArea()
1140                 ? &currentMainWorkArea()->bufferView()
1141                 : 0;
1142 }
1143
1144
1145 BufferView * GuiView::currentBufferView()
1146 {
1147         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1148 }
1149
1150
1151 BufferView const * GuiView::currentBufferView() const
1152 {
1153         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1154 }
1155
1156
1157 void GuiView::autoSave()
1158 {
1159         LYXERR(Debug::INFO, "Running autoSave()");
1160
1161         if (documentBufferView())
1162                 documentBufferView()->buffer().autoSave();
1163 }
1164
1165
1166 void GuiView::resetAutosaveTimers()
1167 {
1168         if (lyxrc.autosave)
1169                 d.autosave_timeout_.restart();
1170 }
1171
1172
1173 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1174 {
1175         bool enable = true;
1176         Buffer * buf = currentBufferView()
1177                 ? &currentBufferView()->buffer() : 0;
1178
1179         if (cmd.origin == FuncRequest::TOC) {
1180                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1181                 FuncStatus fs;
1182                 if (toc->getStatus(documentBufferView()->cursor(), cmd, fs))
1183                         flag |= fs;
1184                 else
1185                         flag.setEnabled(false);
1186                 return true;
1187         }
1188
1189         switch(cmd.action) {
1190         case LFUN_BUFFER_WRITE:
1191                 enable = buf && (buf->isUnnamed() || !buf->isClean());
1192                 break;
1193
1194         case LFUN_BUFFER_WRITE_AS:
1195                 enable = buf;
1196                 break;
1197
1198         case LFUN_BUFFER_CLOSE_ALL:
1199                 enable = theBufferList().last() != theBufferList().first();
1200                 break;
1201
1202         case LFUN_SPLIT_VIEW:
1203                 if (cmd.getArg(0) == "vertical")
1204                         enable = buf && (d.splitter_->count() == 1 ||
1205                                          d.splitter_->orientation() == Qt::Vertical);
1206                 else
1207                         enable = buf && (d.splitter_->count() == 1 ||
1208                                          d.splitter_->orientation() == Qt::Horizontal);
1209                 break;
1210
1211         case LFUN_CLOSE_TAB_GROUP:
1212                 enable = d.currentTabWorkArea();
1213                 break;
1214
1215         case LFUN_TOOLBAR_TOGGLE:
1216                 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1217                         flag.setOnOff(t->isVisible());
1218                 break;
1219
1220         case LFUN_UI_TOGGLE:
1221                 flag.setOnOff(isFullScreen());
1222                 break;
1223
1224         case LFUN_DIALOG_TOGGLE:
1225                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1226                 // fall through to set "enable"
1227         case LFUN_DIALOG_SHOW: {
1228                 string const name = cmd.getArg(0);
1229                 if (!buf)
1230                         enable = name == "aboutlyx"
1231                                 || name == "file" //FIXME: should be removed.
1232                                 || name == "prefs"
1233                                 || name == "texinfo";
1234                 else if (name == "print")
1235                         enable = buf->isExportable("dvi")
1236                                 && lyxrc.print_command != "none";
1237                 else if (name == "character" || name == "symbols") {
1238                         if (buf->isReadonly() || !currentBufferView() 
1239                                 || !currentBufferView()->cursor().inTexted())
1240                                 enable = false;
1241                         else {
1242                                 // FIXME we should consider passthru
1243                                 // paragraphs too.
1244                                 Inset const & in = currentBufferView()->cursor().inset();
1245                                 enable = !in.getLayout().isPassThru();
1246                         }
1247                 }
1248                 else if (name == "latexlog")
1249                         enable = FileName(buf->logName()).isReadableFile();
1250                 else if (name == "spellchecker")
1251                         enable = theSpellChecker() && !buf->isReadonly();
1252                 else if (name == "vclog")
1253                         enable = buf->lyxvc().inUse();
1254                 break;
1255         }
1256
1257         case LFUN_DIALOG_UPDATE: {
1258                 string const name = cmd.getArg(0);
1259                 if (!buf)
1260                         enable = name == "prefs";
1261                 break;
1262         }
1263
1264         case LFUN_INSET_APPLY: {
1265                 string const name = cmd.getArg(0);
1266                 Inset * inset = getOpenInset(name);
1267                 if (inset) {
1268                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1269                         FuncStatus fs;
1270                         if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1271                                 // Every inset is supposed to handle this
1272                                 LASSERT(false, break);
1273                         }
1274                         flag |= fs;
1275                 } else {
1276                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1277                         flag |= lyx::getStatus(fr);
1278                 }
1279                 enable = flag.enabled();
1280                 break;
1281         }
1282
1283         case LFUN_COMPLETION_INLINE:
1284                 if (!d.current_work_area_
1285                     || !d.current_work_area_->completer().inlinePossible(
1286                         currentBufferView()->cursor()))
1287                     enable = false;
1288                 break;
1289
1290         case LFUN_COMPLETION_POPUP:
1291                 if (!d.current_work_area_
1292                     || !d.current_work_area_->completer().popupPossible(
1293                         currentBufferView()->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(
1300                         currentBufferView()->cursor()))
1301                     enable = false;
1302                 break;
1303
1304         case LFUN_COMPLETION_ACCEPT:
1305                 if (!d.current_work_area_
1306                     || (!d.current_work_area_->completer().popupVisible()
1307                         && !d.current_work_area_->completer().inlineVisible()
1308                         && !d.current_work_area_->completer().completionAvailable()))
1309                         enable = false;
1310                 break;
1311
1312         case LFUN_COMPLETION_CANCEL:
1313                 if (!d.current_work_area_
1314                     || (!d.current_work_area_->completer().popupVisible()
1315                         && !d.current_work_area_->completer().inlineVisible()))
1316                         enable = false;
1317                 break;
1318
1319         case LFUN_BUFFER_ZOOM_OUT:
1320                 enable = buf && lyxrc.zoom > 10;
1321                 break;
1322
1323         case LFUN_BUFFER_ZOOM_IN:
1324                 enable = buf;
1325                 break;
1326
1327         default:
1328                 return false;
1329         }
1330
1331         if (!enable)
1332                 flag.setEnabled(false);
1333
1334         return true;
1335 }
1336
1337
1338 static FileName selectTemplateFile()
1339 {
1340         FileDialog dlg(qt_("Select template file"));
1341         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1342         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1343
1344         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1345                              QStringList(qt_("LyX Documents (*.lyx)")));
1346
1347         if (result.first == FileDialog::Later)
1348                 return FileName();
1349         if (result.second.isEmpty())
1350                 return FileName();
1351         return FileName(fromqstr(result.second));
1352 }
1353
1354
1355 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1356 {
1357         setBusy(true);
1358
1359         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1360
1361         if (!newBuffer) {
1362                 message(_("Document not loaded."));
1363                 setBusy(false);
1364                 return 0;
1365         }
1366         
1367         setBuffer(newBuffer);
1368
1369         // scroll to the position when the file was last closed
1370         if (lyxrc.use_lastfilepos) {
1371                 LastFilePosSection::FilePos filepos =
1372                         theSession().lastFilePos().load(filename);
1373                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1374         }
1375
1376         if (tolastfiles)
1377                 theSession().lastFiles().add(filename);
1378
1379         setBusy(false);
1380         return newBuffer;
1381 }
1382
1383
1384 void GuiView::openDocument(string const & fname)
1385 {
1386         string initpath = lyxrc.document_path;
1387
1388         if (documentBufferView()) {
1389                 string const trypath = documentBufferView()->buffer().filePath();
1390                 // If directory is writeable, use this as default.
1391                 if (FileName(trypath).isDirWritable())
1392                         initpath = trypath;
1393         }
1394
1395         string filename;
1396
1397         if (fname.empty()) {
1398                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1399                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1400                 dlg.setButton2(qt_("Examples|#E#e"),
1401                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1402
1403                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1404                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1405                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1406                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1407                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1408                 FileDialog::Result result =
1409                         dlg.open(toqstr(initpath), filter);
1410
1411                 if (result.first == FileDialog::Later)
1412                         return;
1413
1414                 filename = fromqstr(result.second);
1415
1416                 // check selected filename
1417                 if (filename.empty()) {
1418                         message(_("Canceled."));
1419                         return;
1420                 }
1421         } else
1422                 filename = fname;
1423
1424         // get absolute path of file and add ".lyx" to the filename if
1425         // necessary. 
1426         FileName const fullname = 
1427                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1428         if (!fullname.empty())
1429                 filename = fullname.absFilename();
1430
1431         if (!fullname.onlyPath().isDirectory()) {
1432                 Alert::warning(_("Invalid filename"),
1433                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1434                                 from_utf8(fullname.absFilename())));
1435                 return;
1436         }
1437         // if the file doesn't exist, let the user create one
1438         if (!fullname.exists()) {
1439                 // the user specifically chose this name. Believe him.
1440                 Buffer * const b = newFile(filename, string(), true);
1441                 if (b)
1442                         setBuffer(b);
1443                 return;
1444         }
1445
1446         docstring const disp_fn = makeDisplayPath(filename);
1447         message(bformat(_("Opening document %1$s..."), disp_fn));
1448
1449         docstring str2;
1450         Buffer * buf = loadDocument(fullname);
1451         if (buf) {
1452                 buf->updateLabels();
1453                 setBuffer(buf);
1454                 buf->errors("Parse");
1455                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1456                 if (buf->lyxvc().inUse())
1457                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1458                                 " " + _("Version control detected.");
1459         } else {
1460                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1461         }
1462         message(str2);
1463 }
1464
1465 // FIXME: clean that
1466 static bool import(GuiView * lv, FileName const & filename,
1467         string const & format, ErrorList & errorList)
1468 {
1469         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1470
1471         string loader_format;
1472         vector<string> loaders = theConverters().loaders();
1473         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1474                 for (vector<string>::const_iterator it = loaders.begin();
1475                      it != loaders.end(); ++it) {
1476                         if (!theConverters().isReachable(format, *it))
1477                                 continue;
1478
1479                         string const tofile =
1480                                 support::changeExtension(filename.absFilename(),
1481                                 formats.extension(*it));
1482                         if (!theConverters().convert(0, filename, FileName(tofile),
1483                                 filename, format, *it, errorList))
1484                                 return false;
1485                         loader_format = *it;
1486                         break;
1487                 }
1488                 if (loader_format.empty()) {
1489                         frontend::Alert::error(_("Couldn't import file"),
1490                                      bformat(_("No information for importing the format %1$s."),
1491                                          formats.prettyName(format)));
1492                         return false;
1493                 }
1494         } else
1495                 loader_format = format;
1496
1497         if (loader_format == "lyx") {
1498                 Buffer * buf = lv->loadDocument(lyxfile);
1499                 if (!buf)
1500                         return false;
1501                 buf->updateLabels();
1502                 lv->setBuffer(buf);
1503                 buf->errors("Parse");
1504         } else {
1505                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1506                 if (!b)
1507                         return false;
1508                 lv->setBuffer(b);
1509                 bool as_paragraphs = loader_format == "textparagraph";
1510                 string filename2 = (loader_format == format) ? filename.absFilename()
1511                         : support::changeExtension(filename.absFilename(),
1512                                           formats.extension(loader_format));
1513                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1514                         as_paragraphs);
1515                 theLyXFunc().setLyXView(lv);
1516                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1517         }
1518
1519         return true;
1520 }
1521
1522
1523 void GuiView::importDocument(string const & argument)
1524 {
1525         string format;
1526         string filename = split(argument, format, ' ');
1527
1528         LYXERR(Debug::INFO, format << " file: " << filename);
1529
1530         // need user interaction
1531         if (filename.empty()) {
1532                 string initpath = lyxrc.document_path;
1533                 if (documentBufferView()) {
1534                         string const trypath = documentBufferView()->buffer().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         if (documentBufferView()) {
1617                 FileName const trypath(documentBufferView()->buffer().filePath());
1618                 // If directory is writeable, use this as default.
1619                 if (trypath.isDirWritable())
1620                         initpath = trypath;
1621         }
1622
1623         string templatefile;
1624         if (from_template) {
1625                 templatefile = selectTemplateFile().absFilename();
1626                 if (templatefile.empty())
1627                         return;
1628         }
1629         
1630         Buffer * b;
1631         if (filename.empty())
1632                 b = newUnnamedFile(templatefile, initpath);
1633         else
1634                 b = newFile(filename, templatefile, true);
1635
1636         if (b)
1637                 setBuffer(b);
1638
1639         // If no new document could be created, it is unsure 
1640         // whether there is a valid BufferView.
1641         if (currentBufferView())
1642                 // Ensure the cursor is correctly positioned on screen.
1643                 currentBufferView()->showCursor();
1644 }
1645
1646
1647 void GuiView::insertLyXFile(docstring const & fname)
1648 {
1649         BufferView * bv = documentBufferView();
1650         if (!bv)
1651                 return;
1652
1653         // FIXME UNICODE
1654         FileName filename(to_utf8(fname));
1655         
1656         if (!filename.empty()) {
1657                 bv->insertLyXFile(filename);
1658                 return;
1659         }
1660
1661         // Launch a file browser
1662         // FIXME UNICODE
1663         string initpath = lyxrc.document_path;
1664         string const trypath = bv->buffer().filePath();
1665         // If directory is writeable, use this as default.
1666         if (FileName(trypath).isDirWritable())
1667                 initpath = trypath;
1668
1669         // FIXME UNICODE
1670         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1671         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1672         dlg.setButton2(qt_("Examples|#E#e"),
1673                 toqstr(addPath(package().system_support().absFilename(),
1674                 "examples")));
1675
1676         FileDialog::Result result = dlg.open(toqstr(initpath),
1677                              QStringList(qt_("LyX Documents (*.lyx)")));
1678
1679         if (result.first == FileDialog::Later)
1680                 return;
1681
1682         // FIXME UNICODE
1683         filename.set(fromqstr(result.second));
1684
1685         // check selected filename
1686         if (filename.empty()) {
1687                 // emit message signal.
1688                 message(_("Canceled."));
1689                 return;
1690         }
1691
1692         bv->insertLyXFile(filename);
1693 }
1694
1695
1696 void GuiView::insertPlaintextFile(docstring const & fname,
1697         bool asParagraph)
1698 {
1699         BufferView * bv = documentBufferView();
1700         if (!bv)
1701                 return;
1702
1703         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1704                 message(_("Absolute filename expected."));
1705                 return;
1706         }
1707
1708         // FIXME UNICODE
1709         FileName filename(to_utf8(fname));
1710         
1711         if (!filename.empty()) {
1712                 bv->insertPlaintextFile(filename, asParagraph);
1713                 return;
1714         }
1715
1716         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1717                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1718
1719         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1720                 QStringList(qt_("All Files (*)")));
1721
1722         if (result.first == FileDialog::Later)
1723                 return;
1724
1725         // FIXME UNICODE
1726         filename.set(fromqstr(result.second));
1727
1728         // check selected filename
1729         if (filename.empty()) {
1730                 // emit message signal.
1731                 message(_("Canceled."));
1732                 return;
1733         }
1734
1735         bv->insertPlaintextFile(filename, asParagraph);
1736 }
1737
1738
1739 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1740 {
1741         FileName fname = b.fileName();
1742         FileName const oldname = fname;
1743
1744         if (!newname.empty()) {
1745                 // FIXME UNICODE
1746                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1747         } else {
1748                 // Switch to this Buffer.
1749                 setBuffer(&b);
1750
1751                 // No argument? Ask user through dialog.
1752                 // FIXME UNICODE
1753                 FileDialog dlg(qt_("Choose a filename to save document as"),
1754                                    LFUN_BUFFER_WRITE_AS);
1755                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1756                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1757
1758                 if (!isLyXFilename(fname.absFilename()))
1759                         fname.changeExtension(".lyx");
1760
1761                 FileDialog::Result result =
1762                         dlg.save(toqstr(fname.onlyPath().absFilename()),
1763                                QStringList(qt_("LyX Documents (*.lyx)")),
1764                                      toqstr(fname.onlyFileName()));
1765
1766                 if (result.first == FileDialog::Later)
1767                         return false;
1768
1769                 fname.set(fromqstr(result.second));
1770
1771                 if (fname.empty())
1772                         return false;
1773
1774                 if (!isLyXFilename(fname.absFilename()))
1775                         fname.changeExtension(".lyx");
1776         }
1777
1778         if (FileName(fname).exists()) {
1779                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1780                 docstring text = bformat(_("The document %1$s already "
1781                                            "exists.\n\nDo you want to "
1782                                            "overwrite that document?"), 
1783                                          file);
1784                 int const ret = Alert::prompt(_("Overwrite document?"),
1785                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1786                 switch (ret) {
1787                 case 0: break;
1788                 case 1: return renameBuffer(b, docstring());
1789                 case 2: return false;
1790                 }
1791         }
1792
1793         FileName oldauto = b.getAutosaveFilename();
1794
1795         // Ok, change the name of the buffer
1796         b.setFileName(fname.absFilename());
1797         b.markDirty();
1798         bool unnamed = b.isUnnamed();
1799         b.setUnnamed(false);
1800         b.saveCheckSum(fname);
1801
1802         // bring the autosave file with us, just in case.
1803         b.moveAutosaveFile(oldauto);
1804         
1805         if (!saveBuffer(b)) {
1806                 oldauto = b.getAutosaveFilename();
1807                 b.setFileName(oldname.absFilename());
1808                 b.setUnnamed(unnamed);
1809                 b.saveCheckSum(oldname);
1810                 b.moveAutosaveFile(oldauto);
1811                 return false;
1812         }
1813
1814         return true;
1815 }
1816
1817
1818 bool GuiView::saveBuffer(Buffer & b)
1819 {
1820         if (workArea(b) && workArea(b)->inDialogMode())
1821                 return true;
1822
1823         if (b.isUnnamed())
1824                 return renameBuffer(b, docstring());
1825
1826         if (b.save()) {
1827                 theSession().lastFiles().add(b.fileName());
1828                 return true;
1829         }
1830
1831         // Switch to this Buffer.
1832         setBuffer(&b);
1833
1834         // FIXME: we don't tell the user *WHY* the save failed !!
1835         docstring const file = makeDisplayPath(b.absFileName(), 30);
1836         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1837                                    "Do you want to rename the document and "
1838                                    "try again?"), file);
1839         int const ret = Alert::prompt(_("Rename and save?"),
1840                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1841         switch (ret) {
1842         case 0:
1843                 if (!renameBuffer(b, docstring()))
1844                         return false;
1845                 break;
1846         case 1:
1847                 break;
1848         case 2:
1849                 return false;
1850         }
1851
1852         return saveBuffer(b);
1853 }
1854
1855
1856 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1857 {
1858         return closeWorkArea(wa, false);
1859 }
1860
1861
1862 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1863 {
1864         Buffer & buf = wa->bufferView().buffer();
1865         return closeWorkArea(wa, !buf.parent());
1866 }
1867
1868
1869 bool GuiView::closeBuffer()
1870 {
1871         GuiWorkArea * wa = currentMainWorkArea();
1872         Buffer & buf = wa->bufferView().buffer();
1873         return wa && closeWorkArea(wa, !buf.parent());
1874 }
1875
1876
1877 void GuiView::writeSession() const {
1878         GuiWorkArea const * active_wa = currentMainWorkArea();
1879         for (int i = 0; i < d.splitter_->count(); ++i) {
1880                 TabWorkArea * twa = d.tabWorkArea(i);
1881                 for (int j = 0; j < twa->count(); ++j) {
1882                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1883                         Buffer & buf = wa->bufferView().buffer();
1884                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1885                 }
1886         }
1887 }
1888
1889
1890 bool GuiView::closeBufferAll()
1891 {
1892         // Close the workareas in all other views
1893         QList<int> const ids = guiApp->viewIds();
1894         for (int i = 0; i != ids.size(); ++i) {
1895                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
1896                         return false;
1897         }
1898
1899         // Close our own workareas
1900         if (!closeWorkAreaAll())
1901                 return false;
1902
1903         // Now close the hidden buffers. We prevent hidden buffers from being
1904         // dirty, so we can just close them.
1905         theBufferList().closeAll();
1906         return true;
1907 }
1908
1909
1910 bool GuiView::closeWorkAreaAll()
1911 {
1912         setCurrentWorkArea(currentMainWorkArea());
1913
1914         // We might be in a situation that there is still a tabWorkArea, but
1915         // there are no tabs anymore. This can happen when we get here after a 
1916         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
1917         // many TabWorkArea's have no documents anymore.
1918         int empty_twa = 0;
1919
1920         // We have to call count() each time, because it can happen that
1921         // more than one splitter will disappear in one iteration (bug 5998).
1922         for (; d.splitter_->count() > empty_twa; ) {
1923                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
1924
1925                 if (twa->count() == 0)
1926                         ++empty_twa;
1927                 else {
1928                         setCurrentWorkArea(twa->currentWorkArea());
1929                         if (!closeTabWorkArea(twa))
1930                                 return false;
1931                 }
1932         }
1933         return true;
1934 }
1935
1936
1937 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
1938 {
1939         Buffer & buf = wa->bufferView().buffer();
1940
1941         // If we are in a close_event all children will be closed in some time,
1942         // so no need to do it here. This will ensure that the children end up
1943         // in the session file in the correct order. If we close the master
1944         // buffer, we can close or release the child buffers here too.
1945         if (close_buffer && !closing_) {
1946                 vector<Buffer *> clist = buf.getChildren();
1947                 for (vector<Buffer *>::const_iterator it = clist.begin();
1948                          it != clist.end(); ++it) {
1949                         // If a child is dirty, do not close
1950                         // without user intervention
1951                         //FIXME: should we look in other tabworkareas?
1952                         Buffer * child_buf = *it;
1953                         GuiWorkArea * child_wa = workArea(*child_buf);
1954                         if (child_wa) {
1955                                 if (!closeWorkArea(child_wa, true))
1956                                         return false;
1957                         } else
1958                                 theBufferList().releaseChild(&buf, child_buf);
1959                 }
1960         }
1961         // goto bookmark to update bookmark pit.
1962         //FIXME: we should update only the bookmarks related to this buffer!
1963         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
1964         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1965                 theLyXFunc().gotoBookmark(i+1, false, false);
1966
1967         // if we are only hiding the buffer and there are multiple views
1968         // of the buffer, then we do not need to ensure a clean buffer.
1969         bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
1970
1971         if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
1972                 // save in sessions if requested
1973                 // do not save childs if their master
1974                 // is opened as well
1975                 if (!close_buffer)
1976                         removeWorkArea(wa);
1977                 else
1978                         theBufferList().release(&buf);
1979                 return true;
1980         }
1981         return false;
1982 }
1983
1984
1985 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
1986 {
1987         while (twa == d.currentTabWorkArea()) {
1988                 twa->setCurrentIndex(twa->count()-1);
1989
1990                 GuiWorkArea * wa = twa->currentWorkArea();
1991                 Buffer & b = wa->bufferView().buffer();
1992
1993                 // We only want to close the buffer if the same buffer is not visible
1994                 // in another view, and if this is not a child and if we are closing
1995                 // a view (not a tabgroup).
1996                 bool const close_buffer = 
1997                         !inMultiViews(wa) && !b.parent() && closing_;
1998
1999                 if (!closeWorkArea(wa, close_buffer))
2000                         return false;
2001         }
2002         return true;
2003 }
2004
2005
2006 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2007 {
2008         if (buf.isClean() || buf.paragraphs().empty())
2009                 return true;
2010
2011         // Switch to this Buffer.
2012         setBuffer(&buf);
2013
2014         docstring file;
2015         // FIXME: Unicode?
2016         if (buf.isUnnamed())
2017                 file = from_utf8(buf.fileName().onlyFileName());
2018         else
2019                 file = buf.fileName().displayName(30);
2020
2021         // Bring this window to top before asking questions.
2022         raise();
2023         activateWindow();
2024
2025         int ret;
2026         if (hiding && buf.isUnnamed()) {
2027                 docstring const text = bformat(_("The document %1$s has not been "
2028                                              "saved yet.\n\nDo you want to save "
2029                                              "the document?"), file);
2030                 ret = Alert::prompt(_("Save new document?"), 
2031                         text, 0, 1, _("&Save"), _("&Cancel"));
2032                 if (ret == 1)
2033                         ++ret;
2034         } else {
2035                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2036                         "\n\nDo you want to save the document or discard the changes?"), file);
2037                 ret = Alert::prompt(_("Save changed document?"),
2038                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2039         }
2040
2041         switch (ret) {
2042         case 0:
2043                 if (!saveBuffer(buf))
2044                         return false;
2045                 break;
2046         case 1:
2047                 // if we crash after this we could
2048                 // have no autosave file but I guess
2049                 // this is really improbable (Jug)
2050                 buf.removeAutosaveFile();
2051                 if (hiding)
2052                         // revert all changes
2053                         buf.loadLyXFile(buf.fileName());
2054                 buf.markClean();
2055                 break;
2056         case 2:
2057                 return false;
2058         }
2059         return true;
2060 }
2061
2062
2063 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2064 {
2065         Buffer & buf = wa->bufferView().buffer();
2066
2067         for (int i = 0; i != d.splitter_->count(); ++i) {
2068                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2069                 if (wa_ && wa_ != wa)
2070                         return true;
2071         }
2072         return inMultiViews(wa);
2073 }
2074
2075
2076 bool GuiView::inMultiViews(GuiWorkArea * wa)
2077 {
2078         QList<int> const ids = guiApp->viewIds();
2079         Buffer & buf = wa->bufferView().buffer();
2080
2081         int found_twa = 0;
2082         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2083                 if (id_ == ids[i])
2084                         continue;
2085                 
2086                 if (guiApp->view(ids[i]).workArea(buf))
2087                         return true;
2088         }
2089         return false;
2090 }
2091
2092
2093 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2094 {
2095         Buffer * const curbuf = documentBufferView()
2096                 ? &documentBufferView()->buffer() : 0;
2097         Buffer * nextbuf = curbuf;
2098         while (true) {
2099                 if (np == NEXTBUFFER)
2100                         nextbuf = theBufferList().next(nextbuf);
2101                 else
2102                         nextbuf = theBufferList().previous(nextbuf);
2103                 if (nextbuf == curbuf)
2104                         break;
2105                 if (nextbuf == 0) {
2106                         nextbuf = curbuf;
2107                         break;
2108                 }
2109                 if (workArea(*nextbuf))
2110                         break;
2111         }
2112         setBuffer(nextbuf);
2113 }
2114
2115
2116 bool GuiView::dispatch(FuncRequest const & cmd)
2117 {
2118         BufferView * bv = currentBufferView();
2119         // By default we won't need any update.
2120         if (bv)
2121                 bv->cursor().updateFlags(Update::None);
2122         bool dispatched = true;
2123
2124         if (cmd.origin == FuncRequest::TOC) {
2125                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2126                 toc->doDispatch(bv->cursor(), cmd);
2127                 return true;
2128         }
2129
2130         switch(cmd.action) {
2131                 case LFUN_BUFFER_IMPORT:
2132                         importDocument(to_utf8(cmd.argument()));
2133                         break;
2134
2135                 case LFUN_BUFFER_SWITCH:
2136                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2137                                 Buffer * buffer = 
2138                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2139                                 if (buffer)
2140                                         setBuffer(buffer);
2141                                 else
2142                                         bv->cursor().message(_("Document not loaded"));
2143                         }
2144                         break;
2145
2146                 case LFUN_BUFFER_NEXT:
2147                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2148                         break;
2149
2150                 case LFUN_BUFFER_PREVIOUS:
2151                         gotoNextOrPreviousBuffer(PREVBUFFER);
2152                         break;
2153
2154                 case LFUN_COMMAND_EXECUTE: {
2155                         bool const show_it = cmd.argument() != "off";
2156                         // FIXME: this is a hack, "minibuffer" should not be
2157                         // hardcoded.
2158                         if (GuiToolbar * t = toolbar("minibuffer")) {
2159                                 t->setVisible(show_it);
2160                                 if (show_it && t->commandBuffer())
2161                                         t->commandBuffer()->setFocus();
2162                         }
2163                         break;
2164                 }
2165                 case LFUN_DROP_LAYOUTS_CHOICE:
2166                         d.layout_->showPopup();
2167                         break;
2168
2169                 case LFUN_MENU_OPEN:
2170                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2171                                 menu->exec(QCursor::pos());
2172                         break;
2173
2174                 case LFUN_FILE_INSERT:
2175                         insertLyXFile(cmd.argument());
2176                         break;
2177                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2178                         insertPlaintextFile(cmd.argument(), true);
2179                         break;
2180
2181                 case LFUN_FILE_INSERT_PLAINTEXT:
2182                         insertPlaintextFile(cmd.argument(), false);
2183                         break;
2184
2185                 case LFUN_BUFFER_WRITE:
2186                         if (bv)
2187                                 saveBuffer(bv->buffer());
2188                         break;
2189
2190                 case LFUN_BUFFER_WRITE_AS:
2191                         if (bv)
2192                                 renameBuffer(bv->buffer(), cmd.argument());
2193                         break;
2194
2195                 case LFUN_BUFFER_WRITE_ALL: {
2196                         Buffer * first = theBufferList().first();
2197                         if (!first)
2198                                 break;
2199                         message(_("Saving all documents..."));
2200                         // We cannot use a for loop as the buffer list cycles.
2201                         Buffer * b = first;
2202                         do {
2203                                 if (!b->isClean()) {
2204                                         saveBuffer(*b);
2205                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2206                                 }
2207                                 b = theBufferList().next(b);
2208                         } while (b != first); 
2209                         message(_("All documents saved."));
2210                         break;
2211                 }
2212
2213                 case LFUN_TOOLBAR_TOGGLE: {
2214                         string const name = cmd.getArg(0);
2215                         if (GuiToolbar * t = toolbar(name))
2216                                 t->toggle();
2217                         break;
2218                 }
2219
2220                 case LFUN_DIALOG_UPDATE: {
2221                         string const name = to_utf8(cmd.argument());
2222                         // Can only update a dialog connected to an existing inset
2223                         Inset * inset = getOpenInset(name);
2224                         if (inset) {
2225                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2226                                 inset->dispatch(currentBufferView()->cursor(), fr);
2227                         } else if (name == "paragraph") {
2228                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2229                         } else if (name == "prefs" || name == "document") {
2230                                 updateDialog(name, string());
2231                         }
2232                         break;
2233                 }
2234
2235                 case LFUN_DIALOG_TOGGLE: {
2236                         if (isDialogVisible(cmd.getArg(0)))
2237                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2238                         else
2239                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2240                         break;
2241                 }
2242
2243                 case LFUN_DIALOG_DISCONNECT_INSET:
2244                         disconnectDialog(to_utf8(cmd.argument()));
2245                         break;
2246
2247                 case LFUN_DIALOG_HIDE: {
2248                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2249                         break;
2250                 }
2251
2252                 case LFUN_DIALOG_SHOW: {
2253                         string const name = cmd.getArg(0);
2254                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2255
2256                         if (name == "character") {
2257                                 data = freefont2string();
2258                                 if (!data.empty())
2259                                         showDialog("character", data);
2260                         } else if (name == "latexlog") {
2261                                 Buffer::LogType type; 
2262                                 string const logfile = documentBufferView()->buffer().logName(&type);
2263                                 switch (type) {
2264                                 case Buffer::latexlog:
2265                                         data = "latex ";
2266                                         break;
2267                                 case Buffer::buildlog:
2268                                         data = "literate ";
2269                                         break;
2270                                 }
2271                                 data += Lexer::quoteString(logfile);
2272                                 showDialog("log", data);
2273                         } else if (name == "vclog") {
2274                                 string const data = "vc " +
2275                                         Lexer::quoteString(documentBufferView()->buffer().lyxvc().getLogFile());
2276                                 showDialog("log", data);
2277                         } else if (name == "symbols") {
2278                                 data = bv->cursor().getEncoding()->name();
2279                                 if (!data.empty())
2280                                         showDialog("symbols", data);
2281                         // bug 5274
2282                         } else if (name == "prefs" && isFullScreen()) {
2283                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2284                                 lfunUiToggle(fr);
2285                                 showDialog("prefs", data);
2286                         } else
2287                                 showDialog(name, data);
2288                         break;
2289                 }
2290
2291                 case LFUN_INSET_APPLY: {
2292                         string const name = cmd.getArg(0);
2293                         Inset * inset = getOpenInset(name);
2294                         if (inset) {
2295                                 // put cursor in front of inset.
2296                                 if (!currentBufferView()->setCursorFromInset(inset)) {
2297                                         LASSERT(false, break);
2298                                 }
2299                                 BufferView * bv = currentBufferView();
2300                                 // useful if we are called from a dialog.
2301                                 bv->cursor().beginUndoGroup();
2302                                 bv->cursor().recordUndo();
2303                                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2304                                 inset->dispatch(bv->cursor(), fr);
2305                                 bv->cursor().endUndoGroup();
2306                         } else {
2307                                 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2308                                 lyx::dispatch(fr);
2309                         }
2310                         break;
2311                 }
2312
2313                 case LFUN_UI_TOGGLE:
2314                         lfunUiToggle(cmd);
2315                         // Make sure the keyboard focus stays in the work area.
2316                         setFocus();
2317                         break;
2318
2319                 case LFUN_SPLIT_VIEW:
2320                         if (documentBufferView()) {
2321                                 string const orientation = cmd.getArg(0);
2322                                 d.splitter_->setOrientation(orientation == "vertical"
2323                                         ? Qt::Vertical : Qt::Horizontal);
2324                                 TabWorkArea * twa = addTabWorkArea();
2325                                 GuiWorkArea * wa = twa->addWorkArea(documentBufferView()->buffer(), *this);
2326                                 setCurrentWorkArea(wa);
2327                         }
2328                         break;
2329
2330                 case LFUN_CLOSE_TAB_GROUP:
2331                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2332                                 closeTabWorkArea(twa);
2333                                 d.current_work_area_ = 0;
2334                                 twa = d.currentTabWorkArea();
2335                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2336                                 if (twa) {
2337                                         // Make sure the work area is up to date.
2338                                         setCurrentWorkArea(twa->currentWorkArea());
2339                                 } else {
2340                                         setCurrentWorkArea(0);
2341                                 }
2342                         }
2343                         break;
2344                         
2345                 case LFUN_COMPLETION_INLINE:
2346                         if (d.current_work_area_)
2347                                 d.current_work_area_->completer().showInline();
2348                         break;
2349
2350                 case LFUN_COMPLETION_POPUP:
2351                         if (d.current_work_area_)
2352                                 d.current_work_area_->completer().showPopup();
2353                         break;
2354
2355
2356                 case LFUN_COMPLETION_COMPLETE:
2357                         if (d.current_work_area_)
2358                                 d.current_work_area_->completer().tab();
2359                         break;
2360
2361                 case LFUN_COMPLETION_CANCEL:
2362                         if (d.current_work_area_) {
2363                                 if (d.current_work_area_->completer().popupVisible())
2364                                         d.current_work_area_->completer().hidePopup();
2365                                 else
2366                                         d.current_work_area_->completer().hideInline();
2367                         }
2368                         break;
2369
2370                 case LFUN_COMPLETION_ACCEPT:
2371                         if (d.current_work_area_)
2372                                 d.current_work_area_->completer().activate();
2373                         break;
2374
2375                 case LFUN_BUFFER_ZOOM_IN:
2376                 case LFUN_BUFFER_ZOOM_OUT:
2377                         if (cmd.argument().empty()) {
2378                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2379                                         lyxrc.zoom += 20;
2380                                 else
2381                                         lyxrc.zoom -= 20;
2382                         } else
2383                                 lyxrc.zoom += convert<int>(cmd.argument());
2384
2385                         if (lyxrc.zoom < 10)
2386                                 lyxrc.zoom = 10;
2387                                 
2388                         // The global QPixmapCache is used in GuiPainter to cache text
2389                         // painting so we must reset it.
2390                         QPixmapCache::clear();
2391                         guiApp->fontLoader().update();
2392                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2393                         break;
2394
2395                 default:
2396                         dispatched = false;
2397                         break;
2398         }
2399
2400         // Part of automatic menu appearance feature.
2401         if (isFullScreen()) {
2402                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2403                         menuBar()->hide();
2404                 if (statusBar()->isVisible())
2405                         statusBar()->hide();
2406         }
2407
2408         return dispatched;
2409 }
2410
2411
2412 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2413 {
2414         string const arg = cmd.getArg(0);
2415         if (arg == "scrollbar") {
2416                 // hide() is of no help
2417                 if (d.current_work_area_->verticalScrollBarPolicy() ==
2418                         Qt::ScrollBarAlwaysOff)
2419
2420                         d.current_work_area_->setVerticalScrollBarPolicy(
2421                                 Qt::ScrollBarAsNeeded);
2422                 else
2423                         d.current_work_area_->setVerticalScrollBarPolicy(
2424                                 Qt::ScrollBarAlwaysOff);
2425                 return;
2426         }
2427         if (arg == "statusbar") {
2428                 statusBar()->setVisible(!statusBar()->isVisible());
2429                 return;
2430         }
2431         if (arg == "menubar") {
2432                 menuBar()->setVisible(!menuBar()->isVisible());
2433                 return;
2434         }
2435 #if QT_VERSION >= 0x040300
2436         if (arg == "frame") {
2437                 int l, t, r, b;
2438                 getContentsMargins(&l, &t, &r, &b);
2439                 //are the frames in default state?
2440                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2441                 if (l == 0) {
2442                         setContentsMargins(-2, -2, -2, -2);
2443                 } else {
2444                         setContentsMargins(0, 0, 0, 0);
2445                 }
2446                 return;
2447         }
2448 #endif
2449         if (arg == "fullscreen") {
2450                 toggleFullScreen();
2451                 return;
2452         }
2453
2454         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2455 }
2456
2457
2458 void GuiView::toggleFullScreen()
2459 {
2460         if (isFullScreen()) {
2461                 for (int i = 0; i != d.splitter_->count(); ++i)
2462                         d.tabWorkArea(i)->setFullScreen(false);
2463 #if QT_VERSION >= 0x040300
2464                 setContentsMargins(0, 0, 0, 0);
2465 #endif
2466                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2467                 restoreLayout();
2468                 menuBar()->show();
2469                 statusBar()->show();
2470         } else {
2471                 // bug 5274
2472                 hideDialogs("prefs", 0);
2473                 for (int i = 0; i != d.splitter_->count(); ++i)
2474                         d.tabWorkArea(i)->setFullScreen(true);
2475 #if QT_VERSION >= 0x040300
2476                 setContentsMargins(-2, -2, -2, -2);
2477 #endif
2478                 saveLayout();
2479                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2480                 statusBar()->hide();
2481                 if (lyxrc.full_screen_menubar)
2482                         menuBar()->hide();
2483                 if (lyxrc.full_screen_toolbars) {
2484                         ToolbarMap::iterator end = d.toolbars_.end();
2485                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2486                                 it->second->hide();
2487                 }
2488         }
2489
2490         // give dialogs like the TOC a chance to adapt
2491         updateDialogs();
2492 }
2493
2494
2495 Buffer const * GuiView::updateInset(Inset const * inset)
2496 {
2497         if (!d.current_work_area_)
2498                 return 0;
2499
2500         if (inset)
2501                 d.current_work_area_->scheduleRedraw();
2502
2503         return &d.current_work_area_->bufferView().buffer();
2504 }
2505
2506
2507 void GuiView::restartCursor()
2508 {
2509         /* When we move around, or type, it's nice to be able to see
2510          * the cursor immediately after the keypress.
2511          */
2512         if (d.current_work_area_)
2513                 d.current_work_area_->startBlinkingCursor();
2514
2515         // Take this occasion to update the other GUI elements.
2516         updateDialogs();
2517         updateStatusBar();
2518 }
2519
2520
2521 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2522 {
2523         if (d.current_work_area_)
2524                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2525 }
2526
2527 namespace {
2528
2529 // This list should be kept in sync with the list of insets in
2530 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
2531 // dialog should have the same name as the inset.
2532 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2533 // docs in LyXAction.cpp.
2534
2535 char const * const dialognames[] = {
2536 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2537 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2538 "findreplaceadv", "float", "graphics", "href", "include", "index",
2539 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2540 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2541 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2542 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2543 "toc", "view-source", "vspace", "wrap" };
2544
2545 char const * const * const end_dialognames =
2546         dialognames + (sizeof(dialognames) / sizeof(char *));
2547
2548 class cmpCStr {
2549 public:
2550         cmpCStr(char const * name) : name_(name) {}
2551         bool operator()(char const * other) {
2552                 return strcmp(other, name_) == 0;
2553         }
2554 private:
2555         char const * name_;
2556 };
2557
2558
2559 bool isValidName(string const & name)
2560 {
2561         return find_if(dialognames, end_dialognames,
2562                             cmpCStr(name.c_str())) != end_dialognames;
2563 }
2564
2565 } // namespace anon
2566
2567
2568 void GuiView::resetDialogs()
2569 {
2570         // Make sure that no LFUN uses any LyXView.
2571         theLyXFunc().setLyXView(0);
2572         saveLayout();
2573         menuBar()->clear();
2574         constructToolbars();
2575         guiApp->menus().fillMenuBar(menuBar(), this, false);
2576         d.layout_->updateContents(true);
2577         // Now update controls with current buffer.
2578         theLyXFunc().setLyXView(this);
2579         restoreLayout();
2580         restartCursor();
2581 }
2582
2583
2584 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2585 {
2586         if (!isValidName(name))
2587                 return 0;
2588
2589         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2590
2591         if (it != d.dialogs_.end()) {
2592                 if (hide_it)
2593                         it->second->hideView();
2594                 return it->second.get();
2595         }
2596
2597         Dialog * dialog = build(name);
2598         d.dialogs_[name].reset(dialog);
2599         if (lyxrc.allow_geometry_session)
2600                 dialog->restoreSession();
2601         if (hide_it)
2602                 dialog->hideView();
2603         return dialog;
2604 }
2605
2606
2607 void GuiView::showDialog(string const & name, string const & data,
2608         Inset * inset)
2609 {
2610         if (d.in_show_)
2611                 return;
2612
2613         d.in_show_ = true;
2614         try {
2615                 Dialog * dialog = findOrBuild(name, false);
2616                 if (dialog) {
2617                         dialog->showData(data);
2618                         if (inset)
2619                                 d.open_insets_[name] = inset;
2620                 }
2621         }
2622         catch (ExceptionMessage const & ex) {
2623                 d.in_show_ = false;
2624                 throw ex;
2625         }
2626         d.in_show_ = false;
2627 }
2628
2629
2630 bool GuiView::isDialogVisible(string const & name) const
2631 {
2632         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2633         if (it == d.dialogs_.end())
2634                 return false;
2635         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2636 }
2637
2638
2639 void GuiView::hideDialog(string const & name, Inset * inset)
2640 {
2641         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2642         if (it == d.dialogs_.end())
2643                 return;
2644
2645         if (inset && inset != getOpenInset(name))
2646                 return;
2647
2648         Dialog * const dialog = it->second.get();
2649         if (dialog->isVisibleView())
2650                 dialog->hideView();
2651         d.open_insets_[name] = 0;
2652 }
2653
2654
2655 void GuiView::disconnectDialog(string const & name)
2656 {
2657         if (!isValidName(name))
2658                 return;
2659
2660         if (d.open_insets_.find(name) != d.open_insets_.end())
2661                 d.open_insets_[name] = 0;
2662 }
2663
2664
2665 Inset * GuiView::getOpenInset(string const & name) const
2666 {
2667         if (!isValidName(name))
2668                 return 0;
2669
2670         map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2671         return it == d.open_insets_.end() ? 0 : it->second;
2672 }
2673
2674
2675 void GuiView::hideAll() const
2676 {
2677         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2678         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2679
2680         for(; it != end; ++it)
2681                 it->second->hideView();
2682 }
2683
2684
2685 void GuiView::updateDialogs()
2686 {
2687         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2688         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2689
2690         for(; it != end; ++it) {
2691                 Dialog * dialog = it->second.get();
2692                 if (dialog && dialog->isVisibleView())
2693                         dialog->checkStatus();
2694         }
2695         updateToolbars();
2696         updateLayoutList();
2697 }
2698
2699
2700 // will be replaced by a proper factory...
2701 Dialog * createGuiAbout(GuiView & lv);
2702 Dialog * createGuiBibitem(GuiView & lv);
2703 Dialog * createGuiBibtex(GuiView & lv);
2704 Dialog * createGuiBox(GuiView & lv);
2705 Dialog * createGuiBranch(GuiView & lv);
2706 Dialog * createGuiChanges(GuiView & lv);
2707 Dialog * createGuiCharacter(GuiView & lv);
2708 Dialog * createGuiCitation(GuiView & lv);
2709 Dialog * createGuiDelimiter(GuiView & lv);
2710 Dialog * createGuiDocument(GuiView & lv);
2711 Dialog * createGuiErrorList(GuiView & lv);
2712 Dialog * createGuiERT(GuiView & lv);
2713 Dialog * createGuiExternal(GuiView & lv);
2714 Dialog * createGuiFloat(GuiView & lv);
2715 Dialog * createGuiGraphics(GuiView & lv);
2716 Dialog * createGuiInclude(GuiView & lv);
2717 Dialog * createGuiIndex(GuiView & lv);
2718 Dialog * createGuiInfo(GuiView & lv);
2719 Dialog * createGuiLabel(GuiView & lv);
2720 Dialog * createGuiListings(GuiView & lv);
2721 Dialog * createGuiLog(GuiView & lv);
2722 Dialog * createGuiMathHSpace(GuiView & lv);
2723 Dialog * createGuiMathMatrix(GuiView & lv);
2724 Dialog * createGuiNomenclature(GuiView & lv);
2725 Dialog * createGuiNote(GuiView & lv);
2726 Dialog * createGuiParagraph(GuiView & lv);
2727 Dialog * createGuiPhantom(GuiView & lv);
2728 Dialog * createGuiPreferences(GuiView & lv);
2729 Dialog * createGuiPrint(GuiView & lv);
2730 Dialog * createGuiPrintindex(GuiView & lv);
2731 Dialog * createGuiPrintNomencl(GuiView & lv);
2732 Dialog * createGuiRef(GuiView & lv);
2733 Dialog * createGuiSearch(GuiView & lv);
2734 Dialog * createGuiSearchAdv(GuiView & lv);
2735 Dialog * createGuiSendTo(GuiView & lv);
2736 Dialog * createGuiShowFile(GuiView & lv);
2737 Dialog * createGuiSpellchecker(GuiView & lv);
2738 Dialog * createGuiSymbols(GuiView & lv);
2739 Dialog * createGuiTabularCreate(GuiView & lv);
2740 Dialog * createGuiTabular(GuiView & lv);
2741 Dialog * createGuiTexInfo(GuiView & lv);
2742 Dialog * createGuiTextHSpace(GuiView & lv);
2743 Dialog * createGuiToc(GuiView & lv);
2744 Dialog * createGuiThesaurus(GuiView & lv);
2745 Dialog * createGuiHyperlink(GuiView & lv);
2746 Dialog * createGuiVSpace(GuiView & lv);
2747 Dialog * createGuiViewSource(GuiView & lv);
2748 Dialog * createGuiWrap(GuiView & lv);
2749
2750
2751 Dialog * GuiView::build(string const & name)
2752 {
2753         LASSERT(isValidName(name), return 0);
2754
2755         if (name == "aboutlyx")
2756                 return createGuiAbout(*this);
2757         if (name == "bibitem")
2758                 return createGuiBibitem(*this);
2759         if (name == "bibtex")
2760                 return createGuiBibtex(*this);
2761         if (name == "box")
2762                 return createGuiBox(*this);
2763         if (name == "branch")
2764                 return createGuiBranch(*this);
2765         if (name == "changes")
2766                 return createGuiChanges(*this);
2767         if (name == "character")
2768                 return createGuiCharacter(*this);
2769         if (name == "citation")
2770                 return createGuiCitation(*this);
2771         if (name == "document")
2772                 return createGuiDocument(*this);
2773         if (name == "errorlist")
2774                 return createGuiErrorList(*this);
2775         if (name == "ert")
2776                 return createGuiERT(*this);
2777         if (name == "external")
2778                 return createGuiExternal(*this);
2779         if (name == "file")
2780                 return createGuiShowFile(*this);
2781         if (name == "findreplace")
2782                 return createGuiSearch(*this);
2783         if (name == "findreplaceadv")
2784                 return createGuiSearchAdv(*this);
2785         if (name == "float")
2786                 return createGuiFloat(*this);
2787         if (name == "graphics")
2788                 return createGuiGraphics(*this);
2789         if (name == "href")
2790                 return createGuiHyperlink(*this);
2791         if (name == "include")
2792                 return createGuiInclude(*this);
2793         if (name == "index")
2794                 return createGuiIndex(*this);
2795         if (name == "index_print")
2796                 return createGuiPrintindex(*this);
2797         if (name == "info")
2798                 return createGuiInfo(*this);
2799         if (name == "label")
2800                 return createGuiLabel(*this);
2801         if (name == "listings")
2802                 return createGuiListings(*this);
2803         if (name == "log")
2804                 return createGuiLog(*this);
2805         if (name == "mathdelimiter")
2806                 return createGuiDelimiter(*this);
2807         if (name == "mathspace")
2808                 return createGuiMathHSpace(*this);
2809         if (name == "mathmatrix")
2810                 return createGuiMathMatrix(*this);
2811         if (name == "nomenclature")
2812                 return createGuiNomenclature(*this);
2813         if (name == "nomencl_print")
2814                 return createGuiPrintNomencl(*this);
2815         if (name == "note")
2816                 return createGuiNote(*this);
2817         if (name == "paragraph")
2818                 return createGuiParagraph(*this);
2819         if (name == "phantom")
2820                 return createGuiPhantom(*this);
2821         if (name == "prefs")
2822                 return createGuiPreferences(*this);
2823         if (name == "print")
2824                 return createGuiPrint(*this);
2825         if (name == "ref")
2826                 return createGuiRef(*this);
2827         if (name == "sendto")
2828                 return createGuiSendTo(*this);
2829         if (name == "space")
2830                 return createGuiTextHSpace(*this);
2831         if (name == "spellchecker")
2832                 return createGuiSpellchecker(*this);
2833         if (name == "symbols")
2834                 return createGuiSymbols(*this);
2835         if (name == "tabular")
2836                 return createGuiTabular(*this);
2837         if (name == "tabularcreate")
2838                 return createGuiTabularCreate(*this);
2839         if (name == "texinfo")
2840                 return createGuiTexInfo(*this);
2841         if (name == "thesaurus")
2842                 return createGuiThesaurus(*this);
2843         if (name == "toc")
2844                 return createGuiToc(*this);
2845         if (name == "view-source")
2846                 return createGuiViewSource(*this);
2847         if (name == "vspace")
2848                 return createGuiVSpace(*this);
2849         if (name == "wrap")
2850                 return createGuiWrap(*this);
2851
2852         return 0;
2853 }
2854
2855
2856 } // namespace frontend
2857 } // namespace lyx
2858
2859 #include "moc_GuiView.cpp"