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