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