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