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