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