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