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