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