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