]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
ee10e3d6929f5d5461d8a62f99fc1c2359a6d7b8
[lyx.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "Dialog.h"
19 #include "FileDialog.h"
20 #include "FontLoader.h"
21 #include "GuiApplication.h"
22 #include "GuiCommandBuffer.h"
23 #include "GuiCompleter.h"
24 #include "GuiWorkArea.h"
25 #include "GuiKeySymbol.h"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "LayoutBox.h"
29 #include "Menus.h"
30 #include "TocModel.h"
31
32 #include "qt_helpers.h"
33
34 #include "frontends/alert.h"
35
36 #include "buffer_funcs.h"
37 #include "Buffer.h"
38 #include "BufferList.h"
39 #include "BufferParams.h"
40 #include "BufferView.h"
41 #include "Converter.h"
42 #include "Cursor.h"
43 #include "CutAndPaste.h"
44 #include "Encoding.h"
45 #include "ErrorList.h"
46 #include "Format.h"
47 #include "FuncStatus.h"
48 #include "FuncRequest.h"
49 #include "Intl.h"
50 #include "Layout.h"
51 #include "Lexer.h"
52 #include "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_IMPORT:
1195                 break;
1196
1197         case LFUN_BUFFER_RELOAD:
1198                 enable = doc_buffer && !doc_buffer->isUnnamed()
1199                         && doc_buffer->fileName().exists()
1200                         && (!doc_buffer->isClean()
1201                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1202                 break;
1203
1204         case LFUN_BUFFER_WRITE:
1205                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1206                 break;
1207
1208         case LFUN_BUFFER_WRITE_AS:
1209                 enable = doc_buffer;
1210                 break;
1211
1212         case LFUN_BUFFER_CLOSE:
1213                 enable = doc_buffer;
1214                 break;
1215
1216         case LFUN_BUFFER_CLOSE_ALL:
1217                 enable = theBufferList().last() != theBufferList().first();
1218                 break;
1219
1220         case LFUN_SPLIT_VIEW:
1221                 if (cmd.getArg(0) == "vertical")
1222                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1223                                          d.splitter_->orientation() == Qt::Vertical);
1224                 else
1225                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1226                                          d.splitter_->orientation() == Qt::Horizontal);
1227                 break;
1228
1229         case LFUN_CLOSE_TAB_GROUP:
1230                 enable = d.currentTabWorkArea();
1231                 break;
1232
1233         case LFUN_TOOLBAR_TOGGLE:
1234                 if (GuiToolbar * t = toolbar(cmd.getArg(0)))
1235                         flag.setOnOff(t->isVisible());
1236                 break;
1237
1238         case LFUN_UI_TOGGLE:
1239                 flag.setOnOff(isFullScreen());
1240                 break;
1241
1242         case LFUN_DIALOG_DISCONNECT_INSET:
1243                 break;
1244
1245         case LFUN_DIALOG_HIDE:
1246                 // FIXME: should we check if the dialog is shown?
1247                 break;
1248
1249         case LFUN_DIALOG_TOGGLE:
1250                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1251                 // fall through to set "enable"
1252         case LFUN_DIALOG_SHOW: {
1253                 string const name = cmd.getArg(0);
1254                 if (!doc_buffer)
1255                         enable = name == "aboutlyx"
1256                                 || name == "file" //FIXME: should be removed.
1257                                 || name == "prefs"
1258                                 || name == "texinfo";
1259                 else if (name == "print")
1260                         enable = doc_buffer->isExportable("dvi")
1261                                 && lyxrc.print_command != "none";
1262                 else if (name == "character" || name == "symbols") {
1263                         if (!buf || buf->isReadonly()
1264                                 || !currentBufferView()->cursor().inTexted())
1265                                 enable = false;
1266                         else {
1267                                 // FIXME we should consider passthru
1268                                 // paragraphs too.
1269                                 Inset const & in = currentBufferView()->cursor().inset();
1270                                 enable = !in.getLayout().isPassThru();
1271                         }
1272                 }
1273                 else if (name == "latexlog")
1274                         enable = FileName(doc_buffer->logName()).isReadableFile();
1275                 else if (name == "spellchecker")
1276                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1277                 else if (name == "vclog")
1278                         enable = doc_buffer->lyxvc().inUse();
1279                 break;
1280         }
1281
1282         case LFUN_DIALOG_UPDATE: {
1283                 string const name = cmd.getArg(0);
1284                 if (!buf)
1285                         enable = name == "prefs";
1286                 break;
1287         }
1288
1289         case LFUN_COMMAND_EXECUTE:
1290         case LFUN_MESSAGE:
1291         case LFUN_MENU_OPEN:
1292                 // Nothing to check.
1293                 break;
1294
1295         case LFUN_INSET_APPLY: {
1296                 string const name = cmd.getArg(0);
1297                 Inset * inset = getOpenInset(name);
1298                 if (inset) {
1299                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
1300                         FuncStatus fs;
1301                         if (!inset->getStatus(currentBufferView()->cursor(), fr, fs)) {
1302                                 // Every inset is supposed to handle this
1303                                 LASSERT(false, break);
1304                         }
1305                         flag |= fs;
1306                 } else {
1307                         FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
1308                         flag |= lyx::getStatus(fr);
1309                 }
1310                 enable = flag.enabled();
1311                 break;
1312         }
1313
1314         case LFUN_COMPLETION_INLINE:
1315                 if (!d.current_work_area_
1316                     || !d.current_work_area_->completer().inlinePossible(
1317                         currentBufferView()->cursor()))
1318                     enable = false;
1319                 break;
1320
1321         case LFUN_COMPLETION_POPUP:
1322                 if (!d.current_work_area_
1323                     || !d.current_work_area_->completer().popupPossible(
1324                         currentBufferView()->cursor()))
1325                     enable = false;
1326                 break;
1327
1328         case LFUN_COMPLETION_COMPLETE:
1329                 if (!d.current_work_area_
1330                         || !d.current_work_area_->completer().inlinePossible(
1331                         currentBufferView()->cursor()))
1332                     enable = false;
1333                 break;
1334
1335         case LFUN_COMPLETION_ACCEPT:
1336                 if (!d.current_work_area_
1337                     || (!d.current_work_area_->completer().popupVisible()
1338                         && !d.current_work_area_->completer().inlineVisible()
1339                         && !d.current_work_area_->completer().completionAvailable()))
1340                         enable = false;
1341                 break;
1342
1343         case LFUN_COMPLETION_CANCEL:
1344                 if (!d.current_work_area_
1345                     || (!d.current_work_area_->completer().popupVisible()
1346                         && !d.current_work_area_->completer().inlineVisible()))
1347                         enable = false;
1348                 break;
1349
1350         case LFUN_BUFFER_ZOOM_OUT:
1351                 enable = doc_buffer && lyxrc.zoom > 10;
1352                 break;
1353
1354         case LFUN_BUFFER_ZOOM_IN:
1355                 enable = doc_buffer;
1356                 break;
1357         
1358         case LFUN_BUFFER_NEXT:
1359         case LFUN_BUFFER_PREVIOUS:
1360                 // FIXME: should we check is there is an previous or next buffer?
1361                 break;
1362         case LFUN_BUFFER_SWITCH:
1363                 // toggle on the current buffer, but do not toggle off
1364                 // the other ones (is that a good idea?)
1365                 if (doc_buffer
1366                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1367                         flag.setOnOff(true);
1368                 break;
1369
1370         case LFUN_VC_REGISTER:
1371                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1372                 break;
1373         case LFUN_VC_CHECK_IN:
1374                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1375                 break;
1376         case LFUN_VC_CHECK_OUT:
1377                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1378                 break;
1379         case LFUN_VC_LOCKING_TOGGLE:
1380                 enable = doc_buffer && !doc_buffer->isReadonly()
1381                         && doc_buffer->lyxvc().lockingToggleEnabled();
1382                 flag.setOnOff(enable && !doc_buffer->lyxvc().locker().empty());
1383                 break;
1384         case LFUN_VC_REVERT:
1385                 enable = doc_buffer && doc_buffer->lyxvc().inUse();
1386                 break;
1387         case LFUN_VC_UNDO_LAST:
1388                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1389                 break;
1390         case LFUN_VC_COMMAND: {
1391                 if (cmd.argument().empty())
1392                         enable = false;
1393                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1394                         enable = false;
1395                 break;
1396         }
1397
1398         default:
1399                 return false;
1400         }
1401
1402         if (!enable)
1403                 flag.setEnabled(false);
1404
1405         return true;
1406 }
1407
1408
1409 static FileName selectTemplateFile()
1410 {
1411         FileDialog dlg(qt_("Select template file"));
1412         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1413         dlg.setButton1(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1414
1415         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1416                              QStringList(qt_("LyX Documents (*.lyx)")));
1417
1418         if (result.first == FileDialog::Later)
1419                 return FileName();
1420         if (result.second.isEmpty())
1421                 return FileName();
1422         return FileName(fromqstr(result.second));
1423 }
1424
1425
1426 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1427 {
1428         setBusy(true);
1429
1430         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1431
1432         if (!newBuffer) {
1433                 message(_("Document not loaded."));
1434                 setBusy(false);
1435                 return 0;
1436         }
1437         
1438         setBuffer(newBuffer);
1439
1440         // scroll to the position when the file was last closed
1441         if (lyxrc.use_lastfilepos) {
1442                 LastFilePosSection::FilePos filepos =
1443                         theSession().lastFilePos().load(filename);
1444                 documentBufferView()->moveToPosition(filepos.pit, filepos.pos, 0, 0);
1445         }
1446
1447         if (tolastfiles)
1448                 theSession().lastFiles().add(filename);
1449
1450         setBusy(false);
1451         return newBuffer;
1452 }
1453
1454
1455 void GuiView::openDocument(string const & fname)
1456 {
1457         string initpath = lyxrc.document_path;
1458
1459         if (documentBufferView()) {
1460                 string const trypath = documentBufferView()->buffer().filePath();
1461                 // If directory is writeable, use this as default.
1462                 if (FileName(trypath).isDirWritable())
1463                         initpath = trypath;
1464         }
1465
1466         string filename;
1467
1468         if (fname.empty()) {
1469                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1470                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1471                 dlg.setButton2(qt_("Examples|#E#e"),
1472                                 toqstr(addPath(package().system_support().absFilename(), "examples")));
1473
1474                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1475                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1476                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1477                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1478                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1479                 FileDialog::Result result =
1480                         dlg.open(toqstr(initpath), filter);
1481
1482                 if (result.first == FileDialog::Later)
1483                         return;
1484
1485                 filename = fromqstr(result.second);
1486
1487                 // check selected filename
1488                 if (filename.empty()) {
1489                         message(_("Canceled."));
1490                         return;
1491                 }
1492         } else
1493                 filename = fname;
1494
1495         // get absolute path of file and add ".lyx" to the filename if
1496         // necessary. 
1497         FileName const fullname = 
1498                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1499         if (!fullname.empty())
1500                 filename = fullname.absFilename();
1501
1502         if (!fullname.onlyPath().isDirectory()) {
1503                 Alert::warning(_("Invalid filename"),
1504                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1505                                 from_utf8(fullname.absFilename())));
1506                 return;
1507         }
1508         // if the file doesn't exist, let the user create one
1509         if (!fullname.exists()) {
1510                 // the user specifically chose this name. Believe him.
1511                 Buffer * const b = newFile(filename, string(), true);
1512                 if (b)
1513                         setBuffer(b);
1514                 return;
1515         }
1516
1517         docstring const disp_fn = makeDisplayPath(filename);
1518         message(bformat(_("Opening document %1$s..."), disp_fn));
1519
1520         docstring str2;
1521         Buffer * buf = loadDocument(fullname);
1522         if (buf) {
1523                 buf->updateLabels();
1524                 setBuffer(buf);
1525                 buf->errors("Parse");
1526                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1527                 if (buf->lyxvc().inUse())
1528                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1529                                 " " + _("Version control detected.");
1530         } else {
1531                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1532         }
1533         message(str2);
1534 }
1535
1536 // FIXME: clean that
1537 static bool import(GuiView * lv, FileName const & filename,
1538         string const & format, ErrorList & errorList)
1539 {
1540         FileName const lyxfile(support::changeExtension(filename.absFilename(), ".lyx"));
1541
1542         string loader_format;
1543         vector<string> loaders = theConverters().loaders();
1544         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1545                 for (vector<string>::const_iterator it = loaders.begin();
1546                      it != loaders.end(); ++it) {
1547                         if (!theConverters().isReachable(format, *it))
1548                                 continue;
1549
1550                         string const tofile =
1551                                 support::changeExtension(filename.absFilename(),
1552                                 formats.extension(*it));
1553                         if (!theConverters().convert(0, filename, FileName(tofile),
1554                                 filename, format, *it, errorList))
1555                                 return false;
1556                         loader_format = *it;
1557                         break;
1558                 }
1559                 if (loader_format.empty()) {
1560                         frontend::Alert::error(_("Couldn't import file"),
1561                                      bformat(_("No information for importing the format %1$s."),
1562                                          formats.prettyName(format)));
1563                         return false;
1564                 }
1565         } else
1566                 loader_format = format;
1567
1568         if (loader_format == "lyx") {
1569                 Buffer * buf = lv->loadDocument(lyxfile);
1570                 if (!buf)
1571                         return false;
1572                 buf->updateLabels();
1573                 lv->setBuffer(buf);
1574                 buf->errors("Parse");
1575         } else {
1576                 Buffer * const b = newFile(lyxfile.absFilename(), string(), true);
1577                 if (!b)
1578                         return false;
1579                 lv->setBuffer(b);
1580                 bool as_paragraphs = loader_format == "textparagraph";
1581                 string filename2 = (loader_format == format) ? filename.absFilename()
1582                         : support::changeExtension(filename.absFilename(),
1583                                           formats.extension(loader_format));
1584                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
1585                         as_paragraphs);
1586                 theLyXFunc().setLyXView(lv);
1587                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1588         }
1589
1590         return true;
1591 }
1592
1593
1594 void GuiView::importDocument(string const & argument)
1595 {
1596         string format;
1597         string filename = split(argument, format, ' ');
1598
1599         LYXERR(Debug::INFO, format << " file: " << filename);
1600
1601         // need user interaction
1602         if (filename.empty()) {
1603                 string initpath = lyxrc.document_path;
1604                 if (documentBufferView()) {
1605                         string const trypath = documentBufferView()->buffer().filePath();
1606                         // If directory is writeable, use this as default.
1607                         if (FileName(trypath).isDirWritable())
1608                                 initpath = trypath;
1609                 }
1610
1611                 docstring const text = bformat(_("Select %1$s file to import"),
1612                         formats.prettyName(format));
1613
1614                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
1615                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1616                 dlg.setButton2(qt_("Examples|#E#e"),
1617                         toqstr(addPath(package().system_support().absFilename(), "examples")));
1618
1619                 docstring filter = formats.prettyName(format);
1620                 filter += " (*.";
1621                 // FIXME UNICODE
1622                 filter += from_utf8(formats.extension(format));
1623                 filter += ')';
1624
1625                 FileDialog::Result result =
1626                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
1627
1628                 if (result.first == FileDialog::Later)
1629                         return;
1630
1631                 filename = fromqstr(result.second);
1632
1633                 // check selected filename
1634                 if (filename.empty())
1635                         message(_("Canceled."));
1636         }
1637
1638         if (filename.empty())
1639                 return;
1640
1641         // get absolute path of file
1642         FileName const fullname(support::makeAbsPath(filename));
1643
1644         FileName const lyxfile(support::changeExtension(fullname.absFilename(), ".lyx"));
1645
1646         // Check if the document already is open
1647         Buffer * buf = theBufferList().getBuffer(lyxfile);
1648         if (buf) {
1649                 setBuffer(buf);
1650                 if (!closeBuffer()) {
1651                         message(_("Canceled."));
1652                         return;
1653                 }
1654         }
1655
1656         docstring const displaypath = makeDisplayPath(lyxfile.absFilename(), 30);
1657
1658         // if the file exists already, and we didn't do
1659         // -i lyx thefile.lyx, warn
1660         if (lyxfile.exists() && fullname != lyxfile) {
1661
1662                 docstring text = bformat(_("The document %1$s already exists.\n\n"
1663                         "Do you want to overwrite that document?"), displaypath);
1664                 int const ret = Alert::prompt(_("Overwrite document?"),
1665                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
1666
1667                 if (ret == 1) {
1668                         message(_("Canceled."));
1669                         return;
1670                 }
1671         }
1672
1673         message(bformat(_("Importing %1$s..."), displaypath));
1674         ErrorList errorList;
1675         if (import(this, fullname, format, errorList))
1676                 message(_("imported."));
1677         else
1678                 message(_("file not imported!"));
1679
1680         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
1681 }
1682
1683
1684 void GuiView::newDocument(string const & filename, bool from_template)
1685 {
1686         FileName initpath(lyxrc.document_path);
1687         if (documentBufferView()) {
1688                 FileName const trypath(documentBufferView()->buffer().filePath());
1689                 // If directory is writeable, use this as default.
1690                 if (trypath.isDirWritable())
1691                         initpath = trypath;
1692         }
1693
1694         string templatefile;
1695         if (from_template) {
1696                 templatefile = selectTemplateFile().absFilename();
1697                 if (templatefile.empty())
1698                         return;
1699         }
1700         
1701         Buffer * b;
1702         if (filename.empty())
1703                 b = newUnnamedFile(templatefile, initpath);
1704         else
1705                 b = newFile(filename, templatefile, true);
1706
1707         if (b)
1708                 setBuffer(b);
1709
1710         // If no new document could be created, it is unsure 
1711         // whether there is a valid BufferView.
1712         if (currentBufferView())
1713                 // Ensure the cursor is correctly positioned on screen.
1714                 currentBufferView()->showCursor();
1715 }
1716
1717
1718 void GuiView::insertLyXFile(docstring const & fname)
1719 {
1720         BufferView * bv = documentBufferView();
1721         if (!bv)
1722                 return;
1723
1724         // FIXME UNICODE
1725         FileName filename(to_utf8(fname));
1726         
1727         if (!filename.empty()) {
1728                 bv->insertLyXFile(filename);
1729                 return;
1730         }
1731
1732         // Launch a file browser
1733         // FIXME UNICODE
1734         string initpath = lyxrc.document_path;
1735         string const trypath = bv->buffer().filePath();
1736         // If directory is writeable, use this as default.
1737         if (FileName(trypath).isDirWritable())
1738                 initpath = trypath;
1739
1740         // FIXME UNICODE
1741         FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
1742         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1743         dlg.setButton2(qt_("Examples|#E#e"),
1744                 toqstr(addPath(package().system_support().absFilename(),
1745                 "examples")));
1746
1747         FileDialog::Result result = dlg.open(toqstr(initpath),
1748                              QStringList(qt_("LyX Documents (*.lyx)")));
1749
1750         if (result.first == FileDialog::Later)
1751                 return;
1752
1753         // FIXME UNICODE
1754         filename.set(fromqstr(result.second));
1755
1756         // check selected filename
1757         if (filename.empty()) {
1758                 // emit message signal.
1759                 message(_("Canceled."));
1760                 return;
1761         }
1762
1763         bv->insertLyXFile(filename);
1764 }
1765
1766
1767 void GuiView::insertPlaintextFile(docstring const & fname,
1768         bool asParagraph)
1769 {
1770         BufferView * bv = documentBufferView();
1771         if (!bv)
1772                 return;
1773
1774         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
1775                 message(_("Absolute filename expected."));
1776                 return;
1777         }
1778
1779         // FIXME UNICODE
1780         FileName filename(to_utf8(fname));
1781         
1782         if (!filename.empty()) {
1783                 bv->insertPlaintextFile(filename, asParagraph);
1784                 return;
1785         }
1786
1787         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
1788                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
1789
1790         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
1791                 QStringList(qt_("All Files (*)")));
1792
1793         if (result.first == FileDialog::Later)
1794                 return;
1795
1796         // FIXME UNICODE
1797         filename.set(fromqstr(result.second));
1798
1799         // check selected filename
1800         if (filename.empty()) {
1801                 // emit message signal.
1802                 message(_("Canceled."));
1803                 return;
1804         }
1805
1806         bv->insertPlaintextFile(filename, asParagraph);
1807 }
1808
1809
1810 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
1811 {
1812         FileName fname = b.fileName();
1813         FileName const oldname = fname;
1814
1815         if (!newname.empty()) {
1816                 // FIXME UNICODE
1817                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFilename());
1818         } else {
1819                 // Switch to this Buffer.
1820                 setBuffer(&b);
1821
1822                 // No argument? Ask user through dialog.
1823                 // FIXME UNICODE
1824                 FileDialog dlg(qt_("Choose a filename to save document as"),
1825                                    LFUN_BUFFER_WRITE_AS);
1826                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1827                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1828
1829                 if (!isLyXFilename(fname.absFilename()))
1830                         fname.changeExtension(".lyx");
1831
1832                 FileDialog::Result result =
1833                         dlg.save(toqstr(fname.onlyPath().absFilename()),
1834                                QStringList(qt_("LyX Documents (*.lyx)")),
1835                                      toqstr(fname.onlyFileName()));
1836
1837                 if (result.first == FileDialog::Later)
1838                         return false;
1839
1840                 fname.set(fromqstr(result.second));
1841
1842                 if (fname.empty())
1843                         return false;
1844
1845                 if (!isLyXFilename(fname.absFilename()))
1846                         fname.changeExtension(".lyx");
1847         }
1848
1849         if (FileName(fname).exists()) {
1850                 docstring const file = makeDisplayPath(fname.absFilename(), 30);
1851                 docstring text = bformat(_("The document %1$s already "
1852                                            "exists.\n\nDo you want to "
1853                                            "overwrite that document?"), 
1854                                          file);
1855                 int const ret = Alert::prompt(_("Overwrite document?"),
1856                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
1857                 switch (ret) {
1858                 case 0: break;
1859                 case 1: return renameBuffer(b, docstring());
1860                 case 2: return false;
1861                 }
1862         }
1863
1864         FileName oldauto = b.getAutosaveFilename();
1865
1866         // Ok, change the name of the buffer
1867         b.setFileName(fname.absFilename());
1868         b.markDirty();
1869         bool unnamed = b.isUnnamed();
1870         b.setUnnamed(false);
1871         b.saveCheckSum(fname);
1872
1873         // bring the autosave file with us, just in case.
1874         b.moveAutosaveFile(oldauto);
1875         
1876         if (!saveBuffer(b)) {
1877                 oldauto = b.getAutosaveFilename();
1878                 b.setFileName(oldname.absFilename());
1879                 b.setUnnamed(unnamed);
1880                 b.saveCheckSum(oldname);
1881                 b.moveAutosaveFile(oldauto);
1882                 return false;
1883         }
1884
1885         return true;
1886 }
1887
1888
1889 bool GuiView::saveBuffer(Buffer & b)
1890 {
1891         if (workArea(b) && workArea(b)->inDialogMode())
1892                 return true;
1893
1894         if (b.isUnnamed())
1895                 return renameBuffer(b, docstring());
1896
1897         if (b.save()) {
1898                 theSession().lastFiles().add(b.fileName());
1899                 return true;
1900         }
1901
1902         // Switch to this Buffer.
1903         setBuffer(&b);
1904
1905         // FIXME: we don't tell the user *WHY* the save failed !!
1906         docstring const file = makeDisplayPath(b.absFileName(), 30);
1907         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
1908                                    "Do you want to rename the document and "
1909                                    "try again?"), file);
1910         int const ret = Alert::prompt(_("Rename and save?"),
1911                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
1912         switch (ret) {
1913         case 0:
1914                 if (!renameBuffer(b, docstring()))
1915                         return false;
1916                 break;
1917         case 1:
1918                 break;
1919         case 2:
1920                 return false;
1921         }
1922
1923         return saveBuffer(b);
1924 }
1925
1926
1927 bool GuiView::hideWorkArea(GuiWorkArea * wa)
1928 {
1929         return closeWorkArea(wa, false);
1930 }
1931
1932
1933 bool GuiView::closeWorkArea(GuiWorkArea * wa)
1934 {
1935         Buffer & buf = wa->bufferView().buffer();
1936         return closeWorkArea(wa, !buf.parent());
1937 }
1938
1939
1940 bool GuiView::closeBuffer()
1941 {
1942         GuiWorkArea * wa = currentMainWorkArea();
1943         Buffer & buf = wa->bufferView().buffer();
1944         return wa && closeWorkArea(wa, !buf.parent());
1945 }
1946
1947
1948 void GuiView::writeSession() const {
1949         GuiWorkArea const * active_wa = currentMainWorkArea();
1950         for (int i = 0; i < d.splitter_->count(); ++i) {
1951                 TabWorkArea * twa = d.tabWorkArea(i);
1952                 for (int j = 0; j < twa->count(); ++j) {
1953                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
1954                         Buffer & buf = wa->bufferView().buffer();
1955                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
1956                 }
1957         }
1958 }
1959
1960
1961 bool GuiView::closeBufferAll()
1962 {
1963         // Close the workareas in all other views
1964         QList<int> const ids = guiApp->viewIds();
1965         for (int i = 0; i != ids.size(); ++i) {
1966                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
1967                         return false;
1968         }
1969
1970         // Close our own workareas
1971         if (!closeWorkAreaAll())
1972                 return false;
1973
1974         // Now close the hidden buffers. We prevent hidden buffers from being
1975         // dirty, so we can just close them.
1976         theBufferList().closeAll();
1977         return true;
1978 }
1979
1980
1981 bool GuiView::closeWorkAreaAll()
1982 {
1983         setCurrentWorkArea(currentMainWorkArea());
1984
1985         // We might be in a situation that there is still a tabWorkArea, but
1986         // there are no tabs anymore. This can happen when we get here after a 
1987         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
1988         // many TabWorkArea's have no documents anymore.
1989         int empty_twa = 0;
1990
1991         // We have to call count() each time, because it can happen that
1992         // more than one splitter will disappear in one iteration (bug 5998).
1993         for (; d.splitter_->count() > empty_twa; ) {
1994                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
1995
1996                 if (twa->count() == 0)
1997                         ++empty_twa;
1998                 else {
1999                         setCurrentWorkArea(twa->currentWorkArea());
2000                         if (!closeTabWorkArea(twa))
2001                                 return false;
2002                 }
2003         }
2004         return true;
2005 }
2006
2007
2008 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2009 {
2010         Buffer & buf = wa->bufferView().buffer();
2011
2012         // If we are in a close_event all children will be closed in some time,
2013         // so no need to do it here. This will ensure that the children end up
2014         // in the session file in the correct order. If we close the master
2015         // buffer, we can close or release the child buffers here too.
2016         if (close_buffer && !closing_) {
2017                 vector<Buffer *> clist = buf.getChildren();
2018                 for (vector<Buffer *>::const_iterator it = clist.begin();
2019                          it != clist.end(); ++it) {
2020                         // If a child is dirty, do not close
2021                         // without user intervention
2022                         //FIXME: should we look in other tabworkareas?
2023                         Buffer * child_buf = *it;
2024                         GuiWorkArea * child_wa = workArea(*child_buf);
2025                         if (child_wa) {
2026                                 if (!closeWorkArea(child_wa, true))
2027                                         return false;
2028                         } else
2029                                 theBufferList().releaseChild(&buf, child_buf);
2030                 }
2031         }
2032         // goto bookmark to update bookmark pit.
2033         //FIXME: we should update only the bookmarks related to this buffer!
2034         LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2035         for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2036                 theLyXFunc().gotoBookmark(i+1, false, false);
2037
2038         // if we are only hiding the buffer and there are multiple views
2039         // of the buffer, then we do not need to ensure a clean buffer.
2040         bool const allow_dirty = inMultiTabs(wa) && !close_buffer;
2041
2042         if (allow_dirty || saveBufferIfNeeded(buf, !close_buffer)) {
2043                 // save in sessions if requested
2044                 // do not save childs if their master
2045                 // is opened as well
2046                 if (!close_buffer)
2047                         removeWorkArea(wa);
2048                 else
2049                         theBufferList().release(&buf);
2050                 return true;
2051         }
2052         return false;
2053 }
2054
2055
2056 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2057 {
2058         while (twa == d.currentTabWorkArea()) {
2059                 twa->setCurrentIndex(twa->count()-1);
2060
2061                 GuiWorkArea * wa = twa->currentWorkArea();
2062                 Buffer & b = wa->bufferView().buffer();
2063
2064                 // We only want to close the buffer if the same buffer is not visible
2065                 // in another view, and if this is not a child and if we are closing
2066                 // a view (not a tabgroup).
2067                 bool const close_buffer = 
2068                         !inMultiViews(wa) && !b.parent() && closing_;
2069
2070                 if (!closeWorkArea(wa, close_buffer))
2071                         return false;
2072         }
2073         return true;
2074 }
2075
2076
2077 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2078 {
2079         if (buf.isClean() || buf.paragraphs().empty())
2080                 return true;
2081
2082         // Switch to this Buffer.
2083         setBuffer(&buf);
2084
2085         docstring file;
2086         // FIXME: Unicode?
2087         if (buf.isUnnamed())
2088                 file = from_utf8(buf.fileName().onlyFileName());
2089         else
2090                 file = buf.fileName().displayName(30);
2091
2092         // Bring this window to top before asking questions.
2093         raise();
2094         activateWindow();
2095
2096         int ret;
2097         if (hiding && buf.isUnnamed()) {
2098                 docstring const text = bformat(_("The document %1$s has not been "
2099                                              "saved yet.\n\nDo you want to save "
2100                                              "the document?"), file);
2101                 ret = Alert::prompt(_("Save new document?"), 
2102                         text, 0, 1, _("&Save"), _("&Cancel"));
2103                 if (ret == 1)
2104                         ++ret;
2105         } else {
2106                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2107                         "\n\nDo you want to save the document or discard the changes?"), file);
2108                 ret = Alert::prompt(_("Save changed document?"),
2109                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2110         }
2111
2112         switch (ret) {
2113         case 0:
2114                 if (!saveBuffer(buf))
2115                         return false;
2116                 break;
2117         case 1:
2118                 // if we crash after this we could
2119                 // have no autosave file but I guess
2120                 // this is really improbable (Jug)
2121                 buf.removeAutosaveFile();
2122                 if (hiding)
2123                         // revert all changes
2124                         buf.loadLyXFile(buf.fileName());
2125                 buf.markClean();
2126                 break;
2127         case 2:
2128                 return false;
2129         }
2130         return true;
2131 }
2132
2133
2134 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2135 {
2136         Buffer & buf = wa->bufferView().buffer();
2137
2138         for (int i = 0; i != d.splitter_->count(); ++i) {
2139                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2140                 if (wa_ && wa_ != wa)
2141                         return true;
2142         }
2143         return inMultiViews(wa);
2144 }
2145
2146
2147 bool GuiView::inMultiViews(GuiWorkArea * wa)
2148 {
2149         QList<int> const ids = guiApp->viewIds();
2150         Buffer & buf = wa->bufferView().buffer();
2151
2152         int found_twa = 0;
2153         for (int i = 0; i != ids.size() && found_twa <= 1; ++i) {
2154                 if (id_ == ids[i])
2155                         continue;
2156                 
2157                 if (guiApp->view(ids[i]).workArea(buf))
2158                         return true;
2159         }
2160         return false;
2161 }
2162
2163
2164 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2165 {
2166         Buffer * const curbuf = documentBufferView()
2167                 ? &documentBufferView()->buffer() : 0;
2168         Buffer * nextbuf = curbuf;
2169         while (true) {
2170                 if (np == NEXTBUFFER)
2171                         nextbuf = theBufferList().next(nextbuf);
2172                 else
2173                         nextbuf = theBufferList().previous(nextbuf);
2174                 if (nextbuf == curbuf)
2175                         break;
2176                 if (nextbuf == 0) {
2177                         nextbuf = curbuf;
2178                         break;
2179                 }
2180                 if (workArea(*nextbuf))
2181                         break;
2182         }
2183         setBuffer(nextbuf);
2184 }
2185
2186
2187 /// make sure the document is saved
2188 static bool ensureBufferClean(Buffer * buffer)
2189 {
2190         LASSERT(buffer, return false);
2191         if (buffer->isClean() && !buffer->isUnnamed())
2192                 return true;
2193
2194         docstring const file = buffer->fileName().displayName(30);
2195         docstring title;
2196         docstring text;
2197         if (!buffer->isUnnamed()) {
2198                 text = bformat(_("The document %1$s has unsaved "
2199                                              "changes.\n\nDo you want to save "
2200                                              "the document?"), file);
2201                 title = _("Save changed document?");
2202                 
2203         } else {
2204                 text = bformat(_("The document %1$s has not been "
2205                                              "saved yet.\n\nDo you want to save "
2206                                              "the document?"), file);
2207                 title = _("Save new document?");
2208         }
2209         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2210
2211         if (ret == 0)
2212                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2213
2214         return buffer->isClean() && !buffer->isUnnamed();
2215 }
2216
2217
2218 void GuiView::reloadBuffer()
2219 {
2220         Buffer * buf = &documentBufferView()->buffer();
2221         FileName filename = buf->fileName();
2222         // The user has already confirmed that the changes, if any, should
2223         // be discarded. So we just release the Buffer and don't call closeBuffer();
2224         theBufferList().release(buf);
2225         buf = loadDocument(filename);
2226         docstring const disp_fn = makeDisplayPath(filename.absFilename());
2227         docstring str;
2228         if (buf) {
2229                 buf->updateLabels();
2230                 setBuffer(buf);
2231                 buf->errors("Parse");
2232                 str = bformat(_("Document %1$s reloaded."), disp_fn);
2233         } else {
2234                 str = bformat(_("Could not reload document %1$s"), disp_fn);
2235         }
2236         message(str);
2237 }
2238
2239
2240 void GuiView::dispatchVC(FuncRequest const & cmd)
2241 {
2242         Buffer * buffer = documentBufferView()
2243                 ? &(documentBufferView()->buffer()) : 0;
2244
2245         switch (cmd.action) {
2246         case LFUN_VC_REGISTER:
2247                 if (!buffer || !ensureBufferClean(buffer))
2248                         break;
2249                 if (!buffer->lyxvc().inUse()) {
2250                         if (buffer->lyxvc().registrer())
2251                                 reloadBuffer();
2252                 }
2253                 break;
2254
2255         case LFUN_VC_CHECK_IN:
2256                 if (!buffer || !ensureBufferClean(buffer))
2257                         break;
2258                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2259                         message(from_utf8(buffer->lyxvc().checkIn()));
2260                         reloadBuffer();
2261                 }
2262                 break;
2263
2264         case LFUN_VC_CHECK_OUT:
2265                 if (!buffer || !ensureBufferClean(buffer))
2266                         break;
2267                 if (buffer->lyxvc().inUse()) {
2268                         message(from_utf8(buffer->lyxvc().checkOut()));
2269                         reloadBuffer();
2270                 }
2271                 break;
2272
2273         case LFUN_VC_LOCKING_TOGGLE:
2274                 LASSERT(buffer, return);
2275                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2276                         break;
2277                 if (buffer->lyxvc().inUse()) {
2278                         string res = buffer->lyxvc().lockingToggle();
2279                         if (res.empty()) {
2280                                 frontend::Alert::error(_("Revision control error."),
2281                                 _("Error when setting the locking property."));
2282                         } else {
2283                                 message(from_utf8(res));
2284                                 reloadBuffer();
2285                         }
2286                 }
2287                 break;
2288
2289         case LFUN_VC_REVERT:
2290                 LASSERT(buffer, return);
2291                 buffer->lyxvc().revert();
2292                 reloadBuffer();
2293                 break;
2294
2295         case LFUN_VC_UNDO_LAST:
2296                 LASSERT(buffer, return);
2297                 buffer->lyxvc().undoLast();
2298                 reloadBuffer();
2299                 break;
2300
2301         case LFUN_VC_COMMAND: {
2302                 string flag = cmd.getArg(0);
2303                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2304                         break;
2305                 docstring message;
2306                 if (contains(flag, 'M')) {
2307                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2308                                 break;
2309                 }
2310                 string path = cmd.getArg(1);
2311                 if (contains(path, "$$p") && buffer)
2312                         path = subst(path, "$$p", buffer->filePath());
2313                 LYXERR(Debug::LYXVC, "Directory: " << path);
2314                 FileName pp(path);
2315                 if (!pp.isReadableDirectory()) {
2316                         lyxerr << _("Directory is not accessible.") << endl;
2317                         break;
2318                 }
2319                 support::PathChanger p(pp);
2320
2321                 string command = cmd.getArg(2);
2322                 if (command.empty())
2323                         break;
2324                 if (buffer) {
2325                         command = subst(command, "$$i", buffer->absFileName());
2326                         command = subst(command, "$$p", buffer->filePath());
2327                 }
2328                 command = subst(command, "$$m", to_utf8(message));
2329                 LYXERR(Debug::LYXVC, "Command: " << command);
2330                 Systemcall one;
2331                 one.startscript(Systemcall::Wait, command);
2332
2333                 if (!buffer)
2334                         break;
2335                 if (contains(flag, 'I'))
2336                         buffer->markDirty();
2337                 if (contains(flag, 'R'))
2338                         reloadBuffer();
2339
2340                 break;
2341                 }
2342         }
2343 }
2344
2345
2346 bool GuiView::dispatch(FuncRequest const & cmd)
2347 {
2348         BufferView * bv = currentBufferView();
2349         // By default we won't need any update.
2350         if (bv)
2351                 bv->cursor().updateFlags(Update::None);
2352
2353         Buffer * doc_buffer = documentBufferView()
2354                 ? &(documentBufferView()->buffer()) : 0;
2355
2356         bool dispatched = true;
2357
2358         if (cmd.origin == FuncRequest::TOC) {
2359                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
2360                 toc->doDispatch(bv->cursor(), cmd);
2361                 return true;
2362         }
2363
2364         switch(cmd.action) {
2365                 case LFUN_BUFFER_IMPORT:
2366                         importDocument(to_utf8(cmd.argument()));
2367                         break;
2368
2369                 case LFUN_BUFFER_SWITCH:
2370                         if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
2371                                 Buffer * buffer = 
2372                                         theBufferList().getBuffer(FileName(to_utf8(cmd.argument())));
2373                                 if (buffer)
2374                                         setBuffer(buffer);
2375                                 else
2376                                         bv->cursor().message(_("Document not loaded"));
2377                         }
2378                         break;
2379
2380                 case LFUN_BUFFER_NEXT:
2381                         gotoNextOrPreviousBuffer(NEXTBUFFER);
2382                         break;
2383
2384                 case LFUN_BUFFER_PREVIOUS:
2385                         gotoNextOrPreviousBuffer(PREVBUFFER);
2386                         break;
2387
2388                 case LFUN_COMMAND_EXECUTE: {
2389                         bool const show_it = cmd.argument() != "off";
2390                         // FIXME: this is a hack, "minibuffer" should not be
2391                         // hardcoded.
2392                         if (GuiToolbar * t = toolbar("minibuffer")) {
2393                                 t->setVisible(show_it);
2394                                 if (show_it && t->commandBuffer())
2395                                         t->commandBuffer()->setFocus();
2396                         }
2397                         break;
2398                 }
2399                 case LFUN_DROP_LAYOUTS_CHOICE:
2400                         d.layout_->showPopup();
2401                         break;
2402
2403                 case LFUN_MENU_OPEN:
2404                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
2405                                 menu->exec(QCursor::pos());
2406                         break;
2407
2408                 case LFUN_FILE_INSERT:
2409                         insertLyXFile(cmd.argument());
2410                         break;
2411                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
2412                         insertPlaintextFile(cmd.argument(), true);
2413                         break;
2414
2415                 case LFUN_FILE_INSERT_PLAINTEXT:
2416                         insertPlaintextFile(cmd.argument(), false);
2417                         break;
2418
2419                 case LFUN_BUFFER_RELOAD: {
2420                         LASSERT(doc_buffer, break);
2421                         docstring const file = makeDisplayPath(doc_buffer->absFileName(), 20);
2422                         docstring text = bformat(_("Any changes will be lost. Are you sure "
2423                                                              "you want to revert to the saved version of the document %1$s?"), file);
2424                         int const ret = Alert::prompt(_("Revert to saved document?"),
2425                                 text, 1, 1, _("&Revert"), _("&Cancel"));
2426
2427                         if (ret == 0)
2428                                 reloadBuffer();
2429                         break;
2430                 }
2431
2432                 case LFUN_BUFFER_WRITE:
2433                         LASSERT(doc_buffer, break);
2434                         saveBuffer(*doc_buffer);
2435                         break;
2436
2437                 case LFUN_BUFFER_WRITE_AS:
2438                         LASSERT(doc_buffer, break);
2439                         renameBuffer(*doc_buffer, cmd.argument());
2440                         break;
2441
2442                 case LFUN_BUFFER_WRITE_ALL: {
2443                         Buffer * first = theBufferList().first();
2444                         if (!first)
2445                                 break;
2446                         message(_("Saving all documents..."));
2447                         // We cannot use a for loop as the buffer list cycles.
2448                         Buffer * b = first;
2449                         do {
2450                                 if (!b->isClean()) {
2451                                         saveBuffer(*b);
2452                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
2453                                 }
2454                                 b = theBufferList().next(b);
2455                         } while (b != first); 
2456                         message(_("All documents saved."));
2457                         break;
2458                 }
2459
2460                 case LFUN_BUFFER_CLOSE:
2461                         closeBuffer();
2462                         break;
2463
2464                 case LFUN_BUFFER_CLOSE_ALL:
2465                         closeBufferAll();
2466                         break;
2467
2468                 case LFUN_TOOLBAR_TOGGLE: {
2469                         string const name = cmd.getArg(0);
2470                         if (GuiToolbar * t = toolbar(name))
2471                                 t->toggle();
2472                         break;
2473                 }
2474
2475                 case LFUN_DIALOG_UPDATE: {
2476                         string const name = to_utf8(cmd.argument());
2477                         // Can only update a dialog connected to an existing inset
2478                         Inset * inset = getOpenInset(name);
2479                         if (inset) {
2480                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
2481                                 inset->dispatch(currentBufferView()->cursor(), fr);
2482                         } else if (name == "paragraph") {
2483                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
2484                         } else if (name == "prefs" || name == "document") {
2485                                 updateDialog(name, string());
2486                         }
2487                         break;
2488                 }
2489
2490                 case LFUN_DIALOG_TOGGLE: {
2491                         if (isDialogVisible(cmd.getArg(0)))
2492                                 dispatch(FuncRequest(LFUN_DIALOG_HIDE, cmd.argument()));
2493                         else
2494                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, cmd.argument()));
2495                         break;
2496                 }
2497
2498                 case LFUN_DIALOG_DISCONNECT_INSET:
2499                         disconnectDialog(to_utf8(cmd.argument()));
2500                         break;
2501
2502                 case LFUN_DIALOG_HIDE: {
2503                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
2504                         break;
2505                 }
2506
2507                 case LFUN_DIALOG_SHOW: {
2508                         string const name = cmd.getArg(0);
2509                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
2510
2511                         if (name == "character") {
2512                                 data = freefont2string();
2513                                 if (!data.empty())
2514                                         showDialog("character", data);
2515                         } else if (name == "latexlog") {
2516                                 Buffer::LogType type; 
2517                                 string const logfile = doc_buffer->logName(&type);
2518                                 switch (type) {
2519                                 case Buffer::latexlog:
2520                                         data = "latex ";
2521                                         break;
2522                                 case Buffer::buildlog:
2523                                         data = "literate ";
2524                                         break;
2525                                 }
2526                                 data += Lexer::quoteString(logfile);
2527                                 showDialog("log", data);
2528                         } else if (name == "vclog") {
2529                                 string const data = "vc " +
2530                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
2531                                 showDialog("log", data);
2532                         } else if (name == "symbols") {
2533                                 data = bv->cursor().getEncoding()->name();
2534                                 if (!data.empty())
2535                                         showDialog("symbols", data);
2536                         // bug 5274
2537                         } else if (name == "prefs" && isFullScreen()) {
2538                                 FuncRequest fr(LFUN_INSET_INSERT, "fullscreen");
2539                                 lfunUiToggle(fr);
2540                                 showDialog("prefs", data);
2541                         } else
2542                                 showDialog(name, data);
2543                         break;
2544                 }
2545
2546                 case LFUN_MESSAGE:
2547                         message(cmd.argument());
2548                         break;
2549
2550                 case LFUN_INSET_APPLY: {
2551                         string const name = cmd.getArg(0);
2552                         Inset * inset = getOpenInset(name);
2553                         if (inset) {
2554                                 // put cursor in front of inset.
2555                                 if (!currentBufferView()->setCursorFromInset(inset)) {
2556                                         LASSERT(false, break);
2557                                 }
2558                                 BufferView * bv = currentBufferView();
2559                                 // useful if we are called from a dialog.
2560                                 bv->cursor().beginUndoGroup();
2561                                 bv->cursor().recordUndo();
2562                                 FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument());
2563                                 inset->dispatch(bv->cursor(), fr);
2564                                 bv->cursor().endUndoGroup();
2565                         } else {
2566                                 FuncRequest fr(LFUN_INSET_INSERT, cmd.argument());
2567                                 lyx::dispatch(fr);
2568                         }
2569                         break;
2570                 }
2571
2572                 case LFUN_UI_TOGGLE:
2573                         lfunUiToggle(cmd);
2574                         // Make sure the keyboard focus stays in the work area.
2575                         setFocus();
2576                         break;
2577
2578                 case LFUN_SPLIT_VIEW: {
2579                         LASSERT(doc_buffer, break);
2580                         string const orientation = cmd.getArg(0);
2581                         d.splitter_->setOrientation(orientation == "vertical"
2582                                 ? Qt::Vertical : Qt::Horizontal);
2583                         TabWorkArea * twa = addTabWorkArea();
2584                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
2585                         setCurrentWorkArea(wa);
2586                         break;
2587                 }
2588                 case LFUN_CLOSE_TAB_GROUP:
2589                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2590                                 closeTabWorkArea(twa);
2591                                 d.current_work_area_ = 0;
2592                                 twa = d.currentTabWorkArea();
2593                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
2594                                 if (twa) {
2595                                         // Make sure the work area is up to date.
2596                                         setCurrentWorkArea(twa->currentWorkArea());
2597                                 } else {
2598                                         setCurrentWorkArea(0);
2599                                 }
2600                         }
2601                         break;
2602                         
2603                 case LFUN_COMPLETION_INLINE:
2604                         if (d.current_work_area_)
2605                                 d.current_work_area_->completer().showInline();
2606                         break;
2607
2608                 case LFUN_COMPLETION_POPUP:
2609                         if (d.current_work_area_)
2610                                 d.current_work_area_->completer().showPopup();
2611                         break;
2612
2613
2614                 case LFUN_COMPLETION_COMPLETE:
2615                         if (d.current_work_area_)
2616                                 d.current_work_area_->completer().tab();
2617                         break;
2618
2619                 case LFUN_COMPLETION_CANCEL:
2620                         if (d.current_work_area_) {
2621                                 if (d.current_work_area_->completer().popupVisible())
2622                                         d.current_work_area_->completer().hidePopup();
2623                                 else
2624                                         d.current_work_area_->completer().hideInline();
2625                         }
2626                         break;
2627
2628                 case LFUN_COMPLETION_ACCEPT:
2629                         if (d.current_work_area_)
2630                                 d.current_work_area_->completer().activate();
2631                         break;
2632
2633                 case LFUN_BUFFER_ZOOM_IN:
2634                 case LFUN_BUFFER_ZOOM_OUT:
2635                         if (cmd.argument().empty()) {
2636                                 if (cmd.action == LFUN_BUFFER_ZOOM_IN)
2637                                         lyxrc.zoom += 20;
2638                                 else
2639                                         lyxrc.zoom -= 20;
2640                         } else
2641                                 lyxrc.zoom += convert<int>(cmd.argument());
2642
2643                         if (lyxrc.zoom < 10)
2644                                 lyxrc.zoom = 10;
2645                                 
2646                         // The global QPixmapCache is used in GuiPainter to cache text
2647                         // painting so we must reset it.
2648                         QPixmapCache::clear();
2649                         guiApp->fontLoader().update();
2650                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2651                         break;
2652
2653                 case LFUN_VC_REGISTER:
2654                 case LFUN_VC_CHECK_IN:
2655                 case LFUN_VC_CHECK_OUT:
2656                 case LFUN_VC_LOCKING_TOGGLE:
2657                 case LFUN_VC_REVERT:
2658                 case LFUN_VC_UNDO_LAST:
2659                 case LFUN_VC_COMMAND:
2660                         dispatchVC(cmd);
2661                         break;
2662
2663                 default:
2664                         dispatched = false;
2665                         break;
2666         }
2667
2668         // Part of automatic menu appearance feature.
2669         if (isFullScreen()) {
2670                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
2671                         menuBar()->hide();
2672                 if (statusBar()->isVisible())
2673                         statusBar()->hide();
2674         }
2675
2676         return dispatched;
2677 }
2678
2679
2680 void GuiView::lfunUiToggle(FuncRequest const & cmd)
2681 {
2682         string const arg = cmd.getArg(0);
2683         if (arg == "scrollbar") {
2684                 // hide() is of no help
2685                 if (d.current_work_area_->verticalScrollBarPolicy() ==
2686                         Qt::ScrollBarAlwaysOff)
2687
2688                         d.current_work_area_->setVerticalScrollBarPolicy(
2689                                 Qt::ScrollBarAsNeeded);
2690                 else
2691                         d.current_work_area_->setVerticalScrollBarPolicy(
2692                                 Qt::ScrollBarAlwaysOff);
2693                 return;
2694         }
2695         if (arg == "statusbar") {
2696                 statusBar()->setVisible(!statusBar()->isVisible());
2697                 return;
2698         }
2699         if (arg == "menubar") {
2700                 menuBar()->setVisible(!menuBar()->isVisible());
2701                 return;
2702         }
2703 #if QT_VERSION >= 0x040300
2704         if (arg == "frame") {
2705                 int l, t, r, b;
2706                 getContentsMargins(&l, &t, &r, &b);
2707                 //are the frames in default state?
2708                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
2709                 if (l == 0) {
2710                         setContentsMargins(-2, -2, -2, -2);
2711                 } else {
2712                         setContentsMargins(0, 0, 0, 0);
2713                 }
2714                 return;
2715         }
2716 #endif
2717         if (arg == "fullscreen") {
2718                 toggleFullScreen();
2719                 return;
2720         }
2721
2722         message(bformat("LFUN_UI_TOGGLE " + _("%1$s unknown command!"), from_utf8(arg)));
2723 }
2724
2725
2726 void GuiView::toggleFullScreen()
2727 {
2728         if (isFullScreen()) {
2729                 for (int i = 0; i != d.splitter_->count(); ++i)
2730                         d.tabWorkArea(i)->setFullScreen(false);
2731 #if QT_VERSION >= 0x040300
2732                 setContentsMargins(0, 0, 0, 0);
2733 #endif
2734                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2735                 restoreLayout();
2736                 menuBar()->show();
2737                 statusBar()->show();
2738         } else {
2739                 // bug 5274
2740                 hideDialogs("prefs", 0);
2741                 for (int i = 0; i != d.splitter_->count(); ++i)
2742                         d.tabWorkArea(i)->setFullScreen(true);
2743 #if QT_VERSION >= 0x040300
2744                 setContentsMargins(-2, -2, -2, -2);
2745 #endif
2746                 saveLayout();
2747                 setWindowState(windowState() ^ Qt::WindowFullScreen);
2748                 statusBar()->hide();
2749                 if (lyxrc.full_screen_menubar)
2750                         menuBar()->hide();
2751                 if (lyxrc.full_screen_toolbars) {
2752                         ToolbarMap::iterator end = d.toolbars_.end();
2753                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
2754                                 it->second->hide();
2755                 }
2756         }
2757
2758         // give dialogs like the TOC a chance to adapt
2759         updateDialogs();
2760 }
2761
2762
2763 Buffer const * GuiView::updateInset(Inset const * inset)
2764 {
2765         if (!d.current_work_area_)
2766                 return 0;
2767
2768         if (inset)
2769                 d.current_work_area_->scheduleRedraw();
2770
2771         return &d.current_work_area_->bufferView().buffer();
2772 }
2773
2774
2775 void GuiView::restartCursor()
2776 {
2777         /* When we move around, or type, it's nice to be able to see
2778          * the cursor immediately after the keypress.
2779          */
2780         if (d.current_work_area_)
2781                 d.current_work_area_->startBlinkingCursor();
2782
2783         // Take this occasion to update the other GUI elements.
2784         updateDialogs();
2785         updateStatusBar();
2786 }
2787
2788
2789 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
2790 {
2791         if (d.current_work_area_)
2792                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
2793 }
2794
2795 namespace {
2796
2797 // This list should be kept in sync with the list of insets in
2798 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
2799 // dialog should have the same name as the inset.
2800 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
2801 // docs in LyXAction.cpp.
2802
2803 char const * const dialognames[] = {
2804 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
2805 "citation", "document", "errorlist", "ert", "external", "file", "findreplace",
2806 "findreplaceadv", "float", "graphics", "href", "include", "index",
2807 "index_print", "info", "listings", "label", "log", "mathdelimiter",
2808 "mathmatrix", "mathspace", "nomenclature", "nomencl_print", "note",
2809 "paragraph", "phantom", "prefs", "print", "ref", "sendto", "space",
2810 "spellchecker", "symbols", "tabular", "tabularcreate", "thesaurus", "texinfo",
2811 "toc", "view-source", "vspace", "wrap" };
2812
2813 char const * const * const end_dialognames =
2814         dialognames + (sizeof(dialognames) / sizeof(char *));
2815
2816 class cmpCStr {
2817 public:
2818         cmpCStr(char const * name) : name_(name) {}
2819         bool operator()(char const * other) {
2820                 return strcmp(other, name_) == 0;
2821         }
2822 private:
2823         char const * name_;
2824 };
2825
2826
2827 bool isValidName(string const & name)
2828 {
2829         return find_if(dialognames, end_dialognames,
2830                             cmpCStr(name.c_str())) != end_dialognames;
2831 }
2832
2833 } // namespace anon
2834
2835
2836 void GuiView::resetDialogs()
2837 {
2838         // Make sure that no LFUN uses any LyXView.
2839         theLyXFunc().setLyXView(0);
2840         saveLayout();
2841         menuBar()->clear();
2842         constructToolbars();
2843         guiApp->menus().fillMenuBar(menuBar(), this, false);
2844         d.layout_->updateContents(true);
2845         // Now update controls with current buffer.
2846         theLyXFunc().setLyXView(this);
2847         restoreLayout();
2848         restartCursor();
2849 }
2850
2851
2852 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
2853 {
2854         if (!isValidName(name))
2855                 return 0;
2856
2857         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
2858
2859         if (it != d.dialogs_.end()) {
2860                 if (hide_it)
2861                         it->second->hideView();
2862                 return it->second.get();
2863         }
2864
2865         Dialog * dialog = build(name);
2866         d.dialogs_[name].reset(dialog);
2867         if (lyxrc.allow_geometry_session)
2868                 dialog->restoreSession();
2869         if (hide_it)
2870                 dialog->hideView();
2871         return dialog;
2872 }
2873
2874
2875 void GuiView::showDialog(string const & name, string const & data,
2876         Inset * inset)
2877 {
2878         if (d.in_show_)
2879                 return;
2880
2881         d.in_show_ = true;
2882         try {
2883                 Dialog * dialog = findOrBuild(name, false);
2884                 if (dialog) {
2885                         dialog->showData(data);
2886                         if (inset)
2887                                 d.open_insets_[name] = inset;
2888                 }
2889         }
2890         catch (ExceptionMessage const & ex) {
2891                 d.in_show_ = false;
2892                 throw ex;
2893         }
2894         d.in_show_ = false;
2895 }
2896
2897
2898 bool GuiView::isDialogVisible(string const & name) const
2899 {
2900         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2901         if (it == d.dialogs_.end())
2902                 return false;
2903         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
2904 }
2905
2906
2907 void GuiView::hideDialog(string const & name, Inset * inset)
2908 {
2909         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
2910         if (it == d.dialogs_.end())
2911                 return;
2912
2913         if (inset && inset != getOpenInset(name))
2914                 return;
2915
2916         Dialog * const dialog = it->second.get();
2917         if (dialog->isVisibleView())
2918                 dialog->hideView();
2919         d.open_insets_[name] = 0;
2920 }
2921
2922
2923 void GuiView::disconnectDialog(string const & name)
2924 {
2925         if (!isValidName(name))
2926                 return;
2927
2928         if (d.open_insets_.find(name) != d.open_insets_.end())
2929                 d.open_insets_[name] = 0;
2930 }
2931
2932
2933 Inset * GuiView::getOpenInset(string const & name) const
2934 {
2935         if (!isValidName(name))
2936                 return 0;
2937
2938         map<string, Inset *>::const_iterator it = d.open_insets_.find(name);
2939         return it == d.open_insets_.end() ? 0 : it->second;
2940 }
2941
2942
2943 void GuiView::hideAll() const
2944 {
2945         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2946         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2947
2948         for(; it != end; ++it)
2949                 it->second->hideView();
2950 }
2951
2952
2953 void GuiView::updateDialogs()
2954 {
2955         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
2956         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
2957
2958         for(; it != end; ++it) {
2959                 Dialog * dialog = it->second.get();
2960                 if (dialog && dialog->isVisibleView())
2961                         dialog->checkStatus();
2962         }
2963         updateToolbars();
2964         updateLayoutList();
2965 }
2966
2967
2968 // will be replaced by a proper factory...
2969 Dialog * createGuiAbout(GuiView & lv);
2970 Dialog * createGuiBibitem(GuiView & lv);
2971 Dialog * createGuiBibtex(GuiView & lv);
2972 Dialog * createGuiBox(GuiView & lv);
2973 Dialog * createGuiBranch(GuiView & lv);
2974 Dialog * createGuiChanges(GuiView & lv);
2975 Dialog * createGuiCharacter(GuiView & lv);
2976 Dialog * createGuiCitation(GuiView & lv);
2977 Dialog * createGuiDelimiter(GuiView & lv);
2978 Dialog * createGuiDocument(GuiView & lv);
2979 Dialog * createGuiErrorList(GuiView & lv);
2980 Dialog * createGuiERT(GuiView & lv);
2981 Dialog * createGuiExternal(GuiView & lv);
2982 Dialog * createGuiFloat(GuiView & lv);
2983 Dialog * createGuiGraphics(GuiView & lv);
2984 Dialog * createGuiInclude(GuiView & lv);
2985 Dialog * createGuiIndex(GuiView & lv);
2986 Dialog * createGuiInfo(GuiView & lv);
2987 Dialog * createGuiLabel(GuiView & lv);
2988 Dialog * createGuiListings(GuiView & lv);
2989 Dialog * createGuiLog(GuiView & lv);
2990 Dialog * createGuiMathHSpace(GuiView & lv);
2991 Dialog * createGuiMathMatrix(GuiView & lv);
2992 Dialog * createGuiNomenclature(GuiView & lv);
2993 Dialog * createGuiNote(GuiView & lv);
2994 Dialog * createGuiParagraph(GuiView & lv);
2995 Dialog * createGuiPhantom(GuiView & lv);
2996 Dialog * createGuiPreferences(GuiView & lv);
2997 Dialog * createGuiPrint(GuiView & lv);
2998 Dialog * createGuiPrintindex(GuiView & lv);
2999 Dialog * createGuiPrintNomencl(GuiView & lv);
3000 Dialog * createGuiRef(GuiView & lv);
3001 Dialog * createGuiSearch(GuiView & lv);
3002 Dialog * createGuiSearchAdv(GuiView & lv);
3003 Dialog * createGuiSendTo(GuiView & lv);
3004 Dialog * createGuiShowFile(GuiView & lv);
3005 Dialog * createGuiSpellchecker(GuiView & lv);
3006 Dialog * createGuiSymbols(GuiView & lv);
3007 Dialog * createGuiTabularCreate(GuiView & lv);
3008 Dialog * createGuiTabular(GuiView & lv);
3009 Dialog * createGuiTexInfo(GuiView & lv);
3010 Dialog * createGuiTextHSpace(GuiView & lv);
3011 Dialog * createGuiToc(GuiView & lv);
3012 Dialog * createGuiThesaurus(GuiView & lv);
3013 Dialog * createGuiHyperlink(GuiView & lv);
3014 Dialog * createGuiVSpace(GuiView & lv);
3015 Dialog * createGuiViewSource(GuiView & lv);
3016 Dialog * createGuiWrap(GuiView & lv);
3017
3018
3019 Dialog * GuiView::build(string const & name)
3020 {
3021         LASSERT(isValidName(name), return 0);
3022
3023         if (name == "aboutlyx")
3024                 return createGuiAbout(*this);
3025         if (name == "bibitem")
3026                 return createGuiBibitem(*this);
3027         if (name == "bibtex")
3028                 return createGuiBibtex(*this);
3029         if (name == "box")
3030                 return createGuiBox(*this);
3031         if (name == "branch")
3032                 return createGuiBranch(*this);
3033         if (name == "changes")
3034                 return createGuiChanges(*this);
3035         if (name == "character")
3036                 return createGuiCharacter(*this);
3037         if (name == "citation")
3038                 return createGuiCitation(*this);
3039         if (name == "document")
3040                 return createGuiDocument(*this);
3041         if (name == "errorlist")
3042                 return createGuiErrorList(*this);
3043         if (name == "ert")
3044                 return createGuiERT(*this);
3045         if (name == "external")
3046                 return createGuiExternal(*this);
3047         if (name == "file")
3048                 return createGuiShowFile(*this);
3049         if (name == "findreplace")
3050                 return createGuiSearch(*this);
3051         if (name == "findreplaceadv")
3052                 return createGuiSearchAdv(*this);
3053         if (name == "float")
3054                 return createGuiFloat(*this);
3055         if (name == "graphics")
3056                 return createGuiGraphics(*this);
3057         if (name == "href")
3058                 return createGuiHyperlink(*this);
3059         if (name == "include")
3060                 return createGuiInclude(*this);
3061         if (name == "index")
3062                 return createGuiIndex(*this);
3063         if (name == "index_print")
3064                 return createGuiPrintindex(*this);
3065         if (name == "info")
3066                 return createGuiInfo(*this);
3067         if (name == "label")
3068                 return createGuiLabel(*this);
3069         if (name == "listings")
3070                 return createGuiListings(*this);
3071         if (name == "log")
3072                 return createGuiLog(*this);
3073         if (name == "mathdelimiter")
3074                 return createGuiDelimiter(*this);
3075         if (name == "mathspace")
3076                 return createGuiMathHSpace(*this);
3077         if (name == "mathmatrix")
3078                 return createGuiMathMatrix(*this);
3079         if (name == "nomenclature")
3080                 return createGuiNomenclature(*this);
3081         if (name == "nomencl_print")
3082                 return createGuiPrintNomencl(*this);
3083         if (name == "note")
3084                 return createGuiNote(*this);
3085         if (name == "paragraph")
3086                 return createGuiParagraph(*this);
3087         if (name == "phantom")
3088                 return createGuiPhantom(*this);
3089         if (name == "prefs")
3090                 return createGuiPreferences(*this);
3091         if (name == "print")
3092                 return createGuiPrint(*this);
3093         if (name == "ref")
3094                 return createGuiRef(*this);
3095         if (name == "sendto")
3096                 return createGuiSendTo(*this);
3097         if (name == "space")
3098                 return createGuiTextHSpace(*this);
3099         if (name == "spellchecker")
3100                 return createGuiSpellchecker(*this);
3101         if (name == "symbols")
3102                 return createGuiSymbols(*this);
3103         if (name == "tabular")
3104                 return createGuiTabular(*this);
3105         if (name == "tabularcreate")
3106                 return createGuiTabularCreate(*this);
3107         if (name == "texinfo")
3108                 return createGuiTexInfo(*this);
3109         if (name == "thesaurus")
3110                 return createGuiThesaurus(*this);
3111         if (name == "toc")
3112                 return createGuiToc(*this);
3113         if (name == "view-source")
3114                 return createGuiViewSource(*this);
3115         if (name == "vspace")
3116                 return createGuiVSpace(*this);
3117         if (name == "wrap")
3118                 return createGuiWrap(*this);
3119
3120         return 0;
3121 }
3122
3123
3124 } // namespace frontend
3125 } // namespace lyx
3126
3127 #include "moc_GuiView.cpp"