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