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