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