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