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