ia2TextMozilla.py 20.4 KB
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
#NVDAObjects/IAccessible/ia2TextMozilla.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2015-2016 NV Access Limited

"""Support for the IAccessible2 rich text model first implemented by Mozilla.
This is now used by other applications as well.
"""

import itertools
from comtypes import COMError
import winUser
import textInfos
import controlTypes
import IAccessibleHandler
import api
from NVDAObjects import NVDAObject, NVDAObjectTextInfo
from . import IA2TextTextInfo, IAccessible
from compoundDocuments import CompoundTextInfo

class FakeEmbeddingTextInfo(textInfos.offsets.OffsetsTextInfo):

	def _getStoryLength(self):
		return self.obj.childCount

	def _iterTextWithEmbeddedObjects(self, withFields, formatConfig=None):
		return xrange(self._startOffset, self._endOffset)

	def _getUnitOffsets(self,unit,offset):
		if unit in (textInfos.UNIT_WORD,textInfos.UNIT_LINE):
			unit=textInfos.UNIT_CHARACTER
		return super(FakeEmbeddingTextInfo,self)._getUnitOffsets(unit,offset)

def _getRawTextInfo(obj):
	if not hasattr(obj, "IAccessibleTextObject") and obj.role in (controlTypes.ROLE_TABLE, controlTypes.ROLE_TABLEROW):
		return FakeEmbeddingTextInfo
	elif obj.TextInfo is NVDAObjectTextInfo:
		return NVDAObjectTextInfo
	return IA2TextTextInfo

def _getEmbedded(obj, offset):
	if not hasattr(obj, "IAccessibleTextObject"):
		return obj.getChild(offset)
	# Mozilla uses IAccessibleHypertext to facilitate quick retrieval of embedded objects.
	try:
		ht = obj.iaHypertext
		hi = ht.hyperlinkIndex(offset)
		if hi != -1:
			hl = ht.hyperlink(hi)
			return IAccessible(IAccessibleObject=hl.QueryInterface(IAccessibleHandler.IAccessible2), IAccessibleChildID=0)
	except COMError:
		pass
	return None

