forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
articleview.cc
2725 lines (2236 loc) · 77.8 KB
/
articleview.cc
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This file is (c) 2008-2012 Konstantin Isakov <[email protected]>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "articleview.hh"
#include "externalviewer.hh"
#include <map>
#include <QMessageBox>
#include <QWebHitTestResult>
#include <QMenu>
#include <QDesktopServices>
#include <QWebHistory>
#include <QClipboard>
#include <QKeyEvent>
#include <QFileDialog>
#include "folding.hh"
#include "wstring_qt.hh"
#include "webmultimediadownload.hh"
#include "programs.hh"
#include "gddebug.hh"
#include "ffmpegaudio.hh"
#include <QDebug>
#include <QCryptographicHash>
#include "gestures.hh"
#include "fulltextsearch.hh"
#if QT_VERSION >= 0x040600
#include <QWebElement>
#include <QWebElementCollection>
#endif
#include "qt4x5.hh"
#include <assert.h>
#ifdef Q_OS_WIN32
#include <windows.h>
#include <QPainter>
#endif
#include <QBuffer>
#if defined( Q_OS_WIN32 ) || defined( Q_OS_MAC )
#include "speechclient.hh"
#endif
using std::map;
using std::list;
/// AccentMarkHandler class
///
/// Remove accent marks from text
/// and mirror position in normalized text to original text
class AccentMarkHandler
{
QString normalizedString;
QVector< int > accentMarkPos;
public:
static QChar accentMark()
{ return QChar( 0x301 ); }
/// Create text without accent marks
/// and store mark positions
void setText( QString const & baseString )
{
accentMarkPos.clear();
normalizedString.clear();
int pos = 0;
QChar mark = accentMark();
for( int x = 0; x < baseString.length(); x++ )
{
if( baseString.at( x ) == mark )
{
accentMarkPos.append( pos );
continue;
}
normalizedString.append( baseString.at( x ) );
pos++;
}
}
/// Return text without accent marks
QString const & normalizedText() const
{ return normalizedString; }
/// Convert position into position in original text
int mirrorPosition( int const & pos ) const
{
int newPos = pos;
for( int x = 0; x < accentMarkPos.size(); x++ )
{
if( accentMarkPos.at( x ) < pos )
newPos++;
else
break;
}
return newPos;
}
};
/// End of DslAccentMark class
static QVariant evaluateJavaScriptVariableSafe( QWebFrame * frame, const QString & variable )
{
return frame->evaluateJavaScript(
QString( "( typeof( %1 ) !== 'undefined' && %1 !== undefined ) ? %1 : null;" )
.arg( variable ) );
}
ArticleView::ArticleView( QWidget * parent, ArticleNetworkAccessManager & nm,
std::vector< sptr< Dictionary::Class > > const & allDictionaries_,
Instances::Groups const & groups_, bool popupView_,
Config::Class const & cfg_,
QAction & openSearchAction_,
QAction * dictionaryBarToggled_,
GroupComboBox const * groupComboBox_ ):
QFrame( parent ),
articleNetMgr( nm ),
allDictionaries( allDictionaries_ ),
groups( groups_ ),
popupView( popupView_ ),
cfg( cfg_ ),
pasteAction( this ),
articleUpAction( this ),
articleDownAction( this ),
goBackAction( this ),
goForwardAction( this ),
selectCurrentArticleAction( this ),
copyAsTextAction( this ),
inspectAction( this ),
openSearchAction( openSearchAction_ ),
searchIsOpened( false ),
dictionaryBarToggled( dictionaryBarToggled_ ),
groupComboBox( groupComboBox_ ),
ftsSearchIsOpened( false ),
ftsSearchMatchCase( false ),
ftsPosition( 0 )
{
ui.setupUi( this );
ui.definition->setUp( const_cast< Config::Class * >( &cfg ) );
goBackAction.setShortcut( QKeySequence( "Alt+Left" ) );
ui.definition->addAction( &goBackAction );
connect( &goBackAction, SIGNAL( triggered() ),
this, SLOT( back() ) );
goForwardAction.setShortcut( QKeySequence( "Alt+Right" ) );
ui.definition->addAction( &goForwardAction );
connect( &goForwardAction, SIGNAL( triggered() ),
this, SLOT( forward() ) );
ui.definition->pageAction( QWebPage::Copy )->setShortcut( QKeySequence::Copy );
ui.definition->addAction( ui.definition->pageAction( QWebPage::Copy ) );
QAction * selectAll = ui.definition->pageAction( QWebPage::SelectAll );
selectAll->setShortcut( QKeySequence::SelectAll );
selectAll->setShortcutContext( Qt::WidgetWithChildrenShortcut );
ui.definition->addAction( selectAll );
ui.definition->setContextMenuPolicy( Qt::CustomContextMenu );
ui.definition->page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks );
ui.definition->page()->setNetworkAccessManager( &articleNetMgr );
connect( ui.definition, SIGNAL( loadFinished( bool ) ),
this, SLOT( loadFinished( bool ) ) );
attachToJavaScript();
connect( ui.definition->page()->mainFrame(), SIGNAL( javaScriptWindowObjectCleared() ),
this, SLOT( attachToJavaScript() ) );
connect( ui.definition, SIGNAL( titleChanged( QString const & ) ),
this, SLOT( handleTitleChanged( QString const & ) ) );
connect( ui.definition, SIGNAL( urlChanged( QUrl const & ) ),
this, SLOT( handleUrlChanged( QUrl const & ) ) );
connect( ui.definition, SIGNAL( customContextMenuRequested( QPoint const & ) ),
this, SLOT( contextMenuRequested( QPoint const & ) ) );
connect( ui.definition, SIGNAL( linkClicked( QUrl const & ) ),
this, SLOT( linkClicked( QUrl const & ) ) );
connect( ui.definition->page(), SIGNAL( linkHovered ( const QString &, const QString &, const QString & ) ),
this, SLOT( linkHovered ( const QString &, const QString &, const QString & ) ) );
connect( ui.definition, SIGNAL(doubleClicked()),this,SLOT(doubleClicked()) );
pasteAction.setShortcut( QKeySequence::Paste );
ui.definition->addAction( &pasteAction );
connect( &pasteAction, SIGNAL( triggered() ), this, SLOT( pasteTriggered() ) );
articleUpAction.setShortcut( QKeySequence( "Alt+Up" ) );
ui.definition->addAction( &articleUpAction );
connect( &articleUpAction, SIGNAL( triggered() ), this, SLOT( moveOneArticleUp() ) );
articleDownAction.setShortcut( QKeySequence( "Alt+Down" ) );
ui.definition->addAction( &articleDownAction );
connect( &articleDownAction, SIGNAL( triggered() ), this, SLOT( moveOneArticleDown() ) );
ui.definition->addAction( &openSearchAction );
connect( &openSearchAction, SIGNAL( triggered() ), this, SLOT( openSearch() ) );
selectCurrentArticleAction.setShortcut( QKeySequence( "Ctrl+Shift+A" ));
selectCurrentArticleAction.setText( tr( "Select Current Article" ) );
ui.definition->addAction( &selectCurrentArticleAction );
connect( &selectCurrentArticleAction, SIGNAL( triggered() ),
this, SLOT( selectCurrentArticle() ) );
copyAsTextAction.setShortcut( QKeySequence( "Ctrl+Shift+C" ) );
copyAsTextAction.setText( tr( "Copy as text" ) );
ui.definition->addAction( ©AsTextAction );
connect( ©AsTextAction, SIGNAL( triggered() ),
this, SLOT( copyAsText() ) );
inspectAction.setShortcut( QKeySequence( Qt::Key_F12 ) );
inspectAction.setText( tr( "Inspect" ) );
ui.definition->addAction( &inspectAction );
connect( &inspectAction, SIGNAL( triggered() ), this, SLOT( inspect() ) );
ui.definition->installEventFilter( this );
ui.searchFrame->installEventFilter( this );
ui.ftsSearchFrame->installEventFilter( this );
// Load the default blank page instantly, so there would be no flicker.
QString contentType;
QUrl blankPage( "gdlookup://localhost?blank=1" );
sptr< Dictionary::DataRequest > r = articleNetMgr.getResource( blankPage,
contentType );
ui.definition->setHtml( QString::fromUtf8( &( r->getFullData().front() ),
r->getFullData().size() ),
blankPage );
expandOptionalParts = cfg.preferences.alwaysExpandOptionalParts;
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
ui.definition->grabGesture( Gestures::GDPinchGestureType );
ui.definition->grabGesture( Gestures::GDSwipeGestureType );
#endif
// Variable name for store current selection range
rangeVarName = QString( "sr_%1" ).arg( QString::number( (quint64)this, 16 ) );
}
// explicitly report the minimum size, to avoid
// sidebar widgets' improper resize during restore
QSize ArticleView::minimumSizeHint() const
{
return ui.searchFrame->minimumSizeHint();
}
void ArticleView::setGroupComboBox( GroupComboBox const * g )
{
groupComboBox = g;
}
ArticleView::~ArticleView()
{
cleanupTemp();
#ifndef DISABLE_INTERNAL_PLAYER
if ( cfg.preferences.useInternalPlayer )
Ffmpeg::AudioPlayer::instance().stop();
#endif
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
ui.definition->ungrabGesture( Gestures::GDPinchGestureType );
ui.definition->ungrabGesture( Gestures::GDSwipeGestureType );
#endif
}
void ArticleView::showDefinition( QString const & word, unsigned group,
QString const & scrollTo,
Contexts const & contexts_ )
{
#ifndef DISABLE_INTERNAL_PLAYER
// first, let's stop the player
if ( cfg.preferences.useInternalPlayer )
Ffmpeg::AudioPlayer::instance().stop();
#endif
QUrl req;
Contexts contexts( contexts_ );
req.setScheme( "gdlookup" );
req.setHost( "localhost" );
Qt4x5::Url::addQueryItem( req, "word", word );
Qt4x5::Url::addQueryItem( req, "group", QString::number( group ) );
if ( scrollTo.size() )
Qt4x5::Url::addQueryItem( req, "scrollto", scrollTo );
Contexts::Iterator pos = contexts.find( "gdanchor" );
if( pos != contexts.end() )
{
Qt4x5::Url::addQueryItem( req, "gdanchor", contexts[ "gdanchor" ] );
contexts.erase( pos );
}
if ( contexts.size() )
{
QBuffer buf;
buf.open( QIODevice::WriteOnly );
QDataStream stream( &buf );
stream << contexts;
buf.close();
Qt4x5::Url::addQueryItem( req, "contexts", QString::fromLatin1( buf.buffer().toBase64() ) );
}
QString mutedDicts = getMutedForGroup( group );
if ( mutedDicts.size() )
Qt4x5::Url::addQueryItem( req, "muted", mutedDicts );
// Update both histories (pages history and headwords history)
saveHistoryUserData();
emit sendWordToHistory( word );
// Any search opened is probably irrelevant now
closeSearch();
// Clear highlight all button selection
ui.highlightAllButton->setChecked(false);
emit setExpandMode( expandOptionalParts );
ui.definition->load( req );
//QApplication::setOverrideCursor( Qt::WaitCursor );
ui.definition->setCursor( Qt::WaitCursor );
}
void ArticleView::showDefinition( QString const & word, QStringList const & dictIDs,
QRegExp const & searchRegExp, unsigned group )
{
if( dictIDs.isEmpty() )
return;
#ifndef DISABLE_INTERNAL_PLAYER
// first, let's stop the player
if ( cfg.preferences.useInternalPlayer )
Ffmpeg::AudioPlayer::instance().stop();
#endif
QUrl req;
req.setScheme( "gdlookup" );
req.setHost( "localhost" );
Qt4x5::Url::addQueryItem( req, "word", word );
Qt4x5::Url::addQueryItem( req, "dictionaries", dictIDs.join( ",") );
Qt4x5::Url::addQueryItem( req, "regexp", searchRegExp.pattern() );
if( searchRegExp.caseSensitivity() == Qt::CaseSensitive )
Qt4x5::Url::addQueryItem( req, "matchcase", "1" );
if( searchRegExp.patternSyntax() == QRegExp::WildcardUnix )
Qt4x5::Url::addQueryItem( req, "wildcards", "1" );
Qt4x5::Url::addQueryItem( req, "group", QString::number( group ) );
// Update both histories (pages history and headwords history)
saveHistoryUserData();
emit sendWordToHistory( word );
// Any search opened is probably irrelevant now
closeSearch();
// Clear highlight all button selection
ui.highlightAllButton->setChecked(false);
emit setExpandMode( expandOptionalParts );
ui.definition->load( req );
//QApplication::setOverrideCursor( Qt::WaitCursor );
ui.definition->setCursor( Qt::WaitCursor );
}
void ArticleView::showAnticipation()
{
ui.definition->setHtml( "" );
ui.definition->setCursor( Qt::WaitCursor );
//QApplication::setOverrideCursor( Qt::WaitCursor );
}
void ArticleView::loadFinished( bool )
{
QUrl url = ui.definition->url();
// See if we have any iframes in need of expansion
QList< QWebFrame * > frames = ui.definition->page()->mainFrame()->childFrames();
bool wereFrames = false;
for( QList< QWebFrame * >::iterator i = frames.begin(); i != frames.end(); ++i )
{
if ( (*i)->frameName().startsWith( "gdexpandframe-" ) )
{
//DPRINTF( "Name: %s\n", (*i)->frameName().toUtf8().data() );
//DPRINTF( "Size: %d\n", (*i)->contentsSize().height() );
//DPRINTF( ">>>>>>>>Height = %s\n", (*i)->evaluateJavaScript( "document.body.offsetHeight;" ).toString().toUtf8().data() );
// Set the height
ui.definition->page()->mainFrame()->evaluateJavaScript( QString( "document.getElementById('%1').height = %2;" ).
arg( (*i)->frameName() ).
arg( (*i)->contentsSize().height() ) );
// Show it
ui.definition->page()->mainFrame()->evaluateJavaScript( QString( "document.getElementById('%1').style.display = 'block';" ).
arg( (*i)->frameName() ) );
(*i)->evaluateJavaScript( "var gdLastUrlText;" );
(*i)->evaluateJavaScript( "document.addEventListener( 'click', function() { gdLastUrlText = window.event.srcElement.textContent; }, true );" );
(*i)->evaluateJavaScript( "document.addEventListener( 'contextmenu', function() { gdLastUrlText = window.event.srcElement.textContent; }, true );" );
wereFrames = true;
}
}
if ( wereFrames )
{
// There's some sort of glitch -- sometimes you need to move a mouse
QMouseEvent ev( QEvent::MouseMove, QPoint(), Qt::MouseButton(), 0, 0 );
qApp->sendEvent( ui.definition, &ev );
}
QVariant userDataVariant = ui.definition->history()->currentItem().userData();
if ( userDataVariant.type() == QVariant::Map )
{
QMap< QString, QVariant > userData = userDataVariant.toMap();
QString currentArticle = userData.value( "currentArticle" ).toString();
if ( currentArticle.size() )
{
// There's an active article saved, so set it to be active.
setCurrentArticle( currentArticle );
}
double sx = 0, sy = 0;
if ( userData.value( "sx" ).type() == QVariant::Double )
sx = userData.value( "sx" ).toDouble();
if ( userData.value( "sy" ).type() == QVariant::Double )
sy = userData.value( "sy" ).toDouble();
if ( sx != 0 || sy != 0 )
{
// Restore scroll position
ui.definition->page()->mainFrame()->evaluateJavaScript(
QString( "window.scroll( %1, %2 );" ).arg( sx ).arg( sy ) );
}
}
else
if ( Qt4x5::Url::queryItemValue( url, "scrollto" ).startsWith( "gdfrom-" ) )
{
// There is no active article saved in history, but we have it as a parameter.
// setCurrentArticle will save it and scroll there.
setCurrentArticle( Qt4x5::Url::queryItemValue( url, "scrollto" ), true );
}
ui.definition->unsetCursor();
//QApplication::restoreOverrideCursor();
// Expand collapsed article if only one loaded
ui.definition->page()->mainFrame()->evaluateJavaScript( QString( "gdCheckArticlesNumber();" ) );
// Jump to current article after page reloading
if( !articleToJump.isEmpty() )
{
setCurrentArticle( articleToJump, true );
articleToJump.clear();
}
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
if( !Qt4x5::Url::queryItemValue( url, "gdanchor" ).isEmpty() )
{
QString anchor = QUrl::fromPercentEncoding( Qt4x5::Url::encodedQueryItemValue( url, "gdanchor" ) );
// Find GD anchor on page
int n = anchor.indexOf( '_' );
if( n == 33 )
// MDict pattern: ("g" + dictionary ID (33 chars total))_(articleID(quint64, hex))_(original anchor)
n = anchor.indexOf( '_', n + 1 );
else
n = 0;
if( n > 0 )
{
QString originalAnchor = anchor.mid( n + 1 );
QRegExp rx;
rx.setMinimal( true );
rx.setPattern( anchor.left( 34 ) + "[0-9a-f]*_" + originalAnchor );
QWebElementCollection coll = ui.definition->page()->mainFrame()->findAllElements( "a[name]" );
coll += ui.definition->page()->mainFrame()->findAllElements( "a[id]" );
for( QWebElementCollection::iterator it = coll.begin(); it != coll.end(); ++it )
{
QString name = (*it).attribute( "name" );
QString id = (*it).attribute( "id" );
if( ( !name.isEmpty() && rx.indexIn( name ) >= 0 )
|| ( !id.isEmpty() && rx.indexIn( id ) >= 0 ))
{
// Anchor found, jump to it
url.clear();
url.setFragment( rx.cap( 0 ) );
ui.definition->page()->mainFrame()->evaluateJavaScript(
QString( "window.location.hash = \"%1\"" ).arg( QString::fromUtf8( url.toEncoded() ) ) );
break;
}
}
}
else
{
url.clear();
url.setFragment( anchor );
ui.definition->page()->mainFrame()->evaluateJavaScript(
QString( "window.location.hash = \"%1\"" ).arg( QString::fromUtf8( url.toEncoded() ) ) );
}
}
#endif
emit pageLoaded( this );
if( Qt4x5::Url::hasQueryItem( ui.definition->url(), "regexp" ) )
highlightFTSResults();
}
void ArticleView::handleTitleChanged( QString const & title )
{
if( !title.isEmpty() ) // Qt 5.x WebKit raise signal titleChanges(QString()) while navigation within page
emit titleChanged( this, title );
}
void ArticleView::handleUrlChanged( QUrl const & url )
{
QIcon icon;
unsigned group = getGroup( url );
if ( group )
{
// Find the group's instance corresponding to the fragment value
for( unsigned x = 0; x < groups.size(); ++x )
if ( groups[ x ].id == group )
{
// Found it
icon = groups[ x ].makeIcon();
break;
}
}
emit iconChanged( this, icon );
}
unsigned ArticleView::getGroup( QUrl const & url )
{
if ( url.scheme() == "gdlookup" && Qt4x5::Url::hasQueryItem( url, "group" ) )
return Qt4x5::Url::queryItemValue( url, "group" ).toUInt();
return 0;
}
QStringList ArticleView::getArticlesList()
{
return evaluateJavaScriptVariableSafe( ui.definition->page()->mainFrame(), "gdArticleContents" )
.toString().trimmed().split( ' ', QString::SkipEmptyParts );
}
QString ArticleView::getActiveArticleId()
{
QString currentArticle = getCurrentArticle();
if ( !currentArticle.startsWith( "gdfrom-" ) )
return QString(); // Incorrect id
return currentArticle.mid( 7 );
}
QString ArticleView::getCurrentArticle()
{
QVariant v = evaluateJavaScriptVariableSafe( ui.definition->page()->mainFrame(), "gdCurrentArticle" );
if ( v.type() == QVariant::String )
return v.toString();
else
return QString();
}
void ArticleView::jumpToDictionary( QString const & id, bool force )
{
QString targetArticle = "gdfrom-" + id;
// jump only if neceessary, or when forced
if ( force || targetArticle != getCurrentArticle() )
{
setCurrentArticle( targetArticle, true );
}
}
void ArticleView::setCurrentArticle( QString const & id, bool moveToIt )
{
if ( !id.startsWith( "gdfrom-" ) )
return; // Incorrect id
if ( !ui.definition->isVisible() )
return; // No action on background page, scrollIntoView there don't work
if ( getArticlesList().contains( id.mid( 7 ) ) )
{
if ( moveToIt )
ui.definition->page()->mainFrame()->evaluateJavaScript( QString( "document.getElementById('%1').scrollIntoView(true);" ).arg( id ) );
QMap< QString, QVariant > userData = ui.definition->history()->
currentItem().userData().toMap();
userData[ "currentArticle" ] = id;
ui.definition->history()->currentItem().setUserData( userData );
ui.definition->page()->mainFrame()->evaluateJavaScript(
QString( "gdMakeArticleActive( '%1' );" ).arg( id.mid( 7 ) ) );
}
}
void ArticleView::selectCurrentArticle()
{
ui.definition->page()->mainFrame()->evaluateJavaScript(
QString( "gdSelectArticle( '%1' );" ).arg( getActiveArticleId() ) );
}
bool ArticleView::isFramedArticle( QString const & ca )
{
if ( ca.isEmpty() )
return false;
return ui.definition->page()->mainFrame()->
evaluateJavaScript( QString( "!!document.getElementById('gdexpandframe-%1');" ).arg( ca.mid( 7 ) ) ).toBool();
}
bool ArticleView::isExternalLink( QUrl const & url )
{
return url.scheme() == "http" || url.scheme() == "https" ||
url.scheme() == "ftp" || url.scheme() == "mailto" ||
url.scheme() == "file";
}
void ArticleView::tryMangleWebsiteClickedUrl( QUrl & url, Contexts & contexts )
{
// Don't try mangling audio urls, even if they are from the framed websites
if( ( url.scheme() == "http" || url.scheme() == "https" )
&& ! Dictionary::WebMultimediaDownload::isAudioUrl( url ) )
{
// Maybe a link inside a website was clicked?
QString ca = getCurrentArticle();
if ( isFramedArticle( ca ) )
{
QVariant result = evaluateJavaScriptVariableSafe( ui.definition->page()->currentFrame(), "gdLastUrlText" );
if ( result.type() == QVariant::String )
{
// Looks this way
contexts[ ca.mid( 7 ) ] = QString::fromLatin1( url.toEncoded() );
QUrl target;
QString queryWord = result.toString();
// Empty requests are treated as no request, so we work this around by
// adding a space.
if ( queryWord.isEmpty() )
queryWord = " ";
target.setScheme( "gdlookup" );
target.setHost( "localhost" );
target.setPath( "/" + queryWord );
url = target;
}
}
}
}
void ArticleView::updateCurrentArticleFromCurrentFrame( QWebFrame * frame )
{
if ( !frame )
frame = ui.definition->page()->currentFrame();
for( ; frame; frame = frame->parentFrame() )
{
QString frameName = frame->frameName();
if ( frameName.startsWith( "gdexpandframe-" ) )
{
QString newCurrent = "gdfrom-" + frameName.mid( 14 );
if ( getCurrentArticle() != newCurrent )
setCurrentArticle( newCurrent, false );
break;
}
}
}
void ArticleView::saveHistoryUserData()
{
QMap< QString, QVariant > userData = ui.definition->history()->
currentItem().userData().toMap();
// Save current article, which can be empty
userData[ "currentArticle" ] = getCurrentArticle();
// We also save window position. We restore it when the page is fully loaded,
// when any hidden frames are expanded.
userData[ "sx" ] = ui.definition->page()->mainFrame()->evaluateJavaScript( "window.scrollX;" ).toDouble();
userData[ "sy" ] = ui.definition->page()->mainFrame()->evaluateJavaScript( "window.scrollY;" ).toDouble();
ui.definition->history()->currentItem().setUserData( userData );
}
void ArticleView::cleanupTemp()
{
if ( desktopOpenedTempFile.size() )
{
QFile( desktopOpenedTempFile ).remove();
desktopOpenedTempFile.clear();
}
}
bool ArticleView::handleF3( QObject * /*obj*/, QEvent * ev )
{
if ( ev->type() == QEvent::ShortcutOverride
|| ev->type() == QEvent::KeyPress )
{
QKeyEvent * ke = static_cast<QKeyEvent *>( ev );
if ( ke->key() == Qt::Key_F3 && isSearchOpened() ) {
if ( !ke->modifiers() )
{
if( ev->type() == QEvent::KeyPress )
on_searchNext_clicked();
ev->accept();
return true;
}
if ( ke->modifiers() == Qt::ShiftModifier )
{
if( ev->type() == QEvent::KeyPress )
on_searchPrevious_clicked();
ev->accept();
return true;
}
}
if ( ke->key() == Qt::Key_F3 && ftsSearchIsOpened )
{
if ( !ke->modifiers() )
{
if( ev->type() == QEvent::KeyPress )
on_ftsSearchNext_clicked();
ev->accept();
return true;
}
if ( ke->modifiers() == Qt::ShiftModifier )
{
if( ev->type() == QEvent::KeyPress )
on_ftsSearchPrevious_clicked();
ev->accept();
return true;
}
}
}
return false;
}
bool ArticleView::eventFilter( QObject * obj, QEvent * ev )
{
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
if( ev->type() == QEvent::Gesture )
{
Gestures::GestureResult result;
QPoint pt;
bool handled = Gestures::handleGestureEvent( obj, ev, result, pt );
if( handled )
{
if( result == Gestures::ZOOM_IN )
zoomIn();
else
if( result == Gestures::ZOOM_OUT )
zoomOut();
else
if( result == Gestures::SWIPE_LEFT )
back();
else
if( result == Gestures::SWIPE_RIGHT )
forward();
else
if( result == Gestures::SWIPE_UP || result == Gestures::SWIPE_DOWN )
{
int delta = result == Gestures::SWIPE_UP ? -120 : 120;
QWidget *widget = static_cast< QWidget * >( obj );
QWidget *child = widget->childAt( widget->mapFromGlobal( pt ) );
if( child )
{
QWheelEvent whev( child->mapFromGlobal( pt ), pt, delta, Qt::NoButton, Qt::NoModifier );
qApp->sendEvent( child, &whev );
}
else
{
QWheelEvent whev( widget->mapFromGlobal( pt ), pt, delta, Qt::NoButton, Qt::NoModifier );
qApp->sendEvent( widget, &whev );
}
}
}
return handled;
}
if( ev->type() == QEvent::MouseMove )
{
if( Gestures::isFewTouchPointsPresented() )
{
ev->accept();
return true;
}
}
#endif
if ( handleF3( obj, ev ) )
{
return true;
}
if ( obj == ui.definition )
{
if ( ev->type() == QEvent::MouseButtonPress ) {
QMouseEvent * event = static_cast< QMouseEvent * >( ev );
if ( event->button() == Qt::XButton1 ) {
back();
return true;
}
if ( event->button() == Qt::XButton2 ) {
forward();
return true;
}
}
else
if ( ev->type() == QEvent::KeyPress )
{
QKeyEvent * keyEvent = static_cast< QKeyEvent * >( ev );
if ( keyEvent->modifiers() &
( Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier ) )
return false; // A non-typing modifier is pressed
if ( keyEvent->key() == Qt::Key_Space ||
keyEvent->key() == Qt::Key_Backspace ||
keyEvent->key() == Qt::Key_Tab ||
keyEvent->key() == Qt::Key_Backtab ||
keyEvent->key() == Qt::Key_Return ||
keyEvent->key() == Qt::Key_Enter )
return false; // Those key have other uses than to start typing
QString text = keyEvent->text();
if ( text.size() )
{
emit typingEvent( text );
return true;
}
}
}
else
return QFrame::eventFilter( obj, ev );
return false;
}
QString ArticleView::getMutedForGroup( unsigned group )
{
if ( dictionaryBarToggled && dictionaryBarToggled->isChecked() )
{
// Dictionary bar is active -- mute the muted dictionaries
Instances::Group const * groupInstance = groups.findGroup( group );
// Find muted dictionaries for current group
Config::Group const * grp = cfg.getGroup( group );
Config::MutedDictionaries const * mutedDictionaries;
if( group == Instances::Group::AllGroupId )
mutedDictionaries = popupView ? &cfg.popupMutedDictionaries : &cfg.mutedDictionaries;
else
mutedDictionaries = grp ? ( popupView ? &grp->popupMutedDictionaries : &grp->mutedDictionaries ) : 0;
if( !mutedDictionaries )
return QString();
QStringList mutedDicts;
if ( groupInstance )
{
for( unsigned x = 0; x < groupInstance->dictionaries.size(); ++x )
{
QString id = QString::fromStdString(
groupInstance->dictionaries[ x ]->getId() );
if ( mutedDictionaries->contains( id ) )
mutedDicts.append( id );
}
}
if ( mutedDicts.size() )
return mutedDicts.join( "," );
}
return QString();
}
void ArticleView::linkHovered ( const QString & link, const QString & , const QString & )
{
QString msg;
QUrl url(link);
if ( url.scheme() == "bres" )
{
msg = tr( "Resource" );
}
else
if ( url.scheme() == "gdau" || Dictionary::WebMultimediaDownload::isAudioUrl( url ) )
{
msg = tr( "Audio" );
}
else
if ( url.scheme() == "gdtts" )
{
msg = tr( "TTS Voice" );
}
else
if ( url.scheme() == "gdpicture" )
{
msg = tr( "Picture" );
}
else
if ( url.scheme() == "gdvideo" )
{
if ( url.path().isEmpty() )
{
msg = tr( "Video" );
}
else
{
QString path = url.path();
if ( path.startsWith( '/' ) )
{
path = path.mid( 1 );
}
msg = tr( "Video: %1" ).arg( path );
}
}
else
if (url.scheme() == "gdlookup" || url.scheme().compare( "bword" ) == 0)
{
QString def = url.path();
if (def.startsWith("/"))
{
def = def.mid( 1 );
}
if( Qt4x5::Url::hasQueryItem( url, "dict" ) )
{