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