File: macmouseover.mm

package info (click to toggle)
goldendict 1.5.0~rc2%2Bgit20181207%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 16,496 kB
  • sloc: cpp: 58,990; ansic: 11,311; xml: 488; makefile: 77; sh: 42
file content (337 lines) | stat: -rw-r--r-- 9,125 bytes parent folder | download | duplicates (6)
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
#include "macmouseover.hh"
#include <AppKit/NSTouch.h>
#include <AppKit/NSEvent.h>
#include <AppKit/NSScreen.h>
#include <Foundation/NSAutoreleasePool.h>
#include <Foundation/Foundation.h>

#ifndef AVAILABLE_MAC_OS_X_VERSION_10_11_AND_LATER
#define kAXValueTypeCGPoint kAXValueCGPointType
#define kAXValueTypeCFRange kAXValueCFRangeType
#endif

const int mouseOverInterval = 300;

CGEventRef eventCallback( CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon )
{
(void) proxy;
  if( type != kCGEventMouseMoved )
    return event;
  static_cast< MacMouseOver * >( refcon )->mouseMoved();
  return event;
}

static CGPoint carbonScreenPointFromCocoaScreenPoint( NSPoint cocoaPoint )
{
  NSScreen *foundScreen = nil;
  CGPoint thePoint;

  for (NSScreen *screen in [NSScreen screens]) {
    if (NSPointInRect(cocoaPoint, [screen frame])) {
        foundScreen = screen;
    }
  }

  if (foundScreen) {
    CGFloat screenHeight = [foundScreen frame].size.height;
    thePoint = CGPointMake(cocoaPoint.x, screenHeight - cocoaPoint.y - 1);
  }
  else
    thePoint = CGPointMake(0.0, 0.0);

  return thePoint;
}

MacMouseOver & MacMouseOver::instance()
{
  static MacMouseOver m;

  return m;
}

MacMouseOver::MacMouseOver() :
  pPref(NULL)
, tapRef( 0 )
, loop( 0 )
{
  mouseTimer.setSingleShot( true );
  connect( &mouseTimer, SIGNAL( timeout() ), this, SLOT( timerShot() ) );

  elementSystemWide = AXUIElementCreateSystemWide();
}

MacMouseOver::~MacMouseOver()
{
  disableMouseOver();

  if( tapRef )
    CFRelease( tapRef );

  if( loop )
    CFRelease( loop );

  if( elementSystemWide )
    CFRelease( elementSystemWide );
}

QString MacMouseOver::CFStringRefToQString( CFStringRef str )
{
  int length = CFStringGetLength( str );
  if( length == 0 )
    return QString();

  UniChar *chars = new UniChar[ length ];
  CFStringGetCharacters( str, CFRangeMake( 0, length ), chars );

  QString result = QString::fromUtf16( chars, length );

  delete[] chars;
  return result;
}

void MacMouseOver::mouseMoved()
{
  mouseTimer.start( mouseOverInterval );
}

void MacMouseOver::enableMouseOver()
{
  mouseTimer.stop();
  if( !isAXAPIEnabled() )
    return;
  if( !tapRef )
    tapRef = CGEventTapCreate( kCGAnnotatedSessionEventTap, kCGHeadInsertEventTap,
                               kCGEventTapOptionListenOnly,
                               CGEventMaskBit( kCGEventMouseMoved ),
                               eventCallback, this );
  if( !tapRef )
    return;
  if( !loop )
    loop = CFMachPortCreateRunLoopSource( kCFAllocatorDefault, tapRef, 0 );
  if( loop )
    CFRunLoopAddSource( CFRunLoopGetMain(), loop, kCFRunLoopCommonModes );
}

void MacMouseOver::disableMouseOver()
{
  mouseTimer.stop();
  if( loop )
    CFRunLoopRemoveSource( CFRunLoopGetMain(), loop, kCFRunLoopCommonModes );
}

void MacMouseOver::timerShot()
{
  if( mouseMutex.tryLock( 0 ) )
    mouseMutex.unlock();
  else
    return;
  if( !pPref )
    return;
  if( !pPref->enableScanPopupModifiers || checkModifiersPressed( pPref->scanPopupModifiers ) )
    handlePosition();
}

