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