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