]> git.lyx.org Git - features.git/blob - src/frontends/qt4/GuiView.cpp
d1d0336be5f15256994ff3da8c81abd1f4905ed6
[features.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "Dialog.h"
19 #include "DispatchResult.h"
20 #include "FileDialog.h"
21 #include "FontLoader.h"
22 #include "GuiApplication.h"
23 #include "GuiCommandBuffer.h"
24 #include "GuiCompleter.h"
25 #include "GuiKeySymbol.h"
26 #include "GuiToc.h"
27 #include "GuiToolbar.h"
28 #include "GuiWorkArea.h"
29 #include "GuiProgress.h"
30 #include "LayoutBox.h"
31 #include "Menus.h"
32 #include "TocModel.h"
33
34 #include "qt_helpers.h"
35
36 #include "frontends/alert.h"
37
38 #include "buffer_funcs.h"
39 #include "Buffer.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "Compare.h"
44 #include "Converter.h"
45 #include "Cursor.h"
46 #include "CutAndPaste.h"
47 #include "Encoding.h"
48 #include "ErrorList.h"
49 #include "Format.h"
50 #include "FuncStatus.h"
51 #include "FuncRequest.h"
52 #include "Intl.h"
53 #include "Layout.h"
54 #include "Lexer.h"
55 #include "LyXAction.h"
56 #include "LyX.h"
57 #include "LyXRC.h"
58 #include "LyXVC.h"
59 #include "Paragraph.h"
60 #include "SpellChecker.h"
61 #include "TexRow.h"
62 #include "TextClass.h"
63 #include "Text.h"
64 #include "Toolbars.h"
65 #include "version.h"
66
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/ExceptionMessage.h"
70 #include "support/FileName.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/filetools.h"
74 #include "support/ForkedCalls.h"
75 #include "support/lassert.h"
76 #include "support/lstrings.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/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         QObject::disconnect(d.current_work_area_, SIGNAL(busy(bool)),
998                 this, SLOT(setBusy(bool)));
999         disconnectBuffer();
1000         disconnectBufferView();
1001         connectBufferView(wa->bufferView());
1002         connectBuffer(wa->bufferView().buffer());
1003         d.current_work_area_ = wa;
1004         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
1005                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
1006         QObject::connect(wa, SIGNAL(busy(bool)), this, SLOT(setBusy(bool)));
1007         updateWindowTitle(wa);
1008
1009         structureChanged();
1010
1011         // The document settings needs to be reinitialised.
1012         updateDialog("document", "");
1013
1014         // Buffer-dependent dialogs must be updated. This is done here because
1015         // some dialogs require buffer()->text.
1016         updateDialogs();
1017 }
1018
1019
1020 void GuiView::on_lastWorkAreaRemoved()
1021 {
1022         if (closing_)
1023                 // We already are in a close event. Nothing more to do.
1024                 return;
1025
1026         if (d.splitter_->count() > 1)
1027                 // We have a splitter so don't close anything.
1028                 return;
1029
1030         // Reset and updates the dialogs.
1031         d.toc_models_.reset(0);
1032         updateDialog("document", "");
1033         updateDialogs();
1034
1035         resetWindowTitleAndIconText();
1036         updateStatusBar();
1037
1038         if (lyxrc.open_buffers_in_tabs)
1039                 // Nothing more to do, the window should stay open.
1040                 return;
1041
1042         if (guiApp->viewIds().size() > 1) {
1043                 close();
1044                 return;
1045         }
1046
1047 #ifdef Q_WS_MACX
1048         // On Mac we also close the last window because the application stay
1049         // resident in memory. On other platforms we don't close the last
1050         // window because this would quit the application.
1051         close();
1052 #endif
1053 }
1054
1055
1056 void GuiView::updateStatusBar()
1057 {
1058         // let the user see the explicit message
1059         if (d.statusbar_timer_.isActive())
1060                 return;
1061
1062         showMessage();
1063 }
1064
1065
1066 void GuiView::showMessage()
1067 {
1068         QString msg = toqstr(theGuiApp()->viewStatusMessage());
1069         if (msg.isEmpty()) {
1070                 BufferView const * bv = currentBufferView();
1071                 if (bv)
1072                         msg = toqstr(bv->cursor().currentState());
1073                 else
1074                         msg = qt_("Welcome to LyX!");
1075         }
1076         statusBar()->showMessage(msg);
1077 }
1078
1079
1080 bool GuiView::event(QEvent * e)
1081 {
1082         switch (e->type())
1083         {
1084         // Useful debug code:
1085         //case QEvent::ActivationChange:
1086         //case QEvent::WindowDeactivate:
1087         //case QEvent::Paint:
1088         //case QEvent::Enter:
1089         //case QEvent::Leave:
1090         //case QEvent::HoverEnter:
1091         //case QEvent::HoverLeave:
1092         //case QEvent::HoverMove:
1093         //case QEvent::StatusTip:
1094         //case QEvent::DragEnter:
1095         //case QEvent::DragLeave:
1096         //case QEvent::Drop:
1097         //      break;
1098
1099         case QEvent::WindowActivate: {
1100                 GuiView * old_view = guiApp->currentView();
1101                 if (this == old_view) {
1102                         setFocus();
1103                         return QMainWindow::event(e);
1104                 }
1105                 if (old_view && old_view->currentBufferView()) {
1106                         // save current selection to the selection buffer to allow
1107                         // middle-button paste in this window.
1108                         cap::saveSelection(old_view->currentBufferView()->cursor());
1109                 }
1110                 guiApp->setCurrentView(this);
1111                 if (d.current_work_area_) {
1112                         BufferView & bv = d.current_work_area_->bufferView();
1113                         connectBufferView(bv);
1114                         connectBuffer(bv.buffer());
1115                         // The document structure, name and dialogs might have
1116                         // changed in another view.
1117                         structureChanged();
1118                         // The document settings needs to be reinitialised.
1119                         updateDialog("document", "");
1120                         updateDialogs();
1121                 } else {
1122                         resetWindowTitleAndIconText();
1123                 }
1124                 setFocus();
1125                 return QMainWindow::event(e);
1126         }
1127
1128         case QEvent::ShortcutOverride: {
1129
1130 // See bug 4888
1131 #if (!defined Q_WS_X11) || (QT_VERSION >= 0x040500)
1132                 if (isFullScreen() && menuBar()->isHidden()) {
1133                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
1134                         // FIXME: we should also try to detect special LyX shortcut such as
1135                         // Alt-P and Alt-M. Right now there is a hack in
1136                         // GuiWorkArea::processKeySym() that hides again the menubar for
1137                         // those cases.
1138                         if (ke->modifiers() & Qt::AltModifier && ke->key() != Qt::Key_Alt) {
1139                                 menuBar()->show();
1140                                 return QMainWindow::event(e);
1141                         }
1142                 }
1143 #endif
1144                 return QMainWindow::event(e);
1145         }
1146
1147         default:
1148                 return QMainWindow::event(e);
1149         }
1150 }
1151
1152 void GuiView::resetWindowTitleAndIconText()
1153 {
1154         setWindowTitle(qt_("LyX"));
1155         setWindowIconText(qt_("LyX"));
1156 }
1157
1158 bool GuiView::focusNextPrevChild(bool /*next*/)
1159 {
1160         setFocus();
1161         return true;
1162 }
1163
1164
1165 bool GuiView::busy() const
1166 {
1167         return busy_ > 0;
1168 }
1169
1170
1171 void GuiView::setBusy(bool busy)
1172 {
1173         bool const busy_before = busy_ > 0;
1174         busy ? ++busy_ : --busy_;
1175         if ((busy_ > 0) == busy_before)
1176                 // busy state didn't change
1177                 return;
1178
1179         if (busy) {
1180                 QApplication::setOverrideCursor(Qt::WaitCursor);
1181                 return;
1182         }
1183         QApplication::restoreOverrideCursor();
1184         updateLayoutList();     
1185 }
1186
1187
1188 GuiWorkArea * GuiView::workArea(int index)
1189 {
1190         if (TabWorkArea * twa = d.currentTabWorkArea())
1191                 if (index < twa->count())
1192                         return dynamic_cast<GuiWorkArea *>(twa->widget(index));
1193         return 0;
1194 }
1195
1196
1197 GuiWorkArea * GuiView::workArea(Buffer & buffer)
1198 {
1199         if (currentWorkArea()
1200                 && &currentWorkArea()->bufferView().buffer() == &buffer)
1201                 return (GuiWorkArea *) currentWorkArea();
1202         if (TabWorkArea * twa = d.currentTabWorkArea())
1203                 return twa->workArea(buffer);
1204         return 0;
1205 }
1206
1207
1208 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
1209 {
1210         // Automatically create a TabWorkArea if there are none yet.
1211         TabWorkArea * tab_widget = d.splitter_->count()
1212                 ? d.currentTabWorkArea() : addTabWorkArea();
1213         return tab_widget->addWorkArea(buffer, *this);
1214 }
1215
1216
1217 TabWorkArea * GuiView::addTabWorkArea()
1218 {
1219         TabWorkArea * twa = new TabWorkArea;
1220         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
1221                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
1222         QObject::connect(twa, SIGNAL(lastWorkAreaRemoved()),
1223                          this, SLOT(on_lastWorkAreaRemoved()));
1224
1225         d.splitter_->addWidget(twa);
1226         d.stack_widget_->setCurrentWidget(d.splitter_);
1227         return twa;
1228 }
1229
1230
1231 GuiWorkArea const * GuiView::currentWorkArea() const
1232 {
1233         return d.current_work_area_;
1234 }
1235
1236
1237 GuiWorkArea * GuiView::currentWorkArea()
1238 {
1239         return d.current_work_area_;
1240 }
1241
1242
1243 GuiWorkArea const * GuiView::currentMainWorkArea() const
1244 {
1245         if (!d.currentTabWorkArea())
1246                 return 0;
1247         return d.currentTabWorkArea()->currentWorkArea();
1248 }
1249
1250
1251 GuiWorkArea * GuiView::currentMainWorkArea()
1252 {
1253         if (!d.currentTabWorkArea())
1254                 return 0;
1255         return d.currentTabWorkArea()->currentWorkArea();
1256 }
1257
1258
1259 void GuiView::setCurrentWorkArea(GuiWorkArea * wa)
1260 {
1261         LYXERR(Debug::DEBUG, "Setting current wa: " << wa << endl);
1262         if (!wa) {
1263                 d.current_work_area_ = 0;
1264                 d.setBackground();
1265                 return;
1266         }
1267
1268         // FIXME: I've no clue why this is here and why it accesses
1269         //  theGuiApp()->currentView, which might be 0 (bug 6464).
1270         //  See also 27525 (vfr).
1271         if (theGuiApp()->currentView() == this
1272                   && theGuiApp()->currentView()->currentWorkArea() == wa)
1273                 return;
1274
1275         if (currentBufferView())
1276                 cap::saveSelection(currentBufferView()->cursor());
1277
1278         theGuiApp()->setCurrentView(this);
1279         d.current_work_area_ = wa;
1280         
1281         // We need to reset this now, because it will need to be
1282         // right if the tabWorkArea gets reset in the for loop. We
1283         // will change it back if we aren't in that case.
1284         GuiWorkArea * const old_cmwa = d.current_main_work_area_;
1285         d.current_main_work_area_ = wa;
1286
1287         for (int i = 0; i != d.splitter_->count(); ++i) {
1288                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa)) {
1289                         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() 
1290                                 << ", Current main wa: " << currentMainWorkArea());
1291                         return;
1292                 }
1293         }
1294         
1295         d.current_main_work_area_ = old_cmwa;
1296         
1297         LYXERR(Debug::DEBUG, "This is not a tabbed wa");
1298         on_currentWorkAreaChanged(wa);
1299         BufferView & bv = wa->bufferView();
1300         bv.cursor().fixIfBroken();
1301         bv.updateMetrics();
1302         wa->setUpdatesEnabled(true);
1303         LYXERR(Debug::DEBUG, "Current wa: " << currentWorkArea() << ", Current main wa: " << currentMainWorkArea());
1304 }
1305
1306
1307 void GuiView::removeWorkArea(GuiWorkArea * wa)
1308 {
1309         LASSERT(wa, return);
1310         if (wa == d.current_work_area_) {
1311                 disconnectBuffer();
1312                 disconnectBufferView();
1313                 d.current_work_area_ = 0;
1314                 d.current_main_work_area_ = 0;
1315         }
1316
1317         bool found_twa = false;
1318         for (int i = 0; i != d.splitter_->count(); ++i) {
1319                 TabWorkArea * twa = d.tabWorkArea(i);
1320                 if (twa->removeWorkArea(wa)) {
1321                         // Found in this tab group, and deleted the GuiWorkArea.
1322                         found_twa = true;
1323                         if (twa->count() != 0) {
1324                                 if (d.current_work_area_ == 0)
1325                                         // This means that we are closing the current GuiWorkArea, so
1326                                         // switch to the next GuiWorkArea in the found TabWorkArea.
1327                                         setCurrentWorkArea(twa->currentWorkArea());
1328                         } else {
1329                                 // No more WorkAreas in this tab group, so delete it.
1330                                 delete twa;
1331                         }
1332                         break;
1333                 }
1334         }
1335
1336         // It is not a tabbed work area (i.e., the search work area), so it
1337         // should be deleted by other means.
1338         LASSERT(found_twa, /* */);
1339
1340         if (d.current_work_area_ == 0) {
1341                 if (d.splitter_->count() != 0) {
1342                         TabWorkArea * twa = d.currentTabWorkArea();
1343                         setCurrentWorkArea(twa->currentWorkArea());
1344                 } else {
1345                         // No more work areas, switch to the background widget.
1346                         setCurrentWorkArea(0);
1347                 }
1348         }
1349 }
1350
1351
1352 LayoutBox * GuiView::getLayoutDialog() const
1353 {
1354         return d.layout_;
1355 }
1356
1357
1358 void GuiView::updateLayoutList()
1359 {
1360         if (d.layout_)
1361                 d.layout_->updateContents(false);
1362 }
1363
1364
1365 void GuiView::updateToolbars()
1366 {
1367         ToolbarMap::iterator end = d.toolbars_.end();
1368         if (d.current_work_area_) {
1369                 bool const math =
1370                         d.current_work_area_->bufferView().cursor().inMathed()
1371                         && !d.current_work_area_->bufferView().cursor().inRegexped();
1372                 bool const table =
1373                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1374                 bool const review =
1375                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1376                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onOff(true);
1377                 bool const mathmacrotemplate =
1378                         lyx::getStatus(FuncRequest(LFUN_IN_MATHMACROTEMPLATE)).enabled();
1379
1380                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1381                         it->second->update(math, table, review, mathmacrotemplate);
1382         } else
1383                 for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
1384                         it->second->update(false, false, false, false);
1385 }
1386
1387
1388 void GuiView::setBuffer(Buffer * newBuffer)
1389 {
1390         LYXERR(Debug::DEBUG, "Setting buffer: " << newBuffer << endl);
1391         LASSERT(newBuffer, return);
1392         
1393         GuiWorkArea * wa = workArea(*newBuffer);
1394         if (wa == 0) {
1395                 setBusy(true);
1396                 newBuffer->masterBuffer()->updateBuffer();
1397                 setBusy(false);
1398                 wa = addWorkArea(*newBuffer);
1399                 // scroll to the position when the BufferView was last closed
1400                 if (lyxrc.use_lastfilepos) {
1401                         LastFilePosSection::FilePos filepos =
1402                                 theSession().lastFilePos().load(newBuffer->fileName());
1403                         wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1404                 }
1405         } else {
1406                 //Disconnect the old buffer...there's no new one.
1407                 disconnectBuffer();
1408         }
1409         connectBuffer(*newBuffer);
1410         connectBufferView(wa->bufferView());
1411         setCurrentWorkArea(wa);
1412 }
1413
1414
1415 void GuiView::connectBuffer(Buffer & buf)
1416 {
1417         buf.setGuiDelegate(this);
1418 }
1419
1420
1421 void GuiView::disconnectBuffer()
1422 {
1423         if (d.current_work_area_)
1424                 d.current_work_area_->bufferView().buffer().setGuiDelegate(0);
1425 }
1426
1427
1428 void GuiView::connectBufferView(BufferView & bv)
1429 {
1430         bv.setGuiDelegate(this);
1431 }
1432
1433
1434 void GuiView::disconnectBufferView()
1435 {
1436         if (d.current_work_area_)
1437                 d.current_work_area_->bufferView().setGuiDelegate(0);
1438 }
1439
1440
1441 void GuiView::errors(string const & error_type, bool from_master)
1442 {
1443         BufferView const * const bv = currentBufferView();
1444         if (!bv)
1445                 return;
1446
1447 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
1448         // We are called with from_master == false by default, so we
1449         // have to figure out whether that is the case or not.
1450         ErrorList & el = bv->buffer().errorList(error_type);
1451         if (el.empty()) {
1452             el = bv->buffer().masterBuffer()->errorList(error_type);
1453             from_master = true;
1454         }
1455 #else
1456         ErrorList const & el = from_master ?
1457                 bv->buffer().masterBuffer()->errorList(error_type) :
1458                 bv->buffer().errorList(error_type);
1459 #endif
1460
1461         if (el.empty())
1462                 return;
1463
1464         string data = error_type;
1465         if (from_master)
1466                 data = "from_master|" + error_type;
1467         showDialog("errorlist", data);
1468 }
1469
1470
1471 void GuiView::updateTocItem(string const & type, DocIterator const & dit)
1472 {
1473         d.toc_models_.updateItem(toqstr(type), dit);
1474 }
1475
1476
1477 void GuiView::structureChanged()
1478 {
1479         d.toc_models_.reset(documentBufferView());
1480         // Navigator needs more than a simple update in this case. It needs to be
1481         // rebuilt.
1482         updateDialog("toc", "");
1483 }
1484
1485
1486 void GuiView::updateDialog(string const & name, string const & data)
1487 {
1488         if (!isDialogVisible(name))
1489                 return;
1490
1491         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
1492         if (it == d.dialogs_.end())
1493                 return;
1494
1495         Dialog * const dialog = it->second.get();
1496         if (dialog->isVisibleView())
1497                 dialog->initialiseParams(data);
1498 }
1499
1500
1501 BufferView * GuiView::documentBufferView()
1502 {
1503         return currentMainWorkArea()
1504                 ? &currentMainWorkArea()->bufferView()
1505                 : 0;
1506 }
1507
1508
1509 BufferView const * GuiView::documentBufferView() const
1510 {
1511         return currentMainWorkArea()
1512                 ? &currentMainWorkArea()->bufferView()
1513                 : 0;
1514 }
1515
1516
1517 BufferView * GuiView::currentBufferView()
1518 {
1519         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1520 }
1521
1522
1523 BufferView const * GuiView::currentBufferView() const
1524 {
1525         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1526 }
1527
1528
1529 #if (QT_VERSION >= 0x040400)
1530 docstring GuiView::GuiViewPrivate::autosaveAndDestroy(
1531         Buffer const * orig, Buffer * buffer)
1532 {
1533         bool const success = buffer->autoSave();
1534         delete buffer;
1535         busyBuffers.remove(orig);
1536         return success
1537                 ? _("Automatic save done.")
1538                 : _("Automatic save failed!");
1539 }
1540 #endif
1541
1542
1543 void GuiView::autoSave()
1544 {
1545         LYXERR(Debug::INFO, "Running autoSave()");
1546
1547         Buffer * buffer = documentBufferView()
1548                 ? &documentBufferView()->buffer() : 0;
1549         if (!buffer) {
1550                 resetAutosaveTimers();
1551                 return;
1552         }
1553
1554 #if (QT_VERSION >= 0x040400)
1555         GuiViewPrivate::busyBuffers.insert(buffer);
1556         QFuture<docstring> f = QtConcurrent::run(GuiViewPrivate::autosaveAndDestroy,
1557                 buffer, buffer->clone());
1558         d.autosave_watcher_.setFuture(f);
1559 #else
1560         buffer->autoSave();
1561 #endif
1562         resetAutosaveTimers();
1563 }
1564
1565
1566 void GuiView::resetAutosaveTimers()
1567 {
1568         if (lyxrc.autosave)
1569                 d.autosave_timeout_.restart();
1570 }
1571
1572
1573 bool GuiView::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1574 {
1575         bool enable = true;
1576         Buffer * buf = currentBufferView()
1577                 ? &currentBufferView()->buffer() : 0;
1578         Buffer * doc_buffer = documentBufferView()
1579                 ? &(documentBufferView()->buffer()) : 0;
1580
1581         // Check whether we need a buffer
1582         if (!lyxaction.funcHasFlag(cmd.action(), LyXAction::NoBuffer) && !buf) {
1583                 // no, exit directly
1584                 flag.message(from_utf8(N_("Command not allowed with"
1585                                         "out any document open")));
1586                 flag.setEnabled(false);
1587                 return true;
1588         }
1589
1590         if (cmd.origin() == FuncRequest::TOC) {
1591                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
1592                 if (!toc || !toc->getStatus(documentBufferView()->cursor(), cmd, flag))
1593                         flag.setEnabled(false);
1594                 return true;
1595         }
1596
1597         switch(cmd.action()) {
1598         case LFUN_BUFFER_IMPORT:
1599                 break;
1600
1601         case LFUN_MASTER_BUFFER_UPDATE:
1602         case LFUN_MASTER_BUFFER_VIEW:
1603                 enable = doc_buffer && doc_buffer->parent() != 0
1604                         && !d.processing_thread_watcher_.isRunning();
1605                 break;
1606
1607         case LFUN_BUFFER_UPDATE:
1608         case LFUN_BUFFER_VIEW: {
1609                 if (!doc_buffer || d.processing_thread_watcher_.isRunning()) {
1610                         enable = false;
1611                         break;
1612                 }
1613                 string format = to_utf8(cmd.argument());
1614                 if (cmd.argument().empty())
1615                         format = doc_buffer->params().getDefaultOutputFormat();
1616                 enable = doc_buffer->params().isExportableFormat(format);
1617                 break;
1618         }
1619
1620         case LFUN_BUFFER_RELOAD:
1621                 enable = doc_buffer && !doc_buffer->isUnnamed()
1622                         && doc_buffer->fileName().exists()
1623                         && (!doc_buffer->isClean()
1624                            || doc_buffer->isExternallyModified(Buffer::timestamp_method));
1625                 break;
1626
1627         case LFUN_BUFFER_CHILD_OPEN:
1628                 enable = doc_buffer;
1629                 break;
1630
1631         case LFUN_BUFFER_WRITE:
1632                 enable = doc_buffer && (doc_buffer->isUnnamed() || !doc_buffer->isClean());
1633                 break;
1634
1635         //FIXME: This LFUN should be moved to GuiApplication.
1636         case LFUN_BUFFER_WRITE_ALL: {
1637                 // We enable the command only if there are some modified buffers
1638                 Buffer * first = theBufferList().first();
1639                 enable = false;
1640                 if (!first)
1641                         break;
1642                 Buffer * b = first;
1643                 // We cannot use a for loop as the buffer list is a cycle.
1644                 do {
1645                         if (!b->isClean()) {
1646                                 enable = true;
1647                                 break;
1648                         }
1649                         b = theBufferList().next(b);
1650                 } while (b != first);
1651                 break;
1652         }
1653
1654         case LFUN_BUFFER_WRITE_AS:
1655         case LFUN_BUFFER_EXPORT_AS:
1656                 enable = doc_buffer;
1657                 break;
1658
1659         case LFUN_BUFFER_CLOSE:
1660                 enable = doc_buffer;
1661                 break;
1662
1663         case LFUN_BUFFER_CLOSE_ALL:
1664                 enable = theBufferList().last() != theBufferList().first();
1665                 break;
1666
1667         case LFUN_SPLIT_VIEW:
1668                 if (cmd.getArg(0) == "vertical")
1669                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1670                                          d.splitter_->orientation() == Qt::Vertical);
1671                 else
1672                         enable = doc_buffer && (d.splitter_->count() == 1 ||
1673                                          d.splitter_->orientation() == Qt::Horizontal);
1674                 break;
1675
1676         case LFUN_CLOSE_TAB_GROUP:
1677                 enable = d.currentTabWorkArea();
1678                 break;
1679
1680         case LFUN_TOOLBAR_TOGGLE: {
1681                 string const name = cmd.getArg(0);
1682                 if (GuiToolbar * t = toolbar(name))
1683                         flag.setOnOff(t->isVisible());
1684                 else {
1685                         enable = false;
1686                         docstring const msg =
1687                                 bformat(_("Unknown toolbar \"%1$s\""), from_utf8(name));
1688                         flag.message(msg);
1689                 }
1690                 break;
1691         }
1692
1693         case LFUN_DROP_LAYOUTS_CHOICE:
1694                 enable = buf;
1695                 break;
1696
1697         case LFUN_UI_TOGGLE:
1698                 flag.setOnOff(isFullScreen());
1699                 break;
1700
1701         case LFUN_DIALOG_DISCONNECT_INSET:
1702                 break;
1703
1704         case LFUN_DIALOG_HIDE:
1705                 // FIXME: should we check if the dialog is shown?
1706                 break;
1707
1708         case LFUN_DIALOG_TOGGLE:
1709                 flag.setOnOff(isDialogVisible(cmd.getArg(0)));
1710                 // fall through to set "enable"
1711         case LFUN_DIALOG_SHOW: {
1712                 string const name = cmd.getArg(0);
1713                 if (!doc_buffer)
1714                         enable = name == "aboutlyx"
1715                                 || name == "file" //FIXME: should be removed.
1716                                 || name == "prefs"
1717                                 || name == "texinfo"
1718                                 || name == "progress"
1719                                 || name == "compare";
1720                 else if (name == "print")
1721                         enable = doc_buffer->params().isExportable("dvi")
1722                                 && lyxrc.print_command != "none";
1723                 else if (name == "character" || name == "symbols") {
1724                         if (!buf || buf->isReadonly())
1725                                 enable = false;
1726                         else {
1727                                 Cursor const & cur = currentBufferView()->cursor();
1728                                 enable = !(cur.inTexted() && cur.paragraph().isPassThru());
1729                         }
1730                 }
1731                 else if (name == "latexlog")
1732                         enable = FileName(doc_buffer->logName()).isReadableFile();
1733                 else if (name == "spellchecker")
1734                         enable = theSpellChecker() && !doc_buffer->isReadonly();
1735                 else if (name == "vclog")
1736                         enable = doc_buffer->lyxvc().inUse();
1737                 break;
1738         }
1739
1740         case LFUN_DIALOG_UPDATE: {
1741                 string const name = cmd.getArg(0);
1742                 if (!buf)
1743                         enable = name == "prefs";
1744                 break;
1745         }
1746
1747         case LFUN_COMMAND_EXECUTE:
1748         case LFUN_MESSAGE:
1749         case LFUN_MENU_OPEN:
1750                 // Nothing to check.
1751                 break;
1752
1753         case LFUN_COMPLETION_INLINE:
1754                 if (!d.current_work_area_
1755                         || !d.current_work_area_->completer().inlinePossible(
1756                         currentBufferView()->cursor()))
1757                         enable = false;
1758                 break;
1759
1760         case LFUN_COMPLETION_POPUP:
1761                 if (!d.current_work_area_
1762                         || !d.current_work_area_->completer().popupPossible(
1763                         currentBufferView()->cursor()))
1764                         enable = false;
1765                 break;
1766
1767         case LFUN_COMPLETION_COMPLETE:
1768                 if (!d.current_work_area_
1769                         || !d.current_work_area_->completer().inlinePossible(
1770                         currentBufferView()->cursor()))
1771                         enable = false;
1772                 break;
1773
1774         case LFUN_COMPLETION_ACCEPT:
1775                 if (!d.current_work_area_
1776                         || (!d.current_work_area_->completer().popupVisible()
1777                         && !d.current_work_area_->completer().inlineVisible()
1778                         && !d.current_work_area_->completer().completionAvailable()))
1779                         enable = false;
1780                 break;
1781
1782         case LFUN_COMPLETION_CANCEL:
1783                 if (!d.current_work_area_
1784                         || (!d.current_work_area_->completer().popupVisible()
1785                         && !d.current_work_area_->completer().inlineVisible()))
1786                         enable = false;
1787                 break;
1788
1789         case LFUN_BUFFER_ZOOM_OUT:
1790                 enable = doc_buffer && lyxrc.zoom > 10;
1791                 break;
1792
1793         case LFUN_BUFFER_ZOOM_IN:
1794                 enable = doc_buffer;
1795                 break;
1796
1797         case LFUN_BUFFER_NEXT:
1798         case LFUN_BUFFER_PREVIOUS:
1799                 // FIXME: should we check is there is an previous or next buffer?
1800                 break;
1801         case LFUN_BUFFER_SWITCH:
1802                 // toggle on the current buffer, but do not toggle off
1803                 // the other ones (is that a good idea?)
1804                 if (doc_buffer
1805                         && to_utf8(cmd.argument()) == doc_buffer->absFileName())
1806                         flag.setOnOff(true);
1807                 break;
1808
1809         case LFUN_VC_REGISTER:
1810                 enable = doc_buffer && !doc_buffer->lyxvc().inUse();
1811                 break;
1812         case LFUN_VC_CHECK_IN:
1813                 enable = doc_buffer && doc_buffer->lyxvc().checkInEnabled();
1814                 break;
1815         case LFUN_VC_CHECK_OUT:
1816                 enable = doc_buffer && doc_buffer->lyxvc().checkOutEnabled();
1817                 break;
1818         case LFUN_VC_LOCKING_TOGGLE:
1819                 enable = doc_buffer && !doc_buffer->isReadonly()
1820                         && doc_buffer->lyxvc().lockingToggleEnabled();
1821                 flag.setOnOff(enable && doc_buffer->lyxvc().locking());
1822                 break;
1823         case LFUN_VC_REVERT:
1824                 enable = doc_buffer && doc_buffer->lyxvc().inUse() && !doc_buffer->isReadonly();
1825                 break;
1826         case LFUN_VC_UNDO_LAST:
1827                 enable = doc_buffer && doc_buffer->lyxvc().undoLastEnabled();
1828                 break;
1829         case LFUN_VC_REPO_UPDATE:
1830                 enable = doc_buffer && doc_buffer->lyxvc().repoUpdateEnabled();
1831                 break;
1832         case LFUN_VC_COMMAND: {
1833                 if (cmd.argument().empty())
1834                         enable = false;
1835                 if (!doc_buffer && contains(cmd.getArg(0), 'D'))
1836                         enable = false;
1837                 break;
1838         }
1839         case LFUN_VC_COMPARE:
1840                 enable = doc_buffer && doc_buffer->lyxvc().prepareFileRevisionEnabled();
1841                 break;
1842
1843         case LFUN_SERVER_GOTO_FILE_ROW:
1844                 break;
1845         case LFUN_FORWARD_SEARCH:
1846                 enable = !(lyxrc.forward_search_dvi.empty() && lyxrc.forward_search_pdf.empty());
1847                 break;
1848
1849         default:
1850                 return false;
1851         }
1852
1853         if (!enable)
1854                 flag.setEnabled(false);
1855
1856         return true;
1857 }
1858
1859
1860 static FileName selectTemplateFile()
1861 {
1862         FileDialog dlg(qt_("Select template file"));
1863         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1864         dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
1865
1866         FileDialog::Result result = dlg.open(toqstr(lyxrc.template_path),
1867                                  QStringList(qt_("LyX Documents (*.lyx)")));
1868
1869         if (result.first == FileDialog::Later)
1870                 return FileName();
1871         if (result.second.isEmpty())
1872                 return FileName();
1873         return FileName(fromqstr(result.second));
1874 }
1875
1876
1877 Buffer * GuiView::loadDocument(FileName const & filename, bool tolastfiles)
1878 {
1879         setBusy(true);
1880
1881         Buffer * newBuffer = 0;
1882         try {
1883                 newBuffer = checkAndLoadLyXFile(filename);
1884         } catch (ExceptionMessage const & e) {
1885                 setBusy(false);
1886                 throw(e);
1887         }
1888         setBusy(false);
1889
1890         if (!newBuffer) {
1891                 message(_("Document not loaded."));
1892                 return 0;
1893         }
1894
1895         setBuffer(newBuffer);
1896         newBuffer->errors("Parse");
1897
1898         if (tolastfiles)
1899                 theSession().lastFiles().add(filename);
1900
1901         return newBuffer;
1902 }
1903
1904
1905 void GuiView::openDocument(string const & fname)
1906 {
1907         string initpath = lyxrc.document_path;
1908
1909         if (documentBufferView()) {
1910                 string const trypath = documentBufferView()->buffer().filePath();
1911                 // If directory is writeable, use this as default.
1912                 if (FileName(trypath).isDirWritable())
1913                         initpath = trypath;
1914         }
1915
1916         string filename;
1917
1918         if (fname.empty()) {
1919                 FileDialog dlg(qt_("Select document to open"), LFUN_FILE_OPEN);
1920                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
1921                 dlg.setButton2(qt_("Examples|#E#e"),
1922                                 toqstr(addPath(package().system_support().absFileName(), "examples")));
1923
1924                 QStringList filter(qt_("LyX Documents (*.lyx)"));
1925                 filter << qt_("LyX-1.3.x Documents (*.lyx13)")
1926                         << qt_("LyX-1.4.x Documents (*.lyx14)")
1927                         << qt_("LyX-1.5.x Documents (*.lyx15)")
1928                         << qt_("LyX-1.6.x Documents (*.lyx16)");
1929                 FileDialog::Result result =
1930                         dlg.open(toqstr(initpath), filter);
1931
1932                 if (result.first == FileDialog::Later)
1933                         return;
1934
1935                 filename = fromqstr(result.second);
1936
1937                 // check selected filename
1938                 if (filename.empty()) {
1939                         message(_("Canceled."));
1940                         return;
1941                 }
1942         } else
1943                 filename = fname;
1944
1945         // get absolute path of file and add ".lyx" to the filename if
1946         // necessary.
1947         FileName const fullname =
1948                         fileSearch(string(), filename, "lyx", support::may_not_exist);
1949         if (!fullname.empty())
1950                 filename = fullname.absFileName();
1951
1952         if (!fullname.onlyPath().isDirectory()) {
1953                 Alert::warning(_("Invalid filename"),
1954                                 bformat(_("The directory in the given path\n%1$s\ndoes not exist."),
1955                                 from_utf8(fullname.absFileName())));
1956                 return;
1957         }
1958
1959         // if the file doesn't exist and isn't already open (bug 6645),
1960         // let the user create one
1961         if (!fullname.exists() && !theBufferList().exists(fullname)) {
1962                 // the user specifically chose this name. Believe him.
1963                 Buffer * const b = newFile(filename, string(), true);
1964                 if (b)
1965                         setBuffer(b);
1966                 return;
1967         }
1968
1969         docstring const disp_fn = makeDisplayPath(filename);
1970         message(bformat(_("Opening document %1$s..."), disp_fn));
1971
1972         docstring str2;
1973         Buffer * buf = loadDocument(fullname);
1974         if (buf) {
1975                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1976                 if (buf->lyxvc().inUse())
1977                         str2 += " " + from_utf8(buf->lyxvc().versionString()) +
1978                                 " " + _("Version control detected.");
1979         } else {
1980                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1981         }
1982         message(str2);
1983 }
1984
1985 // FIXME: clean that
1986 static bool import(GuiView * lv, FileName const & filename,
1987         string const & format, ErrorList & errorList)
1988 {
1989         FileName const lyxfile(support::changeExtension(filename.absFileName(), ".lyx"));
1990
1991         string loader_format;
1992         vector<string> loaders = theConverters().loaders();
1993         if (find(loaders.begin(), loaders.end(), format) == loaders.end()) {
1994                 for (vector<string>::const_iterator it = loaders.begin();
1995                          it != loaders.end(); ++it) {
1996                         if (!theConverters().isReachable(format, *it))
1997                                 continue;
1998
1999                         string const tofile =
2000                                 support::changeExtension(filename.absFileName(),
2001                                 formats.extension(*it));
2002                         if (!theConverters().convert(0, filename, FileName(tofile),
2003                                 filename, format, *it, errorList))
2004                                 return false;
2005                         loader_format = *it;
2006                         break;
2007                 }
2008                 if (loader_format.empty()) {
2009                         frontend::Alert::error(_("Couldn't import file"),
2010                                          bformat(_("No information for importing the format %1$s."),
2011                                          formats.prettyName(format)));
2012                         return false;
2013                 }
2014         } else
2015                 loader_format = format;
2016
2017         if (loader_format == "lyx") {
2018                 Buffer * buf = lv->loadDocument(lyxfile);
2019                 if (!buf)
2020                         return false;
2021         } else {
2022                 Buffer * const b = newFile(lyxfile.absFileName(), string(), true);
2023                 if (!b)
2024                         return false;
2025                 lv->setBuffer(b);
2026                 bool as_paragraphs = loader_format == "textparagraph";
2027                 string filename2 = (loader_format == format) ? filename.absFileName()
2028                         : support::changeExtension(filename.absFileName(),
2029                                           formats.extension(loader_format));
2030                 lv->currentBufferView()->insertPlaintextFile(FileName(filename2),
2031                         as_paragraphs);
2032                 guiApp->setCurrentView(lv);
2033                 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
2034         }
2035
2036         return true;
2037 }
2038
2039
2040 void GuiView::importDocument(string const & argument)
2041 {
2042         string format;
2043         string filename = split(argument, format, ' ');
2044
2045         LYXERR(Debug::INFO, format << " file: " << filename);
2046
2047         // need user interaction
2048         if (filename.empty()) {
2049                 string initpath = lyxrc.document_path;
2050                 if (documentBufferView()) {
2051                         string const trypath = documentBufferView()->buffer().filePath();
2052                         // If directory is writeable, use this as default.
2053                         if (FileName(trypath).isDirWritable())
2054                                 initpath = trypath;
2055                 }
2056
2057                 docstring const text = bformat(_("Select %1$s file to import"),
2058                         formats.prettyName(format));
2059
2060                 FileDialog dlg(toqstr(text), LFUN_BUFFER_IMPORT);
2061                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2062                 dlg.setButton2(qt_("Examples|#E#e"),
2063                         toqstr(addPath(package().system_support().absFileName(), "examples")));
2064
2065                 docstring filter = formats.prettyName(format);
2066                 filter += " (*.{";
2067                 // FIXME UNICODE
2068                 filter += from_utf8(formats.extensions(format));
2069                 filter += "})";
2070
2071                 FileDialog::Result result =
2072                         dlg.open(toqstr(initpath), fileFilters(toqstr(filter)));
2073
2074                 if (result.first == FileDialog::Later)
2075                         return;
2076
2077                 filename = fromqstr(result.second);
2078
2079                 // check selected filename
2080                 if (filename.empty())
2081                         message(_("Canceled."));
2082         }
2083
2084         if (filename.empty())
2085                 return;
2086
2087         // get absolute path of file
2088         FileName const fullname(support::makeAbsPath(filename));
2089
2090         FileName const lyxfile(support::changeExtension(fullname.absFileName(), ".lyx"));
2091
2092         // Check if the document already is open
2093         Buffer * buf = theBufferList().getBuffer(lyxfile);
2094         if (buf) {
2095                 setBuffer(buf);
2096                 if (!closeBuffer()) {
2097                         message(_("Canceled."));
2098                         return;
2099                 }
2100         }
2101
2102         docstring const displaypath = makeDisplayPath(lyxfile.absFileName(), 30);
2103
2104         // if the file exists already, and we didn't do
2105         // -i lyx thefile.lyx, warn
2106         if (lyxfile.exists() && fullname != lyxfile) {
2107
2108                 docstring text = bformat(_("The document %1$s already exists.\n\n"
2109                         "Do you want to overwrite that document?"), displaypath);
2110                 int const ret = Alert::prompt(_("Overwrite document?"),
2111                         text, 0, 1, _("&Overwrite"), _("&Cancel"));
2112
2113                 if (ret == 1) {
2114                         message(_("Canceled."));
2115                         return;
2116                 }
2117         }
2118
2119         message(bformat(_("Importing %1$s..."), displaypath));
2120         ErrorList errorList;
2121         if (import(this, fullname, format, errorList))
2122                 message(_("imported."));
2123         else
2124                 message(_("file not imported!"));
2125
2126         // FIXME (Abdel 12/08/06): Is there a need to display the error list here?
2127 }
2128
2129
2130 void GuiView::newDocument(string const & filename, bool from_template)
2131 {
2132         FileName initpath(lyxrc.document_path);
2133         if (documentBufferView()) {
2134                 FileName const trypath(documentBufferView()->buffer().filePath());
2135                 // If directory is writeable, use this as default.
2136                 if (trypath.isDirWritable())
2137                         initpath = trypath;
2138         }
2139
2140         string templatefile;
2141         if (from_template) {
2142                 templatefile = selectTemplateFile().absFileName();
2143                 if (templatefile.empty())
2144                         return;
2145         }
2146
2147         Buffer * b;
2148         if (filename.empty())
2149                 b = newUnnamedFile(initpath, to_utf8(_("newfile")), templatefile);
2150         else
2151                 b = newFile(filename, templatefile, true);
2152
2153         if (b)
2154                 setBuffer(b);
2155
2156         // If no new document could be created, it is unsure
2157         // whether there is a valid BufferView.
2158         if (currentBufferView())
2159                 // Ensure the cursor is correctly positioned on screen.
2160                 currentBufferView()->showCursor();
2161 }
2162
2163
2164 void GuiView::insertLyXFile(docstring const & fname)
2165 {
2166         BufferView * bv = documentBufferView();
2167         if (!bv)
2168                 return;
2169
2170         // FIXME UNICODE
2171         FileName filename(to_utf8(fname));
2172         if (filename.empty()) {
2173                 // Launch a file browser
2174                 // FIXME UNICODE
2175                 string initpath = lyxrc.document_path;
2176                 string const trypath = bv->buffer().filePath();
2177                 // If directory is writeable, use this as default.
2178                 if (FileName(trypath).isDirWritable())
2179                         initpath = trypath;
2180
2181                 // FIXME UNICODE
2182                 FileDialog dlg(qt_("Select LyX document to insert"), LFUN_FILE_INSERT);
2183                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2184                 dlg.setButton2(qt_("Examples|#E#e"),
2185                         toqstr(addPath(package().system_support().absFileName(),
2186                         "examples")));
2187
2188                 FileDialog::Result result = dlg.open(toqstr(initpath),
2189                                          QStringList(qt_("LyX Documents (*.lyx)")));
2190
2191                 if (result.first == FileDialog::Later)
2192                         return;
2193
2194                 // FIXME UNICODE
2195                 filename.set(fromqstr(result.second));
2196
2197                 // check selected filename
2198                 if (filename.empty()) {
2199                         // emit message signal.
2200                         message(_("Canceled."));
2201                         return;
2202                 }
2203         }
2204
2205         bv->insertLyXFile(filename);
2206         bv->buffer().errors("Parse");
2207 }
2208
2209
2210 void GuiView::insertPlaintextFile(docstring const & fname,
2211         bool asParagraph)
2212 {
2213         BufferView * bv = documentBufferView();
2214         if (!bv)
2215                 return;
2216
2217         if (!fname.empty() && !FileName::isAbsolute(to_utf8(fname))) {
2218                 message(_("Absolute filename expected."));
2219                 return;
2220         }
2221
2222         // FIXME UNICODE
2223         FileName filename(to_utf8(fname));
2224
2225         if (!filename.empty()) {
2226                 bv->insertPlaintextFile(filename, asParagraph);
2227                 return;
2228         }
2229
2230         FileDialog dlg(qt_("Select file to insert"), (asParagraph ?
2231                 LFUN_FILE_INSERT_PLAINTEXT_PARA : LFUN_FILE_INSERT_PLAINTEXT));
2232
2233         FileDialog::Result result = dlg.open(toqstr(bv->buffer().filePath()),
2234                 QStringList(qt_("All Files (*)")));
2235
2236         if (result.first == FileDialog::Later)
2237                 return;
2238
2239         // FIXME UNICODE
2240         filename.set(fromqstr(result.second));
2241
2242         // check selected filename
2243         if (filename.empty()) {
2244                 // emit message signal.
2245                 message(_("Canceled."));
2246                 return;
2247         }
2248
2249         bv->insertPlaintextFile(filename, asParagraph);
2250 }
2251
2252
2253 bool GuiView::renameBuffer(Buffer & b, docstring const & newname)
2254 {
2255         FileName fname = b.fileName();
2256         FileName const oldname = fname;
2257
2258         if (!newname.empty()) {
2259                 // FIXME UNICODE
2260                 fname = support::makeAbsPath(to_utf8(newname), oldname.onlyPath().absFileName());
2261         } else {
2262                 // Switch to this Buffer.
2263                 setBuffer(&b);
2264
2265                 // No argument? Ask user through dialog.
2266                 // FIXME UNICODE
2267                 FileDialog dlg(qt_("Choose a filename to save document as"),
2268                                    LFUN_BUFFER_WRITE_AS);
2269                 dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2270                 dlg.setButton2(qt_("Templates|#T#t"), toqstr(lyxrc.template_path));
2271
2272                 if (!isLyXFileName(fname.absFileName()))
2273                         fname.changeExtension(".lyx");
2274
2275                 FileDialog::Result result =
2276                         dlg.save(toqstr(fname.onlyPath().absFileName()),
2277                                    QStringList(qt_("LyX Documents (*.lyx)")),
2278                                          toqstr(fname.onlyFileName()));
2279
2280                 if (result.first == FileDialog::Later)
2281                         return false;
2282
2283                 fname.set(fromqstr(result.second));
2284
2285                 if (fname.empty())
2286                         return false;
2287
2288                 if (!isLyXFileName(fname.absFileName()))
2289                         fname.changeExtension(".lyx");
2290         }
2291
2292         // fname is now the new Buffer location.
2293         if (FileName(fname).exists()) {
2294                 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2295                 docstring text = bformat(_("The document %1$s already "
2296                                            "exists.\n\nDo you want to "
2297                                            "overwrite that document?"),
2298                                          file);
2299                 int const ret = Alert::prompt(_("Overwrite document?"),
2300                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2301                 switch (ret) {
2302                 case 0: break;
2303                 case 1: return renameBuffer(b, docstring());
2304                 case 2: return false;
2305                 }
2306         }
2307
2308         return saveBuffer(b, fname);
2309 }
2310
2311
2312 struct PrettyNameComparator
2313 {
2314         bool operator()(Format const *first, Format const *second) const {
2315                 return compare_ascii_no_case(first->prettyname(), second->prettyname()) <= 0;
2316         }
2317 };
2318
2319
2320 bool GuiView::exportBufferAs(Buffer & b)
2321 {
2322         FileName fname = b.fileName();
2323
2324         FileDialog dlg(qt_("Choose a filename to export the document as"));
2325         dlg.setButton1(qt_("Documents|#o#O"), toqstr(lyxrc.document_path));
2326
2327         QStringList types;
2328         types << "Any supported format (*.*)";
2329         Formats::const_iterator it = formats.begin();
2330         vector<Format const *> export_formats;
2331         for (; it != formats.end(); ++it)
2332                 if (it->documentFormat() && it->inExportMenu())
2333                         export_formats.push_back(&(*it));
2334         PrettyNameComparator cmp;
2335         sort(export_formats.begin(), export_formats.end(), cmp);
2336         vector<Format const *>::const_iterator fit = export_formats.begin();
2337         for (; fit != export_formats.end(); ++fit)
2338                 types << toqstr((*fit)->prettyname() + " (*." + (*fit)->extension() + ")");
2339         QString filter;
2340         FileDialog::Result result =
2341                 dlg.save(toqstr(fname.onlyPath().absFileName()),
2342                          types,
2343                          toqstr(fname.onlyFileName()),
2344                          &filter);
2345         if (result.first != FileDialog::Chosen)
2346                 return false;
2347
2348         string s = fromqstr(filter);
2349         size_t pos = s.find(" (*.");
2350         LASSERT(pos != string::npos, /**/);
2351         string fmt_prettyname = s.substr(0, pos);
2352         string fmt_name;
2353         fname.set(fromqstr(result.second));
2354         if (fmt_prettyname == "Any supported format")
2355                 fmt_name = formats.getFormatFromExtension(fname.extension());
2356         else
2357                 fmt_name = formats.getFormatFromPrettyName(fmt_prettyname);
2358         LYXERR(Debug::FILES, "fmt_prettyname=" << fmt_prettyname
2359                << ", fmt_name=" << fmt_name << ", fname=" << fname.absFileName());
2360
2361         if (fmt_name.empty() || fname.empty())
2362                 return false;
2363
2364         // fname is now the new Buffer location.
2365         if (FileName(fname).exists()) {
2366                 docstring const file = makeDisplayPath(fname.absFileName(), 30);
2367                 docstring text = bformat(_("The document %1$s already "
2368                                            "exists.\n\nDo you want to "
2369                                            "overwrite that document?"),
2370                                          file);
2371                 int const ret = Alert::prompt(_("Overwrite document?"),
2372                         text, 0, 2, _("&Overwrite"), _("&Rename"), _("&Cancel"));
2373                 switch (ret) {
2374                 case 0: break;
2375                 case 1: return exportBufferAs(b);
2376                 case 2: return false;
2377                 }
2378         }
2379
2380         FuncRequest cmd(LFUN_BUFFER_EXPORT, fmt_name + " " + fname.absFileName());
2381         DispatchResult dr;
2382         dispatch(cmd, dr);
2383         return dr.dispatched();
2384 }
2385
2386
2387 bool GuiView::saveBuffer(Buffer & b) {
2388         return saveBuffer(b, FileName());
2389 }
2390
2391
2392 bool GuiView::saveBuffer(Buffer & b, FileName const & fn)
2393 {
2394         if (workArea(b) && workArea(b)->inDialogMode())
2395                 return true;
2396
2397         if (fn.empty() && b.isUnnamed())
2398                         return renameBuffer(b, docstring());
2399
2400         bool success;
2401         if (fn.empty())
2402                 success = b.save();
2403         else
2404                 success = b.saveAs(fn);
2405         
2406         if (success) {
2407                 theSession().lastFiles().add(b.fileName());
2408                 return true;
2409         }
2410
2411         // Switch to this Buffer.
2412         setBuffer(&b);
2413
2414         // FIXME: we don't tell the user *WHY* the save failed !!
2415         docstring const file = makeDisplayPath(b.absFileName(), 30);
2416         docstring text = bformat(_("The document %1$s could not be saved.\n\n"
2417                                    "Do you want to rename the document and "
2418                                    "try again?"), file);
2419         int const ret = Alert::prompt(_("Rename and save?"),
2420                 text, 0, 2, _("&Rename"), _("&Retry"), _("&Cancel"));
2421         switch (ret) {
2422         case 0:
2423                 if (!renameBuffer(b, docstring()))
2424                         return false;
2425                 break;
2426         case 1:
2427                 break;
2428         case 2:
2429                 return false;
2430         }
2431
2432         return saveBuffer(b);
2433 }
2434
2435
2436 bool GuiView::hideWorkArea(GuiWorkArea * wa)
2437 {
2438         return closeWorkArea(wa, false);
2439 }
2440
2441
2442 bool GuiView::closeWorkArea(GuiWorkArea * wa)
2443 {
2444         Buffer & buf = wa->bufferView().buffer();
2445         return closeWorkArea(wa, !buf.parent());
2446 }
2447
2448
2449 bool GuiView::closeBuffer()
2450 {
2451         GuiWorkArea * wa = currentMainWorkArea();
2452         setCurrentWorkArea(wa);
2453         Buffer & buf = wa->bufferView().buffer();
2454         return wa && closeWorkArea(wa, !buf.parent());
2455 }
2456
2457
2458 void GuiView::writeSession() const {
2459         GuiWorkArea const * active_wa = currentMainWorkArea();
2460         for (int i = 0; i < d.splitter_->count(); ++i) {
2461                 TabWorkArea * twa = d.tabWorkArea(i);
2462                 for (int j = 0; j < twa->count(); ++j) {
2463                         GuiWorkArea * wa = static_cast<GuiWorkArea *>(twa->widget(j));
2464                         Buffer & buf = wa->bufferView().buffer();
2465                         theSession().lastOpened().add(buf.fileName(), wa == active_wa);
2466                 }
2467         }
2468 }
2469
2470
2471 bool GuiView::closeBufferAll()
2472 {
2473         // Close the workareas in all other views
2474         QList<int> const ids = guiApp->viewIds();
2475         for (int i = 0; i != ids.size(); ++i) {
2476                 if (id_ != ids[i] && !guiApp->view(ids[i]).closeWorkAreaAll())
2477                         return false;
2478         }
2479
2480         // Close our own workareas
2481         if (!closeWorkAreaAll())
2482                 return false;
2483
2484         // Now close the hidden buffers. We prevent hidden buffers from being
2485         // dirty, so we can just close them.
2486         theBufferList().closeAll();
2487         return true;
2488 }
2489
2490
2491 bool GuiView::closeWorkAreaAll()
2492 {
2493         setCurrentWorkArea(currentMainWorkArea());
2494
2495         // We might be in a situation that there is still a tabWorkArea, but
2496         // there are no tabs anymore. This can happen when we get here after a
2497         // TabWorkArea::lastWorkAreaRemoved() signal. Therefore we count how
2498         // many TabWorkArea's have no documents anymore.
2499         int empty_twa = 0;
2500
2501         // We have to call count() each time, because it can happen that
2502         // more than one splitter will disappear in one iteration (bug 5998).
2503         for (; d.splitter_->count() > empty_twa; ) {
2504                 TabWorkArea * twa = d.tabWorkArea(empty_twa);
2505
2506                 if (twa->count() == 0)
2507                         ++empty_twa;
2508                 else {
2509                         setCurrentWorkArea(twa->currentWorkArea());
2510                         if (!closeTabWorkArea(twa))
2511                                 return false;
2512                 }
2513         }
2514         return true;
2515 }
2516
2517
2518 bool GuiView::closeWorkArea(GuiWorkArea * wa, bool close_buffer)
2519 {
2520         if (!wa)
2521                 return false;
2522
2523         Buffer & buf = wa->bufferView().buffer();
2524
2525         if (close_buffer && GuiViewPrivate::busyBuffers.contains(&buf)) {
2526                 Alert::warning(_("Close document"), 
2527                         _("Document could not be closed because it is being processed by LyX."));
2528                 return false;
2529         }
2530
2531         if (close_buffer)
2532                 return closeBuffer(buf);
2533         else {
2534                 if (!inMultiTabs(wa))
2535                         if (!saveBufferIfNeeded(buf, true))
2536                                 return false;
2537                 removeWorkArea(wa);
2538                 return true;
2539         }
2540 }
2541
2542
2543 bool GuiView::closeBuffer(Buffer & buf)
2544 {
2545         // If we are in a close_event all children will be closed in some time,
2546         // so no need to do it here. This will ensure that the children end up
2547         // in the session file in the correct order. If we close the master
2548         // buffer, we can close or release the child buffers here too.
2549         bool success = true;
2550         if (!closing_) {
2551                 ListOfBuffers clist = buf.getChildren();
2552                 ListOfBuffers::const_iterator it = clist.begin();
2553                 ListOfBuffers::const_iterator const bend = clist.end();
2554                 for (; it != bend; ++it) {
2555                         // If a child is dirty, do not close
2556                         // without user intervention
2557                         //FIXME: should we look in other tabworkareas?
2558                         Buffer * child_buf = *it;
2559                         GuiWorkArea * child_wa = workArea(*child_buf);
2560                         if (child_wa) {
2561                                 if (!closeWorkArea(child_wa, true)) {
2562                                         success = false;
2563                                         break;
2564                                 }
2565                         } else
2566                                 theBufferList().releaseChild(&buf, child_buf);
2567                 }
2568         }
2569         if (success) {
2570                 // goto bookmark to update bookmark pit.
2571                 //FIXME: we should update only the bookmarks related to this buffer!
2572                 LYXERR(Debug::DEBUG, "GuiView::closeBuffer()");
2573                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
2574                         guiApp->gotoBookmark(i+1, false, false);
2575
2576                 if (saveBufferIfNeeded(buf, false)) {
2577                         buf.removeAutosaveFile();
2578                         theBufferList().release(&buf);
2579                         return true;
2580                 }
2581         }
2582         // open all children again to avoid a crash because of dangling
2583         // pointers (bug 6603)
2584         buf.updateBuffer();
2585         return false;
2586 }
2587
2588
2589 bool GuiView::closeTabWorkArea(TabWorkArea * twa)
2590 {
2591         while (twa == d.currentTabWorkArea()) {
2592                 twa->setCurrentIndex(twa->count()-1);
2593
2594                 GuiWorkArea * wa = twa->currentWorkArea();
2595                 Buffer & b = wa->bufferView().buffer();
2596
2597                 // We only want to close the buffer if the same buffer is not visible
2598                 // in another view, and if this is not a child and if we are closing
2599                 // a view (not a tabgroup).
2600                 bool const close_buffer =
2601                         !inOtherView(b) && !b.parent() && closing_;
2602
2603                 if (!closeWorkArea(wa, close_buffer))
2604                         return false;
2605         }
2606         return true;
2607 }
2608
2609
2610 bool GuiView::saveBufferIfNeeded(Buffer & buf, bool hiding)
2611 {
2612         if (buf.isClean() || buf.paragraphs().empty())
2613                 return true;
2614
2615         // Switch to this Buffer.
2616         setBuffer(&buf);
2617
2618         docstring file;
2619         // FIXME: Unicode?
2620         if (buf.isUnnamed())
2621                 file = from_utf8(buf.fileName().onlyFileName());
2622         else
2623                 file = buf.fileName().displayName(30);
2624
2625         // Bring this window to top before asking questions.
2626         raise();
2627         activateWindow();
2628
2629         int ret;
2630         if (hiding && buf.isUnnamed()) {
2631                 docstring const text = bformat(_("The document %1$s has not been "
2632                                                  "saved yet.\n\nDo you want to save "
2633                                                  "the document?"), file);
2634                 ret = Alert::prompt(_("Save new document?"),
2635                         text, 0, 1, _("&Save"), _("&Cancel"));
2636                 if (ret == 1)
2637                         ++ret;
2638         } else {
2639                 docstring const text = bformat(_("The document %1$s has unsaved changes."
2640                         "\n\nDo you want to save the document or discard the changes?"), file);
2641                 ret = Alert::prompt(_("Save changed document?"),
2642                         text, 0, 2, _("&Save"), _("&Discard"), _("&Cancel"));
2643         }
2644
2645         switch (ret) {
2646         case 0:
2647                 if (!saveBuffer(buf))
2648                         return false;
2649                 break;
2650         case 1:
2651                 // If we crash after this we could have no autosave file
2652                 // but I guess this is really improbable (Jug).
2653                 // Sometimes improbable things happen:
2654                 // - see bug http://www.lyx.org/trac/ticket/6587 (ps)
2655                 // buf.removeAutosaveFile();
2656                 if (hiding)
2657                         // revert all changes
2658                         reloadBuffer(buf);
2659                 buf.markClean();
2660                 break;
2661         case 2:
2662                 return false;
2663         }
2664         return true;
2665 }
2666
2667
2668 bool GuiView::inMultiTabs(GuiWorkArea * wa)
2669 {
2670         Buffer & buf = wa->bufferView().buffer();
2671
2672         for (int i = 0; i != d.splitter_->count(); ++i) {
2673                 GuiWorkArea * wa_ = d.tabWorkArea(i)->workArea(buf);
2674                 if (wa_ && wa_ != wa)
2675                         return true;
2676         }
2677         return inOtherView(buf);
2678 }
2679
2680
2681 bool GuiView::inOtherView(Buffer & buf)
2682 {
2683         QList<int> const ids = guiApp->viewIds();
2684
2685         for (int i = 0; i != ids.size(); ++i) {
2686                 if (id_ == ids[i])
2687                         continue;
2688
2689                 if (guiApp->view(ids[i]).workArea(buf))
2690                         return true;
2691         }
2692         return false;
2693 }
2694
2695
2696 void GuiView::gotoNextOrPreviousBuffer(NextOrPrevious np)
2697 {
2698         if (!documentBufferView())
2699                 return;
2700         
2701         if (TabWorkArea * twa = d.currentTabWorkArea()) {
2702                 Buffer * const curbuf = &documentBufferView()->buffer();
2703                 int nwa = twa->count();
2704                 for (int i = 0; i < nwa; ++i) {
2705                         if (&workArea(i)->bufferView().buffer() == curbuf) {
2706                                 int next_index;
2707                                 if (np == NEXTBUFFER)
2708                                         next_index = (i == nwa - 1 ? 0 : i + 1);
2709                                 else
2710                                         next_index = (i == 0 ? nwa - 1 : i - 1);
2711                                 setBuffer(&workArea(next_index)->bufferView().buffer());
2712                                 break;
2713                         }
2714                 }
2715         }
2716 }
2717
2718
2719 /// make sure the document is saved
2720 static bool ensureBufferClean(Buffer * buffer)
2721 {
2722         LASSERT(buffer, return false);
2723         if (buffer->isClean() && !buffer->isUnnamed())
2724                 return true;
2725
2726         docstring const file = buffer->fileName().displayName(30);
2727         docstring title;
2728         docstring text;
2729         if (!buffer->isUnnamed()) {
2730                 text = bformat(_("The document %1$s has unsaved "
2731                                                  "changes.\n\nDo you want to save "
2732                                                  "the document?"), file);
2733                 title = _("Save changed document?");
2734
2735         } else {
2736                 text = bformat(_("The document %1$s has not been "
2737                                                  "saved yet.\n\nDo you want to save "
2738                                                  "the document?"), file);
2739                 title = _("Save new document?");
2740         }
2741         int const ret = Alert::prompt(title, text, 0, 1, _("&Save"), _("&Cancel"));
2742
2743         if (ret == 0)
2744                 dispatch(FuncRequest(LFUN_BUFFER_WRITE));
2745
2746         return buffer->isClean() && !buffer->isUnnamed();
2747 }
2748
2749
2750 bool GuiView::reloadBuffer(Buffer & buf)
2751 {
2752         Buffer::ReadStatus status = buf.reload();
2753         return status == Buffer::ReadSuccess;
2754 }
2755
2756
2757 void GuiView::checkExternallyModifiedBuffers()
2758 {
2759         BufferList::iterator bit = theBufferList().begin();
2760         BufferList::iterator const bend = theBufferList().end();
2761         for (; bit != bend; ++bit) {
2762                 Buffer * buf = *bit;
2763                 if (buf->fileName().exists()
2764                         && buf->isExternallyModified(Buffer::checksum_method)) {
2765                         docstring text = bformat(_("Document \n%1$s\n has been externally modified."
2766                                         " Reload now? Any local changes will be lost."),
2767                                         from_utf8(buf->absFileName()));
2768                         int const ret = Alert::prompt(_("Reload externally changed document?"),
2769                                                 text, 0, 1, _("&Reload"), _("&Cancel"));
2770                         if (!ret)
2771                                 reloadBuffer(*buf);
2772                 }
2773         }
2774 }
2775
2776
2777 void GuiView::dispatchVC(FuncRequest const & cmd, DispatchResult & dr)
2778 {
2779         Buffer * buffer = documentBufferView()
2780                 ? &(documentBufferView()->buffer()) : 0;
2781
2782         switch (cmd.action()) {
2783         case LFUN_VC_REGISTER:
2784                 if (!buffer || !ensureBufferClean(buffer))
2785                         break;
2786                 if (!buffer->lyxvc().inUse()) {
2787                         if (buffer->lyxvc().registrer()) {
2788                                 reloadBuffer(*buffer);
2789                                 dr.suppressMessageUpdate();
2790                         }
2791                 }
2792                 break;
2793
2794         case LFUN_VC_CHECK_IN:
2795                 if (!buffer || !ensureBufferClean(buffer))
2796                         break;
2797                 if (buffer->lyxvc().inUse() && !buffer->isReadonly()) {
2798                         dr.setMessage(buffer->lyxvc().checkIn());
2799                         if (!dr.message().empty())
2800                                 reloadBuffer(*buffer);
2801                 }
2802                 break;
2803
2804         case LFUN_VC_CHECK_OUT:
2805                 if (!buffer || !ensureBufferClean(buffer))
2806                         break;
2807                 if (buffer->lyxvc().inUse()) {
2808                         dr.setMessage(buffer->lyxvc().checkOut());
2809                         reloadBuffer(*buffer);
2810                 }
2811                 break;
2812
2813         case LFUN_VC_LOCKING_TOGGLE:
2814                 LASSERT(buffer, return);
2815                 if (!ensureBufferClean(buffer) || buffer->isReadonly())
2816                         break;
2817                 if (buffer->lyxvc().inUse()) {
2818                         string res = buffer->lyxvc().lockingToggle();
2819                         if (res.empty()) {
2820                                 frontend::Alert::error(_("Revision control error."),
2821                                 _("Error when setting the locking property."));
2822                         } else {
2823                                 dr.setMessage(res);
2824                                 reloadBuffer(*buffer);
2825                         }
2826                 }
2827                 break;
2828
2829         case LFUN_VC_REVERT:
2830                 LASSERT(buffer, return);
2831                 if (buffer->lyxvc().revert()) {
2832                         reloadBuffer(*buffer);
2833                         dr.suppressMessageUpdate();
2834                 }
2835                 break;
2836
2837         case LFUN_VC_UNDO_LAST:
2838                 LASSERT(buffer, return);
2839                 buffer->lyxvc().undoLast();
2840                 reloadBuffer(*buffer);
2841                 dr.suppressMessageUpdate();
2842                 break;
2843
2844         case LFUN_VC_REPO_UPDATE:
2845                 LASSERT(buffer, return);
2846                 if (ensureBufferClean(buffer)) {
2847                         dr.setMessage(buffer->lyxvc().repoUpdate());
2848                         checkExternallyModifiedBuffers();
2849                 }
2850                 break;
2851
2852         case LFUN_VC_COMMAND: {
2853                 string flag = cmd.getArg(0);
2854                 if (buffer && contains(flag, 'R') && !ensureBufferClean(buffer))
2855                         break;
2856                 docstring message;
2857                 if (contains(flag, 'M')) {
2858                         if (!Alert::askForText(message, _("LyX VC: Log Message")))
2859                                 break;
2860                 }
2861                 string path = cmd.getArg(1);
2862                 if (contains(path, "$$p") && buffer)
2863                         path = subst(path, "$$p", buffer->filePath());
2864                 LYXERR(Debug::LYXVC, "Directory: " << path);
2865                 FileName pp(path);
2866                 if (!pp.isReadableDirectory()) {
2867                         lyxerr << _("Directory is not accessible.") << endl;
2868                         break;
2869                 }
2870                 support::PathChanger p(pp);
2871
2872                 string command = cmd.getArg(2);
2873                 if (command.empty())
2874                         break;
2875                 if (buffer) {
2876                         command = subst(command, "$$i", buffer->absFileName());
2877                         command = subst(command, "$$p", buffer->filePath());
2878                 }
2879                 command = subst(command, "$$m", to_utf8(message));
2880                 LYXERR(Debug::LYXVC, "Command: " << command);
2881                 Systemcall one;
2882                 one.startscript(Systemcall::Wait, command);
2883
2884                 if (!buffer)
2885                         break;
2886                 if (contains(flag, 'I'))
2887                         buffer->markDirty();
2888                 if (contains(flag, 'R'))
2889                         reloadBuffer(*buffer);
2890
2891                 break;
2892                 }
2893
2894         case LFUN_VC_COMPARE: {
2895
2896                 if (cmd.argument().empty()) {
2897                         lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "comparehistory"));
2898                         break;
2899                 }
2900
2901                 string rev1 = cmd.getArg(0);
2902                 string f1, f2;
2903
2904                 // f1
2905                 if (!buffer->lyxvc().prepareFileRevision(rev1, f1))
2906                         break;
2907
2908                 if (isStrInt(rev1) && convert<int>(rev1) <= 0) {
2909                         f2 = buffer->absFileName();
2910                 } else {
2911                         string rev2 = cmd.getArg(1);
2912                         if (rev2.empty())
2913                                 break;
2914                         // f2
2915                         if (!buffer->lyxvc().prepareFileRevision(rev2, f2))
2916                                 break;
2917                 }
2918
2919                 LYXERR(Debug::LYXVC, "Launching comparison for fetched revisions:\n" <<
2920                                         f1 << "\n"  << f2 << "\n" );
2921                 string par = "compare run " + quoteName(f1) + " " + quoteName(f2);
2922                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, par));
2923                 break;
2924         }
2925
2926         default:
2927                 break;
2928         }
2929 }
2930
2931
2932 void GuiView::openChildDocument(string const & fname)
2933 {
2934         LASSERT(documentBufferView(), return);
2935         Buffer & buffer = documentBufferView()->buffer();
2936         FileName const filename = support::makeAbsPath(fname, buffer.filePath());
2937         documentBufferView()->saveBookmark(false);
2938         Buffer * child = 0;
2939         if (theBufferList().exists(filename)) {
2940                 child = theBufferList().getBuffer(filename);
2941                 setBuffer(child);
2942         } else {
2943                 message(bformat(_("Opening child document %1$s..."),
2944                         makeDisplayPath(filename.absFileName())));
2945                 child = loadDocument(filename, false);
2946         }
2947         // Set the parent name of the child document.
2948         // This makes insertion of citations and references in the child work,
2949         // when the target is in the parent or another child document.
2950         if (child)
2951                 child->setParent(&buffer);
2952 }
2953
2954
2955 bool GuiView::goToFileRow(string const & argument)
2956 {
2957         string file_name;
2958         int row;
2959         size_t i = argument.find_last_of(' ');
2960         if (i != string::npos) {
2961                 file_name = os::internal_path(trim(argument.substr(0, i)));
2962                 istringstream is(argument.substr(i + 1));
2963                 is >> row;
2964                 if (is.fail())
2965                         i = string::npos;
2966         }
2967         if (i == string::npos) {
2968                 LYXERR0("Wrong argument: " << argument);
2969                 return false;
2970         }
2971         Buffer * buf = 0;
2972         string const abstmp = package().temp_dir().absFileName();
2973         string const realtmp = package().temp_dir().realPath();
2974         // We have to use os::path_prefix_is() here, instead of
2975         // simply prefixIs(), because the file name comes from
2976         // an external application and may need case adjustment.
2977         if (os::path_prefix_is(file_name, abstmp, os::CASE_ADJUSTED)
2978                 || os::path_prefix_is(file_name, realtmp, os::CASE_ADJUSTED)) {
2979                 // Needed by inverse dvi search. If it is a file
2980                 // in tmpdir, call the apropriated function.
2981                 // If tmpdir is a symlink, we may have the real
2982                 // path passed back, so we correct for that.
2983                 if (!prefixIs(file_name, abstmp))
2984                         file_name = subst(file_name, realtmp, abstmp);
2985                 buf = theBufferList().getBufferFromTmp(file_name);
2986         } else {
2987                 // Must replace extension of the file to be .lyx
2988                 // and get full path
2989                 FileName const s = fileSearch(string(),
2990                                                   support::changeExtension(file_name, ".lyx"), "lyx");
2991                 // Either change buffer or load the file
2992                 if (theBufferList().exists(s))
2993                         buf = theBufferList().getBuffer(s);
2994                 else if (s.exists()) {
2995                         buf = loadDocument(s);
2996                         if (!buf)
2997                                 return false;
2998                 } else {
2999                         message(bformat(
3000                                         _("File does not exist: %1$s"),
3001                                         makeDisplayPath(file_name)));
3002                         return false;
3003                 }
3004         }
3005         if (!buf) {
3006                 message(bformat(
3007                         _("No buffer for file: %1$s."),
3008                         makeDisplayPath(file_name))
3009                 );
3010                 return false;
3011         }
3012         setBuffer(buf);
3013         documentBufferView()->setCursorFromRow(row);
3014         return true;
3015 }
3016
3017
3018 #if (QT_VERSION >= 0x040400)
3019 template<class T>
3020 docstring GuiView::GuiViewPrivate::runAndDestroy(const T& func, Buffer const * orig, Buffer * buffer, string const & format, string const & msg)
3021 {
3022         bool const update_unincluded =
3023                                 buffer->params().maintain_unincluded_children
3024                                 && !buffer->params().getIncludedChildren().empty();
3025         bool const success = func(format, update_unincluded);
3026
3027         // the cloning operation will have produced a clone of the entire set of
3028         // documents, starting from the master. so we must delete those.
3029         Buffer * mbuf = const_cast<Buffer *>(buffer->masterBuffer());
3030         delete mbuf;
3031         busyBuffers.remove(orig);
3032         if (msg == "preview") {
3033                 return success
3034                         ? bformat(_("Successful preview of format: %1$s"), from_utf8(format))
3035                         : bformat(_("Error while previewing format: %1$s"), from_utf8(format));
3036         }
3037         return success
3038                 ? bformat(_("Successful export to format: %1$s"), from_utf8(format))
3039                 : bformat(_("Error while exporting format: %1$s"), from_utf8(format));
3040 }
3041
3042
3043 docstring GuiView::GuiViewPrivate::compileAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3044 {
3045         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
3046         return runAndDestroy(bind(mem_func, buffer, _1, true, _2), orig, buffer, format, "export");
3047 }
3048
3049
3050 docstring GuiView::GuiViewPrivate::exportAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3051 {
3052         bool (Buffer::* mem_func)(std::string const &, bool, bool) const = &Buffer::doExport;
3053         return runAndDestroy(bind(mem_func, buffer, _1, false, _2), orig, buffer, format, "export");
3054 }
3055
3056
3057 docstring GuiView::GuiViewPrivate::previewAndDestroy(Buffer const * orig, Buffer * buffer, string const & format)
3058 {
3059         bool(Buffer::* mem_func)(std::string const &, bool) const = &Buffer::preview;
3060         return runAndDestroy(bind(mem_func, buffer, _1, _2), orig, buffer, format, "preview");
3061 }
3062
3063 #else
3064
3065 // not used, but the linker needs them
3066
3067 docstring GuiView::GuiViewPrivate::compileAndDestroy(
3068                 Buffer const *, Buffer *, string const &)
3069 {
3070         return docstring();
3071 }
3072
3073
3074 docstring GuiView::GuiViewPrivate::exportAndDestroy(
3075                 Buffer const *, Buffer *, string const &)
3076 {
3077         return docstring();
3078 }
3079
3080
3081 docstring GuiView::GuiViewPrivate::previewAndDestroy(
3082                 Buffer const *, Buffer *, string const &)
3083 {
3084         return docstring();
3085 }
3086
3087 #endif
3088
3089
3090 bool GuiView::GuiViewPrivate::asyncBufferProcessing(
3091                            string const & argument,
3092                            Buffer const * used_buffer,
3093                            docstring const & msg,
3094                            docstring (*asyncFunc)(Buffer const *, Buffer *, string const &),
3095                            bool (Buffer::*syncFunc)(string const &, bool, bool) const,
3096                            bool (Buffer::*previewFunc)(string const &, bool) const)
3097 {
3098         if (!used_buffer)
3099                 return false;
3100
3101         string format = argument;
3102         if (format.empty())
3103                 format = used_buffer->params().getDefaultOutputFormat();
3104
3105 #if EXPORT_in_THREAD && (QT_VERSION >= 0x040400)
3106         if (!msg.empty()) {
3107                 progress_->clearMessages();
3108                 gv_->message(msg);
3109         }
3110         GuiViewPrivate::busyBuffers.insert(used_buffer);
3111         QFuture<docstring> f = QtConcurrent::run(
3112                                 asyncFunc,
3113                                 used_buffer,
3114                                 used_buffer->clone(),
3115                                 format);
3116         setPreviewFuture(f);
3117         last_export_format = used_buffer->params().bufferFormat();
3118         (void) syncFunc;
3119         (void) previewFunc;
3120         // We are asynchronous, so we don't know here anything about the success
3121         return true;
3122 #else
3123         if (syncFunc) {
3124                 // TODO check here if it breaks exporting with Qt < 4.4
3125                 bool const update_unincluded =
3126                                 used_buffer->params().maintain_unincluded_children &&
3127                                 !used_buffer->params().getIncludedChildren().empty();
3128                 return (used_buffer->*syncFunc)(format, true, update_unincluded);
3129         } else if (previewFunc) {
3130                 return (used_buffer->*previewFunc)(format, false);
3131         }
3132         (void) asyncFunc;
3133         return false;
3134 #endif
3135 }
3136
3137 void GuiView::dispatchToBufferView(FuncRequest const & cmd, DispatchResult & dr)
3138 {
3139         BufferView * bv = currentBufferView();
3140         LASSERT(bv, /**/);
3141
3142         // Let the current BufferView dispatch its own actions.
3143         bv->dispatch(cmd, dr);
3144         if (dr.dispatched())
3145                 return;
3146
3147         // Try with the document BufferView dispatch if any.
3148         BufferView * doc_bv = documentBufferView();
3149         if (doc_bv && doc_bv != bv) {
3150                 doc_bv->dispatch(cmd, dr);
3151                 if (dr.dispatched())
3152                         return;
3153         }
3154
3155         // Then let the current Cursor dispatch its own actions.
3156         bv->cursor().dispatch(cmd);
3157
3158         // update completion. We do it here and not in
3159         // processKeySym to avoid another redraw just for a
3160         // changed inline completion
3161         if (cmd.origin() == FuncRequest::KEYBOARD) {
3162                 if (cmd.action() == LFUN_SELF_INSERT
3163                         || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
3164                         updateCompletion(bv->cursor(), true, true);
3165                 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
3166                         updateCompletion(bv->cursor(), false, true);
3167                 else
3168                         updateCompletion(bv->cursor(), false, false);
3169         }
3170
3171         dr = bv->cursor().result();
3172 }
3173
3174
3175 void GuiView::dispatch(FuncRequest const & cmd, DispatchResult & dr)
3176 {
3177         BufferView * bv = currentBufferView();
3178         // By default we won't need any update.
3179         dr.screenUpdate(Update::None);
3180         // assume cmd will be dispatched
3181         dr.dispatched(true);
3182
3183         Buffer * doc_buffer = documentBufferView()
3184                 ? &(documentBufferView()->buffer()) : 0;
3185
3186         if (cmd.origin() == FuncRequest::TOC) {
3187                 GuiToc * toc = static_cast<GuiToc*>(findOrBuild("toc", false));
3188                 // FIXME: do we need to pass a DispatchResult object here?
3189                 toc->doDispatch(bv->cursor(), cmd);
3190                 return;
3191         }
3192
3193         string const argument = to_utf8(cmd.argument());
3194
3195         switch(cmd.action()) {
3196                 case LFUN_BUFFER_CHILD_OPEN:
3197                         openChildDocument(to_utf8(cmd.argument()));
3198                         break;
3199
3200                 case LFUN_BUFFER_IMPORT:
3201                         importDocument(to_utf8(cmd.argument()));
3202                         break;
3203
3204                 case LFUN_BUFFER_EXPORT: {
3205                         if (!doc_buffer)
3206                                 break;
3207                         // GCC only sees strfwd.h when building merged
3208                         if (::lyx::operator==(cmd.argument(), "custom")) {
3209                                 dispatch(FuncRequest(LFUN_DIALOG_SHOW, "sendto"), dr);
3210                                 break;
3211                         }
3212 #if QT_VERSION < 0x040400
3213                         if (!doc_buffer->doExport(argument, false)) {
3214                                 dr.setError(true);
3215                                 dr.setMessage(bformat(_("Error exporting to format: %1$s"),
3216                                         cmd.argument()));
3217                         }
3218 #else
3219                         /* TODO/Review: Is it a problem to also export the children?
3220                                         See the update_unincluded flag */
3221                         d.asyncBufferProcessing(argument,
3222                                                 doc_buffer,
3223                                                 _("Exporting ..."),
3224                                                 &GuiViewPrivate::exportAndDestroy,
3225                                                 &Buffer::doExport,
3226                                                 0);
3227                         // TODO Inform user about success
3228 #endif
3229                         break;
3230                 }
3231
3232                 case LFUN_BUFFER_EXPORT_AS:
3233                         LASSERT(doc_buffer, break);
3234                         exportBufferAs(*doc_buffer);
3235                         break;
3236
3237                 case LFUN_BUFFER_UPDATE: {
3238                         d.asyncBufferProcessing(argument,
3239                                                 doc_buffer,
3240                                                 _("Exporting ..."),
3241                                                 &GuiViewPrivate::compileAndDestroy,
3242                                                 &Buffer::doExport,
3243                                                 0);
3244                         break;
3245                 }
3246                 case LFUN_BUFFER_VIEW: {
3247                         d.asyncBufferProcessing(argument,
3248                                                 doc_buffer,
3249                                                 _("Previewing ..."),
3250                                                 &GuiViewPrivate::previewAndDestroy,
3251                                                 0,
3252                                                 &Buffer::preview);
3253                         break;
3254                 }
3255                 case LFUN_MASTER_BUFFER_UPDATE: {
3256                         d.asyncBufferProcessing(argument,
3257                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3258                                                 docstring(),
3259                                                 &GuiViewPrivate::compileAndDestroy,
3260                                                 &Buffer::doExport,
3261                                                 0);
3262                         break;
3263                 }
3264                 case LFUN_MASTER_BUFFER_VIEW: {
3265                         d.asyncBufferProcessing(argument,
3266                                                 (doc_buffer ? doc_buffer->masterBuffer() : 0),
3267                                                 docstring(),
3268                                                 &GuiViewPrivate::previewAndDestroy,
3269                                                 0, &Buffer::preview);
3270                         break;
3271                 }
3272                 case LFUN_BUFFER_SWITCH: {
3273                         string const file_name = to_utf8(cmd.argument());
3274                         if (!FileName::isAbsolute(file_name)) {
3275                                 dr.setError(true);
3276                                 dr.setMessage(_("Absolute filename expected."));
3277                                 break;
3278                         }
3279
3280                         Buffer * buffer = theBufferList().getBuffer(FileName(file_name));
3281                         if (!buffer) {
3282                                 dr.setError(true);
3283                                 dr.setMessage(_("Document not loaded"));
3284                                 break;
3285                         }
3286
3287                         // Do we open or switch to the buffer in this view ?
3288                         if (workArea(*buffer)
3289                                   || lyxrc.open_buffers_in_tabs || !documentBufferView()) {
3290                                 setBuffer(buffer);
3291                                 break;
3292                         }
3293
3294                         // Look for the buffer in other views
3295                         QList<int> const ids = guiApp->viewIds();
3296                         int i = 0;
3297                         for (; i != ids.size(); ++i) {
3298                                 GuiView & gv = guiApp->view(ids[i]);
3299                                 if (gv.workArea(*buffer)) {
3300                                         gv.activateWindow();
3301                                         gv.setBuffer(buffer);
3302                                         break;
3303                                 }
3304                         }
3305
3306                         // If necessary, open a new window as a last resort
3307                         if (i == ids.size()) {
3308                                 lyx::dispatch(FuncRequest(LFUN_WINDOW_NEW));
3309                                 lyx::dispatch(cmd);
3310                         }
3311                         break;
3312                 }
3313
3314                 case LFUN_BUFFER_NEXT:
3315                         gotoNextOrPreviousBuffer(NEXTBUFFER);
3316                         break;
3317
3318                 case LFUN_BUFFER_PREVIOUS:
3319                         gotoNextOrPreviousBuffer(PREVBUFFER);
3320                         break;
3321
3322                 case LFUN_COMMAND_EXECUTE: {
3323                         bool const show_it = cmd.argument() != "off";
3324                         // FIXME: this is a hack, "minibuffer" should not be
3325                         // hardcoded.
3326                         if (GuiToolbar * t = toolbar("minibuffer")) {
3327                                 t->setVisible(show_it);
3328                                 if (show_it && t->commandBuffer())
3329                                         t->commandBuffer()->setFocus();
3330                         }
3331                         break;
3332                 }
3333                 case LFUN_DROP_LAYOUTS_CHOICE:
3334                         d.layout_->showPopup();
3335                         break;
3336
3337                 case LFUN_MENU_OPEN:
3338                         if (QMenu * menu = guiApp->menus().menu(toqstr(cmd.argument()), *this))
3339                                 menu->exec(QCursor::pos());
3340                         break;
3341
3342                 case LFUN_FILE_INSERT:
3343                         insertLyXFile(cmd.argument());
3344                         break;
3345
3346                 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3347                         insertPlaintextFile(cmd.argument(), true);
3348                         break;
3349
3350                 case LFUN_FILE_INSERT_PLAINTEXT:
3351                         insertPlaintextFile(cmd.argument(), false);
3352                         break;
3353
3354                 case LFUN_BUFFER_RELOAD: {
3355                         LASSERT(doc_buffer, break);
3356
3357                         int ret = 0;
3358                         if (!doc_buffer->isClean()) {
3359                                 docstring const file =
3360                                         makeDisplayPath(doc_buffer->absFileName(), 20);
3361                                 docstring text = bformat(_("Any changes will be lost. "
3362                                         "Are you sure you want to revert to the saved version "
3363                                         "of the document %1$s?"), file);
3364                                 ret = Alert::prompt(_("Revert to saved document?"),
3365                                         text, 1, 1, _("&Revert"), _("&Cancel"));
3366                         }
3367
3368                         if (ret == 0) {
3369                                 doc_buffer->markClean();
3370                                 reloadBuffer(*doc_buffer);
3371                                 dr.forceBufferUpdate();
3372                         }
3373                         break;
3374                 }
3375
3376                 case LFUN_BUFFER_WRITE:
3377                         LASSERT(doc_buffer, break);
3378                         saveBuffer(*doc_buffer);
3379                         break;
3380
3381                 case LFUN_BUFFER_WRITE_AS:
3382                         LASSERT(doc_buffer, break);
3383                         renameBuffer(*doc_buffer, cmd.argument());
3384                         break;
3385
3386                 case LFUN_BUFFER_WRITE_ALL: {
3387                         Buffer * first = theBufferList().first();
3388                         if (!first)
3389                                 break;
3390                         message(_("Saving all documents..."));
3391                         // We cannot use a for loop as the buffer list cycles.
3392                         Buffer * b = first;
3393                         do {
3394                                 if (!b->isClean()) {
3395                                         saveBuffer(*b);
3396                                         LYXERR(Debug::ACTION, "Saved " << b->absFileName());
3397                                 }
3398                                 b = theBufferList().next(b);
3399                         } while (b != first);
3400                         dr.setMessage(_("All documents saved."));
3401                         break;
3402                 }
3403
3404                 case LFUN_BUFFER_CLOSE:
3405                         closeBuffer();
3406                         break;
3407
3408                 case LFUN_BUFFER_CLOSE_ALL:
3409                         closeBufferAll();
3410                         break;
3411
3412                 case LFUN_TOOLBAR_TOGGLE: {
3413                         string const name = cmd.getArg(0);
3414                         if (GuiToolbar * t = toolbar(name))
3415                                 t->toggle();
3416                         break;
3417                 }
3418
3419                 case LFUN_DIALOG_UPDATE: {
3420                         string const name = to_utf8(cmd.argument());
3421                         if (name == "prefs" || name == "document")
3422                                 updateDialog(name, string());
3423                         else if (name == "paragraph")
3424                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
3425                         else if (currentBufferView()) {
3426                                 Inset * inset = currentBufferView()->editedInset(name);
3427                                 // Can only update a dialog connected to an existing inset
3428                                 if (inset) {
3429                                         // FIXME: get rid of this indirection; GuiView ask the inset
3430                                         // if he is kind enough to update itself...
3431                                         FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument());
3432                                         //FIXME: pass DispatchResult here?
3433                                         inset->dispatch(currentBufferView()->cursor(), fr);
3434                                 }
3435                         }
3436                         break;
3437                 }
3438
3439                 case LFUN_DIALOG_TOGGLE: {
3440                         FuncCode const func_code = isDialogVisible(cmd.getArg(0))
3441                                 ? LFUN_DIALOG_HIDE : LFUN_DIALOG_SHOW;
3442                         dispatch(FuncRequest(func_code, cmd.argument()), dr);
3443                         break;
3444                 }
3445
3446                 case LFUN_DIALOG_DISCONNECT_INSET:
3447                         disconnectDialog(to_utf8(cmd.argument()));
3448                         break;
3449
3450                 case LFUN_DIALOG_HIDE: {
3451                         guiApp->hideDialogs(to_utf8(cmd.argument()), 0);
3452                         break;
3453                 }
3454
3455                 case LFUN_DIALOG_SHOW: {
3456                         string const name = cmd.getArg(0);
3457                         string data = trim(to_utf8(cmd.argument()).substr(name.size()));
3458
3459                         if (name == "character") {
3460                                 data = freefont2string();
3461                                 if (!data.empty())
3462                                         showDialog("character", data);
3463                         } else if (name == "latexlog") {
3464                                 Buffer::LogType type;
3465                                 string const logfile = doc_buffer->logName(&type);
3466                                 switch (type) {
3467                                 case Buffer::latexlog:
3468                                         data = "latex ";
3469                                         break;
3470                                 case Buffer::buildlog:
3471                                         data = "literate ";
3472                                         break;
3473                                 }
3474                                 data += Lexer::quoteString(logfile);
3475                                 showDialog("log", data);
3476                         } else if (name == "vclog") {
3477                                 string const data = "vc " +
3478                                         Lexer::quoteString(doc_buffer->lyxvc().getLogFile());
3479                                 showDialog("log", data);
3480                         } else if (name == "symbols") {
3481                                 data = bv->cursor().getEncoding()->name();
3482                                 if (!data.empty())
3483                                         showDialog("symbols", data);
3484                         // bug 5274
3485                         } else if (name == "prefs" && isFullScreen()) {
3486                                 lfunUiToggle("fullscreen");
3487                                 showDialog("prefs", data);
3488                         } else
3489                                 showDialog(name, data);
3490                         break;
3491                 }
3492
3493                 case LFUN_MESSAGE:
3494                         dr.setMessage(cmd.argument());
3495                         break;
3496
3497                 case LFUN_UI_TOGGLE: {
3498                         string arg = cmd.getArg(0);
3499                         if (!lfunUiToggle(arg)) {
3500                                 docstring const msg = "ui-toggle " + _("%1$s unknown command!");
3501                                 dr.setMessage(bformat(msg, from_utf8(arg)));
3502                         }
3503                         // Make sure the keyboard focus stays in the work area.
3504                         setFocus();
3505                         break;
3506                 }
3507
3508                 case LFUN_SPLIT_VIEW: {
3509                         LASSERT(doc_buffer, break);
3510                         string const orientation = cmd.getArg(0);
3511                         d.splitter_->setOrientation(orientation == "vertical"
3512                                 ? Qt::Vertical : Qt::Horizontal);
3513                         TabWorkArea * twa = addTabWorkArea();
3514                         GuiWorkArea * wa = twa->addWorkArea(*doc_buffer, *this);
3515                         setCurrentWorkArea(wa);
3516                         break;
3517                 }
3518                 case LFUN_CLOSE_TAB_GROUP:
3519                         if (TabWorkArea * twa = d.currentTabWorkArea()) {
3520                                 closeTabWorkArea(twa);
3521                                 d.current_work_area_ = 0;
3522                                 twa = d.currentTabWorkArea();
3523                                 // Switch to the next GuiWorkArea in the found TabWorkArea.
3524                                 if (twa) {
3525                                         // Make sure the work area is up to date.
3526                                         setCurrentWorkArea(twa->currentWorkArea());
3527                                 } else {
3528                                         setCurrentWorkArea(0);
3529                                 }
3530                         }
3531                         break;
3532
3533                 case LFUN_COMPLETION_INLINE:
3534                         if (d.current_work_area_)
3535                                 d.current_work_area_->completer().showInline();
3536                         break;
3537
3538                 case LFUN_COMPLETION_POPUP:
3539                         if (d.current_work_area_)
3540                                 d.current_work_area_->completer().showPopup();
3541                         break;
3542
3543
3544                 case LFUN_COMPLETION_COMPLETE:
3545                         if (d.current_work_area_)
3546                                 d.current_work_area_->completer().tab();
3547                         break;
3548
3549                 case LFUN_COMPLETION_CANCEL:
3550                         if (d.current_work_area_) {
3551                                 if (d.current_work_area_->completer().popupVisible())
3552                                         d.current_work_area_->completer().hidePopup();
3553                                 else
3554                                         d.current_work_area_->completer().hideInline();
3555                         }
3556                         break;
3557
3558                 case LFUN_COMPLETION_ACCEPT:
3559                         if (d.current_work_area_)
3560                                 d.current_work_area_->completer().activate();
3561                         break;
3562
3563                 case LFUN_BUFFER_ZOOM_IN:
3564                 case LFUN_BUFFER_ZOOM_OUT:
3565                         if (cmd.argument().empty()) {
3566                                 if (cmd.action() == LFUN_BUFFER_ZOOM_IN)
3567                                         lyxrc.zoom += 20;
3568                                 else
3569                                         lyxrc.zoom -= 20;
3570                         } else
3571                                 lyxrc.zoom += convert<int>(cmd.argument());
3572
3573                         if (lyxrc.zoom < 10)
3574                                 lyxrc.zoom = 10;
3575
3576                         // The global QPixmapCache is used in GuiPainter to cache text
3577                         // painting so we must reset it.
3578                         QPixmapCache::clear();
3579                         guiApp->fontLoader().update();
3580                         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
3581                         break;
3582
3583                 case LFUN_VC_REGISTER:
3584                 case LFUN_VC_CHECK_IN:
3585                 case LFUN_VC_CHECK_OUT:
3586                 case LFUN_VC_REPO_UPDATE:
3587                 case LFUN_VC_LOCKING_TOGGLE:
3588                 case LFUN_VC_REVERT:
3589                 case LFUN_VC_UNDO_LAST:
3590                 case LFUN_VC_COMMAND:
3591                 case LFUN_VC_COMPARE:
3592                         dispatchVC(cmd, dr);
3593                         break;
3594
3595                 case LFUN_SERVER_GOTO_FILE_ROW:
3596                         goToFileRow(to_utf8(cmd.argument()));
3597                         break;
3598
3599                 case LFUN_FORWARD_SEARCH: {
3600                         Buffer const * doc_master = doc_buffer->masterBuffer();
3601                         FileName const path(doc_master->temppath());
3602                         string const texname = doc_master->isChild(doc_buffer)
3603                                 ? DocFileName(changeExtension(
3604                                         doc_buffer->absFileName(),
3605                                                 "tex")).mangledFileName()
3606                                 : doc_buffer->latexName();
3607                         string const mastername =
3608                                 removeExtension(doc_master->latexName());
3609                         FileName const dviname(addName(path.absFileName(),
3610                                         addExtension(mastername, "dvi")));
3611                         FileName const pdfname(addName(path.absFileName(),
3612                                         addExtension(mastername, "pdf")));
3613                         bool const have_dvi = dviname.exists();
3614                         bool const have_pdf = pdfname.exists();
3615                         if (!have_dvi && !have_pdf) {
3616                                 dr.setMessage(_("Please, preview the document first."));
3617                                 break;
3618                         }
3619                         string outname = dviname.onlyFileName();
3620                         string command = lyxrc.forward_search_dvi;
3621                         if (!have_dvi || (have_pdf &&
3622                             pdfname.lastModified() > dviname.lastModified())) {
3623                                 outname = pdfname.onlyFileName();
3624                                 command = lyxrc.forward_search_pdf;
3625                         }
3626
3627                         int row = doc_buffer->texrow().getRowFromIdPos(bv->cursor().paragraph().id(), bv->cursor().pos());
3628                         LYXERR(Debug::ACTION, "Forward search: row:" << row
3629                                 << " id:" << bv->cursor().paragraph().id());
3630                         if (!row || command.empty()) {
3631                                 dr.setMessage(_("Couldn't proceed."));
3632                                 break;
3633                         }
3634                         string texrow = convert<string>(row);
3635
3636                         command = subst(command, "$$n", texrow);
3637                         command = subst(command, "$$t", texname);
3638                         command = subst(command, "$$o", outname);
3639
3640                         PathChanger p(path);
3641                         Systemcall one;
3642                         one.startscript(Systemcall::DontWait, command);
3643                         break;
3644                 }
3645                 default:
3646                         // The LFUN must be for one of BufferView, Buffer or Cursor;
3647                         // let's try that:
3648                         dispatchToBufferView(cmd, dr);
3649                         break;
3650         }
3651
3652         // Part of automatic menu appearance feature.
3653         if (isFullScreen()) {
3654                 if (menuBar()->isVisible() && lyxrc.full_screen_menubar)
3655                         menuBar()->hide();
3656                 if (statusBar()->isVisible())
3657                         statusBar()->hide();
3658         }
3659 }
3660
3661
3662 bool GuiView::lfunUiToggle(string const & ui_component)
3663 {
3664         if (ui_component == "scrollbar") {
3665                 // hide() is of no help
3666                 if (d.current_work_area_->verticalScrollBarPolicy() ==
3667                         Qt::ScrollBarAlwaysOff)
3668
3669                         d.current_work_area_->setVerticalScrollBarPolicy(
3670                                 Qt::ScrollBarAsNeeded);
3671                 else
3672                         d.current_work_area_->setVerticalScrollBarPolicy(
3673                                 Qt::ScrollBarAlwaysOff);
3674         } else if (ui_component == "statusbar") {
3675                 statusBar()->setVisible(!statusBar()->isVisible());
3676         } else if (ui_component == "menubar") {
3677                 menuBar()->setVisible(!menuBar()->isVisible());
3678         } else
3679 #if QT_VERSION >= 0x040300
3680         if (ui_component == "frame") {
3681                 int l, t, r, b;
3682                 getContentsMargins(&l, &t, &r, &b);
3683                 //are the frames in default state?
3684                 d.current_work_area_->setFrameStyle(QFrame::NoFrame);
3685                 if (l == 0) {
3686                         setContentsMargins(-2, -2, -2, -2);
3687                 } else {
3688                         setContentsMargins(0, 0, 0, 0);
3689                 }
3690         } else
3691 #endif
3692         if (ui_component == "fullscreen") {
3693                 toggleFullScreen();
3694         } else
3695                 return false;
3696         return true;
3697 }
3698
3699
3700 void GuiView::toggleFullScreen()
3701 {
3702         if (isFullScreen()) {
3703                 for (int i = 0; i != d.splitter_->count(); ++i)
3704                         d.tabWorkArea(i)->setFullScreen(false);
3705 #if QT_VERSION >= 0x040300
3706                 setContentsMargins(0, 0, 0, 0);
3707 #endif
3708                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3709                 restoreLayout();
3710                 menuBar()->show();
3711                 statusBar()->show();
3712         } else {
3713                 // bug 5274
3714                 hideDialogs("prefs", 0);
3715                 for (int i = 0; i != d.splitter_->count(); ++i)
3716                         d.tabWorkArea(i)->setFullScreen(true);
3717 #if QT_VERSION >= 0x040300
3718                 setContentsMargins(-2, -2, -2, -2);
3719 #endif
3720                 saveLayout();
3721                 setWindowState(windowState() ^ Qt::WindowFullScreen);
3722                 statusBar()->hide();
3723                 if (lyxrc.full_screen_menubar)
3724                         menuBar()->hide();
3725                 if (lyxrc.full_screen_toolbars) {
3726                         ToolbarMap::iterator end = d.toolbars_.end();
3727                         for (ToolbarMap::iterator it = d.toolbars_.begin(); it != end; ++it)
3728                                 it->second->hide();
3729                 }
3730         }
3731
3732         // give dialogs like the TOC a chance to adapt
3733         updateDialogs();
3734 }
3735
3736
3737 Buffer const * GuiView::updateInset(Inset const * inset)
3738 {
3739         if (!inset)
3740                 return 0;
3741
3742         Buffer const * inset_buffer = &(inset->buffer());
3743
3744         for (int i = 0; i != d.splitter_->count(); ++i) {
3745                 GuiWorkArea * wa = d.tabWorkArea(i)->currentWorkArea();
3746                 if (!wa)
3747                         continue;
3748                 Buffer const * buffer = &(wa->bufferView().buffer());
3749                 if (inset_buffer == buffer)
3750                         wa->scheduleRedraw();
3751         }
3752         return inset_buffer;
3753 }
3754
3755
3756 void GuiView::restartCursor()
3757 {
3758         /* When we move around, or type, it's nice to be able to see
3759          * the cursor immediately after the keypress.
3760          */
3761         if (d.current_work_area_)
3762                 d.current_work_area_->startBlinkingCursor();
3763
3764         // Take this occasion to update the other GUI elements.
3765         updateDialogs();
3766         updateStatusBar();
3767 }
3768
3769
3770 void GuiView::updateCompletion(Cursor & cur, bool start, bool keep)
3771 {
3772         if (d.current_work_area_)
3773                 d.current_work_area_->completer().updateVisibility(cur, start, keep);
3774 }
3775
3776 namespace {
3777
3778 // This list should be kept in sync with the list of insets in
3779 // src/insets/Inset.cpp.  I.e., if a dialog goes with an inset, the
3780 // dialog should have the same name as the inset.
3781 // Changes should be also recorded in LFUN_DIALOG_SHOW doxygen
3782 // docs in LyXAction.cpp.
3783
3784 char const * const dialognames[] = {
3785
3786 "aboutlyx", "bibitem", "bibtex", "box", "branch", "changes", "character",
3787 "citation", "compare", "comparehistory", "document", "errorlist", "ert",
3788 "external", "file", "findreplace", "findreplaceadv", "float", "graphics",
3789 "href", "include", "index", "index_print", "info", "listings", "label", "line",
3790 "log", "mathdelimiter", "mathmatrix", "mathspace", "nomenclature",
3791 "nomencl_print", "note", "paragraph", "phantom", "prefs", "print", "ref",
3792 "sendto", "space", "spellchecker", "symbols", "tabular", "tabularcreate",
3793 "thesaurus", "texinfo", "toc", "view-source", "vspace", "wrap", "progress"};
3794
3795 char const * const * const end_dialognames =
3796         dialognames + (sizeof(dialognames) / sizeof(char *));
3797
3798 class cmpCStr {
3799 public:
3800         cmpCStr(char const * name) : name_(name) {}
3801         bool operator()(char const * other) {
3802                 return strcmp(other, name_) == 0;
3803         }
3804 private:
3805         char const * name_;
3806 };
3807
3808
3809 bool isValidName(string const & name)
3810 {
3811         return find_if(dialognames, end_dialognames,
3812                                 cmpCStr(name.c_str())) != end_dialognames;
3813 }
3814
3815 } // namespace anon
3816
3817
3818 void GuiView::resetDialogs()
3819 {
3820         // Make sure that no LFUN uses any GuiView.
3821         guiApp->setCurrentView(0);
3822         saveLayout();
3823         saveUISettings();
3824         menuBar()->clear();
3825         constructToolbars();
3826         guiApp->menus().fillMenuBar(menuBar(), this, false);
3827         d.layout_->updateContents(true);
3828         // Now update controls with current buffer.
3829         guiApp->setCurrentView(this);
3830         restoreLayout();
3831         restartCursor();
3832 }
3833
3834
3835 Dialog * GuiView::findOrBuild(string const & name, bool hide_it)
3836 {
3837         if (!isValidName(name))
3838                 return 0;
3839
3840         map<string, DialogPtr>::iterator it = d.dialogs_.find(name);
3841
3842         if (it != d.dialogs_.end()) {
3843                 if (hide_it)
3844                         it->second->hideView();
3845                 return it->second.get();
3846         }
3847
3848         Dialog * dialog = build(name);
3849         d.dialogs_[name].reset(dialog);
3850         if (lyxrc.allow_geometry_session)
3851                 dialog->restoreSession();
3852         if (hide_it)
3853                 dialog->hideView();
3854         return dialog;
3855 }
3856
3857
3858 void GuiView::showDialog(string const & name, string const & data,
3859         Inset * inset)
3860 {
3861         triggerShowDialog(toqstr(name), toqstr(data), inset);
3862 }
3863
3864
3865 void GuiView::doShowDialog(QString const & qname, QString const & qdata,
3866         Inset * inset)
3867 {
3868         if (d.in_show_)
3869                 return;
3870
3871         const string name = fromqstr(qname);
3872         const string data = fromqstr(qdata);
3873
3874         d.in_show_ = true;
3875         try {
3876                 Dialog * dialog = findOrBuild(name, false);
3877                 if (dialog) {
3878                         bool const visible = dialog->isVisibleView();
3879                         dialog->showData(data);
3880                         if (inset && currentBufferView())
3881                                 currentBufferView()->editInset(name, inset);
3882                         // We only set the focus to the new dialog if it was not yet
3883                         // visible in order not to change the existing previous behaviour
3884                         if (visible) {
3885                                 // activateWindow is needed for floating dockviews
3886                                 dialog->asQWidget()->raise();
3887                                 dialog->asQWidget()->activateWindow();
3888                                 dialog->asQWidget()->setFocus();
3889                         }
3890                 }
3891         }
3892         catch (ExceptionMessage const & ex) {
3893                 d.in_show_ = false;
3894                 throw ex;
3895         }
3896         d.in_show_ = false;
3897 }
3898
3899
3900 bool GuiView::isDialogVisible(string const & name) const
3901 {
3902         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3903         if (it == d.dialogs_.end())
3904                 return false;
3905         return it->second.get()->isVisibleView() && !it->second.get()->isClosing();
3906 }
3907
3908
3909 void GuiView::hideDialog(string const & name, Inset * inset)
3910 {
3911         map<string, DialogPtr>::const_iterator it = d.dialogs_.find(name);
3912         if (it == d.dialogs_.end())
3913                 return;
3914
3915         if (inset) {
3916                 if (!currentBufferView())
3917                         return;
3918                 if (inset != currentBufferView()->editedInset(name))
3919                         return;
3920         }
3921
3922         Dialog * const dialog = it->second.get();
3923         if (dialog->isVisibleView())
3924                 dialog->hideView();
3925         if (currentBufferView())
3926                 currentBufferView()->editInset(name, 0);
3927 }
3928
3929
3930 void GuiView::disconnectDialog(string const & name)
3931 {
3932         if (!isValidName(name))
3933                 return;
3934         if (currentBufferView())
3935                 currentBufferView()->editInset(name, 0);
3936 }
3937
3938
3939 void GuiView::hideAll() const
3940 {
3941         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3942         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3943
3944         for(; it != end; ++it)
3945                 it->second->hideView();
3946 }
3947
3948
3949 void GuiView::updateDialogs()
3950 {
3951         map<string, DialogPtr>::const_iterator it  = d.dialogs_.begin();
3952         map<string, DialogPtr>::const_iterator end = d.dialogs_.end();
3953
3954         for(; it != end; ++it) {
3955                 Dialog * dialog = it->second.get();
3956                 if (dialog) {
3957                         if (dialog->needBufferOpen() && !documentBufferView())
3958                                 hideDialog(fromqstr(dialog->name()), 0);
3959                         else if (dialog->isVisibleView())
3960                                 dialog->checkStatus();
3961                 }
3962         }
3963         updateToolbars();
3964         updateLayoutList();
3965 }
3966
3967 Dialog * createDialog(GuiView & lv, string const & name);
3968
3969 // will be replaced by a proper factory...
3970 Dialog * createGuiAbout(GuiView & lv);
3971 Dialog * createGuiBibtex(GuiView & lv);
3972 Dialog * createGuiChanges(GuiView & lv);
3973 Dialog * createGuiCharacter(GuiView & lv);
3974 Dialog * createGuiCitation(GuiView & lv);
3975 Dialog * createGuiCompare(GuiView & lv);
3976 Dialog * createGuiCompareHistory(GuiView & lv);
3977 Dialog * createGuiDelimiter(GuiView & lv);
3978 Dialog * createGuiDocument(GuiView & lv);
3979 Dialog * createGuiErrorList(GuiView & lv);
3980 Dialog * createGuiExternal(GuiView & lv);
3981 Dialog * createGuiGraphics(GuiView & lv);
3982 Dialog * createGuiInclude(GuiView & lv);
3983 Dialog * createGuiIndex(GuiView & lv);
3984 Dialog * createGuiListings(GuiView & lv);
3985 Dialog * createGuiLog(GuiView & lv);
3986 Dialog * createGuiMathMatrix(GuiView & lv);
3987 Dialog * createGuiNote(GuiView & lv);
3988 Dialog * createGuiParagraph(GuiView & lv);
3989 Dialog * createGuiPhantom(GuiView & lv);
3990 Dialog * createGuiPreferences(GuiView & lv);
3991 Dialog * createGuiPrint(GuiView & lv);
3992 Dialog * createGuiPrintindex(GuiView & lv);
3993 Dialog * createGuiRef(GuiView & lv);
3994 Dialog * createGuiSearch(GuiView & lv);
3995 Dialog * createGuiSearchAdv(GuiView & lv);
3996 Dialog * createGuiSendTo(GuiView & lv);
3997 Dialog * createGuiShowFile(GuiView & lv);
3998 Dialog * createGuiSpellchecker(GuiView & lv);
3999 Dialog * createGuiSymbols(GuiView & lv);
4000 Dialog * createGuiTabularCreate(GuiView & lv);
4001 Dialog * createGuiTexInfo(GuiView & lv);
4002 Dialog * createGuiToc(GuiView & lv);
4003 Dialog * createGuiThesaurus(GuiView & lv);
4004 Dialog * createGuiViewSource(GuiView & lv);
4005 Dialog * createGuiWrap(GuiView & lv);
4006 Dialog * createGuiProgressView(GuiView & lv);
4007
4008
4009
4010 Dialog * GuiView::build(string const & name)
4011 {
4012         LASSERT(isValidName(name), return 0);
4013
4014         Dialog * dialog = createDialog(*this, name);
4015         if (dialog)
4016                 return dialog;
4017
4018         if (name == "aboutlyx")
4019                 return createGuiAbout(*this);
4020         if (name == "bibtex")
4021                 return createGuiBibtex(*this);
4022         if (name == "changes")
4023                 return createGuiChanges(*this);
4024         if (name == "character")
4025                 return createGuiCharacter(*this);
4026         if (name == "citation")
4027                 return createGuiCitation(*this);
4028         if (name == "compare")
4029                 return createGuiCompare(*this);
4030         if (name == "comparehistory")
4031                 return createGuiCompareHistory(*this);
4032         if (name == "document")
4033                 return createGuiDocument(*this);
4034         if (name == "errorlist")
4035                 return createGuiErrorList(*this);
4036         if (name == "external")
4037                 return createGuiExternal(*this);
4038         if (name == "file")
4039                 return createGuiShowFile(*this);
4040         if (name == "findreplace")
4041                 return createGuiSearch(*this);
4042         if (name == "findreplaceadv")
4043                 return createGuiSearchAdv(*this);
4044         if (name == "graphics")
4045                 return createGuiGraphics(*this);
4046         if (name == "include")
4047                 return createGuiInclude(*this);
4048         if (name == "index")
4049                 return createGuiIndex(*this);
4050         if (name == "index_print")
4051                 return createGuiPrintindex(*this);
4052         if (name == "listings")
4053                 return createGuiListings(*this);
4054         if (name == "log")
4055                 return createGuiLog(*this);
4056         if (name == "mathdelimiter")
4057                 return createGuiDelimiter(*this);
4058         if (name == "mathmatrix")
4059                 return createGuiMathMatrix(*this);
4060         if (name == "note")
4061                 return createGuiNote(*this);
4062         if (name == "paragraph")
4063                 return createGuiParagraph(*this);
4064         if (name == "phantom")
4065                 return createGuiPhantom(*this);
4066         if (name == "prefs")
4067                 return createGuiPreferences(*this);
4068         if (name == "print")
4069                 return createGuiPrint(*this);
4070         if (name == "ref")
4071                 return createGuiRef(*this);
4072         if (name == "sendto")
4073                 return createGuiSendTo(*this);
4074         if (name == "spellchecker")
4075                 return createGuiSpellchecker(*this);
4076         if (name == "symbols")
4077                 return createGuiSymbols(*this);
4078         if (name == "tabularcreate")
4079                 return createGuiTabularCreate(*this);
4080         if (name == "texinfo")
4081                 return createGuiTexInfo(*this);
4082         if (name == "thesaurus")
4083                 return createGuiThesaurus(*this);
4084         if (name == "toc")
4085                 return createGuiToc(*this);
4086         if (name == "view-source")
4087                 return createGuiViewSource(*this);
4088         if (name == "wrap")
4089                 return createGuiWrap(*this);
4090         if (name == "progress")
4091                 return createGuiProgressView(*this);
4092
4093         return 0;
4094 }
4095
4096
4097 } // namespace frontend
4098 } // namespace lyx
4099
4100 #include "moc_GuiView.cpp"