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