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