Debian Codegraph @

src/qdjvuwidget.cpp

raw
1 //C- -*- C++ -*-
2 //C- -------------------------------------------------------------------
3 //C- DjView4
4 //C- Copyright (c) 2006- Leon Bottou
5 //C-
6 //C- This software is subject to, and may be distributed under, the
7 //C- GNU General Public License, either version 2 of the license,
8 //C- or (at your option) any later version. The license should have
9 //C- accompanied the software or you may obtain a copy of the license
10 //C- from the Free Software Foundation at http://www.fsf.org .
11 //C-
12 //C- This program is distributed in the hope that it will be useful,
13 //C- but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 //C- GNU General Public License for more details.
16 //C- ------------------------------------------------------------------
17
18 #if AUTOCONF
19 # include "config.h"
20 #endif
21
22 #include <stddef.h>
23 #include <stdlib.h>
24 #include <math.h>
25
26 #include <libdjvu/ddjvuapi.h>
27 #include <libdjvu/miniexp.h>
28
29
30 #include "qdjvu.h"
31 #include "qdjvuwidget.h"
32
33 #include <QApplication>
34 #include <QBitmap>
35 #include <QCursor>
36 #include <QDebug>
37 #include <QImage>
38 #include <QKeyEvent>
39 #include <QList>
40 #include <QMap>
41 #include <QMenu>
42 #include <QMouseEvent>
43 #include <QPainter>
44 #include <QPainterPath>
45 #include <QPaintEvent>
46 #include <QPixmap>
47 #include <QPolygon>
48 #include <QRect>
49 #include <QRectF>
50 #include <QScrollBar>
51 #include <QTimer>
52 #include <QToolTip>
53 #include <QVector>
54 #include <QWheelEvent>
55 #include <QWidget>
56 #if QT_VERSION >= 0x040600
57 #include <QGesture>
58 #endif
59 #ifdef QT_OPENGL_LIB
60 # if QT_VERSION >= 0x60000
61 # undef QT_OPENGL_LIB
62 # else
63 # include <QGLWidget>
64 # include <QGLFormat>
65 # endif
66 #endif
67
68 #if DDJVUAPI_VERSION < 17
69 # error "DDJVUAPI_VERSION>=17 is required !"
70 #endif
71
72 #if DDJVUAPI_VERSION >= 18
73 # ifndef QDJVUWIDGET_PIXMAP_CACHE
74 # define QDJVUWIDGET_PIXMAP_CACHE 1
75 # endif
76 #endif
77
78 #ifdef Q_NO_USING_KEYWORD
79 # define BEGIN_ANONYMOUS_NAMESPACE
80 # define END_ANONYMOUS_NAMESPACE
81 # define QRectMapper QDjVu_QRectMapper
82 # define Page QDjVu_Page
83 # define Cache QDjVu_Cache
84 # define MapArea QDjVu_MapArea
85 # define Keywords QDjVu_Keywords
86 # define DragMode QDjVu_DragMode
87 #else
88 # define BEGIN_ANONYMOUS_NAMESPACE namespace {
89 # define END_ANONYMOUS_NAMESPACE }
90 #endif
91
92 typedef QDjVuWidget::Align Align;
93 typedef QDjVuWidget::DisplayMode DisplayMode;
94 typedef QDjVuWidget::Position Position;
95 typedef QDjVuWidget::PageInfo PageInfo;
96 typedef QDjVuWidget::Priority Priority;
97
98 #define ZOOM_STRETCH QDjVuWidget::ZOOM_STRETCH
99 #define ZOOM_ONE2ONE QDjVuWidget::ZOOM_ONE2ONE
100 #define ZOOM_FITPAGE QDjVuWidget::ZOOM_FITPAGE
101 #define ZOOM_FITWIDTH QDjVuWidget::ZOOM_FITWIDTH
102 #define ZOOM_MIN QDjVuWidget::ZOOM_MIN
103 #define ZOOM_100 QDjVuWidget::ZOOM_100
104 #define ZOOM_MAX QDjVuWidget::ZOOM_MAX
105
106 #define DISPLAY_COLOR QDjVuWidget::DISPLAY_COLOR
107 #define DISPLAY_STENCIL QDjVuWidget::DISPLAY_STENCIL
108 #define DISPLAY_BG QDjVuWidget::DISPLAY_BG
109 #define DISPLAY_FG QDjVuWidget::DISPLAY_FG
110 #define DISPLAY_TEXT QDjVuWidget::DISPLAY_TEXT
111
112 #define ALIGN_TOP QDjVuWidget::ALIGN_TOP
113 #define ALIGN_LEFT QDjVuWidget::ALIGN_LEFT
114 #define ALIGN_CENTER QDjVuWidget::ALIGN_CENTER
115 #define ALIGN_BOTTOM QDjVuWidget::ALIGN_BOTTOM
116 #define ALIGN_RIGHT QDjVuWidget::ALIGN_RIGHT
117
118 #define PRIORITY_DEFAULT QDjVuWidget::PRIORITY_DEFAULT
119 #define PRIORITY_ANNO QDjVuWidget::PRIORITY_ANNO
120 #define PRIORITY_CGI QDjVuWidget::PRIORITY_CGI
121 #define PRIORITY_USER QDjVuWidget::PRIORITY_USER
122
123
124
125
126 // ----------------------------------------
127 // UTILITIES
128
129 static inline void
130 rect_to_qrect(const ddjvu_rect_t &rect, QRect &qrect)
131 {
132 qrect.setRect(rect.x, rect.y, rect.w, rect.h );
133 }
134
135 static inline void
136 qrect_to_rect(const QRect &qrect, ddjvu_rect_t &rect, int scale=1)
137 {
138 qrect.getRect(&rect.x, &rect.y, (int*)&rect.w, (int*)&rect.h);
139 if (scale > 1)
140 {
141 rect.x *= scale;
142 rect.y *= scale;
143 rect.w *= scale;
144 rect.h *= scale;
145 }
146 }
147
148 static inline int
149 scale_int(int x, int numerator, int denominator)
150 {
151 qint64 y = (qint64)x * numerator;
152 return (int)(y + denominator - 1)/denominator;
153 }
154
155 static QSize
156 scale_size(int w, int h, int numerator, int denominator, int rot=0)
157 {
158 int sw = scale_int(w,numerator,denominator);
159 int sh = scale_int(h,numerator,denominator);
160 return (rot & 1) ? QSize(sh, sw) : QSize(sw, sh);
161 }
162
163 static bool
164 all_numbers(const char *s)
165 {
166 for (int i=0; s[i]; i++)
167 if (s[i]<'0' || s[i]>'9')
168 return false;
169 return true;
170 }
171
172 template<class T> static inline int
173 ksmallest(T *v, int n, int k)
174 {
175 int lo = 0;
176 int hi = n-1;
177 while (lo<hi)
178 {
179 int m,l,h;
180 T pivot;
181 /* Sort v[lo], v[m], v[hi] by insertion */
182 m = (lo+hi)/2;
183 if (v[lo]>v[m])
184 qSwap(v[lo],v[m]);
185 if (v[m]>v[hi]) {
186 qSwap(v[m],v[hi]);
187 if (v[lo]>v[m])
188 qSwap(v[lo],v[m]);
189 }
190 /* Extract pivot, place sentinel */
191 pivot = v[m];
192 v[m] = v[lo+1];
193 v[lo+1] = v[lo];
194 v[lo] = pivot;
195 /* Partition */
196 l = lo;
197 h = hi;
198 loop:
199 do ++l; while (v[l]<pivot);
200 do --h; while (v[h]>pivot);
201 if (l < h) {
202 qSwap(v[l],v[h]);
203 goto loop;
204 }
205 /* Finish up */
206 if (k <= h)
207 hi = h;
208 else if (k >= l)
209 lo = l;
210 else
211 break;
212 }
213 return v[k];
214 }
215
216 static QCursor
217 qcursor_by_name(const char *s, int hotx=8, int hoty=8)
218 {
219 QString name(s);
220 QPixmap pixmap(name);
221 if (pixmap.isNull())
222 return QCursor();
223 hotx = (hotx * pixmap.width()) / 16;
224 hoty = (hoty * pixmap.height()) / 16;
225 return QCursor(pixmap, hotx, hoty);
226 }
227
228 #if QT_VERSION > 0x60000
229 # define foreachrect(r,rgn) \
230 for (const auto &it : rgn) \
231 if (r = it; false) {} else
232 #elif QT_VERSION > 0x50800
233 # define foreachrect(r,rgn) \
234 foreach(r,rgn)
235 #else
236 # define foreachrect(r,rgn) \
237 foreach(r,(rgn).rects())
238 #endif
239
240 static QRegion
241 cover_region(QRegion region, const QRect &brect)
242 {
243 // dilate region
244 QRegion dilated;
245 foreachrect(const QRect &r, region)
246 dilated |= r.adjusted(-8, -8, 8, 8).intersected(brect);
247 // find nice cover
248 QList<int> myarea;
249 QList<QRect> myrect;
250 foreachrect(const QRect &r, dilated)
251 {
252 int a = r.width() * r.height();
253 int j = myrect.size();
254 while (--j >= 0)
255 {
256 int na = myarea[j] + a;
257 QRect nr = myrect[j].united(r);
258 if (nr.width() * nr.height() < 2 * na )
259 {
260 myarea[j] = na;
261 myrect[j] = nr;
262 break;
263 }
264 }
265 if (j < 0)
266 {
267 myarea << a;
268 myrect << r;
269 }
270 }
271 // recompose region
272 QRegion ret;
273 for (int i=0; i<myrect.size(); i++)
274 ret += myrect[i];
275 return ret;
276 }
277
278 static qreal max_stay_in_rect(QPointF s, QRectF r, QPointF v)
279 {
280 qreal m = 1e10;
281 if (v.x() > 0)
282 m = qMin(m, (r.right() - s.x()) / v.x());
283 if (v.x() < 0)
284 m = qMin(m, (r.left() - s.x()) / v.x());
285 if (v.y() > 0)
286 m = qMin(m, (r.bottom() - s.y()) / v.y());
287 if (v.y() < 0)
288 m = qMin(m, (r.top() - s.y()) / v.y());
289 return m;
290 }
291
292
293 static bool
294 miniexp_get_int(miniexp_t &r, int &x)
295 {
296 if (! miniexp_numberp(miniexp_car(r)))
297 return false;
298 x = miniexp_to_int(miniexp_car(r));
299 r = miniexp_cdr(r);
300 return true;
301 }
302
303 static bool
304 miniexp_get_rect(miniexp_t &r, QRect &rect)
305 {
306 int x, y, w, h;
307 if (! (miniexp_get_int(r, x) && miniexp_get_int(r, y) &&
308 miniexp_get_int(r, w) && miniexp_get_int(r, h) ))
309 return false;
310 if (w<0 || h<0 || r)
311 return false;
312 rect.setRect(x, y, w, h);
313 return true;
314 }
315
316 static bool
317 miniexp_get_rect_from_points(miniexp_t &r, QRect &rect)
318 {
319 int x1,y1,x2,y2;
320 if (! (miniexp_get_int(r, x1) && miniexp_get_int(r, y1) &&
321 miniexp_get_int(r, x2) && miniexp_get_int(r, y2) ))
322 return false;
323 if (x2<x1 || y2<y1)
324 return false;
325 rect.setCoords(x1, y1, x2, y2);
326 return true;
327 }
328
329 static bool
330 miniexp_get_points(miniexp_t &r, QRect &rect, QList<QPoint> &points)
331 {
332 rect = QRect();
333 points.clear();
334 while (miniexp_consp(r))
335 {
336 int x, y;
337 if (!miniexp_get_int(r, x) || !miniexp_get_int(r, y))
338 return false;
339 points << QPoint(x,y);
340 rect |= QRect(x,y,1,1);
341 }
342 if (r || points.size() < 2)
343 return false;
344 return true;
345 }
346
347 static bool
348 miniexp_get_color(miniexp_t &r, QColor &color)
349 {
350 const char *s = miniexp_to_name(miniexp_car(r));
351 if (! (s && s[0]=='#'))
352 return false;
353 color.setNamedColor(QString::fromUtf8(s));
354 if (! color.isValid())
355 return false;
356 r = miniexp_cdr(r);
357 return true;
358 }
359
360 QString
361 miniexp_to_qstring(miniexp_t r)
362 {
363 const char *s = miniexp_to_str(r);
364 if (s) return QString::fromUtf8(s);
365 return QString();
366 }
367
368 void
369 flatten_hiddentext_sub(miniexp_t p, minivar_t &d)
370 {
371 miniexp_t type = miniexp_car(p);
372 miniexp_t r = miniexp_cdr(p);
373 QRect rect;
374 if (miniexp_symbolp(type) &&
375 miniexp_get_rect_from_points(r, rect) )
376 {
377 if (miniexp_stringp(miniexp_car(r)))
378 {
379 d = miniexp_cons(p, d);
380 }
381 else
382 {
383 while (miniexp_consp(r))
384 {
385 flatten_hiddentext_sub(miniexp_car(r), d);
386 r = miniexp_cdr(r);
387 }
388 d = miniexp_cons(type, d);
389 }
390 }
391 }
392
393 miniexp_t
394 flatten_hiddentext(miniexp_t p)
395 {
396 // Output list contains
397 // - terminals of the hidden text tree
398 // (keyword x1 y1 x2 y2 string)
399 // - or a keyword symbol indicating the need for a separator
400 // page,column,region,para,line,word
401 minivar_t d;
402 flatten_hiddentext_sub(p, d);
403 d = miniexp_reverse(d);
404 // Uncomment the following line to print it:
405 // miniexp_pprint(d, 72);
406 return d;
407 }
408
409 void
410 invert_luminance(QImage &img)
411 {
412 if (img.format() == QImage::Format_RGB32 ||
413 img.format() == QImage::Format_ARGB32 )
414 {
415 int w = img.width();
416 int h = img.height();
417 for (int y=0; y<h; y++)
418 {
419 qint32 *words = (qint32*)img.scanLine(y);
420 for (int x=0; x<w; x++)
421 {
422 qint32 word = *words;
423 qint32 r = (word >> 16) & 0xff;
424 qint32 g = (word >> 8) & 0xff;
425 qint32 b = (word >> 0) & 0xff;
426 word &= 0xff000000;
427 qint32 s = 255 - qMax(r,qMax(g,b)) - qMin(r,qMin(g,b));
428 word |= ((r+s)<<16) | ((b+s)<<8) | (g+s);
429 *words++ = word;
430 }
431 }
432 }
433 else
434 {
435 // revert to standard inversion.
436 img.invertPixels();
437 }
438 }
439
440 // ----------------------------------------
441 // Position
442
443
444 /*! \class QDjVuWidget::Position
445 \brief Defines a position in the document.
446
447 Variable \a pageNo indicates the closest page number.
448
449 Flag \a inPage indicates that the position falls inside
450 a page with known geometry. Variable \a posPage then
451 indicates the position within the full resolution
452 page coordinates (same coordinates as those used
453 for the DjVu page annotations).
454
455 Variable \a posView usually indicates the position
456 relative to, in general, the top-left corner of the page rectangle.
457 In fact variables \a hAnchor and \a vAnchor indicate
458 the coordinates of the reference point as a percentages
459 of the width and height relative to the top left corner.
460 These are always zero when the position is returned
461 by QDjVuWidget::position. Finally flag \a doPage
462 makes sure that \a pageNo is indeed the closest page.
463 This is always false when the position is returned
464 by QDjVuWidget::position. */
465
466 Position::Position()
467 : pageNo(0),
468 posPage(0,0),
469 posView(0,0),
470 inPage(false),
471 doPage(false),
472 hAnchor(0),
473 vAnchor(0)
474 {
475 }
476
477
478
479 // ----------------------------------------
480 // QRECTMAPPER
481
482
483 BEGIN_ANONYMOUS_NAMESPACE
484
485 class QRectMapper
486 {
487 private:
488 ddjvu_rectmapper_t *p;
489 public:
490 ~QRectMapper();
491 QRectMapper();
492 QRectMapper(const QRect &in, const QRect &out);
493 void setMap(const QRect &in, const QRect &out);
494 void setTransform(int rotation, bool mirrorx=false, bool mirrory=false);
495 QPoint mapped(const QPoint &p);
496 QRect mapped(const QRect &r);
497 QPoint unMapped(const QPoint &p);
498 QRect unMapped(const QRect &r);
499 };
500
501 QRectMapper::~QRectMapper()
502 {
503 ddjvu_rectmapper_release(p);
504 p = 0;
505 }
506
507 QRectMapper::QRectMapper()
508 : p(0)
509 {
510 }
511
512 QRectMapper::QRectMapper(const QRect &in, const QRect &out)
513 : p(0)
514 {
515 setMap(in, out);
516 }
517
518 void
519 QRectMapper::setMap(const QRect &in, const QRect &out)
520 {
521 ddjvu_rect_t rin, rout;
522 ddjvu_rectmapper_release(p);
523 p = 0;
524 qrect_to_rect(in, rin);
525 qrect_to_rect(out, rout);
526 p = ddjvu_rectmapper_create(&rin, &rout);
527 }
528
529 void
530 QRectMapper::setTransform(int rotation, bool mirrorx, bool mirrory)
531 {
532 if (!p) qWarning("QRectMapper: please call setMap first.");
533 ddjvu_rectmapper_modify(p, rotation, (mirrorx?1:0), (mirrory?1:0));
534 }
535
536 QPoint
537 QRectMapper::mapped(const QPoint &qp)
538 {
539 QPoint q = qp;
540 if (p) ddjvu_map_point(p, &q.rx(), &q.ry());
541 return q;
542 }
543
544 QRect
545 QRectMapper::mapped(const QRect &qr)
546 {
547 QRect q;
548 ddjvu_rect_t r;
549 qrect_to_rect(qr, r);
550 if (p) ddjvu_map_rect(p, &r);
551 rect_to_qrect(r, q);
552 return q;
553 }
554
555 QPoint
556 QRectMapper::unMapped(const QPoint &qp)
557 {
558 QPoint q = qp;
559 if (p) ddjvu_unmap_point(p, &q.rx(), &q.ry());
560 return q;
561 }
562
563 QRect
564 QRectMapper::unMapped(const QRect &qr)
565 {
566 QRect q;
567 ddjvu_rect_t r;
568 qrect_to_rect(qr, r);
569 if (p) ddjvu_unmap_rect(p, &r);
570 rect_to_qrect(r, q);
571 return q;
572 }
573
574 END_ANONYMOUS_NAMESPACE
575
576
577 // ----------------------------------------
578 // PRIORITIZED SETTINGS
579
580 // Some settings can be set/unset from several sources
581
582 BEGIN_ANONYMOUS_NAMESPACE
583
584 template<class Value>
585 class Prioritized
586 {
587 public:
588 Prioritized();
589 operator Value() const;
590 void set(Priority priority, Value value);
591 void unset(Priority priority);
592 void reduce(Priority priority);
593 private:
594 bool flags[PRIORITY_USER+1];
595 Value values[PRIORITY_USER+1];
596 };
597
598 template<class Value>
599 Prioritized<Value>::Prioritized()
600 {
601 for (int i=0; i<=PRIORITY_USER; i++)
602 flags[i] = false;
603 }
604
605 template<class Value>
606 Prioritized<Value>::operator Value() const
607 {
608 for (int i=PRIORITY_USER; i>0; i--)
609 if (flags[i])
610 return values[i];
611 return values[PRIORITY_DEFAULT];
612 }
613
614 template<class Value> void
615 Prioritized<Value>::set(Priority priority, Value val)
616 {
617 values[priority] = val;
618 flags[priority] = true;
619 }
620
621 template<class Value> void
622 Prioritized<Value>::unset(Priority priority)
623 {
624 flags[priority] = false;
625 }
626
627 template<class Value> void
628 Prioritized<Value>::reduce(Priority priority)
629 {
630 for (int i=PRIORITY_USER; i>priority; i--)
631 if (flags[i])
632 {
633 flags[i-1] = flags[i];
634 values[i-1] = values[i];
635 flags[i] = false;
636 }
637 }
638
639 END_ANONYMOUS_NAMESPACE
640
641
642 // ----------------------------------------
643 // QDJVULENS (declaration)
644
645
646 class QDjVuLens : public QWidget
647 {
648 Q_OBJECT
649 public:
650 QDjVuLens(int size, int mag, QDjVuPrivate *priv, QDjVuWidget *widget);
651 protected:
652 virtual bool event(QEvent *event);
653 virtual void paintEvent(QPaintEvent *event);
654 virtual void moveEvent(QMoveEvent *event);
655 virtual void resizeEvent(QResizeEvent *event);
656 virtual bool eventFilter(QObject*, QEvent*);
657 private:
658 QDjVuPrivate *priv;
659 QDjVuWidget *widget;
660 QRect lensRect;
661 int mag;
662 public slots:
663 void recenter(const QPoint &p);
664 void redisplay();
665 private:
666 void refocus();
667 };
668
669
670
671 // ----------------------------------------
672 // QDJVUPRIVATE
673
674
675 BEGIN_ANONYMOUS_NAMESPACE
676
677 struct MapArea
678 {
679 minivar_t expr;
680 miniexp_t url;
681 miniexp_t target;
682 miniexp_t comment;
683 miniexp_t areaType;
684 QRect areaRect;
685 QList<QPoint> areaPoints;
686 miniexp_t borderType;
687 QColor borderColor;
688 QColor hiliteColor;
689 QColor foregroundColor;
690 unsigned char borderWidth;
691 bool borderAlwaysVisible;
692 unsigned char hiliteOpacity;
693 bool pushpin;
694 bool lineArrow;
695 unsigned char lineWidth;
696 bool rectNeedsRotation;
697
698 MapArea();
699 bool error(const char *err, int pageno, miniexp_t info);
700 bool parse(miniexp_t anno, int pageno=-1);
701 bool isClickable(bool hyperlink=true);
702 bool clicked(void);
703 bool hasTransient(bool allLinks=false);
704 bool hasPermanent();
705 bool contains(const QPoint &p);
706 void maybeRotate(struct Page *p);
707 QPainterPath contour(QRectMapper &m, QPoint &offset);
708 void update(QWidget *w, QRectMapper &m, QPoint offset, bool permanent=false);
709 void paintBorder(QPaintDevice *w, QRectMapper &m, QPoint offset, bool allLinks=false);
710 void paintPermanent(QPaintDevice *w, QRectMapper &m, QPoint o, double z=100);
711 void paintTransient(QPaintDevice *w, QRectMapper &m, QPoint o, bool allLinks=false);
712 };
713
714 struct Page
715 {
716 int pageno;
717 int width; // page coordinates
718 int height; // page coordinates
719 int dpi; // zero to indicate unknown size
720 QRect rect; // desk coordinates
721 QRect viewRect; // viewport coordinates
722 QRectMapper mapper; // from page to desk coordinates
723 QDjVuPage *page; // the page decoder
724 minivar_t annotations; // the djvu page annotations
725 minivar_t hiddenText; // the hidden djvu page text
726 int initialRot; // initial rotation (used for text)
727 QList<MapArea> mapAreas; // the list of mapareas
728 bool redisplay; // must redisplay
729 bool infoNeeded; // we want the page info now.
730
731 void clear() { delete page; page=0; }
732 ~Page() { clear(); };
733 Page() : pageno(-1),width(0),height(0),dpi(0),page(0),
734 annotations(miniexp_dummy),hiddenText(miniexp_dummy),
735 initialRot(-1),redisplay(false),
736 infoNeeded(false) { clear(); }
737 };
738
739 struct Cache
740 {
741 QRect rect; // desk coordinates
742 QImage image;
743 #if QDJVUWIDGET_PIXMAP_CACHE
744 QPixmap pixmap;
745 #endif
746 };
747
748 enum {
749 CHANGE_STATS = 0x1, // recompute estimated page sizes
750 CHANGE_PAGES = 0x2, // change the displayed pages
751 CHANGE_SIZE = 0x4, // update the recorded size of displayed pages
752 CHANGE_SCALE = 0x8, // update the scale of displayed pages
753 CHANGE_POSITIONS = 0x10, // update the disposition of the pages
754 CHANGE_SCALE_PASS2 = 0x20, // internal
755 CHANGE_VIEW = 0x40, // move to a new position
756 CHANGE_VISIBLE = 0x80, // update the visible rectangle
757 CHANGE_SCROLLBARS = 0x100, // update the scrollbars
758 UPDATE_BORDERS = 0x200, // redisplay the visible desk surface
759 UPDATE_PAGES = 0x400, // redisplay, possibly by scrolling smartly
760 UPDATE_ALL = 0x800, // redisplay everything
761 REFRESH_PAGES = 0x1000, // redraw pages with new pixels
762 SCHEDULED = 0x8000 // internal: change scheduled
763 };
764
765 enum DragMode {
766 DRAG_NONE,
767 DRAG_PANNING,
768 DRAG_LENSING,
769 DRAG_SELECTING,
770 DRAG_LINKING
771 };
772
773 END_ANONYMOUS_NAMESPACE
774
775 class QDjVuPrivate : public QObject
776 {
777 Q_OBJECT
778
779 private:
780 virtual ~QDjVuPrivate();
781 QDjVuPrivate(QDjVuWidget *widget);
782 friend class QDjVuWidget;
783 friend class QDjVuLens;
784
785 public:
786 QDjVuWidget * const widget; // the widget
787
788 QDjVuDocument *doc;
789 bool docFailed; // page decoding has failed
790 bool docStopped; // page decoding has stopped
791 bool docReady; // page decoding is done
792 int numPages; // total number of pages
793 Position currentPos; // last clicked position
794 QPoint currentPoint; // last clicked point
795 Position cursorPos; // cursor position
796 QPoint cursorPoint; // cursor point
797 // display
798 int zoom;
799 int rotation;
800 DisplayMode display;
801 Align hAlign;
802 Align vAlign;
803 bool frame;
804 bool continuous;
805 bool sideBySide;
806 bool coverPage;
807 bool rightToLeft;
808 QBrush borderBrush;
809 // layout
810 int layoutChange; // scheduled changes
811 int layoutLoop; // loop avoidance counter
812 QPoint movePoint; // desired viewport point (CHANGE_VIEW)
813 Position movePos; // desired page point (CHANGE_VIEW)
814 QVector<Page> pageData; // all pages
815 QList<Page*> pageLayout; // pages in current layout
816 QList<Page*> pageVisible; // pages visible in viewport
817 QMap<int,Page*> pageMap; // keyed by page number
818 QRect deskRect; // desk rectangle (0,0,w,h)
819 QRect visibleRect; // visible rectangle (desk coordinates)
820 int zoomFactor; // effective zoom level
821 int savedFactor; // temporary factor used for gestures
822 int estimatedWidth; // median of known page widths
823 int estimatedHeight; // median of known page heights
824 QSize unknownSize; // displayed page size when unknown (pixels)
825 int borderSize; // size of borders around pages (pixels)
826 int separatorSize; // size of separation between pages (pixels)
827 int shadowSize; // size of the page shadow (pixels)
828 // page requests
829 int pageRequestDelay; // delay when scrollbars are down
830 QTimer *pageRequestTimer; // timer for page requests
831 // painting
832 int pixelCacheSize; // size of pixel cache
833 QRect selectedRect; // selection rectangle (viewport coord)
834 double gamma; // display gamma
835 bool invertLuminance; // invert images
836 QColor white; // display white point
837 int sdpi; // screen dpi
838 ddjvu_format_t *renderFormat; // ddjvu format
839 QList<Cache> pixelCache; // pixel cache
840 int devicePixelRatio; // device pixel ratio for cached images
841 // gui
842 bool keyboardEnabled; // obey keyboard commands
843 bool mouseEnabled; // obey mouse commands
844 bool hyperlinkEnabled; // follow hyperlinks
845 bool animationEnabled; // animate position changes
846 bool changingSBars; // set while changing scrollbars
847 bool mouseWheelZoom; // mouse wheel function
848 DragMode dragMode; // dragging mode
849 QPoint dragStart; // starting point for dragging
850 QMenu* contextMenu; // popup menu
851 QDjVuLens *lens; // lens (only while lensing)
852 int lensMag; // lens maginification
853 int lensSize; // lens size
854 double hourGlassRatio; // hour glass timer ratio
855 int lineStep; // pixels moved by arrow keys
856 Qt::MouseButtons buttons; // current mouse buttons
857 Qt::KeyboardModifiers modifiers; // current modifiers
858 Qt::KeyboardModifiers modifiersForLinks; // keys to show hyperlink
859 Qt::KeyboardModifiers modifiersForLens; // keys to show lens
860 Qt::KeyboardModifiers modifiersForSelect; // keys to select
861 QList<Position> animationPosition; // list of positions to hit
862 QPoint animationPoint; // reference point
863 QTimer *animationTimer; // animation timer
864
865 // prioritized settings
866 Prioritized<int> qBorderSize;
867 Prioritized<int> qZoom;
868 Prioritized<QBrush> qBorderBrush;
869 Prioritized<DisplayMode> qDisplay;
870 Prioritized<Align> qHAlign;
871 Prioritized<Align> qVAlign;
872 // hyperlinks
873 bool displayMapAreas;
874 Page *currentMapAreaPage;
875 MapArea *currentMapArea;
876 QString currentUrl;
877 QString currentTarget;
878 QString currentComment;
879 bool currentLinkDisplayed;
880 bool allLinksDisplayed;
881 QTimer *toolTipTimer;
882 // messages
883 int maxMessages;
884 QList<QString> errorMessages;
885 QList<QString> infoMessages;
886 // cursors
887 QCursor cursHandOpen;
888 QCursor cursHandClosed;
889
890 void initWidget(bool noaccel);
891 void changeLayout(int change, int delay=0);
892 void getAnnotationsAndText(Page *p);
893 bool requestPage(Page *p);
894 int findClosestPage(const QPoint&, const QList<Page*>&, Page**, int*);
895 Position findPosition(const QPoint &point, bool closestAnchor=false);
896 void updateModifiers(Qt::KeyboardModifiers, Qt::MouseButtons);
897 void updatePosition(const QPoint &point, bool click=false, bool links=true);
898 void updateCurrentPoint(const Position &pos);
899 void adjustSettings(Priority priority, miniexp_t expr);
900 void prepareMapAreas(Page*);
901 bool mustDisplayMapArea(MapArea*);
902 void checkCurrentMapArea(bool forceno=false);
903 void showTransientMapAreas(bool);
904 void updateTransientMapArea(Page*, MapArea*);
905 void trimPixelCache();
906 void addToPixelCache(const QRect &rect, QImage image);
907 bool paintHiddenText(QImage&, Page*, const QRect&, const QRect *pr=0);
908 bool paintMapAreas(QImage&, Page*, const QRect&, bool, const QRect *pr=0);
909 bool paintPage(QPainter&, Page*, const QRegion&);
910 void paintAll(QPainter&, const QRegion&);
911 bool pointerScroll(const QPoint &p);
912 void changeSelectedRectangle(const QRect &rect);
913 bool eventFilter(QObject*, QEvent*);
914 void clearAnimation(void);
915 bool computeAnimation(const Position&, const QPoint&);
916 void changeBorderSize(void);
917 void changeZoom(void);
918 void changeBorderBrush(void);
919 void changeDisplay(void);
920 void changeHAlign(void);
921 void changeVAlign(void);
922 QRect hourGlassRect(void) const;
923 void pageinfoPage(QDjVuPage*);
924
925 public slots:
926 void makeLayout();
927 void makePageRequests();
928 void docinfo();
929 void pageinfo();
930 void pageinfoPage();
931 void redisplayPage();
932 void error(QString msg, QString filename, int lineno);
933 void info(QString msg);
934 void makeToolTip();
935 void animate();
936 };
937
938 QDjVuPrivate::~QDjVuPrivate()
939 {
940 if (doc)
941 doc->deref();
942 doc = 0;
943 if (renderFormat)
944 ddjvu_format_release(renderFormat);
945 renderFormat = 0;
946 }
947
948 QDjVuPrivate::QDjVuPrivate(QDjVuWidget *widget)
949 : widget(widget)
950 {
951 // doc
952 doc = 0;
953 docReady = false;
954 docStopped = false;
955 docFailed = false;
956 numPages = 1;
957 // aspect
958 zoom = 100;
959 rotation = 0;
960 frame = true;
961 display = DISPLAY_COLOR;
962 hAlign = ALIGN_CENTER;
963 vAlign = ALIGN_CENTER;
964 sideBySide = false;
965 continuous = false;
966 coverPage = false;
967 rightToLeft = false;
968 borderBrush = QBrush(Qt::lightGray);
969 unknownSize = QSize(128,128);
970 borderSize = 8;
971 separatorSize = 12;
972 shadowSize = 2;
973 // prioritized
974 qBorderSize.set(PRIORITY_DEFAULT, borderSize);
975 qZoom.set(PRIORITY_DEFAULT, zoom);
976 qBorderBrush.set(PRIORITY_DEFAULT, borderBrush);
977 qDisplay.set(PRIORITY_DEFAULT, display);
978 qHAlign.set(PRIORITY_DEFAULT, hAlign);
979 qVAlign.set(PRIORITY_DEFAULT, vAlign);
980 // gui
981 contextMenu = 0;
982 keyboardEnabled = true;
983 hyperlinkEnabled = true;
984 mouseEnabled = true;
985 animationEnabled = true;
986 lineStep = 12;
987 buttons = (Qt::MouseButtons)(-1);
988 modifiers = (Qt::KeyboardModifiers)(-1);
989 modifiersForLinks = Qt::ShiftModifier;
990 modifiersForLens = Qt::ShiftModifier|Qt::ControlModifier;
991 modifiersForSelect = Qt::ControlModifier;
992 changingSBars = false;
993 dragMode = DRAG_NONE;
994 lens = 0;
995 lensMag = 3;
996 lensSize = 300;
997 hourGlassRatio = 0;
998 animationTimer = new QTimer(this);
999 animationTimer->setSingleShot(false);
1000 connect(animationTimer, SIGNAL(timeout()), this, SLOT(animate()));
1001 // scheduled changes
1002 layoutChange = 0;
1003 layoutLoop = 0;
1004 pageRequestDelay = 250;
1005 pageRequestTimer = new QTimer(this);
1006 pageRequestTimer->setSingleShot(true);
1007 // render format
1008 gamma = 2.2;
1009 invertLuminance = false;
1010 white = QColor(Qt::white);
1011 sdpi = 100;
1012 #if DDJVUAPI_VERSION < 18
1013 unsigned int masks[3] = { 0xff0000, 0xff00, 0xff };
1014 renderFormat = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 3, masks);
1015 #else
1016 unsigned int masks[4] = { 0xff0000, 0xff00, 0xff, 0xff000000 };
1017 renderFormat = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 4, masks);
1018 #endif
1019 ddjvu_format_set_row_order(renderFormat, true);
1020 ddjvu_format_set_y_direction(renderFormat, true);
1021 ddjvu_format_set_ditherbits(renderFormat, QPixmap::defaultDepth());
1022 ddjvu_format_set_gamma(renderFormat, gamma);
1023 // misc
1024 maxMessages = 20;
1025 displayMapAreas = true;
1026 currentMapAreaPage = 0;
1027 currentMapArea = 0;
1028 currentLinkDisplayed = false;
1029 allLinksDisplayed = false;
1030 pixelCacheSize = 256 * 1024;
1031 devicePixelRatio = 1;
1032 // cursors
1033 cursHandOpen = qcursor_by_name(":/images/cursor_hand_open.png");
1034 cursHandClosed = qcursor_by_name(":/images/cursor_hand_closed.png");
1035 // tooltips
1036 toolTipTimer = new QTimer(this);
1037 toolTipTimer->setSingleShot(true);
1038 // connect
1039 connect(pageRequestTimer, SIGNAL(timeout()),
1040 this, SLOT(makePageRequests()) );
1041 connect(toolTipTimer, SIGNAL(timeout()),
1042 this, SLOT(makeToolTip()) );
1043 connect(widget->horizontalScrollBar(), SIGNAL(sliderReleased()),
1044 this, SLOT(makePageRequests()) );
1045 connect(widget->verticalScrollBar(), SIGNAL(sliderReleased()),
1046 this, SLOT(makePageRequests()) );
1047 }
1048
1049
1050
1051 // ----------------------------------------
1052 // LAYOUT
1053
1054
1055 // Schedule a layout recomputation.
1056 void
1057 QDjVuPrivate::changeLayout(int change, int delay)
1058 {
1059 int oldChange = layoutChange;
1060 layoutChange = oldChange | change | SCHEDULED;
1061 layoutLoop = 0;
1062 if (! (oldChange & SCHEDULED))
1063 QTimer::singleShot(delay, this, SLOT(makeLayout()));
1064 }
1065
1066 // Perform a scheduled layout recomputation.
1067 void
1068 QDjVuPrivate::makeLayout()
1069 {
1070 // save position
1071 int futureLayoutChange = 0;
1072 if (docReady && !(layoutChange & CHANGE_VIEW))
1073 {
1074 movePoint = currentPoint;
1075 movePos = currentPos;
1076 }
1077 // adjust layout information
1078 while (layoutChange && docReady)
1079 {
1080 // Recompute estimated page sizes
1081 if (layoutChange & CHANGE_STATS)
1082 {
1083 int k = 0;
1084 QVector<int> widthVec(numPages+1);
1085 QVector<int> heightVec(numPages+1);
1086 layoutChange &= ~CHANGE_STATS;
1087 futureLayoutChange |= CHANGE_STATS;
1088 for (int i=0; i<numPages; i++)
1089 if (pageData[i].dpi > 0)
1090 {
1091 int dpi = pageData[i].dpi;
1092 widthVec[k] = pageData[i].width * 100 / dpi;
1093 heightVec[k] = pageData[i].height * 100 / dpi;
1094 k += 1;
1095 }
1096 if (k > 0)
1097 {
1098 futureLayoutChange &= ~CHANGE_STATS;
1099 estimatedWidth = ksmallest(widthVec.data(), k, k/2);
1100 estimatedHeight = ksmallest(heightVec.data(), k, k/2);
1101 for (int i=0; i<numPages; i++)
1102 if (pageData[i].dpi <= 0)
1103 {
1104 pageData[i].width = estimatedWidth;
1105 pageData[i].height = estimatedHeight;
1106 }
1107 }
1108 }
1109 // Layout composition
1110 else if (layoutChange & CHANGE_PAGES)
1111 {
1112 layoutChange &= ~CHANGE_PAGES;
1113 layoutChange |= CHANGE_SIZE;
1114 layoutChange |= CHANGE_SCALE;
1115 pageLayout.clear();
1116 pageMap.clear();
1117 if (movePos.pageNo<0 || movePos.pageNo>=numPages)
1118 {
1119 qWarning("makeLayout: invalid page number");
1120 movePos.pageNo = widget->page();
1121 }
1122 int loPage = movePos.pageNo;
1123 int hiPage = qMin(numPages, loPage+1);
1124 if (continuous)
1125 {
1126 loPage = 0;
1127 hiPage = numPages;
1128 }
1129 else if (sideBySide && coverPage)
1130 {
1131 loPage = qMax(0, (loPage & 1) ? loPage : loPage-1);
1132 hiPage = qMin(numPages, (loPage & 1) ? loPage+2 : loPage+1);
1133 }
1134 else if (sideBySide)
1135 {
1136 loPage = qMax(0, (loPage & 1) ? loPage-1 : loPage);
1137 hiPage = qMin(numPages, loPage+2);
1138 }
1139 for (int i=loPage; i<hiPage; i++)
1140 {
1141 pageData[i].viewRect = QRect();
1142 pageLayout << &pageData[i];
1143 pageMap[i] = &pageData[i];
1144 }
1145 for(int i=0; i<numPages; i++)
1146 if (i < loPage - 2 && i >= hiPage + 2)
1147 pageData[i].clear();
1148 // Display settings are unclear when showing multiple page.
1149 // We use the annotations of the first displayed page as a proxy.
1150 adjustSettings(PRIORITY_ANNO, pageLayout[0]->annotations);
1151 }
1152 // Layout page sizes
1153 else if (layoutChange & CHANGE_SIZE)
1154 {
1155 layoutChange &= ~CHANGE_SIZE;
1156 Page *p;
1157 foreach(p, pageLayout)
1158 {
1159 int n = p->pageno;
1160 if (! p->infoNeeded)
1161 continue;
1162 if (p->dpi <= 0)
1163 {
1164 ddjvu_pageinfo_t info;
1165 ddjvu_status_t status;
1166 status = ddjvu_document_get_pageinfo(*doc, n, &info);
1167 if (status == DDJVU_JOB_OK)
1168 if (info.dpi > 0 && info.width > 0 && info.height > 0)
1169 {
1170 p->dpi = info.dpi;
1171 p->width = info.width;
1172 p->height = info.height;
1173 #if DDJVUAPI_VERSION >= 18
1174 p->initialRot = info.rotation;
1175 #endif
1176 }
1177 layoutChange |= CHANGE_SCALE;
1178 layoutChange |= UPDATE_BORDERS;
1179 }
1180 getAnnotationsAndText(p);
1181 }
1182 }
1183 // Layout scaled page size
1184 else if (layoutChange & CHANGE_SCALE)
1185 {
1186 // some setups require two passes
1187 layoutChange &= ~CHANGE_SCALE;
1188 layoutChange &= ~CHANGE_SCALE_PASS2;
1189 layoutChange |= CHANGE_POSITIONS;
1190 if (pageLayout.size() > 1)
1191 if (zoom==ZOOM_FITWIDTH || zoom==ZOOM_FITPAGE)
1192 layoutChange |= CHANGE_SCALE_PASS2;
1193 // rescale pages
1194 Page *p;
1195 int r = rotation;
1196 int vpw = qMax(64, widget->viewport()->width() - 2*borderSize);
1197 int vph = qMax(64, widget->viewport()->height() - 2*borderSize);
1198 zoomFactor = zoom;
1199 foreach(p, pageLayout)
1200 {
1201 QSize size;
1202 if (p->width <= 0 || p->height <= 0) {
1203 size = unknownSize;
1204 } else if (p->dpi <= 0) {
1205 size = (zoom <= 0) ? unknownSize :
1206 scale_size(p->width, p->height, zoom*sdpi, 10000, r);
1207 } else if (layoutChange & CHANGE_SCALE_PASS2) {
1208 size = scale_size(p->width, p->height, sdpi, p->dpi, r);
1209 } else if (zoom == ZOOM_ONE2ONE) {
1210 size = scale_size(p->width, p->height, p->dpi, p->dpi, r);
1211 } else if (zoom == ZOOM_STRETCH) {
1212 int v2pw = (sideBySide) ? (vpw-separatorSize)/2 : vpw;
1213 size = QSize(v2pw, vph);
1214 } else if (zoom == ZOOM_FITWIDTH) {
1215 int pgw = (r&1) ? p->height : p->width;
1216 size = scale_size(p->width, p->height, vpw, pgw, r);
1217 zoomFactor = (vpw * p->dpi * 100) / (pgw * sdpi);
1218 } else if (zoom == ZOOM_FITPAGE) {
1219 int pgw = (r&1) ? p->height : p->width;
1220 int pgh = (r&1) ? p->width : p->height;
1221 if (vpw*pgh > vph*pgw)
1222 { vpw = vph; pgw = pgh; }
1223 size = scale_size(p->width, p->height, vpw, pgw, r);
1224 zoomFactor = (vpw * p->dpi * 100) / (pgw * sdpi);
1225 } else
1226 size = scale_size(p->width, p->height, zoom*sdpi,100*p->dpi,r);
1227 p->rect.setSize(size);
1228 }
1229 }
1230 // Layout page positions
1231 else if (layoutChange & CHANGE_POSITIONS)
1232 {
1233 layoutChange |= CHANGE_VIEW;
1234 layoutChange |= CHANGE_SCROLLBARS;
1235 layoutChange &= ~CHANGE_POSITIONS;
1236 // position pages
1237 Page *p;
1238 QRect fullRect;
1239 if (! continuous)
1240 {
1241 // single page or side by side pages
1242 int x = borderSize;
1243 int s = pageLayout.size();
1244 for (int i=0; i<s; i++)
1245 {
1246 if (rightToLeft)
1247 p = pageLayout[s-i-1];
1248 else
1249 p = pageLayout[i];
1250 p->rect.moveTo(x,borderSize);
1251 fullRect |= p->rect;
1252 x = x + p->rect.width() + separatorSize;
1253 }
1254 foreach(p, pageLayout)
1255 {
1256 int dy = fullRect.height() - p->rect.height();
1257 if (vAlign == ALIGN_CENTER)
1258 p->rect.translate(0, dy/2);
1259 else if (vAlign == ALIGN_BOTTOM)
1260 p->rect.translate(0, dy);
1261 }
1262 }
1263 else if (!sideBySide)
1264 {
1265 // continuous single pages
1266 int y = borderSize;
1267 foreach(p, pageLayout)
1268 {
1269 p->rect.moveTo(borderSize, y);
1270 y = y + p->rect.height() + separatorSize;
1271 fullRect |= p->rect;
1272 }
1273 foreach(p, pageLayout)
1274 {
1275 int dx = fullRect.width() - p->rect.width();
1276 if (hAlign == ALIGN_CENTER)
1277 p->rect.translate(dx/2, 0);
1278 else if (hAlign == ALIGN_RIGHT)
1279 p->rect.translate(dx,0);
1280 }
1281 }
1282 else
1283 {
1284 // continuous side-by-side pages
1285 int wLeft = 0;
1286 int wTotal = 0;
1287 int k = 0;
1288 while(k < pageLayout.size())
1289 {
1290 Page *lp = pageLayout[k++];
1291 Page *rp = lp;
1292 if (k < pageLayout.size() && (k>1 || !coverPage))
1293 rp = pageLayout[k++];
1294 if (rightToLeft)
1295 { Page *tmp=lp; lp=rp; rp=tmp; }
1296 int lw = lp->rect.width();
1297 wLeft = qMax(wLeft, lw);
1298 wTotal = qMax(wTotal, lw);
1299 if (rp)
1300 wTotal = qMax(wTotal, lw+rp->rect.width()+separatorSize);
1301 }
1302 int y = borderSize;
1303 k = 0;
1304 while(k < pageLayout.size())
1305 {
1306 Page *lp = pageLayout[k++];
1307 Page *rp = lp;
1308 if (k < pageLayout.size() && (k > 1 || !coverPage))
1309 rp = pageLayout[k++];
1310 if (rightToLeft)
1311 { Page *tmp=lp; lp=rp; rp=tmp; }
1312 int h = qMax(lp->rect.height(), rp->rect.height());
1313 int ly, ry, lx, rx;
1314 ly = ry = y;
1315 if (vAlign==ALIGN_BOTTOM) {
1316 ly += (h - lp->rect.height());
1317 ry += (h - rp->rect.height());
1318 } else if (vAlign==ALIGN_CENTER) {
1319 ly += (h - lp->rect.height())/2;
1320 ry += (h - rp->rect.height())/2;
1321 }
1322 if (hAlign==ALIGN_LEFT) {
1323 lx = borderSize;
1324 rx = lx + lp->rect.width() + separatorSize;
1325 } else if (hAlign==ALIGN_RIGHT) {
1326 if (rp == lp)
1327 rx = wTotal + borderSize + separatorSize;
1328 else
1329 rx = wTotal + borderSize - rp->rect.width();
1330 lx = rx - separatorSize - lp->rect.width();
1331 } else if (lp == rp) {
1332 lx = borderSize+wLeft+(separatorSize-lp->rect.width())/2;
1333 rx = lx;
1334 } else {
1335 lx = borderSize + wLeft - lp->rect.width();
1336 rx = borderSize + wLeft + separatorSize;
1337 }
1338 lp->rect.moveTo(lx, ly);
1339 if (rp != lp)
1340 rp->rect.moveTo(rx, ry);
1341 fullRect |= lp->rect;
1342 fullRect |= rp->rect;
1343 y = y + h + separatorSize;
1344 }
1345 }
1346 // setup rectangles
1347 fullRect.adjust(-borderSize, -borderSize,
1348 +borderSize, +borderSize );
1349 deskRect = fullRect;
1350 // setup mappers
1351 foreach(p, pageLayout)
1352 {
1353 int w = (p->width>0) ? p->width : unknownSize.width();
1354 int h = (p->height>0) ? p->height : unknownSize.height();
1355 p->mapper.setMap(QRect(0,0,w,h), p->rect);
1356 p->mapper.setTransform(rotation, false, true);
1357 }
1358 // clear pixel cache
1359 pixelCache.clear();
1360 }
1361 // Layout page positions
1362 else if (layoutChange & CHANGE_SCALE_PASS2)
1363 {
1364 Page *p;
1365 // compute usable viewport size (minus margins and separators)
1366 int vw = widget->viewport()->width() - 2*borderSize - 2;
1367 int vh = widget->viewport()->height() - 2*borderSize - 2;
1368 if (sideBySide && pageLayout.size()>1)
1369 vw = vw - separatorSize;
1370 vw = qMax(64, vw);
1371 vh = qMax(64, vh);
1372 // compute target size for zoom 100%
1373 int dw = deskRect.width() - 2*borderSize;
1374 int dh = deskRect.height() - 2*borderSize;
1375 if (sideBySide && pageLayout.size()>1)
1376 dw = dw - separatorSize;
1377 if (continuous)
1378 { dh = 0; foreach(p, pageLayout) dh = qMax(dh, p->rect.height()); }
1379 // compute zoom factor into vw/dw
1380 if (zoom == ZOOM_FITPAGE && vw*dh > vh*dw)
1381 { vw = vh; dw = dh; }
1382 zoomFactor = vw * 100 / dw;
1383 // apply zoom
1384 int r = rotation;
1385 foreach(p, pageLayout)
1386 {
1387 QSize size = unknownSize;
1388 int dpi = (p->dpi > 0) ? p->dpi : 100;
1389 if (p->width>0 && p->height>0)
1390 size = scale_size(p->width, p->height, vw * sdpi, dw * dpi, r);
1391 p->rect.setSize(size);
1392 }
1393 // prepare further adjustments
1394 layoutChange |= CHANGE_POSITIONS;
1395 layoutChange &= ~CHANGE_SCALE_PASS2;
1396 }
1397 // Viewport adjustment
1398 else if (layoutChange & CHANGE_VIEW)
1399 {
1400 if (pageMap.contains(movePos.pageNo))
1401 {
1402 Page *p = pageMap[movePos.pageNo];
1403 QPoint dp = p->rect.topLeft();
1404 if (movePos.hAnchor > 0 && movePos.hAnchor <= 100)
1405 dp.rx() += (p->rect.width() - 1) * movePos.hAnchor / 100;
1406 if (movePos.vAnchor > 0 && movePos.vAnchor <= 100)
1407 dp.ry() += (p->rect.height() - 1) * movePos.vAnchor / 100;
1408 QPoint sdp = dp;
1409 if (movePos.inPage && p->dpi)
1410 dp = p->mapper.mapped(movePos.posPage);
1411 else if (!movePos.inPage)
1412 dp += movePos.posView;
1413 // special case: unknown page geometry
1414 if (! p->dpi)
1415 if (movePos.inPage || movePos.vAnchor || movePos.hAnchor)
1416 futureLayoutChange = CHANGE_VIEW;
1417 // special case: not the closest page
1418 if (movePos.doPage)
1419 if (movePos.pageNo != findClosestPage(dp, pageLayout, 0, 0))
1420 dp = sdp;
1421 // perform move
1422 visibleRect.moveTo(dp - movePoint);
1423 }
1424 layoutChange |= CHANGE_VISIBLE;
1425 layoutChange &= ~CHANGE_VIEW;
1426 }
1427 // Layout page visibility adjustment
1428 else if (layoutChange & CHANGE_VISIBLE)
1429 {
1430 Page *p;
1431 QSize vpSize = widget->viewport()->size();
1432 QRect &rv = visibleRect;
1433 QRect &rd = deskRect;
1434 // adjust size
1435 rv.setSize(vpSize);
1436 // reposition rectVisible according to alignment.
1437 rv.moveRight(qMin(rv.right(), rd.right()));
1438 rv.moveLeft(qMax(rv.left(), rd.left()));
1439 rv.moveBottom(qMin(rv.bottom(), rd.bottom()));
1440 rv.moveTop(qMax(rv.top(), rd.top()));
1441 if (hAlign == ALIGN_RIGHT)
1442 rv.moveRight(qMin(rv.right(), rd.right()));
1443 if (vAlign == ALIGN_BOTTOM)
1444 rv.moveBottom(qMin(rv.bottom(), rd.bottom()));
1445 QPoint cd = rd.center();
1446 QPoint cv = rv.center();
1447 if (hAlign==ALIGN_CENTER && rv.width()>=rd.width())
1448 cv.setX(cd.x());
1449 if (vAlign==ALIGN_CENTER && rv.height()>=rd.height())
1450 cv.setY(cd.y());
1451 rv.moveCenter(cv);
1452 // delete QDjVuPage that are too far away
1453 int sw = rv.width();
1454 int sh = rv.height();
1455 QRect v = rv.adjusted(-sw, -sh, +sw, +sh);
1456 foreach(p, pageLayout)
1457 if (p->page && !v.intersects(p->rect))
1458 p->clear();
1459 // construct pageVisible array and schedule page requests
1460 pageVisible.clear();
1461 foreach(p, pageLayout)
1462 if (rv.intersects(p->rect))
1463 pageVisible.append(p);
1464 // schedule page requests
1465 QScrollBar *hBar = widget->horizontalScrollBar();
1466 QScrollBar *vBar = widget->verticalScrollBar();
1467 if (hBar->isSliderDown() || vBar->isSliderDown())
1468 pageRequestTimer->start(pageRequestDelay);
1469 else
1470 pageRequestTimer->start(0);
1471 // synchronize currentpoint and cursorpos
1472 updateCurrentPoint(movePos);
1473 updatePosition(cursorPoint, false, false);
1474 // continue
1475 layoutChange |= UPDATE_PAGES;
1476 layoutChange &= ~CHANGE_VISIBLE;
1477 }
1478 // scrollbar adjustment
1479 else if (layoutChange & CHANGE_SCROLLBARS)
1480 {
1481 QRect &rv = visibleRect;
1482 QRect rd = deskRect.united(rv);
1483 QScrollBar *hBar = widget->horizontalScrollBar();
1484 QScrollBar *vBar = widget->verticalScrollBar();
1485 int vmin = rd.top();
1486 int vmax = rd.bottom() + 1 - rv.height();
1487 int hmin = rd.left();
1488 int hmax = rd.right() + 1 - rv.width();
1489 // loop prevention
1490 if (++layoutLoop >= 4)
1491 {
1492 if (hBar->isVisible() && hmax <= hmin)
1493 hmax = hmin + 1;
1494 if (vBar->isVisible() && vmax <= vmin)
1495 vmax = vmin + 1;
1496 }
1497 // set scrollbars
1498 changingSBars = true;
1499 vBar->setMinimum(vmin);
1500 vBar->setMaximum(vmax);
1501 vBar->setPageStep(rv.height());
1502 vBar->setSingleStep(lineStep * 2);
1503 vBar->setValue(rv.top());
1504 hBar->setMinimum(hmin);
1505 hBar->setMaximum(hmax);
1506 hBar->setPageStep(rv.width());
1507 hBar->setSingleStep(lineStep * 2);
1508 hBar->setValue(rv.left());
1509 changingSBars = false;
1510 layoutChange &= ~CHANGE_SCROLLBARS;
1511 }
1512 // force redraw
1513 else if (layoutChange & UPDATE_ALL)
1514 {
1515 Page *p;
1516 QRect &rv = visibleRect;
1517 foreach(p, pageLayout)
1518 p->viewRect = p->rect.translated(-rv.topLeft());
1519 layoutChange &= ~UPDATE_ALL;
1520 layoutChange &= ~UPDATE_PAGES;
1521 layoutChange &= ~UPDATE_BORDERS;
1522 widget->viewport()->update();
1523 checkCurrentMapArea();
1524 emit widget->layoutChanged();
1525 }
1526 // otherwise try scrolling
1527 else if (layoutChange & UPDATE_PAGES)
1528 {
1529 Page *p;
1530 QRect &rv = visibleRect;
1531 // redraw on failure
1532 layoutChange |= UPDATE_ALL;
1533 // determine potential scroll
1534 int dx = 0;
1535 int dy = 0;
1536 bool scroll = false;
1537 foreach(p, pageVisible)
1538 if (p->viewRect.size() == p->rect.size()) {
1539 scroll = true;
1540 dx = p->rect.left() - rv.left() - p->viewRect.left();
1541 dy = p->rect.top() - rv.top() - p->viewRect.top();
1542 break;
1543 }
1544 if (! scroll)
1545 continue;
1546 // verify potential scroll
1547 QRect rs = widget->viewport()->rect();
1548 rs &= rs.translated(-dx,-dy);
1549 if (rs.isEmpty())
1550 continue;
1551 foreach(p, pageLayout)
1552 {
1553 QRect rect = p->rect.translated(-rv.topLeft());
1554 if (rs.intersects(p->viewRect))
1555 p->viewRect.translate(dx,dy);
1556 else
1557 p->viewRect = rect;
1558 if (rv.intersects(p->rect))
1559 if (p->viewRect != rect)
1560 scroll = false;
1561 }
1562 if (! scroll)
1563 continue;
1564 layoutChange &= ~UPDATE_PAGES;
1565 layoutChange &= ~UPDATE_ALL;
1566 dragStart += QPoint(dx,dy);
1567 selectedRect.translate(dx, dy);
1568 // Tooltips mess things up during scrolls
1569 QToolTip::showText(QPoint(),QString());
1570 // hourGlass messes things up too
1571 widget->setHourGlassRatio(0);
1572 // Attention: scroll can generate a paintEvent
1573 // and call makeLayout again. This is why we
1574 // do these four things before.
1575 widget->viewport()->scroll(dx,dy);
1576 checkCurrentMapArea();
1577 emit widget->layoutChanged();
1578 }
1579 else if (layoutChange & UPDATE_BORDERS)
1580 {
1581 Page *p;
1582 QRegion region = widget->viewport()->rect();
1583 foreach(p, pageVisible)
1584 region -= p->viewRect;
1585 layoutChange &= ~UPDATE_BORDERS;
1586 widget->viewport()->update(region);
1587 emit widget->layoutChanged();
1588 }
1589 else if (layoutChange & REFRESH_PAGES)
1590 {
1591 Page *p;
1592 bool changes = false;
1593 foreach(p, pageLayout)
1594 if (p->redisplay)
1595 {
1596 if (visibleRect.intersects(p->rect))
1597 widget->viewport()->update(p->viewRect);
1598 p->redisplay = false;
1599 changes = true;
1600 }
1601 if (changes)
1602 pixelCache.clear();
1603 layoutChange &= ~REFRESH_PAGES;
1604 }
1605 else
1606 {
1607 // deschedule
1608 if (layoutChange & ~SCHEDULED)
1609 qWarning("QDjVuWidget::makeLayout: unknown bits");
1610 layoutChange = 0;
1611 }
1612 }
1613 // deschedule
1614 layoutChange &= ~SCHEDULED;
1615 layoutChange |= futureLayoutChange;
1616 }
1617
1618
1619 // Make all page requests
1620 void
1621 QDjVuPrivate::makePageRequests(void)
1622 {
1623 Page *p;
1624 QRect &rv = visibleRect;
1625 bool found = false;
1626 if (! doc)
1627 return;
1628 // visible pages
1629 foreach(p, pageVisible)
1630 if (p && rv.intersects(p->rect))
1631 found |= requestPage(p);
1632 // search more if document is idle (prefetch/predecode)
1633 if (!found && !doc->runningProcesses())
1634 {
1635 if (continuous)
1636 {
1637 int sw = rv.width() / 2;
1638 int sh = rv.height() / 2;
1639 QRect brv = rv.adjusted(-sw,-sh,sw,sh);
1640 foreach(p, pageLayout)
1641 if (!p->page && brv.intersects(p->rect))
1642 found |= requestPage(p);
1643 }
1644 else if (pageVisible.size() > 0)
1645 {
1646 int pmin = pageVisible[0]->pageno;
1647 int pmax = pageVisible[0]->pageno;
1648 foreach(p, pageVisible)
1649 {
1650 pmax = qMax(pmax, p->pageno);
1651 pmin = qMin(pmin, p->pageno);
1652 }
1653 if (pmax+1 < numPages)
1654 found |= requestPage(&pageData[pmax+1]);
1655 if (! found && pmin-1 >= 0)
1656 found |= requestPage(&pageData[pmin-1]);
1657 if (! found && pmax+2 < numPages)
1658 found |= requestPage(&pageData[pmax+2]);
1659 if (! found && pmin-2 >= 0)
1660 found |= requestPage(&pageData[pmin-2]);
1661 }
1662 }
1663 }
1664
1665 // Obtain page annotations and hidden text if not present
1666 void
1667 QDjVuPrivate::getAnnotationsAndText(Page *p)
1668 {
1669 if (p->annotations == miniexp_dummy)
1670 {
1671 p->annotations = doc->getPageAnnotations(p->pageno);
1672 if (p->annotations)
1673 if (pageLayout.size() > 0 && p == pageLayout[0])
1674 adjustSettings(PRIORITY_ANNO, p->annotations);
1675 if (p->annotations)
1676 prepareMapAreas(p);
1677 }
1678 if (p->hiddenText == miniexp_dummy)
1679 {
1680 miniexp_t expr = doc->getPageText(p->pageno);
1681 if (expr != miniexp_dummy)
1682 p->hiddenText = flatten_hiddentext(expr);
1683 }
1684 }
1685
1686
1687 // Create the page decoder and connects its slots.
1688 bool
1689 QDjVuPrivate::requestPage(Page *p)
1690 {
1691 bool result = false;
1692 if (! p->page)
1693 {
1694 // create and connect page
1695 p->page = new QDjVuPage(doc, p->pageno);
1696 connect(p->page, SIGNAL(pageinfo()),
1697 this, SLOT(pageinfoPage()));
1698 connect(p->page, SIGNAL(redisplay()),
1699 this, SLOT(redisplayPage()));
1700 connect(p->page, SIGNAL(error(QString,QString,int)),
1701 this, SLOT(error(QString,QString,int)) );
1702 connect(p->page, SIGNAL(info(QString)),
1703 this, SLOT(info(QString)) );
1704 if (! p->page->isValid())
1705 emit widget->errorCondition(p->pageno);
1706 // decoded page found in the cache (needed with djvulibre <= 3.5.27)
1707 if (ddjvu_page_decoding_status(*(p->page)) >= DDJVU_JOB_OK)
1708 pageinfoPage(p->page);
1709 // schedule redisplay
1710 p->redisplay = true;
1711 changeLayout(REFRESH_PAGES);
1712 result = true;
1713 }
1714 if (! p->infoNeeded)
1715 {
1716 p->infoNeeded = true;
1717 changeLayout(CHANGE_SIZE);
1718 }
1719 getAnnotationsAndText(p);
1720 return result;
1721 }
1722
1723
1724 // finds closest page to a point in desk coordinates
1725 int
1726 QDjVuPrivate::findClosestPage(const QPoint &deskPoint,
1727 const QList<Page*> &pages,
1728 Page **pp, int *pd)
1729 {
1730 Page *p;
1731 Page *bestPage = 0;
1732 int bestDistance = 0;
1733 foreach(p, pages)
1734 {
1735 int distance = 0;
1736 if (deskPoint.y() < p->rect.top())
1737 distance += p->rect.top() - deskPoint.y();
1738 else if (deskPoint.y() > p->rect.bottom() - 1)
1739 distance += deskPoint.y() - p->rect.bottom() + 1;
1740 if (deskPoint.x() < p->rect.left())
1741 distance += p->rect.left() - deskPoint.x();
1742 else if (deskPoint.x() > p->rect.right() - 1)
1743 distance += deskPoint.x() - p->rect.right() + 1;
1744 if (bestPage==0 || distance<bestDistance)
1745 {
1746 bestPage = p;
1747 bestDistance = distance;
1748 if (! bestDistance)
1749 break;
1750 }
1751 }
1752 if (! bestPage)
1753 return -1;
1754 if (pp)
1755 *pp = bestPage;
1756 if (pd)
1757 *pd = bestDistance;
1758 return bestPage->pageno;
1759 }
1760
1761 // compute Position for a given viewport point.
1762 Position
1763 QDjVuPrivate::findPosition(const QPoint &point, bool closestAnchor)
1764 {
1765 Position pos;
1766 Page *bestPage = 0;
1767 int bestDistance = 0;
1768 QPoint deskPoint = visibleRect.topLeft() + point;
1769 findClosestPage(deskPoint, pageVisible, &bestPage, &bestDistance);
1770 if (! bestPage)
1771 findClosestPage(deskPoint, pageLayout, &bestPage, &bestDistance);
1772 if (bestPage)
1773 {
1774 pos.pageNo = bestPage->pageno;
1775 pos.posView = deskPoint - bestPage->rect.topLeft();
1776 pos.posPage = bestPage->mapper.unMapped(deskPoint);
1777 pos.inPage = (bestDistance == 0 && bestPage->dpi > 0);
1778 if (closestAnchor)
1779 {
1780 int w = bestPage->rect.width() - 1;
1781 int h = bestPage->rect.height() - 1;
1782 pos.hAnchor = 100 * qBound(0, pos.posView.x(), w) / w;
1783 pos.vAnchor = 100 * qBound(0, pos.posView.y(), h) / h;
1784 int x = w * pos.hAnchor / 100;
1785 int y = h * pos.vAnchor / 100;
1786 pos.posView = pos.posView - QPoint(x,y);
1787 }
1788 }
1789 return pos;
1790 }
1791
1792 // when the pointer moves
1793 void
1794 QDjVuPrivate::updatePosition(const QPoint &point, bool click, bool links)
1795 {
1796 if (point.isNull())
1797 return;
1798 // locate
1799 bool changed = false;
1800 cursorPoint = point;
1801 Position pos = findPosition(point);
1802 if (! pageMap.contains(pos.pageNo))
1803 return;
1804 if (pos.pageNo != cursorPos.pageNo ||
1805 pos.inPage != cursorPos.inPage ||
1806 pos.posView != cursorPos.posView ||
1807 pos.posPage != cursorPos.posPage )
1808 changed = true;
1809 // update
1810 cursorPos = pos;
1811 if (click)
1812 updateCurrentPoint(pos);
1813 if (! changed)
1814 return;
1815 // emit pointerposition signal
1816 PageInfo info;
1817 Page *p = pageMap.value(pos.pageNo,0);
1818 if (p != 0)
1819 {
1820 info.pageno = pos.pageNo;
1821 info.width = p->width;
1822 info.height = p->height;
1823 info.dpi = p->dpi;
1824 info.segment = widget->getSegmentForRect(selectedRect, info.pageno);
1825 info.selected = selectedRect;
1826 emit widget->pointerPosition(pos, info);
1827 }
1828 // check mapareas
1829 if (links)
1830 checkCurrentMapArea();
1831 }
1832
1833
1834 // when the view moves
1835 void
1836 QDjVuPrivate::updateCurrentPoint(const Position &pos)
1837 {
1838 QPoint point;
1839 bool changePos = !pos.doPage;
1840 if (pageMap.contains(pos.pageNo))
1841 {
1842 Page *p = pageMap[pos.pageNo];
1843 point = p->rect.topLeft();
1844 if (pos.hAnchor > 0 && pos.hAnchor <= 100)
1845 point.rx() += (p->rect.width() - 1) * pos.hAnchor / 100;
1846 if (pos.vAnchor > 0 && pos.vAnchor <= 100)
1847 point.ry() += (p->rect.height() - 1) * pos.vAnchor / 100;
1848 if (pos.inPage && p->dpi > 0)
1849 point = p->mapper.mapped(pos.posPage);
1850 else if (!pos.inPage)
1851 point += pos.posView;
1852 }
1853 else
1854 {
1855 int n = pageLayout.size();
1856 if (n > 0 && pos.pageNo < pageLayout[0]->pageno)
1857 point = pageLayout[0]->rect.topLeft();
1858 else if (n > 0 && pos.pageNo > pageLayout[n-1]->pageno)
1859 point = pageLayout[n-1]->rect.bottomRight();
1860 }
1861 // check visibility
1862 if (! visibleRect.contains(point))
1863 {
1864 changePos = true;
1865 point.ry() = qBound(visibleRect.top() + borderSize,
1866 point.y(),
1867 visibleRect.bottom() - borderSize);
1868 point.rx() = qBound(visibleRect.left() + borderSize,
1869 point.x(),
1870 visibleRect.right() - borderSize);
1871 }
1872 // update currentPoint
1873 currentPoint = point - visibleRect.topLeft();
1874 // update currentPos
1875 int oldPage = currentPos.pageNo;
1876 if (changePos || pos.hAnchor || pos.vAnchor)
1877 currentPos = findPosition(currentPoint);
1878 else
1879 currentPos = pos;
1880 if (oldPage != currentPos.pageNo)
1881 emit widget->pageChanged(currentPos.pageNo);
1882 }
1883
1884
1885 // ----------------------------------------
1886 // QDJVUPRIVATE SLOTS
1887
1888 void
1889 QDjVuPrivate::docinfo()
1890 {
1891 ddjvu_status_t status;
1892 status = ddjvu_document_decoding_status(*doc);
1893 if (status == DDJVU_JOB_OK && !docReady)
1894 {
1895 docReady = true;
1896 numPages = ddjvu_document_get_pagenum(*doc);
1897 pageData.clear();
1898 pageData.resize(numPages);
1899 for (int i=0; i<numPages; i++)
1900 pageData[i].pageno = i;
1901 changeLayout(CHANGE_PAGES|UPDATE_ALL);
1902 // request first page immediately
1903 if (numPages > 0)
1904 requestPage((pageMap[0] = &pageData[0]));
1905 }
1906 else if (status == DDJVU_JOB_STOPPED && !docStopped)
1907 {
1908 docStopped = true;
1909 emit widget->stopCondition(-1);
1910 widget->viewport()->update();
1911 }
1912 else if (status == DDJVU_JOB_FAILED && !docFailed)
1913 {
1914 docFailed = true;
1915 emit widget->errorCondition(-1);
1916 widget->viewport()->update();
1917 }
1918 }
1919
1920 void
1921 QDjVuPrivate::pageinfo()
1922 {
1923 changeLayout(CHANGE_SIZE, 250);
1924 }
1925
1926 void
1927 QDjVuPrivate::pageinfoPage()
1928 {
1929 QObject *send = sender();
1930 pageinfoPage(qobject_cast<QDjVuPage*>(send));
1931 }
1932
1933 void
1934 QDjVuPrivate::pageinfoPage(QDjVuPage *page)
1935 {
1936 if (page)
1937 {
1938 Page *p = 0;
1939 int pageno = page->pageNo();
1940 if (pageno>=0 && pageno<pageData.size())
1941 p = &pageData[pageno];
1942 // decoding finished?
1943 switch(ddjvu_page_decoding_status(*page))
1944 {
1945 case DDJVU_JOB_OK:
1946 if (p)
1947 getAnnotationsAndText(p);
1948 /* FALLTHRU */
1949 case DDJVU_JOB_STARTED:
1950 if (p && p->dpi <= 0)
1951 {
1952 ddjvu_page_rotation_t rot;
1953 rot = ddjvu_page_get_initial_rotation(*page);
1954 ddjvu_page_set_rotation(*page, rot);
1955 int w = ddjvu_page_get_width(*page);
1956 int h = ddjvu_page_get_height(*page);
1957 int d = ddjvu_page_get_resolution(*page);
1958 if (d > 0 && w > 0 && h > 0)
1959 {
1960 p->width = w;
1961 p->height = h;
1962 p->dpi = d;
1963 p->initialRot = rot;
1964 changeLayout(CHANGE_STATS|CHANGE_SCALE|UPDATE_BORDERS);
1965 }
1966 }
1967 break;
1968 case DDJVU_JOB_STOPPED:
1969 docStopped = true;
1970 emit widget->stopCondition(page->pageNo());
1971 break;
1972 case DDJVU_JOB_FAILED:
1973 emit widget->errorCondition(page->pageNo());
1974 break;
1975 default:
1976 break;
1977 }
1978 }
1979 }
1980
1981 void
1982 QDjVuPrivate::redisplayPage()
1983 {
1984 QObject *send = sender();
1985 QDjVuPage *page = qobject_cast<QDjVuPage*>(send);
1986 if (page)
1987 {
1988 int pageno = page->pageNo();
1989 if (pageMap.contains(pageno))
1990 {
1991 Page *p = pageMap[pageno];
1992 if (p && !p->redisplay)
1993 {
1994 p->redisplay = true;
1995 changeLayout(REFRESH_PAGES);
1996 }
1997 }
1998 }
1999 }
2000
2001 void
2002 QDjVuPrivate::error(QString message, QString filename, int lineno)
2003 {
2004 emit widget->error(message, filename, lineno);
2005 errorMessages.prepend(message);
2006 while (errorMessages.size() > maxMessages)
2007 errorMessages.removeLast();
2008 }
2009
2010 void
2011 QDjVuPrivate::info(QString message)
2012 {
2013 emit widget->info(message);
2014 infoMessages.prepend(message);
2015 while (infoMessages.size() > maxMessages)
2016 infoMessages.removeLast();
2017 }
2018
2019
2020
2021 // ----------------------------------------
2022 // QDJVUWIDGET
2023
2024
2025 /*! \class QDjVuWidget
2026 \brief Widget for display DjVu documents.
2027
2028 Class \a QDjVuWidget implements the elementary widget for displaying DjVu
2029 documents. It appears as a display area possibly surrounded by horizontal
2030 and vertical scrollbars. The display area can show a single page, two pages
2031 side by side, or all pages in continuously scrollable area. */
2032
2033 QDjVuWidget::~QDjVuWidget()
2034 {
2035 delete priv;
2036 priv = 0;
2037 }
2038
2039 // This is a helper for the constructors
2040 void
2041 QDjVuPrivate::initWidget(bool opengl)
2042 {
2043 // set widget policies
2044 widget->setFocusPolicy(Qt::StrongFocus);
2045 widget->setSizePolicy(QSizePolicy::MinimumExpanding,
2046 QSizePolicy::MinimumExpanding);
2047 // set opengl acceleration
2048 #if QT_VERSION >= 0x040400
2049 if (opengl)
2050 {
2051 const char *ge = 0;
2052 #ifdef QT_OPENGL_LIB
2053 QGLWidget *gw = 0;
2054 if (! QGLFormat::hasOpenGL())
2055 ge = "cannot find openGL on this system";
2056 if (!ge)
2057 gw = new QGLWidget();
2058 if (gw && !ge && !gw->isValid())
2059 ge = "cannot setup openGL context";
2060 if (gw && !ge && !gw->format().directRendering())
2061 ge = "cannot setup openGL direct rendering";
2062 if (gw && !ge) {
2063 gw->setFocusPolicy(Qt::ClickFocus);
2064 widget->setViewport(gw);
2065 } else if (gw)
2066 delete gw;
2067 #else
2068 ge = "disabled at compilation time";
2069 #endif
2070 if (!ge)
2071 qWarning("Using openGL rendering");
2072 else
2073 qWarning("Using default rendering (%s)", ge);
2074 }
2075 #endif
2076 // setup viewport
2077 QWidget *vp = widget->viewport();
2078 #if QT_VERSION >= 0x50000
2079 vp->setAttribute(Qt::WA_OpaquePaintEvent);
2080 #elif QT_VERSION >= 0x040100
2081 vp->setAttribute(Qt::WA_OpaquePaintEvent);
2082 vp->setAttribute(Qt::WA_NativeWindow);
2083 #else
2084 vp->setAttribute(Qt::WA_StaticContents);
2085 vp->setAttribute(Qt::WA_NoSystemBackground);
2086 vp->setAttribute(Qt::WA_NativeWindow);
2087 #endif
2088 #if QT_VERSION >= 0x040600
2089 vp->grabGesture(Qt::PinchGesture);
2090 #endif
2091 vp->setMouseTracking(true);
2092 }
2093
2094 /*! Construct a \a QDjVuWidget instance.
2095 Argument \a parent is the parent of this widget
2096 in the \a QObject hierarchy. Setting argument
2097 \a opengl to true enables openGL acceleration */
2098
2099 QDjVuWidget::QDjVuWidget(bool opengl, QWidget *parent)
2100 : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
2101 {
2102 priv->initWidget(opengl);
2103 }
2104
2105 /*! Overloaded constructor */
2106
2107 QDjVuWidget::QDjVuWidget(QWidget *parent)
2108 : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
2109 {
2110 priv->initWidget(false);
2111 }
2112
2113 /*! This overloaded constructor calls \a setDocument. */
2114
2115 QDjVuWidget::QDjVuWidget(QDjVuDocument *doc, bool opengl, QWidget *parent)
2116 : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
2117 {
2118 priv->initWidget(opengl);
2119 setDocument(doc);
2120 }
2121
2122 /*! This overloaded constructor calls \a setDocument. */
2123
2124 QDjVuWidget::QDjVuWidget(QDjVuDocument *doc, QWidget *parent)
2125 : QAbstractScrollArea(parent), priv(new QDjVuPrivate(this))
2126 {
2127 priv->initWidget(false);
2128 setDocument(doc);
2129 }
2130
2131
2132 // ----------------------------------------
2133 // MESSAGE
2134
2135
2136 /*! Return one of the last error messages.
2137 Argument \a n indicates which message should be returned.
2138 Value 0 corresponds to the most recent message.
2139 */
2140
2141 QString
2142 QDjVuWidget::pastErrorMessage(int n)
2143 {
2144 if (0 <= n && n < priv->errorMessages.size())
2145 return priv->errorMessages.at(n);
2146 return QString();
2147 }
2148
2149 /*! Return one of the last informational messages.
2150 Argument \a n indicates which message should be returned.
2151 Value 0 corresponds to the most recent message.
2152 */
2153
2154 QString
2155 QDjVuWidget::pastInfoMessage(int n)
2156 {
2157 if (0 <= n && n < priv->infoMessages.size())
2158 return priv->infoMessages.at(n);
2159 return QString();
2160 }
2161
2162
2163
2164
2165 // ----------------------------------------
2166 // QDJVUWIDGET PROPERTIES
2167
2168
2169 /*! \property QDjVuWidget::document
2170 The \a QDjVuDocument object shown in this widget. */
2171
2172 QDjVuDocument *
2173 QDjVuWidget::document(void) const
2174 {
2175 return priv->doc;
2176 }
2177
2178 /*! Specify the \a QDjVuDocument shown by this widget.
2179 The caller is responsible to ensure that the
2180 document object \a d remains allocated until
2181 the djvu widget is either destroyed or directed
2182 to use another document.
2183 Two techniques are interesting:
2184 The first consists of capturing the document signal \a destroyed()
2185 and to call \a setDocument(0) before the destruction occurs.
2186 The second consists of allocating the document object
2187 in \a autoDelete mode, since the djvu widget calls
2188 methods \a ref() and \a deref() adequately. */
2189
2190 void
2191 QDjVuWidget::setDocument(QDjVuDocument *d)
2192 {
2193 if (d != priv->doc)
2194 {
2195 // cleanup
2196 if (priv->doc)
2197 {
2198 priv->adjustSettings(PRIORITY_ANNO, miniexp_nil);
2199 priv->adjustSettings(PRIORITY_CGI, miniexp_nil);
2200 disconnect(priv->doc, 0, priv, 0);
2201 priv->doc->deref();
2202 }
2203 priv->doc = 0;
2204 priv->pageData.clear();
2205 priv->pageLayout.clear();
2206 priv->pageMap.clear();
2207 priv->pageVisible.clear();
2208 priv->currentMapAreaPage = 0;
2209 priv->currentMapArea = 0;
2210 priv->dragMode = DRAG_NONE;
2211 delete priv->lens;
2212 priv->lens = 0;
2213 // setup
2214 if (d)
2215 d->ref();
2216 priv->doc = d;
2217 priv->docReady = false;
2218 priv->docStopped = false;
2219 priv->docFailed = false;
2220 priv->numPages = 1;
2221 if (! (priv->doc && priv->doc->isValid()))
2222 priv->docFailed = true;
2223 // connect
2224 if (priv->doc)
2225 {
2226 connect(priv->doc, SIGNAL(docinfo()),
2227 priv, SLOT(docinfo()));
2228 connect(priv->doc, SIGNAL(pageinfo()),
2229 priv, SLOT(pageinfo()));
2230 connect(priv->doc, SIGNAL(error(QString,QString,int)),
2231 priv, SLOT(error(QString,QString,int)));
2232 connect(priv->doc, SIGNAL(info(QString)),
2233 priv, SLOT(info(QString)));
2234 connect(priv->doc, SIGNAL(idle()),
2235 priv, SLOT(makePageRequests()));
2236 // the document may already be ready
2237 QTimer::singleShot(0, priv, SLOT(docinfo()));
2238 }
2239 // update
2240 priv->estimatedWidth = 0;
2241 priv->estimatedHeight = 0;
2242 priv->visibleRect.setRect(0,0,0,0);
2243 priv->currentPos = Position();
2244 priv->currentPoint = QPoint(priv->borderSize,priv->borderSize);
2245 priv->cursorPos = Position();
2246 priv->cursorPoint = QPoint(0,0);
2247 priv->layoutChange = 0;
2248 priv->changeLayout(CHANGE_STATS|CHANGE_PAGES|UPDATE_ALL);
2249 }
2250 }
2251
2252 /*! \property QDjVuWidget::page
2253 The page currently displayed.
2254 When getting the property, this is the number of the page
2255 that is closest to the center of the display area.
2256 When setting the property, the topleft corner of the
2257 desired page replaces the topleft corner of the current page.
2258 Default: page 0.
2259 */
2260
2261 int
2262 QDjVuWidget::page(void) const
2263 {
2264 return qBound(0, priv->currentPos.pageNo, priv->numPages);
2265 }
2266
2267 void
2268 QDjVuWidget::setPage(int n, bool keep)
2269 {
2270 int currentPageNo = page();
2271 if (n != currentPageNo && n>=0 && n<priv->numPages)
2272 {
2273 Position pos;
2274 QPoint pnt(priv->borderSize, priv->borderSize);
2275 if (keep)
2276 {
2277 pnt = priv->currentPoint;
2278 pos = priv->findPosition(pnt);
2279 }
2280 pos.pageNo = n;
2281 pos.doPage = true;
2282 pos.inPage = false;
2283 setPosition(pos, pnt);
2284 }
2285 }
2286
2287 /*! \property QDjVuWidget::position
2288 The document position associated with a viewport point.
2289 The default point is close to the topLeft corner of the viewport.
2290 When setting the position, flag \a Position::inPage
2291 is used to determine if the document position is expressed
2292 in full resolution page coordinates (\a Position::posPage) or
2293 in pixels relative to the top left page corner (\a Position::posView)
2294 or the point specified by the \a Position::hAnchor
2295 and \a Position::vAnchor.
2296 When \a Position::inPage is \a true,
2297 variable \a Position::posPage must be contained inside
2298 the full resolution page rectangle.
2299 */
2300
2301 Position
2302 QDjVuWidget::position(void) const
2303 {
2304 QPoint topLeft(priv->borderSize, priv->borderSize);
2305 return position(topLeft);
2306 }
2307
2308
2309 QPoint
2310 QDjVuWidget::hotSpot() const
2311 {
2312 return priv->currentPoint;
2313 }
2314
2315
2316 Position
2317 QDjVuWidget::position(const QPoint &point) const
2318 {
2319 return priv->findPosition(point);
2320 }
2321
2322 void
2323 QDjVuWidget::setPosition(const Position &pos)
2324 {
2325 QPoint topLeft(priv->borderSize, priv->borderSize);
2326 setPosition(pos, topLeft);
2327 }
2328
2329 void
2330 QDjVuWidget::setPosition(const Position &pos, const QPoint &p, bool animate)
2331 {
2332 // animation
2333 priv->clearAnimation();
2334 if (animate && priv->animationEnabled)
2335 if (priv->computeAnimation(pos, p))
2336 return;
2337 // standard procedure
2338 priv->movePoint = p;
2339 priv->movePos = pos;
2340 if (priv->pageMap.contains(pos.pageNo))
2341 priv->changeLayout(CHANGE_VIEW|CHANGE_SCROLLBARS);
2342 else
2343 priv->changeLayout(CHANGE_PAGES|CHANGE_VIEW|CHANGE_SCROLLBARS);
2344 }
2345
2346
2347 /*! Unlike \a position() which sets the anchor fields
2348 \a pos.hAnchor and \a pos.vAnchor to zero,
2349 this version determines where to place the anchor
2350 to minimize the length of vector \a pos.posView. */
2351
2352 Position
2353 QDjVuWidget::positionWithClosestAnchor(const QPoint &point) const
2354 {
2355 return priv->findPosition(point, true);
2356 }
2357
2358
2359 /*! \property QDjVuWidget::rotation
2360 Number of counter-clockwise quarter turns applied to the pages.
2361 Only the low two bits of this number are meaningful.
2362 Default: 0. */
2363
2364 int
2365 QDjVuWidget::rotation(void) const
2366 {
2367 return priv->rotation;
2368 }
2369
2370 void
2371 QDjVuWidget::setRotation(int r)
2372 {
2373 if (r != priv->rotation)
2374 {
2375 priv->rotation = r;
2376 priv->changeLayout(CHANGE_SCALE|UPDATE_ALL);
2377 }
2378 }
2379
2380 /*! \property QDjVuWidget::zoom
2381 Zoom factor applied to the pages.
2382 Positive zoom factors take into account the resolution
2383 of the page images and assumes that the display resolution
2384 is 100 dpi. Negative zoom factors define special behaviors:
2385 \a ZOOM_ONE2ONE displays one image pixel for one screen pixel.
2386 \a ZOOM_FITWIDTH and \a ZOOM_FITPAGE dynamically compute
2387 the zoom factor to fit the page(s) inside the display area.
2388 Default: \a ZOOM_100.
2389
2390 */
2391
2392 int
2393 QDjVuWidget::zoom(void) const
2394 {
2395 return priv->zoom;
2396 }
2397
2398 void
2399 QDjVuWidget::setZoom(int z)
2400 {
2401 priv->qZoom.set(PRIORITY_USER, z);
2402 priv->changeZoom();
2403 }
2404
2405 void
2406 QDjVuPrivate::changeZoom(void)
2407 {
2408 int z = qZoom;
2409 switch(z)
2410 {
2411 case ZOOM_STRETCH:
2412 case ZOOM_ONE2ONE:
2413 case ZOOM_FITWIDTH:
2414 case ZOOM_FITPAGE:
2415 break;
2416 default:
2417 z = qBound((int)ZOOM_MIN, z, (int)ZOOM_MAX);
2418 break;
2419 }
2420 if (zoom != z)
2421 {
2422 zoom = z;
2423 changeLayout(CHANGE_SCALE|UPDATE_ALL);
2424 }
2425 }
2426
2427
2428 /*! Return the effective zoom factor of the current page.
2429 This is the same as \a zoom() when the zoom factor is positive.
2430 Otherwise this function returns the dynamically computed
2431 zoom factor. */
2432
2433 int
2434 QDjVuWidget::zoomFactor(void) const
2435 {
2436 if (priv->zoom >= ZOOM_MIN && priv->zoom <= ZOOM_MAX)
2437 return priv->zoom;
2438 if (priv->zoomFactor >= ZOOM_MIN && priv->zoomFactor <= ZOOM_MAX)
2439 return priv->zoomFactor;
2440 // Only when ZOOM_ONE2ONE or ZOOM_STRETCH is selected:
2441 priv->makeLayout();
2442 if (! priv->pageMap.contains(priv->currentPos.pageNo))
2443 return 100;
2444 Page *p = priv->pageMap[priv->currentPos.pageNo];
2445 if (p->dpi>0 && p->width>0)
2446 return (p->rect.width() * p->dpi * 100) / (p->width * priv->sdpi);
2447 return 100;
2448 }
2449
2450 /*! \property QDjVuWidget::gamma
2451 Gamma factor of the display.
2452 Default 2.2. */
2453
2454 double
2455 QDjVuWidget::gamma(void) const
2456 {
2457 return priv->gamma;
2458 }
2459
2460 void
2461 QDjVuWidget::setGamma(double gamma)
2462 {
2463 priv->gamma = gamma;
2464 ddjvu_format_set_gamma(priv->renderFormat, gamma);
2465 priv->pixelCache.clear();
2466 priv->changeLayout(UPDATE_ALL);
2467 }
2468
2469
2470 /*! \property QDjVuWidget::invertLuminance
2471 Display image with inverted luminance.
2472 */
2473
2474
2475 bool
2476 QDjVuWidget::invertLuminance(void) const
2477 {
2478 return priv->invertLuminance;
2479 }
2480
2481 void
2482 QDjVuWidget::setInvertLuminance(bool b)
2483 {
2484 priv->invertLuminance = b;
2485 priv->pixelCache.clear();
2486 priv->changeLayout(UPDATE_ALL);
2487 }
2488
2489 /*! \property QDjVuWidget::invertLuminance
2490 Specify whether mouse wheel zooms the image or scrolls the page.
2491 */
2492
2493 bool
2494 QDjVuWidget::mouseWheelZoom(void) const
2495 {
2496 return priv->mouseWheelZoom;
2497 }
2498
2499 void
2500 QDjVuWidget::setMouseWheelZoom(bool b)
2501 {
2502 priv->mouseWheelZoom = b;
2503 }
2504
2505
2506 /*! \property QDjVuWidget::white
2507 White point of the display.
2508 This is a noop when DDJVUAPI_VERSION<20.
2509 Default 0xffffff. */
2510
2511 QColor
2512 QDjVuWidget::white(void) const
2513 {
2514 return priv->white;
2515 }
2516
2517 void
2518 QDjVuWidget::setWhite(QColor w)
2519 {
2520 #if DDJVUAPI_VERSION >= 20
2521 priv->white = w;
2522 ddjvu_format_set_white(priv->renderFormat, w.blue(), w.green(), w.red());
2523 priv->pixelCache.clear();
2524 priv->changeLayout(UPDATE_ALL);
2525 #endif
2526 }
2527
2528
2529 /*! \property QDjVuWidget::screenDpi
2530 Resolution of the screen.
2531 Default is 100dpi. */
2532
2533 int
2534 QDjVuWidget::screenDpi(void) const
2535 {
2536 return priv->sdpi;
2537 }
2538
2539 void
2540 QDjVuWidget::setScreenDpi(int sdpi)
2541 {
2542 sdpi = qBound(25, sdpi, 600);
2543 if (priv->sdpi != sdpi)
2544 {
2545 priv->sdpi = sdpi;
2546 priv->changeLayout(CHANGE_SCALE|UPDATE_ALL);
2547 }
2548 }
2549
2550
2551 /*! \property QDjVuWidget::displayMode
2552 Display mode for the DjVu images.
2553 Default: \a DISPLAY_COLOR. */
2554
2555
2556 DisplayMode
2557 QDjVuWidget::displayMode(void) const
2558 {
2559 return priv->display;
2560 }
2561
2562 void
2563 QDjVuWidget::setDisplayMode(DisplayMode m)
2564 {
2565 priv->qDisplay.set(PRIORITY_USER, m);
2566 priv->changeDisplay();
2567 }
2568
2569 void
2570 QDjVuPrivate::changeDisplay()
2571 {
2572 if (display != qDisplay)
2573 {
2574 display = qDisplay;
2575 pixelCache.clear();
2576 changeLayout(UPDATE_ALL);
2577 }
2578 }
2579
2580 /*! \property QDjVuWidget::displayFrame
2581 When this property is true, a frame
2582 is displayed around each page.
2583 Default: \a true. */
2584
2585 bool
2586 QDjVuWidget::displayFrame(void) const
2587 {
2588 return priv->frame;
2589 }
2590
2591 void
2592 QDjVuWidget::setDisplayFrame(bool b)
2593 {
2594 if (b != priv->frame)
2595 {
2596 priv->frame = b;
2597 priv->changeLayout(UPDATE_ALL);
2598 }
2599 }
2600
2601 /*! \property QDjVuWidget::sideBySide
2602 Determine the layout of the pages shown in the displayed area.
2603 Setting this property to \a true displays pages side by side.
2604 This can be combined with the \a continuous property.
2605 Default: \a false. */
2606
2607 bool
2608 QDjVuWidget::sideBySide(void) const
2609 {
2610 return priv->sideBySide;
2611 }
2612
2613 void
2614 QDjVuWidget::setSideBySide(bool b)
2615 {
2616 if (b != priv->sideBySide)
2617 {
2618 priv->sideBySide = b;
2619 priv->changeLayout(CHANGE_PAGES|UPDATE_ALL);
2620 }
2621 }
2622
2623 /*! \property QDjVuWidget::coverPage
2624 Determine whether the first page must be show alone when
2625 multipage documents are displayed side-by-side.
2626 Default: \a false. */
2627
2628 bool
2629 QDjVuWidget::coverPage(void) const
2630 {
2631 return priv->coverPage;
2632 }
2633
2634 void
2635 QDjVuWidget::setCoverPage(bool b)
2636 {
2637 if (b != priv->coverPage)
2638 {
2639 priv->coverPage = b;
2640 if (priv->sideBySide)
2641 priv->changeLayout(CHANGE_PAGES|UPDATE_ALL);
2642 }
2643 }
2644
2645
2646 /*! \property QDjVuWidget::rightToLeft
2647 Determine whether the side-by-side pages should be displayed
2648 right-to-left instead of left-to-right.
2649 Default: \a false. */
2650
2651 bool
2652 QDjVuWidget::rightToLeft(void) const
2653 {
2654 return priv->rightToLeft;
2655 }
2656
2657 void
2658 QDjVuWidget::setRightToLeft(bool b)
2659 {
2660 if (b != priv->rightToLeft)
2661 {
2662 priv->rightToLeft = b;
2663 if (priv->sideBySide)
2664 priv->changeLayout(CHANGE_PAGES|UPDATE_ALL);
2665 }
2666 }
2667
2668
2669
2670 /*! \property QDjVuWidget::continuous
2671 Determine the layout of the pages shown in the displayed area.
2672 Setting this property to \a true displays all the document
2673 pages in a continuously scrollable area. This can be combined
2674 with the \a sideBySide property. Default: \a false. */
2675
2676
2677 bool
2678 QDjVuWidget::continuous(void) const
2679 {
2680 return priv->continuous;
2681 }
2682
2683 void
2684 QDjVuWidget::setContinuous(bool b)
2685 {
2686 if (b != priv->continuous)
2687 {
2688 priv->continuous = b;
2689 priv->changeLayout(CHANGE_PAGES|UPDATE_ALL);
2690 }
2691 }
2692
2693 /*! \property QDjVuWidget::horizAlign
2694 Determine the horizontal alignment of the pages in the display area.
2695 Horizontal alignment can be complicated in continuous mode.
2696 Default: \a ALIGN_CENTER. */
2697
2698 Align
2699 QDjVuWidget::horizAlign(void) const
2700 {
2701 return priv->hAlign;
2702 }
2703
2704 void
2705 QDjVuWidget::setHorizAlign(Align a)
2706 {
2707 priv->qHAlign.set(PRIORITY_USER, a);
2708 priv->changeHAlign();
2709 }
2710
2711 void
2712 QDjVuPrivate::changeHAlign(void)
2713 {
2714 if (hAlign != qHAlign)
2715 {
2716 hAlign = qHAlign;
2717 changeLayout(CHANGE_POSITIONS);
2718 }
2719 }
2720
2721 /*! \property QDjVuWidget::vertAlign
2722 Determine the vertical alignment of the pages in the display area.
2723 Vertical alignment can be very subtle in continuous mode
2724 because it only matters when pages are also displayed side by side.
2725 Default: \a ALIGN_CENTER. */
2726
2727 Align
2728 QDjVuWidget::vertAlign(void) const
2729 {
2730 return priv->vAlign;
2731 }
2732
2733 void
2734 QDjVuWidget::setVertAlign(Align a)
2735 {
2736 priv->qVAlign.set(PRIORITY_USER, a);
2737 priv->changeVAlign();
2738 }
2739
2740 void
2741 QDjVuPrivate::changeVAlign(void)
2742 {
2743 if (vAlign != qVAlign)
2744 {
2745 vAlign = qVAlign;
2746 changeLayout(CHANGE_POSITIONS);
2747 }
2748 }
2749
2750 /*! \property QDjVuWidget::borderBrush
2751 Brush used to fill the part of the
2752 display area that is not covered by a page.
2753 Default: light gray. */
2754
2755 QBrush
2756 QDjVuWidget::borderBrush(void) const
2757 {
2758 return priv->borderBrush;
2759 }
2760
2761 void
2762 QDjVuWidget::setBorderBrush(QBrush b)
2763 {
2764 priv->qBorderBrush.set(PRIORITY_USER, b);
2765 priv->changeBorderBrush();
2766 }
2767
2768 void
2769 QDjVuPrivate::changeBorderBrush(void)
2770 {
2771 if (borderBrush != qBorderBrush)
2772 {
2773 borderBrush = qBorderBrush;
2774 changeLayout(UPDATE_BORDERS);
2775 }
2776 }
2777
2778
2779 /*! \property QDjVuWidget::borderSize
2780 The minimal size of the border around the pages.
2781 Default: 8 pixels. */
2782
2783
2784 int
2785 QDjVuWidget::borderSize(void) const
2786 {
2787 return priv->borderSize;
2788 }
2789
2790 void
2791 QDjVuWidget::setBorderSize(int b)
2792 {
2793 priv->qBorderSize.set(PRIORITY_USER, b);
2794 priv->changeBorderSize();
2795 }
2796
2797 void
2798 QDjVuPrivate::changeBorderSize(void)
2799 {
2800 if (borderSize != qBorderSize)
2801 {
2802 borderSize = qBorderSize;
2803 changeLayout(CHANGE_POSITIONS);
2804 }
2805 }
2806
2807
2808 /*! \property QDjVuWidget::separatorSize
2809 The size of the gap between pages in side-by-side mode.
2810 Default: 12 pixels. */
2811
2812
2813 int
2814 QDjVuWidget::separatorSize(void) const
2815 {
2816 return priv->separatorSize;
2817 }
2818
2819 void
2820 QDjVuWidget::setSeparatorSize(int b)
2821 {
2822 b = qMax(0, b);
2823 if (b != priv->separatorSize)
2824 {
2825 priv->separatorSize = b;
2826 if (priv->sideBySide || priv->continuous)
2827 priv->changeLayout(CHANGE_PAGES|UPDATE_ALL);
2828 }
2829 }
2830
2831
2832
2833 /*! \property QDjVuWidget::contextMenu
2834 Menu displayed when the user invokes a context menu for this widget.
2835 Default: no context menu. */
2836
2837 QMenu*
2838 QDjVuWidget::contextMenu(void) const
2839 {
2840 return priv->contextMenu;
2841 }
2842
2843 void
2844 QDjVuWidget::setContextMenu(QMenu *m)
2845 {
2846 priv->contextMenu = m;
2847 }
2848
2849
2850 /*! \property QDjVuWidget::displayMapAreas
2851 Indicates whether the mapareas specified in the annotations
2852 should be displayed. Default: \a true. */
2853
2854 bool
2855 QDjVuWidget::displayMapAreas(void) const
2856 {
2857 return priv->displayMapAreas;
2858 }
2859
2860 void
2861 QDjVuWidget::setDisplayMapAreas(bool b)
2862 {
2863 if (b != priv->displayMapAreas)
2864 {
2865 priv->displayMapAreas = b;
2866 viewport()->update();
2867 priv->checkCurrentMapArea();
2868 priv->showTransientMapAreas(priv->allLinksDisplayed);
2869 }
2870 }
2871
2872
2873 /*! \property QDjVuWidget::keyboardEnabled
2874 Enables keyboard interaction.
2875 This property controls the behavior of
2876 arrows keys, page movement keys, and
2877 various shortcut keys.
2878 Default: \a true. */
2879
2880 bool
2881 QDjVuWidget::keyboardEnabled(void) const
2882 {
2883 return priv->keyboardEnabled;
2884 }
2885
2886 void
2887 QDjVuWidget::enableKeyboard(bool b)
2888 {
2889 if (b != priv->keyboardEnabled)
2890 priv->keyboardEnabled = b;
2891 }
2892
2893 /*! \property QDjVuWidget::mouseEnabled
2894 Enables mouse interaction.
2895 Default: \a true. */
2896
2897 bool
2898 QDjVuWidget::mouseEnabled(void) const
2899 {
2900 return priv->mouseEnabled;
2901 }
2902
2903 void
2904 QDjVuWidget::enableMouse(bool b)
2905 {
2906 if (b != priv->mouseEnabled)
2907 priv->mouseEnabled = b;
2908 }
2909
2910 /*! \property QDjVuWidget::hyperlinkEnabled
2911 Enables hyperlinks.
2912 This propery indicates whether hyperlink feedback
2913 is displayed, and whether the signals \a pointerEnter,
2914 \a pointerLeave and \a pointerClick are emitted.
2915 You must also set \a mouseEnabled and \a displayMapAreas to \a true.
2916 Default: \a true. */
2917
2918 bool
2919 QDjVuWidget::hyperlinkEnabled(void) const
2920 {
2921 return priv->hyperlinkEnabled;
2922 }
2923
2924 void
2925 QDjVuWidget::enableHyperlink(bool b)
2926 {
2927 if (b != priv->hyperlinkEnabled)
2928 {
2929 priv->hyperlinkEnabled = b;
2930 priv->checkCurrentMapArea();
2931 }
2932 }
2933
2934
2935 /*! \property QDjVuWidget::animationEnabled
2936 Enables animation on position changes.
2937 This property indicates whether certain position changes
2938 are performed using a display animation.
2939 Default: \a true. */
2940
2941 bool
2942 QDjVuWidget::animationEnabled(void) const
2943 {
2944 return priv->animationEnabled;
2945 }
2946
2947 void
2948 QDjVuWidget::enableAnimation(bool b)
2949 {
2950 priv->clearAnimation();
2951 priv->animationEnabled = b;
2952 }
2953
2954
2955 /*! \property QDjVuWidget::animationInProgress
2956 Read-only property that tells whether an animation is in progress. */
2957
2958 bool
2959 QDjVuWidget::animationInProgress(void) const
2960 {
2961 if (priv->animationEnabled)
2962 if (! priv->animationPosition.isEmpty())
2963 return true;
2964 return false;
2965 }
2966
2967
2968 /*! \property QDjVuWidget::pixelCacheSize
2969 Defines the maximal number of pixels in the cache
2970 for decoded images segments. */
2971
2972 int
2973 QDjVuWidget::pixelCacheSize(void) const
2974 {
2975 return priv->pixelCacheSize;
2976 }
2977
2978 void
2979 QDjVuWidget::setPixelCacheSize(int s)
2980 {
2981 int oldPixelCacheSize = priv->pixelCacheSize;
2982 priv->pixelCacheSize = s;
2983 if (s < oldPixelCacheSize)
2984 priv->trimPixelCache();
2985 }
2986
2987
2988 /*! \property QDjVuWidget::lensPower
2989 Sets the power of the magnification lens.
2990 Legal value range from 0x to 10x.
2991 Value 0x disables the lens.
2992 Default is 3x. */
2993
2994 int
2995 QDjVuWidget::lensPower(void) const
2996 {
2997 return priv->lensMag;
2998 }
2999
3000 void
3001 QDjVuWidget::setLensPower(int mag)
3002 {
3003 priv->lensMag = qBound(0,mag,10);
3004 }
3005
3006 /*! \property QDjVuWidget::lensSize
3007 Sets the size of the magnification lens.
3008 Legal value range from 0 to 500 pixels.
3009 Value 0 disables the lens.
3010 Default is 300. */
3011
3012 int
3013 QDjVuWidget::lensSize(void) const
3014 {
3015 return priv->lensSize;
3016 }
3017
3018 void
3019 QDjVuWidget::setLensSize(int size)
3020 {
3021 priv->lensSize = qBound(0,size,500);
3022 }
3023
3024
3025 /*! \property QDjVuWidget::hourGlassRatio
3026 Setups the hour glass timer indicator.
3027 Nothing is displayed when value is zero.
3028 Otherwise it indicates that one should
3029 display the specified fraction of time
3030 before switching page in slideshow more. */
3031
3032 double
3033 QDjVuWidget::hourGlassRatio() const
3034 {
3035 return priv->hourGlassRatio;
3036 }
3037
3038 QRect
3039 QDjVuPrivate::hourGlassRect() const
3040 {
3041 int bs = qBound(4, borderSize / 2, 16);
3042 int hs = qBound(16, borderSize * 6, 64);
3043 int w = widget->viewport()->width();
3044 int h = widget->viewport()->height();
3045 if (w > hs+bs+bs && h > hs+bs+bs)
3046 return QRect(w-bs-hs,h-bs-hs,hs,hs);
3047 return QRect();
3048 }
3049
3050 void
3051 QDjVuWidget::setHourGlassRatio(double ratio)
3052 {
3053 if (ratio != priv->hourGlassRatio && ratio>=0 && ratio<=1)
3054 {
3055 priv->hourGlassRatio = ratio;
3056 QRect rect = priv->hourGlassRect();
3057 if (!rect.isEmpty())
3058 viewport()->update(rect.adjusted(-2,-2,2,2));
3059 }
3060 }
3061
3062 /*! \property QDjVuWidget::modifiersForLens
3063 Sets the modifier that should be depressed in
3064 order to display the magnifying lens.
3065 Default: Control + Shift. */
3066
3067 Qt::KeyboardModifiers
3068 QDjVuWidget::modifiersForLens() const
3069 {
3070 return priv->modifiersForLens;
3071 }
3072
3073 void
3074 QDjVuWidget::setModifiersForLens(Qt::KeyboardModifiers m)
3075 {
3076 if (priv->modifiersForLens != m)
3077 {
3078 priv->modifiersForLens = m;
3079 if (priv->dragMode == DRAG_NONE)
3080 modifierEvent(priv->modifiers, priv->buttons, priv->cursorPoint);
3081 }
3082 }
3083
3084 /*! \property QDjVuWidget::modifiersForSelect
3085 Sets the modifier that should be depressed
3086 in conjunction with the left mouse button in
3087 order to select a rectangular area.
3088 Default: Control. */
3089
3090 Qt::KeyboardModifiers
3091 QDjVuWidget::modifiersForSelect() const
3092 {
3093 return priv->modifiersForSelect;
3094 }
3095
3096 void
3097 QDjVuWidget::setModifiersForSelect(Qt::KeyboardModifiers m)
3098 {
3099 if (priv->modifiersForSelect != m)
3100 {
3101 priv->modifiersForSelect = m;
3102 if (priv->dragMode == DRAG_NONE)
3103 modifierEvent(priv->modifiers, priv->buttons, priv->cursorPoint);
3104 }
3105 }
3106
3107
3108 /*! \property QDjVuWidget::modifiersForLinks
3109 Sets the modifier that should be depressed in
3110 order to display all hyperlinks.
3111 Default: Shift. */
3112
3113 Qt::KeyboardModifiers
3114 QDjVuWidget::modifiersForLinks() const
3115 {
3116 return priv->modifiersForLinks;
3117 }
3118
3119 void
3120 QDjVuWidget::setModifiersForLinks(Qt::KeyboardModifiers m)
3121 {
3122 if (priv->modifiersForLinks != m)
3123 {
3124 priv->modifiersForLinks = m;
3125 priv->showTransientMapAreas(m!=Qt::NoModifier && m==priv->modifiers);
3126 if (priv->dragMode == DRAG_NONE)
3127 modifierEvent(priv->modifiers, priv->buttons, priv->cursorPoint);
3128 }
3129 }
3130
3131
3132 // ----------------------------------------
3133 // MAPAREAS AND HIDDEN TEXT
3134
3135 BEGIN_ANONYMOUS_NAMESPACE
3136
3137 struct Keywords {
3138 // maparea keywords
3139 miniexp_t url, rect, oval, poly, line, text;
3140 miniexp_t none, xxor, border;
3141 miniexp_t shadow_in, shadow_out, shadow_ein, shadow_eout;
3142 miniexp_t border_avis, hilite, opacity;
3143 miniexp_t arrow, width, lineclr;
3144 miniexp_t backclr, textclr, pushpin;
3145 // hiddentext keywords
3146 miniexp_t h[7];
3147 Keywords() {
3148 #define S(n,s) n=miniexp_symbol(s)
3149 #define D(n) S(n,#n)
3150 // maparea
3151 D(url); D(rect); D(oval); D(poly); D(line); D(text);
3152 D(none); S(xxor,"xor"); D(border);
3153 D(shadow_in); D(shadow_out); D(shadow_ein); D(shadow_eout);
3154 D(border_avis); D(hilite); D(opacity);
3155 D(arrow); D(width); D(lineclr);
3156 D(backclr); D(textclr); D(pushpin);
3157 // hidden text
3158 S(h[0],"page"); S(h[1],"column"); S(h[2],"region");
3159 S(h[3],"para"); S(h[4],"line"); S(h[5],"word"); S(h[6],"char");
3160 #undef D
3161 #undef S
3162 }
3163 };
3164
3165 Q_GLOBAL_STATIC(Keywords, keywords)
3166
3167 END_ANONYMOUS_NAMESPACE
3168
3169
3170 MapArea::MapArea()
3171 {
3172 expr = miniexp_nil;
3173 url = target = comment = miniexp_nil;
3174 areaType = borderType = miniexp_nil;
3175 borderWidth = 1;
3176 borderAlwaysVisible = false;
3177 hiliteOpacity = 50;
3178 lineArrow = false;
3179 lineWidth = 1;
3180 foregroundColor = Qt::black;
3181 pushpin = false;
3182 rectNeedsRotation = false;
3183 }
3184
3185 bool
3186 MapArea::error(const char *err, int pageno, miniexp_t info)
3187 {
3188 if (pageno >= 0)
3189 qWarning("Error in maparea for page %d\n%s\n%s\n",
3190 pageno+1, err, miniexp_to_str(miniexp_pname(info, 72)) );
3191 return false;
3192 }
3193
3194 bool
3195 MapArea::parse(miniexp_t full, int pageno)
3196 {
3197 Keywords &k = *keywords();
3198 expr = full;
3199 miniexp_t anno = miniexp_cdr(full);
3200 miniexp_t q = miniexp_car(anno);
3201 int itmp;
3202 // hyperlink
3203 if (miniexp_stringp(q)) {
3204 const char *s = miniexp_to_str(q);
3205 url = (s && s[0]) ? q : miniexp_nil;
3206 } else if (miniexp_consp(q) && miniexp_car(q)==k.url) {
3207 if (! (miniexp_stringp(miniexp_cadr(q)) &&
3208 miniexp_stringp(miniexp_caddr(q)) &&
3209 ! miniexp_cdddr(q) ) )
3210 return error("Bad url", pageno, q);
3211 url = miniexp_cadr(q);
3212 target = miniexp_caddr(q);
3213 const char *s = miniexp_to_str(url);
3214 if (! (s && s[0]))
3215 url = target = miniexp_nil;
3216 } else if (q)
3217 return error("Bad url", pageno, full);
3218 else
3219 error("Some viewers prefer \"\" over () for empty urls.",
3220 pageno, full );
3221 // comment
3222 anno = miniexp_cdr(anno);
3223 q = miniexp_car(anno);
3224 if (miniexp_stringp(q))
3225 {
3226 const char *s = miniexp_to_str(q);
3227 if (s && s[0])
3228 comment = q;
3229 }
3230 else if (q)
3231 return error("Bad comment", pageno, full);
3232 else
3233 error("Some viewers prefer \"\" over () for empty comments.",
3234 pageno, full );
3235 // area
3236 anno = miniexp_cdr(anno);
3237 q = miniexp_car(anno);
3238 areaType = miniexp_car(q);
3239 if (areaType == k.rect || areaType == k.oval || areaType == k.text)
3240 {
3241 q = miniexp_cdr(q);
3242 if (!miniexp_get_rect(q, areaRect) || q)
3243 return error("Bad rectangle", pageno, miniexp_car(anno));
3244 }
3245 else if (areaType == k.poly)
3246 {
3247 q = miniexp_cdr(q);
3248 if (!miniexp_get_points(q, areaRect, areaPoints))
3249 return error("Bad polygon", pageno, miniexp_car(anno));
3250 }
3251 else if (areaType == k.line)
3252 {
3253 q = miniexp_cdr(q);
3254 if (!miniexp_get_points(q,areaRect,areaPoints) || areaPoints.size()!=2)
3255 return error("Bad line", pageno, miniexp_car(anno));
3256 }
3257 else
3258 return error("Bad area", pageno, full);
3259 // remaining
3260 while (miniexp_consp(anno = miniexp_cdr(anno)))
3261 {
3262 q = miniexp_car(anno);
3263 miniexp_t s = miniexp_car(q);
3264 miniexp_t a = miniexp_cdr(q);
3265 // borders
3266 if (s==k.none || s==k.xxor || s==k.border
3267 || s==k.shadow_in || s==k.shadow_out
3268 || s==k.shadow_ein || s==k.shadow_eout )
3269 {
3270 if (s==k.none)
3271 {
3272 borderWidth = 0;
3273 }
3274 else if (s==k.xxor)
3275 {
3276 borderWidth = 1;
3277 }
3278 else if (s==k.border)
3279 {
3280 if (! miniexp_get_color(a, borderColor))
3281 return error("Color expected", pageno, q);
3282 borderWidth = 1;
3283 }
3284 else
3285 {
3286 if (! miniexp_get_int(a, itmp))
3287 return error("Integer expected", pageno, q);
3288 borderWidth = qBound(1, itmp, 32);
3289 if (areaType != k.rect)
3290 return error("Only for rectangle maparea", pageno, q);
3291 }
3292 if (borderType)
3293 error("Multiple border specification", pageno, full);
3294 borderType = s;
3295 }
3296 // border avis
3297 else if (s == k.border_avis)
3298 {
3299 borderAlwaysVisible = true;
3300 }
3301 // hilite
3302 else if (s == k.hilite)
3303 {
3304 if (areaType != k.rect)
3305 error("Only for rectangle maparea", pageno, q);
3306 else if (! miniexp_get_color(a, hiliteColor))
3307 return error("Color expected", pageno, q);
3308 }
3309 else if (s == k.opacity)
3310 {
3311 if (areaType != k.rect)
3312 error("Only for rectangle maparea", pageno, q);
3313 else if (! miniexp_get_int(a, itmp))
3314 return error("Integer expected", pageno, q);
3315 hiliteOpacity = qBound(0, itmp, 200);
3316 }
3317 // line stuff
3318 else if (s == k.arrow)
3319 {
3320 if (areaType != k.line)
3321 error("Only for line maparea", pageno, q);
3322 lineArrow = true;
3323 }
3324 else if (s == k.width)
3325 {
3326 if (areaType != k.line)
3327 error("Only for line maparea", pageno, q);
3328 if (! miniexp_get_int(a, itmp))
3329 return error("Integer expected", pageno, q);
3330 lineWidth = qBound(1, itmp, 32);
3331 }
3332 else if (s == k.lineclr)
3333 {
3334 if (areaType != k.line)
3335 error("Only for line maparea", pageno, q);
3336 if (! miniexp_get_color(a, foregroundColor))
3337 return error("Color expected", pageno, q);
3338 }
3339 // text stuff
3340 else if (s == k.backclr)
3341 {
3342 if (areaType != k.text)
3343 error("Only for text maparea", pageno, q);
3344 if (! miniexp_get_color(a, hiliteColor))
3345 return error("Color expected", pageno, q);
3346 hiliteOpacity = 200;
3347 }
3348 else if (s == k.textclr)
3349 {
3350 if (areaType != k.text)
3351 error("Only for text maparea", pageno, q);
3352 if (! miniexp_get_color(a, foregroundColor))
3353 return error("Color expected", pageno, q);
3354 }
3355 else if (s == k.pushpin)
3356 {
3357 if (areaType != k.text)
3358 error("Only for text maparea", pageno, q);
3359 pushpin = true;
3360 }
3361 else
3362 error("Unrecognized specification", pageno, q);
3363 // test for extra arguments
3364 if (a)
3365 error("Extra arguments were ignored", pageno, q);
3366 }
3367 // border type sanity checks
3368 if (areaType == k.line)
3369 {
3370 if (borderType && borderType != k.none)
3371 error("Line maparea should not specify a border.", pageno, expr);
3372 if (miniexp_stringp(url))
3373 error("Line maparea should not specify a url.", pageno, expr);
3374 borderType = miniexp_nil;
3375 url = miniexp_nil;
3376 }
3377 else if (borderType == miniexp_nil)
3378 {
3379 error("Maparea without border type defaults to (xor).", pageno, expr);
3380 borderType = k.xxor;
3381 }
3382 return true;
3383 }
3384
3385 bool
3386 MapArea::clicked(void)
3387 {
3388 Keywords &k = *keywords();
3389 if (areaType == k.text && pushpin)
3390 {
3391 areaType = k.pushpin; // fake area type
3392 borderType = miniexp_nil; // no border
3393 hiliteColor = QColor(); // no hilite
3394 return true;
3395 }
3396 else if (areaType == k.pushpin)
3397 {
3398 parse(expr); // restore
3399 return true;
3400 }
3401 return false;
3402 }
3403
3404 bool
3405 MapArea::isClickable(bool hyperlink)
3406 {
3407 Keywords &k = *keywords();
3408 if (url && hyperlink)
3409 return true;
3410 if (areaType == k.pushpin)
3411 return true;
3412 if (areaType == k.text && pushpin)
3413 return true;
3414 return false;
3415 }
3416
3417 bool
3418 MapArea::hasTransient(bool allLinks)
3419 {
3420 Keywords &k = *keywords();
3421 if (areaType == miniexp_nil)
3422 return false;
3423 if (allLinks && miniexp_stringp(url))
3424 return true;
3425 if (borderAlwaysVisible)
3426 return false;
3427 if (borderType == k.none || borderType == miniexp_nil)
3428 return false;
3429 return true;
3430 }
3431
3432 bool
3433 MapArea::hasPermanent()
3434 {
3435 Keywords &k = *keywords();
3436 if (hiliteColor.isValid()
3437 || areaType == k.line || areaType == k.text
3438 || areaType == k.pushpin )
3439 return true;
3440 return false;
3441 }
3442
3443 void
3444 MapArea::maybeRotate(struct Page *p)
3445 {
3446 if (rectNeedsRotation && p->dpi >= 0)
3447 {
3448 int rot = p->initialRot;
3449 if (rot > 0)
3450 {
3451 int rw = (rot&1) ? p->height : p->width;
3452 int rh = (rot&1) ? p->width : p->height;
3453 QRectMapper mapper;
3454 mapper.setMap(QRect(0,0,rw,rh), QRect(0,0,p->width,p->height));
3455 mapper.setTransform(rot, false, false);
3456 areaRect = mapper.mapped(areaRect);
3457 }
3458 rectNeedsRotation = false;
3459 }
3460 }
3461
3462 QPainterPath
3463 MapArea::contour(QRectMapper &m, QPoint &offset)
3464 {
3465 Keywords &k = *keywords();
3466 QRect rect = m.mapped(areaRect).translated(-offset);
3467 QPainterPath path;
3468 if (areaType == k.poly)
3469 {
3470 QPoint p = m.mapped(areaPoints[0]) - offset;
3471 path.moveTo(p);
3472 for (int j=1; j<areaPoints.size(); j++)
3473 path.lineTo(m.mapped(areaPoints[j]) - offset);
3474 }
3475 else if (areaType == k.oval)
3476 path.addEllipse(rect);
3477 else
3478 path.addRect(rect);
3479 path.closeSubpath();
3480 return path;
3481 }
3482
3483 bool
3484 MapArea::contains(const QPoint &p)
3485 {
3486 Keywords &k = *keywords();
3487 if (! areaRect.contains(p))
3488 return false;
3489 if (areaType == k.oval || areaType == k.poly)
3490 {
3491 QRectMapper nullmapper;
3492 QPoint nullpoint;
3493 QPainterPath path = contour(nullmapper, nullpoint);
3494 if (! path .contains(p))
3495 return false;
3496 }
3497 return true;
3498 }
3499
3500 void
3501 MapArea::update(QWidget *w, QRectMapper &m, QPoint offset, bool permanent)
3502 {
3503 // The mapper <m> maps page coordinates to
3504 // widget coordinates translated by <offset>.
3505 Keywords &k = *keywords();
3506 int bw = borderWidth;
3507 QRect rect = m.mapped(areaRect).translated(-offset);
3508 if (! rect.intersects(w->rect()))
3509 {
3510 return;
3511 }
3512 else if (permanent && hiliteColor.isValid() && hiliteOpacity>0)
3513 {
3514 int bw2 = (bw / 2) + 1;
3515 w->update(rect.adjusted(-bw2-1, -bw2-1, bw2+1, bw2+1));
3516 }
3517 else if (permanent && (areaType == k.text || areaType == k.pushpin))
3518 {
3519 int bw2 = (bw / 2) + 1;
3520 w->update(rect.adjusted(-bw2-1, -bw2-1, bw2+1, bw2+1));
3521 }
3522 else if (areaType == k.oval || areaType == k.poly)
3523 {
3524 int bw2 = (bw / 2) + 1;
3525 QPainterPath path = contour(m, offset);
3526 rect.adjust(-bw2, -bw2, bw2, bw2);
3527 QBitmap bm(rect.width(),rect.height());
3528 bm.clear();
3529 QPainter paint;
3530 paint.begin(&bm);
3531 paint.translate(-rect.topLeft());
3532 paint.strokePath(path, QPen(Qt::black, bw+4));
3533 paint.end();
3534 QRegion region(bm);
3535 region.translate(rect.topLeft());
3536 w->update(region);
3537 }
3538 else
3539 {
3540 int bw2 = (bw / 2) + 1;
3541 QRegion region = rect.adjusted(-bw2-1, -bw2-1, bw2+1, bw2+1);
3542 region = region.subtracted(rect.adjusted(bw+1, bw+1, -bw-1, -bw-1));
3543 w->update(region);
3544 }
3545 }
3546
3547 void
3548 MapArea::paintBorder(QPaintDevice *w, QRectMapper &m, QPoint offset, bool allLinks)
3549 {
3550 // The mapper <m> maps page coordinates to
3551 // widget coordinates translated by <offset>.
3552 Keywords &k = *keywords();
3553 QRect rect = m.mapped(areaRect).translated(-offset);
3554 bool forceXor = false;
3555 if (allLinks && miniexp_stringp(url))
3556 forceXor = (borderType == k.none || borderType == miniexp_nil);
3557 QPainter paint(w);
3558 paint.setRenderHint(QPainter::Antialiasing);
3559 paint.setRenderHint(QPainter::TextAntialiasing);
3560 if (borderType == k.border)
3561 {
3562 QPainterPath path = contour(m, offset);
3563 paint.strokePath(path, QPen(borderColor, borderWidth));
3564 }
3565 else if (borderType == k.xxor || forceXor)
3566 {
3567 QPainterPath path = contour(m, offset);
3568 paint.strokePath(path, QPen(Qt::white, borderWidth));
3569 paint.strokePath(path, QPen(Qt::black, borderWidth, Qt::DashLine));
3570 }
3571 else if (borderType == k.shadow_in || borderType==k.shadow_out)
3572 {
3573 rect.adjust(0,0,+1,+1);
3574 int bw = borderWidth;
3575 bw = qMin(bw, qMin(rect.width()/4, rect.height()/4));
3576 QRect irect = rect.adjusted(bw, bw, -bw, -bw);
3577 paint.setPen(Qt::NoPen);
3578 QColor c1(255,255,255,100);
3579 QColor c2(0,0,0,100);
3580 QPolygon p(6);
3581 p[0] = irect.bottomLeft();
3582 p[1] = rect.bottomLeft();
3583 p[2] = rect.bottomRight();
3584 p[3] = rect.topRight();
3585 p[4] = irect.topRight();
3586 p[5] = irect.bottomRight();
3587 paint.setBrush((borderType==k.shadow_in) ? c1 : c2);
3588 paint.drawPolygon(p);
3589 p[0] = irect.bottomLeft();
3590 p[1] = rect.bottomLeft();
3591 p[2] = rect.topLeft();
3592 p[3] = rect.topRight();
3593 p[4] = irect.topRight();
3594 p[5] = irect.topLeft();
3595 paint.setBrush((borderType==k.shadow_in) ? c2 : c1);
3596 paint.drawPolygon(p);
3597 }
3598 else if (borderType == k.shadow_ein || borderType==k.shadow_eout)
3599 {
3600 rect.adjust(0,0,+1,+1);
3601 int bw = borderWidth;
3602 bw = qMin(bw, qMin(rect.width()/4, rect.height()/4));
3603 QRect irect = rect.adjusted(bw, bw, -bw, -bw);
3604 paint.setBrush(Qt::NoBrush);
3605 QColor c1(255,255,255,100);
3606 QColor c2(0,0,0,100);
3607 QPolygon p(3);
3608 paint.setPen(QPen((borderType==k.shadow_ein) ? c1 : c2, 1));
3609 p[0] = irect.bottomLeft();
3610 p[1] = irect.topLeft();
3611 p[2] = irect.topRight();
3612 paint.drawPolyline(p);
3613 p[0] = rect.bottomLeft();
3614 p[1] = rect.bottomRight();
3615 p[2] = rect.topRight();
3616 paint.drawPolyline(p);
3617 paint.setPen(QPen((borderType==k.shadow_ein) ? c2 : c1, 1));
3618 p[0] = irect.bottomLeft();
3619 p[1] = irect.bottomRight();
3620 p[2] = irect.topRight();
3621 paint.drawPolyline(p);
3622 p[0] = rect.bottomLeft();
3623 p[1] = rect.topLeft();
3624 p[2] = rect.topRight();
3625 paint.drawPolyline(p);
3626 }
3627 }
3628
3629 void
3630 MapArea::paintPermanent(QPaintDevice *w, QRectMapper &m,
3631 QPoint offset, double z)
3632 {
3633 // The mapper <m> maps page coordinates to
3634 // widget coordinates translated by <offset>.
3635 Keywords &k = *keywords();
3636 QRect rect = m.mapped(areaRect).translated(-offset);
3637 if (hasPermanent())
3638 {
3639 QPainter paint(w);
3640 paint.setRenderHint(QPainter::Antialiasing);
3641 paint.setRenderHint(QPainter::TextAntialiasing);
3642 if (hiliteColor.isValid() && hiliteOpacity>0)
3643 {
3644 QColor color = hiliteColor;
3645 color.setAlpha(hiliteOpacity*255/200);
3646 paint.fillRect(rect, color);
3647 }
3648 if (areaType == k.line)
3649 {
3650 QPen pen(foregroundColor, lineWidth);
3651 pen.setJoinStyle(Qt::MiterJoin);
3652 paint.setPen(pen);
3653 paint.setBrush(foregroundColor);
3654 QPoint pFrom = m.mapped(areaPoints[0]) - offset;
3655 QPoint pTo = m.mapped(areaPoints[1]) - offset;
3656 if (lineArrow)
3657 {
3658 QPointF v = pFrom - pTo;
3659 qreal vn = sqrt(v.x() * v.x() + v.y() * v.y());
3660 v = v * qMin(0.25, (10.0 / vn));
3661 QPointF v90 = QPointF(-v.y()/2.0, v.x()/2.0);
3662 QPointF p[3];
3663 p[0] = pTo;
3664 p[1] = pTo + v - v90;
3665 p[2] = pTo + v + v90;
3666 paint.drawPolygon(p, 3);
3667 paint.drawLine(pFrom, pTo+ v * 0.5);
3668 }
3669 else
3670 {
3671 paint.drawLine(pFrom, pTo);
3672 }
3673 }
3674 else if (areaType == k.text)
3675 {
3676 int bw = borderWidth + 2;
3677 bw = qMin(bw, qMin(rect.width()/4, rect.height()/4));
3678 QRect r = rect.adjusted(bw, bw, -bw, -bw);
3679 QString s = miniexp_to_qstring(comment);
3680 paint.setPen(foregroundColor);
3681 int flags = Qt::AlignVCenter|Qt::TextWordWrap;
3682 QFont font = paint.font();
3683 // estimate font size
3684 int size = (int)(z * 0.12);
3685 while (size > 1)
3686 {
3687 QRect br;
3688 font.setPixelSize(size);
3689 paint.setFont(font);
3690 paint.drawText(r,flags|Qt::AlignHCenter|Qt::TextDontPrint,s,&br);
3691 if (r.contains(br))
3692 {
3693 // found good font size
3694 paint.drawText(r,flags|Qt::AlignLeft,s,0);
3695 break;
3696 }
3697 size -= 1;
3698 }
3699 }
3700 else if (areaType == k.pushpin)
3701 {
3702 QPixmap pixmap;
3703 pixmap.load(":/images/text_pushpin.png");
3704 if (! pixmap.isNull())
3705 {
3706 QRect r = pixmap.rect().translated(rect.topLeft());
3707 if (r.width() > rect.width())
3708 {
3709 r.setHeight(r.height() * rect.width() / r.width());
3710 r.setWidth(rect.width());
3711 }
3712 if (r.height() > rect.height())
3713 {
3714 r.setWidth(r.width() * rect.height() / r.height());
3715 r.setHeight(rect.height());
3716 }
3717 paint.drawPixmap(r, pixmap);
3718 }
3719 }
3720 }
3721 if (! hasTransient())
3722 paintBorder(w, m, offset);
3723 }
3724
3725 void
3726 MapArea::paintTransient(QPaintDevice *w, QRectMapper &m, QPoint offset, bool allLinks)
3727 {
3728 if (hasTransient(allLinks))
3729 paintBorder(w, m, offset, allLinks);
3730 }
3731
3732 void
3733 QDjVuPrivate::prepareMapAreas(Page *p)
3734 {
3735 // remove annotation mapareas.
3736 int j = p->mapAreas.size();
3737 while (--j >= 0)
3738 if (p->mapAreas[j].expr)
3739 p->mapAreas.removeAt(j);
3740 // parse annotations.
3741 if (p->annotations && p->annotations != miniexp_dummy)
3742 {
3743 miniexp_t *annos;
3744 annos = ddjvu_anno_get_hyperlinks(p->annotations);
3745 if (annos)
3746 {
3747 for (int i=0; annos[i]; i++)
3748 {
3749 MapArea data;
3750 miniexp_t anno = annos[i];
3751 if (data.parse(anno, p->pageno))
3752 {
3753 data.clicked(); // collapse pushpins
3754 p->mapAreas << data;
3755 }
3756 }
3757 free(annos);
3758 }
3759 }
3760 }
3761
3762 bool
3763 QDjVuPrivate::mustDisplayMapArea(MapArea *area)
3764 {
3765 if (allLinksDisplayed)
3766 return true;
3767 if (area != currentMapArea)
3768 return false;
3769 if (hyperlinkEnabled && mouseEnabled)
3770 return true;
3771 return false;
3772 }
3773
3774 void
3775 QDjVuPrivate::checkCurrentMapArea(bool forceno)
3776 {
3777 const Position &pos = cursorPos;
3778 Page *savedMapAreaPage = currentMapAreaPage;
3779 MapArea *savedMapArea = currentMapArea;
3780 Page *newMapAreaPage = 0;
3781 MapArea *newMapArea = 0;
3782 // locate new maparea
3783 if (displayMapAreas && !forceno && pos.inPage)
3784 if (pageMap.contains(pos.pageNo))
3785 {
3786 Page *p = pageMap[pos.pageNo];
3787 for (int i=0; i<p->mapAreas.size(); i++)
3788 {
3789 MapArea &area = p->mapAreas[i];
3790 area.maybeRotate(p);
3791 if (area.expr &&
3792 area.areaRect.contains(pos.posPage) &&
3793 area.contains(pos.posPage) )
3794 {
3795 newMapArea = &area;
3796 newMapAreaPage = p;
3797 break;
3798 }
3799 }
3800 }
3801 // change map area
3802 if (savedMapArea != newMapArea)
3803 {
3804 currentMapArea = 0;
3805 currentMapAreaPage = 0;
3806 if (savedMapArea)
3807 {
3808 if (savedMapArea->hasTransient())
3809 if (currentLinkDisplayed && !allLinksDisplayed)
3810 savedMapArea->update(widget->viewport(),
3811 savedMapAreaPage->mapper,
3812 visibleRect.topLeft());
3813 emit widget->pointerLeave(pos, savedMapArea->expr);
3814 }
3815 currentUrl = QString();
3816 currentTarget = QString();
3817 currentComment = QString();
3818 currentLinkDisplayed = false;
3819 if (newMapArea)
3820 {
3821 currentMapArea = newMapArea;
3822 currentMapAreaPage = newMapAreaPage;
3823 currentUrl = miniexp_to_qstring(currentMapArea->url);
3824 currentTarget = miniexp_to_qstring(currentMapArea->target);
3825 currentComment = miniexp_to_qstring(currentMapArea->comment);
3826 if (mustDisplayMapArea(newMapArea))
3827 newMapArea->update(widget->viewport(),
3828 newMapAreaPage->mapper,
3829 visibleRect.topLeft());
3830 emit widget->pointerEnter(pos, currentMapArea->expr);
3831 }
3832 widget->modifierEvent(modifiers, buttons, cursorPoint);
3833 widget->chooseTooltip();
3834 }
3835 }
3836
3837 void
3838 QDjVuPrivate::showTransientMapAreas(bool b)
3839 {
3840 b = b && displayMapAreas && hyperlinkEnabled && mouseEnabled;
3841 if (b != allLinksDisplayed)
3842 {
3843 Page *p;
3844 allLinksDisplayed = b;
3845 foreach (p, pageVisible)
3846 for (int i=0; i<p->mapAreas.size(); i++)
3847 {
3848 MapArea &area = p->mapAreas[i];
3849 area.maybeRotate(p);
3850 if (area.hasTransient(true))
3851 area.update(widget->viewport(), p->mapper,
3852 visibleRect.topLeft() );
3853 }
3854 }
3855 }
3856
3857
3858
3859 /*! Removes all highlight rectangles
3860 installed for page \a pageno. */
3861
3862 void
3863 QDjVuWidget::clearHighlights(int pageno)
3864 {
3865 if (pageno>=0 && pageno<priv->pageData.size())
3866 {
3867 Page *p = &priv->pageData[pageno];
3868 int j = p->mapAreas.size();
3869 while (--j >= 0)
3870 if (! p->mapAreas[j].expr)
3871 {
3872 MapArea &area = p->mapAreas[j];
3873 if (priv->pageMap.contains(pageno) && p->dpi>0)
3874 area.update(viewport(), p->mapper, priv->visibleRect.topLeft(), true);
3875 priv->pixelCache.clear();
3876 p->mapAreas.removeAt(j);
3877 }
3878 }
3879 }
3880
3881 /*! Add a new highlight rectangle with color \a color,
3882 at position \a x, \a y, \a w, \a h on page \a pageno.
3883 Argument \a rc indicates whether coordinates are
3884 rotated (like annotations) or unrotated (like text). */
3885
3886 void
3887 QDjVuWidget::addHighlight(int pageno, int x, int y, int w, int h,
3888 QColor color, bool rc)
3889 {
3890 if (!priv->docReady)
3891 priv->docinfo();
3892 if (pageno>=0 && pageno<priv->pageData.size() && w>0 && h>0)
3893 {
3894 Page *p = &priv->pageData[pageno];
3895 Keywords &k = *keywords();
3896 MapArea area;
3897 area.areaType = k.rect;
3898 area.areaRect = QRect(x,y,w,h);
3899 area.hiliteColor = color;
3900 area.hiliteColor.setAlpha(255);
3901 area.hiliteOpacity = color.alpha() * 200 / 255;
3902 area.borderType = miniexp_nil;
3903 area.rectNeedsRotation = rc;
3904 area.maybeRotate(p);
3905 p->mapAreas << area;
3906 priv->pixelCache.clear();
3907 if (priv->pageMap.contains(pageno) && p->dpi>0)
3908 area.update(viewport(), p->mapper, priv->visibleRect.topLeft(), true);
3909 }
3910 }
3911
3912
3913 /*! Returns the url string for the maparea located
3914 below the pointer. This function is valid when called from signal
3915 \a pointerEnter, \a pointerLeave, or \a pointerClick. */
3916
3917 QString
3918 QDjVuWidget::linkUrl(void)
3919 {
3920 if (priv->hyperlinkEnabled && priv->mouseEnabled)
3921 return priv->currentUrl;
3922 return QString();
3923 }
3924
3925 /*! Returns the target string for the maparea located
3926 below the pointer. This function is valid when called from signal
3927 \a pointerEnter, \a pointerLeave, or \a pointerClick. */
3928
3929 QString
3930 QDjVuWidget::linkTarget(void)
3931 {
3932 if (priv->hyperlinkEnabled && priv->mouseEnabled)
3933 return priv->currentTarget;
3934 return QString();
3935 }
3936
3937 /*! Returns the comment string for the maparea located
3938 below the pointer. This function is valid when called from signal
3939 \a pointerEnter, \a pointerLeave, or \a pointerClick. */
3940
3941 QString
3942 QDjVuWidget::linkComment(void)
3943 {
3944 return priv->currentComment;
3945 }
3946
3947
3948 /*! Determine the text around a particular point.
3949 Produces an array of three string. The middle string
3950 is the selected information. All the strings represent the line.
3951 Returns true on success. */
3952 bool
3953 QDjVuWidget::getTextForPointer(QString results[])
3954 {
3955 Position &pos = priv->cursorPos;
3956 if (!pos.inPage || !priv->pageMap.contains(pos.pageNo))
3957 return false;
3958 Page *page = priv->pageMap[pos.pageNo];
3959 // map point
3960 int rot = page->initialRot;
3961 int w = (rot&1) ? page->height : page->width;
3962 int h = (rot&1) ? page->width : page->height;
3963 QRectMapper mapper;
3964 mapper.setMap(QRect(0,0,w,h), page->rect);
3965 mapper.setTransform(rot + priv->rotation, false, true);
3966 QPoint posRot = mapper.unMapped(pos.posView + page->rect.topLeft());
3967 // search zones
3968 Keywords &k = *keywords();
3969 miniexp_t q = page->hiddenText;
3970 miniexp_t l = page->hiddenText;
3971 while(miniexp_consp(q))
3972 {
3973 QRect rect;
3974 miniexp_t type = miniexp_car(q);
3975 miniexp_t r = miniexp_cdr(type);
3976 if (miniexp_consp(type))
3977 type = miniexp_car(type);
3978 if (miniexp_consp(r) && miniexp_get_rect_from_points(r, rect)
3979 && rect.adjusted(-2,-2,2,2).contains(posRot) )
3980 break;
3981 q = miniexp_cdr(q);
3982 int sep = 0;
3983 for (sep=0; sep<7; sep++)
3984 if (type == k.h[sep])
3985 break;
3986 if (sep <= 4)
3987 l = q;
3988 }
3989 if (miniexp_consp(q))
3990 {
3991 int state = 0;
3992 bool separator = false;
3993 results[0] = results[1] = results[2] = QString();
3994 while (miniexp_consp(l))
3995 {
3996 miniexp_t type = miniexp_car(l);
3997 miniexp_t s = miniexp_nth(5, type);
3998 bool is = miniexp_stringp(s);
3999 if (miniexp_consp(type))
4000 type = miniexp_car(type);
4001 if (state == 1)
4002 state = 2;
4003 if (is && separator)
4004 results[state] += " ";
4005 if (l == q)
4006 state = 1;
4007 l = miniexp_cdr(l);
4008 if (miniexp_stringp(s))
4009 results[state] += miniexp_to_qstring(s);
4010 int sep = 0;
4011 for (sep=0; sep<7; sep++)
4012 if (type == k.h[sep])
4013 break;
4014 if (sep <= 5)
4015 separator = true;
4016 else if (is)
4017 separator = false;
4018 if (sep <= 4 && state >= 1)
4019 break;
4020 }
4021 return true;
4022 }
4023 return false;
4024 }
4025
4026
4027 /*! Returns the text spanned with a particular
4028 rectangle \a target in viewport coordinates.
4029 Returns the empty string if no text is available. */
4030
4031 QString
4032 QDjVuWidget::getTextForRect(const QRect &vtarget)
4033 {
4034 QRect target = vtarget;
4035 target.translate(priv->visibleRect.topLeft());
4036 Keywords &k = *keywords();
4037 int separator = 6;
4038 QString ans;
4039 Page *p;
4040 foreach(p, priv->pageVisible)
4041 {
4042 // quick check
4043 miniexp_t q = p->hiddenText;
4044 if (p->initialRot < 0 || q == miniexp_nil || q == miniexp_dummy)
4045 continue;
4046 QRect pagerect = target.intersected(p->rect);
4047 if (!p->hiddenText || pagerect.isEmpty())
4048 { separator = 0; continue; }
4049 // map rectangle
4050 int rot = p->initialRot;
4051 int w = (rot&1) ? p->height : p->width;
4052 int h = (rot&1) ? p->width : p->height;
4053 QRectMapper mapper;
4054 mapper.setMap(QRect(0,0,w,h), p->rect);
4055 mapper.setTransform(rot + priv->rotation, false, true);
4056 pagerect = mapper.unMapped(pagerect);
4057 // loop
4058 while (miniexp_consp(q))
4059 {
4060 miniexp_t r = miniexp_car(q);
4061 q = miniexp_cdr(q);
4062 miniexp_t type = r;
4063 if (miniexp_consp(r))
4064 {
4065 QRect rect;
4066 type = miniexp_car(r);
4067 r = miniexp_cdr(r);
4068 if (miniexp_symbolp(type) &&
4069 miniexp_get_rect_from_points(r, rect) &&
4070 pagerect.intersects(rect) )
4071 {
4072 if (!ans.isEmpty())
4073 {
4074 if (separator == 0)
4075 ans += "\n\f";
4076 else if (separator <= 4)
4077 ans += "\n";
4078 else if (separator <= 5)
4079 ans += " ";
4080 }
4081 separator = 6;
4082 ans += miniexp_to_qstring(miniexp_car(r));
4083 }
4084 }
4085 for (int s=separator-1; s>=0; s--)
4086 if (type == k.h[s])
4087 separator = s;
4088 }
4089 }
4090 return ans;
4091 }
4092
4093 /*! Returns the image corresponding to a particular
4094 rectangle \a rect in viewport coordinates.
4095 Image is painted using the current display mode. */
4096
4097 QImage
4098 QDjVuWidget::getImageForRect(const QRect &rect)
4099 {
4100 priv->changeSelectedRectangle(QRect());
4101 QImage img(rect.width(), rect.height(), QImage::Format_RGB32);
4102 QRegion region = rect;
4103 QPainter paint;
4104 paint.begin(&img);
4105 paint.translate(- rect.topLeft());
4106 priv->paintAll(paint, region);
4107
4108 paint.end();
4109 return img;
4110 }
4111
4112
4113 /*! Returns a page coordinate rectangle describing
4114 the part of page \a pageNo that is covered by
4115 rectangle \a rect. */
4116
4117 QRect
4118 QDjVuWidget::getSegmentForRect(const QRect &rect, int pageNo)
4119 {
4120 QRect ans;
4121 if (priv->pageMap.contains(pageNo))
4122 {
4123 Page *p = priv->pageMap[pageNo];
4124 const QRect &v = priv->visibleRect;
4125 QRect d = rect.translated(v.topLeft()).intersected(p->rect);
4126 if (p->dpi && !d.isEmpty())
4127 ans = p->mapper.unMapped(d.intersected(p->rect));
4128 }
4129 return ans;
4130 }
4131
4132
4133
4134 /*! Indicate whether the page size if known */
4135
4136 bool
4137 QDjVuWidget::pageSizeKnown(int pageno) const
4138 {
4139 if (pageno >= 0 && pageno < priv->pageData.size())
4140 return (priv->pageData[pageno].dpi > 0);
4141 return false;
4142 }
4143
4144
4145 // ----------------------------------------
4146 // SETTINGS FROM ANNOTATIONS
4147
4148
4149
4150 /*! \enum QDjVuWidget::Priority
4151 Levels for prioritized properties.
4152 Certain properties can be set at various priority levels for
4153 defining the default values, annotation options, cgi options,
4154 and user specified values. Priority levels matter when one changes
4155 the current document or the current page: new property values
4156 might be unmasked when the annotation or cgi level values are unset.
4157 The prioritized properties are: \a borderSize, \a zoom,
4158 \a borderBrush, \a displayMode, \a horizAlign, \a vertAlign.
4159 */
4160
4161
4162 /*! The property setting function always set the prioritized
4163 properties at priority level \a PRIORITY_USER.
4164 This function downgrades all options set with a
4165 priority higher than \a priority to priority
4166 level \a priority.
4167 */
4168
4169 void
4170 QDjVuWidget::reduceOptionsToPriority(Priority priority)
4171 {
4172 priv->qBorderSize.reduce(priority);
4173 priv->qZoom.reduce(priority);
4174 priv->qBorderBrush.reduce(priority);
4175 priv->qDisplay.reduce(priority);
4176 priv->qHAlign.reduce(priority);
4177 priv->qVAlign.reduce(priority);
4178 // Apply changes
4179 priv->changeZoom();
4180 priv->changeHAlign();
4181 priv->changeVAlign();
4182 priv->changeDisplay();
4183 priv->changeBorderSize();
4184 priv->changeBorderBrush();
4185 }
4186
4187
4188
4189 void
4190 QDjVuPrivate::adjustSettings(Priority priority, miniexp_t annotations)
4191 {
4192 // Reset everything
4193 qZoom.unset(priority);
4194 qBorderBrush.unset(priority);
4195 qDisplay.unset(priority);
4196 qHAlign.unset(priority);
4197 qVAlign.unset(priority);
4198 qBorderSize.unset(priority);
4199
4200 // Analyse annotations
4201 if (annotations && annotations != miniexp_dummy)
4202 {
4203 const char *xbgcolor = ddjvu_anno_get_bgcolor(annotations);
4204 const char *xzoom = ddjvu_anno_get_zoom(annotations);
4205 const char *xmode = ddjvu_anno_get_mode(annotations);
4206 const char *xhorizalign = ddjvu_anno_get_horizalign(annotations);
4207 const char *xvertalign = ddjvu_anno_get_vertalign(annotations);
4208 // border color
4209 if (xbgcolor && xbgcolor[0]=='#')
4210 {
4211 QColor color(xbgcolor);
4212 qBorderBrush.set(priority, QBrush(color));
4213 }
4214 // zoom
4215 if (xzoom == QLatin1String("stretch"))
4216 qZoom.set(priority, ZOOM_STRETCH);
4217 else if (xzoom == QLatin1String("one2one"))
4218 qZoom.set(priority, ZOOM_ONE2ONE);
4219 else if (xzoom == QLatin1String("width"))
4220 qZoom.set(priority, ZOOM_FITWIDTH);
4221 else if (xzoom == QLatin1String("page"))
4222 qZoom.set(priority, ZOOM_FITPAGE);
4223 else if (xzoom && xzoom[0]=='d' && all_numbers(xzoom+1))
4224 {
4225 int zoom = strtol(xzoom+1,0,10);
4226 qZoom.set(priority, qBound((int)ZOOM_MIN, zoom, (int)ZOOM_MAX));
4227 }
4228 // display mode
4229 if (xmode == QLatin1String("color"))
4230 qDisplay.set(priority, DISPLAY_COLOR);
4231 else if (xmode == QLatin1String("bw") ||
4232 xmode == QLatin1String("black"))
4233 qDisplay.set(priority, DISPLAY_STENCIL);
4234 else if (xmode == QLatin1String("fore") ||
4235 xmode == QLatin1String("fg"))
4236 qDisplay.set(priority, DISPLAY_FG);
4237 else if (xmode == QLatin1String("back") ||
4238 xmode == QLatin1String("bg"))
4239 qDisplay.set(priority, DISPLAY_BG);
4240 // horiz align
4241 if (xhorizalign == QLatin1String("left"))
4242 qHAlign.set(priority, ALIGN_LEFT);
4243 else if (xhorizalign == QLatin1String("center"))
4244 qHAlign.set(priority, ALIGN_CENTER);
4245 else if (xhorizalign == QLatin1String("right"))
4246 qHAlign.set(priority, ALIGN_RIGHT);
4247 // vert align
4248 if (xvertalign == QLatin1String("top"))
4249 qVAlign.set(priority, ALIGN_TOP);
4250 else if (xvertalign == QLatin1String("center"))
4251 qVAlign.set(priority, ALIGN_CENTER);
4252 else if (xvertalign == QLatin1String("bottom"))
4253 qVAlign.set(priority, ALIGN_BOTTOM);
4254 // border size
4255 if (xbgcolor || xzoom || xhorizalign || xvertalign)
4256 qBorderSize.set(priority, 0);
4257 }
4258
4259 // Apply changes
4260 changeZoom();
4261 changeHAlign();
4262 changeVAlign();
4263 changeDisplay();
4264 changeBorderSize();
4265 changeBorderBrush();
4266 }
4267
4268
4269
4270 // ----------------------------------------
4271 // PAINTING
4272
4273 void
4274 QDjVuPrivate::trimPixelCache()
4275 {
4276 int pos;
4277 int pixels = 0;
4278 int sz = pixelCache.size();
4279 for (pos = 0; pos < sz; pos++)
4280 {
4281 Cache &p = pixelCache[pos];
4282 pixels += p.rect.width() * p.rect.height();
4283 if (pixels > pixelCacheSize)
4284 break;
4285 }
4286 pos = qMin(pos, 256); // hard limit!
4287 while (sz-- > pos)
4288 pixelCache.removeLast();
4289 }
4290
4291 void
4292 QDjVuPrivate::addToPixelCache(const QRect &rect, QImage image)
4293 {
4294 if (qMin(rect.width(), rect.height()) < 128)
4295 {
4296 Cache c;
4297 c.rect = rect;
4298 c.image = image;
4299 pixelCache.prepend(c);
4300 trimPixelCache();
4301 }
4302 }
4303
4304 bool
4305 QDjVuPrivate::paintHiddenText(QImage &img, Page *p, const QRect &drect,
4306 const QRect *prect)
4307 {
4308 // do not paint anything unless display is display text
4309 bool okay = false;
4310 if (display != DISPLAY_TEXT)
4311 return okay;
4312 miniexp_t q = p->hiddenText;
4313 if (p->initialRot < 0 || q == miniexp_nil || q == miniexp_dummy)
4314 return okay;
4315 if (! prect)
4316 prect = &p->rect;
4317 // setup mapper
4318 int rot = p->initialRot;
4319 int w = (rot&1) ? p->height : p->width;
4320 int h = (rot&1) ? p->width : p->height;
4321 QRectMapper mapper;
4322 mapper.setMap(QRect(0,0,w,h), *prect);
4323 mapper.setTransform(rot + rotation, false, true);
4324 // setup painter
4325 QPainter paint(&img);
4326 paint.setRenderHint(QPainter::TextAntialiasing);
4327 QColor qblue = Qt::blue;
4328 QColor qwhite = Qt::white;
4329 qwhite.setAlpha(192);
4330 // loop over text
4331 int orientation = (4 - rot - rotation) & 3;
4332 while (miniexp_consp(q))
4333 {
4334 miniexp_t r = miniexp_car(q);
4335 q = miniexp_cdr(q);
4336 if (miniexp_consp(r))
4337 {
4338 QRect rect;
4339 miniexp_t s = miniexp_nth(5, r);
4340 miniexp_t g = miniexp_cdr(r);
4341 if (miniexp_symbolp(miniexp_car(r)) &&
4342 miniexp_stringp(s) &&
4343 miniexp_get_rect_from_points(g, rect) )
4344 {
4345 rect = mapper.mapped(rect);
4346 // heuristically choose orientation
4347 int w = rect.width();
4348 int h = rect.height();
4349 QString text = miniexp_to_qstring(s).trimmed();
4350 if (text.size() >= 2)
4351 if (((orientation & 1) && (w > 2*h)) ||
4352 (!(orientation & 1) && (h > 2*w)) )
4353 orientation ^= 1;
4354 if (!drect.intersects(rect))
4355 continue;
4356 // paint frame
4357 okay = true;
4358 rect.translate(-drect.topLeft());
4359 paint.setPen(QPen(qblue, 1));
4360 paint.setBrush(qwhite);
4361 paint.drawRect(rect.adjusted(0,0,-1,-1));
4362 if (w < 6 || h < 6)
4363 continue;
4364 // paint text
4365 paint.save();
4366 paint.setClipRect(rect);
4367 rect = rect.adjusted(2,2,-2,-2);
4368 paint.translate(rect.topLeft());
4369 paint.setPen(Qt::black);
4370 paint.setBrush(Qt::NoBrush);
4371 QFont font = paint.font();
4372 font.setPixelSize(128);
4373 QFontMetrics metrics(font);
4374 #if QT_VERSION >= 0x40300 && !defined(Q_OS_WIN)
4375 QRect brect = metrics.tightBoundingRect(text);
4376 #else
4377 QRect brect = metrics.boundingRect(text);
4378 #endif
4379 double dw = rect.width();
4380 double dh = rect.height();
4381 double bw = brect.width();
4382 double bh = brect.height();
4383 if (dw > 1 && dh > 1 && bw > 1 && bh > 1)
4384 {
4385 switch(orientation)
4386 {
4387 case 2:
4388 paint.translate(dw, dh);
4389 paint.rotate(180);
4390 /* FALLTHRU */
4391 default:
4392 paint.scale(dw/bw, dh/bh);
4393 break;
4394 case 3:
4395 paint.translate(dw, dh);
4396 paint.rotate(180);
4397 /* FALLTHRU */
4398 case 1:
4399 paint.translate(dw, 0);
4400 paint.rotate(90);
4401 paint.scale(dh/bw, dw/bh);
4402 break;
4403 }
4404 paint.setFont(font);
4405 paint.drawText(-brect.topLeft(), text);
4406 }
4407 paint.restore();
4408 }
4409 }
4410 }
4411 return okay;
4412 }
4413
4414 bool
4415 QDjVuPrivate::paintMapAreas(QImage &img, Page *p, const QRect &r,
4416 bool perm, const QRect *prect)
4417 {
4418 // do not paint anything when disabled
4419 if (! displayMapAreas)
4420 return false;
4421 // setup mapper
4422 QRectMapper mapper;
4423 QRectMapper *pmapper = &p->mapper;
4424 if (! prect)
4425 prect = &p->rect;
4426 else {
4427 mapper.setMap(QRect(0,0,p->width,p->height), *prect);
4428 mapper.setTransform(rotation, false, true);
4429 pmapper = &mapper;
4430 }
4431 // warning: rect in desk coordinates.
4432 bool changed = false;
4433 for (int i=0; i<p->mapAreas.size(); i++)
4434 {
4435 QRect arect;
4436 MapArea &area = p->mapAreas[i];
4437 QPoint p1 = pmapper->mapped(area.areaRect.topLeft());
4438 QPoint p2 = pmapper->mapped(area.areaRect.bottomRight());
4439 int bw2 = (area.borderWidth + 1) / 2;
4440 arect.setLeft(qMin(p1.x(),p2.x())-bw2);
4441 arect.setTop(qMin(p1.y(),p2.y())-bw2);
4442 arect.setRight(qMax(p1.x(),p2.x())+bw2);
4443 arect.setBottom(qMax(p1.y(),p2.y())+bw2);
4444 // The above code is necessary because mapping a small rect
4445 // can round to a rect of zero width or height.
4446 if (r.intersects(arect.adjusted(-8,-8,8,8)))
4447 {
4448 if (perm)
4449 {
4450 double z = (prect->width() * p->dpi * 100.0) / (p->width * sdpi);
4451 area.paintPermanent(&img, *pmapper, r.topLeft(), z);
4452 changed = true;
4453 }
4454 else if (mustDisplayMapArea(&area) && area.hasTransient(allLinksDisplayed))
4455 {
4456 img.detach();
4457 area.paintTransient(&img, *pmapper, r.topLeft(), allLinksDisplayed);
4458 changed = true;
4459 }
4460 }
4461 }
4462 return changed;
4463 }
4464
4465 bool
4466 QDjVuPrivate::paintPage(QPainter &paint, Page *p, const QRegion &region)
4467 {
4468 // check
4469 if (region.isEmpty())
4470 return true;
4471 if (p->dpi<=0 || p->page==0)
4472 return false;
4473 // invalidate cache when device pixel ratio changes
4474 #if QT_VERSION >= 0x50200
4475 int dpr = paint.device()->devicePixelRatio();
4476 if (devicePixelRatio != dpr)
4477 pixelCache.clear();
4478 devicePixelRatio = dpr;
4479 #else
4480 int dpr = 1;
4481 #endif
4482 // caching
4483 QList<Cache*> cachelist;
4484 QRegion remainder = region;
4485 QPoint deskToView = - visibleRect.topLeft();
4486 for (int i=0; i<pixelCache.size(); i++)
4487 {
4488 QRect rect = pixelCache[i].rect.translated(deskToView);
4489 if (! region.intersects(rect)) continue;
4490 cachelist << &pixelCache[i];
4491 remainder -= rect;
4492 }
4493 // cover
4494 QRegion cover = cover_region(remainder, p->viewRect);
4495 // prune cache list
4496 QRegion shown = cover;
4497 for (int i=cachelist.size()-1; i>=0; i--)
4498 {
4499 QRect r = cachelist[i]->rect.translated(deskToView);
4500 r = region.intersected(r).boundingRect();
4501 if (shown.intersected(r) == r)
4502 cachelist.removeAt(i);
4503 shown += r;
4504 }
4505 // process cached segments
4506 QRegion displayed;
4507 for (int i=0; i<cachelist.size(); i++)
4508 {
4509 Cache *cache = cachelist[i];
4510 QImage img = cache->image;
4511 QRect r = cache->rect;
4512 #if QDJVUWIDGET_PIXMAP_CACHE
4513 if (cache->pixmap.isNull())
4514 cache->pixmap = QPixmap::fromImage(img, Qt::ThresholdDither);
4515 bool hastransient = paintMapAreas(img, p, r, false);
4516 #else
4517 paintMapAreas(img, p, r, false);
4518 #endif
4519 r.translate(deskToView);
4520 QRegion dr = region.intersected(r) - displayed;
4521 if (dr.isEmpty()) continue;
4522 QRect d = dr.boundingRect();
4523 displayed += d;
4524 QRect s = d.translated(-r.topLeft());
4525 if (dpr > 1)
4526 s.setRect(s.left()*dpr, s.top()*dpr, s.width()*dpr, s.height()*dpr);
4527 #if QDJVUWIDGET_PIXMAP_CACHE
4528 if (hastransient)
4529 paint.drawImage(d.topLeft(), img, s, Qt::ThresholdDither);
4530 else
4531 paint.drawPixmap(d.topLeft(), cachelist[i]->pixmap, s);
4532 #else
4533 paint.drawImage(d.topLeft(), img, s, Qt::ThresholdDither);
4534 #endif
4535 }
4536 // mode for new segments
4537 ddjvu_render_mode_t mode = DDJVU_RENDER_COLOR;
4538 if (display == DISPLAY_STENCIL)
4539 mode = DDJVU_RENDER_BLACK;
4540 else if (display == DISPLAY_BG)
4541 mode = DDJVU_RENDER_BACKGROUND;
4542 else if (display == DISPLAY_FG)
4543 mode = DDJVU_RENDER_FOREGROUND;
4544 // render new segments
4545 foreachrect(const QRect &ri, cover)
4546 {
4547 int rot;
4548 ddjvu_rect_t pr, rr;
4549 QRect r = ri.translated(visibleRect.topLeft());
4550 QImage img(r.width()*dpr, r.height()*dpr, QImage::Format_RGB32);
4551 #if QT_VERSION >= 0x50200
4552 img.setDevicePixelRatio(dpr);
4553 #endif
4554 QDjVuPage *dp = p->page;
4555 qrect_to_rect(r, rr, dpr);
4556 qrect_to_rect(p->rect, pr, dpr);
4557 #if DDJVUAPI_VERSION < 18
4558 p->initialRot = ddjvu_page_get_initial_rotation(*dp);
4559 #endif
4560 rot = p->initialRot + rotation;
4561 ddjvu_page_set_rotation(*dp, (ddjvu_page_rotation_t)(rot & 0x3));
4562 if (! ddjvu_page_render(*dp, mode, &pr, &rr, renderFormat,
4563 img.bytesPerLine(), (char*)img.bits() ))
4564 return false;
4565 paintHiddenText(img, p, r);
4566 if (invertLuminance)
4567 invert_luminance(img);
4568 paintMapAreas(img, p, r, true);
4569 addToPixelCache(r, img);
4570 paintMapAreas(img, p, r, false);
4571 r.translate(deskToView);
4572 QRegion dr = region.intersected(r) - displayed;
4573 if (dr.isEmpty()) continue;
4574 QRect d = dr.boundingRect();
4575 displayed += d;
4576 QRect s = d.translated(-r.topLeft());
4577 if (dpr > 1)
4578 s.setRect(s.left()*dpr, s.top()*dpr, s.width()*dpr, s.height()*dpr);
4579 paint.drawImage(d.topLeft(), img, s, Qt::ThresholdDither);
4580 }
4581 return true;
4582 }
4583
4584 void
4585 QDjVuPrivate::paintAll(QPainter &paint, const QRegion &paintRegion)
4586 {
4587 // Document not ready yet
4588 if (pageLayout.isEmpty())
4589 {
4590 bool waiting = (docReady || !docFailed) && !docStopped;
4591 QRect rect(QPoint(borderSize,borderSize), unknownSize);
4592 widget->paintEmpty(paint, rect, waiting, docStopped, docFailed);
4593 widget->paintDesk(paint, paintRegion-rect);
4594 widget->paintFrame(paint, rect, shadowSize);
4595 return;
4596 }
4597 // Document ready.
4598 Page *p;
4599 foreach(p, pageVisible)
4600 {
4601 // Paint page
4602 QRegion region = paintRegion & p->viewRect;
4603 if (! paintPage(paint, p, region))
4604 {
4605 // Cannot paint page yet
4606 ddjvu_status_t s = DDJVU_JOB_FAILED;
4607 if (p->page && *(p->page))
4608 s = ddjvu_page_decoding_status(*(p->page));
4609 if (!p->page && pageRequestTimer->isActive())
4610 s = DDJVU_JOB_STARTED;
4611 widget->paintEmpty(paint, p->viewRect,
4612 s==DDJVU_JOB_STARTED,
4613 s==DDJVU_JOB_STOPPED,
4614 s==DDJVU_JOB_FAILED);
4615 }
4616 // Paint frames to reduce flashing.
4617 if (frame)
4618 widget->paintFrame(paint, p->viewRect, shadowSize);
4619 }
4620 // Paint desk
4621 QRegion deskRegion = paintRegion;
4622 foreach(p, pageVisible)
4623 deskRegion -= p->viewRect;
4624 widget->paintDesk(paint, deskRegion);
4625 // Paint frames again
4626 if (frame)
4627 {
4628 foreach(p, pageLayout)
4629 {
4630 QRect rect = p->rect.adjusted(0,0,shadowSize,shadowSize);
4631 if (visibleRect.intersects(rect))
4632 widget->paintFrame(paint, p->viewRect, shadowSize);
4633 }
4634 }
4635 // Paint selected rectangle
4636 if (! selectedRect.isEmpty())
4637 {
4638 paint.setBrush(QColor(128,128,192,64));
4639 paint.setPen(QPen(QColor(64,64,96,255), 1));
4640 paint.drawRect(selectedRect.adjusted(0,0,-1,-1));
4641 }
4642 // Paint hour glass
4643 if (hourGlassRatio > 0)
4644 {
4645 QRect rect = hourGlassRect();
4646 if (! rect.isEmpty())
4647 {
4648 const int tp = 360*16;
4649 paint.setPen(QPen());
4650 paint.setBrush(QColor(128,128,192,128));
4651 paint.drawPie(rect, tp/4, (int)(tp*hourGlassRatio));
4652 }
4653 }
4654 }
4655
4656
4657
4658 /*! \internal */
4659 void
4660 QDjVuWidget::paintEvent(QPaintEvent *event)
4661 {
4662 // mark maparea
4663 if (priv->currentMapArea)
4664 {
4665 MapArea *a = priv->currentMapArea;
4666 priv->currentLinkDisplayed = priv->mustDisplayMapArea(a);
4667 }
4668 // paint everything
4669 QPainter paint(viewport());
4670 QRegion region = event->region() & viewport()->rect();
4671 priv->paintAll(paint, region);
4672 // debugging code
4673 #ifdef DEBUG_SHOW_PAINTED_AREAS
4674 QColor color(rand()%256,rand()%256,rand()%256);
4675 color.setAlpha(128);
4676 paint.setClipRegion(region);
4677 paint.fillRect(region.boundingRect(), color);
4678 #endif
4679 }
4680
4681
4682 // ----------------------------------------
4683 // USER INTERFACE
4684
4685
4686 /*! Overridden \a QAbstractScrollArea virtual function. */
4687 void
4688 QDjVuWidget::scrollContentsBy(int, int)
4689 {
4690 if (! priv->changingSBars)
4691 {
4692 QScrollBar *hBar = horizontalScrollBar();
4693 QScrollBar *vBar = verticalScrollBar();
4694 QPoint p = priv->visibleRect.topLeft();
4695 if (hBar->maximum() > hBar->minimum())
4696 p.rx() = hBar->sliderPosition();
4697 if (vBar->maximum() > vBar->minimum())
4698 p.ry() = vBar->sliderPosition();
4699 QPoint np = p - priv->visibleRect.topLeft();
4700 priv->movePoint = priv->currentPoint;
4701 priv->movePos = priv->findPosition(np + priv->movePoint);
4702 priv->changeLayout(CHANGE_VIEW);
4703 priv->clearAnimation();
4704 }
4705 }
4706
4707
4708 /*! Overridden \a QAbstractScrollArea virtual function. */
4709 bool
4710 QDjVuWidget::event(QEvent *event)
4711 {
4712 // Actual widget resize instead of viewport.
4713 if (event->type() == QEvent::Resize)
4714 priv->layoutLoop = 0;
4715 // Default function
4716 return QAbstractScrollArea::event(event);
4717 }
4718
4719 /*! Overridden \a QAbstractScrollArea virtual function. */
4720 bool
4721 QDjVuWidget::viewportEvent(QEvent *event)
4722 {
4723 switch (event->type())
4724 {
4725 case QEvent::Enter:
4726 // Install filter to capture modifiers
4727 QApplication::instance()->installEventFilter(priv);
4728 break;
4729 case QEvent::Leave:
4730 // Remove filter to capture modifiers
4731 QApplication::instance()->removeEventFilter(priv);
4732 // Uncheck any active map area
4733 priv->checkCurrentMapArea(true);
4734 break;
4735 #if QT_VERSION >= 0x040600
4736 case QEvent::Gesture:
4737 gestureEvent(event);
4738 if (event->isAccepted())
4739 return true;
4740 break;
4741 #endif
4742 default:
4743 break;
4744 }
4745 // The default function calls the following
4746 // QAbstractScrollArea handlers:
4747 // - resizeEvent, paintEvent
4748 // - mouse{Press,Release,Move}Event
4749 // - contextMenuEvent
4750 return QAbstractScrollArea::viewportEvent(event);
4751 }
4752
4753
4754 /*! Overridden \a QAbstractScrollArea virtual function. */
4755 void
4756 QDjVuWidget::resizeEvent(QResizeEvent *event)
4757 {
4758 QAbstractScrollArea::resizeEvent(event);
4759 int change = CHANGE_VISIBLE|CHANGE_SCROLLBARS;
4760 if (priv->zoom == ZOOM_FITWIDTH ||
4761 priv->zoom == ZOOM_FITPAGE ||
4762 priv->zoom == ZOOM_STRETCH )
4763 change |= CHANGE_SCALE;
4764 // Do not reset loop counter
4765 // Update layout immediately because Qt40 gets confused
4766 // by asynchronous mixes of scrolls and resizes.
4767 // Also we do not want to reset the loop counter!
4768 priv->layoutChange |= change;
4769 priv->makeLayout();
4770 }
4771
4772
4773 /* capture modifier changes */
4774 bool
4775 QDjVuPrivate::eventFilter(QObject *, QEvent *event)
4776 {
4777 QEvent::Type type = event->type();
4778 switch (type)
4779 {
4780 default:
4781 return false;
4782 case QEvent::KeyPress:
4783 case QEvent::KeyRelease:
4784 Qt::KeyboardModifiers change = Qt::NoModifier;
4785 QKeyEvent *kevent = (QKeyEvent*)event;
4786 switch (kevent->key())
4787 {
4788 case Qt::Key_Shift:
4789 change = Qt::ShiftModifier;
4790 break;
4791 case Qt::Key_Control:
4792 change = Qt::ControlModifier;
4793 break;
4794 case Qt::Key_Alt:
4795 change = Qt::AltModifier;
4796 break;
4797 case Qt::Key_Meta:
4798 change = Qt::MetaModifier;
4799 break;
4800 default:
4801 return false;
4802 }
4803 if (type == QEvent::KeyPress)
4804 updateModifiers(modifiers | change, buttons);
4805 else
4806 updateModifiers(modifiers & ~change, buttons);
4807 }
4808 return false;
4809 }
4810
4811 void
4812 QDjVuPrivate::updateModifiers(Qt::KeyboardModifiers newModifiers,
4813 Qt::MouseButtons newButtons)
4814 {
4815 Qt::KeyboardModifiers oldModifiers = modifiers;
4816 Qt::MouseButtons oldButtons = buttons;
4817 modifiers = newModifiers;
4818 buttons = newButtons;
4819 if (modifiers != oldModifiers)
4820 showTransientMapAreas(modifiers == modifiersForLinks &&
4821 modifiers != Qt::NoModifier );
4822 if (modifiers != oldModifiers ||
4823 buttons != oldButtons )
4824 widget->modifierEvent(modifiers, buttons, cursorPoint);
4825 }
4826
4827 void
4828 QDjVuPrivate::changeSelectedRectangle(const QRect& rect)
4829 {
4830 QRect normRect = rect.normalized();
4831 QRect newRect;
4832 if (normRect.width() >= 2 && normRect.height() >= 2)
4833 newRect = normRect;
4834 QRect oldRect = selectedRect;
4835 selectedRect = newRect;
4836 if (oldRect.isEmpty())
4837 widget->viewport()->update(newRect.adjusted(-2,-2,2,2));
4838 else if (newRect.isEmpty())
4839 widget->viewport()->update(oldRect.adjusted(-2,-2,2,2));
4840 else
4841 {
4842 QRegion region = QRegion(newRect) ^ QRegion(oldRect);
4843 QRegion dilated;
4844 foreachrect(const QRect &r, region)
4845 dilated += r.adjusted(-2,-2,2,2);
4846 widget->viewport()->update(dilated);
4847 }
4848 }
4849
4850
4851 /*! This function should be called from \a modifierEvent.
4852 It sets the specified cursor, initiates the interactively
4853 selection of a rectangular area, and returns immediately.
4854 The interactive selection stops when all mouse buttons and
4855 modifiers are released.
4856 */
4857
4858 bool
4859 QDjVuWidget::startSelecting(const QPoint &point)
4860 {
4861 priv->updatePosition(point, true);
4862 if (priv->dragMode == DRAG_NONE)
4863 {
4864 priv->dragStart = point;
4865 priv->dragMode = DRAG_SELECTING;
4866 return true;
4867 }
4868 return false;
4869 }
4870
4871 /*! This function should be called from \a modifierEvent.
4872 It initiates panning the display area, and returns immediately.
4873 Panning stops when all mouse buttons and modifiers are released. */
4874
4875 bool
4876 QDjVuWidget::startPanning(const QPoint &point)
4877 {
4878 priv->updatePosition(point, true);
4879 if (priv->dragMode == DRAG_NONE)
4880 {
4881 priv->dragStart = point;
4882 priv->dragMode = DRAG_PANNING;
4883 return true;
4884 }
4885 return false;
4886 }
4887
4888 /*! This function should be called from \a modifierEvent.
4889 It initiates selecting the current hyperlink and returns immediately.
4890 Interaction stops when all mouse buttons and modifiers are released.
4891 Interaction changes to panning of the mouse moves more than 8 pixels. */
4892
4893 bool
4894 QDjVuWidget::startLinking(const QPoint &point)
4895 {
4896 priv->updatePosition(point, true);
4897 if (priv->dragMode == DRAG_NONE)
4898 {
4899 priv->dragStart = point;
4900 priv->dragMode = DRAG_LINKING;
4901 return true;
4902 }
4903 return false;
4904 }
4905
4906 /*! This function should be called from \a modifierEvent.
4907 It initiates user interaction with the magnification lens
4908 and returns immediately. Lensing stops when all mouse buttons
4909 and modifiers are released. */
4910
4911 bool
4912 QDjVuWidget::startLensing(const QPoint &point)
4913 {
4914 if (priv->dragMode == DRAG_NONE
4915 && priv->lensMag>0 && priv->lensSize>0 )
4916 {
4917 priv->dragStart = point;
4918 priv->dragMode = DRAG_LENSING;
4919 priv->lens = new QDjVuLens(priv->lensSize, priv->lensMag, priv, this);
4920 QRect r = priv->lens->geometry();
4921 QPoint p = viewport()->mapToGlobal(point);
4922 r.translate(p - r.center());
4923 priv->lens->setGeometry(r);
4924 priv->lens->show();
4925 return true;
4926 }
4927 return false;
4928 }
4929
4930 /*! Terminates user interaction initiated by \a startSelecting,
4931 \a startPanning ot \a startLensing. Returns \a true if such
4932 interaction was ongoing, \a false otherwise. */
4933
4934 bool
4935 QDjVuWidget::stopInteraction(void)
4936 {
4937 QRect temp;
4938 switch (priv->dragMode)
4939 {
4940 case DRAG_LINKING:
4941 priv->updatePosition(priv->cursorPoint, true);
4942 if (priv->currentMapArea && priv->currentMapArea->clicked())
4943 {
4944 priv->pixelCache.clear();
4945 priv->currentMapArea->update(priv->widget->viewport(),
4946 priv->currentMapAreaPage->mapper,
4947 priv->visibleRect.topLeft(),
4948 true);
4949 }
4950 else if (priv->currentMapArea && priv->currentMapArea->url
4951 && priv->hyperlinkEnabled )
4952 emit pointerClick(priv->cursorPos, priv->currentMapArea->expr);
4953 break;
4954 case DRAG_SELECTING:
4955 priv->updatePosition(priv->cursorPoint, true);
4956 temp = priv->selectedRect;
4957 emit pointerSelect(viewport()->mapToGlobal(priv->cursorPoint), temp);
4958 priv->changeSelectedRectangle(QRect());
4959 break;
4960 case DRAG_LENSING:
4961 priv->lens->hide();
4962 priv->lens->deleteLater();
4963 priv->lens = 0;
4964 break;
4965 case DRAG_PANNING:
4966 priv->updatePosition(priv->cursorPoint, true);
4967 break;
4968 default:
4969 return false;
4970 }
4971 priv->dragMode = DRAG_NONE;
4972 return true;
4973 }
4974
4975 /*!
4976 This function is called when the set of depressed
4977 modifiers and mouse button changes while the cursor
4978 is at position \a point in the viewport. It is also called
4979 when the pointer crosses hyperlink boundaries or when the
4980 gui interaction settings change.
4981 */
4982
4983 void
4984 QDjVuWidget::modifierEvent(Qt::KeyboardModifiers modifiers,
4985 Qt::MouseButtons buttons,
4986 QPoint point)
4987 {
4988 if (priv->dragMode != DRAG_NONE &&
4989 modifiers == Qt::NoModifier &&
4990 buttons == Qt::NoButton)
4991 {
4992 stopInteraction();
4993 }
4994 if (priv->dragMode == DRAG_NONE)
4995 {
4996 if (! priv->mouseEnabled)
4997 {
4998 viewport()->setCursor(Qt::ArrowCursor);
4999 }
5000 else if (buttons & Qt::RightButton)
5001 {
5002 return; // Wait for the contextMenuEvent
5003 }
5004 else if (modifiers == Qt::NoModifier &&
5005 buttons == Qt::MiddleButton )
5006 {
5007 viewport()->setCursor(Qt::CrossCursor);
5008 startSelecting(point);
5009 }
5010 else if (modifiers == Qt::ControlModifier &&
5011 buttons == Qt::MiddleButton )
5012 {
5013 viewport()->setCursor(priv->cursHandClosed);
5014 startPanning(point);
5015 }
5016 else if (modifiers == priv->modifiersForLens &&
5017 modifiers != Qt::NoModifier )
5018 {
5019 viewport()->setCursor(Qt::CrossCursor);
5020 startLensing(point);
5021 }
5022 else if (modifiers == priv->modifiersForSelect)
5023 {
5024 viewport()->setCursor(Qt::CrossCursor);
5025 if (buttons != Qt::NoButton)
5026 startSelecting(point);
5027 }
5028 else if (priv->currentMapArea &&
5029 priv->currentMapArea->isClickable(priv->hyperlinkEnabled) )
5030 {
5031 viewport()->setCursor(Qt::ArrowCursor);
5032 if (buttons != Qt::NoButton)
5033 startLinking(point);
5034 }
5035 else if (buttons != Qt::NoButton)
5036 {
5037 viewport()->setCursor(priv->cursHandClosed);
5038 startPanning(point);
5039 }
5040 else
5041 {
5042 viewport()->setCursor(priv->cursHandOpen);
5043 }
5044 }
5045 }
5046
5047 /*! Override \a QAbstractScrollArea virtual function. */
5048 void
5049 QDjVuWidget::mousePressEvent(QMouseEvent *event)
5050 {
5051 mouseMoveEvent(event);
5052 }
5053
5054 /*! Override \a QAbstractScrollArea virtual function. */
5055 void
5056 QDjVuWidget::mouseDoubleClickEvent(QMouseEvent *event)
5057 {
5058 mouseMoveEvent(event);
5059 }
5060
5061 /*! Override \a QAbstractScrollArea virtual function. */
5062 void
5063 QDjVuWidget::mouseReleaseEvent(QMouseEvent *event)
5064 {
5065 mouseMoveEvent(event);
5066 }
5067
5068
5069 bool
5070 QDjVuPrivate::pointerScroll(const QPoint &p)
5071 {
5072 int dx = 0;
5073 int dy = 0;
5074 QRect r = widget->viewport()->rect();
5075 if (p.x() >= r.right())
5076 dx = lineStep;
5077 else if (p.x() < r.left())
5078 dx = -lineStep;
5079 if (p.y() >= r.bottom())
5080 dy = lineStep;
5081 else if (p.y() < r.top())
5082 dy = -lineStep;
5083 if (dx == 0 && dy == 0)
5084 return false;
5085 movePos = cursorPos;
5086 movePoint = cursorPoint - QPoint(dx,dy);
5087 changeLayout(CHANGE_VIEW|CHANGE_SCROLLBARS);
5088 clearAnimation();
5089 return true;
5090 }
5091
5092
5093 /*! Override \a QAbstractScrollArea virtual function. */
5094 void
5095 QDjVuWidget::mouseMoveEvent(QMouseEvent *event)
5096 {
5097 event->accept();
5098 QPoint p = event->pos();
5099 priv->cursorPoint = p;
5100 priv->updateModifiers(event->modifiers(), event->buttons());
5101 switch (priv->dragMode)
5102 {
5103 case DRAG_LINKING:
5104 priv->updatePosition(event->pos());
5105 p = p - priv->dragStart;
5106 if (p.manhattanLength() <= 8)
5107 break;
5108 viewport()->setCursor(priv->cursHandClosed);
5109 priv->dragMode = DRAG_PANNING;
5110 // fall through
5111 case DRAG_PANNING:
5112 priv->movePoint = priv->cursorPoint;
5113 priv->movePos = priv->cursorPos;
5114 priv->changeLayout(CHANGE_VIEW|CHANGE_SCROLLBARS);
5115 priv->clearAnimation();
5116 break;
5117 case DRAG_SELECTING:
5118 priv->updatePosition(p);
5119 priv->changeSelectedRectangle(QRect(priv->dragStart, event->pos()));
5120 priv->pointerScroll(p);
5121 break;
5122 case DRAG_LENSING:
5123 priv->updatePosition(p);
5124 if (! priv->pointerScroll(p))
5125 priv->lens->recenter(event->pos());
5126 break;
5127 default:
5128 priv->updatePosition(p);
5129 break;
5130 }
5131 }
5132
5133 /*! Override \a QAbstractScrollArea virtual function. */
5134 void
5135 QDjVuWidget::keyPressEvent(QKeyEvent *event)
5136 {
5137 if (priv->keyboardEnabled)
5138 {
5139 // Capturing this signal can override any key binding
5140 bool done = false;
5141 emit keyPressSignal(event, done);
5142 if (done)
5143 return;
5144 // Standard key bindings
5145 Qt::KeyboardModifiers modifiers = event->modifiers();
5146 switch(event->key())
5147 {
5148 case Qt::Key_1:
5149 setZoom(100);
5150 break;
5151 case Qt::Key_2:
5152 setZoom(200);
5153 break;
5154 case Qt::Key_3:
5155 setZoom(300);
5156 break;
5157 case Qt::Key_W:
5158 setZoom(ZOOM_FITWIDTH);
5159 break;
5160 case Qt::Key_P:
5161 setZoom(ZOOM_FITPAGE);
5162 break;
5163 case Qt::Key_BracketLeft:
5164 priv->updateCurrentPoint(priv->cursorPos);
5165 rotateLeft();
5166 break;
5167 case Qt::Key_BracketRight:
5168 priv->updateCurrentPoint(priv->cursorPos);
5169 rotateRight();
5170 break;
5171 case Qt::Key_Plus:
5172 case Qt::Key_Equal:
5173 priv->updateCurrentPoint(priv->cursorPos);
5174 zoomIn();
5175 break;
5176 case Qt::Key_Minus:
5177 priv->updateCurrentPoint(priv->cursorPos);
5178 zoomOut();
5179 break;
5180 case Qt::Key_Home:
5181 if (modifiers == Qt::ControlModifier)
5182 firstPage();
5183 else if (modifiers == Qt::NoModifier)
5184 moveToPageTop();
5185 else
5186 return;
5187 break;
5188 case Qt::Key_End:
5189 if (modifiers==Qt::ControlModifier)
5190 lastPage();
5191 else if (modifiers == Qt::NoModifier)
5192 moveToPageBottom();
5193 else
5194 return;
5195 break;
5196 case Qt::Key_PageUp:
5197 prevPage();
5198 break;
5199 case Qt::Key_PageDown:
5200 nextPage();
5201 break;
5202 case Qt::Key_Space:
5203 if (modifiers==Qt::ShiftModifier)
5204 readPrev();
5205 else if (modifiers == Qt::NoModifier)
5206 readNext();
5207 else
5208 return;
5209 break;
5210 case Qt::Key_B:
5211 case Qt::Key_Backspace:
5212 if (modifiers==Qt::ShiftModifier)
5213 readNext();
5214 else if (modifiers == Qt::NoModifier)
5215 readPrev();
5216 else
5217 return;
5218 break;
5219 case Qt::Key_Left:
5220 case Qt::Key_Right:
5221 case Qt::Key_Up:
5222 case Qt::Key_Down:
5223 if (modifiers == Qt::NoModifier) {
5224 int svstep = verticalScrollBar()->singleStep();
5225 int shstep = horizontalScrollBar()->singleStep();
5226 verticalScrollBar()->setSingleStep(priv->lineStep);
5227 horizontalScrollBar()->setSingleStep(priv->lineStep);
5228 QAbstractScrollArea::keyPressEvent(event);
5229 verticalScrollBar()->setSingleStep(svstep);
5230 horizontalScrollBar()->setSingleStep(shstep);
5231 } else
5232 return;
5233 break;
5234 case Qt::Key_H:
5235 {
5236 int pageno = page();
5237 if (pageno>=0)
5238 clearHighlights(pageno);
5239 break;
5240 }
5241 default:
5242 // Return without accepting the event
5243 return;
5244 }
5245 // Only reach this point when key is accepted
5246 event->accept();
5247 }
5248 }
5249
5250 /*! Override \a QAbstractScrollArea virtual function. */
5251 void
5252 QDjVuWidget::contextMenuEvent (QContextMenuEvent *event)
5253 {
5254 if (priv->contextMenu)
5255 {
5256 priv->contextMenu->exec(event->globalPos());
5257 event->accept();
5258 }
5259 }
5260
5261
5262 /*! Override \a QAbstractScrollArea virtual function. */
5263 void
5264 QDjVuWidget::wheelEvent (QWheelEvent *event)
5265 {
5266 if (priv->mouseEnabled)
5267 {
5268 #if QT_VERSION < 0x50200
5269 int delta = 0;
5270 if (event->orientation() == Qt::Vertical)
5271 delta = event->delta();
5272 #else
5273 int delta = event->angleDelta().y();
5274 #endif
5275 bool zoom = priv->mouseWheelZoom;
5276 if (event->modifiers() == Qt::ControlModifier)
5277 zoom = ! zoom;
5278 if (zoom && delta)
5279 {
5280 static int zWheel = 0;
5281 zWheel += delta;
5282 if (qAbs(zWheel) >= 120)
5283 {
5284 priv->updateCurrentPoint(priv->cursorPos);
5285 if (zWheel > 0)
5286 zoomIn();
5287 else
5288 zoomOut();
5289 zWheel = 0;
5290 }
5291 return;
5292 }
5293 }
5294 QAbstractScrollArea::wheelEvent(event);
5295 }
5296
5297
5298 /*! New virtual function. */
5299 void
5300 QDjVuWidget::gestureEvent(QEvent *e)
5301 {
5302 #if QT_VERSION >= 0x040600
5303 if (e->type() == QEvent::Gesture)
5304 {
5305 QGestureEvent *g = (QGestureEvent*)(e);
5306 QPinchGesture *p = (QPinchGesture*)(g->gesture(Qt::PinchGesture));
5307 if (p)
5308 {
5309 g->accept(p);
5310 if (p->state() == Qt::GestureStarted)
5311 priv->savedFactor = priv->zoomFactor;
5312 if (p->state() == Qt::GestureCanceled)
5313 setZoom(priv->savedFactor);
5314 else if (p->changeFlags() & QPinchGesture::ScaleFactorChanged)
5315 {
5316 qreal z = priv->savedFactor * p->scaleFactor();
5317 setZoom(qBound((int)ZOOM_MIN, (int)z, (int)ZOOM_MAX));
5318 }
5319 return;
5320 }
5321 }
5322 #endif
5323 e->ignore();
5324 }
5325
5326 bool
5327 QDjVuPrivate::computeAnimation(const Position &pos, const QPoint &p)
5328 {
5329 // no animation unless layout is finalized.
5330 if (layoutChange)
5331 return false;
5332 if (0 > pos.pageNo || pos.pageNo >= numPages)
5333 return false;
5334 Position currentPos = findPosition(p);
5335 Position targetPos = pos;
5336 Page *currentPage = pageMap.value(currentPos.pageNo, 0);
5337 Page *targetPage = pageMap.value(targetPos.pageNo, 0);
5338 // Standardize target position
5339 if (targetPos.inPage && targetPage && targetPage->dpi > 0)
5340 {
5341 QPoint dp = targetPage->mapper.mapped(targetPos.posPage);
5342 targetPos.hAnchor = targetPos.vAnchor = 0;
5343 targetPos.posView = dp - targetPage->rect.topLeft();
5344 targetPos.inPage = false;
5345 }
5346 if (targetPos.inPage)
5347 return false;
5348 // Both position on the same page
5349 if (currentPos.pageNo == targetPos.pageNo)
5350 {
5351 char dHAnchor = targetPos.hAnchor - currentPos.hAnchor;
5352 char dVAnchor = targetPos.vAnchor - currentPos.vAnchor;
5353 QPoint dPosView = targetPos.posView - currentPos.posView;
5354 const double profile[] = { 0.05, 0.3, 0.5, 0.7, 0.95 };
5355 const int profileSize = (int)(sizeof(profile)/sizeof(double));
5356 for (int i=0; i<profileSize; i++)
5357 {
5358 double s = profile[i];
5359 Position ipos = currentPos;
5360 ipos.hAnchor += (char)(dHAnchor * s);
5361 ipos.vAnchor += (char)(dVAnchor * s);
5362 ipos.posView.rx() += (int)(dPosView.x() * s);
5363 ipos.posView.ry() += (int)(dPosView.y() * s);
5364 ipos.inPage = false;
5365 ipos.doPage = false;
5366 animationPosition << ipos;
5367 }
5368 animationPoint = p;
5369 animationPosition << pos;
5370 animationTimer->start(10);
5371 return true;
5372 }
5373 // Both position in the same view
5374 if (currentPage && targetPage)
5375 {
5376 // compute desk positions.
5377 QPointF cPoint = currentPage->rect.topLeft() + currentPos.posView;
5378 if (currentPos.hAnchor > 0 && currentPos.hAnchor <= 100)
5379 cPoint.rx() += currentPage->rect.width() * currentPos.hAnchor / 100.0;
5380 if (currentPos.vAnchor > 0 && currentPos.vAnchor <= 100)
5381 cPoint.ry() += currentPage->rect.height() * currentPos.vAnchor / 100.0;
5382 QPointF tPoint = targetPage->rect.topLeft() + targetPos.posView;
5383 if (targetPos.hAnchor > 0 && targetPos.hAnchor <= 100)
5384 tPoint.rx() += targetPage->rect.width() * targetPos.hAnchor / 100.0;
5385 if (targetPos.vAnchor > 0 && targetPos.vAnchor <= 100)
5386 tPoint.ry() += targetPage->rect.height() * targetPos.vAnchor / 100.0;
5387 // compute delta
5388 QPointF v = tPoint - cPoint;
5389 qreal cs = max_stay_in_rect(cPoint, currentPage->rect, v);
5390 qreal ts = max_stay_in_rect(tPoint, targetPage->rect, -v);
5391 const double profile[] = { 0.05, 0.3, 0.5, 0.75, 1 };
5392 const int profileSize = (int)(sizeof(profile)/sizeof(double));
5393 for (int i=0; i<profileSize; i++)
5394 {
5395 QPointF ipoint = cPoint + cs * profile[i] * v;
5396 Position ipos;
5397 ipos.pageNo = currentPos.pageNo;
5398 ipos.hAnchor = ipos.vAnchor = 0;
5399 ipos.inPage = ipos.doPage = false;
5400 ipos.posView = ipoint.toPoint() - currentPage->rect.topLeft();
5401 animationPosition << ipos;
5402 }
5403 for (int i=profileSize-1; i>=0; i--)
5404 {
5405 QPointF ipoint = tPoint - ts * profile[i] * v;
5406 Position ipos;
5407 ipos.pageNo = targetPos.pageNo;
5408 ipos.hAnchor = ipos.vAnchor = 0;
5409 ipos.inPage = ipos.doPage = false;
5410 ipos.posView = ipoint.toPoint() - targetPage->rect.topLeft();
5411 animationPosition << ipos;
5412 }
5413 animationPoint = p;
5414 animationPosition << pos;
5415 animationTimer->start(10);
5416 return true;
5417 }
5418 // Too complex
5419 return false;
5420 }
5421
5422
5423 void
5424 QDjVuPrivate::clearAnimation(void)
5425 {
5426 animationTimer->stop();
5427 animationPosition.clear();
5428 }
5429
5430 void
5431 QDjVuPrivate::animate(void)
5432 {
5433 if (! animationPosition.isEmpty())
5434 {
5435 movePoint = animationPoint;
5436 movePos = animationPosition.takeFirst();
5437 if (! pageMap.contains(movePos.pageNo))
5438 changeLayout(CHANGE_VIEW|CHANGE_SCROLLBARS);
5439 else
5440 changeLayout(CHANGE_PAGES|CHANGE_VIEW|CHANGE_SCROLLBARS);
5441 }
5442 if (animationPosition.isEmpty())
5443 animationTimer->stop();
5444 }
5445
5446
5447 /*!
5448 Terminates all animations in progress and
5449 make sure the page layout is fully updated.
5450 */
5451 void
5452 QDjVuWidget::terminateAnimation(void)
5453 {
5454 while (priv->animationPosition.size() > 1)
5455 priv->animationPosition.removeFirst();
5456 priv->animate();
5457 if (priv->layoutChange)
5458 priv->makeLayout();
5459 }
5460
5461
5462 // ----------------------------------------
5463 // VIRTUALS
5464
5465 /*!
5466 Paint the gray area that surrounds the pages.
5467 Overload this function to redefine the
5468 appearance of this area.
5469 */
5470
5471 void
5472 QDjVuWidget::paintDesk(QPainter &p, const QRegion &region)
5473 {
5474 p.save();
5475 p.setClipRegion(region, Qt::IntersectClip);
5476 p.setBrushOrigin(- priv->visibleRect.topLeft());
5477 p.fillRect(region.boundingRect(), priv->borderBrush);
5478 p.restore();
5479 }
5480
5481 /*!
5482 Paint the frame and the shadow surrounding a page.
5483 Argument \a rect is the page rectangle.
5484 Overload this function to redefine the
5485 appearance of the page frame.
5486 */
5487
5488 void
5489 QDjVuWidget::paintFrame(QPainter &p, const QRect &crect, int sw)
5490 {
5491 QRect rect = crect.adjusted(0,0,-1,-1);
5492 if (!rect.isValid())
5493 return;
5494 // draw shadow
5495 QBrush brush(QColor(0,0,0,80));
5496 p.setPen(Qt::NoPen);
5497 p.setBrush(brush);
5498 p.drawRect(rect.right()+1, rect.top()+sw, sw, rect.height());
5499 if (rect.width() > sw)
5500 p.drawRect(rect.left()+sw, rect.bottom()+1, rect.width()-sw, sw);
5501 // draw frame
5502 p.setBrush(Qt::NoBrush);
5503 QPen pen(Qt::black, 1, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin);
5504 p.setPen(pen);
5505 p.drawRect(rect);
5506 }
5507
5508
5509 /*!
5510 Paint the page area while waiting for page data
5511 or when the decoding job has failed or has been
5512 stopped. Argument \a rect is the page rectangle.
5513 Argument \a status indicates what is going on.
5514 Overload this function to redefine
5515 the transient appearance of such pages.
5516 */
5517
5518 void
5519 QDjVuWidget::paintEmpty(QPainter &p, const QRect &rect,
5520 bool waiting, bool stopped, bool error )
5521 {
5522 QString name;
5523 QPixmap pixmap;
5524 if (waiting)
5525 name = ":/images/djvu_logo.png";
5526 else if (stopped)
5527 name = ":/images/djvu_stop.png";
5528 else if (error)
5529 name = ":/images/djvu_fail.png";
5530 if (!name.isEmpty())
5531 pixmap.load(name);
5532 // start painting
5533 QBrush brush(priv->white);
5534 p.fillRect(rect, brush);
5535 if (pixmap.isNull()) return;
5536 if (pixmap.width() > rect.width()) return;
5537 if (pixmap.height() > rect.height()) return;
5538 p.save();
5539 p.setClipRect(rect, Qt::IntersectClip);
5540 QSize s = pixmap.size() * 5 / 4;
5541 QPoint c = rect.center();
5542 int imin = (rect.left() - c.x())/s.width();
5543 int imax = (rect.right() - c.x())/s.width();
5544 int jmin = (rect.top() - c.y())/s.height();
5545 int jmax = (rect.bottom() - c.y())/s.height();
5546 c -= QPoint( pixmap.width()/2, pixmap.height()/2 );
5547 for (int i=imin; i<=imax; i++)
5548 for (int j=jmin; j<=jmax; j++)
5549 if (! ((i + j) & 1))
5550 p.drawPixmap(c.x()+i*s.width(), c.y()+j*s.height(), pixmap);
5551 p.restore();
5552 }
5553
5554 /*!
5555 This function displays the current hyperlink comment in a tooltip.
5556 It is called whenever the pointer crosses hyperlink boundaries.
5557 */
5558
5559 void
5560 QDjVuWidget::chooseTooltip(void)
5561 {
5562 QToolTip::showText(QPoint(), QString());
5563 priv->toolTipTimer->stop();
5564 if (!linkComment().isEmpty())
5565 priv->toolTipTimer->start(250);
5566 }
5567
5568
5569 void
5570 QDjVuPrivate::makeToolTip(void)
5571 {
5572 QWidget *w = widget->viewport();
5573 QPoint p = w->mapToGlobal(cursorPoint);
5574 QToolTip::showText(p, currentComment, w);
5575 }
5576
5577
5578 // ----------------------------------------
5579 // QDJVULENS
5580
5581
5582 QDjVuLens::QDjVuLens(int size, int magx,
5583 QDjVuPrivate *priv, QDjVuWidget *widget)
5584 : QWidget(widget, Qt::Window|Qt::Popup), priv(priv), widget(widget)
5585 {
5586 mag = qBound(1,magx,10);
5587 size = qBound(50,size,500);
5588 setGeometry(0,0,size,size);
5589 setCursor(Qt::CrossCursor);
5590 setMouseTracking(true);
5591 connect(widget,SIGNAL(layoutChanged()), this, SLOT(redisplay()));
5592 QApplication::instance()->installEventFilter(this);
5593 }
5594
5595 bool
5596 QDjVuLens::eventFilter(QObject *object, QEvent *event)
5597 {
5598 return priv->eventFilter(object, event);
5599 }
5600
5601 bool
5602 QDjVuLens::event(QEvent *event)
5603 {
5604 switch (event->type())
5605 {
5606 case QEvent::MouseButtonPress:
5607 case QEvent::MouseButtonDblClick:
5608 case QEvent::MouseButtonRelease:
5609 case QEvent::MouseMove:
5610 {
5611 QMouseEvent *oldEvent = (QMouseEvent*)event;
5612 #if QT_VERSION >= 0x60000
5613 QPoint pos = oldEvent->globalPosition().toPoint();
5614 #else
5615 QPoint pos = oldEvent->globalPos();
5616 #endif
5617 QMouseEvent newEvent(oldEvent->type(),
5618 widget->viewport()->mapFromGlobal(pos),
5619 pos, oldEvent->button(), oldEvent->buttons(),
5620 oldEvent->modifiers());
5621 return widget->viewportEvent(&newEvent);
5622 }
5623 default:
5624 break;
5625 }
5626 return QWidget::event(event);
5627 }
5628
5629 void
5630 QDjVuLens::recenter(const QPoint &p)
5631 {
5632 QPoint npos;
5633 QRect rect = geometry();
5634 QPoint pos = rect.center();
5635 QRect vrect = widget->viewport()->rect();
5636 npos.rx() = qBound(vrect.left(), p.x(), vrect.right());
5637 npos.ry() = qBound(vrect.top(), p.y(), vrect.bottom());
5638 npos = widget->viewport()->mapToGlobal(npos);
5639 rect.translate(npos - pos);
5640 vrect.moveTo(widget->viewport()->mapToGlobal(vrect.topLeft()));
5641 setVisible(vrect.intersects(rect));
5642 setGeometry(rect);
5643 #if QT_VERSION >= 0x50E00
5644 QCoreApplication::sendPostedEvents();
5645 #else
5646 QCoreApplication::flush();
5647 #endif
5648 }
5649
5650 void
5651 QDjVuLens::refocus(void)
5652 {
5653 QRect r = rect();
5654 QPoint p = mapToGlobal(rect().center());
5655 int sx = ( r.width() + mag - 1 ) / mag;
5656 int sy = ( r.height() + mag - 1 ) / mag;
5657 lensRect.setRect(0,0,sx,sy);
5658 QPoint vp = widget->viewport()->mapFromGlobal(p);
5659 lensRect.translate(vp - lensRect.center());
5660 }
5661
5662 void
5663 QDjVuLens::moveEvent(QMoveEvent *event)
5664 {
5665 refocus();
5666 #if QT_VERSION >= 0x50200
5667 int dpr = devicePixelRatio();
5668 #else
5669 int dpr = 1;
5670 #endif
5671 QPoint delta = event->pos() - event->oldPos();
5672 QRect r = rect().adjusted(dpr,dpr,-dpr,-dpr);
5673 scroll(-mag*delta.x(), -mag*delta.y(), r);
5674 }
5675
5676 void
5677 QDjVuLens::resizeEvent(QResizeEvent *)
5678 {
5679 refocus();
5680 }
5681
5682 void
5683 QDjVuLens::redisplay(void)
5684 {
5685 refocus();
5686 update();
5687 }
5688
5689 void
5690 QDjVuLens::paintEvent(QPaintEvent *event)
5691 {
5692 // Copied from main painting code but simpler
5693 // TODO: maybe hyperlinks.
5694 QPainter paint(this);
5695 QRegion paintRegion = event->region();
5696 QRegion deskRegion = paintRegion;
5697 QRectMapper mapper(lensRect, rect());
5698 Page *p;
5699 ddjvu_render_mode_t mode = DDJVU_RENDER_COLOR;
5700 if (priv->display == DISPLAY_STENCIL)
5701 mode = DDJVU_RENDER_BLACK;
5702 else if (priv->display == DISPLAY_BG)
5703 mode = DDJVU_RENDER_BACKGROUND;
5704 else if (priv->display == DISPLAY_FG)
5705 mode = DDJVU_RENDER_FOREGROUND;
5706 #if QT_VERSION >= 0x50200
5707 int dpr = devicePixelRatio();
5708 #else
5709 int dpr = 1;
5710 #endif
5711 foreach(p, priv->pageVisible)
5712 {
5713 QRect prect = mapper.mapped(p->viewRect);
5714 QRegion region = paintRegion & prect;
5715 if (region.isEmpty())
5716 continue;
5717 paint.fillRect(prect, Qt::white);
5718 if (p->dpi>0 && p->page)
5719 {
5720 QRegion prgn = cover_region(region, prect);
5721 foreachrect(const QRect &r, prgn)
5722 {
5723 int rot;
5724 ddjvu_rect_t pr, rr;
5725 QDjVuPage *dp = p->page;
5726 QImage img(r.width()*dpr, r.height()*dpr, QImage::Format_RGB32);
5727 #if QT_VERSION >= 0x50200
5728 img.setDevicePixelRatio(dpr);
5729 #endif
5730 qrect_to_rect(prect, pr, dpr);
5731 qrect_to_rect(r, rr, dpr);
5732 rot = p->initialRot + priv->rotation;
5733 ddjvu_page_set_rotation(*dp,(ddjvu_page_rotation_t)(rot & 0x3));
5734 if (ddjvu_page_render(*dp, mode, &pr, &rr, priv->renderFormat,
5735 img.bytesPerLine(), (char*)img.bits() ))
5736 {
5737 // priv->paintHiddenText(img, p, r, &prect);
5738 // When displaying in hidden text mode,
5739 // the above line paints the hidden text in the lens.
5740 // But the opposite behavior is more convenient
5741 // for proofreading.
5742 if (priv->invertLuminance)
5743 invert_luminance(img);
5744 priv->paintMapAreas(img, p, r, true, &prect);
5745 paint.drawImage(r.topLeft(), img, img.rect(),
5746 Qt::ThresholdDither);
5747 }
5748 }
5749 }
5750 deskRegion -= prect;
5751 }
5752 widget->paintDesk(paint, deskRegion);
5753 if (priv->frame)
5754 {
5755 foreach(p, priv->pageVisible)
5756 {
5757 QRect prect = mapper.mapped(p->viewRect);
5758 widget->paintFrame(paint, prect, priv->shadowSize);
5759 }
5760 }
5761 paint.setPen(Qt::gray);
5762 paint.setBrush(Qt::NoBrush);
5763 paint.drawRect(rect().adjusted(0,0,-1,-1));
5764 }
5765
5766
5767 // ----------------------------------------
5768 // MORE SLOTS
5769
5770 static int preferredZoom[] = {
5771 ZOOM_MIN, ZOOM_MIN,
5772 10, 25, 50, 75, 100, 150,
5773 200, 300, 400, 600, 800,
5774 ZOOM_MAX, ZOOM_MAX
5775 };
5776
5777
5778 /*! Increase the zoom factor. */
5779 void
5780 QDjVuWidget::zoomIn(void)
5781 {
5782 int s = 1;
5783 int z = qBound((int)ZOOM_MIN, zoomFactor(), (int)ZOOM_MAX);
5784 while (z >= preferredZoom[s]) { s += 1; }
5785 setZoom(preferredZoom[s]);
5786 }
5787
5788 /*! Decrease the zoom factor. */
5789 void
5790 QDjVuWidget::zoomOut(void)
5791 {
5792 int s = 1;
5793 int z = qBound((int)ZOOM_MIN, zoomFactor(), (int)ZOOM_MAX);
5794 while (z > preferredZoom[s]) { s += 1; }
5795 setZoom(preferredZoom[s-1]);
5796 }
5797
5798 /*! Maximize the maginification in order to keep rectangle \a rect visible.
5799 The rectangle is expressed in viewport coordinates. */
5800
5801 void
5802 QDjVuWidget::zoomRect(QRect rect)
5803 {
5804 rect = rect.normalized();
5805 Position pos = priv->findPosition(rect.center());
5806 pos.inPage = true;
5807 int z = zoomFactor();
5808 int zw = z * viewport()->width() / qMax(1,rect.width());
5809 int zh = z * viewport()->height() / qMax(1,rect.height());
5810 z = qBound((int)ZOOM_MIN, qMin(zw, zh), (int)ZOOM_MAX);
5811 setZoom(z);
5812 setPosition(pos, viewport()->rect().center());
5813 }
5814
5815 /*! Rotate the page images clockwise. */
5816 void
5817 QDjVuWidget::rotateRight(void)
5818 {
5819 setRotation((rotation() - 1) & 0x3);
5820 }
5821
5822 /*! Rotate the page images counter-clockwise. */
5823 void
5824 QDjVuWidget::rotateLeft(void)
5825 {
5826 setRotation((rotation() + 1) & 0x3);
5827 }
5828
5829 /*! Set the display mode to \a DISPLAY_COLOR. */
5830 void
5831 QDjVuWidget::displayModeColor(void)
5832 {
5833 setDisplayMode(DISPLAY_COLOR);
5834 }
5835
5836 /*! Set the display mode to \a DISPLAY_STENCIL. */
5837 void
5838 QDjVuWidget::displayModeStencil(void)
5839 {
5840 setDisplayMode(DISPLAY_STENCIL);
5841 }
5842
5843 /*! Set the display mode to \a DISPLAY_BG. */
5844 void
5845 QDjVuWidget::displayModeBackground(void)
5846 {
5847 setDisplayMode(DISPLAY_BG);
5848 }
5849
5850 /*! Set the display mode to \a DISPLAY_FG. */
5851 void
5852 QDjVuWidget::displayModeForeground(void)
5853 {
5854 setDisplayMode(DISPLAY_FG);
5855 }
5856
5857 /*! Set the display mode to \a DISPLAY_TEXT. */
5858 void
5859 QDjVuWidget::displayModeText(void)
5860 {
5861 setDisplayMode(DISPLAY_TEXT);
5862 }
5863
5864 /*! Move to the next page. */
5865 void
5866 QDjVuWidget::nextPage(void)
5867 {
5868 terminateAnimation();
5869 int pageNo = page();
5870 const QRect &dr = priv->deskRect;
5871 const QRect &vr = priv->visibleRect;
5872 const Page *pg = priv->pageMap.value(pageNo,0);
5873 while (pageNo < priv->numPages - 1)
5874 {
5875 pageNo += 1;
5876 if (priv->layoutChange || !priv->pageMap.contains(pageNo) || !pg)
5877 break;
5878 // Skip pages until we get a meaningful change.
5879 const QRect &pr = priv->pageMap[pageNo]->rect;
5880 if (! vr.contains(pr))
5881 if (pr.top() != pg->rect.top() || vr.width() < dr.width())
5882 break;
5883 }
5884 setPage(pageNo, true);
5885 }
5886
5887 /*! Move to the previous page. */
5888 void
5889 QDjVuWidget::prevPage(void)
5890 {
5891 terminateAnimation();
5892 int pageNo = page();
5893 const QRect &dr = priv->deskRect;
5894 const QRect &vr = priv->visibleRect;
5895 const Page *pg = priv->pageMap.value(pageNo,0);
5896 while (pageNo > 0)
5897 {
5898 pageNo -= 1;
5899 if (priv->layoutChange || !priv->pageMap.contains(pageNo) || !pg)
5900 break;
5901 // Skip pages until we get a meaningful change.
5902 const QRect &pr = priv->pageMap[pageNo]->rect;
5903 if (! vr.contains(pr))
5904 if (pr.top() != pg->rect.top() || vr.width() < dr.width())
5905 break;
5906 }
5907 setPage(pageNo, true);
5908 }
5909
5910 /*! Move to the first page. */
5911 void
5912 QDjVuWidget::firstPage(void)
5913 {
5914 terminateAnimation();
5915 Position pos;
5916 pos.pageNo = 0;
5917 pos.inPage = false;
5918 pos.posView = pos.posPage = QPoint(0,0);
5919 setPosition(pos);
5920 }
5921
5922 /*! Move to the last page. */
5923 void
5924 QDjVuWidget::lastPage(void)
5925 {
5926 terminateAnimation();
5927 Position pos;
5928 pos.pageNo = priv->numPages - 1;
5929 pos.inPage = false;
5930 pos.posView = pos.posPage = QPoint(0,0);
5931 pos.hAnchor = pos.vAnchor = 100;
5932 QPoint p;
5933 p.rx() = priv->visibleRect.width() - priv->borderSize;
5934 p.ry() = priv->visibleRect.height() - priv->borderSize;
5935 setPosition(pos, p);
5936 }
5937
5938
5939 /*! Move to top of current page. */
5940 void
5941 QDjVuWidget::moveToPageTop(void)
5942 {
5943 terminateAnimation();
5944 Position pos = priv->currentPos;
5945 pos.inPage = false;
5946 pos.posView = pos.posPage = QPoint(0,0);
5947 pos.hAnchor = 0;
5948 pos.vAnchor = 0;
5949 setPosition(pos);
5950 }
5951
5952
5953 /*! Move to bottom of current page. */
5954 void
5955 QDjVuWidget::moveToPageBottom(void)
5956 {
5957 terminateAnimation();
5958 Position pos = priv->currentPos;
5959 pos.inPage = false;
5960 pos.posView = pos.posPage = QPoint(0,0);
5961 pos.hAnchor = 0;
5962 pos.vAnchor = 100;
5963 QPoint p;
5964 p.rx() = priv->visibleRect.width() - priv->borderSize;
5965 p.ry() = priv->visibleRect.height() - priv->borderSize;
5966 setPosition(pos, p);
5967 }
5968
5969
5970 /*! Move to next position in approximate reading order. */
5971 void
5972 QDjVuWidget::readNext(void)
5973 {
5974 terminateAnimation();
5975 QPoint point = priv->currentPoint;
5976 Position pos = priv->currentPos;
5977 int bs = priv->borderSize;
5978 if (priv->pageMap.contains(pos.pageNo))
5979 {
5980 Page *p = priv->pageMap[pos.pageNo];
5981 QRect nv = priv->visibleRect.adjusted(bs,bs,-bs,-bs);
5982 QRect v = priv->visibleRect.intersected(p->rect);
5983 if (v.bottom() < p->rect.bottom())
5984 {
5985 // scroll in page
5986 point.ry() = bs;
5987 nv.moveTop(v.bottom());
5988 nv.moveBottom(qMin(nv.bottom(), p->rect.bottom()));
5989 pos.inPage = false;
5990 pos.posView.ry() = nv.top() - p->rect.top();
5991 setPosition(pos, point);
5992 return;
5993 }
5994 }
5995 // find forward a partially hidden page
5996 while (pos.pageNo < priv->numPages - 1)
5997 {
5998 pos.pageNo += 1;
5999 pos.posView.ry() = 0;
6000 pos.vAnchor = 0;
6001 pos.hAnchor = 0;
6002 point.ry() = bs;
6003 if (! priv->pageMap.contains(pos.pageNo) ||
6004 ! priv->visibleRect.contains(priv->pageMap[pos.pageNo]->rect) )
6005 break;
6006 }
6007 pos.inPage = false;
6008 pos.doPage = true;
6009 setPosition(pos, point);
6010 }
6011
6012
6013 /*! Move to previous position in approximate reading order. */
6014 void
6015 QDjVuWidget::readPrev(void)
6016 {
6017 terminateAnimation();
6018 QPoint point = priv->currentPoint;
6019 Position pos = priv->currentPos;
6020 int bs = priv->borderSize;
6021 if (priv->pageMap.contains(pos.pageNo))
6022 {
6023 Page *p = priv->pageMap[pos.pageNo];
6024 QRect nv = priv->visibleRect.adjusted(bs,bs,-bs,-bs);
6025 QRect v = priv->visibleRect.intersected(p->rect);
6026 if (v.top() > p->rect.top())
6027 {
6028 // scroll in page
6029 point.ry() = bs;
6030 nv.moveBottom(v.top());
6031 nv.moveTop(qMax(nv.top(), p->rect.top()));
6032 pos.inPage = false;
6033 pos.posView.ry() = nv.top() - p->rect.top();
6034 setPosition(pos, point);
6035 return;
6036 }
6037 }
6038 // find backward a partially hidden page
6039 while (pos.pageNo > 0)
6040 {
6041 pos.pageNo -= 1;
6042 pos.posView.ry() = 0;
6043 pos.vAnchor = 100;
6044 pos.hAnchor = 0;
6045 point.ry() = priv->visibleRect.height() - bs;
6046 if (! priv->pageMap.contains(pos.pageNo) ||
6047 ! priv->visibleRect.contains(priv->pageMap[pos.pageNo]->rect) )
6048 break;
6049 }
6050 pos.inPage = false;
6051 pos.doPage = true;
6052 setPosition(pos, point);
6053 }
6054
6055
6056
6057
6058
6059 // ----------------------------------------
6060 // MOC
6061
6062 #include "qdjvuwidget.moc"
6063
6064
6065 // ----------------------------------------
6066 // DOCUMENTATION
6067
6068
6069 /*! \class QDjVuWidget::PageInfo
6070 \brief Additional information for pointerPosition signal.
6071 Variable \a pageno is the page number.
6072 Variables \a width and \a height give the page size
6073 in pixels. Variable \a dpi gives the page resolution.
6074 Variable \a segment gives the page coordinates of
6075 the page segment covered by the selected rectangle
6076 All these variables are null when the page geometry
6077 is still unknown.
6078 */
6079
6080 /*! \enum QDjVuWidget::DisplayMode
6081 Modes for displaying a DjVu image.
6082 Only mode \a DISPLAY_COLOR is really useful.
6083 The other modes show various layers of the DjVu image.
6084 */
6085
6086 /*! \enum QDjVuWidget::Align
6087 Possible values of the alignment properties.
6088 */
6089
6090 /*! \fn QDjVuWidget::layoutChanged()
6091 This signal is emitted when the layout of the
6092 displayed pages has changed. This can happen
6093 when more data is available, or when the user
6094 changes zoom, rotation, layout, display mode, etc. */
6095
6096 /*! \fn QDjVuWidget::pageChanged(int pageno)
6097 This signal is emitted when the current page number is changed.
6098 This refer to the current page used when moving the document
6099 to keep reading (space bar). */
6100
6101 /*! \fn QDjVuWidget::pointerPosition(const Position &pos, const PageInfo &page)
6102 This signal is emitted when the mouse move.
6103 Variable \a pos reports the position of the mouse in the document.
6104 Variable \a page reports the page geometry. */
6105
6106 /*! \fn QDjVuWidget::pointerEnter(const Position &pos, miniexp_t maparea)
6107 This signal is emitted when the mouse enters a maparea.
6108 Variable \a pos reports the position of the mouse in the document.
6109 Variable \a maparea contains the area description.
6110 Additional information can be obtained using functions
6111 \a linkUrl, \a linkTarget, and \a linkComment. */
6112
6113 /*! \fn QDjVuWidget::pointerLeave(const Position &pos, miniexp_t maparea)
6114 This signal is emitted when the mouse leaves a maparea.
6115 Variable \a pos reports the position of the mouse in the document.
6116 Variable \a maparea contains the area description.
6117 Additional information can be obtained using functions
6118 \a linkUrl, \a linkTarget, and \a linkComment. */
6119
6120 /*! \fn QDjVuWidget::pointerClick(const Position &pos, miniexp_t maparea)
6121 This signal is emitted when the user clicks an hyperlink maparea.
6122 Variable \a pos reports the position of the mouse in the document.
6123 Variable \a maparea contains the area description.
6124 Additional information can be obtained using functions
6125 \a linkUrl, \a linkTarget, and \a linkComment. */
6126
6127 /*! \fn QDjVuWidget::pointerSelect(const QPoint &pos, const QRect &rect)
6128 This signal is emitted when the user has selected a
6129 rectangular area in the image. Argument \a rect gives the
6130 rectangle coordinates in the viewport. Argument \a pos
6131 is the global mouse position. Use \a getTextForRect and
6132 \a getImageForRect to extract associated information. */
6133
6134 /*! \fn QDjVuWidget::errorCondition(int pageno)
6135 This signal is emitted when an error occurs during decoding.
6136 Recorded error messages can be obtained using function \a errorMessage.
6137 Argument \a pageno is -1 if the error occurs at the document level.
6138 Otherwise it indicates the page with the error. */
6139
6140 /*! \fn QDjVuWidget::stopCondition(int pageno)
6141 This signal is emitted when decoding stops.
6142 Recorded error messages can be obtained using function \a errorMessage.
6143 Argument \a pageno is -1 if the condition occurs at the document level.
6144 Otherwise it indicates the page with the error. */
6145
6146 /*! \fn QDjVuWidget::keyPressSignal(QKeyEvent *event, bool &done)
6147 This signal is emitted from the widget's \a keyPressEvent routine.
6148 Setting flag \a done to \a true suppress any further processing.
6149 Otherwise default key bindings are applied. */
6150
6151 /*! \fn QDjVuWidget::error(QString message, QString filename, int lineno)
6152 This signal relays all error messages generated by the \a QDjVuDocument and
6153 \a QDjVuPage objects associated with this widget. The last few error
6154 messages are saved and are available via function \a pastErrorMessage().
6155 Error message occur asynchronously and might be related to a background job
6156 such as prefetching pages. Use instead signal \a errorCondition() as an
6157 indicator that an error has just ocurred. */
6158
6159 /*! \fn QDjVuWidget::info(QString message)
6160 This signal relays all informational messages generated by the \a
6161 QDjVuDocument and \a QDjVuPage objects associated with this widget. The last
6162 few messages are saved and are available via function \a pastInfoMessage().
6163 Note that informational message occur asynchronously and might not be
6164 relevant. */
6165
6166
6167
6168 /* -------------------------------------------------------------
6169 Local Variables:
6170 c++-font-lock-extra-types: ( "\\sw+_t" "[A-Z]\\sw*[a-z]\\sw*" )
6171 End:
6172 ------------------------------------------------------------- */