]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiWorkArea.C
This commit initialise correctly the tab bar in a new window.
[lyx.git] / src / frontends / qt4 / GuiWorkArea.C
1 /**
2  * \file GuiWorkArea.C
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 "QLPainter.h"
18 #include "QLyXKeySym.h"
19 #include "qt_helpers.h"
20
21 #include "LyXView.h"
22
23 #include "BufferView.h"
24 #include "rowpainter.h"
25 #include "debug.h"
26 #include "funcrequest.h"
27 #include "LColor.h"
28 #include "version.h"
29 #include "lyxrc.h"
30
31 #include "support/filetools.h" // LibFileSearch
32 #include "support/os.h"
33
34 #include "graphics/GraphicsImage.h"
35 #include "graphics/GraphicsLoader.h"
36
37 #include <QLayout>
38 #include <QMainWindow>
39 #include <QMimeData>
40 #include <QUrl>
41 #include <QDragEnterEvent>
42 #include <QPixmap>
43 #include <QPainter>
44 #include <QScrollBar>
45
46 #include <boost/bind.hpp>
47 #include <boost/current_function.hpp>
48
49 // Abdel (26/06/2006):
50 // On windows-XP the UserGuide PageDown scroll test is faster without event pruning (16 s)
51 // than with it (23 s).
52 #ifdef Q_WS_WIN
53  #define USE_EVENT_PRUNING 0
54 #else
55  #define USE_EVENT_PRUNING 0
56 #endif
57
58
59 using std::endl;
60 using std::string;
61
62 namespace os = lyx::support::os;
63
64
65 namespace lyx {
66
67 /// return the LyX key state from Qt's
68 static key_modifier::state q_key_state(Qt::KeyboardModifiers state)
69 {
70         key_modifier::state k = key_modifier::none;
71         if (state & Qt::ControlModifier)
72                 k |= key_modifier::ctrl;
73         if (state & Qt::ShiftModifier)
74                 k |= key_modifier::shift;
75         if (state & Qt::AltModifier || state & Qt::MetaModifier)
76                 k |= key_modifier::alt;
77         return k;
78 }
79
80
81 /// return the LyX mouse button state from Qt's
82 static mouse_button::state q_button_state(Qt::MouseButton button)
83 {
84         mouse_button::state b = mouse_button::none;
85         switch (button) {
86                 case Qt::LeftButton:
87                         b = mouse_button::button1;
88                         break;
89                 case Qt::MidButton:
90                         b = mouse_button::button2;
91                         break;
92                 case Qt::RightButton:
93                         b = mouse_button::button3;
94                         break;
95                 default:
96                         break;
97         }
98         return b;
99 }
100
101
102 /// return the LyX mouse button state from Qt's
103 mouse_button::state q_motion_state(Qt::MouseButton state)
104 {
105         mouse_button::state b = mouse_button::none;
106         if (state & Qt::LeftButton)
107                 b |= mouse_button::button1;
108         if (state & Qt::MidButton)
109                 b |= mouse_button::button2;
110         if (state & Qt::RightButton)
111                 b |= mouse_button::button3;
112         return b;
113 }
114
115
116 namespace frontend {
117
118 class CursorWidget : public QWidget {
119 public:
120         CursorWidget(QWidget * parent)
121                 : QWidget(parent)
122         {
123                 resize(2, 20);
124         }
125
126         void paintEvent(QPaintEvent *)
127         {
128                 QColor const & col = guiApp->colorCache().get(LColor::cursor);
129
130 /*      
131                 int cursor_w_;
132                 int cursor_h_;
133
134                 switch (cursor_shape_) {
135                 case BAR_SHAPE:
136                         // FIXME the cursor width shouldn't be hard-coded!
137                         cursor_w_ = 2;
138                         lshape_cursor_ = false;
139                         break;
140                 case L_SHAPE:
141                         cursor_w_ = cursor_h_ / 3;
142                         lshape_cursor_ = true;
143                         break;
144                 case REVERSED_L_SHAPE:
145                         cursor_w_ = cursor_h_ / 3;
146                         //cursor_x_ -= cursor_w_ - 1;
147                         lshape_cursor_ = true;
148                         break;
149                 }
150 */
151
152                 // We cache two pixmaps:
153                 // 1 the vertical line of the cursor.
154                 // 2 the horizontal line of the L-shaped cursor (if necessary).
155
156                 // Draw the new (vertical) cursor.
157                 QPainter pain(this);
158                 pain.fillRect(rect(), col);
159 /*
160                 // Draw the new (horizontal) cursor if necessary.
161                 if (lshape_cursor_) {
162                         hcursor_ = QPixmap(cursor_w_, 1);
163                         hcursor_.fill(col);
164                         show_hcursor_ = true;
165                 }
166 */
167         }
168         /// shown?
169         bool on_;
170         ///
171         CursorShape shape_;
172 };
173
174
175 // This is a 'heartbeat' generating synthetic mouse move events when the
176 // cursor is at the top or bottom edge of the viewport. One scroll per 0.2 s
177 SyntheticMouseEvent::SyntheticMouseEvent()
178         : timeout(200), restart_timeout(true),
179           x_old(-1), y_old(-1), scrollbar_value_old(-1.0)
180 {}
181
182
183 GuiWorkArea::GuiWorkArea(int w, int h, int id, LyXView & lyx_view)
184         : WorkArea(id, lyx_view)
185 {
186         cursor_ = new frontend::CursorWidget(this);
187         cursor_->hide();
188
189         setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
190         setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
191         setAcceptDrops(true);
192         setMinimumSize(100, 70);
193
194         //viewport()->setAutoFillBackground(false);
195         //viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
196         setFocusPolicy(Qt::WheelFocus);
197
198         viewport()->setCursor(Qt::IBeamCursor);
199
200         resize(w, h);
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         // PageStep only depends on the viewport height.
211         verticalScrollBar()->setPageStep(viewport()->height());
212
213         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
214                 << "\n Area width\t" << width()
215                 << "\n Area height\t" << height()
216                 << "\n viewport width\t" << viewport()->width()
217                 << "\n viewport height\t" << viewport()->height()
218                 << endl;
219
220         if (USE_EVENT_PRUNING) {
221                 // This is the keyboard buffering stuff...
222                 // I don't see any need for this under windows. The keyboard is reactive
223                 // enough...
224
225                 if ( !QObject::connect(&step_timer_, SIGNAL(timeout()),
226                         this, SLOT(keyeventTimeout())) )
227                         lyxerr[Debug::GUI] << "ERROR: keyeventTimeout cannot connect!" << endl;
228
229                 // Start the timer, one-shot.
230                 step_timer_.setSingleShot(true);
231                 step_timer_.start(50);
232         }
233
234         // Enables input methods for asian languages.
235         // Must be set when creating custom text editing widgets.
236         setAttribute(Qt::WA_InputMethodEnabled, true);
237 }
238
239
240 void GuiWorkArea::setScrollbarParams(int h, int scroll_pos, int scroll_line_step)
241 {
242         verticalScrollBar()->setTracking(false);
243
244         // do what cursor movement does (some grey)
245         h += height() / 4;
246         int scroll_max_ = std::max(0, h - height());
247
248         setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
249         verticalScrollBar()->setRange(0, scroll_max_);
250         verticalScrollBar()->setSliderPosition(scroll_pos);
251         verticalScrollBar()->setSingleStep(scroll_line_step);
252         verticalScrollBar()->setValue(scroll_pos);
253
254         verticalScrollBar()->setTracking(true);
255 }
256
257
258 void GuiWorkArea::adjustViewWithScrollBar(int)
259 {
260         scrollBufferView(verticalScrollBar()->sliderPosition());
261 }
262
263
264 void GuiWorkArea::dragEnterEvent(QDragEnterEvent * event)
265 {
266         if (event->mimeData()->hasUrls())
267                 event->accept();
268         /// \todo Ask lyx-devel is this is enough:
269         /// if (event->mimeData()->hasFormat("text/plain"))
270         ///     event->acceptProposedAction();
271 }
272
273
274 void GuiWorkArea::dropEvent(QDropEvent* event)
275 {
276         QList<QUrl> files = event->mimeData()->urls();
277         if (files.isEmpty())
278                 return;
279
280         lyxerr[Debug::GUI] << "GuiWorkArea::dropEvent: got URIs!" << endl;
281         for (int i = 0; i!=files.size(); ++i) {
282                 string const file = os::internal_path(fromqstr(files.at(i).toLocalFile()));
283                 if (!file.empty())
284                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
285         }
286 }
287
288
289 void GuiWorkArea::focusInEvent(QFocusEvent * /*event*/)
290 {
291         // FIXME: it would be better to send a signal "newBuffer()"
292         // in BufferList that could be connected to the different tabbar.
293         lyx_view_.updateTab();
294         startBlinkingCursor();
295 }
296
297
298 void GuiWorkArea::focusOutEvent(QFocusEvent * /*event*/)
299 {
300         stopBlinkingCursor();
301 }
302
303
304 void GuiWorkArea::mousePressEvent(QMouseEvent * e)
305 {
306         if (dc_event_.active && dc_event_ == *e) {
307                 dc_event_.active = false;
308                 FuncRequest cmd(LFUN_MOUSE_TRIPLE,
309                         dc_event_.x, dc_event_.y,
310                         q_button_state(dc_event_.state));
311                 dispatch(cmd);
312                 return;
313         }
314
315         FuncRequest const cmd(LFUN_MOUSE_PRESS, e->x(), e->y(),
316                               q_button_state(e->button()));
317         dispatch(cmd);
318 }
319
320
321 void GuiWorkArea::mouseReleaseEvent(QMouseEvent * e)
322 {
323         if (synthetic_mouse_event_.timeout.running())
324                 synthetic_mouse_event_.timeout.stop();
325
326         FuncRequest const cmd(LFUN_MOUSE_RELEASE, e->x(), e->y(),
327                               q_button_state(e->button()));
328         dispatch(cmd);
329 }
330
331
332 void GuiWorkArea::mouseMoveEvent(QMouseEvent * e)
333 {
334         FuncRequest cmd(LFUN_MOUSE_MOTION, e->x(), e->y(),
335                               q_motion_state(e->button()));
336
337         // If we're above or below the work area...
338         if (e->y() <= 20 || e->y() >= viewport()->height() - 20) {
339                 // Make sure only a synthetic event can cause a page scroll,
340                 // so they come at a steady rate:
341                 if (e->y() <= 20)
342                         // _Force_ a scroll up:
343                         cmd.y = -40;
344                 else
345                         cmd.y = viewport()->height();
346                 // Store the event, to be handled when the timeout expires.
347                 synthetic_mouse_event_.cmd = cmd;
348
349                 if (synthetic_mouse_event_.timeout.running())
350                         // Discard the event. Note that it _may_ be handled
351                         // when the timeout expires if
352                         // synthetic_mouse_event_.cmd has not been overwritten.
353                         // Ie, when the timeout expires, we handle the
354                         // most recent event but discard all others that
355                         // occurred after the one used to start the timeout
356                         // in the first place.
357                         return;
358                 else {
359                         synthetic_mouse_event_.restart_timeout = true;
360                         synthetic_mouse_event_.timeout.start();
361                         // Fall through to handle this event...
362                 }
363
364         } else if (synthetic_mouse_event_.timeout.running()) {
365                 // Store the event, to be possibly handled when the timeout
366                 // expires.
367                 // Once the timeout has expired, normal control is returned
368                 // to mouseMoveEvent (restart_timeout = false).
369                 // This results in a much smoother 'feel' when moving the
370                 // mouse back into the work area.
371                 synthetic_mouse_event_.cmd = cmd;
372                 synthetic_mouse_event_.restart_timeout = false;
373                 return;
374         }
375
376         // Has anything changed on-screen since the last QMouseEvent
377         // was received?
378         double const scrollbar_value = verticalScrollBar()->value();
379         if (e->x() != synthetic_mouse_event_.x_old ||
380             e->y() != synthetic_mouse_event_.y_old ||
381             scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
382                 // Yes it has. Store the params used to check this.
383                 synthetic_mouse_event_.x_old = e->x();
384                 synthetic_mouse_event_.y_old = e->y();
385                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
386
387                 // ... and dispatch the event to the LyX core.
388                 dispatch(cmd);
389         }
390 }
391
392
393 void GuiWorkArea::wheelEvent(QWheelEvent * e)
394 {
395         // Wheel rotation by one notch results in a delta() of 120 (see
396         // documentation of QWheelEvent)
397         int const lines = qApp->wheelScrollLines() * e->delta() / 120;
398         verticalScrollBar()->setValue(verticalScrollBar()->value() -
399                         lines *  verticalScrollBar()->singleStep());
400         adjustViewWithScrollBar();
401 }
402
403
404 void GuiWorkArea::generateSyntheticMouseEvent()
405 {
406 // Set things off to generate the _next_ 'pseudo' event.
407         if (synthetic_mouse_event_.restart_timeout)
408                 synthetic_mouse_event_.timeout.start();
409
410         // Has anything changed on-screen since the last timeout signal
411         // was received?
412         double const scrollbar_value = verticalScrollBar()->value();
413         if (scrollbar_value != synthetic_mouse_event_.scrollbar_value_old) {
414                 // Yes it has. Store the params used to check this.
415                 synthetic_mouse_event_.scrollbar_value_old = scrollbar_value;
416
417                 // ... and dispatch the event to the LyX core.
418                 dispatch(synthetic_mouse_event_.cmd);
419         }
420 }
421
422
423 void GuiWorkArea::keyPressEvent(QKeyEvent * e)
424 {
425         lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
426                 << " count=" << e->count()
427                 << " text=" << fromqstr(e->text())
428                 << " isAutoRepeat=" << e->isAutoRepeat()
429                 << " key=" << e->key()
430                 << endl;
431
432         if (USE_EVENT_PRUNING) {
433                 keyeventQueue_.push(boost::shared_ptr<QKeyEvent>(new QKeyEvent(*e)));
434         }
435         else {
436                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
437                 sym->set(e);
438                 processKeySym(sym, q_key_state(e->modifiers()));
439         }
440 }
441
442
443 // This is used only if USE_EVENT_PRUNING is defined...
444 void GuiWorkArea::keyeventTimeout()
445 {
446         bool handle_autos = true;
447
448         while (!keyeventQueue_.empty()) {
449                 boost::shared_ptr<QKeyEvent> ev = keyeventQueue_.front();
450
451                 // We never handle more than one auto repeated
452                 // char in a list of queued up events.
453                 if (!handle_autos && ev->isAutoRepeat()) {
454                         keyeventQueue_.pop();
455                         continue;
456                 }
457
458                 boost::shared_ptr<QLyXKeySym> sym(new QLyXKeySym);
459                 sym->set(ev.get());
460
461                 lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
462                                    << " count=" << ev->count()
463                                    << " text=" <<  fromqstr(ev->text())
464                                    << " isAutoRepeat=" << ev->isAutoRepeat()
465                                    << " key=" << ev->key()
466                                    << endl;
467
468                 processKeySym(sym, q_key_state(ev->modifiers()));
469                 keyeventQueue_.pop();
470
471                 handle_autos = false;
472         }
473
474         // Restart the timer.
475         step_timer_.setSingleShot(true);
476         step_timer_.start(25);
477 }
478
479
480 void GuiWorkArea::mouseDoubleClickEvent(QMouseEvent * e)
481 {
482         dc_event_ = double_click(e);
483
484         if (!dc_event_.active)
485                 return;
486
487         dc_event_.active = false;
488
489         FuncRequest cmd(LFUN_MOUSE_DOUBLE,
490                 dc_event_.x, dc_event_.y,
491                 q_button_state(dc_event_.state));
492         dispatch(cmd);
493 }
494
495
496 void GuiWorkArea::resizeEvent(QResizeEvent * ev)
497 {
498         cursor_->hide();
499         verticalScrollBar()->setPageStep(viewport()->height());
500         QAbstractScrollArea::resizeEvent(ev);
501         resizeBufferView();
502 }
503
504
505 void GuiWorkArea::update(int x, int y, int w, int h)
506 {
507         viewport()->update(x, y, w, h);
508 }
509
510
511 void GuiWorkArea::doGreyOut(QLPainter & pain)
512 {
513         greyed_out_ = true;
514         pain.fillRectangle(0, 0, width(), height(),
515                 LColor::bottomarea);
516
517         //if (!lyxrc.show_banner)
518         //      return;
519         lyxerr << "show banner: " << lyxrc.show_banner << endl;
520         /// The text to be written on top of the pixmap
521         string const text = lyx_version ? lyx_version : "unknown";
522         string const file = support::libFileSearch("images", "banner", "ppm");
523         if (file.empty())
524                 return;
525
526         QPixmap pm(toqstr(file));
527         if (!pm) {
528                 lyxerr << "could not load splash screen: '" << file << "'" << endl;
529                 return;
530         }
531
532         QFont font;
533         // The font used to display the version info
534         font.setStyleHint(QFont::SansSerif);
535         font.setWeight(QFont::Bold);
536         font.setPointSize(LyXFont::SIZE_NORMAL);
537
538         int const w = pm.width();
539         int const h = pm.height();
540
541         int x = (width() - w) / 2;
542         int y = (height() - h) / 2;
543
544         pain.drawPixmap(x, y, pm);
545
546         x += 260;
547         y += 265;
548
549         pain.setPen(QColor(255, 255, 0));
550         pain.setFont(font);
551         pain.drawText(x, y, toqstr(text));
552 }
553
554
555 void GuiWorkArea::paintEvent(QPaintEvent * ev)
556 {
557         /*
558         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
559                 << "\n QWidget width\t" << this->width()
560                 << "\n QWidget height\t" << this->height()
561                 << "\n viewport width\t" << viewport()->width()
562                 << "\n viewport height\t" << viewport()->height()
563                 << "\n QPaintEvent x\t" << e->rect().x()
564                 << "\n QPaintEvent y\t" << e->rect().y()
565                 << "\n QPaintEvent w\t" << e->rect().width()
566                 << "\n QPaintEvent h\t" << e->rect().height()
567                 << endl;
568         */
569
570         QRect const rc = ev->rect(); 
571         //lyxerr << "paintEvent begin: x: " << rc.x()
572         //      << " y: " << rc.y()
573         //      << " w: " << rc.width()
574         //      << " h: " << rc.height() << endl;
575
576         if (!buffer_view_) {
577                 lyxerr << "no bufferview" << endl;
578                 return;
579         }
580
581         QLPainter pain(viewport());
582
583         if (rc.width() == 3) { // FIXME HACK
584                 // Assume splash screen drawing is requested when
585                 // width == 3
586                 lyxerr << "splash screen requested" << endl;
587                 doGreyOut(pain);
588                 return;
589         }
590
591         if (!buffer_view_->buffer()) {
592                 lyxerr << "no buffer: " << endl;
593                 doGreyOut(pain);
594                 updateScrollbar();
595                 return;
596         }
597
598         //lyxerr << "real drawing" << endl;
599         paintText(*buffer_view_, pain);
600 }
601
602
603
604 void GuiWorkArea::expose(int x, int y, int w, int h)
605 {
606         update(x, y, w, h);
607 }
608
609
610 void GuiWorkArea::showCursor(int x, int y, int h, CursorShape shape)
611 {
612         cursor_->setGeometry(x, y, 2, h);
613         cursor_->shape_ = shape;
614         cursor_->on_ = true;
615         cursor_->show();
616 }
617
618
619 void GuiWorkArea::removeCursor()
620 {
621         if (!qApp->focusWidget())
622                 return;
623         cursor_->hide();
624 }
625
626
627 void GuiWorkArea::inputMethodEvent(QInputMethodEvent * e)
628 {
629         QString const & text = e->commitString();
630         if (!text.isEmpty()) {
631
632                 lyxerr[Debug::KEY] << BOOST_CURRENT_FUNCTION
633                         << " preeditString =" << fromqstr(e->preeditString())
634                         << " commitString  =" << fromqstr(e->commitString())
635                         << endl;
636
637                 int key = 0;
638                 // needed to make math superscript work on some systems
639                 // ideally, such special coding should not be necessary
640                 if (text == "^")
641                         key = Qt::Key_AsciiCircum;
642                 // FIXME: Needs for investigation, this key is not really used,
643                 // the ctor below just check if key is different from 0.
644                 QKeyEvent ev(QEvent::KeyPress, key, Qt::NoModifier, text);
645                 keyPressEvent(&ev);
646         }
647         e->accept();
648 }
649
650 } // namespace frontend
651 } // namespace lyx
652
653 #include "GuiWorkArea_moc.cpp"