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