forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanpopup.cc
1065 lines (860 loc) · 28.7 KB
/
scanpopup.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 "scanpopup.hh"
#include "folding.hh"
#include "wstring_qt.hh"
#include <QCursor>
#include <QPixmap>
#include <QBitmap>
#include <QMenu>
#include <QMouseEvent>
#include <QDesktopWidget>
#include "gddebug.hh"
#include "gestures.hh"
#ifdef Q_OS_MAC
#include "macmouseover.hh"
#define MouseOver MacMouseOver
#else
#include "mouseover.hh"
#endif
using std::wstring;
/// We use different window flags under Windows and X11 due to slight differences
/// in their behavior on those platforms.
static Qt::WindowFlags popupWindowFlags =
#if defined (Q_OS_WIN) || ( defined (Q_OS_MAC) && QT_VERSION < QT_VERSION_CHECK( 5, 3, 0 ) )
Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint
#else
Qt::Popup
#endif
;
ScanPopup::ScanPopup( QWidget * parent,
Config::Class & cfg_,
ArticleNetworkAccessManager & articleNetMgr,
std::vector< sptr< Dictionary::Class > > const & allDictionaries_,
Instances::Groups const & groups_,
History & history_ ):
QMainWindow( parent ),
cfg( cfg_ ),
isScanningEnabled( false ),
allDictionaries( allDictionaries_ ),
groups( groups_ ),
history( history_ ),
escapeAction( this ),
switchExpandModeAction( this ),
focusTranslateLineAction( this ),
openSearchAction( this ),
wordFinder( this ),
dictionaryBar( this, configEvents, cfg.editDictionaryCommandLine, cfg.preferences.maxDictionaryRefsInContextMenu ),
mouseEnteredOnce( false ),
mouseIntercepted( false ),
hideTimer( this )
{
ui.setupUi( this );
openSearchAction.setShortcut( QKeySequence( "Ctrl+F" ) );
if( layoutDirection() == Qt::RightToLeft )
{
// Adjust button icons for Right-To-Left layout
ui.goBackButton->setIcon( QIcon( ":/icons/next.png" ) );
ui.goForwardButton->setIcon( QIcon( ":/icons/previous.png" ) );
}
mainStatusBar = new MainStatusBar( this );
ui.queryError->hide();
definition = new ArticleView( ui.outerFrame, articleNetMgr, allDictionaries,
groups, true, cfg,
openSearchAction,
dictionaryBar.toggleViewAction()
);
connect( this, SIGNAL(switchExpandMode() ),
definition, SLOT( switchExpandOptionalParts() ) );
connect( this, SIGNAL(setViewExpandMode( bool ) ),
definition, SLOT( receiveExpandOptionalParts( bool ) ) );
connect( definition, SIGNAL( setExpandMode( bool ) ),
this, SIGNAL( setExpandMode( bool ) ) );
connect( definition, SIGNAL( forceAddWordToHistory( QString ) ),
this, SIGNAL( forceAddWordToHistory( QString ) ) );
connect( this, SIGNAL( closeMenu() ),
definition, SIGNAL( closePopupMenu() ) );
connect( definition, SIGNAL( sendWordToHistory( QString ) ),
this, SIGNAL( sendWordToHistory( QString ) ) );
connect( definition, SIGNAL( typingEvent( QString const & ) ),
this, SLOT( typingEvent( QString const & ) ) );
applyZoomFactor();
ui.mainLayout->addWidget( definition );
ui.translateBox->wordList()->attachFinder( &wordFinder );
ui.translateBox->wordList()->setFocusPolicy(Qt::ClickFocus);
ui.translateBox->translateLine()->installEventFilter( this );
connect( ui.translateBox->translateLine(), SIGNAL( textChanged( QString const & ) ),
this, SLOT( translateInputChanged( QString const & ) ) );
connect( ui.translateBox->translateLine(), SIGNAL( returnPressed() ),
this, SLOT( translateInputFinished() ) );
connect( ui.translateBox->wordList(), SIGNAL( itemClicked( QListWidgetItem * ) ),
this, SLOT( wordListItemActivated( QListWidgetItem * ) ) );
connect( ui.translateBox->wordList(), SIGNAL( itemDoubleClicked ( QListWidgetItem * ) ),
this, SLOT( wordListItemActivated( QListWidgetItem * ) ) );
connect( ui.translateBox->wordList(), SIGNAL( statusBarMessage( QString const &, int, QPixmap const & ) ),
this, SLOT( showStatusBarMessage( QString const &, int, QPixmap const & ) ) );
ui.pronounceButton->hide();
ui.groupList->fill( groups );
ui.groupList->setCurrentGroup( cfg.lastPopupGroupId );
dictionaryBar.setFloatable( false );
Instances::Group const * igrp = groups.findGroup( cfg.lastPopupGroupId );
if( cfg.lastPopupGroupId == Instances::Group::AllGroupId )
{
if( igrp )
igrp->checkMutedDictionaries( &cfg.popupMutedDictionaries );
dictionaryBar.setMutedDictionaries( &cfg.popupMutedDictionaries );
}
else
{
Config::Group * grp = cfg.getGroup( cfg.lastPopupGroupId );
if( igrp && grp )
igrp->checkMutedDictionaries( &grp->popupMutedDictionaries );
dictionaryBar.setMutedDictionaries( grp ? &grp->popupMutedDictionaries : 0 );
}
addToolBar( Qt::RightToolBarArea, &dictionaryBar );
connect( &dictionaryBar, SIGNAL(editGroupRequested()),
this, SLOT(editGroupRequested()) );
connect( this, SIGNAL( closeMenu() ),
&dictionaryBar, SIGNAL( closePopupMenu() ) );
connect( &dictionaryBar, SIGNAL( showDictionaryInfo( QString const & ) ),
this, SIGNAL( showDictionaryInfo( QString const & ) ) );
connect( &dictionaryBar, SIGNAL( openDictionaryFolder( QString const & ) ),
this, SIGNAL( openDictionaryFolder( QString const & ) ) );
if ( cfg.popupWindowGeometry.size() )
restoreGeometry( cfg.popupWindowGeometry );
if ( cfg.popupWindowState.size() )
restoreState( cfg.popupWindowState, 1 );
ui.pinButton->setChecked( cfg.pinPopupWindow );
if ( cfg.pinPopupWindow )
{
dictionaryBar.setMovable( true );
setWindowFlags( Qt::Dialog );
}
else
{
dictionaryBar.setMovable( false );
setWindowFlags( popupWindowFlags );
}
connect( &configEvents, SIGNAL( mutedDictionariesChanged() ),
this, SLOT( mutedDictionariesChanged() ) );
definition->focus();
#if 0 // Experimental code to give window a non-rectangular shape (i.e.
// balloon) using a colorkey mask.
QPixmap pixMask( size() );
render( &pixMask );
setMask( pixMask.createMaskFromColor( QColor( 255, 0, 0 ) ) );
// This helps against flickering
setAttribute( Qt::WA_NoSystemBackground );
#endif
escapeAction.setShortcut( QKeySequence( "Esc" ) );
addAction( &escapeAction );
connect( &escapeAction, SIGNAL( triggered() ),
this, SLOT( escapePressed() ) );
focusTranslateLineAction.setShortcutContext( Qt::WidgetWithChildrenShortcut );
addAction( &focusTranslateLineAction );
focusTranslateLineAction.setShortcuts( QList< QKeySequence >() <<
QKeySequence( "Alt+D" ) <<
QKeySequence( "Ctrl+L" ) );
connect( &focusTranslateLineAction, SIGNAL( triggered() ),
this, SLOT( focusTranslateLine() ) );
switchExpandModeAction.setShortcuts( QList< QKeySequence >() <<
QKeySequence( Qt::CTRL + Qt::Key_8 ) <<
QKeySequence( Qt::CTRL + Qt::Key_Asterisk ) <<
QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_8 ) );
addAction( &switchExpandModeAction );
connect( &switchExpandModeAction, SIGNAL( triggered() ),
this, SLOT(switchExpandOptionalPartsMode() ) );
connect( ui.groupList, SIGNAL( currentIndexChanged( QString const & ) ),
this, SLOT( currentGroupChanged( QString const & ) ) );
connect( &wordFinder, SIGNAL( finished() ),
this, SLOT( prefixMatchFinished() ) );
connect( ui.pinButton, SIGNAL( clicked( bool ) ),
this, SLOT( pinButtonClicked( bool ) ) );
connect( definition, SIGNAL( pageLoaded( ArticleView * ) ),
this, SLOT( pageLoaded( ArticleView * ) ) );
connect( definition, SIGNAL( statusBarMessage( QString const &, int, QPixmap const & ) ),
this, SLOT( showStatusBarMessage( QString const &, int, QPixmap const & ) ) );
#ifdef HAVE_X11
connect( QApplication::clipboard(), SIGNAL( changed( QClipboard::Mode ) ),
this, SLOT( clipboardChanged( QClipboard::Mode ) ) );
#else
if( cfg.preferences.trackClipboardChanges )
connect( QApplication::clipboard(), SIGNAL( changed( QClipboard::Mode ) ),
this, SLOT( clipboardChanged( QClipboard::Mode ) ) );
#endif
connect( &MouseOver::instance(), SIGNAL( hovered( QString const &, bool ) ),
this, SLOT( mouseHovered( QString const &, bool ) ) );
#ifdef Q_OS_WIN32
connect( &MouseOver::instance(), SIGNAL( isGoldenDictWindow( HWND ) ),
this, SIGNAL( isGoldenDictWindow( HWND ) ) );
#endif
hideTimer.setSingleShot( true );
hideTimer.setInterval( 400 );
connect( &hideTimer, SIGNAL( timeout() ),
this, SLOT( hideTimerExpired() ) );
altModeExpirationTimer.setSingleShot( true );
altModeExpirationTimer.setInterval( cfg.preferences.scanPopupAltModeSecs * 1000 );
connect( &altModeExpirationTimer, SIGNAL( timeout() ),
this, SLOT( altModeExpired() ) );
// This one polls constantly for modifiers while alt mode lasts
altModePollingTimer.setSingleShot( false );
altModePollingTimer.setInterval( 50 );
connect( &altModePollingTimer, SIGNAL( timeout() ),
this, SLOT( altModePoll() ) );
mouseGrabPollTimer.setSingleShot( false );
mouseGrabPollTimer.setInterval( 10 );
connect( &mouseGrabPollTimer, SIGNAL( timeout() ),
this, SLOT(mouseGrabPoll()) );
MouseOver::instance().setPreferencesPtr( &( cfg.preferences ) );
ui.goBackButton->setEnabled( false );
ui.goForwardButton->setEnabled( false );
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
grabGesture( Gestures::GDPinchGestureType );
grabGesture( Gestures::GDSwipeGestureType );
#endif
}
ScanPopup::~ScanPopup()
{
// Save state, geometry and pin status
cfg.popupWindowState = saveState( 1 );
cfg.popupWindowGeometry = saveGeometry();
cfg.pinPopupWindow = ui.pinButton->isChecked();
disableScanning();
#if QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)
ungrabGesture( Gestures::GDPinchGestureType );
ungrabGesture( Gestures::GDSwipeGestureType );
#endif
}
void ScanPopup::enableScanning()
{
if ( !isScanningEnabled )
{
isScanningEnabled = true;
MouseOver::instance().enableMouseOver();
}
}
void ScanPopup::disableScanning()
{
if ( isScanningEnabled )
{
MouseOver::instance().disableMouseOver();
isScanningEnabled = false;
}
}
void ScanPopup::applyZoomFactor()
{
definition->setZoomFactor( cfg.preferences.zoomFactor );
}
void ScanPopup::translateWordFromClipboard()
{
return translateWordFromClipboard(QClipboard::Clipboard);
}
void ScanPopup::translateWordFromSelection()
{
return translateWordFromClipboard(QClipboard::Selection);
}
void ScanPopup::editGroupRequested()
{
emit editGroupRequested( ui.groupList->getCurrentGroup() );
}
void ScanPopup::translateWordFromClipboard(QClipboard::Mode m)
{
GD_DPRINTF( "translating from clipboard or selection\n" );
QString subtype = "plain";
QString str = QApplication::clipboard()->text( subtype, m);
translateWord( str );
}
void ScanPopup::translateWord( QString const & word )
{
QString str = pendingInputWord = gd::toQString( Folding::trimWhitespaceOrPunct( gd::toWString( word ) ) ).simplified();
if ( !str.size() )
return; // Nothing there
// In case we had any timers engaged before, cancel them now.
altModePollingTimer.stop();
altModeExpirationTimer.stop();
inputWord = str;
engagePopup( false,
#ifdef Q_OS_WIN
true // We only focus popup under Windows when activated via Ctrl+C+C
// -- on Linux it already has an implicit focus
#else
false
#endif
);
}
void ScanPopup::clipboardChanged( QClipboard::Mode m )
{
if ( !isScanningEnabled )
return;
GD_DPRINTF( "clipboard changed\n" );
QString subtype = "plain";
handleInputWord( QApplication::clipboard()->text( subtype, m ) );
}
void ScanPopup::mouseHovered( QString const & str, bool forcePopup )
{
handleInputWord( str, forcePopup );
}
void ScanPopup::handleInputWord( QString const & str, bool forcePopup )
{
QString sanitizedStr = gd::toQString( Folding::trimWhitespaceOrPunct( gd::toWString( str ) ) );
if ( isVisible() && sanitizedStr == inputWord )
{
// Attempt to translate the same word we already have shown in scan popup.
// Ignore it, as it is probably a spurious mouseover event.
return;
}
pendingInputWord = sanitizedStr;
if ( !pendingInputWord.size() )
{
if ( cfg.preferences.scanPopupAltMode )
{
// In case we had any timers engaged before, cancel them now, since
// we're not going to translate anything anymore.
altModePollingTimer.stop();
altModeExpirationTimer.stop();
}
return;
}
// Check key modifiers
if ( cfg.preferences.enableScanPopupModifiers && !checkModifiersPressed( cfg.preferences.scanPopupModifiers ) )
{
if ( cfg.preferences.scanPopupAltMode )
{
altModePollingTimer.start();
altModeExpirationTimer.start();
}
return;
}
inputWord = pendingInputWord;
engagePopup( forcePopup );
}
void ScanPopup::engagePopup( bool forcePopup, bool giveFocus )
{
if( cfg.preferences.scanToMainWindow && !forcePopup )
{
// Send translated word to main window istead of show popup
emit sendWordToMainWindow( inputWord );
return;
}
definition->setSelectionBySingleClick( cfg.preferences.selectWordBySingleClick );
if ( !isVisible() )
{
// Need to show the window
if ( !ui.pinButton->isChecked() )
{
// Decide where should the window land
QPoint currentPos = QCursor::pos();
QRect desktop = QApplication::desktop()->screenGeometry();
QSize windowSize = geometry().size();
int x, y;
/// Try the to-the-right placement
if ( currentPos.x() + 4 + windowSize.width() <= desktop.topRight().x() )
x = currentPos.x() + 4;
else
/// Try the to-the-left placement
if ( currentPos.x() - 4 - windowSize.width() >= desktop.x() )
x = currentPos.x() - 4 - windowSize.width();
else
// Center it
x = desktop.x() + ( desktop.width() - windowSize.width() ) / 2;
/// Try the to-the-bottom placement
if ( currentPos.y() + 15 + windowSize.height() <= desktop.bottomLeft().y() )
y = currentPos.y() + 15;
else
/// Try the to-the-top placement
if ( currentPos.y() - 15 - windowSize.height() >= desktop.y() )
y = currentPos.y() - 15 - windowSize.height();
else
// Center it
y = desktop.y() + ( desktop.height() - windowSize.height() ) / 2;
move( x, y );
}
show();
if ( giveFocus )
{
activateWindow();
raise();
}
if ( !ui.pinButton->isChecked() )
{
mouseEnteredOnce = false;
// Need to monitor the mouse so we know when to hide the window
interceptMouse();
}
// This produced some funky mouse grip-related bugs so we commented it out
//QApplication::processEvents(); // Make window appear immediately no matter what
}
else
if ( ui.pinButton->isChecked() )
{
// Pinned-down window isn't always on top, so we need to raise it
show();
activateWindow();
raise();
}
if ( ui.pinButton->isChecked() )
setWindowTitle( tr( "%1 - %2" ).arg( elideInputWord(), "GoldenDict" ) );
/// Too large strings make window expand which is probably not what user
/// wants
ui.translateBox->setText( inputWord, false );
showTranslationFor( inputWord );
}
QString ScanPopup::elideInputWord()
{
return inputWord.size() > 32 ? inputWord.mid( 0, 32 ) + "..." : inputWord;
}
void ScanPopup::currentGroupChanged( QString const & )
{
cfg.lastPopupGroupId = ui.groupList->getCurrentGroup();
Instances::Group const * igrp = groups.findGroup( cfg.lastPopupGroupId );
if( cfg.lastPopupGroupId == Instances::Group::AllGroupId )
{
if( igrp )
igrp->checkMutedDictionaries( &cfg.popupMutedDictionaries );
dictionaryBar.setMutedDictionaries( &cfg.popupMutedDictionaries );
}
else
{
Config::Group * grp = cfg.getGroup( cfg.lastPopupGroupId );
if( grp )
{
if( igrp )
igrp->checkMutedDictionaries( &grp->popupMutedDictionaries );
dictionaryBar.setMutedDictionaries( &grp->popupMutedDictionaries );
}
else
dictionaryBar.setMutedDictionaries( 0 );
}
updateDictionaryBar();
if ( isVisible() )
{
translateInputChanged( ui.translateBox->translateLine()->text() );
translateInputFinished();
}
cfg.lastPopupGroupId = ui.groupList->getCurrentGroup();
}
void ScanPopup::wordListItemActivated( QListWidgetItem * item )
{
showTranslationFor( item->text() );
}
void ScanPopup::translateInputChanged( QString const & text )
{
mainStatusBar->clearMessage();
ui.translateBox->wordList()->setCurrentItem( 0, QItemSelectionModel::Clear );
QString req = text.trimmed();
if ( !req.size() )
{
// An empty request always results in an empty result
wordFinder.cancel();
ui.translateBox->wordList()->clear();
ui.translateBox->wordList()->unsetCursor();
// Reset the noResults mark if it's on right now
if ( ui.translateBox->translateLine()->property( "noResults" ).toBool() )
{
ui.translateBox->translateLine()->setProperty( "noResults", false );
setStyleSheet( styleSheet() );
}
return;
}
ui.translateBox->wordList()->setCursor( Qt::WaitCursor );
wordFinder.prefixMatch( req, getActiveDicts() );
}
void ScanPopup::translateInputFinished()
{
inputWord = ui.translateBox->translateLine()->text().trimmed();
showTranslationFor( inputWord );
}
void ScanPopup::showTranslationFor( QString const & inputWord )
{
ui.pronounceButton->hide();
definition->showDefinition( inputWord, ui.groupList->getCurrentGroup() );
definition->focus();
// Add to history
emit sendWordToHistory( inputWord.trimmed() );
}
vector< sptr< Dictionary::Class > > const & ScanPopup::getActiveDicts()
{
int current = ui.groupList->currentIndex();
if ( current < 0 || current >= (int) groups.size() )
{
// This shouldn't ever happen
return allDictionaries;
}
Config::MutedDictionaries const * mutedDictionaries = dictionaryBar.getMutedDictionaries();
if ( !dictionaryBar.toggleViewAction()->isChecked() || mutedDictionaries == 0 )
return groups[ current ].dictionaries;
else
{
vector< sptr< Dictionary::Class > > const & activeDicts =
groups[ current ].dictionaries;
// Populate the special dictionariesUnmuted array with only unmuted
// dictionaries
dictionariesUnmuted.clear();
dictionariesUnmuted.reserve( activeDicts.size() );
for( unsigned x = 0; x < activeDicts.size(); ++x )
if ( !mutedDictionaries->contains(
QString::fromStdString( activeDicts[ x ]->getId() ) ) )
dictionariesUnmuted.push_back( activeDicts[ x ] );
return dictionariesUnmuted;
}
}
void ScanPopup::typingEvent( QString const & t )
{
if ( t == "\n" || t == "\r" )
{
focusTranslateLine();
}
else
{
ui.translateBox->translateLine()->setFocus();
ui.translateBox->setText( t, true );
ui.translateBox->translateLine()->setCursorPosition( t.size() );
}
}
bool ScanPopup::eventFilter( QObject * watched, QEvent * event )
{
if ( event->type() == QEvent::FocusIn && watched == ui.translateBox->translateLine() )
{
QFocusEvent * focusEvent = static_cast< QFocusEvent * >( event );
// select all on mouse click
if ( focusEvent->reason() == Qt::MouseFocusReason ) {
QTimer::singleShot(0, this, SLOT(focusTranslateLine()));
}
return false;
}
if ( mouseIntercepted )
{
// We're only interested in our events
if ( event->type() == QEvent::MouseMove )
{
// DPRINTF( "Object: %s\n", watched->objectName().toUtf8().data() );
QMouseEvent * mouseEvent = ( QMouseEvent * ) event;
reactOnMouseMove( mouseEvent->globalPos() );
}
}
return QMainWindow::eventFilter( watched, event );
}
void ScanPopup::reactOnMouseMove( QPoint const & p )
{
if ( geometry().contains( p ) )
{
// DPRINTF( "got inside\n" );
hideTimer.stop();
mouseEnteredOnce = true;
uninterceptMouse();
}
else
{
// DPRINTF( "outside\n" );
// We're in grab mode and outside the window - calculate the
// distance from it. We might want to hide it.
// When the mouse has entered once, we don't allow it stayng outside,
// but we give a grace period for it to return.
int proximity = mouseEnteredOnce ? 0 : 60;
// Note: watched == this ensures no other child objects popping out are
// receiving this event, meaning there's basically nothing under the
// cursor.
if ( /*watched == this &&*/
!frameGeometry().adjusted( -proximity, -proximity, proximity, proximity ).
contains( p ) )
{
// We've way too far from the window -- hide the popup
// If the mouse never entered the popup, hide the window instantly --
// the user just moved the cursor further away from the window.
if ( !mouseEnteredOnce )
hideWindow();
else
hideTimer.start();
}
}
}
void ScanPopup::mousePressEvent( QMouseEvent * ev )
{
// With mouse grabs, the press can occur anywhere on the screen, which
// might mean hiding the window.
if ( !frameGeometry().contains( ev->globalPos() ) )
{
hideWindow();
return;
}
if ( ev->button() == Qt::LeftButton )
{
startPos = ev->globalPos();
setCursor( Qt::ClosedHandCursor );
}
QMainWindow::mousePressEvent( ev );
}
void ScanPopup::mouseMoveEvent( QMouseEvent * event )
{
if ( event->buttons() && cursor().shape() == Qt::ClosedHandCursor )
{
QPoint newPos = event->globalPos();
QPoint delta = newPos - startPos;
startPos = newPos;
// Move the window
move( pos() + delta );
}
QMainWindow::mouseMoveEvent( event );
}
void ScanPopup::mouseReleaseEvent( QMouseEvent * ev )
{
unsetCursor();
QMainWindow::mouseReleaseEvent( ev );
}
void ScanPopup::leaveEvent( QEvent * event )
{
QMainWindow::leaveEvent( event );
// We hide the popup when the mouse leaves it.
// Combo-boxes seem to generate leave events for their parents when
// unfolded, so we check coordinates as well.
// If the dialog is pinned, we don't hide the popup.
// If some mouse buttons are pressed, we don't hide the popup either,
// since it indicates the move operation is underway.
if ( !ui.pinButton->isChecked() && !geometry().contains( QCursor::pos() ) &&
QApplication::mouseButtons() == Qt::NoButton )
{
hideTimer.start();
}
}
void ScanPopup::enterEvent( QEvent * event )
{
QMainWindow::enterEvent( event );
if ( mouseEnteredOnce )
{
// We "enter" first time via our event filter. This seems to evade some
// unexpected behavior under Windows.
// If there was a countdown to hide the window, stop it.
hideTimer.stop();
}
}
void ScanPopup::requestWindowFocus()
{
// One of the rare, actually working workarounds for requesting a user keyboard focus on X11,
// works for Qt::Popup windows, exactly like our Scan Popup (in unpinned state).
// Modern window managers actively resist to automatically focus pop-up windows.
#ifdef HAVE_X11
if ( !ui.pinButton->isChecked() )
{
QMenu m( this );
m.addAction( "" );
m.show();
m.hide();
}
#endif
}
void ScanPopup::showEvent( QShowEvent * ev )
{
QMainWindow::showEvent( ev );
QTimer::singleShot(100, this, SLOT( requestWindowFocus() ) );
if ( groups.size() <= 1 ) // Only the default group? Hide then.
ui.groupList->hide();
if ( ui.showDictionaryBar->isChecked() != dictionaryBar.isVisible() )
{
ui.showDictionaryBar->setChecked( dictionaryBar.isVisible() );
updateDictionaryBar();
}
}
void ScanPopup::prefixMatchFinished()
{
// Check that there's a window there at all
if ( isVisible() )
{
if ( wordFinder.getErrorString().size() )
{
ui.queryError->setToolTip( wordFinder.getErrorString() );
ui.queryError->show();
}
else
ui.queryError->hide();
}
}
void ScanPopup::on_pronounceButton_clicked()
{
definition->playSound();
}
void ScanPopup::pinButtonClicked( bool checked )
{
if ( checked )
{
uninterceptMouse();
setWindowFlags( Qt::Dialog );
setWindowTitle( tr( "%1 - %2" ).arg( elideInputWord(), "GoldenDict" ) );
dictionaryBar.setMovable( true );
hideTimer.stop();
}
else
{
dictionaryBar.setMovable( false );
setWindowFlags( popupWindowFlags );
mouseEnteredOnce = true;
}
show();
}
void ScanPopup::focusTranslateLine()
{
if ( !isActiveWindow() )
activateWindow();
ui.translateBox->translateLine()->setFocus();
ui.translateBox->translateLine()->selectAll();
}
void ScanPopup::on_showDictionaryBar_clicked( bool checked )
{
dictionaryBar.setVisible( checked );
updateDictionaryBar();
definition->updateMutedContents();
}
void ScanPopup::hideTimerExpired()
{
if ( isVisible() )
hideWindow();
}
void ScanPopup::altModeExpired()
{
// The alt mode duration has expired, so there's no need to poll for modifiers
// anymore.
altModePollingTimer.stop();
}
void ScanPopup::altModePoll()
{
if ( !pendingInputWord.size() )
{
altModePollingTimer.stop();
altModeExpirationTimer.stop();
}
else
if ( checkModifiersPressed( cfg.preferences.scanPopupModifiers ) )
{
altModePollingTimer.stop();
altModeExpirationTimer.stop();
inputWord = pendingInputWord;
engagePopup( false );
}
}
void ScanPopup::pageLoaded( ArticleView * )
{
ui.pronounceButton->setVisible( definition->hasSound() );
updateBackForwardButtons();
if ( cfg.preferences.pronounceOnLoadPopup )
definition->playSound();
}
void ScanPopup::showStatusBarMessage( QString const & message, int timeout, QPixmap const & icon )
{
mainStatusBar->showMessage( message, timeout, icon );
}
void ScanPopup::escapePressed()
{
if ( !definition->closeSearch() )
hideWindow();
}
void ScanPopup::hideWindow()
{
uninterceptMouse();
emit closeMenu();
hideTimer.stop();
unsetCursor();
ui.translateBox->setPopupEnabled( false );
ui.translateBox->translateLine()->deselect();
hide();
}
void ScanPopup::interceptMouse()
{
if ( !mouseIntercepted )
{
// We used to grab the mouse -- but this doesn't always work reliably
// (e.g. doesn't work at all in Windows 7 for some reason). Therefore
// we use a polling timer now.
// grabMouse();
mouseGrabPollTimer.start();
qApp->installEventFilter( this );
mouseIntercepted = true;
}
}
void ScanPopup::mouseGrabPoll()
{
if ( mouseIntercepted )
reactOnMouseMove( QCursor::pos() );
}
void ScanPopup::uninterceptMouse()
{
if ( mouseIntercepted )
{
qApp->removeEventFilter( this );
mouseGrabPollTimer.stop();
// releaseMouse();
mouseIntercepted = false;
}
}
void ScanPopup::updateDictionaryBar()
{
if ( !dictionaryBar.toggleViewAction()->isChecked() )
return; // It's not enabled, therefore hidden -- don't waste time
unsigned currentId = ui.groupList->getCurrentGroup();
Instances::Group const * grp = groups.findGroup( currentId );
if ( grp ) // Should always be !0, but check as a safeguard
dictionaryBar.setDictionaries( grp->dictionaries );
if( currentId == Instances::Group::AllGroupId )
dictionaryBar.setMutedDictionaries( &cfg.popupMutedDictionaries );
else
{
Config::Group * grp = cfg.getGroup( currentId );
dictionaryBar.setMutedDictionaries( grp ? &grp->popupMutedDictionaries : 0 );
}
setDictionaryIconSize();
}