void MacMouseOver::handlePosition()
{
  Mutex::Lock _( mouseMutex );

  QString strToTranslate;

  NSAutoreleasePool * pool = [ [ NSAutoreleasePool alloc ] init ];
  CGPoint pt = carbonScreenPointFromCocoaScreenPoint( [NSEvent mouseLocation] );
  [ pool drain ];

  CFArrayRef names = 0;

  AXUIElementRef elem = 0;
  AXError err = AXUIElementCopyElementAtPosition( elementSystemWide, pt.x, pt.y, &elem );

  if( err != kAXErrorSuccess )
    return;

  for( ; ; )
  {
    CFTypeRef parameter = AXValueCreate( kAXValueTypeCGPoint, &pt );
    CFTypeRef rangeValue;
    err = AXUIElementCopyParameterizedAttributeNames( elem, &names );
    if( err != kAXErrorSuccess )
      break;

    int numOfAttributes = CFArrayGetCount( names );
    if( CFArrayContainsValue( names, CFRangeMake( 0, numOfAttributes ), CFSTR( "AXRangeForPosition" ) ) )
    {
      // Standard interface
      err = AXUIElementCopyParameterizedAttributeValue( elem, kAXRangeForPositionParameterizedAttribute,
                                                            parameter, ( CFTypeRef * )&rangeValue );
      CFRelease( parameter );
      if( err != kAXErrorSuccess )
        break;

      CFStringRef stringValue;

      CFRange decodedRange = CFRangeMake( 0, 0 );
      bool b = AXValueGetValue( (AXValueRef)rangeValue, kAXValueTypeCFRange, &decodedRange );
      CFRelease( rangeValue );
      if( b )
      {
        int fromPos = decodedRange.location - 127;
        if( fromPos < 0 )
          fromPos = 0;
        int wordPos = decodedRange.location - fromPos;  // Cursor position in result string

        CFRange range = CFRangeMake( fromPos, wordPos + 1 );
        parameter = AXValueCreate( kAXValueTypeCFRange, &range );
        err = AXUIElementCopyParameterizedAttributeValue( elem, kAXStringForRangeParameterizedAttribute,
                                                            parameter, (CFTypeRef *)&stringValue );
        CFRelease( parameter );
        if( err != kAXErrorSuccess )
          break;

        strToTranslate = CFStringRefToQString( stringValue );
        CFRelease( stringValue );

        // Read string further
        for( int i = 1; i < 128; i++ )
        {
          range = CFRangeMake( decodedRange.location + i, 1 );
          parameter = AXValueCreate( kAXValueTypeCFRange, &range );
          err = AXUIElementCopyParameterizedAttributeValue( elem, kAXStringForRangeParameterizedAttribute,
                                                              parameter, (CFTypeRef *)&stringValue );
          CFRelease( parameter );

          if( err != kAXErrorSuccess )
            break;

          QString s = CFStringRefToQString( stringValue );
          CFRelease( stringValue );

          if( s[ 0 ].isLetterOrNumber() || s[ 0 ] == '-' )
            strToTranslate += s;
          else
            break;
        }

        handleRetrievedString( strToTranslate, wordPos );
      }
    }
    else if( CFArrayContainsValue( names, CFRangeMake( 0, numOfAttributes ), CFSTR( "AXTextMarkerForPosition" ) ) )
    {
      // Safari interface
      CFTypeRef marker, range;
      CFStringRef str;
      err = AXUIElementCopyParameterizedAttributeValue( elem, CFSTR( "AXTextMarkerForPosition" ),
                                                            parameter, ( CFTypeRef * )&marker );
      CFRelease( parameter );
      if( err != kAXErrorSuccess )
        break;

      err = AXUIElementCopyParameterizedAttributeValue( elem, CFSTR( "AXLeftWordTextMarkerRangeForTextMarker" ),
                                                        marker, ( CFTypeRef * )&range );
      CFRelease( marker );
      if( err != kAXErrorSuccess )
        break;

      err = AXUIElementCopyParameterizedAttributeValue( elem, CFSTR( "AXStringForTextMarkerRange" ),
                                                        range, ( CFTypeRef * )&str );
      CFRelease( range );
      if( err == kAXErrorSuccess )
      {
        strToTranslate = CFStringRefToQString( str );
        CFRelease( str );
        handleRetrievedString( strToTranslate, 0 );
      }
    }
    break;
  }
  if( elem )
    CFRelease( elem );
  if( names )
    CFRelease( names );
}

void MacMouseOver::handleRetrievedString( QString & wordSeq, int wordSeqPos )
{

  if( wordSeq.isEmpty() )
    return;

  // locate the word inside the sequence

  QString word;

  if ( wordSeq[ wordSeqPos ].isSpace() )
  {
    // Currently we ignore such cases
    return;
  }
  else
  if ( !wordSeq[ wordSeqPos ].isLetterOrNumber() )
  {
    // Special case: the cursor points to something which doesn't look like a
    // middle of the word -- assume that it's something that joins two words
    // together.

    int begin = wordSeqPos;

    for( ; begin; --begin )
      if ( !wordSeq[ begin - 1 ].isLetterOrNumber() )
        break;

    int end = wordSeqPos;

    while( ++end < wordSeq.size() )
      if ( !wordSeq[ end ].isLetterOrNumber() )
        break;

    if ( end - begin == 1 )
    {
      // Well, turns out it was just a single non-letter char, discard it
      return;
    }

    word = wordSeq.mid( begin, end - begin );
  }
  else
  {
    // Cursor points to a letter -- cut the word it points to

    int begin = wordSeqPos;

    for( ; begin; --begin )
      if ( !wordSeq[ begin - 1 ].isLetterOrNumber() )
        break;

    int end = wordSeqPos;

    while( ++end < wordSeq.size() )
    {
      if ( !wordSeq[ end ].isLetterOrNumber() )
        break;
    }
    word = wordSeq.mid( begin, end - begin );
  }

  // See if we have an RTL char. Reverse the whole string if we do.

  for( int x = 0; x < word.size(); ++x )
  {
    QChar::Direction d = word[ x ].direction();

    if ( d == QChar::DirR || d == QChar::DirAL ||
         d == QChar::DirRLE || d == QChar::DirRLO )
    {
      std::reverse( word.begin(), word.end() );
      break;
    }
  }

  emit instance().hovered( word, false );
}

bool MacMouseOver::isAXAPIEnabled()
{
  if( NSFoundationVersionNumber >= 1000 )  // MacOS 10.9+
    return AXIsProcessTrusted();

  return AXAPIEnabled();
}