class MozillaCompoundTextInfo(CompoundTextInfo):

	def __init__(self, obj, position):
		super(MozillaCompoundTextInfo, self).__init__(obj, position)
		if isinstance(position, NVDAObject):
			# FIXME
			position = textInfos.POSITION_CARET
		if isinstance(position, self.__class__):
			self._start = position._start.copy()
			self._startObj = position._startObj
			if position._end is position._start:
				self._end = self._start
			else:
				self._end = position._end.copy()
			self._endObj = position._endObj
		elif position in (textInfos.POSITION_FIRST, textInfos.POSITION_LAST):
			self._start, self._startObj = self._findContentDescendant(obj, position)
			self._end = self._start
			self._endObj = self._startObj
		elif position == textInfos.POSITION_ALL:
			self._start, self._startObj = self._findContentDescendant(obj, textInfos.POSITION_FIRST)
			self._start.expand(textInfos.UNIT_STORY)
			self._end, self._endObj = self._findContentDescendant(obj, textInfos.POSITION_LAST)
			self._end.expand(textInfos.UNIT_STORY)
		elif position == textInfos.POSITION_CARET:
			try:
				caretTi, caretObj = self._findContentDescendant(obj, textInfos.POSITION_CARET)
			except LookupError:
				raise RuntimeError("No caret")
			if caretObj is not obj and caretObj.IA2Attributes.get("display") == "inline" and caretTi.compareEndPoints(self._makeRawTextInfo(caretObj, textInfos.POSITION_ALL), "startToEnd") == 0:
				# The caret is at the end of an inline object.
				# This will report "blank", but we want to report the character just after the caret.
				try:
					caretTi, caretObj = self._findNextContent(caretTi)
				except LookupError:
					pass
			self._start = self._end = caretTi
			self._startObj = self._endObj = caretObj
		elif position == textInfos.POSITION_SELECTION:
			# The caret is usually within the selection,
			# so start from the caret for better performance/tolerance of server brokenness.
			tempTi, tempObj = self._findContentDescendant(obj, textInfos.POSITION_CARET)
			try:
				tempTi = self._makeRawTextInfo(tempObj, position)
			except RuntimeError:
				# The caret is just before this object.
				# There is never a selection in this case.
				pass
			else:
				if tempTi.isCollapsed:
					# No selection, but perhaps the caret is at the start of the next/previous object.
					# This happens when you, for example, press shift+rightArrow at the end of a block.
					# Try from the root.
					rootTi = self._makeRawTextInfo(obj, position)
					if not rootTi.isCollapsed:
						# There is definitely a selection.
						tempTi, tempObj = rootTi, obj
			if tempTi.isCollapsed:
				# No selection, so use the caret.
				self._start = self._end = tempTi
				self._startObj = self._endObj = tempObj
			else:
				self._start, self._startObj, self._end, self._endObj = self._findUnitEndpoints(tempTi, position)
		elif isinstance(position, textInfos.Point):
			startObj = api.getDesktopObject().objectFromPoint(position.x, position.y)
			while startObj and startObj.role == controlTypes.ROLE_STATICTEXT:
				# Skip text leaf nodes.
				startObj = startObj.parent
			if not startObj:
				raise LookupError
			self._startObj = startObj
			self._start = self._makeRawTextInfo(startObj, position)
			self._end = self._start
			self._endObj = self._startObj
		else:
			raise NotImplementedError

	def _makeRawTextInfo(self, obj, position):
		return _getRawTextInfo(obj)(obj, position)

	def _getEmbedding(self, obj):
		# optimisation: Passing an Offsets position checks nCharacters, which is an extra call we don't need.
		info = self._makeRawTextInfo(obj.parent, textInfos.POSITION_FIRST)
		if isinstance(info, FakeEmbeddingTextInfo):
			info._startOffset = obj.indexInParent
			info._endOffset = info._startOffset + 1
			return info
		try:
			hl = obj.IAccessibleObject.QueryInterface(IAccessibleHandler.IAccessibleHyperlink)
			hlOffset = hl.startIndex
			info._startOffset = hlOffset
			info._endOffset = hlOffset + 1
			return info
		except COMError:
			pass
		return None

	POSITION_SELECTION_START = 3
	POSITION_SELECTION_END = 4
	FINDCONTENTDESCENDANT_POSITIONS = {
		textInfos.POSITION_FIRST: 0,
		textInfos.POSITION_CARET: 1,
		textInfos.POSITION_LAST: 2,
	}
	def _findContentDescendant(self, obj, position):
		import ctypes
		import NVDAHelper
		import NVDAObjects.IAccessible
		descendantID=ctypes.c_int()
		descendantOffset=ctypes.c_int()
		what = self.FINDCONTENTDESCENDANT_POSITIONS.get(position, position)
		NVDAHelper.localLib.nvdaInProcUtils_IA2Text_findContentDescendant(obj.appModule.helperLocalBindingHandle,obj.windowHandle,obj.IAccessibleObject.uniqueID,what,ctypes.byref(descendantID),ctypes.byref(descendantOffset))
		if descendantID.value == 0:
			# No descendant.
			raise LookupError("Object has no text descendants")
		if position == self.POSITION_SELECTION_END:
			# As we descend, we need the last offset (not the exclusive end offset),
			# but we want the exclusive end as the final result.
			descendantOffset.value += 1
		# optimisation: If we already have the target obj, don't make a new instance.
		for cached in obj, getattr(self.obj, "_lastCaretObj", None):
			if cached and descendantID.value == cached.IA2UniqueID:
				obj = cached
				break
		else:
			obj=NVDAObjects.IAccessible.getNVDAObjectFromEvent(obj.windowHandle,winUser.OBJID_CLIENT,descendantID.value)
		if position == textInfos.POSITION_CARET:
			# Cache for later use.
			self.obj._lastCaretObj = obj
		# optimisation: Passing an Offsets position checks nCharacters, which is an extra call we don't need.
		ti=self._makeRawTextInfo(obj,textInfos.POSITION_FIRST)
		ti._startOffset=ti._endOffset=descendantOffset.value
		return ti,obj

	def _iterRecursiveText(self, ti, controlStack, formatConfig):
		if ti.obj == self._endObj:
			end = True
			ti.setEndPoint(self._end, "endToEnd")
		else:
			end = False

		for item in ti._iterTextWithEmbeddedObjects(controlStack is not None, formatConfig=formatConfig):
			if item is None:
				yield u""
			elif isinstance(item, basestring):
				yield item
			elif isinstance(item, int): # Embedded object.
				embedded = _getEmbedded(ti.obj, item)
				if controlStack is not None:
					controlField = self._getControlFieldForObject(embedded)
					controlStack.append(controlField)
					if controlField:
						controlField["_startOfNode"] = True
						yield textInfos.FieldCommand("controlStart", controlField)
				if _getRawTextInfo(embedded) is NVDAObjectTextInfo: # No text
					yield embedded.basicText
				else:
					for subItem in self._iterRecursiveText(self._makeRawTextInfo(embedded, textInfos.POSITION_ALL), controlStack, formatConfig):
						yield subItem
						if subItem is None:
							return
				if controlStack is not None and controlField:
					controlField["_endOfNode"] = True
					del controlStack[-1]
					yield textInfos.FieldCommand("controlEnd", None)
			else:
				yield item

		if end:
			# None means the end has been reached and text retrieval should stop.
			yield None

	def _getText(self, withFields, formatConfig=None):
		fields = []
		if self.isCollapsed:
			return fields

		if withFields:
			# Get the initial control fields.
			controlStack = []
			rootObj = self.obj
			obj = self._startObj
			ti = self._start
			cannotBeStart = False
			while obj and obj != rootObj:
				field = self._getControlFieldForObject(obj)
				if field:
					if ti._startOffset == 0:
						if not cannotBeStart:
							field["_startOfNode"] = True
					else:
						# We're not at the start of this object, which also means we're not at the start of any ancestors.
						cannotBeStart = True
					fields.insert(0, textInfos.FieldCommand("controlStart", field))
				controlStack.insert(0, field)
				ti = self._getEmbedding(obj)
				obj = ti.obj
		else:
			controlStack = None

		# Get the fields for start.
		fields += list(self._iterRecursiveText(self._start, controlStack, formatConfig))
		if not fields:
			# We're not getting anything, so the object must be dead.
			# (We already handled collapsed above.)
			return fields
		obj = self._startObj
		while fields[-1] is not None:
			# The end hasn't yet been reached, which means it isn't a descendant of obj.
			# Therefore, continue from where obj was embedded.
			if withFields:
				field = controlStack.pop()
				if field:
					# This object had a control field.
					field["_endOfNode"] = True
					fields.append(textInfos.FieldCommand("controlEnd", None))
			ti = self._getEmbedding(obj)
			obj = ti.obj
			if ti.move(textInfos.UNIT_OFFSET, 1) == 0:
				# There's no more text in this object.
				continue
			ti.setEndPoint(self._makeRawTextInfo(obj, textInfos.POSITION_ALL), "endToEnd")
			fields.extend(self._iterRecursiveText(ti, controlStack, formatConfig))
		del fields[-1]

		if withFields:
			# Determine whether the range covers the end of any ancestors of endObj.
			obj = self._endObj
			ti = self._end
			while obj and obj != rootObj:
				field = controlStack.pop()
				if field:
					fields.append(textInfos.FieldCommand("controlEnd", None))
					if ti.compareEndPoints(self._makeRawTextInfo(obj, textInfos.POSITION_ALL), "endToEnd") == 0:
						field["_endOfNode"] = True
					else:
						# We're not at the end of this object, which also means we're not at the end of any ancestors.
						break
				ti = self._getEmbedding(obj)
				obj = ti.obj

		return fields

	def _get_text(self):
		return "".join(self._getText(False))

	def getTextWithFields(self, formatConfig=None):
		return self._getText(True, formatConfig)

	def _findUnitEndpoints(self, baseTi, unit, findStart=True, findEnd=True):
		start = startObj = end = endObj = None
		baseTi.collapse()
		obj = baseTi.obj

		# Walk up the hierarchy until we find the start and end points.
		while True:
			if unit == textInfos.POSITION_SELECTION:
				expandTi = self._makeRawTextInfo(obj, unit)
			else:
				expandTi = baseTi.copy()
				expandTi.expand(unit)
				if expandTi.isCollapsed:
					# This shouldn't happen, but can due to server implementation bugs; e.g. MozillaBug:1149415.
					expandTi.expand(textInfos.UNIT_OFFSET)
			allTi = self._makeRawTextInfo(obj, textInfos.POSITION_ALL)

			if not start and findStart and expandTi.compareEndPoints(allTi, "startToStart") != 0:
				# The unit definitely starts within this object.
				start = expandTi
				startObj = start.obj
				if unit == textInfos.POSITION_SELECTION:
					startDescPos = self.POSITION_SELECTION_START
				elif baseTi.compareEndPoints(expandTi, "startToStart") == 0:
					startDescPos = textInfos.POSITION_FIRST
				else:
					# The unit expands beyond the base point,
					# so only include the nearest descendant unit.
					startDescPos = textInfos.POSITION_LAST

			if not end and findEnd and expandTi.compareEndPoints(allTi, "endToEnd") != 0:
				# The unit definitely ends within this object.
				end = expandTi
				endObj = end.obj
				if unit == textInfos.POSITION_SELECTION:
					endDescPos = self.POSITION_SELECTION_END
				elif baseTi.compareEndPoints(expandTi, "endToEnd") == 0:
					endDescPos = textInfos.POSITION_LAST
				else:
					# The unit expands beyond the base point,
					# so only include the nearest descendant unit.
					endDescPos = textInfos.POSITION_FIRST

			if (start or not findStart) and (end or not findEnd):
				# Required endpoint(s) have been found, so stop walking.
				break

			# start and/or end hasn't yet been found,
			# so it must be higher in the hierarchy.
			if obj == self.obj:
				# We're at the root. Don't go any further.
				embedTi = None
			else:
				embedTi = self._getEmbedding(obj)
				if isinstance(embedTi, FakeEmbeddingTextInfo):
					# hack: Selection in Mozilla table/table rows is broken (MozillaBug:1169238), so just ignore it.
					embedTi = None
			if not embedTi:
				# There is no embedding object.
				# The unit starts and/or ends at the start and/or end of this last object.
				if findStart and not start:
					start = expandTi
					startObj = start.obj
					if unit == textInfos.POSITION_SELECTION:
						startDescPos = self.POSITION_SELECTION_START
					elif baseTi.compareEndPoints(expandTi, "startToStart") == 0:
						startDescPos = textInfos.POSITION_FIRST
					else:
						# The unit expands beyond the base point,
						# so only include the nearest descendant unit.
						startDescPos = textInfos.POSITION_LAST
				if findEnd and not end:
					end = expandTi
					endObj = end.obj
					if unit == textInfos.POSITION_SELECTION:
						endDescPos = self.POSITION_SELECTION_END
					elif baseTi.compareEndPoints(expandTi, "endToEnd") == 0:
						endDescPos = textInfos.POSITION_LAST
					else:
						# The unit expands beyond the base point,
						# so only include the nearest descendant unit.
						endDescPos = textInfos.POSITION_FIRST
				break

			obj = embedTi.obj
			baseTi = embedTi

		if findStart:
			embedded = _getEmbedded(startObj, start._startOffset)
			if embedded:
				try:
					start, startObj = self._findContentDescendant(embedded, startDescPos)
				except LookupError:
					# No text descendants, so we don't descend.
					pass
				else:
					if unit == textInfos.POSITION_SELECTION:
						start = self._makeRawTextInfo(startObj, unit)
					else:
						start.expand(unit)
			if not findEnd:
				return start, startObj
		if findEnd:
			embedded = _getEmbedded(endObj, end._endOffset - 1)
			if embedded:
				try:
					end, endObj = self._findContentDescendant(embedded, endDescPos)
				except LookupError:
					# No text descendants, so we don't descend.
					pass
				else:
					if unit == textInfos.POSITION_SELECTION:
						end = self._makeRawTextInfo(endObj, unit)
					else:
						end.expand(unit)
			if not findStart:
				return end, endObj

		return start, startObj, end, endObj

	def expand(self, unit):
		if unit in ( textInfos.UNIT_CHARACTER, textInfos.UNIT_OFFSET):
			self._end = self._start
			self._endObj = self._startObj
			self._start.expand(unit)
			return

		start, startObj, end, endObj = self._findUnitEndpoints(self._start, unit)
		if startObj == endObj:
			end = start
			endObj = startObj

		self._start = start
		self._startObj = startObj
		self._end = end
		self._endObj = endObj

	def _findNextContent(self, origin, moveBack=False):
		if isinstance(origin, textInfos.TextInfo):
			ti = origin
			obj = ti.obj
		else:
			ti = None
			obj = origin

		# Ascend until we can move to the next offset.
		direction = -1 if moveBack else 1
		while True:
			if ti and ti.move(textInfos.UNIT_OFFSET, direction) != 0:
				break
			if obj == self.obj:
				# We're at the root. Don't go any further.
				raise LookupError
			ti = self._getEmbedding(obj)
			if not ti:
				raise LookupError
			obj = ti.obj

		embedded = _getEmbedded(obj, ti._startOffset)
		if embedded:
			try:
				return self._findContentDescendant(embedded, textInfos.POSITION_LAST if moveBack else textInfos.POSITION_FIRST)
			except LookupError:
				# No text descendants, so we don't descend.
				pass
		return ti, obj

	def move(self, unit, direction, endPoint=None):
		if direction == 0:
			return 0

		if not endPoint or endPoint == "start":
			moveTi = self._start
			moveObj = self._startObj
			if endPoint and moveTi is self._end:
				# We're just moving start. We don't want end to be affected.
				moveTi = moveTi.copy()
			moveTi.collapse()
		elif endPoint == "end":
			moveTi = self._end
			moveObj = self._endObj
			if endPoint and moveTi is self._start:
				# We're just moving end. We don't want start to be affected.
				moveTi = moveTi.copy()
			moveTi.collapse(end=True)
			if moveTi.compareEndPoints(self._makeRawTextInfo(moveObj, textInfos.POSITION_ALL), "endToEnd") == 0:
				# We're at the end of the object, so move to the start of the next.
				try:
					moveTi, moveObj = self._findNextContent(moveObj)
				except LookupError:
					# Can't move forward any further.
					return 0

		remainingMovement = direction
		moveBack = direction < 0
		while remainingMovement != 0:
			if moveBack:
				# Move back 1 offset to move into the previous unit.
				try:
					moveTi, moveObj = self._findNextContent(moveTi, moveBack=True)
				except LookupError:
					# Can't move back any further.
					break

			# Find the edge of the current unit in the requested direction.
			moveTi, moveObj = self._findUnitEndpoints(moveTi, unit, findStart=moveBack, findEnd=not moveBack)

			if not moveBack:
				# Collapse to the start of the next unit.
				moveTi.collapse(end=True)
				if moveTi.compareEndPoints(self._makeRawTextInfo(moveObj, textInfos.POSITION_ALL), "endToEnd") == 0:
					# We're at the end of the object.
					if remainingMovement == 1 and endPoint == "end":
						# We've moved the required number of units.
						# Stop here, as we don't want end to be the start of the next object,
						# which would cause bogus control fields to be emitted.
						remainingMovement -= 1
						break
					# We haven't finished moving, so move to the start of the next object.
					try:
						moveTi, moveObj = self._findNextContent(moveObj)
					except LookupError:
						# Can't move forward any further.
						if endPoint == "end" and moveTi.compareEndPoints(self._end, "endToEnd") != 0:
							# Moving the end to the end of the document counts as a move.
							remainingMovement -= 1
						break
				else:
					# We may have landed on an embedded object.
					embedded = _getEmbedded(moveObj, moveTi._startOffset)
					if embedded:
						try:
							moveTi, moveObj = self._findContentDescendant(embedded, textInfos.POSITION_FIRST)
						except LookupError:
							# No text descendants, so we don't descend.
							pass

			remainingMovement -= -1 if moveBack else 1

		if not endPoint or endPoint == "start":
			self._start = moveTi
			self._startObj = moveObj
		if not endPoint or endPoint == "end":
			self._end = moveTi
			self._endObj = moveObj
		self._normalizeStartAndEnd()
		return direction - remainingMovement

	def _getAncestors(self, ti, obj):
		data = []
		while True:
			data.insert(0, (ti, obj))
			if obj == self.obj:
				# We're at the root. Don't go any further.
				break
			ti = self._getEmbedding(obj)
			if not ti:
				break
			obj = ti.obj
		return data

	def compareEndPoints(self, other, which):
		if which in ("startToStart", "startToEnd"):
			selfTi = self._start
			selfObj = self._startObj
		else:
			selfTi = self._end
			selfObj = self._endObj
		if which in ("startToStart", "endToStart"):
			otherTi = other._start
			otherObj = other._startObj
		else:
			otherTi = other._end
			otherObj = other._endObj

		if selfObj == otherObj:
			# Same object, so just compare the two TextInfos normally.
			return selfTi.compareEndPoints(otherTi, which)

		# Different objects, so we have to compare ancestors.
		selfAncs = self._getAncestors(selfTi, selfObj)
		otherAncs = self._getAncestors(otherTi, otherObj)
		# Find the first common ancestor.
		maxAncIndex = min(len(selfAncs), len(otherAncs)) - 1
		for (selfAncTi, selfAncObj), (otherAncTi, otherAncObj) in itertools.izip(selfAncs[maxAncIndex::-1], otherAncs[maxAncIndex::-1]):
			if selfAncObj == otherAncObj:
				break
		else:
			# No common ancestor.
			return 1
		return selfAncTi.compareEndPoints(otherAncTi, which)