Search is not available for this dataset
text stringlengths 75 104k |
|---|
def GetPixelColorsHorizontally(self, x: int, y: int, count: int) -> ctypes.Array:
"""
x: int.
y: int.
count: int.
Return `ctypes.Array`, an iterable array of int values in argb form point x,y horizontally.
"""
arrayType = ctypes.c_uint32 * count
values = arrayType()
_DllClient.instance().dll.BitmapGetPixelsHorizontally(ctypes.c_size_t(self._bitmap), x, y, values, count)
return values |
def SetPixelColorsHorizontally(self, x: int, y: int, colors: Iterable) -> bool:
"""
Set pixel colors form x,y horizontally.
x: int.
y: int.
colors: Iterable, an iterable list of int color values in argb.
Return bool, True if succeed otherwise False.
"""
count = len(colors)
arrayType = ctypes.c_uint32 * count
values = arrayType(*colors)
return _DllClient.instance().dll.BitmapSetPixelsHorizontally(ctypes.c_size_t(self._bitmap), x, y, values, count) |
def GetPixelColorsVertically(self, x: int, y: int, count: int) -> ctypes.Array:
"""
x: int.
y: int.
count: int.
Return `ctypes.Array`, an iterable array of int values in argb form point x,y vertically.
"""
arrayType = ctypes.c_uint32 * count
values = arrayType()
_DllClient.instance().dll.BitmapGetPixelsVertically(ctypes.c_size_t(self._bitmap), x, y, values, count)
return values |
def GetPixelColorsOfRow(self, y: int) -> ctypes.Array:
"""
y: int, row index.
Return `ctypes.Array`, an iterable array of int values in argb of y row.
"""
return self.GetPixelColorsOfRect(0, y, self.Width, 1) |
def GetPixelColorsOfColumn(self, x: int) -> ctypes.Array:
"""
x: int, column index.
Return `ctypes.Array`, an iterable array of int values in argb of x column.
"""
return self.GetPixelColorsOfRect(x, 0, 1, self.Height) |
def GetPixelColorsOfRect(self, x: int, y: int, width: int, height: int) -> ctypes.Array:
"""
x: int.
y: int.
width: int.
height: int.
Return `ctypes.Array`, an iterable array of int values in argb of the input rect.
"""
arrayType = ctypes.c_uint32 * (width * height)
values = arrayType()
_DllClient.instance().dll.BitmapGetPixelsOfRect(ctypes.c_size_t(self._bitmap), x, y, width, height, values)
return values |
def SetPixelColorsOfRect(self, x: int, y: int, width: int, height: int, colors: Iterable) -> bool:
"""
x: int.
y: int.
width: int.
height: int.
colors: Iterable, an iterable list of int values, it's length must equal to width*height.
Return `ctypes.Array`, an iterable array of int values in argb of the input rect.
"""
arrayType = ctypes.c_uint32 * (width * height)
values = arrayType(*colors)
return bool(_DllClient.instance().dll.BitmapSetPixelsOfRect(ctypes.c_size_t(self._bitmap), x, y, width, height, values)) |
def GetPixelColorsOfRects(self, rects: list) -> list:
"""
rects: a list of rects, such as [(0,0,10,10), (10,10,20,20),(x,y,width,height)].
Return list, a list whose elements are ctypes.Array which is an iterable array of int values in argb.
"""
rects2 = [(x, y, x + width, y + height) for x, y, width, height in rects]
left, top, right, bottom = zip(*rects2)
left, top, right, bottom = min(left), min(top), max(right), max(bottom)
width, height = right - left, bottom - top
allColors = self.GetPixelColorsOfRect(left, top, width, height)
colorsOfRects = []
for x, y, w, h in rects:
x -= left
y -= top
colors = []
for row in range(h):
colors.extend(allColors[(y + row) * width + x:(y + row) * width + x + w])
colorsOfRects.append(colors)
return colorsOfRects |
def GetAllPixelColors(self) -> ctypes.Array:
"""
Return `ctypes.Array`, an iterable array of int values in argb.
"""
return self.GetPixelColorsOfRect(0, 0, self.Width, self.Height) |
def GetSubBitmap(self, x: int, y: int, width: int, height: int) -> 'Bitmap':
"""
x: int.
y: int.
width: int.
height: int.
Return `Bitmap`, a sub bitmap of the input rect.
"""
colors = self.GetPixelColorsOfRect(x, y, width, height)
bitmap = Bitmap(width, height)
bitmap.SetPixelColorsOfRect(0, 0, width, height, colors)
return bitmap |
def Navigate(self, direction: int) -> 'Control':
"""
Call IUIAutomationCustomNavigationPattern::Navigate.
Get the next control in the specified direction within the logical UI tree.
direction: int, a value in class `NavigateDirection`.
Return `Control` subclass or None.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationcustomnavigationpattern-navigate
"""
ele = self.pattern.Navigate(direction)
return Control.CreateControlFromElement(ele) |
def SetDockPosition(self, dockPosition: int, waitTime: float = OPERATION_WAIT_TIME) -> int:
"""
Call IUIAutomationDockPattern::SetDockPosition.
dockPosition: int, a value in class `DockPosition`.
waitTime: float.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdockpattern-setdockposition
"""
ret = self.pattern.SetDockPosition(dockPosition)
time.sleep(waitTime)
return ret |
def GetGrabbedItems(self) -> list:
"""
Call IUIAutomationDragPattern::GetCurrentGrabbedItems.
Return list, a list of `Control` subclasses that represent the full set of items
that the user is dragging as part of a drag operation.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-getcurrentgrabbeditems
"""
eleArray = self.pattern.GetCurrentGrabbedItems()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def Expand(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationExpandCollapsePattern::Expand.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-collapse
"""
ret = self.pattern.Expand() == S_OK
time.sleep(waitTime)
return ret |
def FindItemByProperty(control: 'Control', propertyId: int, propertyValue) -> 'Control':
"""
Call IUIAutomationItemContainerPattern::FindItemByProperty.
control: `Control` or its subclass.
propertyValue: COM VARIANT according to propertyId? todo.
propertyId: int, a value in class `PropertyId`.
Return `Control` subclass, a control within a containing element, based on a specified property value.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationitemcontainerpattern-finditembyproperty
"""
ele = self.pattern.FindItemByProperty(control.Element, propertyId, propertyValue)
return Control.CreateControlFromElement(ele) |
def GetSelection(self) -> list:
"""
Call IUIAutomationLegacyIAccessiblePattern::GetCurrentSelection.
Return list, a list of `Control` subclasses,
the Microsoft Active Accessibility property that identifies the selected children of this element.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-getcurrentselection
"""
eleArray = self.pattern.GetCurrentSelection()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def SetValue(self, value: str, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationLegacyIAccessiblePattern::SetValue.
Set the Microsoft Active Accessibility value property for the element.
value: str.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-setvalue
"""
ret = self.pattern.SetValue(value) == S_OK
time.sleep(waitTime)
return ret |
def SetView(self, view: int) -> bool:
"""
Call IUIAutomationMultipleViewPattern::SetCurrentView.
Set the view of the control.
view: int, the control-specific view identifier.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationmultipleviewpattern-getviewname
"""
return self.pattern.SetCurrentView(view) == S_OK |
def Scroll(self, horizontalAmount: int, verticalAmount: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationScrollPattern::Scroll.
Scroll the visible region of the content area horizontally and vertically.
horizontalAmount: int, a value in ScrollAmount.
verticalAmount: int, a value in ScrollAmount.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-scroll
"""
ret = self.pattern.Scroll(horizontalAmount, verticalAmount) == S_OK
time.sleep(waitTime)
return ret |
def SetScrollPercent(self, horizontalPercent: float, verticalPercent: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationScrollPattern::SetScrollPercent.
Set the horizontal and vertical scroll positions as a percentage of the total content area within the UI Automation element.
horizontalPercent: float or int, a value in [0, 100] or ScrollPattern.NoScrollValue(-1) if no scroll.
verticalPercent: float or int, a value in [0, 100] or ScrollPattern.NoScrollValue(-1) if no scroll.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollpattern-setscrollpercent
"""
ret = self.pattern.SetScrollPercent(horizontalPercent, verticalPercent) == S_OK
time.sleep(waitTime)
return ret |
def GetAnnotationObjects(self) -> list:
"""
Call IUIAutomationSelectionPattern::GetCurrentAnnotationObjects.
Return list, a list of `Control` subclasses representing the annotations associated with this spreadsheet cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetitempattern-getcurrentannotationobjects
"""
eleArray = self.pattern.GetCurrentAnnotationObjects()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def GetItemByName(self, name: str) -> 'Control':
"""
Call IUIAutomationSpreadsheetPattern::GetItemByName.
name: str.
Return `Control` subclass or None, represents the spreadsheet cell that has the specified name..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationspreadsheetpattern-getitembyname
"""
ele = self.pattern.GetItemByName(name)
return Control.CreateControlFromElement(element=ele) |
def GetColumnHeaderItems(self) -> list:
"""
Call IUIAutomationTableItemPattern::GetCurrentColumnHeaderItems.
Return list, a list of `Control` subclasses, the column headers associated with a table item or cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtableitempattern-getcurrentcolumnheaderitems
"""
eleArray = self.pattern.GetCurrentColumnHeaderItems()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def GetRowHeaderItems(self) -> list:
"""
Call IUIAutomationTableItemPattern::GetCurrentRowHeaderItems.
Return list, a list of `Control` subclasses, the row headers associated with a table item or cell.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtableitempattern-getcurrentrowheaderitems
"""
eleArray = self.pattern.GetCurrentRowHeaderItems()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def GetColumnHeaders(self) -> list:
"""
Call IUIAutomationTablePattern::GetCurrentColumnHeaders.
Return list, a list of `Control` subclasses, representing all the column headers in a table..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern-getcurrentcolumnheaders
"""
eleArray = self.pattern.GetCurrentColumnHeaders()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def GetRowHeaders(self) -> list:
"""
Call IUIAutomationTablePattern::GetCurrentRowHeaders.
Return list, a list of `Control` subclasses, representing all the row headers in a table.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern-getcurrentrowheaders
"""
eleArray = self.pattern.GetCurrentRowHeaders()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def Compare(self, textRange: 'TextRange') -> bool:
"""
Call IUIAutomationTextRange::Compare.
textRange: `TextRange`.
Return bool, specifies whether this text range has the same endpoints as another text range.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-compare
"""
return bool(self.textRange.Compare(textRange.textRange)) |
def CompareEndpoints(self, srcEndPoint: int, textRange: 'TextRange', targetEndPoint: int) -> int:
"""
Call IUIAutomationTextRange::CompareEndpoints.
srcEndPoint: int, a value in class `TextPatternRangeEndpoint`.
textRange: `TextRange`.
targetEndPoint: int, a value in class `TextPatternRangeEndpoint`.
Return int, a negative value if the caller's endpoint occurs earlier in the text than the target endpoint;
0 if the caller's endpoint is at the same location as the target endpoint;
or a positive value if the caller's endpoint occurs later in the text than the target endpoint.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-compareendpoints
"""
return self.textRange.CompareEndpoints(srcEndPoint, textRange, targetEndPoint) |
def FindAttribute(self, textAttributeId: int, val, backward: bool) -> 'TextRange':
"""
Call IUIAutomationTextRange::FindAttribute.
textAttributeID: int, a value in class `TextAttributeId`.
val: COM VARIANT according to textAttributeId? todo.
backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False.
return `TextRange` or None, a text range subset that has the specified text attribute value.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-findattribute
"""
textRange = self.textRange.FindAttribute(textAttributeId, val, int(backward))
if textRange:
return TextRange(textRange=textRange) |
def FindText(self, text: str, backward: bool, ignoreCase: bool) -> 'TextRange':
"""
Call IUIAutomationTextRange::FindText.
text: str,
backward: bool, True if the last occurring text range should be returned instead of the first; otherwise False.
ignoreCase: bool, True if case should be ignored; otherwise False.
return `TextRange` or None, a text range subset that contains the specified text.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-findtext
"""
textRange = self.textRange.FindText(text, int(backward), int(ignoreCase))
if textRange:
return TextRange(textRange=textRange) |
def GetAttributeValue(self, textAttributeId: int) -> ctypes.POINTER(comtypes.IUnknown):
"""
Call IUIAutomationTextRange::GetAttributeValue.
textAttributeId: int, a value in class `TextAttributeId`.
Return `ctypes.POINTER(comtypes.IUnknown)` or None, the value of the specified text attribute across the entire text range, todo.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-getattributevalue
"""
return self.textRange.GetAttributeValue(textAttributeId) |
def GetBoundingRectangles(self) -> list:
"""
Call IUIAutomationTextRange::GetBoundingRectangles.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Rect`.
bounding rectangles for each fully or partially visible line of text in a text range..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-getboundingrectangles
for rect in textRange.GetBoundingRectangles():
print(rect.left, rect.top, rect.right, rect.bottom, rect.width(), rect.height(), rect.xcenter(), rect.ycenter())
"""
floats = self.textRange.GetBoundingRectangles()
rects = []
for i in range(len(floats) // 4):
rect = Rect(int(floats[i * 4]), int(floats[i * 4 + 1]),
int(floats[i * 4]) + int(floats[i * 4 + 2]), int(floats[i * 4 + 1]) + int(floats[i * 4 + 3]))
rects.append(rect)
return rects |
def GetChildren(self) -> list:
"""
Call IUIAutomationTextRange::GetChildren.
textAttributeId: int, a value in class `TextAttributeId`.
Return list, a list of `Control` subclasses, embedded objects that fall within the text range..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-getchildren
"""
eleArray = self.textRange.GetChildren()
if eleArray:
controls = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
con = Control.CreateControlFromElement(element=ele)
if con:
controls.append(con)
return controls
return [] |
def Move(self, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME) -> int:
"""
Call IUIAutomationTextRange::Move.
Move the text range forward or backward by the specified number of text units.
unit: int, a value in class `TextUnit`.
count: int, the number of text units to move.
A positive value moves the text range forward.
A negative value moves the text range backward. Zero has no effect.
waitTime: float.
Return: int, the number of text units actually moved.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-move
"""
ret = self.textRange.Move(unit, count)
time.sleep(waitTime)
return ret |
def MoveEndpointByRange(self, srcEndPoint: int, textRange: 'TextRange', targetEndPoint: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTextRange::MoveEndpointByRange.
Move one endpoint of the current text range to the specified endpoint of a second text range.
srcEndPoint: int, a value in class `TextPatternRangeEndpoint`.
textRange: `TextRange`.
targetEndPoint: int, a value in class `TextPatternRangeEndpoint`.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-moveendpointbyrange
"""
ret = self.textRange.MoveEndpointByRange(srcEndPoint, textRange.textRange, targetEndPoint) == S_OK
time.sleep(waitTime)
return ret |
def MoveEndpointByUnit(self, endPoint: int, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME) -> int:
"""
Call IUIAutomationTextRange::MoveEndpointByUnit.
Move one endpoint of the text range the specified number of text units within the document range.
endPoint: int, a value in class `TextPatternRangeEndpoint`.
unit: int, a value in class `TextUnit`.
count: int, the number of units to move.
A positive count moves the endpoint forward.
A negative count moves backward.
A count of 0 has no effect.
waitTime: float.
Return int, the count of units actually moved.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-moveendpointbyunit
"""
ret = self.textRange.MoveEndpointByUnit(endPoint, unit, count)
time.sleep(waitTime)
return ret |
def ScrollIntoView(self, alignTop: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTextRange::ScrollIntoView.
Cause the text control to scroll until the text range is visible in the viewport.
alignTop: bool, True if the text control should be scrolled so that the text range is flush with the top of the viewport;
False if it should be flush with the bottom of the viewport.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-scrollintoview
"""
ret = self.textRange.ScrollIntoView(int(alignTop)) == S_OK
time.sleep(waitTime)
return ret |
def GetActiveComposition(self) -> TextRange:
"""
Call IUIAutomationTextEditPattern::GetActiveComposition.
Return `TextRange` or None, the active composition.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-getactivecomposition
"""
textRange = self.pattern.GetActiveComposition()
if textRange:
return TextRange(textRange=textRange) |
def GetConversionTarget(self) -> TextRange:
"""
Call IUIAutomationTextEditPattern::GetConversionTarget.
Return `TextRange` or None, the current conversion target range..
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtexteditpattern-getconversiontarget
"""
textRange = self.pattern.GetConversionTarget()
if textRange:
return TextRange(textRange=textRange) |
def GetVisibleRanges(self) -> list:
"""
Call IUIAutomationTextPattern::GetVisibleRanges.
Return list, a list of `TextRange`, disjoint text ranges from a text-based control
where each text range represents a contiguous span of visible text.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-getvisibleranges
"""
eleArray = self.pattern.GetVisibleRanges()
if eleArray:
textRanges = []
for i in range(eleArray.Length):
ele = eleArray.GetElement(i)
textRanges.append(TextRange(textRange=ele))
return textRanges
return [] |
def RangeFromChild(self, child) -> TextRange:
"""
Call IUIAutomationTextPattern::RangeFromChild.
child: `Control` or its subclass.
Return `TextRange` or None, a text range enclosing a child element such as an image,
hyperlink, Microsoft Excel spreadsheet, or other embedded object.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-rangefromchild
"""
textRange = self.pattern.RangeFromChild(Control.Element)
if textRange:
return TextRange(textRange=textRange) |
def RangeFromPoint(self, x: int, y: int) -> TextRange:
"""
Call IUIAutomationTextPattern::RangeFromPoint.
child: `Control` or its subclass.
Return `TextRange` or None, the degenerate (empty) text range nearest to the specified screen coordinates.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-rangefrompoint
"""
textRange = self.pattern.RangeFromPoint(ctypes.wintypes.POINT(x, y))
if textRange:
return TextRange(textRange=textRange) |
def Move(self, x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern::Move.
Move the UI Automation element.
x: int.
y: int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-move
"""
ret = self.pattern.Move(x, y) == S_OK
time.sleep(waitTime)
return ret |
def Resize(self, width: int, height: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern::Resize.
Resize the UI Automation element.
width: int.
height: int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-resize
"""
ret = self.pattern.Resize(width, height) == S_OK
time.sleep(waitTime)
return ret |
def Rotate(self, degrees: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern::Rotate.
Rotates the UI Automation element.
degrees: int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern-rotate
"""
ret = self.pattern.Rotate(degrees) == S_OK
time.sleep(waitTime)
return ret |
def Zoom(self, zoomLevel: float, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern2::Zoom.
Zoom the viewport of the control.
zoomLevel: float for int.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern2-zoom
"""
ret = self.pattern.Zoom(zoomLevel) == S_OK
time.sleep(waitTime)
return ret |
def ZoomByUnit(self, zoomUnit: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern2::ZoomByUnit.
Zoom the viewport of the control by the specified unit.
zoomUnit: int, a value in class `ZoomUnit`.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtransformpattern2-zoombyunit
"""
ret = self.pattern.ZoomByUnit(zoomUnit) == S_OK
time.sleep(waitTime)
return ret |
def SetWindowVisualState(self, state: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationWindowPattern::SetWindowVisualState.
Minimize, maximize, or restore the window.
state: int, a value in class `WindowVisualState`.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-setwindowvisualstate
"""
ret = self.pattern.SetWindowVisualState(state) == S_OK
time.sleep(waitTime)
return ret |
def WaitForInputIdle(self, milliseconds: int) -> bool:
'''
Call IUIAutomationWindowPattern::WaitForInputIdle.
Cause the calling code to block for the specified time or
until the associated process enters an idle state, whichever completes first.
milliseconds: int.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-waitforinputidle
'''
return self.pattern.WaitForInputIdle(milliseconds) == S_OK |
def CreateControlFromElement(element) -> 'Control':
"""
Create a concreate `Control` from a com type `IUIAutomationElement`.
element: `ctypes.POINTER(IUIAutomationElement)`.
Return a subclass of `Control`, an instance of the control's real type.
"""
if element:
controlType = element.CurrentControlType
if controlType in ControlConstructors:
return ControlConstructors[controlType](element=element)
else:
Logger.WriteLine("element.CurrentControlType returns {}, invalid ControlType!".format(controlType), ConsoleColor.Red) |
def AddSearchProperties(self, **searchProperties) -> None:
"""
Add search properties using `dict.update`.
searchProperties: dict, same as searchProperties in `Control.__init__`.
"""
self.searchProperties.update(searchProperties)
if 'Depth' in searchProperties:
self.searchDepth = searchProperties['Depth']
if 'RegexName' in searchProperties:
regName = searchProperties['RegexName']
self.regexName = re.compile(regName) if regName else None |
def RemoveSearchProperties(self, **searchProperties) -> None:
"""
searchProperties: dict, same as searchProperties in `Control.__init__`.
"""
for key in searchProperties:
del self.searchProperties[key]
if key == 'RegexName':
self.regexName = None |
def GetColorfulSearchPropertiesStr(self, keyColor='DarkGreen', valueColor='DarkCyan') -> str:
"""keyColor, valueColor: str, color name in class ConsoleColor"""
strs = ['<Color={}>{}</Color>: <Color={}>{}</Color>'.format(keyColor if k in Control.ValidKeys else 'DarkYellow', k, valueColor,
ControlTypeNames[v] if k == 'ControlType' else repr(v)) for k, v in self.searchProperties.items()]
return '{' + ', '.join(strs) + '}' |
def BoundingRectangle(self) -> Rect:
"""
Property BoundingRectangle.
Call IUIAutomationElement::get_CurrentBoundingRectangle.
Return `Rect`.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentboundingrectangle
rect = control.BoundingRectangle
print(rect.left, rect.top, rect.right, rect.bottom, rect.width(), rect.height(), rect.xcenter(), rect.ycenter())
"""
rect = self.Element.CurrentBoundingRectangle
return Rect(rect.left, rect.top, rect.right, rect.bottom) |
def GetClickablePoint(self) -> tuple:
"""
Call IUIAutomationElement::GetClickablePoint.
Return tuple, (x: int, y: int, gotClickable: bool), like (20, 10, True)
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getclickablepoint
"""
point, gotClickable = self.Element.GetClickablePoint()
return (point.x, point.y, bool(gotClickable)) |
def GetPattern(self, patternId: int):
"""
Call IUIAutomationElement::GetCurrentPattern.
Get a new pattern by pattern id if it supports the pattern.
patternId: int, a value in class `PatternId`.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcurrentpattern
"""
try:
pattern = self.Element.GetCurrentPattern(patternId)
if pattern:
subPattern = CreatePattern(patternId, pattern)
self._supportedPatterns[patternId] = subPattern
return subPattern
except comtypes.COMError as ex:
pass |
def GetPatternAs(self, patternId: int, riid):
"""
Call IUIAutomationElement::GetCurrentPatternAs.
Get a new pattern by pattern id if it supports the pattern, todo.
patternId: int, a value in class `PatternId`.
riid: GUID.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcurrentpatternas
"""
return self.Element.GetCurrentPatternAs(patternId, riid) |
def GetPropertyValueEx(self, propertyId: int, ignoreDefaultValue: int) -> Any:
"""
Call IUIAutomationElement::GetCurrentPropertyValueEx.
propertyId: int, a value in class `PropertyId`.
ignoreDefaultValue: int, 0 or 1.
Return Any, corresponding type according to propertyId.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getcurrentpropertyvalueex
"""
return self.Element.GetCurrentPropertyValueEx(propertyId, ignoreDefaultValue) |
def Element(self):
"""
Property Element.
Return `ctypes.POINTER(IUIAutomationElement)`.
"""
if not self._element:
self.Refind(maxSearchSeconds=TIME_OUT_SECOND, searchIntervalSeconds=self.searchWaitTime)
return self._element |
def GetCachedPattern(self, patternId: int, cache: bool):
"""
Get a pattern by patternId.
patternId: int, a value in class `PatternId`.
Return a pattern if it supports the pattern else None.
cache: bool, if True, store the pattern for later use, if False, get a new pattern by `self.GetPattern`.
"""
if cache:
pattern = self._supportedPatterns.get(patternId, None)
if pattern:
return pattern
else:
pattern = self.GetPattern(patternId)
if pattern:
self._supportedPatterns[patternId] = pattern
return pattern
else:
pattern = self.GetPattern(patternId)
if pattern:
self._supportedPatterns[patternId] = pattern
return pattern |
def GetAncestorControl(self, condition: Callable) -> 'Control':
"""
Get a ancestor control that matches the condition.
condition: Callable, function (control: Control, depth: int)->bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None.
"""
ancestor = self
depth = 0
while True:
ancestor = ancestor.GetParentControl()
depth -= 1
if ancestor:
if condition(ancestor, depth):
return ancestor
else:
break |
def GetParentControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetParentElement(self.Element)
return Control.CreateControlFromElement(ele) |
def GetFirstChildControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetFirstChildElement(self.Element)
return Control.CreateControlFromElement(ele) |
def GetLastChildControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetLastChildElement(self.Element)
return Control.CreateControlFromElement(ele) |
def GetNextSiblingControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetNextSiblingElement(self.Element)
return Control.CreateControlFromElement(ele) |
def GetPreviousSiblingControl(self) -> 'Control':
"""
Return `Control` subclass or None.
"""
ele = _AutomationClient.instance().ViewWalker.GetPreviousSiblingElement(self.Element)
return Control.CreateControlFromElement(ele) |
def GetSiblingControl(self, condition: Callable, forward: bool = True) -> 'Control':
"""
Find a SiblingControl by condition(control: Control)->bool.
forward: bool, if True, only search next siblings, if False, search pervious siblings first, then search next siblings.
condition: Callable, function (control: Control)->bool.
Return `Control` subclass or None.
"""
if not forward:
prev = self
while True:
prev = prev.GetPreviousSiblingControl()
if prev:
if condition(prev):
return prev
else:
break
next_ = self
while True:
next_ = next_.GetNextSiblingControl()
if next_:
if condition(next_):
return next_
else:
break |
def GetChildren(self) -> list:
"""
Return list, a list of `Control` subclasses.
"""
children = []
child = self.GetFirstChildControl()
while child:
children.append(child)
child = child.GetNextSiblingControl()
return children |
def _CompareFunction(self, control: 'Control', depth: int) -> bool:
"""
Define how to search.
control: `Control` or its subclass.
depth: int, tree depth from searchFromControl.
Return bool.
"""
for key, value in self.searchProperties.items():
if 'ControlType' == key:
if value != control.ControlType:
return False
elif 'ClassName' == key:
if value != control.ClassName:
return False
elif 'AutomationId' == key:
if value != control.AutomationId:
return False
elif 'Name' == key:
if value != control.Name:
return False
elif 'SubName' == key:
if value not in control.Name:
return False
elif 'RegexName' == key:
if not self.regexName.match(control.Name):
return False
elif 'Depth' == key:
if value != depth:
return False
elif 'Compare' == key:
if not value(control, depth):
return False
return True |
def Exists(self, maxSearchSeconds: float = 5, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotExist: bool = False) -> bool:
"""
maxSearchSeconds: float
searchIntervalSeconds: float
Find control every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool, True if find
"""
if self._element and self._elementDirectAssign:
#if element is directly assigned, not by searching, just check whether self._element is valid
#but I can't find an API in UIAutomation that can directly check
rootElement = GetRootControl().Element
if self._element == rootElement:
return True
else:
parentElement = _AutomationClient.instance().ViewWalker.GetParentElement(self._element)
if parentElement:
return True
else:
return False
#find the element
if len(self.searchProperties) == 0:
raise LookupError("control's searchProperties must not be empty!")
self._element = None
startTime = ProcessTime()
# Use same timeout(s) parameters for resolve all parents
prev = self.searchFromControl
if prev and not prev._element and not prev.Exists(maxSearchSeconds, searchIntervalSeconds):
if printIfNotExist or DEBUG_EXIST_DISAPPEAR:
Logger.ColorfullyWriteLine(self.GetColorfulSearchPropertiesStr() + '<Color=Red> does not exist.</Color>')
return False
startTime2 = ProcessTime()
if DEBUG_SEARCH_TIME:
startDateTime = datetime.datetime.now()
while True:
control = FindControl(self.searchFromControl, self._CompareFunction, self.searchDepth, False, self.foundIndex)
if control:
self._element = control.Element
control._element = 0 # control will be destroyed, but the element needs to be stroed in self._element
if DEBUG_SEARCH_TIME:
Logger.ColorfullyWriteLine('{} TraverseControls: <Color=Cyan>{}</Color>, SearchTime: <Color=Cyan>{:.3f}</Color>s[{} - {}]'.format(
self.GetColorfulSearchPropertiesStr(), control.traverseCount, ProcessTime() - startTime2,
startDateTime.time(), datetime.datetime.now().time()))
return True
else:
remain = startTime + maxSearchSeconds - ProcessTime()
if remain > 0:
time.sleep(min(remain, searchIntervalSeconds))
else:
if printIfNotExist or DEBUG_EXIST_DISAPPEAR:
Logger.ColorfullyWriteLine(self.GetColorfulSearchPropertiesStr() + '<Color=Red> does not exist.</Color>')
return False |
def Disappears(self, maxSearchSeconds: float = 5, searchIntervalSeconds: float = SEARCH_INTERVAL, printIfNotDisappear: bool = False) -> bool:
"""
maxSearchSeconds: float
searchIntervalSeconds: float
Check if control disappears every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool, True if control disappears.
"""
global DEBUG_EXIST_DISAPPEAR
start = ProcessTime()
while True:
temp = DEBUG_EXIST_DISAPPEAR
DEBUG_EXIST_DISAPPEAR = False # do not print for Exists
if not self.Exists(0, 0, False):
DEBUG_EXIST_DISAPPEAR = temp
return True
DEBUG_EXIST_DISAPPEAR = temp
remain = start + maxSearchSeconds - ProcessTime()
if remain > 0:
time.sleep(min(remain, searchIntervalSeconds))
else:
if printIfNotDisappear or DEBUG_EXIST_DISAPPEAR:
Logger.ColorfullyWriteLine(self.GetColorfulSearchPropertiesStr() + '<Color=Red> does not disappear.</Color>')
return False |
def Refind(self, maxSearchSeconds: float = TIME_OUT_SECOND, searchIntervalSeconds: float = SEARCH_INTERVAL, raiseException: bool = True) -> bool:
"""
Refind the control every searchIntervalSeconds seconds in maxSearchSeconds seconds.
maxSearchSeconds: float.
searchIntervalSeconds: float.
raiseException: bool, if True, raise a LookupError if timeout.
Return bool, True if find.
"""
if not self.Exists(maxSearchSeconds, searchIntervalSeconds, False if raiseException else DEBUG_EXIST_DISAPPEAR):
if raiseException:
Logger.ColorfullyWriteLine('<Color=Red>Find Control Timeout: </Color>' + self.GetColorfulSearchPropertiesStr())
raise LookupError('Find Control Timeout: ' + self.GetSearchPropertiesStr())
else:
return False
return True |
def MoveCursorToInnerPos(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True) -> tuple:
"""
Move cursor to control's internal position, default to center.
x: int, if < 0, move to self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, move to self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool.
Return tuple, two ints(x,y), the cursor positon relative to screen(0,0) after moving or None if control's width or height == 0.
"""
rect = self.BoundingRectangle
if rect.width() == 0 or rect.height() == 0:
Logger.ColorfullyWriteLine('<Color=Yellow>Can not move curosr</Color>. {}\'s BoundingRectangle is {}. SearchProperties: {}'.format(
self.ControlTypeName, rect, self.GetColorfulSearchPropertiesStr()))
return
if x is None:
x = rect.left + int(rect.width() * ratioX)
else:
x = (rect.left if x >= 0 else rect.right) + x
if y is None:
y = rect.top + int(rect.height() * ratioY)
else:
y = (rect.top if y >= 0 else rect.bottom) + y
if simulateMove and MAX_MOVE_SECOND > 0:
MoveTo(x, y, waitTime=0)
else:
SetCursorPos(x, y)
return x, y |
def MoveCursorToMyCenter(self, simulateMove: bool = True) -> tuple:
"""
Move cursor to control's center.
Return tuple, two ints tuple(x,y), the cursor positon relative to screen(0,0) after moving .
"""
return self.MoveCursorToInnerPos(simulateMove=simulateMove) |
def Click(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool, if True, first move cursor to control smoothly.
waitTime: float.
Click(), Click(ratioX=0.5, ratioY=0.5): click center.
Click(10, 10): click left+10, top+10.
Click(-10, -10): click right-10, bottom-10.
"""
point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)
if point:
Click(point[0], point[1], waitTime) |
def DoubleClick(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
x: int, if < 0, right click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, right click self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
simulateMove: bool, if True, first move cursor to control smoothly.
waitTime: float.
DoubleClick(), DoubleClick(ratioX=0.5, ratioY=0.5): double click center.
DoubleClick(10, 10): double click left+10, top+10.
DoubleClick(-10, -10): double click right-10, bottom-10.
"""
x, y = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)
Click(x, y, GetDoubleClickTime() * 1.0 / 2000)
Click(x, y, waitTime) |
def WheelDown(self, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first, move cursor to center and mouse wheel down.
wheelTimes: int.
interval: float.
waitTime: float.
"""
x, y = GetCursorPos()
self.SetFocus()
self.MoveCursorToMyCenter(False)
WheelDown(wheelTimes, interval, waitTime)
SetCursorPos(x, y) |
def ShowWindow(self, cmdShow: int, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Get a native handle from self or ancestors until valid and call native `ShowWindow` with cmdShow.
cmdShow: int, a value in in class `SW`.
waitTime: float.
Return bool, True if succeed otherwise False.
"""
handle = self.NativeWindowHandle
if not handle:
control = self
while not handle:
control = control.GetParentControl()
handle = control.NativeWindowHandle
if handle:
ret = ShowWindow(handle, cmdShow)
time.sleep(waitTime)
return ret |
def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False.
"""
return self.ShowWindow(SW.Show, waitTime) |
def Hide(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call native `ShowWindow(SW.Hide)`.
waitTime: float
Return bool, True if succeed otherwise False.
"""
return self.ShowWindow(SW.Hide, waitTime) |
def MoveWindow(self, x: int, y: int, width: int, height: int, repaint: bool = True) -> bool:
"""
Call native MoveWindow if control has a valid native handle.
x: int.
y: int.
width: int.
height: int.
repaint: bool.
Return bool, True if succeed otherwise False.
"""
handle = self.NativeWindowHandle
if handle:
return MoveWindow(handle, x, y, width, height, int(repaint))
return False |
def SetWindowText(self, text: str) -> bool:
"""
Call native SetWindowText if control has a valid native handle.
"""
handle = self.NativeWindowHandle
if handle:
return SetWindowText(handle, text)
return False |
def SendKey(self, key: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first and type a key.
`self.SetFocus` may not work for some controls, you may need to click it to make it have focus.
key: int, a key code value in class Keys.
waitTime: float.
"""
self.SetFocus()
SendKey(key, waitTime) |
def SendKeys(self, keys: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first and type keys.
`self.SetFocus` may not work for some controls, you may need to click it to make it have focus.
keys: str, keys to type, see the docstring of `SendKeys`.
interval: float, seconds between keys.
"""
self.SetFocus()
SendKeys(keys, interval, waitTime) |
def GetPixelColor(self, x: int, y: int) -> int:
"""
Call native `GetPixelColor` if control has a valid native handle.
Use `self.ToBitmap` if control doesn't have a valid native handle or you get many pixels.
x: int, internal x position.
y: int, internal y position.
Return int, a color value in bgr.
r = bgr & 0x0000FF
g = (bgr & 0x00FF00) >> 8
b = (bgr & 0xFF0000) >> 16
"""
handle = self.NativeWindowHandle
if handle:
return GetPixelColor(x, y, handle) |
def ToBitmap(self, x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> Bitmap:
"""
Capture control to a Bitmap object.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
If width(or height) < 0, image size will be control's width(or height) - width(or height).
"""
bitmap = Bitmap()
bitmap.FromControl(self, x, y, width, height)
return bitmap |
def CaptureToImage(self, savePath: str, x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool:
"""
Capture control to a image file.
savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff.
x, y: int, the point in control's internal position(from 0,0).
width, height: int, image's width and height from x, y, use 0 for entire area.
If width(or height) < 0, image size will be control's width(or height) - width(or height).
Return bool, True if succeed otherwise False.
"""
bitmap = Bitmap()
if bitmap.FromControl(self, x, y, width, height):
return bitmap.ToFile(savePath)
return False |
def IsTopLevel(self) -> bool:
"""Determine whether current control is top level."""
handle = self.NativeWindowHandle
if handle:
return GetAncestor(handle, GAFlag.Root) == handle
return False |
def GetTopLevelControl(self) -> 'Control':
"""
Get the top level control which current control lays.
If current control is top level, return self.
If current control is root control, return None.
Return `PaneControl` or `WindowControl` or None.
"""
handle = self.NativeWindowHandle
if handle:
topHandle = GetAncestor(handle, GAFlag.Root)
if topHandle:
if topHandle == handle:
return self
else:
return ControlFromHandle(topHandle)
else:
#self is root control
pass
else:
control = self
while True:
control = control.GetParentControl()
handle = control.NativeWindowHandle
if handle:
topHandle = GetAncestor(handle, GAFlag.Root)
return ControlFromHandle(topHandle) |
def Select(self, itemName: str = '', condition: Callable = None, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Show combobox's popup menu and select a item by name.
itemName: str.
condition: Callable function(comboBoxItemName: str)->bool, if condition is valid, ignore itemName.
waitTime: float.
Some comboboxs doesn't support SelectionPattern, here is a workaround.
This method tries to and selection support.
It may not work for some comboboxes, such as comboboxes in older Qt version.
If it doesn't work, you should write your own version Select, or it doesn't support selection at all.
"""
expandCollapsePattern = self.GetExpandCollapsePattern()
if expandCollapsePattern:
expandCollapsePattern.Expand()
else:
#Windows Form's ComboBoxControl doesn't support ExpandCollapsePattern
self.Click(x=-10, ratioY=0.5, simulateMove=False)
find = False
if condition:
listItemControl = self.ListItemControl(Compare=lambda c, d: condition(c.Name))
else:
listItemControl = self.ListItemControl(Name=itemName)
if listItemControl.Exists(1):
scrollItemPattern = listItemControl.GetScrollItemPattern()
if scrollItemPattern:
scrollItemPattern.ScrollIntoView(waitTime=0.1)
listItemControl.Click(waitTime=waitTime)
find = True
else:
#ComboBox's popup window is a child of root control
listControl = ListControl(searchDepth= 1)
if listControl.Exists(1):
if condition:
listItemControl = self.ListItemControl(Compare=lambda c, d: condition(c.Name))
else:
listItemControl = self.ListItemControl(Name=itemName)
if listItemControl.Exists(0, 0):
scrollItemPattern = listItemControl.GetScrollItemPattern()
if scrollItemPattern:
scrollItemPattern.ScrollIntoView(waitTime=0.1)
listItemControl.Click(waitTime=waitTime)
find = True
if not find:
Logger.ColorfullyWriteLine('Can\'t find <Color=Cyan>{}</Color> in ComboBoxControl or it does not support selection.'.format(itemName), ConsoleColor.Yellow)
if expandCollapsePattern:
expandCollapsePattern.Collapse(waitTime)
else:
self.Click(x=-10, ratioY=0.5, simulateMove=False, waitTime=waitTime)
return find |
def SetTopmost(self, isTopmost: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Set top level window topmost.
isTopmost: bool.
waitTime: float.
"""
if self.IsTopLevel():
ret = SetWindowTopmost(self.NativeWindowHandle, isTopmost)
time.sleep(waitTime)
return ret
return False |
def Maximize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Set top level window maximize.
"""
if self.IsTopLevel():
return self.ShowWindow(SW.ShowMaximized, waitTime)
return False |
def MoveToCenter(self) -> bool:
"""
Move window to screen center.
"""
if self.IsTopLevel():
rect = self.BoundingRectangle
screenWidth, screenHeight = GetScreenSize()
x, y = (screenWidth - rect.width()) // 2, (screenHeight - rect.height()) // 2
if x < 0: x = 0
if y < 0: y = 0
return SetWindowPos(self.NativeWindowHandle, SWP.HWND_Top, x, y, 0, 0, SWP.SWP_NoSize)
return False |
def SetActive(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""Set top level window active."""
if self.IsTopLevel():
handle = self.NativeWindowHandle
if IsIconic(handle):
ret = ShowWindow(handle, SW.Restore)
elif not IsWindowVisible(handle):
ret = ShowWindow(handle, SW.Show)
ret = SetForegroundWindow(handle) # may fail if foreground windows's process is not python
time.sleep(waitTime)
return ret
return False |
def MetroClose(self, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Only work on Windows 8/8.1, if current window is Metro UI.
waitTime: float.
"""
if self.ClassName == METRO_WINDOW_CLASS_NAME:
screenWidth, screenHeight = GetScreenSize()
MoveTo(screenWidth // 2, 0, waitTime=0)
DragDrop(screenWidth // 2, 0, screenWidth // 2, screenHeight, waitTime=waitTime)
else:
Logger.WriteLine('Window is not Metro!', ConsoleColor.Yellow) |
def DemoCN():
"""for Chinese language"""
thisWindow = auto.GetConsoleWindow()
auto.Logger.ColorfullyWrite('我将运行<Color=Cyan>cmd</Color>并设置它的<Color=Cyan>屏幕缓冲区</Color>使<Color=Cyan>cmd</Color>一行能容纳很多字符\n\n')
time.sleep(3)
auto.SendKeys('{Win}r')
while not isinstance(auto.GetFocusedControl(), auto.EditControl):
time.sleep(1)
auto.SendKeys('cmd{Enter}')
cmdWindow = auto.WindowControl(RegexName = '.+cmd.exe')
cmdWindow.TitleBarControl().RightClick()
auto.SendKey(auto.Keys.VK_P)
optionWindow = cmdWindow.WindowControl(SubName = '属性')
optionWindow.TabItemControl(SubName = '选项').Click()
optionTab = optionWindow.PaneControl(SubName = '选项')
checkBox = optionTab.CheckBoxControl(AutomationId = '103')
if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On:
checkBox.Click()
checkBox = optionTab.CheckBoxControl(AutomationId = '104')
if checkBox.GetTogglePattern().ToggleState != auto.ToggleState.On:
checkBox.Click()
optionWindow.TabItemControl(SubName = '布局').Click()
layoutTab = optionWindow.PaneControl(SubName = '布局')
layoutTab.EditControl(AutomationId='301').GetValuePattern().SetValue('300')
layoutTab.EditControl(AutomationId='303').GetValuePattern().SetValue('3000')
layoutTab.EditControl(AutomationId='305').GetValuePattern().SetValue('140')
layoutTab.EditControl(AutomationId='307').GetValuePattern().SetValue('30')
optionWindow.ButtonControl(AutomationId = '1').Click()
cmdWindow.SetActive()
rect = cmdWindow.BoundingRectangle
auto.DragDrop(rect.left + 50, rect.top + 10, 50, 30)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('我将运行<Color=Cyan>记事本</Color>并输入<Color=Cyan>Hello!!!</Color>\n\n')
time.sleep(3)
subprocess.Popen('notepad')
notepadWindow = auto.WindowControl(searchDepth = 1, ClassName = 'Notepad')
cx, cy = auto.GetScreenSize()
notepadWindow.MoveWindow(cx // 2, 20, cx // 2, cy // 2)
time.sleep(0.5)
notepadWindow.EditControl().SendKeys('Hello!!!', 0.05)
time.sleep(1)
dir = os.path.dirname(__file__)
scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py'))
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('运行"<Color=Cyan>automation.py -h</Color>"显示帮助\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('运行"<Color=Cyan>automation.py -r -d1</Color>"显示所有顶层窗口, 即桌面的子窗口\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('运行"<Color=Cyan>automation.py -c</Color>"显示鼠标光标下的控件\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.MoveCursorToMyCenter()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('运行"<Color=Cyan>automation.py -a</Color>"显示鼠标光标下的控件和它的所有父控件\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.MoveCursorToMyCenter()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('运行"<Color=Cyan>automation.py</Color>"显示当前激活窗口和它的所有子控件\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.EditControl().Click()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.WriteLine('演示结束,按Enter退出', auto.ConsoleColor.Green)
input() |
def DemoEN():
"""for other language"""
thisWindow = auto.GetConsoleWindow()
auto.Logger.ColorfullyWrite('I will run <Color=Cyan>cmd</Color>\n\n')
time.sleep(3)
auto.SendKeys('{Win}r')
while not isinstance(auto.GetFocusedControl(), auto.EditControl):
time.sleep(1)
auto.SendKeys('cmd{Enter}')
cmdWindow = auto.WindowControl(SubName = 'cmd.exe')
rect = cmdWindow.BoundingRectangle
auto.DragDrop(rect.left + 50, rect.top + 10, 50, 10)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('I will run <Color=Cyan>Notepad</Color> and type <Color=Cyan>Hello!!!</Color>\n\n')
time.sleep(3)
subprocess.Popen('notepad')
notepadWindow = auto.WindowControl(searchDepth = 1, ClassName = 'Notepad')
cx, cy = auto.GetScreenSize()
notepadWindow.MoveWindow(cx // 2, 20, cx // 2, cy // 2)
time.sleep(0.5)
notepadWindow.EditControl().SendKeys('Hello!!!', 0.05)
time.sleep(1)
dir = os.path.dirname(__file__)
scriptPath = os.path.abspath(os.path.join(dir, '..\\automation.py'))
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('run "<Color=Cyan>automation.py -h</Color>" to display the help\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -h'.format(scriptPath) + '{Enter}', 0.05)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('run "<Color=Cyan>automation.py -r -d1</Color>" to display the top level windows, desktop\'s children\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -r -d1 -t0'.format(scriptPath) + '{Enter}', 0.05)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('run "<Color=Cyan>automation.py -c</Color>" to display the control under mouse cursor\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -c -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.MoveCursorToMyCenter()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('run "<Color=Cyan>automation.py -a</Color>" to display the control under mouse cursor and its ancestors\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -a -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.MoveCursorToMyCenter()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
thisWindow.SetActive()
auto.Logger.ColorfullyWrite('run "<Color=Cyan>automation.py</Color>" to display the active window\n\n')
time.sleep(3)
cmdWindow.SendKeys('"{}" -t3'.format(scriptPath) + '{Enter}', 0.05)
notepadWindow.SetActive()
notepadWindow.EditControl().Click()
time.sleep(3)
cmdWindow.SetActive(waitTime = 2)
time.sleep(3)
thisWindow.SetActive()
auto.Logger.WriteLine('press Enter to exit', auto.ConsoleColor.Green)
input() |
def threadFunc(root):
"""
If you want to use functionalities related to Controls and Patterns in a new thread.
You must call InitializeUIAutomationInCurrentThread first in the thread
and call UninitializeUIAutomationInCurrentThread when the thread exits.
But you can't use use a Control or a Pattern created in a different thread.
So you can't create a Control or a Pattern in main thread and then pass it to a new thread and use it.
"""
#print(root)# you cannot use root because it is root control created in main thread
th = threading.currentThread()
auto.Logger.WriteLine('\nThis is running in a new thread. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan)
time.sleep(2)
auto.InitializeUIAutomationInCurrentThread()
auto.GetConsoleWindow().CaptureToImage('console_newthread.png')
newRoot = auto.GetRootControl() #ok, root control created in new thread
auto.EnumAndLogControl(newRoot, 1)
auto.UninitializeUIAutomationInCurrentThread()
auto.Logger.WriteLine('\nThread exits. {} {}'.format(th.ident, th.name), auto.ConsoleColor.Cyan) |
def _saliency_map(self, a, image, target, labels, mask, fast=False):
"""Implements Algorithm 3 in manuscript
"""
# pixel influence on target class
alphas = a.gradient(image, target) * mask
# pixel influence on sum of residual classes
# (don't evaluate if fast == True)
if fast:
betas = -np.ones_like(alphas)
else:
betas = np.sum([
a.gradient(image, label) * mask - alphas
for label in labels], 0)
# compute saliency map
# (take into account both pos. & neg. perturbations)
salmap = np.abs(alphas) * np.abs(betas) * np.sign(alphas * betas)
# find optimal pixel & direction of perturbation
idx = np.argmin(salmap)
idx = np.unravel_index(idx, mask.shape)
pix_sign = np.sign(alphas)[idx]
return idx, pix_sign |
def from_keras(cls, model, bounds, input_shape=None,
channel_axis=3, preprocessing=(0, 1)):
"""Alternative constructor for a TensorFlowModel that
accepts a `tf.keras.Model` instance.
Parameters
----------
model : `tensorflow.keras.Model`
A `tensorflow.keras.Model` that accepts a single input tensor
and returns a single output tensor representing logits.
bounds : tuple
Tuple of lower and upper bound for the pixel values, usually
(0, 1) or (0, 255).
input_shape : tuple
The shape of a single input, e.g. (28, 28, 1) for MNIST.
If None, tries to get the the shape from the model's
input_shape attribute.
channel_axis : int
The index of the axis that represents color channels.
preprocessing: 2-element tuple with floats or numpy arrays
Elementwises preprocessing of input; we first subtract the first
element of preprocessing from the input and then divide the input
by the second element.
"""
import tensorflow as tf
if input_shape is None:
try:
input_shape = model.input_shape[1:]
except AttributeError:
raise ValueError(
'Please specify input_shape manually or '
'provide a model with an input_shape attribute')
with tf.keras.backend.get_session().as_default():
inputs = tf.placeholder(tf.float32, (None,) + input_shape)
logits = model(inputs)
return cls(inputs, logits, bounds=bounds,
channel_axis=channel_axis, preprocessing=preprocessing) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.