-
Notifications
You must be signed in to change notification settings - Fork 2
/
indexlist.cpp
635 lines (587 loc) · 37.1 KB
/
indexlist.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#include "indexlist.h"
#include <QEvent>
//"Official" kinetic scrolling. (Backport from Qt 4.8)
// See http://qt.gitorious.org/qt-labs/kineticscroller/commits/solution and
// http://bugreports.qt.nokia.com/browse/QTBUG-9054?focusedCommentId=130700&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_130700
#include <QtScroller>
#include <qtscrollevent>
#include <QDebug>
#include <QScrollBar>
#include <QUrl>
//Uncomment for indexlist debug output
//#define DEBUG_INDEXLIST 1
//To update article list during scrolling.
bool ArticleListFilter::eventFilter(QObject *o, QEvent *e)
{
switch (e->type())
{
case QtScrollPrepareEvent::ScrollPrepare:
{
QtScrollPrepareEvent *se = static_cast<QtScrollPrepareEvent *> (e);
#ifdef DEBUG_INDEXLIST
qDebug() << " ScrollPrepare: " << se->startPos();
#endif
QWidget *w = static_cast<QWidget *> (o);
return false;
}
case QtScrollEvent::Scroll:
{
QtScrollEvent *se = static_cast<QtScrollEvent *> (e);
QWidget *w = static_cast<QWidget *> (o);
if (w->parentWidget())
{
if (QListWidget *lw = qobject_cast<QListWidget *>(w->parentWidget()))
{
if (lw->viewport() == w)
{
qreal delta = lw->visualItemRect(
lw->item(0)).height();
if (se->scrollState()==QtScrollEvent::ScrollStarted) {
#ifdef DEBUG_INDEXLIST
qDebug() << "New Scrolling activity started. ";
qDebug() << " Scroller final position: " << QtScroller::scroller(w)->finalPosition();
qDebug() << "delta: " <<delta;
#endif
}
if (se->contentPos().y() > lw->verticalScrollBar()->maximum() -delta)
// if (QtScroller::scroller(w)->finalPosition().y()==lw->verticalScrollBar()->maximum())
{
if (QtScroller::scroller(w)->velocity().y() > 0.0) {
#ifdef DEBUG_INDEXLIST
qDebug() << " Scroller final position: " << QtScroller::scroller(w)->finalPosition();
qDebug() << " ScrollEvent. ScrollState: " << se->scrollState()
<< " contentPos: " << se->contentPos();
qDebug() << " Velocity " << QtScroller::scroller(w)->velocity();
qDebug() << "ArticleList: vminimum " << lw->verticalScrollBar()->minimum();
qDebug() << "ArticleList: vmaximum "
<< lw->verticalScrollBar()->maximum();
#endif
QtScroller::scroller(w)->stop();
approachingEndOfList(false);
return true;
}
}
else if (se->contentPos().y() < lw->verticalScrollBar()->minimum()+delta)
//else if (QtScroller::scroller(w)->finalPosition().y()==lw->verticalScrollBar()->minimum())
{
if (QtScroller::scroller(w)->velocity().y() < 0.0) {
#ifdef DEBUG_INDEXLIST
qDebug() << " Scroller final position: " << QtScroller::scroller(w)->finalPosition();
qDebug() << " ScrollEvent. ScrollState: " << se->scrollState()
<< " contentPos: " << se->contentPos();
qDebug() << " Velocity " << QtScroller::scroller(w)->velocity();
qDebug() << "ArticleList: vminimum " << lw->verticalScrollBar()->minimum();
qDebug() << "ArticleList: vmaximum "
<< lw->verticalScrollBar()->maximum();
#endif
QtScroller::scroller(w)->stop();
//TODO: Overshoot. Trial not working: if not items added return false (event further processed for overhoot)
emit approachingEndOfList(true);
return true;
//Return true to prevent that default QScroller eventfilter scrolls
// to beginning of list and stop scroller. (Nicer would be for sure
// if it would continue scrolling from the new position with
// the same speed). TODO try to do this (e.g. void QScroller::resendPrepareEvent () )
// QtScroller::scroller(w)->stop(); //Does not really work. Sometimes it works. (Stops, and shows
// element focused by approachingEndOflist, but mostly it "jumps" to first element of list)
//Interestingly behavior basically uncahnged with resendPr.
//TODO
//QtScroller::scroller(w)->resendPrepareEvent();
//Note:Without deleting elements in approachingEndOfList this worked better.
//Note: Could this be a concurrency issue? (are events queued??)=> Try with stopping before.
// => Looks like with stopping before it works fine. (Although a little rough, as it jumps the last
// (use scrollTo of scroller for smooth scrolling??) do something clever with resendPrepareEvent()? (Diffuclt)
// Perhaps also just reload when first element hit. (stopping before is useless if it cannot continue later)
// (Or throw all away and use modelview framework)
//TODO bounce not working anymore.(Probably necessary to not stop (return true) if nothing can be added.
}
}
}
}
}
return false;
}
default:
return false;
}
return false;
}
IndexList::IndexList(QWidget *parent, ZimFileWrapper* zimFileWrapper, bool hasTouchScreen) :
QListWidget(parent), zimFileWrapper(zimFileWrapper), hasTouchScreen(hasTouchScreen)
{
#if defined(Q_OS_ANDROID)
//Default font to large on android (at least with necessitas alpha3.)-> set to 24 px.
setStyleSheet(QLatin1String("QListWidget {font-size: 24px; background-color:white;color: black; selection-background-color: blue}"));
#else
setStyleSheet(QLatin1String("QListWidget {background-color:white;color: black; selection-background-color: blue}"));
#endif
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// ScrollPerPixel required for kinetic scrolling
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
#if defined(Q_OS_SYMBIAN) || defined(Q_OS_ANDROID)
//As following not working (Q_WS_HARMATTAN not defined): #if !defined(Q_WS_SIMULATOR) && !defined(Q_WS_HARMATTAN)
//Crashes on simulator/Bug 70 on harmattan
QtScroller::grabGesture(viewport(), QtScroller::LeftMouseButtonGesture);
#endif
ArticleListFilter *articleListFilter = new ArticleListFilter(this);
viewport()->installEventFilter(articleListFilter);
connect(articleListFilter,SIGNAL(approachingEndOfList(bool)),this, SLOT(addItemsToArticleList(bool)));
}
//For debug output
QString IndexList::articleListItemToString(QListWidgetItem* item) {
QUrl url = item->data(ArticleUrlRole).toUrl();
QString urlEncoded = QString::fromUtf8(url.toEncoded().data(),url.toEncoded().length());
QString s = QString(QLatin1String("arcticleListItem: \n\tindex: %1\n"
"\ttitle: %2\n"
"\turl (encoded): %3\n")).arg(item->data(ArticleIndexRole).toString(),
item->data(ArticleTitleRole).toString(),
urlEncoded);
return s;
}
std::pair <bool, QListWidgetItem*> IndexList::getArticleListItem(zim::File::const_iterator it) {
QListWidgetItem* articleItem = new QListWidgetItem();
if (it==zimFileWrapper->end()) {
#ifdef DEBUG_INDEXLIST
qDebug() << "getArticleListItem iterator points is end of article list. ";
#endif
return std::pair<bool, QListWidgetItem*> (false, articleItem);
}
QString articleTitle = zimFileWrapper->fromUTF8EncodedStdString(it->getTitle());
QUrl articleUrl = QUrl::fromEncoded(QUrl::toPercentEncoding(zimFileWrapper->fromUTF8EncodedStdString(it->getUrl())));
QString articleIdx = QString::number(it->getIndex());
if (it->getNamespace() != 'A')
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< " Index entry to be added is not in article namespace. Stop adding titles. \n\tArticle Title: ["
<< articleIdx << "] " << articleTitle
<< "\n\tArticle Namespace: " << it->getNamespace();
#endif
return std::pair<bool, QListWidgetItem*> (false, articleItem);
}
articleItem->setText(articleTitle);
articleItem->setData(ArticleTitleRole, articleTitle);
articleItem->setData(ArticleIndexRole, articleIdx);
articleItem->setData(ArticleUrlRole, articleUrl);
return std::pair<bool, QListWidgetItem*> (true, articleItem);
}
void IndexList::populateArticleList(QString articleName) {
populateArticleList(articleName, 0, false);
}
void IndexList::populateArticleList(QString articleName, int ignoreFirstN,
bool direction_up, bool noDelete)
{
#ifdef DEBUG_INDEXLIST
qDebug() << "in populateArticleList. articleName: " << articleName
<< ". ignoreFirstN: " << ignoreFirstN << ". direction_up:"
<< direction_up << ".noDelete: " << noDelete;
#endif
if (zimFileWrapper->isValid())
{
try
{
//Find article, if not an exact match, Iterator may point to end, or to
// element of other namespace. (like image (I) or metadata (M))
zim::File::const_iterator it = zimFileWrapper->findByTitle(QLatin1Char('A'),
articleName);
if (((it==zimFileWrapper->end()) || (it->getNamespace() != 'A') )) {
#ifdef DEBUG_INDEXLIST
qDebug() << " No valid article >= \"" << articleName << "\" found. Try using previous entry in zim file instead";
#endif
if (it==zimFileWrapper->begin()) {
#ifdef DEBUG_INDEXLIST
qDebug() << " zim file contains no entries. Add nothing to list";
#endif
return;
}
--it;
if ((it==zimFileWrapper->end()) || (it->getNamespace() != 'A') ) {
qWarning() << " Previous entry is neither a valid article. Bug?. Add nothing to list";
return;
}
}
if (!direction_up) {
// If populating in reverse direction, don´t clear items now
// but instead each time a new item is added. This avoids
// that cannot be fully filled if the beginning of the zim file
// is reached.
if (noDelete==false) {
clear();
}
}
int i = 0;
int insertedItemsCount = 0;
while (true)
{
std::pair <bool, QListWidgetItem*> articleItemPair = getArticleListItem(it);
if (!articleItemPair.first) {
break;
}
if (direction_up)
{
if (i >= ignoreFirstN)
{
insertItem(0, articleItemPair.second);
insertedItemsCount++;
if (noDelete==false) {
QListWidgetItem *lastItem = takeItem(count() - 1);
delete lastItem;
}
}
//Note: zimFile->begin() actually does not necessarily point
// to same article as it if the are equal. (Because it is in title
// order while zimFile->begin() uses url order. However, it is fine to detect
// that it is entry 0, because only the index is compared.
// there is also beginByTitle(), but end() has the same behavior,
// and there is not title order equivalent, therefore for both
// the url order is used.
if (it == zimFileWrapper->begin())
break;
--it;
}
else
{
if (i >= ignoreFirstN)
{
addItem(articleItemPair.second);
insertedItemsCount++;
}
if (it == zimFileWrapper->end())
break;
++it;
}
i++;
if (hasTouchScreen)
{
if (insertedItemsCount >= 100)
{
break;
}
}
else if (insertedItemsCount > 0)
{
//Non-Touch: Only fill visible area, no scrolling
//Calculate height of all inserted items, and stop
//insertion when visible area of list is full.
int itemHeight = visualItemRect(
item(0)).height();
int
articleListWidgetHeight =
maximumViewportSize().height();
QListWidgetItem *bottomItem = item(
insertedItemsCount - 1);
int
bottomItemBottom =
visualItemRect(
bottomItem).bottom();
if ((bottomItemBottom + itemHeight)
>= articleListWidgetHeight)
{
break;
}
}
}
if (hasTouchScreen) {
//Add some items before found item (For smoother scrolling up)
int addedItemsCount = addItemsToArticleList(true,20);
#ifdef DEBUG_INDEXLIST
qDebug() << " Added " << addedItemsCount << " items before searched item. select searched item and scroll it to top of screen";
#endif
//Select found item. (i.p. useful for phones which have a keypad as well, and if not enough items left below found item to fill list)
setCurrentRow(addedItemsCount);
//Scroll to found item. (addItemsToArticleList scrolled to first added item, which is one too early)
scrollToItem (currentItem() , QAbstractItemView::PositionAtTop );
#ifdef DEBUG_INDEXLIST
qDebug() << "First item of list (after add)" << articleListItemToString(item(0));
qDebug() << "Last item of list (after add)" << articleListItemToString(item(count()-1));
#endif
} else {
//Non-touchscreen
setCurrentRow(0); //Select first found item
}
}
catch (const std::exception& e)
{
addItem(QLatin1String("Error occured"));
}
}
}
void IndexList::articleListSelectPreviousEntry()
{
//Actually forwarding key basically worked,
// as well, but crashing when trying to select item outside of list. (pretty strange)
//Anyway, for in future TODO planned to reload list when moving out of list.
if (count() > 0)
{
if (currentRow() == 0)
{
if (hasTouchScreen) {
//To basically same thing if scrolled.
#ifdef DEBUG_INDEXLIST
qDebug() << "up key while first entry selected. Add items.";
#endif
addItemsToArticleList(true);
} else {
//Old behavior. (TODO: May make sense to change to similar scheme as
// used with touchscreen devices)
QListWidgetItem *item = currentItem();
if (item->data(ArticleIndexRole).toInt() > 0)
{
populateArticleList(item->data(ArticleTitleRole).toString(), 1,
true);
setCurrentRow(
count() - 1);
}
}
}
else
{
setCurrentRow(
currentRow() - 1);
}
}
}
void IndexList::articleListSelectNextEntry()
{
//Actually forwarding key basically worked,
// as well, but crashing when trying to select item outside of list. (pretty strange)
//Anyway, for in future TODO planned to reload list when moving out of list.
if (count() > 0)
{
if (currentRow() == count()
- 1)
{
if (hasTouchScreen) {
//To basically same thing if scrolled.
#ifdef DEBUG_INDEXLIST
qDebug() << "down key while last entry selected. Add items.";
#endif
addItemsToArticleList(false);
} else {
//TODO check outof bounds
QListWidgetItem *item = currentItem();
populateArticleList(item->data(ArticleTitleRole).toString(), 1,
false);
setCurrentRow(0);
}
}
else
{
setCurrentRow(
currentRow() + 1);
}
}
}
//TODO Consider merging with regular populate Article List
//addCount: Number of article entries to be added (at most)
//maxCount: maximumCount of article entries allowed. Deletes items furthest away
//from added item for each item added
int IndexList::addItemsToArticleList(bool up, int addCount, int maxCount)
{
#ifdef DEBUG_INDEXLIST
qDebug() << "WikiOnBoard::addItemsToArticleList (up:"<<up<<" addCount: "<<addCount <<" maxCount: "<<maxCount;
#endif
if (zimFileWrapper->isValid())
{
try
{
if (count()==0) {
qWarning() << "articleList empty. addItemsToArticleList requires a least on article in the article list." ;
return 0;
}
if (up)
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< "AddItems to beginning of list";
#endif
QListWidgetItem * firstArticleInCurrentList = item(0);
QString
titleFirstArticleInCurrentList =
firstArticleInCurrentList->data(
ArticleTitleRole).toString();
#ifdef DEBUG_INDEXLIST
qDebug() << " First article in current list is: "<< articleListItemToString(firstArticleInCurrentList);
#endif
std::pair<bool, zim::File::const_iterator> r =
zimFileWrapper->findxByTitle(QLatin1Char('A'), titleFirstArticleInCurrentList);
if (!r.first)
{
qWarning()
<< " No exact match found. (Only possible if bug in wikionboard)";
}
zim::File::const_iterator it = r.second;
if (it == zimFileWrapper->beginByTitle())
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< " Current entry is first entry in index => Do nothing";
#endif
return 0;
}
int insertedItemsCount = 0;
while (insertedItemsCount < addCount)
{
--it;
std::pair <bool, QListWidgetItem*> articleItemPair = getArticleListItem(it);
if (!articleItemPair.first) {
break;
}
insertItem(0, articleItemPair.second);
insertedItemsCount++;
//Remove last item to avoid eating up to much memory.
//(But ensure that that there enough "old" items left
// to fill the article list. (first added new item
// should be on top of list at the end)
if (count()>maxCount) {
QListWidgetItem *lastItem = takeItem(
count() - 1);
delete lastItem;
}
//order is different
if (it == zimFileWrapper->beginByTitle())
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< "Beginning of title index reached. Stop adding titles. Last added title :"<< articleListItemToString(articleItemPair.second);
#endif
break;
}
} //End while
if (insertedItemsCount>0) {
QListWidgetItem *firstNewItem = item(insertedItemsCount-1);
#ifdef DEBUG_INDEXLIST
qDebug() << insertedItemsCount
<< " items inserted at beginning of list. Scroll so that firstly newly added article is at bottom of list. Firstly new added article: "<<articleListItemToString(firstNewItem);
#endif
scrollToItem(firstNewItem,QAbstractItemView::PositionAtTop);
return insertedItemsCount;
} else {
#ifdef DEBUG_INDEXLIST
qDebug() << "No items inserted";
#endif
return 0;
}
}
else
{// end (if up()). => up=false
#ifdef DEBUG_INDEXLIST
qDebug()
<< "AddItems to end of list";
#endif
QListWidgetItem* lastArticleInCurrentList = item(
count() - 1);
QString titleLastArticleInCurrentList =
lastArticleInCurrentList->data(
ArticleTitleRole).toString();
#ifdef DEBUG_INDEXLIST
qDebug() << " Last article in current list is: " << articleListItemToString(item(
count() - 1));
#endif
std::pair<bool, zim::File::const_iterator> r =
zimFileWrapper->findxByTitle(QLatin1Char('A'), titleLastArticleInCurrentList);
if (!r.first)
{
qWarning()
<< " No exact match found. (Only possible if bug in wikionboard)";
}
zim::File::const_iterator it = r.second;
if (it == zimFileWrapper->end())
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< " Current entry is last entry in index => Do nothing";
#endif
return 0;
}
int insertedItemsCount = 0;
while (insertedItemsCount < addCount)
{
++it;
std::pair <bool, QListWidgetItem*> articleItemPair = getArticleListItem(it);
if (!articleItemPair.first) {
break;
}
addItem(articleItemPair.second);
//Remove first item to avoid eating up to much memory.
//TODO: increase overlap. (User scrolls one direction than other else leads directly to reload)
if (count()>maxCount) {
QListWidgetItem *firstItem =
takeItem(0);
delete firstItem;
}
insertedItemsCount++;
if (it == zimFileWrapper->end())
{
#ifdef DEBUG_INDEXLIST
qDebug()
<< "End of title index reached. Stop adding titles. Last added title: "<< articleListItemToString(articleItemPair.second);
#endif
break;
}
} //End while
int indexFirstNewItem = count()-insertedItemsCount;
if ((indexFirstNewItem >= 0) && (indexFirstNewItem
< count()))
{
QListWidgetItem *firstNewItem = item(
indexFirstNewItem);
#ifdef DEBUG_INDEXLIST
qDebug() << insertedItemsCount
<< " items appended to end of list. Scroll so that firstly newly added article is at bottom of list. Firstly new added article: "<<articleListItemToString(firstNewItem);
#endif
scrollToItem(firstNewItem,
QAbstractItemView::PositionAtBottom);
return insertedItemsCount;
} else {
#ifdef DEBUG_INDEXLIST
qDebug() << "No items inserted";
#endif
return 0;
}
} // End else (up=false)
} //End try
catch (const std::exception& e)
{
addItem(QLatin1String("Error occured"));
}
} //End if (zimFile!=NULL)
return 0;
}
QUrl IndexList::currentItemUrl() {
QListWidgetItem *item = currentItem();
if (item != NULL)
{
QUrl url = item->data(ArticleUrlRole).toUrl();
return url;
}
else {
return QUrl();
}
}
void IndexList::resizeEvent(QResizeEvent * event)
{
#ifdef DEBUG_INDEXLIST
qDebug() << "resizeEvent:\n "
"New size: width: " << event->size().width() <<" height: " << event->size().height() << ""
"Old size: width: " << event->oldSize().width() <<" height: " << event->oldSize().height();
qDebug() << " indexList: width: " << this->width() << " height:" << this->height();
#endif DEBUG_INDEXLIST
if (count() > 0)
{
//Current item (if none first) is new first item of list.
// TODO: Keeping offset would be nicer, but more complex
// in case new size is smaller than offset.
int itemIndex = currentRow();
if (itemIndex < 0) {
itemIndex = 0;
}
if (item(itemIndex)->data(ArticleIndexRole).toInt() > 0)
{
populateArticleList(item(itemIndex)->data(ArticleTitleRole).toString(), 0,
false);
//indexList->setCurrentRow(0);
}
}
}