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
|
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2008 NVDA Contributors <http://www.nvda-project.org/>
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import locale
import sys
import comtypes.client
import struct
import ctypes
import pythoncom
import win32clipboard
import oleTypes
import colors
import globalVars
import eventHandler
import comInterfaces.tom
from logHandler import log
import config
import speech
import winKernel
import api
import winUser
import textInfos.offsets
from keyboardHandler import KeyboardInputGesture
from scriptHandler import isScriptWaiting
import IAccessibleHandler
import controlTypes
from . import Window
from .. import NVDAObjectTextInfo
from ..behaviors import EditableTextWithAutoSelectDetection
import braille
import watchdog
selOffsetsAtLastCaretEvent=None
#Edit control window messages
EM_GETSEL=176
EM_SETSEL=177
EM_SCROLLCARET=0xb7
EM_GETLINE=196
EM_GETLINECOUNT=186
EM_LINEFROMCHAR=201
EM_LINEINDEX=187
EM_LINELENGTH=193
EM_POSFROMCHAR=214
EM_CHARFROMPOS=215
EM_GETFIRSTVISIBLELINE=0x0ce
#Rich edit messages
EM_EXGETSEL=winUser.WM_USER+52
EM_EXLINEFROMCHAR=winUser.WM_USER+54
EM_EXSETSEL=winUser.WM_USER+55
EM_GETCHARFORMAT=winUser.WM_USER+58
EM_GETPARAFORMAT=winUser.WM_USER+61
EM_GETTEXTRANGE=winUser.WM_USER+75
EM_FINDWORDBREAK=winUser.WM_USER+76
#Rich edit 2.0 messages
EM_GETTEXTEX=winUser.WM_USER+94
EM_GETTEXTLENGTHEX=winUser.WM_USER+95
#Rich edit 4.0 messages
EM_GETPAGE=winUser.WM_USER+228
LF_FACESIZE=32
#structures
class PointLStruct(ctypes.Structure):
_fields_=[
('x',ctypes.c_long),
('y',ctypes.c_long),
]
class CharRangeStruct(ctypes.Structure):
_fields_=[
('cpMin',ctypes.c_long),
('cpMax',ctypes.c_long),
]
class TextRangeUStruct(ctypes.Structure):
_fields_=[
('chrg',CharRangeStruct),
('lpstrText',ctypes.c_wchar_p),
]
class TextRangeAStruct(ctypes.Structure):
_fields_=[
('chrg',CharRangeStruct),
('lpstrText',ctypes.c_char_p),
]
CFM_LINK=0x20
CFE_AUTOBACKCOLOR=0x4000000
CFE_AUTOCOLOR=0x40000000
CFE_BOLD=1
CFE_ITALIC=2
CFE_UNDERLINE=4
CFE_STRIKEOUT=8
CFE_PROTECTED=16
CFE_SUBSCRIPT=0x00010000 # Superscript and subscript are
CFE_SUPERSCRIPT=0x00020000 # mutually exclusive
SCF_SELECTION=0x1
class CharFormat2WStruct(ctypes.Structure):
_fields_=[
('cbSize',ctypes.c_uint),
('dwMask',ctypes.wintypes.DWORD),
('dwEffects',ctypes.wintypes.DWORD),
('yHeight',ctypes.c_long),
('yOffset',ctypes.c_long),
('crTextColor',ctypes.wintypes.COLORREF),
('bCharSet',ctypes.c_byte),
('bPitchAndFamily',ctypes.c_byte),
('szFaceName',ctypes.c_wchar*LF_FACESIZE),
('wWeight',ctypes.wintypes.WORD),
('sSpacing',ctypes.c_short),
('crBackColor',ctypes.wintypes.COLORREF),
('lcid',ctypes.wintypes.LCID),
('dwReserved',ctypes.wintypes.DWORD),
('sStyle',ctypes.c_short),
('wKerning',ctypes.wintypes.WORD),
('bUnderlineType',ctypes.c_byte),
('bAnimation',ctypes.c_byte),
('bRevAuthor',ctypes.c_byte),
('bReserved1',ctypes.c_byte),
]
class CharFormat2AStruct(ctypes.Structure):
_fields_=CharFormat2WStruct._fields_[:]
_fields_[8]=('szFaceName',ctypes.c_char*LF_FACESIZE)
class getTextExStruct(ctypes.Structure):
_fields_=[
('cb',ctypes.wintypes.DWORD),
('flags',ctypes.wintypes.DWORD),
('codepage',ctypes.c_uint),
('lpDefaultChar',ctypes.wintypes.LPCSTR),
('lpUsedDefChar',ctypes.c_void_p),
]
class getTextLengthExStruct(ctypes.Structure):
_fields_=[
('flags',ctypes.wintypes.DWORD),
('codepage',ctypes.c_uint),
]
#getTextEx flags
GT_DEFAULT=0
GT_USECRLF=1
GT_SELECTION=2
GT_RAWTEXT=4
GT_NOHIDDENTEXT=8
#getTextLengthEx flags
GTL_DEFAULT=0
GTL_USECRLF=1
GTL_PRECISE=2
GTL_CLOSE=4
GTL_NUMCHARS=8
GTL_NUMBYTES=16
#findWordbreak constants
WB_CLASSIFY=3
WB_MOVEWORDLEFT=4
WB_MOVEWORDRIGHT=5
WB_LEFTBREAK=6
WB_RIGHTBREAK=7
class EditTextInfo(textInfos.offsets.OffsetsTextInfo):
def _getPointFromOffset(self,offset):
if self.obj.editAPIVersion==1:
processHandle=self.obj.processHandle
internalP=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(PointLStruct),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
p=PointLStruct(0,0)
winKernel.writeProcessMemory(processHandle,internalP,ctypes.byref(p),ctypes.sizeof(p),None)
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_POSFROMCHAR,internalP,offset)
winKernel.readProcessMemory(processHandle,internalP,ctypes.byref(p),ctypes.sizeof(p),None)
finally:
winKernel.virtualFreeEx(processHandle,internalP,0,winKernel.MEM_RELEASE)
point=textInfos.Point(p.x,p.y)
else:
res=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_POSFROMCHAR,offset,None)
point=textInfos.Point(winUser.LOWORD(res),winUser.HIWORD(res))
(left,top,width,height)=self.obj.location
if point.x and point.y:
point.x=point.x+left
point.y=point.y+top
return point
else:
raise NotImplementedError
def _getOffsetFromPoint(self,x,y):
(left,top,width,height)=self.obj.location
if self.obj.editAPIVersion>=1:
processHandle=self.obj.processHandle
internalP=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(PointLStruct),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
p=PointLStruct(x-left,y-top)
winKernel.writeProcessMemory(processHandle,internalP,ctypes.byref(p),ctypes.sizeof(p),None)
offset=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_CHARFROMPOS,0,internalP)
finally:
winKernel.virtualFreeEx(processHandle,internalP,0,winKernel.MEM_RELEASE)
else:
p=(x-left)+((y-top)<<16)
offset=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_CHARFROMPOS,0,p)&0xffff
return offset
def _getCharFormat(self,offset):
oldSel=self._getSelectionOffsets()
if oldSel!=(offset,offset+1):
self._setSelectionOffsets(offset,offset+1)
if self.obj.isWindowUnicode:
charFormatStruct=CharFormat2WStruct
else:
charFormatStruct=CharFormat2AStruct
charFormat=charFormatStruct()
charFormat.cbSize=ctypes.sizeof(charFormatStruct)
processHandle=self.obj.processHandle
internalCharFormat=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(charFormat),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
winKernel.writeProcessMemory(processHandle,internalCharFormat,ctypes.byref(charFormat),ctypes.sizeof(charFormat),None)
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETCHARFORMAT,SCF_SELECTION, internalCharFormat)
winKernel.readProcessMemory(processHandle,internalCharFormat,ctypes.byref(charFormat),ctypes.sizeof(charFormat),None)
finally:
winKernel.virtualFreeEx(processHandle,internalCharFormat,0,winKernel.MEM_RELEASE)
if oldSel!=(offset,offset+1):
self._setSelectionOffsets(oldSel[0],oldSel[1])
return charFormat
def _getFormatFieldAndOffsets(self,offset,formatConfig,calculateOffsets=True):
#Basic edit fields do not support formatting at all
if self.obj.editAPIVersion<1:
return super(EditTextInfo,self)._getFormatFieldAndOffsets(offset,formatConfig,calculateOffsets=calculateOffsets)
if calculateOffsets:
startOffset,endOffset=self._getWordOffsets(offset)
else:
startOffset,endOffset=self._startOffset,self._endOffset
formatField=textInfos.FormatField()
charFormat=None
if formatConfig["reportFontName"]:
if charFormat is None: charFormat=self._getCharFormat(offset)
formatField["font-name"]=charFormat.szFaceName
if formatConfig["reportFontSize"]:
if charFormat is None: charFormat=self._getCharFormat(offset)
formatField["font-size"]="%spt"%(charFormat.yHeight/20)
if formatConfig["reportFontAttributes"]:
if charFormat is None: charFormat=self._getCharFormat(offset)
formatField["bold"]=bool(charFormat.dwEffects&CFE_BOLD)
formatField["italic"]=bool(charFormat.dwEffects&CFE_ITALIC)
formatField["underline"]=bool(charFormat.dwEffects&CFE_UNDERLINE)
formatField["strikethrough"]=bool(charFormat.dwEffects&CFE_STRIKEOUT)
if charFormat.dwEffects&CFE_SUBSCRIPT:
formatField["text-position"]="sub"
elif charFormat.dwEffects&CFE_SUPERSCRIPT:
formatField["text-position"]="super"
if formatConfig["reportColor"]:
if charFormat is None: charFormat=self._getCharFormat(offset)
formatField["color"]=colors.RGB.fromCOLORREF(charFormat.crTextColor) if not charFormat.dwEffects&CFE_AUTOCOLOR else _("default color")
formatField["background-color"]=colors.RGB.fromCOLORREF(charFormat.crBackColor) if not charFormat.dwEffects&CFE_AUTOBACKCOLOR else _("default color")
if formatConfig["reportLineNumber"]:
formatField["line-number"]=self._getLineNumFromOffset(offset)+1
if formatConfig["reportLinks"]:
if charFormat is None: charFormat=self._getCharFormat(offset)
formatField["link"]=bool(charFormat.dwEffects&CFM_LINK)
return formatField,(startOffset,endOffset)
def _getSelectionOffsets(self):
if self.obj.editAPIVersion>=1:
charRange=CharRangeStruct()
processHandle=self.obj.processHandle
internalCharRange=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(charRange),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_EXGETSEL,0, internalCharRange)
winKernel.readProcessMemory(processHandle,internalCharRange,ctypes.byref(charRange),ctypes.sizeof(charRange),None)
finally:
winKernel.virtualFreeEx(processHandle,internalCharRange,0,winKernel.MEM_RELEASE)
return (charRange.cpMin,charRange.cpMax)
else:
start=ctypes.c_uint()
end=ctypes.c_uint()
res=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETSEL,ctypes.byref(start),ctypes.byref(end))
return start.value,end.value
def _setSelectionOffsets(self,start,end):
if self.obj.editAPIVersion>=1:
charRange=CharRangeStruct()
charRange.cpMin=start
charRange.cpMax=end
processHandle=self.obj.processHandle
internalCharRange=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(charRange),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
winKernel.writeProcessMemory(processHandle,internalCharRange,ctypes.byref(charRange),ctypes.sizeof(charRange),None)
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_EXSETSEL,0, internalCharRange)
finally:
winKernel.virtualFreeEx(processHandle,internalCharRange,0,winKernel.MEM_RELEASE)
else:
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_SETSEL,start,end)
#Make sure the Window is always scrolled to the caret
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_SCROLLCARET,0,0)
def _getCaretOffset(self):
return self._getSelectionOffsets()[0]
def _setCaretOffset(self,offset):
return self._setSelectionOffsets(offset,offset)
def _getStoryText(self):
if controlTypes.STATE_PROTECTED in self.obj.states:
return '*'*(self._getStoryLength()-1)
return self.obj.windowText
def _getStoryLength(self):
if self.obj.editAPIVersion>=2:
info=getTextLengthExStruct()
info.flags=GTL_NUMCHARS
if self.obj.isWindowUnicode:
info.codepage=1200
else:
info.codepage=0
processHandle=self.obj.processHandle
internalInfo=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(info),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
winKernel.writeProcessMemory(processHandle,internalInfo,ctypes.byref(info),ctypes.sizeof(info),None)
textLen=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETTEXTLENGTHEX,internalInfo,0)
finally:
winKernel.virtualFreeEx(processHandle,internalInfo,0,winKernel.MEM_RELEASE)
return textLen+1
else:
return watchdog.cancellableSendMessage(self.obj.windowHandle,winUser.WM_GETTEXTLENGTH,0,0)+1
def _getLineCount(self):
return watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETLINECOUNT,0,0)
def _getTextRange(self,start,end):
if self.obj.editAPIVersion>=2:
bufLen=((end-start)+1)*2
if self.obj.isWindowUnicode:
textRange=TextRangeUStruct()
else:
textRange=TextRangeAStruct()
textRange.chrg.cpMin=start
textRange.chrg.cpMax=end
processHandle=self.obj.processHandle
internalBuf=winKernel.virtualAllocEx(processHandle,None,bufLen,winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
textRange.lpstrText=internalBuf
internalTextRange=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(textRange),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
winKernel.writeProcessMemory(processHandle,internalTextRange,ctypes.byref(textRange),ctypes.sizeof(textRange),None)
res=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETTEXTRANGE,0,internalTextRange)
finally:
winKernel.virtualFreeEx(processHandle,internalTextRange,0,winKernel.MEM_RELEASE)
buf=(ctypes.c_byte*bufLen)()
winKernel.readProcessMemory(processHandle,internalBuf,buf,bufLen,None)
finally:
winKernel.virtualFreeEx(processHandle,internalBuf,0,winKernel.MEM_RELEASE)
if self.obj.isWindowUnicode or (res>1 and (buf[res]!=0 or buf[res+1]!=0)):
return ctypes.cast(buf,ctypes.c_wchar_p).value
else:
return unicode(ctypes.cast(buf,ctypes.c_char_p).value, errors="replace", encoding=locale.getlocale()[1])
else:
return self._getStoryText()[start:end]
def _getWordOffsets(self,offset):
if self.obj.editAPIVersion>=2:
start=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_FINDWORDBREAK,WB_MOVEWORDLEFT,offset)
end=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_FINDWORDBREAK,WB_MOVEWORDRIGHT,start)
if end<=offset:
start=end
end=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_FINDWORDBREAK,WB_MOVEWORDRIGHT,offset)
return (start,end)
elif sys.getwindowsversion().major<6: #Implementation of standard edit field wordbreak behaviour (only breaks on space)
lineStart,lineEnd=self._getLineOffsets(offset)
if offset>=lineEnd:
return offset,offset+1
lineText=self._getTextRange(lineStart,lineEnd)
lineTextLen=len(lineText)
relativeOffset=offset-lineStart
if relativeOffset>=lineTextLen:
return offset,offset+1
#cariage returns are always treeted as a word by themselves
if lineText[relativeOffset] in ['\r','\n']:
return offset,offset+1
#Find the start of the word (possibly moving through space to get to the word first)
tempOffset=relativeOffset
while tempOffset>0 and lineText[tempOffset].isspace():
tempOffset-=1
while tempOffset>0 and not lineText[tempOffset].isspace():
tempOffset-=1
start=lineStart+tempOffset
startOnSpace=True if tempOffset<lineTextLen and lineText[tempOffset].isspace() else False
#Find the end of the word and trailing space
tempOffset=relativeOffset
if startOnSpace:
while tempOffset<lineTextLen and lineText[tempOffset].isspace():
tempOffset+=1
while tempOffset<lineTextLen and not lineText[tempOffset].isspace():
tempOffset+=1
while tempOffset<lineTextLen and lineText[tempOffset].isspace():
tempOffset+=1
end=lineStart+tempOffset
return start,end
else:
if self._getTextRange(offset,offset+1) in ['\r','\n']:
return offset,offset+1
else:
return super(EditTextInfo,self)._getWordOffsets(offset)
def _getLineNumFromOffset(self,offset):
if self.obj.editAPIVersion>=1:
res=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_EXLINEFROMCHAR,0,offset)
return res
else:
return watchdog.cancellableSendMessage(self.obj.windowHandle,EM_LINEFROMCHAR,offset,0)
def _getLineOffsets(self,offset):
lineNum=self._getLineNumFromOffset(offset)
start=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_LINEINDEX,lineNum,0)
length=watchdog.cancellableSendMessage(self.obj.windowHandle,EM_LINELENGTH,offset,0)
end=start+length
#If we just seem to get invalid line info, calculate manually
if start<=0 and end<=0 and lineNum<=0 and self._getLineCount()<=0 and self._getStoryLength()>0:
return super(EditTextInfo,self)._getLineOffsets(offset)
#Some edit controls that show both line feed and carage return can give a length not including the line feed
if end<=offset:
end=offset+1
#edit controls lye about their line length
limit=self._getStoryLength()
while self._getLineNumFromOffset(end)==lineNum and end<limit:
end+=1
return (start,end)
def _getParagraphOffsets(self,offset):
return self._getLineOffsets(offset)
ITextDocumentUnitsToNVDAUnits={
comInterfaces.tom.tomCharacter:textInfos.UNIT_CHARACTER,
comInterfaces.tom.tomWord:textInfos.UNIT_WORD,
comInterfaces.tom.tomLine:textInfos.UNIT_LINE,
comInterfaces.tom.tomSentence:textInfos.UNIT_SENTENCE,
comInterfaces.tom.tomParagraph:textInfos.UNIT_PARAGRAPH,
comInterfaces.tom.tomStory:textInfos.UNIT_STORY,
}
NVDAUnitsToITextDocumentUnits={
textInfos.UNIT_CHARACTER:comInterfaces.tom.tomCharacter,
textInfos.UNIT_WORD:comInterfaces.tom.tomWord,
textInfos.UNIT_LINE:comInterfaces.tom.tomLine,
textInfos.UNIT_SENTENCE:comInterfaces.tom.tomSentence,
textInfos.UNIT_PARAGRAPH:comInterfaces.tom.tomParagraph,
textInfos.UNIT_STORY:comInterfaces.tom.tomStory,
textInfos.UNIT_READINGCHUNK:comInterfaces.tom.tomSentence,
}
class ITextDocumentTextInfo(textInfos.TextInfo):
def _get_pointAtStart(self):
p=textInfos.Point(0,0)
(p.x,p.y)=self._rangeObj.GetPoint(comInterfaces.tom.tomStart)
if p.x and p.y:
return p
else:
raise NotImplementedError
def _getCharFormat(self,range):
oldSel=self.obj.ITextSelectionObject.duplicate
if not (oldSel.start==range.start and oldSel.end==range.end):
self.obj.ITextSelectionObject.start=range.start
self.obj.ITextSelectionObject.end=range.end
if self.obj.isWindowUnicode:
charFormatStruct=CharFormat2WStruct
else:
charFormatStruct=CharFormat2AStruct
charFormat=charFormatStruct()
charFormat.cbSize=ctypes.sizeof(charFormatStruct)
processHandle=self.obj.processHandle
internalCharFormat=winKernel.virtualAllocEx(processHandle,None,ctypes.sizeof(charFormat),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE)
try:
winKernel.writeProcessMemory(processHandle,internalCharFormat,ctypes.byref(charFormat),ctypes.sizeof(charFormat),None)
watchdog.cancellableSendMessage(self.obj.windowHandle,EM_GETCHARFORMAT,SCF_SELECTION, internalCharFormat)
winKernel.readProcessMemory(processHandle,internalCharFormat,ctypes.byref(charFormat),ctypes.sizeof(charFormat),None)
finally:
winKernel.virtualFreeEx(processHandle,internalCharFormat,0,winKernel.MEM_RELEASE)
if not (oldSel.start==range.start and oldSel.end==range.end):
self.obj.ITextSelectionObject.start=oldSel.start
self.obj.ITextSelectionObject.end=oldSel.end
return charFormat
def _getFormatFieldAtRange(self,range,formatConfig):
formatField=textInfos.FormatField()
fontObj=None
paraFormatObj=None
charFormat=None
if formatConfig["reportAlignment"]:
if not paraFormatObj: paraFormatObj=range.para
alignment=paraFormatObj.alignment
if alignment==comInterfaces.tom.tomAlignLeft:
formatField["text-align"]="left"
elif alignment==comInterfaces.tom.tomAlignCenter:
formatField["text-align"]="center"
elif alignment==comInterfaces.tom.tomAlignRight:
formatField["text-align"]="right"
elif alignment==comInterfaces.tom.tomAlignJustify:
formatField["text-align"]="justify"
if formatConfig["reportLineNumber"]:
formatField["line-number"]=range.getIndex(comInterfaces.tom.tomLine)
if formatConfig["reportFontName"]:
if not fontObj: fontObj=range.font
formatField["font-name"]=fontObj.name
if formatConfig["reportFontSize"]:
if not fontObj: fontObj=range.font
formatField["font-size"]="%spt"%fontObj.size
if formatConfig["reportFontAttributes"]:
if not fontObj: fontObj=range.font
formatField["bold"]=bool(fontObj.bold)
formatField["italic"]=bool(fontObj.italic)
formatField["underline"]=bool(fontObj.underline)
formatField["strikethrough"]=bool(fontObj.StrikeThrough)
if fontObj.superscript:
formatField["text-position"]="super"
elif fontObj.subscript:
formatField["text-position"]="sub"
if formatConfig["reportLinks"]:
if charFormat is None: charFormat=self._getCharFormat(range)
formatField["link"]=bool(charFormat.dwEffects&CFM_LINK)
return formatField
def _expandFormatRange(self,range,formatConfig):
startLimit=self._rangeObj.start
endLimit=self._rangeObj.end
chunkRange=range.duplicate
if formatConfig["reportLineNumber"]:
chunkRange.expand(comInterfaces.tom.tomLine)
else:
chunkRange.expand(comInterfaces.tom.tomParagraph)
chunkStart=chunkRange.start
chunkEnd=chunkRange.end
if startLimit<chunkStart:
startLimit=chunkStart
if endLimit>chunkEnd:
endLimit=chunkEnd
#range.moveEnd(comInterfaces.tom.tomCharFormat,1)
range.expand(comInterfaces.tom.tomCharFormat)
if range.end>endLimit:
range.end=endLimit
if range.start<startLimit:
range.start=startLimit
def _getEmbeddedObjectLabel(self,embedRangeObj):
label=None
try:
o=embedRangeObj.GetEmbeddedObject()
except comtypes.COMError:
o=None
if not o:
return None
import oleacc
try:
label=o.QueryInterface(oleacc.IAccessible).accName(0);
except comtypes.COMError:
pass
if label:
return label
left,top=embedRangeObj.GetPoint(comInterfaces.tom.tomStart)
right,bottom=embedRangeObj.GetPoint(comInterfaces.tom.tomEnd)
import displayModel
label=displayModel.getWindowTextInRect(self.obj.appModule.helperLocalBindingHandle, self.obj.windowHandle, left, top, right, bottom+10,1,1)[0]
if label and not label.isspace():
return label
try:
dataObj=o.QueryInterface(oleTypes.IDataObject)
except comtypes.COMError:
dataObj=None
if dataObj:
try:
dataObj=pythoncom._univgw.interface(hash(dataObj),pythoncom.IID_IDataObject)
format=(win32clipboard.CF_UNICODETEXT, None, pythoncom.DVASPECT_CONTENT, -1, pythoncom.TYMED_HGLOBAL)
medium=dataObj.GetData(format)
buf=ctypes.create_string_buffer(medium.data)
buf=ctypes.cast(buf,ctypes.c_wchar_p)
label=buf.value
except:
pass
if label:
return label
try:
oleObj=o.QueryInterface(oleTypes.IOleObject)
label=oleObj.GetUserType(1)
except comtypes.COMError:
pass
return label
def _getTextAtRange(self,rangeObj):
embedRangeObj=None
bufText=rangeObj.text
if bufText is None:
bufText=""
newTextList=[]
start=rangeObj.start
for offset in range(len(bufText)):
if ord(bufText[offset])==0xfffc:
if embedRangeObj is None: embedRangeObj=rangeObj.duplicate
embedRangeObj.setRange(start+offset,start+offset+1)
label=self._getEmbeddedObjectLabel(embedRangeObj)
if label:
newTextList.append(label)
else:
newTextList.append(_("embedded object"))
else:
newTextList.append(bufText[offset])
return "".join(newTextList)
def __init__(self,obj,position,_rangeObj=None):
super(ITextDocumentTextInfo,self).__init__(obj,position)
if _rangeObj:
self._rangeObj=_rangeObj.Duplicate
return
if isinstance(position,textInfos.Point):
self._rangeObj=self.obj.ITextDocumentObject.rangeFromPoint(position.x,position.y)
elif position==textInfos.POSITION_ALL:
self._rangeObj=self.obj.ITextDocumentObject.range(0,0)
self._rangeObj.expand(comInterfaces.tom.tomStory)
elif position==textInfos.POSITION_SELECTION:
self._rangeObj=self.obj.ITextSelectionObject.duplicate
elif position==textInfos.POSITION_CARET:
self._rangeObj=self.obj.ITextSelectionObject.duplicate
self._rangeObj.Collapse(True)
elif position==textInfos.POSITION_FIRST:
self._rangeObj=self.obj.ITextDocumentObject.range(0,0)
elif position==textInfos.POSITION_LAST:
self._rangeObj=self.obj.ITextDocumentObject.range(0,0)
self._rangeObj.move(comInterfaces.tom.tomStory,1)
self._rangeObj.moveStart(comInterfaces.tom.tomCharacter,-1)
elif isinstance(position,textInfos.offsets.Offsets):
self._rangeObj=self.obj.ITextDocumentObject.range(position.startOffset,position.endOffset)
else:
raise NotImplementedError("position: %s"%position)
def getTextWithFields(self,formatConfig=None):
if not formatConfig:
formatConfig=config.conf["documentFormatting"]
range=self._rangeObj.duplicate
range.collapse(True)
if not formatConfig["detectFormatAfterCursor"]:
range.expand(comInterfaces.tom.tomCharacter)
return [textInfos.FieldCommand("formatChange",self._getFormatFieldAtRange(range,formatConfig)),
self._getTextAtRange(self._rangeObj)]
commandList=[]
endLimit=self._rangeObj.end
while range.end<endLimit:
self._expandFormatRange(range,formatConfig)
commandList.append(textInfos.FieldCommand("formatChange",self._getFormatFieldAtRange(range,formatConfig)))
commandList.append(self._getTextAtRange(range))
end=range.end
range.start=end
#Trying to set the start past the end of the document forces both start and end back to the previous offset, so catch this
if range.end<end:
break
return commandList
def expand(self,unit):
if unit in NVDAUnitsToITextDocumentUnits:
self._rangeObj.Expand(NVDAUnitsToITextDocumentUnits[unit])
else:
raise NotImplementedError("unit: %s"%unit)
def compareEndPoints(self,other,which):
if which=="startToStart":
diff=self._rangeObj.Start-other._rangeObj.Start
elif which=="startToEnd":
diff=self._rangeObj.Start-other._rangeObj.End
elif which=="endToStart":
diff=self._rangeObj.End-other._rangeObj.Start
elif which=="endToEnd":
diff=self._rangeObj.End-other._rangeObj.End
else:
raise ValueError("bad argument - which: %s"%which)
if diff<0:
diff=-1
elif diff>0:
diff=1
return diff
def setEndPoint(self,other,which):
if which=="startToStart":
self._rangeObj.Start=other._rangeObj.Start
elif which=="startToEnd":
self._rangeObj.Start=other._rangeObj.End
elif which=="endToStart":
self._rangeObj.End=other._rangeObj.Start
elif which=="endToEnd":
self._rangeObj.End=other._rangeObj.End
else:
raise ValueError("bad argument - which: %s"%which)
def _get_isCollapsed(self):
if self._rangeObj.Start==self._rangeObj.End:
return True
else:
return False
def collapse(self,end=False):
a=self._rangeObj.Start
b=self._rangeObj.end
startOffset=min(a,b)
endOffset=max(a,b)
if not end:
offset=startOffset
else:
offset=endOffset
self._rangeObj.SetRange(offset,offset)
def copy(self):
return ITextDocumentTextInfo(self.obj,None,_rangeObj=self._rangeObj)
def _get_text(self):
return self._getTextAtRange(self._rangeObj)
def move(self,unit,direction,endPoint=None):
if unit in NVDAUnitsToITextDocumentUnits:
unit=NVDAUnitsToITextDocumentUnits[unit]
else:
raise NotImplementedError("unit: %s"%unit)
if endPoint=="start":
moveFunc=self._rangeObj.MoveStart
elif endPoint=="end":
moveFunc=self._rangeObj.MoveEnd
else:
moveFunc=self._rangeObj.Move
res=moveFunc(unit,direction)
return res
def _get_bookmark(self):
return textInfos.offsets.Offsets(self._rangeObj.start,self._rangeObj.end)
def updateCaret(self):
self.obj.ITextSelectionObject.start=self.obj.ITextSelectionObject.end=self._rangeObj.start
def updateSelection(self):
self.obj.ITextSelectionObject.start=self._rangeObj.start
self.obj.ITextSelectionObject.end=self._rangeObj.end
class Edit(EditableTextWithAutoSelectDetection, Window):
editAPIVersion=0
editAPIUnicode=True
useITextDocumentSupport=False
editValueUnit=textInfos.UNIT_LINE
def _get_TextInfo(self):
if self.editAPIVersion>1 and (self.useITextDocumentSupport or self.windowClassName.endswith('PT')) and self.ITextDocumentObject:
return ITextDocumentTextInfo
else:
return EditTextInfo
def _get_ITextDocumentObject(self):
if not hasattr(self,'_ITextDocumentObject'):
try:
ptr=ctypes.POINTER(comInterfaces.tom.ITextDocument)()
ctypes.windll.oleacc.AccessibleObjectFromWindow(self.windowHandle,-16,ctypes.byref(ptr._iid_),ctypes.byref(ptr))
self._ITextDocumentObject=ptr
except:
log.error("Error getting ITextDocument",exc_info=True)
self._ITextDocumentObject=None
return self._ITextDocumentObject
def _get_ITextSelectionObject(self):
if not hasattr(self,'_ITextSelectionObject'):
try:
self._ITextSelectionObject=self.ITextDocumentObject.selection
except:
self._ITextSelectionObject=None
return self._ITextSelectionObject
def _get_value(self):
return None
def _get_role(self):
return controlTypes.ROLE_EDITABLETEXT
def event_caret(self):
global selOffsetsAtLastCaretEvent
#Fetching formatting and calculating word offsets needs to move the caret, so try to ignore these events
selOffsets=self.makeTextInfo(textInfos.POSITION_SELECTION).bookmark
if selOffsets==selOffsetsAtLastCaretEvent:
return
selOffsetsAtLastCaretEvent=selOffsets
#Make sure that this object *really* has the focus before bothering to speak any possible selection change
api.processPendingEvents()
if self is not api.getFocusObject() or eventHandler.isPendingEvents('gainFocus'):
return
if eventHandler.isPendingEvents('valueChange',self):
self.hasContentChangedSinceLastSelection=True
super(Edit,self).event_caret()
self.detectPossibleSelectionChange()
def event_valueChange(self):
self.event_textChange()
def _get_states(self):
states = super(Edit, self)._get_states()
if self.windowStyle & winUser.ES_MULTILINE:
states.add(controlTypes.STATE_MULTILINE)
return states
class RichEdit(Edit):
editAPIVersion=1
class RichEdit20(RichEdit):
editAPIVersion=2
class RichEdit30(RichEdit):
editAPIVersion=3
class RichEdit50(RichEdit):
editAPIVersion=5
|