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