Debian Codegraph @

src/qdjviewsidebar.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 <QAbstractItemDelegate>
27 #include <QAbstractListModel>
28 #include <QAction>
29 #include <QActionGroup>
30 #include <QApplication>
31 #include <QComboBox>
32 #include <QContextMenuEvent>
33 #include <QCheckBox>
34 #include <QDebug>
35 #include <QEvent>
36 #include <QFont>
37 #include <QFontMetrics>
38 #include <QHBoxLayout>
39 #include <QHeaderView>
40 #include <QItemDelegate>
41 #include <QLabel>
42 #include <QLineEdit>
43 #include <QList>
44 #include <QListView>
45 #include <QMap>
46 #include <QMenu>
47 #include <QPainter>
48 #include <QPainterPath>
49 #include <QPushButton>
50 #include <QPixmap>
51 #include <QResizeEvent>
52 #include <QStackedLayout>
53 #include <QStringList>
54 #include <QTimer>
55 #include <QToolBar>
56 #include <QToolButton>
57 #include <QTreeWidget>
58 #include <QVariant>
59 #include <QVBoxLayout>
60 #include <QRegExp>
61 #if QT_VERSION >= 0x50000
62 # include <QUrlQuery>
63 #endif
64 #if QT_VERSION >= 0x50E00
65 # define zero(T) T()
66 #else
67 # define zero(T) 0
68 #endif
69 #if QT_VERSION >= 0x60000
70 # define variantIsA(v,vt,mt) ((v).typeId() == mt)
71 # define reReplace(s,r,a) (r).replaceIn((s),(a))
72 #else
73 # define variantIsA(v,vt,mt) ((v).type() == vt)
74 # define reReplace(s,r,a) (s).replace((r),(a))
75 #endif
76
77
78
79 #include <libdjvu/ddjvuapi.h>
80 #include <libdjvu/miniexp.h>
81
82 #include "qdjvu.h"
83 #include "qdjvuwidget.h"
84 #include "qdjviewsidebar.h"
85 #include "qdjview.h"
86
87
88
89 // =======================================
90 // QDJVIEWOUTLINE
91 // =======================================
92
93
94
95
96 QDjViewOutline::QDjViewOutline(QDjView *djview)
97 : QWidget(djview),
98 djview(djview),
99 loaded(false)
100 {
101 tree = new QTreeWidget(this);
102 tree->setColumnCount(1);
103 tree->setItemsExpandable(true);
104 tree->setUniformRowHeights(true);
105 tree->header()->hide();
106 tree->header()->setStretchLastSection(true);
107 tree->setEditTriggers(QAbstractItemView::NoEditTriggers);
108 tree->setSelectionBehavior(QAbstractItemView::SelectRows);
109 tree->setSelectionMode(QAbstractItemView::SingleSelection);
110 tree->setTextElideMode(Qt::ElideRight);
111 QVBoxLayout *layout = new QVBoxLayout(this);
112 #if QT_VERSION >= 0x60000
113 layout->setContentsMargins(QMargins(0,0,0,0));
114 #else
115 layout->setMargin(0);
116 #endif
117 layout->setSpacing(0);
118 layout->addWidget(tree);
119
120 connect(tree, SIGNAL(itemActivated(QTreeWidgetItem*, int)),
121 this, SLOT(itemActivated(QTreeWidgetItem*)) );
122 connect(djview, SIGNAL(documentClosed(QDjVuDocument*)),
123 this, SLOT(clear()) );
124 connect(djview, SIGNAL(documentOpened(QDjVuDocument*)),
125 this, SLOT(clear()) );
126 connect(djview, SIGNAL(documentReady(QDjVuDocument*)),
127 this, SLOT(refresh()) );
128 connect(djview->getDjVuWidget(), SIGNAL(pageChanged(int)),
129 this, SLOT(pageChanged(int)) );
130 connect(djview->getDjVuWidget(), SIGNAL(layoutChanged()),
131 this, SLOT(refresh()) );
132
133 setWhatsThis(tr("<html><b>Document outline.</b><br/> "
134 "This panel display the document outline, "
135 "or the page names when the outline is not available, "
136 "Double-click any entry to jump to the selected page."
137 "</html>"));
138
139 if (djview->pageNum() > 0)
140 refresh();
141 }
142
143
144 void
145 QDjViewOutline::clear()
146 {
147 tree->clear();
148 loaded = false;
149 }
150
151 void
152 QDjViewOutline::refresh()
153 {
154 QDjVuDocument *doc = djview->getDocument();
155 if (doc && !loaded && djview->pageNum()>0)
156 {
157 miniexp_t outline = doc->getDocumentOutline();
158 if (outline == miniexp_dummy)
159 return;
160 loaded = true;
161 if (outline)
162 {
163 if (!miniexp_consp(outline) ||
164 miniexp_car(outline) != miniexp_symbol("bookmarks"))
165 {
166 QString msg = tr("Outline data is corrupted");
167 qWarning("%s", (const char*)msg.toLocal8Bit());
168 }
169 tree->clear();
170 QTreeWidgetItem *root = new QTreeWidgetItem();
171 fillItems(root, miniexp_cdr(outline));
172 while (root->childCount() > 0)
173 tree->insertTopLevelItem(tree->topLevelItemCount(),
174 root->takeChild(0) );
175 if (tree->topLevelItemCount() == 1)
176 tree->topLevelItem(0)->setExpanded(true);
177 delete root;
178 }
179 else
180 {
181 tree->clear();
182 QTreeWidgetItem *root = new QTreeWidgetItem(tree);
183 root->setText(0, tr("Pages"));
184 root->setFlags(Qt::ItemIsEnabled);
185 root->setData(0, Qt::UserRole, -1);
186 for (int pageno=0; pageno<djview->pageNum(); pageno++)
187 {
188 QTreeWidgetItem *item = new QTreeWidgetItem(root);
189 QString name = djview->pageName(pageno);
190 item->setText(0, tr("Page %1").arg(name));
191 item->setData(0, Qt::UserRole, pageno);
192 item->setData(0, Qt::UserRole+1, pageno);
193 item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
194 item->setToolTip(0, tr("Go: page %1.").arg(name));
195 item->setWhatsThis(0, whatsThis());
196 }
197 root->setExpanded(true);
198 }
199 pageChanged(djview->getDjVuWidget()->page());
200 }
201 }
202
203
204 int
205 QDjViewOutline::pageNumber(const char *link)
206 {
207 if (link && link[0] == '#')
208 return djview->pageNumber(QString::fromUtf8(link+1));
209 if (link == 0 || link[0] != '?')
210 return -1;
211 QByteArray burl = QByteArray("http://f/f") + link;
212 #if QT_VERSION >= 0x50000
213 QUrlQuery qurl(QUrl::fromEncoded(burl));
214 #else
215 QUrl qurl = QUrl::fromEncoded(burl);
216 #endif
217 if (qurl.hasQueryItem("page"))
218 return djview->pageNumber(qurl.queryItemValue("page"));
219 else if (qurl.hasQueryItem("pageno"))
220 return djview->pageNumber("$" + qurl.queryItemValue("pageno"));
221 return -1;
222 }
223
224
225 static const QRegExp spaces("\\s+");
226
227 void
228 QDjViewOutline::fillItems(QTreeWidgetItem *root, miniexp_t expr)
229 {
230 while(miniexp_consp(expr))
231 {
232 miniexp_t s = miniexp_car(expr);
233 expr = miniexp_cdr(expr);
234 if (miniexp_consp(s) &&
235 miniexp_consp(miniexp_cdr(s)) &&
236 miniexp_stringp(miniexp_car(s)) &&
237 miniexp_stringp(miniexp_cadr(s)) )
238 {
239 // fill item
240 const char *name = miniexp_to_str(miniexp_car(s));
241 const char *link = miniexp_to_str(miniexp_cadr(s));
242 int pageno = pageNumber(link);
243 QString pagename = (pageno>=0)?djview->pageName(pageno):QString();
244 QTreeWidgetItem *item = new QTreeWidgetItem(root);
245 QString text = QString::fromUtf8(name);
246 if (name && name[0])
247 item->setText(0, reReplace(text,spaces," "));
248 else if (! pagename.isEmpty())
249 item->setText(0, tr("Page %1").arg(pagename));
250 item->setFlags(zero(Qt::ItemFlags));
251 item->setWhatsThis(0, whatsThis());
252 if (link && link[0])
253 {
254 QString slink = QString::fromUtf8(link);
255 item->setData(0, Qt::UserRole+1, slink);
256 item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
257 item->setToolTip(0, tr("Go: %1").arg(slink));
258 if (pageno >= 0)
259 item->setData(0, Qt::UserRole, pageno);
260 if (! pagename.isEmpty())
261 item->setToolTip(0, tr("Go: page %1.").arg(pagename));
262 }
263 // recurse
264 fillItems(item, miniexp_cddr(s));
265 }
266 }
267 }
268
269
270 void
271 QDjViewOutline::pageChanged(int pageno)
272 {
273 int fp = -1;
274 QTreeWidgetItem *fi = 0;
275 // find current selection
276 QList<QTreeWidgetItem*> sel = tree->selectedItems();
277 QTreeWidgetItem *si = 0;
278 if (sel.size() == 1)
279 si = sel[0];
280 // current selection has priority
281 if (si)
282 searchItem(si, pageno, fi, fp);
283 // search
284 for (int i=0; i<tree->topLevelItemCount(); i++)
285 searchItem(tree->topLevelItem(i), pageno, fi, fp);
286 // select
287 if (si && fi && si != fi)
288 si->setSelected(false);
289 if (fi && si != fi)
290 {
291 tree->setCurrentItem(fi);
292 fi->setSelected(true);
293 tree->scrollToItem(fi);
294 }
295 }
296
297
298 void
299 QDjViewOutline::searchItem(QTreeWidgetItem *item, int pageno,
300 QTreeWidgetItem *&fi, int &fp)
301 {
302 QVariant data = item->data(0, Qt::UserRole);
303 if (variantIsA(data, QVariant::Int, QMetaType::Int))
304 {
305 int page = data.toInt();
306 if (page>=0 && page<=pageno && page>fp)
307 {
308 fi = item;
309 fp = page;
310 }
311 }
312 for (int i=0; i<item->childCount(); i++)
313 searchItem(item->child(i), pageno, fi, fp);
314 }
315
316
317 void
318 QDjViewOutline::itemActivated(QTreeWidgetItem *item)
319 {
320 QVariant data = item->data(0, Qt::UserRole+1);
321 if (variantIsA(data, QVariant::String, QMetaType::QString))
322 {
323 QString link = data.toString();
324 if (link.size() > 0)
325 djview->goToLink(link);
326 }
327 else if (variantIsA(data, QVariant::Int, QMetaType::Int))
328 {
329 int pageno = data.toInt();
330 if (pageno >= 0)
331 djview->goToPage(pageno);
332 }
333 }
334
335
336
337
338
339
340
341 // =======================================
342 // QDJVIEWTHUMBNAILS
343 // =======================================
344
345
346
347
348 class QDjViewThumbnails::View : public QListView
349 {
350 Q_OBJECT
351 public:
352 View(QDjViewThumbnails *widget);
353 protected:
354 #if QT_VERSION >= 0x60000
355 void initViewItemOption(QStyleOptionViewItem *option) const;
356 #else
357 QStyleOptionViewItem viewOptions() const;
358 #endif
359 private:
360 QDjViewThumbnails *widget;
361 };
362
363
364 class QDjViewThumbnails::Model : public QAbstractListModel
365 {
366 Q_OBJECT
367 public:
368 ~Model();
369 Model(QDjViewThumbnails*);
370 virtual int rowCount(const QModelIndex &parent) const;
371 virtual QVariant data(const QModelIndex &index, int role) const;
372 int getSize() { return size; }
373 int getSmart() { return smart; }
374 public slots:
375 void setSize(int);
376 void setSmart(bool);
377 void scheduleRefresh();
378 protected slots:
379 void documentClosed(QDjVuDocument *doc);
380 void documentReady(QDjVuDocument *doc);
381 void thumbnail(int);
382 void refresh();
383 private:
384 QDjView *djview;
385 QDjViewThumbnails *widget;
386 QStringList names;
387 ddjvu_format_t *format;
388 QIcon icon;
389 int size;
390 bool smart;
391 bool refreshScheduled;
392 int pageInProgress;
393 QIcon makeIcon(int pageno) const;
394 QSize makeHint(int pageno) const;
395 };
396
397
398
399 // ----------------------------------------
400 // QDJVIEWTHUMBNAILS::VIEW
401
402
403 QDjViewThumbnails::View::View(QDjViewThumbnails *widget)
404 : QListView(widget),
405 widget(widget)
406 {
407 setDragEnabled(false);
408 setEditTriggers(QAbstractItemView::NoEditTriggers);
409 setSelectionBehavior(QAbstractItemView::SelectRows);
410 setSelectionMode(QAbstractItemView::SingleSelection);
411 setTextElideMode(Qt::ElideRight);
412 setViewMode(QListView::IconMode);
413 setFlow(QListView::LeftToRight);
414 setWrapping(true);
415 setMovement(QListView::Static);
416 setResizeMode(QListView::Adjust);
417 setSpacing(8);
418 setUniformItemSizes(true);
419 }
420
421
422 #if QT_VERSION >= 0x60000
423 void QDjViewThumbnails::View::initViewItemOption(QStyleOptionViewItem *opt) const
424 {
425 QListView::initViewItemOption(opt);
426 int size = widget->model->getSize();
427 opt->decorationAlignment = Qt::AlignCenter;
428 opt->decorationPosition = QStyleOptionViewItem::Top;
429 opt->decorationSize = QSize(size, size);
430 opt->displayAlignment = Qt::AlignCenter;
431 }
432 #else
433 QStyleOptionViewItem
434 QDjViewThumbnails::View::viewOptions() const
435 {
436 int size = widget->model->getSize();
437 QStyleOptionViewItem opt = QListView::viewOptions();
438 opt.decorationAlignment = Qt::AlignCenter;
439 opt.decorationPosition = QStyleOptionViewItem::Top;
440 opt.decorationSize = QSize(size, size);
441 opt.displayAlignment = Qt::AlignCenter;
442 return opt;
443 }
444 #endif
445
446
447 // ----------------------------------------
448 // QDJVIEWTHUMBNAILS::MODEL
449
450
451 QDjViewThumbnails::Model::~Model()
452 {
453 if (format)
454 ddjvu_format_release(format);
455 }
456
457
458 QDjViewThumbnails::Model::Model(QDjViewThumbnails *widget)
459 : QAbstractListModel(widget),
460 djview(widget->djview),
461 widget(widget),
462 format(0),
463 size(0),
464 smart(true),
465 refreshScheduled(false),
466 pageInProgress(-1)
467 {
468 // create format
469 #if DDJVUAPI_VERSION < 18
470 unsigned int masks[3] = { 0xff0000, 0xff00, 0xff };
471 format = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 3, masks);
472 #else
473 unsigned int masks[4] = { 0xff0000, 0xff00, 0xff, 0xff000000 };
474 format = ddjvu_format_create(DDJVU_FORMAT_RGBMASK32, 4, masks);
475 #endif
476 ddjvu_format_set_row_order(format, true);
477 ddjvu_format_set_y_direction(format, true);
478 ddjvu_format_set_ditherbits(format, QPixmap::defaultDepth());
479 // set size
480 setSize(64);
481 // connect
482 connect(djview, SIGNAL(documentClosed(QDjVuDocument*)),
483 this, SLOT(documentClosed(QDjVuDocument*)) );
484 connect(djview, SIGNAL(documentReady(QDjVuDocument*)),
485 this, SLOT(documentReady(QDjVuDocument*)) );
486 // update
487 if (djview->pageNum() > 0)
488 documentReady(djview->getDocument());
489 }
490
491
492 void
493 QDjViewThumbnails::Model::documentClosed(QDjVuDocument *doc)
494 {
495 if (names.size() > 0)
496 {
497 beginRemoveRows(QModelIndex(),0,names.size()-1);
498 names.clear();
499 pageInProgress = -1;
500 endRemoveRows();
501 }
502 disconnect(doc, 0, this, 0);
503 }
504
505
506 void
507 QDjViewThumbnails::Model::documentReady(QDjVuDocument *doc)
508 {
509 if (names.size() > 0)
510 {
511 beginRemoveRows(QModelIndex(),0,names.size()-1);
512 names.clear();
513 pageInProgress = -1;
514 endRemoveRows();
515 }
516 int pagenum = djview->pageNum();
517 if (pagenum > 0)
518 {
519 beginInsertRows(QModelIndex(),0,pagenum-1);
520 for (int pageno=0; pageno<pagenum; pageno++)
521 names << djview->pageName(pageno);
522 endInsertRows();
523 }
524 connect(doc, SIGNAL(thumbnail(int)),
525 this, SLOT(thumbnail(int)) );
526 connect(doc, SIGNAL(pageinfo()),
527 this, SLOT(scheduleRefresh()) );
528 connect(doc, SIGNAL(idle()),
529 this, SLOT(scheduleRefresh()) );
530 widget->pageChanged(djview->getDjVuWidget()->page());
531 scheduleRefresh();
532 }
533
534
535 void
536 QDjViewThumbnails::Model::thumbnail(int pageno)
537 {
538 QModelIndex mi = index(pageno);
539 emit dataChanged(mi, mi);
540 scheduleRefresh();
541 }
542
543
544 void
545 QDjViewThumbnails::Model::scheduleRefresh()
546 {
547 if (! refreshScheduled)
548 QTimer::singleShot(0, this, SLOT(refresh()));
549 refreshScheduled = true;
550 }
551
552
553 void
554 QDjViewThumbnails::Model::refresh()
555 {
556 QDjVuDocument *doc = djview->getDocument();
557 ddjvu_status_t status;
558 refreshScheduled = false;
559 if (doc && pageInProgress >= 0)
560 {
561 status = ddjvu_thumbnail_status(*doc, pageInProgress, 0);
562 if (status >= DDJVU_JOB_OK)
563 pageInProgress = -1;
564 }
565 if (doc && pageInProgress < 0 && widget->isVisible())
566 {
567 QRect dr = widget->view->rect();
568 for (int i=0; i<names.size(); i++)
569 {
570 QModelIndex mi = index(i);
571 if (dr.intersects(widget->view->visualRect(mi)))
572 {
573 status = ddjvu_thumbnail_status(*doc, i, 0);
574 if (status == DDJVU_JOB_NOTSTARTED)
575 {
576 if (smart && !ddjvu_document_check_pagedata(*doc, i))
577 continue;
578 status = ddjvu_thumbnail_status(*doc, i, 1);
579 if (status == DDJVU_JOB_STARTED)
580 {
581 pageInProgress = i;
582 break;
583 }
584 }
585 }
586 }
587 }
588 }
589
590
591 void
592 QDjViewThumbnails::Model::setSmart(bool b)
593 {
594 if (b != smart)
595 {
596 smart = b;
597 scheduleRefresh();
598 }
599 }
600
601
602 void
603 QDjViewThumbnails::Model::setSize(int newSize)
604 {
605 newSize = qBound(16, newSize, 256);
606 if (newSize != size)
607 {
608 size = newSize;
609 QPixmap pixmap(size,size);
610 pixmap.fill();
611 QPainter painter;
612 int s8 = size/8;
613 if (s8 >= 1)
614 {
615 QPolygon poly;
616 poly << QPoint(s8,0)
617 << QPoint(size-2*s8,0)
618 << QPoint(size-s8-1,s8)
619 << QPoint(size-s8-1,size-1)
620 << QPoint(s8,size-1);
621 QPainter painter(&pixmap);
622 painter.setBrush(Qt::NoBrush);
623 painter.setPen(Qt::darkGray);
624 painter.drawPolygon(poly);
625 }
626 icon = QIcon(pixmap);
627 }
628 emit layoutChanged();
629 }
630
631
632 QIcon
633 QDjViewThumbnails::Model::makeIcon(int pageno) const
634 {
635 QDjVuDocument *doc = djview->getDocument();
636 if (doc)
637 {
638 // render thumbnail
639 #if QT_VERSION >= 0x50200
640 int dpr = djview->devicePixelRatio();
641 #else
642 int dpr = 1;
643 #endif
644 int w = size * dpr;
645 int h = size * dpr;
646 QImage img(size*dpr, size*dpr, QImage::Format_RGB32);
647 int status = ddjvu_thumbnail_status(*doc, pageno, 0);
648 if (status == DDJVU_JOB_NOTSTARTED)
649 {
650 const_cast<Model*>(this)->scheduleRefresh();
651 }
652 else if (ddjvu_thumbnail_render(*doc, pageno, &w, &h, format,
653 img.bytesPerLine(), (char*)img.bits() ))
654 {
655 QPixmap pixmap(size*dpr,size*dpr);
656 pixmap.fill();
657 QPoint dst((size*dpr-w)/2, (size*dpr-h)/2);
658 QRect src(0,0,w,h);
659 QPainter painter;
660 painter.begin(&pixmap);
661 painter.drawImage(dst, img, src);
662 painter.setBrush(Qt::NoBrush);
663 painter.setPen(Qt::darkGray);
664 painter.drawRect(dst.x(), dst.y(), w-1, h-1);
665 painter.end();
666 #if QT_VERSION >= 0x50200
667 pixmap.setDevicePixelRatio(dpr);
668 #endif
669 return QIcon(pixmap);
670 }
671 }
672 return icon;
673 }
674
675
676 QSize
677 QDjViewThumbnails::Model::makeHint(int) const
678 {
679 QFontMetrics metrics(widget->view->font());
680 return QSize(size, size+metrics.height());
681 }
682
683
684 int
685 QDjViewThumbnails::Model::rowCount(const QModelIndex &) const
686 {
687 return names.size();
688 }
689
690
691 QVariant
692 QDjViewThumbnails::Model::data(const QModelIndex &index, int role) const
693 {
694 if (index.isValid())
695 {
696 int pageno = index.row();
697 if (pageno>=0 && pageno<names.size())
698 {
699 switch(role)
700 {
701 case Qt::DisplayRole:
702 case Qt::ToolTipRole:
703 return names[pageno];
704 case Qt::DecorationRole:
705 return makeIcon(pageno);
706 case Qt::WhatsThisRole:
707 return widget->whatsThis();
708 case Qt::UserRole:
709 return pageno;
710 case Qt::SizeHintRole:
711 return makeHint(pageno);
712 default:
713 break;
714 }
715 }
716 }
717 return QVariant();
718 }
719
720
721
722
723
724
725 // ----------------------------------------
726 // QDJVIEWTHUMBNAILS
727
728
729 QDjViewThumbnails::QDjViewThumbnails(QDjView *djview)
730 : QWidget(djview),
731 djview(djview)
732 {
733 model = new Model(this);
734 selection = new QItemSelectionModel(model);
735 view = new View(this);
736 view->setModel(model);
737 view->setSelectionModel(selection);
738
739 QVBoxLayout *layout = new QVBoxLayout(this);
740 #if QT_VERSION >= 0x60000
741 layout->setContentsMargins(QMargins(0,0,0,0));
742 #else
743 layout->setMargin(0);
744 #endif
745 layout->setSpacing(0);
746 layout->addWidget(view);
747
748 connect(djview->getDjVuWidget(), SIGNAL(pageChanged(int)),
749 this, SLOT(pageChanged(int)) );
750 connect(view, SIGNAL(activated(const QModelIndex&)),
751 this, SLOT(activated(const QModelIndex&)) );
752
753 menu = new QMenu(this);
754 QActionGroup *group = new QActionGroup(this);
755 QAction *action;
756 action = menu->addAction(tr("Tiny","thumbnail menu"));
757 connect(action,SIGNAL(triggered()),this,SLOT(setSize()) );
758 action->setCheckable(true);
759 action->setActionGroup(group);
760 action->setData(32);
761 action = menu->addAction(tr("Small","thumbnail menu"));
762 connect(action,SIGNAL(triggered()),this,SLOT(setSize()) );
763 action->setCheckable(true);
764 action->setActionGroup(group);
765 action->setData(64);
766 action = menu->addAction(tr("Medium","thumbnail menu"));
767 connect(action,SIGNAL(triggered()),this,SLOT(setSize()) );
768 action->setCheckable(true);
769 action->setActionGroup(group);
770 action->setData(96);
771 action = menu->addAction(tr("Large","thumbnail menu"));
772 connect(action,SIGNAL(triggered()),this,SLOT(setSize()) );
773 action->setCheckable(true);
774 action->setActionGroup(group);
775 action->setData(160);
776 menu->addSeparator();
777 action = menu->addAction(tr("Smart","thumbnail menu"));
778 connect(action,SIGNAL(toggled(bool)),this,SLOT(setSmart(bool)) );
779 action->setCheckable(true);
780 action->setData(true);
781 updateActions();
782
783 #ifdef Q_OS_DARWIN
784 QString mc = tr("Control Left Mouse Button");
785 #else
786 QString mc = tr("Right Mouse Button");
787 #endif
788 setWhatsThis(tr("<html><b>Document thumbnails.</b><br/> "
789 "This panel display thumbnails for the document pages. "
790 "Double click a thumbnail to jump to the selected page. "
791 "%1 to change the thumbnail size or the refresh mode. "
792 "The smart refresh mode only computes thumbnails "
793 "when the page data is present (displayed or cached.)"
794 "</html>").arg(mc) );
795 }
796
797
798 void
799 QDjViewThumbnails::updateActions(void)
800 {
801 QAction *action;
802 int size = model->getSize();
803 bool smart = model->getSmart();
804 foreach(action, menu->actions())
805 {
806 QVariant data = action->data();
807 if (variantIsA(data, QVariant::Bool, QMetaType::Bool))
808 action->setChecked(smart);
809 else
810 action->setChecked(data.toInt() == size);
811 }
812 }
813
814
815 void
816 QDjViewThumbnails::pageChanged(int pageno)
817 {
818 if (pageno >= 0 && pageno < djview->pageNum())
819 {
820 QModelIndex mi = model->index(pageno);
821 if (! selection->isSelected(mi))
822 selection->select(mi, QItemSelectionModel::ClearAndSelect);
823 view->scrollTo(mi);
824 }
825 }
826
827
828 void
829 QDjViewThumbnails::activated(const QModelIndex &index)
830 {
831 if (index.isValid())
832 {
833 int pageno = index.row();
834 if (pageno>=0 && pageno<djview->pageNum())
835 djview->goToPage(pageno);
836 }
837 }
838
839
840 int
841 QDjViewThumbnails::size()
842 {
843 return model->getSize();
844 }
845
846
847 void
848 QDjViewThumbnails::setSize(int size)
849 {
850 model->setSize(size);
851 updateActions();
852 }
853
854
855 void
856 QDjViewThumbnails::setSize()
857 {
858 QAction *action = qobject_cast<QAction*>(sender());
859 if (action)
860 setSize(action->data().toInt());
861 }
862
863
864 bool
865 QDjViewThumbnails::smart()
866 {
867 return model->getSmart();
868 }
869
870
871 void
872 QDjViewThumbnails::setSmart(bool smart)
873 {
874 model->setSmart(smart);
875 updateActions();
876 }
877
878 void
879 QDjViewThumbnails::contextMenuEvent(QContextMenuEvent *event)
880 {
881 menu->exec(event->globalPos());
882 event->accept();
883 }
884
885
886
887
888
889
890
891 // =======================================
892 // QDJVIEWFIND
893 // =======================================
894
895
896 class QDjViewFind::Model : public QAbstractListModel
897 {
898 // This class implements the listview model.
899 // But the bulk contains private data for qdjviewfind!
900 Q_OBJECT
901 public:
902 Model(QDjViewFind*);
903 // model stuff
904 public:
905 virtual int rowCount(const QModelIndex &parent) const;
906 virtual QVariant data(const QModelIndex &index, int role) const;
907 void modelClear();
908 int modelFind(int pageno);
909 bool modelSelect(int pageno);
910 void modelAdd(int pageno, int hits);
911 private:
912 struct RowInfo { int pageno; int hits; QString name; };
913 QList<RowInfo> pages;
914 // private data stuff
915 public:
916 void nextHit(bool backwards);
917 void startFind(bool backwards, int delay=0);
918 void stopFind();
919 typedef QList<miniexp_t> Hit;
920 typedef QList<Hit> Hits;
921 QMap<int, Hits> hits;
922 protected:
923 virtual bool eventFilter(QObject*, QEvent*);
924 public slots:
925 void documentClosed(QDjVuDocument*);
926 void documentReady(QDjVuDocument*);
927 void clear();
928 void doHighlights(int pageno);
929 void doPending();
930 void workTimeout();
931 void animTimeout();
932 void makeSelectionVisible();
933 void pageChanged(int);
934 void textChanged();
935 void pageinfo();
936 void itemActivated(const QModelIndex&);
937 private:
938 friend class QDjViewFind;
939 QDjViewFind *widget;
940 QDjView *djview;
941 QTimer *animTimer;
942 QTimer *workTimer;
943 QItemSelectionModel *selection;
944 QAbstractButton *animButton;
945 QIcon animIcon;
946 QIcon findIcon;
947 QRegExp find;
948 int curWork;
949 int curPage;
950 int curHit;
951 bool searchBackwards;
952 bool caseSensitive;
953 bool wordOnly;
954 bool regExpMode;
955 bool working;
956 bool pending;
957 };
958
959
960 // ----------------------------------------
961 // QDJVIEWFIND::MODEL
962
963
964 QDjViewFind::Model::Model(QDjViewFind *widget)
965 : QAbstractListModel(widget),
966 widget(widget),
967 djview(widget->djview),
968 selection(0),
969 animButton(0),
970 curPage(0),
971 curHit(0),
972 searchBackwards(false),
973 caseSensitive(false),
974 wordOnly(true),
975 regExpMode(false),
976 working(false),
977 pending(false)
978 {
979 selection = new QItemSelectionModel(this);
980 animTimer = new QTimer(this);
981 workTimer = new QTimer(this);
982 workTimer->setSingleShot(true);
983 connect(animTimer, SIGNAL(timeout()), this, SLOT(animTimeout()));
984 connect(workTimer, SIGNAL(timeout()), this, SLOT(workTimeout()));
985 findIcon = QIcon(":/images/icon_empty.png");
986 }
987
988
989 int
990 QDjViewFind::Model::rowCount(const QModelIndex&) const
991 {
992 return pages.size();
993 }
994
995
996 QVariant
997 QDjViewFind::Model::data(const QModelIndex &index, int role) const
998 {
999 if (index.isValid())
1000 {
1001 int row = index.row();
1002 if (row>=0 && row<pages.size())
1003 {
1004 const RowInfo &info = pages[row];
1005 switch(role)
1006 {
1007 case Qt::DisplayRole:
1008 return info.name;
1009 case Qt::ToolTipRole:
1010 if (info.hits == 1)
1011 return tr("1 hit");
1012 return tr("%n hits", 0, info.hits);
1013 case Qt::WhatsThisRole:
1014 return widget->whatsThis();
1015 default:
1016 break;
1017 }
1018 }
1019 }
1020 return QVariant();
1021 }
1022
1023
1024 void
1025 QDjViewFind::Model::modelClear()
1026 {
1027 int nrows = pages.size();
1028 if (nrows > 0)
1029 {
1030 beginRemoveRows(QModelIndex(), 0, nrows-1);
1031 pages.clear();
1032 endRemoveRows();
1033 }
1034 }
1035
1036
1037 int
1038 QDjViewFind::Model::modelFind(int pageno)
1039 {
1040 int lo = 0;
1041 int hi = pages.size();
1042 while (lo < hi)
1043 {
1044 int k = (lo + hi - 1) / 2;
1045 if (pageno > pages[k].pageno)
1046 lo = k + 1;
1047 else if (pageno < pages[k].pageno)
1048 hi = k;
1049 else
1050 lo = hi = k;
1051 }
1052 return lo;
1053 }
1054
1055
1056 bool
1057 QDjViewFind::Model::modelSelect(int pageno)
1058 {
1059 int lo = modelFind(pageno);
1060 QModelIndex mi = index(lo);
1061 if (lo < pages.size() && pages[lo].pageno == pageno)
1062 {
1063 if (!selection->isSelected(mi))
1064 selection->select(mi, QItemSelectionModel::ClearAndSelect);
1065 return true;
1066 }
1067 selection->select(mi, QItemSelectionModel::Clear);
1068 return false;
1069 }
1070
1071
1072 void
1073 QDjViewFind::Model::modelAdd(int pageno, int hits)
1074 {
1075 QString name = djview->pageName(pageno);
1076 RowInfo info;
1077 info.pageno = pageno;
1078 info.hits = hits;
1079 if (hits == 1)
1080 info.name = tr("Page %1 (1 hit)").arg(name);
1081 else
1082 info.name = tr("Page %1 (%n hits)", 0, hits).arg(name);
1083 int lo = modelFind(pageno);
1084 if (lo < pages.size() && pages[lo].pageno == pageno)
1085 {
1086 pages[lo] = info;
1087 QModelIndex mi = index(lo);
1088 emit dataChanged(mi, mi);
1089 }
1090 else
1091 {
1092 beginInsertRows(QModelIndex(), lo, lo);
1093 pages.insert(lo, info);
1094 endInsertRows();
1095 if (pageno == djview->getDjVuWidget()->page())
1096 modelSelect(pageno);
1097 }
1098 }
1099
1100
1101 bool
1102 QDjViewFind::Model::eventFilter(QObject*, QEvent *event)
1103 {
1104 switch (event->type())
1105 {
1106 case QEvent::Show:
1107 if (working)
1108 {
1109 animTimer->start();
1110 workTimer->start();
1111 }
1112 default:
1113 break;
1114 }
1115 return false;
1116 }
1117
1118
1119 void
1120 QDjViewFind::Model::documentClosed(QDjVuDocument *doc)
1121 {
1122 disconnect(doc, 0, this, 0);
1123 stopFind();
1124 clear();
1125 curWork = 0;
1126 curPage = 0;
1127 curHit = -1;
1128 searchBackwards = false;
1129 pending = false;
1130 widget->eraseText();
1131 widget->combo->setEnabled(false);
1132 widget->label->setText(QString());
1133 widget->stack->setCurrentWidget(widget->label);
1134 }
1135
1136
1137 void
1138 QDjViewFind::Model::documentReady(QDjVuDocument *doc)
1139 {
1140 curWork = djview->getDjVuWidget()->page();
1141 curPage = curWork;
1142 curHit = -1;
1143 if (doc)
1144 {
1145 widget->combo->setEnabled(true);
1146 connect(doc, SIGNAL(pageinfo()), this, SLOT(pageinfo()));
1147 connect(doc, SIGNAL(idle()), this, SLOT(pageinfo()));
1148 if (! find.isEmpty())
1149 startFind(false);
1150 }
1151 }
1152
1153
1154 static bool
1155 miniexp_get_int(miniexp_t &r, int &x)
1156 {
1157 if (! miniexp_numberp(miniexp_car(r)))
1158 return false;
1159 x = miniexp_to_int(miniexp_car(r));
1160 r = miniexp_cdr(r);
1161 return true;
1162 }
1163
1164
1165 static bool
1166 miniexp_get_rect(miniexp_t &r, QRect &rect)
1167 {
1168 int x1,y1,x2,y2;
1169 if (! (miniexp_get_int(r, x1) && miniexp_get_int(r, y1) &&
1170 miniexp_get_int(r, x2) && miniexp_get_int(r, y2) ))
1171 return false;
1172 if (x2<x1 || y2<y1)
1173 return false;
1174 rect.setCoords(x1, y1, x2, y2);
1175 return true;
1176 }
1177
1178
1179 static int
1180 parse_text_type(miniexp_t exp)
1181 {
1182 static const char *names[] = {
1183 "char", "word", "line", "para", "region", "column", "page"
1184 };
1185 static const int nsymbs = sizeof(names)/sizeof(const char*);
1186 static miniexp_t symbs[nsymbs];
1187 if (! symbs[0])
1188 for (int i=0; i<nsymbs; i++)
1189 symbs[i] = miniexp_symbol(names[i]);
1190 for (int i=0; i<nsymbs; i++)
1191 if (exp == symbs[i])
1192 return i;
1193 return -1;
1194 }
1195
1196 static int count_final_spaces(const QString &s)
1197 {
1198 int c = 0;
1199 int l = s.size();
1200 while (l>0 && s[--l].isSpace())
1201 c += 1;
1202 return c;
1203 }
1204
1205 static QString chopped(QString s, int c)
1206 {
1207 s.chop(c);
1208 return s;
1209 }
1210
1211 static bool
1212 miniexp_get_text(miniexp_t exp, QString &result,
1213 QMap<int,miniexp_t> &positions, int &state)
1214 {
1215 miniexp_t type = miniexp_car(exp);
1216 int typenum = parse_text_type(type);
1217 miniexp_t r = exp = miniexp_cdr(exp);
1218 if (! miniexp_symbolp(type))
1219 return false;
1220 QRect rect;
1221 if (! miniexp_get_rect(r, rect))
1222 return false;
1223 miniexp_t s = miniexp_car(r);
1224 state = qMax(state, typenum);
1225 if (miniexp_stringp(s) && !miniexp_cdr(r))
1226 {
1227 int c = count_final_spaces(result);
1228 if (state >= 2 && !result.endsWith('\n'))
1229 result = chopped(result,c) + "\n";
1230 else if (state >= 1 && c == 0)
1231 result += " ";
1232 state = -1;
1233 positions[result.size()] = exp;
1234 result += QString::fromUtf8(miniexp_to_str(s)).trimmed();
1235 r = miniexp_cdr(r);
1236 }
1237 while(miniexp_consp(s))
1238 {
1239 miniexp_get_text(s, result, positions, state);
1240 r = miniexp_cdr(r);
1241 s = miniexp_car(r);
1242 }
1243 if (r)
1244 return false;
1245 state = qMax(state, typenum);
1246 return true;
1247 }
1248
1249
1250 static QList<QList<miniexp_t> >
1251 miniexp_search_text(miniexp_t exp, QRegExp regex)
1252 {
1253 QList<QList<miniexp_t> > hits;
1254 QString text;
1255 QMap<int, miniexp_t> positions;
1256 // build string
1257 int state = -1;
1258 if (! miniexp_get_text(exp, text, positions, state))
1259 return hits;
1260 // search hits
1261 int offset = 0;
1262 int match;
1263 while ((match = regex.indexIn(text, offset)) >= 0)
1264 {
1265 QList<miniexp_t> hit;
1266 int endmatch = match + regex.matchedLength();
1267 offset += 1;
1268 if (endmatch <= match)
1269 continue;
1270 QMap<int,miniexp_t>::const_iterator pos = positions.lowerBound(match);
1271 while (pos != positions.begin() && pos.key() > match)
1272 --pos;
1273 for (; pos != positions.end() && pos.key() < endmatch; ++pos)
1274 hit += pos.value();
1275 hits += hit;
1276 if (pos != positions.end())
1277 offset = pos.key();
1278 else
1279 break;
1280 }
1281 return hits;
1282 }
1283
1284
1285 void
1286 QDjViewFind::Model::clear()
1287 {
1288 QDjVuWidget *djvuWidget = djview->getDjVuWidget();
1289 QMap<int,Hits>::const_iterator pos;
1290 for (pos=hits.begin(); pos!=hits.end(); ++pos)
1291 if (pos.value().size() > 0)
1292 djvuWidget->clearHighlights(pos.key());
1293 pending = false;
1294 hits.clear();
1295 modelClear();
1296 }
1297
1298
1299 void
1300 QDjViewFind::Model::doHighlights(int pageno)
1301 {
1302 if (hits.contains(pageno))
1303 {
1304 QColor color = Qt::blue;
1305 QDjVuWidget *djvu = djview->getDjVuWidget();
1306 Hit pageHit;
1307 color.setAlpha(96);
1308 foreach(pageHit, hits[pageno])
1309 {
1310 QRect rect;
1311 miniexp_t exp;
1312 foreach(exp, pageHit)
1313 {
1314 if (miniexp_get_rect(exp, rect))
1315 djvu->addHighlight(pageno, rect.x(), rect.y(),
1316 rect.width(), rect.height(),
1317 color, true );
1318 }
1319 }
1320 }
1321 }
1322
1323
1324 void
1325 QDjViewFind::Model::doPending()
1326 {
1327 QDjVuWidget *djvu = djview->getDjVuWidget();
1328 while (pending && hits.contains(curPage) && pages.size()>0)
1329 {
1330 Hits pageHits = hits[curPage];
1331 int nhits = pageHits.size();
1332 if (searchBackwards)
1333 {
1334 if (curHit < 0 || curHit >= nhits)
1335 curHit = nhits;
1336 curHit--;
1337 }
1338 else
1339 {
1340 if (curHit < 0 || curHit >= nhits)
1341 curHit = -1;
1342 curHit++;
1343 }
1344 if (curHit >= 0 && curHit < nhits)
1345 {
1346 // jump to position
1347 pending = false;
1348 Hit hit = pageHits[curHit];
1349 QRect rect;
1350 if (hit.size() > 0 && miniexp_get_rect(hit[0], rect))
1351 {
1352 QDjVuWidget::Position pos;
1353 pos.pageNo = curPage;
1354 pos.posPage = rect.center();
1355 pos.inPage = true;
1356 djvu->setPosition(pos, djvu->viewport()->rect().center());
1357 }
1358 }
1359 else
1360 {
1361 // next page
1362 curHit = -1;
1363 if (searchBackwards)
1364 {
1365 curPage -= 1;
1366 if (curPage < 0)
1367 curPage = djview->pageNum() - 1;
1368 }
1369 else
1370 {
1371 curPage += 1;
1372 if (curPage >= djview->pageNum())
1373 curPage = 0;
1374 }
1375 }
1376 }
1377 if (! pending)
1378 djview->statusMessage(QString());
1379 }
1380
1381
1382 void
1383 QDjViewFind::Model::workTimeout()
1384 {
1385 // do some work
1386 int startingPoint = curWork;
1387 bool somePagesWithText = false;
1388 doPending();
1389 while (working)
1390 {
1391 if (hits.contains(curWork))
1392 {
1393 somePagesWithText = true;
1394 }
1395 else
1396 {
1397 QString name = djview->pageName(curWork);
1398 QDjVuDocument *doc = djview->getDocument();
1399 miniexp_t exp = doc->getPageText(curWork, false);
1400 if (exp == miniexp_dummy)
1401 {
1402 // data not present
1403 if (pending)
1404 djview->statusMessage(tr("Searching page %1 (waiting for data.)")
1405 .arg(name) );
1406 if (pending || widget->isVisible())
1407 doc->getPageText(curWork, true);
1408 // timer will be reactivated by pageinfo()
1409 return;
1410 }
1411 Hits pageHits;
1412 hits[curWork] = pageHits;
1413 if (exp != miniexp_nil)
1414 {
1415 somePagesWithText = true;
1416 if (pending)
1417 djview->statusMessage(tr("Searching page %1.").arg(name));
1418 pageHits = miniexp_search_text(exp, find);
1419 hits[curWork] = pageHits;
1420 if (pageHits.size() > 0)
1421 {
1422 modelAdd(curWork, pageHits.size());
1423 doHighlights(curWork);
1424 doPending();
1425 makeSelectionVisible();
1426 }
1427 // enough
1428 break;
1429 }
1430 }
1431 // next page
1432 int pageNum = djview->pageNum();
1433 if (searchBackwards)
1434 {
1435 if (curWork <= 0)
1436 curWork = pageNum;
1437 curWork -= 1;
1438 }
1439 else
1440 {
1441 curWork += 1;
1442 if (curWork >= pageNum)
1443 curWork = 0;
1444 }
1445 // finished?
1446 if (curWork == startingPoint)
1447 {
1448 stopFind();
1449 djview->statusMessage(QString());
1450 if (! pages.size())
1451 {
1452 QString msg = tr("No hits!");
1453 if (! somePagesWithText)
1454 {
1455 widget->eraseText();
1456 widget->combo->setEnabled(false);
1457 msg = tr("<html>Document is not searchable. "
1458 "No page contains information "
1459 "about its textual content.</html>");
1460 }
1461 else if (! find.isValid())
1462 {
1463 msg = tr("<html>Invalid regular expression.</html>");
1464 }
1465 widget->stack->setCurrentWidget(widget->label);
1466 widget->label->setText(msg);
1467 }
1468 }
1469 }
1470 // restart timer
1471 if (working)
1472 workTimer->start(0);
1473 }
1474
1475
1476 void
1477 QDjViewFind::Model::animTimeout()
1478 {
1479 if (animButton && !animIcon.isNull())
1480 {
1481 if (animButton->icon().cacheKey() == findIcon.cacheKey())
1482 animButton->setIcon(animIcon);
1483 else
1484 animButton->setIcon(findIcon);
1485 }
1486 }
1487
1488
1489 void
1490 QDjViewFind::Model::nextHit(bool backwards)
1491 {
1492 djview->getDjVuWidget()->terminateAnimation();
1493 if (working && backwards != searchBackwards)
1494 {
1495 pending = false;
1496 startFind(backwards);
1497 }
1498 searchBackwards = backwards;
1499 if (! find.isEmpty())
1500 {
1501 pending = true;
1502 doPending();
1503 if (working && pending && !workTimer->isActive())
1504 workTimer->start(0);
1505 }
1506 }
1507
1508
1509 void
1510 QDjViewFind::Model::startFind(bool backwards, int delay)
1511 {
1512 stopFind();
1513 searchBackwards = backwards;
1514 if (! find.isEmpty() && djview->pageNum() > 0)
1515 {
1516 widget->label->setText(QString());
1517 widget->stack->setCurrentWidget(widget->view);
1518 animButton = (backwards) ? widget->upButton : widget->downButton;
1519 animIcon = animButton->icon();
1520 animTimer->start(250);
1521 workTimer->start(delay);
1522 curWork = djview->getDjVuWidget()->page();
1523 working = true;
1524 }
1525 }
1526
1527
1528 void
1529 QDjViewFind::Model::stopFind()
1530 {
1531 animTimer->stop();
1532 workTimer->stop();
1533 if (animButton)
1534 {
1535 animButton->setIcon(animIcon);
1536 animButton = 0;
1537 }
1538 working = false;
1539 }
1540
1541
1542 void
1543 QDjViewFind::Model::pageinfo()
1544 {
1545 if (working && !workTimer->isActive())
1546 workTimer->start(0);
1547 }
1548
1549
1550 void
1551 QDjViewFind::Model::makeSelectionVisible()
1552 {
1553 QModelIndexList s = selection->selectedIndexes();
1554 if (s.size() > 0)
1555 widget->view->scrollTo(s[0]);
1556 }
1557
1558
1559 void
1560 QDjViewFind::Model::pageChanged(int pageno)
1561 {
1562 QDjVuWidget *djvu = djview->getDjVuWidget();
1563 if (djvu && djvu->animationInProgress())
1564 return;
1565 if (pageno != curPage)
1566 {
1567 curHit = -1;
1568 curPage = pageno;
1569 pending = false;
1570 }
1571 curWork = pageno;
1572 }
1573
1574
1575 void
1576 QDjViewFind::Model::textChanged()
1577 {
1578 stopFind();
1579 clear();
1580 QString s = widget->text();
1581 widget->label->setText(QString());
1582 widget->stack->setCurrentWidget(widget->label);
1583 if (s.isEmpty())
1584 {
1585 find = QRegExp();
1586 }
1587 else
1588 {
1589 if (!regExpMode)
1590 {
1591 s = QRegExp::escape(widget->text());
1592 reReplace(s, QRegExp("\\s+"), " ");
1593 }
1594 if (wordOnly)
1595 s = "\\b" + s;
1596 find = QRegExp(s);
1597 if (caseSensitive)
1598 find.setCaseSensitivity(Qt::CaseSensitive);
1599 else
1600 find.setCaseSensitivity(Qt::CaseInsensitive);
1601 startFind(searchBackwards, 250);
1602 }
1603 }
1604
1605
1606 void
1607 QDjViewFind::Model::itemActivated(const QModelIndex &mi)
1608 {
1609 if (mi.isValid())
1610 {
1611 int row = mi.row();
1612 if (row >= 0 && row < pages.size() && pages[row].hits > 0)
1613 {
1614 curPage = pages[row].pageno;
1615 curHit = -1;
1616 pending = true;
1617 doPending();
1618 }
1619 }
1620 }
1621
1622
1623
1624 // ----------------------------------------
1625 // QDJVIEWFIND
1626
1627
1628 QDjViewFind::QDjViewFind(QDjView *djview)
1629 : QWidget(djview),
1630 djview(djview),
1631 model(0),
1632 view(0)
1633 {
1634 model = new Model(this);
1635 installEventFilter(model);
1636
1637 view = new QListView(this);
1638 view->setModel(model);
1639 view->setSelectionModel(model->selection);
1640 view->setDragEnabled(false);
1641 view->setEditTriggers(QAbstractItemView::NoEditTriggers);
1642 view->setSelectionBehavior(QAbstractItemView::SelectRows);
1643 view->setSelectionMode(QAbstractItemView::SingleSelection);
1644 view->setTextElideMode(Qt::ElideMiddle);
1645 view->setViewMode(QListView::ListMode);
1646 view->setWrapping(false);
1647 view->setResizeMode(QListView::Adjust);
1648 caseSensitiveAction = new QAction(tr("Case sensitive"), this);
1649 caseSensitiveAction->setCheckable(true);
1650 caseSensitiveAction->setChecked(model->caseSensitive);
1651 wordOnlyAction = new QAction(tr("Words only"), this);
1652 wordOnlyAction->setCheckable(true);
1653 wordOnlyAction->setChecked(model->wordOnly);
1654 regExpModeAction = new QAction(tr("Regular expression"), this);
1655 regExpModeAction->setCheckable(true);
1656 regExpModeAction->setChecked(model->regExpMode);
1657 menu = new QMenu(this);
1658 menu->addAction(caseSensitiveAction);
1659 menu->addAction(wordOnlyAction);
1660 menu->addAction(regExpModeAction);
1661 QBoxLayout *vlayout = new QVBoxLayout(this);
1662 combo = new QComboBox(this);
1663 combo->setEditable(true);
1664 combo->setMaxCount(8);
1665 combo->setInsertPolicy(QComboBox::InsertAtTop);
1666 combo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
1667 vlayout->addWidget(combo);
1668 QBoxLayout *hlayout = new QHBoxLayout;
1669 hlayout->setSpacing(0);
1670 vlayout->addLayout(hlayout);
1671 upButton = new QToolButton(this);
1672 upButton->setIcon(QIcon(":/images/icon_up.png"));
1673 upButton->setToolTip(tr("Find Previous (Shift+F3) "));
1674 upButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
1675 hlayout->addWidget(upButton);
1676 downButton = new QToolButton(this);
1677 downButton->setIcon(QIcon(":/images/icon_down.png"));
1678 downButton->setToolTip(tr("Find Next (F3) "));
1679 downButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
1680 hlayout->addWidget(downButton);
1681 hlayout->addStretch(2);
1682 resetButton = new QToolButton(this);
1683 resetButton->setIcon(QIcon(":/images/icon_erase.png"));
1684 resetButton->setToolTip(tr("Reset search options to default values."));
1685 resetButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
1686 hlayout->addWidget(resetButton);
1687 QToolButton *optionButton = new QToolButton(this);
1688 optionButton->setText(tr("Options"));
1689 optionButton->setPopupMode(QToolButton::InstantPopup);
1690 optionButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
1691 optionButton->setMenu(menu);
1692 optionButton->setAttribute(Qt::WA_CustomWhatsThis);
1693 optionButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
1694 hlayout->addWidget(optionButton);
1695 stack = new QStackedLayout();
1696 view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1697 view->setFrameShadow(QFrame::Sunken);
1698 view->setFrameShape(QFrame::StyledPanel);
1699 stack->addWidget(view);
1700 label = new QLabel(this);
1701 label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1702 label->setAlignment(Qt::AlignCenter);
1703 label->setWordWrap(true);
1704 label->setFrameShadow(QFrame::Sunken);
1705 label->setFrameShape(QFrame::StyledPanel);
1706 stack->addWidget(label);
1707 vlayout->addLayout(stack);
1708
1709 connect(djview, SIGNAL(documentClosed(QDjVuDocument*)),
1710 model, SLOT(documentClosed(QDjVuDocument*)) );
1711 connect(djview, SIGNAL(documentReady(QDjVuDocument*)),
1712 model, SLOT(documentReady(QDjVuDocument*)) );
1713 connect(view, SIGNAL(activated(const QModelIndex&)),
1714 model, SLOT(itemActivated(const QModelIndex&)));
1715 connect(djview->getDjVuWidget(), SIGNAL(pageChanged(int)),
1716 this, SLOT(pageChanged(int)));
1717 connect(combo->lineEdit(), SIGNAL(textChanged(QString)),
1718 model, SLOT(textChanged()));
1719 connect(combo->lineEdit(), SIGNAL(returnPressed()),
1720 this, SLOT(findAgain()));
1721 connect(caseSensitiveAction, SIGNAL(triggered(bool)),
1722 this, SLOT(setCaseSensitive(bool)));
1723 connect(wordOnlyAction, SIGNAL(triggered(bool)),
1724 this, SLOT(setWordOnly(bool)));
1725 connect(regExpModeAction, SIGNAL(triggered(bool)),
1726 this, SLOT(setRegExpMode(bool)));
1727 connect(upButton, SIGNAL(clicked()),
1728 this, SLOT(findPrev()));
1729 connect(downButton, SIGNAL(clicked()),
1730 this, SLOT(findNext()));
1731 connect(resetButton, SIGNAL(clicked()),
1732 this, SLOT(eraseText()));
1733
1734 setWhatsThis
1735 (tr("<html><b>Finding text.</b><br/> "
1736 "Search hits appear progressively as soon as you type "
1737 "a search string. Typing enter jumps to the next hit. "
1738 "To move to the previous or next hit, you can also use "
1739 "the arrow buttons or the shortcuts <tt>F3</tt> or "
1740 "<tt>Shift-F3</tt>. You can also double click a page name. "
1741 "Use the <tt>Options</tt> menu to search words only or "
1742 "to specify the case sensitivity."
1743 "</html>"));
1744 wordOnlyAction->setStatusTip
1745 (tr("Specify whether search hits must begin on a word boundary."));
1746 caseSensitiveAction->setStatusTip
1747 (tr("Specify whether searches are case sensitive."));
1748 regExpModeAction->setStatusTip
1749 (tr("Regular expressions describe complex string matching patterns."));
1750 regExpModeAction->setWhatsThis
1751 (tr("<html><b>Regular Expression Quick Guide</b><ul>"
1752 "<li>The dot <tt>.</tt> matches any character.</li>"
1753 "<li>Most characters match themselves.</li>"
1754 "<li>Prepend a backslash <tt>\\</tt> to match special"
1755 " characters <tt>()[]{}|*+.?!^$\\</tt>.</li>"
1756 "<li><tt>\\b</tt> matches a word boundary.</li>"
1757 "<li><tt>\\w</tt> matches a word character.</li>"
1758 "<li><tt>\\d</tt> matches a digit character.</li>"
1759 "<li><tt>\\s</tt> matches a blank character.</li>"
1760 "<li><tt>\\n</tt> matches a newline character.</li>"
1761 "<li><tt>[<i>a</i>-<i>b</i>]</tt> matches characters in range"
1762 " <tt><i>a</i></tt>-<tt><i>b</i></tt>.</li>"
1763 "<li><tt>[^<i>a</i>-<i>b</i>]</tt> matches characters outside range"
1764 " <tt><i>a</i></tt>-<tt><i>b</i></tt>.</li>"
1765 "<li><tt><i>a</i>|<i>b</i></tt> matches either regular expression"
1766 " <tt><i>a</i></tt> or regular expression <tt><i>b</i></tt>.</li>"
1767 "<li><tt><i>a</i>{<i>n</i>,<i>m</i>}</tt> matches regular expression"
1768 " <tt><i>a</i></tt> repeated <tt><i>n</i></tt> to <tt><i>m</i></tt>"
1769 " times.</li>"
1770 "<li><tt><i>a</i>?</tt>, <tt><i>a</i>*</tt>, and <tt><i>a</i>+</tt>"
1771 " are shorthands for <tt><i>a</i>{0,1}</tt>, <tt><i>a</i>{0,}</tt>, "
1772 " and <tt><i>a</i>{1,}</tt>.</li>"
1773 "<li>Use parentheses <tt>()</tt> to group regular expressions "
1774 " before <tt>?+*{</tt>.</li>"
1775 "</ul></html>"));
1776
1777 eraseText();
1778 combo->setEnabled(false);
1779 label->setText(QString());
1780 stack->setCurrentWidget(label);
1781 if (djview->getDocument())
1782 model->documentReady(djview->getDocument());
1783 }
1784
1785
1786 void
1787 QDjViewFind::contextMenuEvent(QContextMenuEvent *event)
1788 {
1789 menu->exec(event->globalPos());
1790 event->accept();
1791 }
1792
1793
1794 void
1795 QDjViewFind::takeFocus(Qt::FocusReason reason)
1796 {
1797 if (combo->isVisible())
1798 combo->setFocus(reason);
1799 }
1800
1801
1802 QString
1803 QDjViewFind::text()
1804 {
1805 return combo->lineEdit()->text();
1806 }
1807
1808
1809 bool
1810 QDjViewFind::caseSensitive()
1811 {
1812 return model->caseSensitive;
1813 }
1814
1815
1816 bool
1817 QDjViewFind::wordOnly()
1818 {
1819 return model->wordOnly;
1820 }
1821
1822
1823 bool
1824 QDjViewFind::regExpMode()
1825 {
1826 return model->regExpMode;
1827 }
1828
1829
1830 void
1831 QDjViewFind::setText(QString s)
1832 {
1833 if (s != text())
1834 combo->lineEdit()->setText(s);
1835 }
1836
1837
1838 void
1839 QDjViewFind::selectAll()
1840 {
1841 combo->lineEdit()->selectAll();
1842 combo->lineEdit()->setFocus();
1843 }
1844
1845
1846 void
1847 QDjViewFind::eraseText()
1848 {
1849 setText(QString());
1850 setRegExpMode(false);
1851 setWordOnly(true);
1852 setCaseSensitive(false);
1853 }
1854
1855
1856 void
1857 QDjViewFind::setCaseSensitive(bool b)
1858 {
1859 if (b != model->caseSensitive)
1860 {
1861 caseSensitiveAction->setChecked(b);
1862 model->caseSensitive = b;
1863 model->textChanged();
1864 }
1865 }
1866
1867
1868 void
1869 QDjViewFind::setWordOnly(bool b)
1870 {
1871 if (b != model->wordOnly)
1872 {
1873 wordOnlyAction->setChecked(b);
1874 model->wordOnly = b;
1875 model->textChanged();
1876 }
1877 }
1878
1879
1880 void
1881 QDjViewFind::setRegExpMode(bool b)
1882 {
1883 if (b != model->regExpMode)
1884 {
1885 regExpModeAction->setChecked(b);
1886 model->regExpMode = b;
1887 model->textChanged();
1888 }
1889 }
1890
1891
1892 void
1893 QDjViewFind::findNext()
1894 {
1895 if (text().isEmpty())
1896 djview->showFind();
1897 model->nextHit(false);
1898 }
1899
1900
1901 void
1902 QDjViewFind::findPrev()
1903 {
1904 if (text().isEmpty())
1905 djview->showFind();
1906 model->nextHit(true);
1907 }
1908
1909
1910 void
1911 QDjViewFind::findAgain()
1912 {
1913 if (model->searchBackwards)
1914 findPrev();
1915 else
1916 findNext();
1917 }
1918
1919
1920 void
1921 QDjViewFind::pageChanged(int pageno)
1922 {
1923 if (pageno >= 0 && pageno < djview->pageNum())
1924 {
1925 model->pageChanged(pageno);
1926 if (model->modelSelect(pageno))
1927 model->makeSelectionVisible();
1928 }
1929 }
1930
1931
1932
1933
1934
1935
1936
1937
1938 // ----------------------------------------
1939 // MOC
1940
1941 #include "qdjviewsidebar.moc"
1942
1943
1944
1945
1946 /* -------------------------------------------------------------
1947 Local Variables:
1948 c++-font-lock-extra-types: ( "\\sw+_t" "[A-Z]\\sw*[a-z]\\sw*" )
1949 End:
1950 ------------------------------------------------------------- */