]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiView.cpp
Some cosmetics and a gcc compile fix.
[lyx.git] / src / frontends / qt4 / GuiView.cpp
1 /**
2  * \file GuiView.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Abdelrazak Younes
9  * \author Peter Kümmel
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "GuiView.h"
17
18 #include "GuiImplementation.h"
19 #include "GuiWorkArea.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiMenubar.h"
22 #include "GuiToolbar.h"
23 #include "GuiToolbars.h"
24 #include "Dialogs.h"
25 #include "Gui.h"
26
27 #include "qt_helpers.h"
28
29 #include "frontends/Application.h"
30 #include "frontends/Dialogs.h"
31 #include "frontends/Gui.h"
32
33 #include "support/filetools.h"
34 #include "support/convert.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
37
38 #include "buffer_funcs.h"
39 #include "Buffer.h"
40 #include "BufferList.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "Cursor.h"
44 #include "debug.h"
45 #include "ErrorList.h"
46 #include "FuncRequest.h"
47 #include "gettext.h"
48 #include "Intl.h"
49 #include "Layout.h"
50 #include "LyXFunc.h"
51 #include "LyX.h"
52 #include "LyXRC.h"
53 #include "MenuBackend.h"
54 #include "Paragraph.h"
55 #include "Session.h"
56 #include "TextClass.h"
57 #include "Text.h"
58 #include "ToolbarBackend.h"
59 #include "version.h"
60
61 #include "support/lstrings.h"
62 #include "support/filetools.h" // OnlyFilename()
63 #include "support/Timeout.h"
64
65 #include <QAction>
66 #include <QApplication>
67 #include <QCloseEvent>
68 #include <QDesktopWidget>
69 #include <QDragEnterEvent>
70 #include <QDropEvent>
71 #include <QList>
72 #include <QMenu>
73 #include <QPainter>
74 #include <QPixmap>
75 #include <QPushButton>
76 #include <QSplitter>
77 #include <QStackedWidget>
78 #include <QStatusBar>
79 #include <QToolBar>
80 #include <QUrl>
81
82 #include <boost/bind.hpp>
83 #include <boost/current_function.hpp>
84
85 #ifdef HAVE_SYS_TIME_H
86 # include <sys/time.h>
87 #endif
88 #ifdef HAVE_UNISTD_H
89 # include <unistd.h>
90 #endif
91
92 using std::endl;
93 using std::string;
94 using std::vector;
95
96 namespace lyx {
97
98 extern bool quitting;
99
100 namespace frontend {
101
102 using support::bformat;
103 using support::FileName;
104 using support::makeDisplayPath;
105 using support::onlyFilename;
106
107 namespace {
108
109 int const statusbar_timer_value = 3000;
110
111 class BackgroundWidget : public QWidget
112 {
113 public:
114         BackgroundWidget(QString const & file, QString const & text)
115         {
116                 splash_ = new QPixmap(file);
117                 if (!splash_) {
118                         lyxerr << "could not load splash screen: '" << fromqstr(file) << "'" << endl;
119                         return;
120                 }
121
122                 QPainter pain(splash_);
123                 pain.setPen(QColor(255, 255, 0));
124                 QFont font;
125                 // The font used to display the version info
126                 font.setStyleHint(QFont::SansSerif);
127                 font.setWeight(QFont::Bold);
128                 font.setPointSize(convert<int>(lyxrc.font_sizes[FONT_SIZE_LARGE]));
129                 pain.setFont(font);
130                 pain.drawText(260, 270, text);
131         }
132
133         void paintEvent(QPaintEvent *)
134         {
135                 if (!splash_)
136                         return;
137
138                 int x = (width() - splash_->width()) / 2;
139                 int y = (height() - splash_->height()) / 2;
140                 QPainter pain(this);
141                 pain.drawPixmap(x, y, *splash_);
142         }
143
144 private:
145         QPixmap * splash_;
146 };
147
148 } // namespace anon
149
150
151 struct GuiView::GuiViewPrivate
152 {
153         GuiViewPrivate()
154                 : current_work_area_(0), posx_offset(0), posy_offset(0)
155         {}
156
157         ~GuiViewPrivate()
158         {
159                 delete splitter_;
160                 delete bg_widget_;
161                 delete stack_widget_;
162                 delete menubar_;
163                 delete toolbars_;
164         }
165
166         unsigned int smallIconSize;
167         unsigned int normalIconSize;
168         unsigned int bigIconSize;
169         // static needed by "New Window"
170         static unsigned int lastIconSize;
171
172         QMenu * toolBarPopup(GuiView * parent)
173         {
174                 // FIXME: translation
175                 QMenu * menu = new QMenu(parent);
176                 QActionGroup * iconSizeGroup = new QActionGroup(parent);
177
178                 QAction * smallIcons = new QAction(iconSizeGroup);
179                 smallIcons->setText(qt_("Small-sized icons"));
180                 smallIcons->setCheckable(true);
181                 QObject::connect(smallIcons, SIGNAL(triggered()),
182                         parent, SLOT(smallSizedIcons()));
183                 menu->addAction(smallIcons);
184
185                 QAction * normalIcons = new QAction(iconSizeGroup);
186                 normalIcons->setText(qt_("Normal-sized icons"));
187                 normalIcons->setCheckable(true);
188                 QObject::connect(normalIcons, SIGNAL(triggered()),
189                         parent, SLOT(normalSizedIcons()));
190                 menu->addAction(normalIcons);
191
192                 QAction * bigIcons = new QAction(iconSizeGroup);
193                 bigIcons->setText(qt_("Big-sized icons"));
194                 bigIcons->setCheckable(true);
195                 QObject::connect(bigIcons, SIGNAL(triggered()),
196                         parent, SLOT(bigSizedIcons()));
197                 menu->addAction(bigIcons);
198
199                 unsigned int cur = parent->iconSize().width();
200                 if ( cur == parent->d.smallIconSize)
201                         smallIcons->setChecked(true);
202                 else if (cur == parent->d.normalIconSize)
203                         normalIcons->setChecked(true);
204                 else if (cur == parent->d.bigIconSize)
205                         bigIcons->setChecked(true);
206
207                 return menu;
208         }
209
210         void initBackground()
211         {
212                 LYXERR(Debug::GUI) << "show banner: " << lyxrc.show_banner << endl;
213                 /// The text to be written on top of the pixmap
214                 QString const text = lyx_version ? QString(lyx_version) : qt_("unknown version");
215                 bg_widget_ = new BackgroundWidget(":/images/banner.png", text);
216         }
217
218         void setBackground()
219         {
220                 stack_widget_->setCurrentWidget(bg_widget_);
221                 bg_widget_->setUpdatesEnabled(true);
222         }
223
224         TabWorkArea * tabWorkArea(int i)
225         {
226                 return dynamic_cast<TabWorkArea *>(splitter_->widget(i));
227         }
228
229         TabWorkArea * currentTabWorkArea()
230         {
231                 if (splitter_->count() == 1)
232                         // The first TabWorkArea is always the first one, if any.
233                         return tabWorkArea(0);
234
235                 TabWorkArea * tab_widget = 0;
236                 for (int i = 0; i != splitter_->count(); ++i) {
237                         QWidget * w = splitter_->widget(i);
238                         if (!w->hasFocus())
239                                 continue;
240                         tab_widget = dynamic_cast<TabWorkArea *>(w);
241                         if (tab_widget)
242                                 break;
243                 }
244
245                 return tab_widget;
246         }
247
248 public:
249         ///
250         string cur_title;
251
252         GuiWorkArea * current_work_area_;
253         int posx_offset;
254         int posy_offset;
255
256         QSplitter * splitter_;
257         QStackedWidget * stack_widget_;
258         BackgroundWidget * bg_widget_;
259         /// view's menubar
260         GuiMenubar * menubar_;
261         /// view's toolbars
262         GuiToolbars * toolbars_;
263         ///
264         docstring current_layout;
265 };
266
267
268 unsigned int GuiView::GuiViewPrivate::lastIconSize = 0;
269
270
271 GuiView::GuiView(int id)
272         : QMainWindow(), LyXView(id),
273           d(*new GuiViewPrivate),
274                 quitting_by_menu_(false),
275                 autosave_timeout_(new Timeout(5000)),
276           dialogs_(new Dialogs(*this))
277 {
278         // Start autosave timer
279         if (lyxrc.autosave) {
280                 autosave_timeout_->timeout.connect(boost::bind(&GuiView::autoSave, this));
281                 autosave_timeout_->setTimeout(lyxrc.autosave * 1000);
282                 autosave_timeout_->start();
283         }
284
285         // Qt bug? signal lastWindowClosed does not work
286         setAttribute(Qt::WA_QuitOnClose, false);
287         setAttribute(Qt::WA_DeleteOnClose, true);
288
289         // hardcode here the platform specific icon size
290         d.smallIconSize = 14;   // scaling problems
291         d.normalIconSize = 20;  // ok, default
292         d.bigIconSize = 26;             // better for some math icons
293
294 #ifndef Q_WS_MACX
295         // assign an icon to main form. We do not do it under Qt/Mac,
296         // since the icon is provided in the application bundle.
297         setWindowIcon(QPixmap(":/images/lyx.png"));
298 #endif
299
300
301         d.splitter_ = new QSplitter;
302
303         d.initBackground();
304         LYXERR(Debug::GUI) << "stack widget!" << endl;
305         d.stack_widget_ = new QStackedWidget;
306         d.stack_widget_->addWidget(d.bg_widget_);
307         d.stack_widget_->addWidget(d.splitter_);
308         setCentralWidget(d.stack_widget_);
309
310         // For Drag&Drop.
311         setAcceptDrops(true);
312 }
313
314
315 GuiView::~GuiView()
316 {
317         delete dialogs_;
318         delete autosave_timeout_;
319         delete &d;
320 }
321
322
323 void GuiView::close()
324 {
325         quitting_by_menu_ = true;
326         d.current_work_area_ = 0;
327         for (int i = 0; i != d.splitter_->count(); ++i) {
328                 TabWorkArea * twa = d.tabWorkArea(i);
329                 if (twa)
330                         twa->closeAll();
331         }
332         QMainWindow::close();
333         quitting_by_menu_ = false;
334 }
335
336
337 void GuiView::setFocus()
338 {
339         if (d.current_work_area_)
340                 d.current_work_area_->setFocus();
341         else
342                 QWidget::setFocus();
343 }
344
345
346 QMenu* GuiView::createPopupMenu()
347 {
348         return d.toolBarPopup(this);
349 }
350
351
352 void GuiView::init()
353 {
354         // GuiToolbars *must* be initialised before GuiMenubar.
355         d.toolbars_ = new GuiToolbars(*this);
356         // FIXME: GuiToolbars::init() cannot be integrated in the ctor
357         // because LyXFunc::getStatus() needs a properly initialized
358         // GuiToolbars object (for LFUN_TOOLBAR_TOGGLE).
359         d.toolbars_->init();
360         d.menubar_ = new GuiMenubar(this, menubackend);
361
362         statusBar()->setSizeGripEnabled(true);
363
364         QObject::connect(&statusbar_timer_, SIGNAL(timeout()),
365                 this, SLOT(clearMessage()));
366
367         d.setBackground();
368 }
369
370
371 void GuiView::closeEvent(QCloseEvent * close_event)
372 {
373         // we may have been called through the close window button
374         // which bypasses the LFUN machinery.
375         if (!quitting_by_menu_ && theApp()->gui().viewIds().size() == 1) {
376                 if (!theBufferList().quitWriteAll()) {
377                         close_event->ignore();
378                         return;
379                 }
380         }
381
382         // Make sure that no LFUN use this close to be closed View.
383         theLyXFunc().setLyXView(0);
384         // Make sure the timer time out will not trigger a statusbar update.
385         statusbar_timer_.stop();
386
387         theApp()->gui().unregisterView(id());
388         if (!theApp()->gui().viewIds().empty()) {
389                 // Just close the window and do nothing else if this is not the
390                 // last window.
391                 close_event->accept();
392                 return;
393         }
394
395         quitting = true;
396
397         // this is the place where we leave the frontend.
398         // it is the only point at which we start quitting.
399         saveGeometry();
400         close_event->accept();
401         // quit the event loop
402         qApp->quit();
403 }
404
405
406 void GuiView::dragEnterEvent(QDragEnterEvent * event)
407 {
408         if (event->mimeData()->hasUrls())
409                 event->accept();
410         /// \todo Ask lyx-devel is this is enough:
411         /// if (event->mimeData()->hasFormat("text/plain"))
412         ///     event->acceptProposedAction();
413 }
414
415
416 void GuiView::dropEvent(QDropEvent* event)
417 {
418         QList<QUrl> files = event->mimeData()->urls();
419         if (files.isEmpty())
420                 return;
421
422         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
423                 << " got URLs!" << endl;
424         for (int i = 0; i != files.size(); ++i) {
425                 string const file = support::os::internal_path(fromqstr(
426                         files.at(i).toLocalFile()));
427                 if (!file.empty())
428                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
429         }
430 }
431
432
433 void GuiView::saveGeometry()
434 {
435         static bool done = false;
436         if (done)
437                 return;
438         else
439                 done = true;
440
441         // FIXME:
442         // change the ifdef to 'geometry = normalGeometry();' only
443         // when Trolltech has fixed the broken normalGeometry on X11:
444         // http://www.trolltech.com/developer/task-tracker/index_html?id=119684+&method=entry
445         // Then also the moveEvent, resizeEvent, and the
446         // code for floatingGeometry_ can be removed;
447         // adjust GuiView::setGeometry()
448
449         QRect normal_geometry;
450         Maximized maximized;
451 #ifdef Q_WS_WIN
452         normal_geometry = normalGeometry();
453         if (isMaximized()) {
454                 maximized = CompletelyMaximized;
455         } else {
456                 maximized = NotMaximized;
457         }
458 #else
459         normal_geometry = updateFloatingGeometry();
460
461         QDesktopWidget& dw = *qApp->desktop();
462         QRect desk = dw.availableGeometry(dw.primaryScreen());
463         // Qt bug on Linux: load completely maximized, vert max. save-> frameGeometry().height() is wrong
464         if (isMaximized() && desk.width() <= frameGeometry().width() && desk.height() <= frameGeometry().height()) {
465                 maximized = CompletelyMaximized;
466                 // maximizing does not work when the window is allready hor. or vert. maximized
467                 // Tested only on KDE
468                 int dh = frameGeometry().height() - height();
469                 if (desk.height() <= normal_geometry.height() + dh)
470                         normal_geometry.setHeight(normal_geometry.height() - 1);
471                 int dw = frameGeometry().width() - width();
472                 if (desk.width() <= normal_geometry.width() + dw)
473                         normal_geometry.setWidth(normal_geometry.width() - 1);
474         } else if (desk.height() <= frameGeometry().height()) {
475                 maximized = VerticallyMaximized;
476         } else if (desk.width() <= frameGeometry().width()) {
477                 maximized = HorizontallyMaximized;
478         } else {
479                 maximized = NotMaximized;
480         }
481 #endif
482
483         // save windows size and position
484         SessionInfoSection & info = LyX::ref().session().sessionInfo();
485         info.save("WindowWidth", convert<string>(normal_geometry.width()));
486         info.save("WindowHeight", convert<string>(normal_geometry.height()));
487         info.save("WindowMaximized", convert<string>(int(maximized)));
488         info.save("IconSizeXY", convert<string>(iconSize().width()));
489         if (lyxrc.geometry_xysaved) {
490                 info.save("WindowPosX", convert<string>(normal_geometry.x() + d.posx_offset));
491                 info.save("WindowPosY", convert<string>(normal_geometry.y() + d.posy_offset));
492         }
493         d.toolbars_->saveToolbarInfo();
494 }
495
496
497 void GuiView::setGeometry(unsigned int width,
498                           unsigned int height,
499                           int posx, int posy,
500                           LyXView::Maximized maximized,
501                           unsigned int iconSizeXY,
502                           const string & geometryArg)
503 {
504         // use last value (not at startup)
505         if (d.lastIconSize != 0)
506                 setIconSize(d.lastIconSize);
507         else if (iconSizeXY != 0)
508                 setIconSize(iconSizeXY);
509         else
510                 setIconSize(d.normalIconSize);
511
512         // only true when the -geometry option was NOT used
513         if (width != 0 && height != 0) {
514                 if (posx != -1 && posy != -1) {
515                         // if there are startup positioning problems:
516                         // http://doc.trolltech.com/4.2/qdesktopwidget.html
517                         QDesktopWidget& dw = *qApp->desktop();
518                         if (dw.isVirtualDesktop()) {
519                                 if(!dw.geometry().contains(posx, posy)) {
520                                         posx = 50;
521                                         posy = 50;
522                                 }
523                         } else {
524                                 // Which system doesn't use a virtual desktop?
525                                 // TODO save also last screen number and check if it is still availabe.
526                         }
527 #ifdef Q_WS_WIN
528                         // FIXME: use setGeometry only when Trolltech has fixed the qt4/X11 bug
529                         QWidget::setGeometry(posx, posy, width, height);
530 #else
531                         resize(width, height);
532                         move(posx, posy);
533 #endif
534                 } else {
535                         resize(width, height);
536                 }
537
538                 // remember original size
539                 floatingGeometry_ = QRect(posx, posy, width, height);
540
541                 if (maximized != NotMaximized) {
542                         if (maximized == CompletelyMaximized) {
543                                 setWindowState(Qt::WindowMaximized);
544                         } else {
545 #ifndef Q_WS_WIN
546                                 // TODO How to set by the window manager?
547                                 //      setWindowState(Qt::WindowVerticallyMaximized);
548                                 //      is not possible
549                                 QDesktopWidget& dw = *qApp->desktop();
550                                 QRect desk = dw.availableGeometry(dw.primaryScreen());
551                                 if (maximized == VerticallyMaximized)
552                                         resize(width, desk.height());
553                                 if (maximized == HorizontallyMaximized)
554                                         resize(desk.width(), height);
555 #endif
556                         }
557                 }
558         }
559         else
560         {
561                 // FIXME: move this code into parse_geometry() (LyX.cpp)
562 #ifdef Q_WS_WIN
563                 int x, y;
564                 int w, h;
565                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
566                 re.indexIn(toqstr(geometryArg.c_str()));
567                 w = re.cap(1).toInt();
568                 h = re.cap(2).toInt();
569                 x = re.cap(3).toInt();
570                 y = re.cap(4).toInt();
571                 QWidget::setGeometry( x, y, w, h );
572 #else
573                 // silence warning
574                 (void)geometryArg;
575 #endif
576         }
577         
578         d.setBackground();
579         
580         show();
581
582         // after show geometry() has changed (Qt bug?)
583         // we compensate the drift when storing the position
584         d.posx_offset = 0;
585         d.posy_offset = 0;
586         if (width != 0 && height != 0)
587                 if (posx != -1 && posy != -1) {
588 #ifdef Q_WS_WIN
589                         d.posx_offset = posx - normalGeometry().x();
590                         d.posy_offset = posy - normalGeometry().y();
591 #else
592 #ifndef Q_WS_MACX
593                         if (maximized == NotMaximized) {
594                                 d.posx_offset = posx - geometry().x();
595                                 d.posy_offset = posy - geometry().y();
596                         }
597 #endif
598 #endif
599                 }
600 }
601
602
603 void GuiView::message(docstring const & str)
604 {
605         statusBar()->showMessage(toqstr(str));
606         statusbar_timer_.stop();
607         statusbar_timer_.start(statusbar_timer_value);
608 }
609
610
611 void GuiView::setIconSize(unsigned int size)
612 {
613         d.lastIconSize = size;
614         QMainWindow::setIconSize(QSize(size, size));
615 }
616
617
618 void GuiView::smallSizedIcons()
619 {
620         setIconSize(d.smallIconSize);
621 }
622
623
624 void GuiView::normalSizedIcons()
625 {
626         setIconSize(d.normalIconSize);
627 }
628
629
630 void GuiView::bigSizedIcons()
631 {
632         setIconSize(d.bigIconSize);
633 }
634
635
636 void GuiView::clearMessage()
637 {
638         if (!hasFocus())
639                 return;
640         theLyXFunc().setLyXView(this);
641         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
642         statusbar_timer_.stop();
643 }
644
645
646 void GuiView::updateWindowTitle(GuiWorkArea * wa)
647 {
648         if (wa != d.current_work_area_)
649                 return;
650         setWindowTitle(qt_("LyX: ") + wa->windowTitle());
651         setWindowIconText(wa->windowIconText());
652 }
653
654
655 void GuiView::on_currentWorkAreaChanged(GuiWorkArea * wa)
656 {
657         disconnectBuffer();
658         disconnectBufferView();
659         connectBufferView(wa->bufferView());
660         connectBuffer(wa->bufferView().buffer());
661         d.current_work_area_ = wa;
662         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
663                 this, SLOT(updateWindowTitle(GuiWorkArea *)));
664         updateWindowTitle(wa);
665
666         updateToc();
667         // Buffer-dependent dialogs should be updated or
668         // hidden. This should go here because some dialogs (eg ToC)
669         // require bv_->text.
670         dialogs_->updateBufferDependent(true);
671         updateToolbars();
672         updateLayoutChoice(false);
673         updateStatusBar();
674 }
675
676
677 void GuiView::updateStatusBar()
678 {
679         // let the user see the explicit message
680         if (statusbar_timer_.isActive())
681                 return;
682
683         statusBar()->showMessage(toqstr(theLyXFunc().viewStatusMessage()));
684 }
685
686
687 void GuiView::activated(FuncRequest const & func)
688 {
689         dispatch(func);
690 }
691
692
693 bool GuiView::hasFocus() const
694 {
695         return qApp->activeWindow() == this;
696 }
697
698
699 QRect  GuiView::updateFloatingGeometry()
700 {
701         QDesktopWidget& dw = *qApp->desktop();
702         QRect desk = dw.availableGeometry(dw.primaryScreen());
703         // remember only non-maximized sizes
704         if (!isMaximized() && desk.width() > frameGeometry().width() && desk.height() > frameGeometry().height()) {
705                 floatingGeometry_ = QRect(x(), y(), width(), height());
706         }
707         return floatingGeometry_;
708 }
709
710
711 void GuiView::resizeEvent(QResizeEvent *)
712 {
713         updateFloatingGeometry();
714 }
715
716
717 void GuiView::moveEvent(QMoveEvent *)
718 {
719         updateFloatingGeometry();
720 }
721
722
723 bool GuiView::event(QEvent * e)
724 {
725         switch (e->type())
726         {
727         // Useful debug code:
728         //case QEvent::ActivationChange:
729         //case QEvent::WindowDeactivate:
730         //case QEvent::Paint:
731         //case QEvent::Enter:
732         //case QEvent::Leave:
733         //case QEvent::HoverEnter:
734         //case QEvent::HoverLeave:
735         //case QEvent::HoverMove:
736         //case QEvent::StatusTip:
737         //case QEvent::DragEnter:
738         //case QEvent::DragLeave:
739         //case QEvent::Drop:
740         //      break;
741
742         case QEvent::WindowActivate: {
743                 theApp()->setCurrentView(*this);
744                 if (d.current_work_area_) {
745                         BufferView & bv = d.current_work_area_->bufferView();
746                         connectBufferView(bv);
747                         connectBuffer(bv.buffer());
748                         // The document structure, name and dialogs might have
749                         // changed in another view.
750                         dialogs_->updateBufferDependent(true);
751                 } else {
752                         setWindowTitle(qt_("LyX"));
753                         setWindowIconText(qt_("LyX"));
754                 }
755                 return QMainWindow::event(e);
756         }
757         case QEvent::ShortcutOverride: {
758                 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
759                 if (!d.current_work_area_) {
760                         theLyXFunc().setLyXView(this);
761                         KeySymbol sym;
762                         setKeySymbol(&sym, ke);
763                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
764                         e->accept();
765                         return true;
766                 }
767                 if (ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab) {
768                         KeySymbol sym;
769                         setKeySymbol(&sym, ke);
770                         d.current_work_area_->processKeySym(sym, NoModifier);
771                         e->accept();
772                         return true;
773                 }
774         }
775         default:
776                 return QMainWindow::event(e);
777         }
778 }
779
780
781 bool GuiView::focusNextPrevChild(bool /*next*/)
782 {
783         setFocus();
784         return true;
785 }
786
787
788 void GuiView::showView()
789 {
790         setWindowTitle(qt_("LyX"));
791         show();
792         updateFloatingGeometry();
793 }
794
795
796 void GuiView::setBusy(bool yes)
797 {
798         if (d.current_work_area_) {
799                 d.current_work_area_->setUpdatesEnabled(!yes);
800                 if (yes)
801                         d.current_work_area_->stopBlinkingCursor();
802                 else
803                         d.current_work_area_->startBlinkingCursor();
804         }
805
806         if (yes)
807                 QApplication::setOverrideCursor(Qt::WaitCursor);
808         else
809                 QApplication::restoreOverrideCursor();
810 }
811
812
813 GuiToolbar * GuiView::makeToolbar(ToolbarInfo const & tbinfo, bool newline)
814 {
815         GuiToolbar * toolBar = new GuiToolbar(tbinfo, *this);
816
817         if (tbinfo.flags & ToolbarInfo::TOP) {
818                 if (newline)
819                         addToolBarBreak(Qt::TopToolBarArea);
820                 addToolBar(Qt::TopToolBarArea, toolBar);
821         }
822
823         if (tbinfo.flags & ToolbarInfo::BOTTOM) {
824 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
825 #if (QT_VERSION >= 0x040202)
826                 if (newline)
827                         addToolBarBreak(Qt::BottomToolBarArea);
828 #endif
829                 addToolBar(Qt::BottomToolBarArea, toolBar);
830         }
831
832         if (tbinfo.flags & ToolbarInfo::LEFT) {
833 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
834 #if (QT_VERSION >= 0x040202)
835                 if (newline)
836                         addToolBarBreak(Qt::LeftToolBarArea);
837 #endif
838                 addToolBar(Qt::LeftToolBarArea, toolBar);
839         }
840
841         if (tbinfo.flags & ToolbarInfo::RIGHT) {
842 // Qt < 4.2.2 cannot handle ToolBarBreak on non-TOP dock.
843 #if (QT_VERSION >= 0x040202)
844                 if (newline)
845                         addToolBarBreak(Qt::RightToolBarArea);
846 #endif
847                 addToolBar(Qt::RightToolBarArea, toolBar);
848         }
849
850         // The following does not work so I cannot restore to exact toolbar location
851         /*
852         ToolbarSection::ToolbarInfo & tbinfo = LyX::ref().session().toolbars().load(tbinfo.name);
853         toolBar->move(tbinfo.posx, tbinfo.posy);
854         */
855
856         return toolBar;
857 }
858
859
860 GuiWorkArea * GuiView::workArea(Buffer & buffer)
861 {
862         for (int i = 0; i != d.splitter_->count(); ++i) {
863                 GuiWorkArea * wa = d.tabWorkArea(i)->workArea(buffer);
864                 if (wa)
865                         return wa;
866         }
867         return 0;
868 }
869
870
871 GuiWorkArea * GuiView::addWorkArea(Buffer & buffer)
872 {
873         GuiWorkArea * wa = new GuiWorkArea(buffer, *this);
874         wa->setUpdatesEnabled(false);
875
876         // Automatically create a TabWorkArea if there are none yet.
877         if (!d.splitter_->count())
878                 addTabWorkArea();
879
880         TabWorkArea * tab_widget = d.currentTabWorkArea();
881         tab_widget->addTab(wa, wa->windowTitle());
882         QObject::connect(wa, SIGNAL(titleChanged(GuiWorkArea *)),
883                 tab_widget, SLOT(updateTabText(GuiWorkArea *)));
884
885         wa->bufferView().updateMetrics();
886
887         // Hide tabbar if there's only one tab.
888         tab_widget->showBar(tab_widget->count() > 1);
889         return wa;
890 }
891
892
893 void GuiView::addTabWorkArea()
894 {
895         TabWorkArea * twa = new TabWorkArea;
896         QObject::connect(twa, SIGNAL(currentWorkAreaChanged(GuiWorkArea *)),
897                 this, SLOT(on_currentWorkAreaChanged(GuiWorkArea *)));
898         d.splitter_->addWidget(twa);
899         d.stack_widget_->setCurrentWidget(d.splitter_);
900 }
901
902
903 GuiWorkArea * GuiView::currentWorkArea()
904 {
905         return d.current_work_area_;
906 }
907
908
909 GuiWorkArea const * GuiView::currentWorkArea() const
910 {
911         return d.current_work_area_;
912 }
913
914
915 void GuiView::setCurrentWorkArea(GuiWorkArea * work_area)
916 {
917         BOOST_ASSERT(work_area);
918
919         // Changing work area can result from opening a file so
920         // update the toc in any case.
921         updateToc();
922
923         GuiWorkArea * wa = static_cast<GuiWorkArea *>(work_area);
924         d.current_work_area_ = wa;
925         for (int i = 0; i != d.splitter_->count(); ++i) {
926                 if (d.tabWorkArea(i)->setCurrentWorkArea(wa))
927                         return;
928         }
929 }
930
931
932 void GuiView::removeWorkArea(GuiWorkArea * work_area)
933 {
934         BOOST_ASSERT(work_area);
935         GuiWorkArea * gwa = static_cast<GuiWorkArea *>(work_area);
936         if (gwa == d.current_work_area_) {
937                 disconnectBuffer();
938                 disconnectBufferView();
939                 dialogs_->hideBufferDependent();
940                 d.current_work_area_ = 0;
941         }
942
943         // removing a work area often results from closing a file so
944         // update the toc in any case.
945         updateToc();
946
947         for (int i = 0; i != d.splitter_->count(); ++i) {
948                 TabWorkArea * twa = d.tabWorkArea(i);
949                 if (!twa->removeWorkArea(gwa))
950                         // Not found in this tab group.
951                         continue;
952
953                 // We found and removed the GuiWorkArea.
954                 if (!twa->count()) {
955                         // No more WorkAreas in this tab group, so delete it.
956                         delete twa;
957                         break;
958                 }
959
960                 if (d.current_work_area_)
961                         // This means that we are not closing the current GuiWorkArea;
962                         break;
963
964                 // Switch to the next GuiWorkArea in the found TabWorkArea.
965                 d.current_work_area_ = twa->currentWorkArea();
966                 break;
967         }
968
969         if (d.splitter_->count() == 0)
970                 // No more work area, switch to the background widget.
971                 d.setBackground();
972 }
973
974
975 void GuiView::showMiniBuffer(bool visible)
976 {
977         d.toolbars_->showCommandBuffer(visible);
978 }
979
980
981 void GuiView::openMenu(docstring const & name)
982 {
983         d.menubar_->openByName(toqstr(name));
984 }
985
986
987 void GuiView::openLayoutList()
988 {
989         d.toolbars_->openLayoutList();
990 }
991
992
993 void GuiView::updateLayoutChoice(bool force)
994 {
995         // Don't show any layouts without a buffer
996         if (!buffer()) {
997                 d.toolbars_->clearLayoutList();
998                 return;
999         }
1000
1001         // Update the layout display
1002         if (d.toolbars_->updateLayoutList(buffer()->params().getTextClassPtr(), force)) {
1003                 d.current_layout = buffer()->params().getTextClass().defaultLayoutName();
1004         }
1005
1006         docstring const & layout = d.current_work_area_->bufferView().cursor().
1007                 innerParagraph().layout()->name();
1008
1009         if (layout != d.current_layout) {
1010                 d.toolbars_->setLayout(layout);
1011                 d.current_layout = layout;
1012         }
1013 }
1014
1015
1016 bool GuiView::isToolbarVisible(std::string const & id)
1017 {
1018         return d.toolbars_->visible(id);
1019 }
1020
1021 void GuiView::updateToolbars()
1022 {
1023         if (d.current_work_area_) {
1024                 bool const math =
1025                         d.current_work_area_->bufferView().cursor().inMathed();
1026                 bool const table =
1027                         lyx::getStatus(FuncRequest(LFUN_LAYOUT_TABULAR)).enabled();
1028                 bool const review =
1029                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).enabled() &&
1030                         lyx::getStatus(FuncRequest(LFUN_CHANGES_TRACK)).onoff(true);
1031
1032                 d.toolbars_->update(math, table, review);
1033         } else
1034                 d.toolbars_->update(false, false, false);
1035
1036         // update read-only status of open dialogs.
1037         dialogs_->checkStatus();
1038 }
1039
1040
1041 ToolbarInfo * GuiView::getToolbarInfo(string const & name)
1042 {
1043         return d.toolbars_->getToolbarInfo(name);
1044 }
1045
1046
1047 void GuiView::toggleToolbarState(string const & name, bool allowauto)
1048 {
1049         // it is possible to get current toolbar status like this,...
1050         // but I decide to obey the order of ToolbarBackend::flags
1051         // and disregard real toolbar status.
1052         // toolbars_->saveToolbarInfo();
1053         //
1054         // toggle state on/off/auto
1055         d.toolbars_->toggleToolbarState(name, allowauto);
1056         // update toolbar
1057         updateToolbars();
1058 }
1059
1060
1061 Buffer * GuiView::buffer()
1062 {
1063         if (d.current_work_area_)
1064                 return &d.current_work_area_->bufferView().buffer();
1065         return 0;
1066 }
1067
1068
1069 Buffer const * GuiView::buffer() const
1070 {
1071         if (d.current_work_area_)
1072                 return &d.current_work_area_->bufferView().buffer();
1073         return 0;
1074 }
1075
1076
1077 void GuiView::setBuffer(Buffer * newBuffer)
1078 {
1079         BOOST_ASSERT(newBuffer);
1080         setBusy(true);
1081
1082         GuiWorkArea * wa = workArea(*newBuffer);
1083         if (wa == 0) {
1084                 updateLabels(*newBuffer->masterBuffer());
1085                 wa = addWorkArea(*newBuffer);
1086         } else {
1087                 //Disconnect the old buffer...there's no new one.
1088                 disconnectBuffer();
1089         }
1090         connectBuffer(*newBuffer);
1091         connectBufferView(wa->bufferView());
1092         setCurrentWorkArea(wa);
1093
1094         setBusy(false);
1095 }
1096
1097
1098 Buffer * GuiView::loadLyXFile(FileName const & filename, bool tolastfiles)
1099 {
1100         setBusy(true);
1101
1102         Buffer * newBuffer = checkAndLoadLyXFile(filename);
1103
1104         if (!newBuffer) {
1105                 message(_("Document not loaded."));
1106                 updateStatusBar();
1107                 setBusy(false);
1108                 return 0;
1109         }
1110
1111         GuiWorkArea * wa = workArea(*newBuffer);
1112         if (wa == 0)
1113                 wa = addWorkArea(*newBuffer);
1114
1115         // scroll to the position when the file was last closed
1116         if (lyxrc.use_lastfilepos) {
1117                 LastFilePosSection::FilePos filepos =
1118                         LyX::ref().session().lastFilePos().load(filename);
1119                 // if successfully move to pit (returned par_id is not zero),
1120                 // update metrics and reset font
1121                 wa->bufferView().moveToPosition(filepos.pit, filepos.pos, 0, 0);
1122         }
1123
1124         if (tolastfiles)
1125                 LyX::ref().session().lastFiles().add(filename);
1126
1127         setBusy(false);
1128         return newBuffer;
1129 }
1130
1131
1132 void GuiView::connectBuffer(Buffer & buf)
1133 {
1134         buf.setGuiDelegate(this);
1135 }
1136
1137
1138 void GuiView::disconnectBuffer()
1139 {
1140         if (d.current_work_area_)
1141                 d.current_work_area_->bufferView().setGuiDelegate(0);
1142 }
1143
1144
1145 void GuiView::connectBufferView(BufferView & bv)
1146 {
1147         bv.setGuiDelegate(this);
1148 }
1149
1150
1151 void GuiView::disconnectBufferView()
1152 {
1153         if (d.current_work_area_)
1154                 d.current_work_area_->bufferView().setGuiDelegate(0);
1155 }
1156
1157
1158 void GuiView::errors(string const & error_type)
1159 {
1160         ErrorList & el = buffer()->errorList(error_type);
1161         if (!el.empty())
1162                 dialogs_->show("errorlist", error_type);
1163 }
1164
1165
1166 void GuiView::showDialog(string const & name)
1167 {
1168         dialogs_->show(name);
1169 }
1170
1171
1172 void GuiView::showDialogWithData(string const & name, string const & data)
1173 {
1174         dialogs_->show(name, data);
1175 }
1176
1177
1178 void GuiView::showInsetDialog(string const & name, string const & data,
1179                 Inset * inset)
1180 {
1181         dialogs_->show(name, data, inset);
1182 }
1183
1184
1185 void GuiView::updateDialog(string const & name, string const & data)
1186 {
1187         if (dialogs_->visible(name))
1188                 dialogs_->update(name, data);
1189 }
1190
1191
1192 BufferView * GuiView::view()
1193 {
1194         return d.current_work_area_ ? &d.current_work_area_->bufferView() : 0;
1195 }
1196
1197
1198 void GuiView::updateToc()
1199 {
1200         updateDialog("toc", "");
1201 }
1202
1203
1204 void GuiView::updateEmbeddedFiles()
1205 {
1206         updateDialog("embedding", "");
1207 }
1208
1209
1210 void GuiView::autoSave()
1211 {
1212         LYXERR(Debug::INFO) << "Running autoSave()" << endl;
1213
1214         if (buffer())
1215                 view()->buffer().autoSave();
1216 }
1217
1218
1219 void GuiView::resetAutosaveTimers()
1220 {
1221         if (lyxrc.autosave)
1222                 autosave_timeout_->restart();
1223 }
1224
1225
1226 void GuiView::dispatch(FuncRequest const & cmd)
1227 {
1228         string const argument = to_utf8(cmd.argument());
1229         switch(cmd.action) {
1230                 case LFUN_BUFFER_SWITCH:
1231                         setBuffer(theBufferList().getBuffer(to_utf8(cmd.argument())));
1232                         break;
1233                 default:
1234                         theLyXFunc().setLyXView(this);
1235                         lyx::dispatch(cmd);
1236         }
1237 }
1238
1239
1240 Buffer const * GuiView::updateInset(Inset const * inset)
1241 {
1242         if (!d.current_work_area_)
1243                 return 0;
1244
1245         if (inset)
1246                 d.current_work_area_->scheduleRedraw();
1247
1248         return &d.current_work_area_->bufferView().buffer();
1249 }
1250
1251
1252 void GuiView::restartCursor()
1253 {
1254         /* When we move around, or type, it's nice to be able to see
1255          * the cursor immediately after the keypress.
1256          */
1257         if (d.current_work_area_)
1258                 d.current_work_area_->startBlinkingCursor();
1259 }
1260
1261 } // namespace frontend
1262 } // namespace lyx
1263
1264 #include "GuiView_moc.cpp"