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