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