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