]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.cpp
Move private part of BufferView to a private implementation.
[lyx.git] / src / frontends / qt4 / GuiWorkArea.cpp
1 /**
2  * \file GuiWorkArea.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  * \author Abdelrazak Younes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "GuiWorkArea.h"
15
16 #include "GuiApplication.h"
17 #include "GuiPainter.h"
18 #include "GuiKeySymbol.h"
19 #include "qt_helpers.h"
20
21 #include "frontends/LyXView.h"
22
23 #include "Buffer.h"
24 #include "BufferView.h"
25 #include "Color.h"
26 #include "Cursor.h"
27 #include "debug.h"
28 #include "FuncRequest.h"
29 #include "LyXFunc.h"
30 #include "LyXRC.h"
31 #include "version.h"
32
33 #include "support/filetools.h" // LibFileSearch
34
35 #include "graphics/GraphicsImage.h"
36 #include "graphics/GraphicsLoader.h"
37
38 #include <QInputContext>
39 #include <QLayout>
40 #include <QMainWindow>
41 #include <QPainter>
42 #include <QPushButton>
43 #include <QScrollBar>
44 #include <QTabBar>
45 #include <QTimer>
46
47 #include <boost/bind.hpp>
48 #include <boost/current_function.hpp>
49
50 #ifdef Q_WS_X11
51 #include <QX11Info>
52 extern "C" int XEventsQueued(Display *display, int mode);
53 #endif
54
55 #ifdef Q_WS_WIN
56 int const CursorWidth = 2;
57 #else
58 int const CursorWidth = 1;
59 #endif
60
61 #undef KeyPress
62 #undef NoModifier 
63
64 using std::endl;
65 using std::string;
66
67 namespace lyx {
68
69 using support::FileName;
70
71 /// return the LyX mouse button state from Qt's
72 static mouse_button::state q_button_state(Qt::MouseButton button)
73 {
74         mouse_button::state b = mouse_button::none;
75         switch (button) {
76                 case Qt::LeftButton:
77                         b = mouse_button::button1;
78                         break;
79                 case Qt::MidButton:
80                         b = mouse_button::button2;
81                         break;
82                 case Qt::RightButton:
83                         b = mouse_button::button3;
84                         break;
85                 default:
86                         break;
87         }
88         return b;
89 }
90
91
92 /// return the LyX mouse button state from Qt's
93 mouse_button::state q_motion_state(Qt::MouseButtons state)
94 {
95         mouse_button::state b = mouse_button::none;
96         if (state & Qt::LeftButton)
97                 b |= mouse_button::button1;
98         if (state & Qt::MidButton)
99                 b |= mouse_button::button2;
100         if (state & Qt::RightButton)
101                 b |= mouse_button::button3;
102         return b;
103 }
104
105
106 namespace frontend {
107
108 class CursorWidget {
109 public:
110         CursorWidget() {}
111
112         void draw(QPainter & painter)
113         {
114                 if (show_ && rect_.isValid()) {
115                         switch (shape_) {
116                         case L_SHAPE:
117                                 painter.fillRect(rect_.x(), rect_.y(), CursorWidth, rect_.height(), color_);
118                                 painter.setPen(color_);
119                                 painter.drawLine(rect_.bottomLeft().x() + CursorWidth, rect_.bottomLeft().y(),
120                                                                                                  rect_.bottomRight().x(), rect_.bottomLeft().y());
121                                 break;
122                         
123                         case REVERSED_L_SHAPE:
124                                 painter.fillRect(rect_.x() + rect_.height() / 3, rect_.y(), CursorWidth, rect_.height(), color_);
125                                 painter.setPen(color_);
126                                 painter.drawLine(rect_.bottomRight().x() - CursorWidth, rect_.bottomLeft().y(),
127                                                                                                          rect_.bottomLeft().x(), rect_.bottomLeft().y());
128                                 break;
129                                         
130                         default:
131                                 painter.fillRect(rect_, color_);
132                                 break;
133                         }
134                 }
135         }
136
137         void update(int x, int y, int h, CursorShape shape)
138         {
139                 color_ = guiApp->colorCache().get(Color::cursor);
140                 shape_ = shape;
141                 switch (shape) {
142                 case L_SHAPE:
143                         rect_ = QRect(x, y, CursorWidth + h / 3, h);
144                         break;
145                 case REVERSED_L_SHAPE:
146                         rect_ = QRect(x - h / 3, y, CursorWidth + h / 3, h);
147                         break;
148                 default: 
149                         rect_ = QRect(x, y, CursorWidth, h);
150                         break;
151                 }
152         }
153
154         void show(bool set_show = true) { show_ = set_show; }
155         void hide() { show_ = false; }
156
157         QRect const & rect() { return rect_; }
158
159 private:
160         ///
161         CursorShape shape_;
162         ///
163         bool show_;
164         ///
165         QColor color_;
166         ///
167         QRect rect_;
168 };
169
170
171 // This is a 'heartbeat' generating synthetic mouse move events when the
172 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
173 SyntheticMouseEvent::SyntheticMouseEvent()
174         : timeout(200), restart_timeout(true),
175           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
176 {}
177
178
179 GuiWorkArea::GuiWorkArea(Buffer & buf, LyXView & lv)
180         : WorkArea(buf, lv), need_resize_(false), schedule_redraw_(false),
181           preedit_lines_(1)
182 {
183         screen_ = QPixmap(viewport()->width(), viewport()->height());
184         cursor_ = new frontend::CursorWidget();
185         cursor_->hide();
186
187         setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
188         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
189         setAcceptDrops(true);
190         setMouseTracking(true);
191         setMinimumSize(100, 70);
192
193         viewport()->setAutoFillBackground(false);
194         // We don't need double-buffering nor SystemBackground on
195         // the viewport because we have our own backing pixmap.
196         viewport()->setAttribute(Qt::WA_NoSystemBackground);
197
198         setFocusPolicy(Qt::WheelFocus);
199
200         viewport()->setCursor(Qt::IBeamCursor);
201
202         synthetic_mouse_event_.timeout.timeout.connect(
203                 boost::bind(&GuiWorkArea::generateSyntheticMouseEvent,
204                             this));
205
206         // Initialize the vertical Scroll Bar
207         QObject::connect(verticalScrollBar(), SIGNAL(actionTriggered(int)),
208                 this, SLOT(adjustViewWithScrollBar(int)));
209
210         // disable context menu for the scrollbar
211         verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
212
213         // PageStep only depends on the viewport height.
214         verticalScrollBar()->setPageStep(viewport()->height());
215
216         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
217                 << "\n Area width\t" << width()
218                 << "\n Area height\t" << height()
219                 << "\n viewport width\t" << viewport()->width()
220                 << "\n viewport height\t" << viewport()->height()
221                 << endl;
222
223         // Enables input methods for asian languages.
224         // Must be set when creating custom text editing widgets.
225         setAttribute(Qt::WA_InputMethodEnabled, true);
226 }
227
228
229 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
230 {
231         if (verticalScrollBarPolicy() != Qt::ScrollBarAlwaysOn)
232                 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
233
234         verticalScrollBar()->setTracking(false);
235
236         // do what cursor movement does (some grey)
237         h += height() / 4;
238         int scroll_max_ = std::max(0, h - height());
239
240         verticalScrollBar()->setRange(0, scroll_max_);
241         verticalScrollBar()->setSliderPosition(scroll_pos);
242         verticalScrollBar()->setSingleStep(scroll_line_step);
243         verticalScrollBar()->setValue(scroll_pos);
244
245         verticalScrollBar()->setTracking(true);
246 }
247
248
249 void GuiWorkArea::adjustViewWithScrollBar(int action)
250 {
251         stopBlinkingCursor();
252         if (action == QAbstractSlider::SliderPageStepAdd)
253                 buffer_view_->scrollDown(viewport()->height());
254         else if (action == QAbstractSlider::SliderPageStepSub)
255                 buffer_view_->scrollUp(viewport()->height());
256         else
257                 buffer_view_->scrollDocView(verticalScrollBar()->sliderPosition());
258
259         if (lyxrc.cursor_follows_scrollbar) {
260                 buffer_view_->setCursorFromScrollbar();
261                 lyx_view_->updateLayoutChoice();
262         }
263         // Show the cursor immediately after any operation.
264         startBlinkingCursor();
265         QApplication::syncX();
266 }
267
268
269 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
270 {
271         // Repaint the whole screen.
272         // Note: this is different from redraw() as only the backing pixmap
273         // will be redrawn, which is cheap.
274         viewport()->repaint();
275
276         startBlinkingCursor();
277 }
278
279
280 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
281 {
282         stopBlinkingCursor();
283 }
284
285
286 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
287 {
288         if (dc_event_.active && dc_event_ == *e) {
289                 dc_event_.active = false;
290                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
291                         e->x(), e->y(),
292                         q_button_state(e->button()));
293                 dispatch(cmd);
294                 return;
295         }
296
297         inputContext()->reset();
298
299         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
300                 q_button_state(e->button()));
301         dispatch(cmd, q_key_state(e->modifiers()));
302 }
303
304
305 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
306 {
307         if (synthetic_mouse_event_.timeout.running())
308                 synthetic_mouse_event_.timeout.stop();
309
310         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
311                               q_button_state(e->button()));
312         dispatch(cmd);
313 }
314
315
316 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
317 {
318         // we kill the triple click if we move
319         doubleClickTimeout();
320         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
321                               q_motion_state(e->buttons()));
322
323         // If we're above or below the work area...
324         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
325                 // Make sure only a synthetic event can cause a page scroll,
326                 // so they come at a steady rate:
327                 if (e->y() <= 20)
328                         // _Force_ a scroll up:
329                         cmd.y = -40;
330                 else
331                         cmd.y = viewport()->height();
332                 // Store the event, to be handled when the timeout expires.
333                 synthetic_mouse_event_.cmd = cmd;
334
335                 if (synthetic_mouse_event_.timeout.running())
336                         // Discard the event. Note that it _may_ be handled
337                         // when the timeout expires if
338                         // synthetic_mouse_event_.cmd has not been overwritten.
339                         // Ie, when the timeout expires, we handle the
340                         // most recent event but discard all others that
341                         // occurred after the one used to start the timeout
342                         // in the first place.
343                         return;
344                 else {
345                         synthetic_mouse_event_.restart_timeout = true;
346                         synthetic_mouse_event_.timeout.start();
347                         // Fall through to handle this event...
348                 }
349
350         } else if (synthetic_mouse_event_.timeout.running()) {
351                 // Store the event, to be possibly handled when the timeout
352                 // expires.
353                 // Once the timeout has expired, normal control is returned
354                 // to mouseMoveEvent (restart_timeout = false).
355                 // This results in a much smoother 'feel' when moving the
356                 // mouse back into the work area.
357                 synthetic_mouse_event_.cmd = cmd;
358                 synthetic_mouse_event_.restart_timeout = false;
359                 return;
360         }
361
362         // Has anything changed on-screen since the last QMouseEvent
363         // was received?
364         double const scrollbar_value = verticalScrollBar()->value();
365         if (e->x() != synthetic_mouse_event_.x_old ||
366             e->y() != synthetic_mouse_event_.y_old ||
367             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
368                 // Yes it has. Store the params used to check this.
369                 synthetic_mouse_event_.x_old = e->x();
370                 synthetic_mouse_event_.y_old = e->y();
371                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
372
373                 // ... and dispatch the event to the LyX core.
374                 dispatch(cmd);
375         }
376 }
377
378
379 void GuiWorkArea::wheelEvent(QWheelEvent * e)
380 {
381         // Wheel rotation by one notch results in a delta() of 120 (see
382         // documentation of QWheelEvent)
383         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
384         verticalScrollBar()->setValue(verticalScrollBar()->value() -
385                         lines *  verticalScrollBar()->singleStep());
386         adjustViewWithScrollBar();
387 }
388
389
390 void GuiWorkArea::generateSyntheticMouseEvent()
391 {
392 // Set things off to generate the _next_ 'pseudo' event.
393         if (synthetic_mouse_event_.restart_timeout)
394                 synthetic_mouse_event_.timeout.start();
395
396         // Has anything changed on-screen since the last timeout signal
397         // was received?
398         double const scrollbar_value = verticalScrollBar()->value();
399         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
400                 // Yes it has. Store the params used to check this.
401                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
402
403                 // ... and dispatch the event to the LyX core.
404                 dispatch(synthetic_mouse_event_.cmd);
405         }
406 }
407
408
409 void GuiWorkArea::keyPressEvent(QKeyEvent * ev)
410 {
411         // do nothing if there are other events
412         // (the auto repeated events come too fast)
413         // \todo FIXME: remove hard coded Qt keys, process the key binding
414 #ifdef Q_WS_X11
415         if (XEventsQueued(QX11Info::display(), 0) > 1 && ev->isAutoRepeat() 
416                         && (Qt::Key_PageDown || Qt::Key_PageUp)) {
417                 LYXERR(Debug::KEY)      
418                         << BOOST_CURRENT_FUNCTION << endl
419                         << "system is busy: scroll key event ignored" << endl;
420                 ev->ignore();
421                 return;
422         }
423 #endif
424
425         LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
426                 << " count=" << ev->count()
427                 << " text=" << fromqstr(ev->text())
428                 << " isAutoRepeat=" << ev->isAutoRepeat()
429                 << " key=" << ev->key()
430                 << endl;
431
432         KeySymbol sym;
433         setKeySymbol(&sym, ev);
434         processKeySym(sym, q_key_state(ev->modifiers()));
435 }
436
437
438 void GuiWorkArea::doubleClickTimeout()
439 {
440         dc_event_.active = false;
441 }
442
443
444 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * ev)
445 {
446         dc_event_ = double_click(ev);
447         QTimer::singleShot(QApplication::doubleClickInterval(), this,
448                            SLOT(doubleClickTimeout()));
449         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
450                         ev->x(), ev->y(),
451                         q_button_state(ev->button()));
452         dispatch(cmd);
453 }
454
455
456 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
457 {
458         QAbstractScrollArea::resizeEvent(ev);
459         need_resize_ = true;
460 }
461
462
463 void GuiWorkArea::update(int x, int y, int w, int h)
464 {
465         viewport()->repaint(x, y, w, h);
466 }
467
468
469 void GuiWorkArea::paintEvent(QPaintEvent * ev)
470 {
471         QRect const rc = ev->rect();
472         /*
473         LYXERR(Debug::PAINTING) << "paintEvent begin: x: " << rc.x()
474                 << " y: " << rc.y()
475                 << " w: " << rc.width()
476                 << " h: " << rc.height() << endl;
477         */
478
479         if (need_resize_) {
480                 verticalScrollBar()->setPageStep(viewport()->height());
481                 screen_ = QPixmap(viewport()->width(), viewport()->height());
482                 resizeBufferView();
483                 updateScreen();
484                 WorkArea::hideCursor();
485                 WorkArea::showCursor();
486                 need_resize_ = false;
487         }
488
489         QPainter pain(viewport());
490         pain.drawPixmap(rc, screen_, rc);
491         cursor_->draw(pain);
492 }
493
494
495 void GuiWorkArea::expose(int x, int y, int w, int h)
496 {
497         updateScreen();
498         update(x, y, w, h);
499 }
500
501
502 void GuiWorkArea::updateScreen()
503 {
504         GuiPainter pain(&screen_);
505         verticalScrollBar()->show();
506         buffer_view_->draw(pain);
507 }
508
509
510 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
511 {
512         if (schedule_redraw_) {
513                 buffer_view_->updateMetrics(false);
514                 updateScreen();
515                 viewport()->update(QRect(0, 0, viewport()->width(), viewport()->height()));
516                 schedule_redraw_ = false;
517                 // Show the cursor immediately after the update.
518                 hideCursor();
519                 toggleCursor();
520                 return;
521         }
522
523         cursor_->update(x, y, h, shape);
524         cursor_->show();
525         viewport()->update(cursor_->rect());
526 }
527
528
529 void GuiWorkArea::removeCursor()
530 {
531         cursor_->hide();
532         //if (!qApp->focusWidget())
533                 viewport()->update(cursor_->rect());
534 }
535
536
537 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
538 {
539         QString const & commit_string = e->commitString();
540         docstring const & preedit_string
541                 = qstring_to_ucs4(e->preeditString());
542
543         if (!commit_string.isEmpty()) {
544
545                 LYXERR(Debug::KEY) << BOOST_CURRENT_FUNCTION
546                         << " preeditString =" << fromqstr(e->preeditString())
547                         << " commitString  =" << fromqstr(e->commitString())
548                         << endl;
549
550                 int key = 0;
551
552                 // FIXME Iwami 04/01/07: we should take care also of UTF16 surrogates here.
553                 for (int i = 0; i < commit_string.size(); ++i) {
554                         QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, commit_string[i]);
555                         keyPressEvent(&ev);
556                 }
557         }
558
559         // Hide the cursor during the kana-kanji transformation.
560         if (preedit_string.empty())
561                 startBlinkingCursor();
562         else
563                 stopBlinkingCursor();
564
565         // last_width : for checking if last preedit string was/wasn't empty.
566         static bool last_width = false;
567         if (!last_width && preedit_string.empty()) {
568                 // if last_width is last length of preedit string.
569                 e->accept();
570                 return;
571         }
572
573         GuiPainter pain(&screen_);
574         buffer_view_->updateMetrics(false);
575         buffer_view_->draw(pain);
576         Font font = buffer_view_->cursor().getFont();
577         FontMetrics const & fm = theFontMetrics(font);
578         int height = fm.maxHeight();
579         int cur_x = cursor_->rect().left();
580         int cur_y = cursor_->rect().bottom();
581
582         // redraw area of preedit string.
583         update(0, cur_y - height, GuiWorkArea::width(),
584                 (height + 1) * preedit_lines_);
585
586         if (preedit_string.empty()) {
587                 last_width = false;
588                 preedit_lines_ = 1;
589                 e->accept();
590                 return;
591         }
592         last_width = true;
593
594         // att : stores an IM attribute.
595         QList<QInputMethodEvent::Attribute> const & att = e->attributes();
596
597         // get attributes of input method cursor.
598         // cursor_pos : cursor position in preedit string.
599         size_t cursor_pos = 0;
600         bool cursor_is_visible = false;
601         for (int i = 0; i < att.size(); ++i) {
602                 if (att.at(i).type == QInputMethodEvent::Cursor) {
603                         cursor_pos = att.at(i).start;
604                         cursor_is_visible = att.at(i).length != 0;
605                         break;
606                 }
607         }
608
609         size_t preedit_length = preedit_string.length();
610
611         // get position of selection in input method.
612         // FIXME: isn't there a way to do this simplier?
613         // rStart : cursor position in selected string in IM.
614         size_t rStart = 0;
615         // rLength : selected string length in IM.
616         size_t rLength = 0;
617         if (cursor_pos < preedit_length) {
618                 for (int i = 0; i < att.size(); ++i) {
619                         if (att.at(i).type == QInputMethodEvent::TextFormat) {
620                                 if (att.at(i).start <= int(cursor_pos)
621                                         && int(cursor_pos) < att.at(i).start + att.at(i).length) {
622                                                 rStart = att.at(i).start;
623                                                 rLength = att.at(i).length;
624                                                 if (!cursor_is_visible)
625                                                         cursor_pos += rLength;
626                                                 break;
627                                 }
628                         }
629                 }
630         }
631         else {
632                 rStart = cursor_pos;
633                 rLength = 0;
634         }
635
636         int const right_margin = rightMargin();
637         Painter::preedit_style ps;
638         // Most often there would be only one line:
639         preedit_lines_ = 1;
640         for (size_t pos = 0; pos != preedit_length; ++pos) {
641                 char_type const typed_char = preedit_string[pos];
642                 // reset preedit string style
643                 ps = Painter::preedit_default;
644
645                 // if we reached the right extremity of the screen, go to next line.
646                 if (cur_x + fm.width(typed_char) > GuiWorkArea::width() - right_margin) {
647                         cur_x = right_margin;
648                         cur_y += height + 1;
649                         ++preedit_lines_;
650                 }
651                 // preedit strings are displayed with dashed underline
652                 // and partial strings are displayed white on black indicating
653                 // that we are in selecting mode in the input method.
654                 // FIXME: rLength == preedit_length is not a changing condition
655                 // FIXME: should be put out of the loop.
656                 if (pos >= rStart
657                         && pos < rStart + rLength
658                         && !(cursor_pos < rLength && rLength == preedit_length))
659                         ps = Painter::preedit_selecting;
660
661                 if (pos == cursor_pos
662                         && (cursor_pos < rLength && rLength == preedit_length))
663                         ps = Painter::preedit_cursor;
664
665                 // draw one character and update cur_x.
666                 cur_x += pain.preeditText(cur_x, cur_y, typed_char, font, ps);
667         }
668
669         // update the preedit string screen area.
670         update(0, cur_y - preedit_lines_*height, GuiWorkArea::width(),
671                 (height + 1) * preedit_lines_);
672
673         // Don't forget to accept the event!
674         e->accept();
675 }
676
677
678 QVariant GuiWorkArea::inputMethodQuery(Qt::InputMethodQuery query) const
679 {
680         QRect cur_r(0,0,0,0);
681         switch (query) {
682                 // this is the CJK-specific composition window position.
683                 case Qt::ImMicroFocus:
684                         cur_r = cursor_->rect();
685                         if (preedit_lines_ != 1)
686                                 cur_r.moveLeft(10);
687                         cur_r.moveBottom(cur_r.bottom() + cur_r.height() * preedit_lines_);
688                         // return lower right of cursor in LyX.
689                         return cur_r;
690                 default:
691                         return QWidget::inputMethodQuery(query);
692         }
693 }
694
695 ////////////////////////////////////////////////////////////////////
696 // TabWorkArea implementation.
697 ////////////////////////////////////////////////////////////////////
698 TabWorkArea::TabWorkArea(QWidget * parent): QTabWidget(parent)
699 {
700         QPushButton * closeTabButton = new QPushButton(this);
701         FileName const file = support::libFileSearch("images", "closetab", "png");
702         if (!file.empty()) {
703                 QPixmap pm(toqstr(file.absFilename()));
704                 closeTabButton->setIcon(QIcon(pm));
705                 closeTabButton->setMaximumSize(pm.size());
706                 closeTabButton->setFlat(true);
707         } else {
708                 closeTabButton->setText("Close");
709         }
710         closeTabButton->setCursor(Qt::ArrowCursor);
711         closeTabButton->setToolTip(tr("Close tab"));
712         closeTabButton->setEnabled(true);
713
714         QObject::connect(this, SIGNAL(currentChanged(int)),
715                 this, SLOT(on_currentTabChanged(int)));
716         QObject::connect(closeTabButton, SIGNAL(clicked()),
717                 this, SLOT(closeCurrentTab()));
718
719         setCornerWidget(closeTabButton);
720 #if QT_VERSION >= 0x040200
721         setUsesScrollButtons(true);
722 #endif
723 }
724
725
726 void TabWorkArea::showBar(bool show)
727 {
728         tabBar()->setVisible(show);
729 }
730
731
732 void TabWorkArea::closeAll()
733 {
734         while (count()) {
735                 GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(0));
736                 BOOST_ASSERT(wa);
737                 removeTab(0);
738                 delete wa;
739         }
740 }
741
742
743 bool TabWorkArea::setCurrentWorkArea(GuiWorkArea * work_area)
744 {
745         BOOST_ASSERT(work_area);
746         int index = indexOf(work_area);
747         if (index == -1)
748                 return false;
749
750         if (index == currentIndex())
751                 // Make sure the work area is up to date.
752                 on_currentTabChanged(index);
753         else
754                 // Switch to the work area.
755                 setCurrentIndex(index);
756         work_area->setFocus();
757
758         return true;
759 }
760
761
762 bool TabWorkArea::removeWorkArea(GuiWorkArea * work_area)
763 {
764         BOOST_ASSERT(work_area);
765         int index = indexOf(work_area);
766         if (index == -1)
767                 return false;
768
769         work_area->setUpdatesEnabled(false);
770         removeTab(index);
771         delete work_area;
772
773         if (count()) {
774                 // make sure the next work area is enabled.
775                 currentWidget()->setUpdatesEnabled(true);
776                 // Hide tabbar if there's only one tab.
777                 showBar(count() > 1);
778         }
779         return true;
780 }
781
782
783 void TabWorkArea::on_currentTabChanged(int i)
784 {
785         GuiWorkArea * wa = dynamic_cast<GuiWorkArea *>(widget(i));
786         BOOST_ASSERT(wa);
787         BufferView & bv = wa->bufferView();
788         bv.updateMetrics(false);
789         bv.cursor().fixIfBroken();
790         wa->setUpdatesEnabled(true);
791         wa->redraw();
792         wa->setFocus();
793         ///
794         currentWorkAreaChanged(wa);
795
796         LYXERR(Debug::GUI) << "currentTabChanged " << i
797                 << "File" << bv.buffer().fileName() << endl;
798 }
799
800
801 void TabWorkArea::closeCurrentTab()
802 {
803         lyx::dispatch(FuncRequest(LFUN_BUFFER_CLOSE));
804 }
805
806 } // namespace frontend
807 } // namespace lyx
808
809 #include "GuiWorkArea_moc.cpp"