code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
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
|
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
|
Zoom
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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
|
ZoomByUnit
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def SetValue(self, value: str, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationTransformPattern2::IUIAutomationValuePattern::SetValue.
Set the value of 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-iuiautomationvaluepattern-setvalue
"""
ret = self.pattern.SetValue(value) == S_OK
time.sleep(waitTime)
return ret
|
Call IUIAutomationTransformPattern2::IUIAutomationValuePattern::SetValue.
Set the value of 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-iuiautomationvaluepattern-setvalue
|
SetValue
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def Realize(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationVirtualizedItemPattern::Realize.
Create a full UI Automation element for a virtualized item.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationvirtualizeditempattern-realize
"""
ret = self.pattern.Realize() == S_OK
time.sleep(waitTime)
return ret
|
Call IUIAutomationVirtualizedItemPattern::Realize.
Create a full UI Automation element for a virtualized item.
waitTime: float.
Return bool, True if succeed otherwise False.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationvirtualizeditempattern-realize
|
Realize
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def Close(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call IUIAutomationWindowPattern::Close.
Close the window.
waitTime: float.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-close
"""
ret = self.pattern.Close() == S_OK
time.sleep(waitTime)
return ret
|
Call IUIAutomationWindowPattern::Close.
Close the window.
waitTime: float.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationwindowpattern-close
|
Close
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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
|
SetWindowVisualState
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def CreatePattern(patternId: int, pattern: ctypes.POINTER(comtypes.IUnknown)):
"""Create a concreate pattern by pattern id and pattern(POINTER(IUnknown))."""
subPattern = pattern.QueryInterface(GetPatternIdInterface(patternId))
if subPattern:
return PatternConstructors[patternId](pattern=subPattern)
|
Create a concreate pattern by pattern id and pattern(POINTER(IUnknown)).
|
CreatePattern
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def __init__(self, searchFromControl: 'Control' = None, searchDepth: int = 0xFFFFFFFF, searchInterval: float = SEARCH_INTERVAL, foundIndex: int = 1, element=None, **searchProperties):
"""
searchFromControl: `Control` or its subclass, if it is None, search from root control(Desktop).
searchDepth: int, max search depth from searchFromControl.
foundIndex: int, starts with 1, >= 1.
searchInterval: float, wait searchInterval after every search in self.Refind and self.Exists, the global timeout is TIME_OUT_SECOND.
element: `ctypes.POINTER(IUIAutomationElement)`, internal use only.
searchProperties: defines how to search, the following keys can be used:
ControlType: int, a value in class `ControlType`.
ClassName: str.
AutomationId: str.
Name: str.
SubName: str, a part str in Name.
RegexName: str, supports regex using re.match.
You can only use one of Name, SubName, RegexName in searchProperties.
Depth: int, only search controls in relative depth from searchFromControl, ignore controls in depth(0~Depth-1),
if set, searchDepth will be set to Depth too.
Compare: Callable[[Control, int], bool], custom compare function(control: Control, depth: int) -> bool.
`Control` wraps IUIAutomationElement.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nn-uiautomationclient-iuiautomationelement
"""
self._element = element
self._elementDirectAssign = True if element else False
self.searchFromControl = searchFromControl
self.searchDepth = searchProperties.get('Depth', searchDepth)
self.searchInterval = searchInterval
self.foundIndex = foundIndex
self.searchProperties = searchProperties
regName = searchProperties.get('RegexName', '')
self.regexName = re.compile(regName) if regName else None
self._supportedPatterns = {}
|
searchFromControl: `Control` or its subclass, if it is None, search from root control(Desktop).
searchDepth: int, max search depth from searchFromControl.
foundIndex: int, starts with 1, >= 1.
searchInterval: float, wait searchInterval after every search in self.Refind and self.Exists, the global timeout is TIME_OUT_SECOND.
element: `ctypes.POINTER(IUIAutomationElement)`, internal use only.
searchProperties: defines how to search, the following keys can be used:
ControlType: int, a value in class `ControlType`.
ClassName: str.
AutomationId: str.
Name: str.
SubName: str, a part str in Name.
RegexName: str, supports regex using re.match.
You can only use one of Name, SubName, RegexName in searchProperties.
Depth: int, only search controls in relative depth from searchFromControl, ignore controls in depth(0~Depth-1),
if set, searchDepth will be set to Depth too.
Compare: Callable[[Control, int], bool], custom compare function(control: Control, depth: int) -> bool.
`Control` wraps IUIAutomationElement.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nn-uiautomationclient-iuiautomationelement
|
__init__
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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) #rarely happens
|
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.
|
CreateControlFromElement
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
Add search properties using `dict.update`.
searchProperties: dict, same as searchProperties in `Control.__init__`.
|
AddSearchProperties
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
searchProperties: dict, same as searchProperties in `Control.__init__`.
|
RemoveSearchProperties
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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) + '}'
|
keyColor, valueColor: str, color name in class ConsoleColor
|
GetColorfulSearchPropertiesStr
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
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())
|
BoundingRectangle
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def ScreenShot(self, savePath: str=None) -> str:
"""
Save the control's screenshot to savePath.
savePath: str, the path to save the screenshot.
Return str, the path of the saved screenshot.
"""
rect = self.Element.CurrentBoundingRectangle
bbox = (rect.left, rect.top, rect.right, rect.bottom)
img = ImageGrab.grab(bbox=bbox, all_screens=True)
if savePath is None:
savePath = os.path.join(os.getcwd(), 'ControlScreenShot.png')
img.save(savePath)
return savePath
|
Save the control's screenshot to savePath.
savePath: str, the path to save the screenshot.
Return str, the path of the saved screenshot.
|
ScreenShot
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def NativeWindowHandle(self) -> str:
"""
Property NativeWindowHandle.
Call IUIAutomationElement::get_CurrentNativeWindowHandle.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentnativewindowhandle
"""
handle = self.Element.CurrentNativeWindowHandle
return 0 if handle is None else handle
|
Property NativeWindowHandle.
Call IUIAutomationElement::get_CurrentNativeWindowHandle.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-get_currentnativewindowhandle
|
NativeWindowHandle
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetClickablePoint(self) -> Tuple[int, int, bool]:
"""
Call IUIAutomationElement::GetClickablePoint.
Return Tuple[int, int, bool], three items tuple (x, y, gotClickable), such as (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))
|
Call IUIAutomationElement::GetClickablePoint.
Return Tuple[int, int, bool], three items tuple (x, y, gotClickable), such as (20, 10, True)
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-getclickablepoint
|
GetClickablePoint
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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
|
GetPattern
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def SetFocus(self) -> bool:
"""
Call IUIAutomationElement::SetFocus.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-setfocus
"""
try:
return self.Element.SetFocus() == S_OK
except comtypes.COMError as ex:
return False
|
Call IUIAutomationElement::SetFocus.
Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationelement-setfocus
|
SetFocus
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def Element(self):
"""
Property Element.
Return `ctypes.POINTER(IUIAutomationElement)`.
"""
if not self._element:
self.Refind(maxSearchSeconds=TIME_OUT_SECOND, searchIntervalSeconds=self.searchInterval)
return self._element
|
Property Element.
Return `ctypes.POINTER(IUIAutomationElement)`.
|
Element
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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`.
|
GetCachedPattern
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetAncestorControl(self, condition: Callable[['Control', int], bool]) -> 'Control':
"""
Get an ancestor control that matches the condition.
condition: Callable[[Control, int], bool], 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
|
Get an ancestor control that matches the condition.
condition: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool,
depth starts with -1 and decreses when search goes up.
Return `Control` subclass or None.
|
GetAncestorControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetSiblingControl(self, condition: Callable[['Control'], bool], forward: bool = True) -> 'Control':
"""
Get a sibling control that matches the condition.
forward: bool, if True, only search next siblings, if False, search pervious siblings first, then search next siblings.
condition: Callable[[Control], bool], 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
|
Get a sibling control that matches the condition.
forward: bool, if True, only search next siblings, if False, search pervious siblings first, then search next siblings.
condition: Callable[[Control], bool], function(control: Control) -> bool.
Return `Control` subclass or None.
|
GetSiblingControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetChildControl(self, index: int, control_type: str = None) -> 'Control':
"""
Get the nth child control.
index: int, starts with 0.
control_type: `Control` or its subclass, if not None, only return the nth control that matches the control_type.
Return `Control` subclass or None.
"""
children = self.GetChildren()
if control_type:
children = [child for child in children if child.ControlTypeName == control_type]
if index < len(children):
return children[index]
else:
return None
|
Get the nth child control.
index: int, starts with 0.
control_type: `Control` or its subclass, if not None, only return the nth control that matches the control_type.
Return `Control` subclass or None.
|
GetChildControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetAllProgeny(self) -> List[List['Control']]:
"""
Get all progeny controls.
Return List[List[Control]], a list of list of `Control` subclasses.
"""
all_elements = []
def find_all_elements(element, depth=0):
children = element.GetChildren()
if depth == len(all_elements):
all_elements.append([])
all_elements[depth].append(element)
for child in children:
find_all_elements(child, depth+1)
return all_elements
return find_all_elements(self)
|
Get all progeny controls.
Return List[List[Control]], a list of list of `Control` subclasses.
|
GetAllProgeny
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetProgenyControl(self, depth: int=1, index: int=0, control_type: str = None) -> 'Control':
"""
Get the nth control in the mth depth.
depth: int, starts with 0.
index: int, starts with 0.
control_type: `Control` or its subclass, if not None, only return the nth control that matches the control_type.
Return `Control` subclass or None.
"""
progeny = self.GetAllProgeny()
try:
controls = progeny[depth]
if control_type:
controls = [child for child in controls if child.ControlTypeName == control_type]
if index < len(controls):
return controls[index]
except IndexError:
return
|
Get the nth control in the mth depth.
depth: int, starts with 0.
index: int, starts with 0.
control_type: `Control` or its subclass, if not None, only return the nth control that matches the control_type.
Return `Control` subclass or None.
|
GetProgenyControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetChildren(self) -> List['Control']:
"""
Return List[Control], a list of `Control` subclasses.
"""
children = []
child = self.GetFirstChildControl()
while child:
children.append(child)
child = child.GetNextSiblingControl()
return children
|
Return List[Control], a list of `Control` subclasses.
|
GetChildren
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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 'Depth' == key:
if value != depth:
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 'Compare' == key:
if not value(control, depth):
return False
return True
|
Define how to search.
control: `Control` or its subclass.
depth: int, tree depth from searchFromControl.
Return bool.
|
_CompareFunction
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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.ColorfullyLog(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.ColorfullyLog('{} 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.ColorfullyLog(self.GetColorfulSearchPropertiesStr() + '<Color=Red> does not exist.</Color>')
return False
|
maxSearchSeconds: float
searchIntervalSeconds: float
Find control every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool, True if find
|
Exists
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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.ColorfullyLog(self.GetColorfulSearchPropertiesStr() + '<Color=Red> does not disappear.</Color>')
return False
|
maxSearchSeconds: float
searchIntervalSeconds: float
Check if control disappears every searchIntervalSeconds seconds in maxSearchSeconds seconds.
Return bool, True if control disappears.
|
Disappears
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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.ColorfullyLog('<Color=Red>Find Control Timeout: </Color>' + self.GetColorfulSearchPropertiesStr())
raise LookupError('Find Control Timeout: ' + self.GetSearchPropertiesStr())
else:
return False
return True
|
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.
|
Refind
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def MoveCursorToInnerPos(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, simulateMove: bool = True) -> Tuple[int, int]:
"""
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[int, int], two ints tuple (x, y), the cursor positon relative to screen(0, 0)
after moving or None if control's width or height is 0.
"""
rect = self.BoundingRectangle
if rect.width() == 0 or rect.height() == 0:
Logger.ColorfullyLog('<Color=Yellow>Can not move cursor</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
|
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[int, int], two ints tuple (x, y), the cursor positon relative to screen(0, 0)
after moving or None if control's width or height is 0.
|
MoveCursorToInnerPos
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
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.
|
Click
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def MiddleClick(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, middle click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, middle 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.
MiddleClick(), MiddleClick(ratioX=0.5, ratioY=0.5): middle click center.
MiddleClick(10, 10): middle click left+10, top+10.
MiddleClick(-10, -10): middle click right-10, bottom-10.
"""
point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)
if point:
MiddleClick(point[0], point[1], waitTime)
|
x: int, if < 0, middle click self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, middle 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.
MiddleClick(), MiddleClick(ratioX=0.5, ratioY=0.5): middle click center.
MiddleClick(10, 10): middle click left+10, top+10.
MiddleClick(-10, -10): middle click right-10, bottom-10.
|
MiddleClick
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def RightClick(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.
RightClick(), RightClick(ratioX=0.5, ratioY=0.5): right click center.
RightClick(10, 10): right click left+10, top+10.
RightClick(-10, -10): right click right-10, bottom-10.
"""
point = self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove)
if point:
RightClick(point[0], point[1], waitTime)
|
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.
RightClick(), RightClick(ratioX=0.5, ratioY=0.5): right click center.
RightClick(10, 10): right click left+10, top+10.
RightClick(-10, -10): right click right-10, bottom-10.
|
RightClick
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
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.
|
DoubleClick
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def WheelDown(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel down.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, move y cursor to self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
wheelTimes: int.
interval: float.
waitTime: float.
"""
cursorX, cursorY = GetCursorPos()
self.SetFocus()
self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove=False)
WheelDown(wheelTimes, interval, waitTime)
SetCursorPos(cursorX, cursorY)
|
Make control have focus first, move cursor to the specified position and mouse wheel down.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, move y cursor to self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
wheelTimes: int.
interval: float.
waitTime: float.
|
WheelDown
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def WheelUp(self, x: int = None, y: int = None, ratioX: float = 0.5, ratioY: float = 0.5, wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Make control have focus first, move cursor to the specified position and mouse wheel up.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, move y cursor to self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
wheelTimes: int.
interval: float.
waitTime: float.
"""
cursorX, cursorY = GetCursorPos()
self.SetFocus()
self.MoveCursorToInnerPos(x, y, ratioX, ratioY, simulateMove=False)
WheelUp(wheelTimes, interval, waitTime)
SetCursorPos(cursorX, cursorY)
|
Make control have focus first, move cursor to the specified position and mouse wheel up.
x: int, if < 0, move x cursor to self.BoundingRectangle.right + x, if not None, ignore ratioX.
y: int, if < 0, move y cursor to self.BoundingRectangle.bottom + y, if not None, ignore ratioY.
ratioX: float.
ratioY: float.
wheelTimes: int.
interval: float.
waitTime: float.
|
WheelUp
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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.
|
ShowWindow
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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.
|
MoveWindow
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def GetWindowText(self) -> str:
"""
Call native GetWindowText if control has a valid native handle.
"""
handle = self.NativeWindowHandle
if handle:
return GetWindowText(handle)
|
Call native GetWindowText if control has a valid native handle.
|
GetWindowText
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
Call native SetWindowText if control has a valid native handle.
|
SetWindowText
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def SendKeys(self, text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, charMode: bool = True) -> 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.
text: str, keys to type, see the docstring of `SendKeys`.
interval: float, seconds between keys.
waitTime: float.
charMode: bool, if False, the text typied is depend on the input method if a input method is on.
"""
self.SetFocus()
SendKeys(text, interval, waitTime, charMode)
|
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.
text: str, keys to type, see the docstring of `SendKeys`.
interval: float, seconds between keys.
waitTime: float.
charMode: bool, if False, the text typied is depend on the input method if a input method is on.
|
SendKeys
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
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
|
GetPixelColor
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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).
|
ToBitmap
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
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.
|
CaptureToImage
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def IsTopLevel(self) -> bool:
"""Determine whether current control is top level."""
handle = self.NativeWindowHandle
if handle:
return GetAncestor(handle, GAFlag.Root) == handle
return False
|
Determine whether current control is top level.
|
IsTopLevel
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
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.
|
GetTopLevelControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def Select(self, itemName: str = '', condition: Callable[[str], bool] = None, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Show combobox's popup menu and select a item by name.
itemName: str.
condition: Callable[[str], bool], 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 add 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 = listControl.ListItemControl(Compare=lambda c, d: condition(c.Name))
else:
listItemControl = listControl.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.ColorfullyLog('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
|
Show combobox's popup menu and select a item by name.
itemName: str.
condition: Callable[[str], bool], 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 add 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.
|
Select
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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
|
Set top level window topmost.
isTopmost: bool.
waitTime: float.
|
SetTopmost
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def Restore(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Restore window to normal state.
Similar to SwitchToThisWindow.
"""
if self.IsTopLevel():
return self.ShowWindow(SW.Restore, waitTime)
return False
|
Restore window to normal state.
Similar to SwitchToThisWindow.
|
Restore
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
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)
|
Only work on Windows 8/8.1, if current window is Metro UI.
waitTime: float.
|
MetroClose
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def SetGlobalSearchTimeout(seconds: float) -> None:
"""
seconds: float.
To make this available, you need explicitly import uiautomation:
from uiautomation import uiautomation as auto
auto.SetGlobalSearchTimeout(10)
"""
global TIME_OUT_SECOND
TIME_OUT_SECOND = seconds
|
seconds: float.
To make this available, you need explicitly import uiautomation:
from uiautomation import uiautomation as auto
auto.SetGlobalSearchTimeout(10)
|
SetGlobalSearchTimeout
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def WalkTree(top, getChildren: Callable[[TreeNode], List[TreeNode]] = None,
getFirstChild: Callable[[TreeNode], TreeNode] = None, getNextSibling: Callable[[TreeNode], TreeNode] = None,
yieldCondition: Callable[[TreeNode, int], bool] = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
Walk a tree not using recursive algorithm.
top: a tree node.
getChildren: Callable[[TreeNode], List[TreeNode]], function(treeNode: TreeNode) -> List[TreeNode].
getNextSibling: Callable[[TreeNode], TreeNode], function(treeNode: TreeNode) -> TreeNode.
getNextSibling: Callable[[TreeNode], TreeNode], function(treeNode: TreeNode) -> TreeNode.
yieldCondition: Callable[[TreeNode, int], bool], function(treeNode: TreeNode, depth: int) -> bool.
includeTop: bool, if True yield top first.
maxDepth: int, enum depth.
If getChildren is valid, ignore getFirstChild and getNextSibling,
yield 3 items tuple: (treeNode, depth, remain children count in current depth).
If getChildren is not valid, using getFirstChild and getNextSibling,
yield 2 items tuple: (treeNode, depth).
If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode: TreeNode, depth: int)->bool returns True.
For example:
def GetDirChildren(dir_):
if os.path.isdir(dir_):
return [os.path.join(dir_, it) for it in os.listdir(dir_)]
for it, depth, leftCount in WalkTree('D:\\', getChildren= GetDirChildren):
print(it, depth, leftCount)
"""
if maxDepth <= 0:
return
depth = 0
if getChildren:
if includeTop:
if not yieldCondition or yieldCondition(top, 0):
yield top, 0, 0
children = getChildren(top)
childList = [children]
while depth >= 0: #or while childList:
lastItems = childList[-1]
if lastItems:
if not yieldCondition or yieldCondition(lastItems[0], depth + 1):
yield lastItems[0], depth + 1, len(lastItems) - 1
if depth + 1 < maxDepth:
children = getChildren(lastItems[0])
if children:
depth += 1
childList.append(children)
del lastItems[0]
else:
del childList[depth]
depth -= 1
elif getFirstChild and getNextSibling:
if includeTop:
if not yieldCondition or yieldCondition(top, 0):
yield top, 0
child = getFirstChild(top)
childList = [child]
while depth >= 0: #or while childList:
lastItem = childList[-1]
if lastItem:
if not yieldCondition or yieldCondition(lastItem, depth + 1):
yield lastItem, depth + 1
child = getNextSibling(lastItem)
childList[depth] = child
if depth + 1 < maxDepth:
child = getFirstChild(lastItem)
if child:
depth += 1
childList.append(child)
else:
del childList[depth]
depth -= 1
|
Walk a tree not using recursive algorithm.
top: a tree node.
getChildren: Callable[[TreeNode], List[TreeNode]], function(treeNode: TreeNode) -> List[TreeNode].
getNextSibling: Callable[[TreeNode], TreeNode], function(treeNode: TreeNode) -> TreeNode.
getNextSibling: Callable[[TreeNode], TreeNode], function(treeNode: TreeNode) -> TreeNode.
yieldCondition: Callable[[TreeNode, int], bool], function(treeNode: TreeNode, depth: int) -> bool.
includeTop: bool, if True yield top first.
maxDepth: int, enum depth.
If getChildren is valid, ignore getFirstChild and getNextSibling,
yield 3 items tuple: (treeNode, depth, remain children count in current depth).
If getChildren is not valid, using getFirstChild and getNextSibling,
yield 2 items tuple: (treeNode, depth).
If yieldCondition is not None, only yield tree nodes that yieldCondition(treeNode: TreeNode, depth: int)->bool returns True.
For example:
def GetDirChildren(dir_):
if os.path.isdir(dir_):
return [os.path.join(dir_, it) for it in os.listdir(dir_)]
for it, depth, leftCount in WalkTree('D:\', getChildren= GetDirChildren):
print(it, depth, leftCount)
|
WalkTree
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def ControlFromCursor() -> Control:
"""
Call ControlFromPoint with current cursor point.
Return `Control` subclass.
"""
x, y = GetCursorPos()
return ControlFromPoint(x, y)
|
Call ControlFromPoint with current cursor point.
Return `Control` subclass.
|
ControlFromCursor
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def ControlFromCursor2() -> Control:
"""
Call ControlFromPoint2 with current cursor point.
Return `Control` subclass.
"""
x, y = GetCursorPos()
return ControlFromPoint2(x, y)
|
Call ControlFromPoint2 with current cursor point.
Return `Control` subclass.
|
ControlFromCursor2
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
control: `Control` or its subclass.
includeTop: bool, if True, yield (control, 0) first.
maxDepth: int, enum depth.
Yield 2 items tuple (control: Control, depth: int).
"""
if includeTop:
yield control, 0
if maxDepth <= 0:
return
depth = 0
child = control.GetFirstChildControl()
controlList = [child]
while depth >= 0:
lastControl = controlList[-1]
if lastControl:
yield lastControl, depth + 1
child = lastControl.GetNextSiblingControl()
controlList[depth] = child
if depth + 1 < maxDepth:
child = lastControl.GetFirstChildControl()
if child:
depth += 1
controlList.append(child)
else:
del controlList[depth]
depth -= 1
|
control: `Control` or its subclass.
includeTop: bool, if True, yield (control, 0) first.
maxDepth: int, enum depth.
Yield 2 items tuple (control: Control, depth: int).
|
WalkControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def LogControl(control: Control, depth: int = 0, showAllName: bool = True, showPid: bool = False) -> None:
"""
Print and log control's properties.
control: `Control` or its subclass.
depth: int, current depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
def getKeyName(theDict, theValue):
for key in theDict:
if theValue == theDict[key]:
return key
indent = ' ' * depth * 4
Logger.Write('{0}ControlType: '.format(indent))
Logger.Write(control.ControlTypeName, ConsoleColor.DarkGreen)
Logger.Write(' ClassName: ')
Logger.Write(control.ClassName, ConsoleColor.DarkGreen)
Logger.Write(' AutomationId: ')
Logger.Write(control.AutomationId, ConsoleColor.DarkGreen)
Logger.Write(' Rect: ')
Logger.Write(control.BoundingRectangle, ConsoleColor.DarkGreen)
Logger.Write(' Name: ')
Logger.Write(control.Name, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30)
Logger.Write(' Handle: ')
Logger.Write('0x{0:X}({0})'.format(control.NativeWindowHandle), ConsoleColor.DarkGreen)
Logger.Write(' Depth: ')
Logger.Write(depth, ConsoleColor.DarkGreen)
if showPid:
Logger.Write(' ProcessId: ')
Logger.Write(control.ProcessId, ConsoleColor.DarkGreen)
supportedPatterns = list(filter(lambda t: t[0], ((control.GetPattern(id_), name) for id_, name in PatternIdNames.items())))
for pt, name in supportedPatterns:
if isinstance(pt, ValuePattern):
Logger.Write(' ValuePattern.Value: ')
Logger.Write(pt.Value, ConsoleColor.DarkGreen, printTruncateLen=0 if showAllName else 30)
elif isinstance(pt, RangeValuePattern):
Logger.Write(' RangeValuePattern.Value: ')
Logger.Write(pt.Value, ConsoleColor.DarkGreen)
elif isinstance(pt, TogglePattern):
Logger.Write(' TogglePattern.ToggleState: ')
Logger.Write('ToggleState.' + getKeyName(ToggleState.__dict__, pt.ToggleState), ConsoleColor.DarkGreen)
elif isinstance(pt, SelectionItemPattern):
Logger.Write(' SelectionItemPattern.IsSelected: ')
Logger.Write(pt.IsSelected, ConsoleColor.DarkGreen)
elif isinstance(pt, ExpandCollapsePattern):
Logger.Write(' ExpandCollapsePattern.ExpandCollapseState: ')
Logger.Write('ExpandCollapseState.' + getKeyName(ExpandCollapseState.__dict__, pt.ExpandCollapseState), ConsoleColor.DarkGreen)
elif isinstance(pt, ScrollPattern):
Logger.Write(' ScrollPattern.HorizontalScrollPercent: ')
Logger.Write(pt.HorizontalScrollPercent, ConsoleColor.DarkGreen)
Logger.Write(' ScrollPattern.VerticalScrollPercent: ')
Logger.Write(pt.VerticalScrollPercent, ConsoleColor.DarkGreen)
elif isinstance(pt, GridPattern):
Logger.Write(' GridPattern.RowCount: ')
Logger.Write(pt.RowCount, ConsoleColor.DarkGreen)
Logger.Write(' GridPattern.ColumnCount: ')
Logger.Write(pt.ColumnCount, ConsoleColor.DarkGreen)
elif isinstance(pt, GridItemPattern):
Logger.Write(' GridItemPattern.Row: ')
Logger.Write(pt.Column, ConsoleColor.DarkGreen)
Logger.Write(' GridItemPattern.Column: ')
Logger.Write(pt.Column, ConsoleColor.DarkGreen)
elif isinstance(pt, TextPattern):
# issue 49: CEF Control as DocumentControl have no "TextPattern.Text" property, skip log this part.
# https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextpattern-get_documentrange
try:
Logger.Write(' TextPattern.Text: ')
Logger.Write(pt.DocumentRange.GetText(30), ConsoleColor.DarkGreen)
except comtypes.COMError as ex:
pass
Logger.Write(' SupportedPattern:')
for pt, name in supportedPatterns:
Logger.Write(' ' + name, ConsoleColor.DarkGreen)
Logger.Write('\n')
|
Print and log control's properties.
control: `Control` or its subclass.
depth: int, current depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
|
LogControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def EnumAndLogControl(control: Control, maxDepth: int = 0xFFFFFFFF, showAllName: bool = True, showPid: bool = False, startDepth: int = 0) -> None:
"""
Print and log control and its descendants' propertyies.
control: `Control` or its subclass.
maxDepth: int, enum depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
startDepth: int, control's current depth.
"""
for c, d in WalkControl(control, True, maxDepth):
LogControl(c, d + startDepth, showAllName, showPid)
|
Print and log control and its descendants' propertyies.
control: `Control` or its subclass.
maxDepth: int, enum depth.
showAllName: bool, if False, print the first 30 characters of control.Name.
startDepth: int, control's current depth.
|
EnumAndLogControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def EnumAndLogControlAncestors(control: Control, showAllName: bool = True, showPid: bool = False) -> None:
"""
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.
"""
lists = []
while control:
lists.insert(0, control)
control = control.GetParentControl()
for i, control in enumerate(lists):
LogControl(control, i, showAllName, showPid)
|
Print and log control and its ancestors' propertyies.
control: `Control` or its subclass.
showAllName: bool, if False, print the first 30 characters of control.Name.
|
EnumAndLogControlAncestors
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def FindControl(control: Control, compare: Callable[[Control, int], bool], maxDepth: int = 0xFFFFFFFF, findFromSelf: bool = False, foundIndex: int = 1) -> Control:
"""
control: `Control` or its subclass.
compare: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool.
maxDepth: int, enum depth.
findFromSelf: bool, if False, do not compare self.
foundIndex: int, starts with 1, >= 1.
Return `Control` subclass or None if not find.
"""
foundCount = 0
if not control:
control = GetRootControl()
traverseCount = 0
for child, depth in WalkControl(control, findFromSelf, maxDepth):
traverseCount += 1
if compare(child, depth):
foundCount += 1
if foundCount == foundIndex:
child.traverseCount = traverseCount
return child
|
control: `Control` or its subclass.
compare: Callable[[Control, int], bool], function(control: Control, depth: int) -> bool.
maxDepth: int, enum depth.
findFromSelf: bool, if False, do not compare self.
foundIndex: int, starts with 1, >= 1.
Return `Control` subclass or None if not find.
|
FindControl
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def WaitHotKeyReleased(hotkey: Tuple[int, int]) -> None:
"""hotkey: Tuple[int, int], two ints tuple (modifierKey, key)"""
mod = {ModifierKey.Alt: Keys.VK_MENU,
ModifierKey.Control: Keys.VK_CONTROL,
ModifierKey.Shift: Keys.VK_SHIFT,
ModifierKey.Win: Keys.VK_LWIN
}
while True:
time.sleep(0.05)
if IsKeyPressed(hotkey[1]):
continue
for k, v in mod.items():
if k & hotkey[0]:
if IsKeyPressed(v):
break
else:
break
|
hotkey: Tuple[int, int], two ints tuple (modifierKey, key)
|
WaitHotKeyReleased
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def RunByHotKey(keyFunctions: Dict[Tuple[int, int], Callable], stopHotKey: Tuple[int, int] = None, exitHotKey: Tuple[int, int] = (ModifierKey.Control, Keys.VK_D), waitHotKeyReleased: bool = True) -> None:
"""
Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed.
keyFunctions: Dict[Tuple[int, int], Callable], such as {(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : function}
stopHotKey: hotkey tuple
exitHotKey: hotkey tuple
waitHotKeyReleased: bool, if True, hotkey function will be triggered after the hotkey is released
def main(stopEvent):
while True:
if stopEvent.is_set(): # must check stopEvent.is_set() if you want to stop when stop hotkey is pressed
break
print(n)
n += 1
stopEvent.wait(1)
print('main exit')
uiautomation.RunByHotKey({(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : main}
, (uiautomation.ModifierKey.Control | uiautomation.ModifierKey.Shift, uiautomation.Keys.VK_2))
"""
import traceback
def getModName(theDict, theValue):
name = ''
for key in theDict:
if isinstance(theDict[key], int) and theValue & theDict[key]:
if name:
name += '|'
name += key
return name
def getKeyName(theDict, theValue):
for key in theDict:
if theValue == theDict[key]:
return key
def releaseAllKey():
for key, value in Keys.__dict__.items():
if isinstance(value, int) and key.startswith('VK'):
if IsKeyPressed(value):
ReleaseKey(value)
def threadFunc(function, stopEvent, hotkey, hotkeyName):
if waitHotKeyReleased:
WaitHotKeyReleased(hotkey)
try:
function(stopEvent)
except Exception as ex:
Logger.ColorfullyWrite('Catch an exception <Color=Red>{}</Color> in thread for hotkey <Color=DarkCyan>{}</Color>\n'.format(
ex.__class__.__name__, hotkeyName), writeToFile=False)
print(traceback.format_exc())
finally:
releaseAllKey() #need to release keys if some keys were pressed
Logger.ColorfullyWrite('{} for function <Color=DarkCyan>{}</Color> exits, hotkey <Color=DarkCyan>{}</Color>\n'.format(
threading.currentThread(), function.__name__, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False)
stopHotKeyId = 1
exitHotKeyId = 2
hotKeyId = 3
registed = True
id2HotKey = {}
id2Function = {}
id2Thread = {}
id2Name = {}
for hotkey in keyFunctions:
id2HotKey[hotKeyId] = hotkey
id2Function[hotKeyId] = keyFunctions[hotkey]
id2Thread[hotKeyId] = None
modName = getModName(ModifierKey.__dict__, hotkey[0])
keyName = getKeyName(Keys.__dict__, hotkey[1])
id2Name[hotKeyId] = str((modName, keyName))
if ctypes.windll.user32.RegisterHotKey(0, hotKeyId, hotkey[0], hotkey[1]):
Logger.ColorfullyWrite('Register hotkey <Color=Cyan>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False)
else:
registed = False
Logger.ColorfullyWrite('Register hotkey <Color=Cyan>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False)
hotKeyId += 1
if stopHotKey and len(stopHotKey) == 2:
modName = getModName(ModifierKey.__dict__, stopHotKey[0])
keyName = getKeyName(Keys.__dict__, stopHotKey[1])
if ctypes.windll.user32.RegisterHotKey(0, stopHotKeyId, stopHotKey[0], stopHotKey[1]):
Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False)
else:
registed = False
Logger.ColorfullyWrite('Register stop hotkey <Color=DarkYellow>{}</Color> unsuccessfully, maybe it was allready registered by another program\n'.format((modName, keyName)), writeToFile=False)
if not registed:
return
if exitHotKey and len(exitHotKey) == 2:
modName = getModName(ModifierKey.__dict__, exitHotKey[0])
keyName = getKeyName(Keys.__dict__, exitHotKey[1])
if ctypes.windll.user32.RegisterHotKey(0, exitHotKeyId, exitHotKey[0], exitHotKey[1]):
Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> successfully\n'.format((modName, keyName)), writeToFile=False)
else:
Logger.ColorfullyWrite('Register exit hotkey <Color=DarkYellow>{}</Color> unsuccessfully\n'.format((modName, keyName)), writeToFile=False)
funcThread = None
livingThreads = []
stopEvent = threading.Event()
msg = ctypes.wintypes.MSG()
while ctypes.windll.user32.GetMessageW(ctypes.byref(msg), ctypes.c_void_p(0), ctypes.c_uint(0), ctypes.c_uint(0)) != 0:
if msg.message == 0x0312: # WM_HOTKEY=0x0312
if msg.wParam in id2HotKey:
if msg.lParam & 0x0000FFFF == id2HotKey[msg.wParam][0] and msg.lParam >> 16 & 0x0000FFFF == id2HotKey[msg.wParam][1]:
Logger.ColorfullyWrite('----------hotkey <Color=Cyan>{}</Color> pressed----------\n'.format(id2Name[msg.wParam]), writeToFile=False)
if not id2Thread[msg.wParam]:
stopEvent.clear()
funcThread = threading.Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam]))
funcThread.start()
id2Thread[msg.wParam] = funcThread
else:
if id2Thread[msg.wParam].is_alive():
Logger.WriteLine('There is a {} that is already running for hotkey {}'.format(id2Thread[msg.wParam], id2Name[msg.wParam]), ConsoleColor.Yellow, writeToFile=False)
else:
stopEvent.clear()
funcThread = threading.Thread(None, threadFunc, args=(id2Function[msg.wParam], stopEvent, id2HotKey[msg.wParam], id2Name[msg.wParam]))
funcThread.start()
id2Thread[msg.wParam] = funcThread
elif stopHotKeyId == msg.wParam:
if msg.lParam & 0x0000FFFF == stopHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == stopHotKey[1]:
Logger.Write('----------stop hotkey pressed----------\n', ConsoleColor.DarkYellow, writeToFile=False)
stopEvent.set()
for id_ in id2Thread:
if id2Thread[id_]:
if id2Thread[id_].is_alive():
livingThreads.append((id2Thread[id_], id2Name[id_]))
id2Thread[id_] = None
elif exitHotKeyId == msg.wParam:
if msg.lParam & 0x0000FFFF == exitHotKey[0] and msg.lParam >> 16 & 0x0000FFFF == exitHotKey[1]:
Logger.Write('Exit hotkey pressed. Exit\n', ConsoleColor.DarkYellow, writeToFile=False)
stopEvent.set()
for id_ in id2Thread:
if id2Thread[id_]:
if id2Thread[id_].is_alive():
livingThreads.append((id2Thread[id_], id2Name[id_]))
id2Thread[id_] = None
break
for thread, hotkeyName in livingThreads:
if thread.is_alive():
Logger.Write('join {} triggered by hotkey {}\n'.format(thread, hotkeyName), ConsoleColor.DarkYellow, writeToFile=False)
thread.join(2)
os._exit(0)
|
Bind functions with hotkeys, the function will be run or stopped in another thread when the hotkey is pressed.
keyFunctions: Dict[Tuple[int, int], Callable], such as {(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : function}
stopHotKey: hotkey tuple
exitHotKey: hotkey tuple
waitHotKeyReleased: bool, if True, hotkey function will be triggered after the hotkey is released
def main(stopEvent):
while True:
if stopEvent.is_set(): # must check stopEvent.is_set() if you want to stop when stop hotkey is pressed
break
print(n)
n += 1
stopEvent.wait(1)
print('main exit')
uiautomation.RunByHotKey({(uiautomation.ModifierKey.Control, uiautomation.Keys.VK_1) : main}
, (uiautomation.ModifierKey.Control | uiautomation.ModifierKey.Shift, uiautomation.Keys.VK_2))
|
RunByHotKey
|
python
|
cluic/wxauto
|
wxauto/uiautomation.py
|
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
|
Apache-2.0
|
def check_setuptools_features():
"""Check if setuptools is up to date."""
import pkg_resources
try:
list(pkg_resources.parse_requirements('foo~=1.0'))
except ValueError:
sys.exit('Your Python distribution comes with an incompatible version '
'of `setuptools`. Please run:\n'
' $ pip3 install --upgrade setuptools\n'
'and then run this command again')
|
Check if setuptools is up to date.
|
check_setuptools_features
|
python
|
bigchaindb/bigchaindb
|
setup.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/setup.py
|
Apache-2.0
|
def map_leafs(func, mapping):
"""Map a function to the leafs of a mapping."""
def _inner(mapping, path=None):
if path is None:
path = []
for key, val in mapping.items():
if isinstance(val, collections.abc.Mapping):
_inner(val, path + [key])
else:
mapping[key] = func(val, path=path+[key])
return mapping
return _inner(copy.deepcopy(mapping))
|
Map a function to the leafs of a mapping.
|
map_leafs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def update(d, u):
"""Recursively update a mapping (i.e. a dict, list, set, or tuple).
Conceptually, d and u are two sets trees (with nodes and edges).
This function goes through all the nodes of u. For each node in u,
if d doesn't have that node yet, then this function adds the node from u,
otherwise this function overwrites the node already in d with u's node.
Args:
d (mapping): The mapping to overwrite and add to.
u (mapping): The mapping to read for changes.
Returns:
mapping: An updated version of d (updated by u).
"""
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
r = update(d.get(k, {}), v)
d[k] = r
else:
d[k] = u[k]
return d
|
Recursively update a mapping (i.e. a dict, list, set, or tuple).
Conceptually, d and u are two sets trees (with nodes and edges).
This function goes through all the nodes of u. For each node in u,
if d doesn't have that node yet, then this function adds the node from u,
otherwise this function overwrites the node already in d with u's node.
Args:
d (mapping): The mapping to overwrite and add to.
u (mapping): The mapping to read for changes.
Returns:
mapping: An updated version of d (updated by u).
|
update
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def file_config(filename=None):
"""Returns the config values found in a configuration file.
Args:
filename (str): the JSON file with the configuration values.
If ``None``, CONFIG_DEFAULT_PATH will be used.
Returns:
dict: The config values in the specified config file (or the
file at CONFIG_DEFAULT_PATH, if filename == None)
"""
logger.debug('On entry into file_config(), filename = {}'.format(filename))
if filename is None:
filename = CONFIG_DEFAULT_PATH
logger.debug('file_config() will try to open `{}`'.format(filename))
with open(filename) as f:
try:
config = json.load(f)
except ValueError as err:
raise exceptions.ConfigurationError(
'Failed to parse the JSON configuration from `{}`, {}'.format(filename, err)
)
logger.info('Configuration loaded from `{}`'.format(filename))
return config
|
Returns the config values found in a configuration file.
Args:
filename (str): the JSON file with the configuration values.
If ``None``, CONFIG_DEFAULT_PATH will be used.
Returns:
dict: The config values in the specified config file (or the
file at CONFIG_DEFAULT_PATH, if filename == None)
|
file_config
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def env_config(config):
"""Return a new configuration with the values found in the environment.
The function recursively iterates over the config, checking if there is
a matching env variable. If an env variable is found, the func updates
the configuration with that value.
The name of the env variable is built combining a prefix (``BIGCHAINDB``)
with the path to the value. If the ``config`` in input is:
``{'database': {'host': 'localhost'}}``
this function will try to read the env variable ``BIGCHAINDB_DATABASE_HOST``.
"""
def load_from_env(value, path):
var_name = CONFIG_SEP.join([CONFIG_PREFIX] + list(map(lambda s: s.upper(), path)))
return os.environ.get(var_name, value)
return map_leafs(load_from_env, config)
|
Return a new configuration with the values found in the environment.
The function recursively iterates over the config, checking if there is
a matching env variable. If an env variable is found, the func updates
the configuration with that value.
The name of the env variable is built combining a prefix (``BIGCHAINDB``)
with the path to the value. If the ``config`` in input is:
``{'database': {'host': 'localhost'}}``
this function will try to read the env variable ``BIGCHAINDB_DATABASE_HOST``.
|
env_config
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def update_types(config, reference, list_sep=':'):
"""Return a new configuration where all the values types
are aligned with the ones in the default configuration
"""
def _coerce(current, value):
# Coerce a value to the `current` type.
try:
# First we try to apply current to the value, since it
# might be a function
return current(value)
except TypeError:
# Then we check if current is a list AND if the value
# is a string.
if isinstance(current, list) and isinstance(value, str):
# If so, we use the colon as the separator
return value.split(list_sep)
try:
# If we are here, we should try to apply the type
# of `current` to the value
return type(current)(value)
except TypeError:
# Worst case scenario we return the value itself.
return value
def _update_type(value, path):
current = reference
for elem in path:
try:
current = current[elem]
except KeyError:
return value
return _coerce(current, value)
return map_leafs(_update_type, config)
|
Return a new configuration where all the values types
are aligned with the ones in the default configuration
|
update_types
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def set_config(config):
"""Set bigchaindb.config equal to the default config dict,
then update that with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
Note:
Any previous changes made to ``bigchaindb.config`` will be lost.
"""
# Deep copy the default config into bigchaindb.config
bigchaindb.config = copy.deepcopy(bigchaindb._config)
# Update the default config with whatever is in the passed config
update(bigchaindb.config, update_types(config, bigchaindb.config))
bigchaindb.config['CONFIGURED'] = True
|
Set bigchaindb.config equal to the default config dict,
then update that with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
Note:
Any previous changes made to ``bigchaindb.config`` will be lost.
|
set_config
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def update_config(config):
"""Update bigchaindb.config with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
"""
# Update the default config with whatever is in the passed config
update(bigchaindb.config, update_types(config, bigchaindb.config))
bigchaindb.config['CONFIGURED'] = True
|
Update bigchaindb.config with whatever is in the provided config dict,
and then set bigchaindb.config['CONFIGURED'] = True
Args:
config (dict): the config dict to read for changes
to the default config
|
update_config
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def write_config(config, filename=None):
"""Write the provided configuration to a specific location.
Args:
config (dict): a dictionary with the configuration to load.
filename (str): the name of the file that will store the new configuration. Defaults to ``None``.
If ``None``, the HOME of the current user and the string ``.bigchaindb`` will be used.
"""
if not filename:
filename = CONFIG_DEFAULT_PATH
with open(filename, 'w') as f:
json.dump(config, f, indent=4)
|
Write the provided configuration to a specific location.
Args:
config (dict): a dictionary with the configuration to load.
filename (str): the name of the file that will store the new configuration. Defaults to ``None``.
If ``None``, the HOME of the current user and the string ``.bigchaindb`` will be used.
|
write_config
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def autoconfigure(filename=None, config=None, force=False):
"""Run ``file_config`` and ``env_config`` if the module has not
been initialized.
"""
if not force and is_configured():
logger.debug('System already configured, skipping autoconfiguration')
return
# start with the current configuration
newconfig = bigchaindb.config
# update configuration from file
try:
newconfig = update(newconfig, file_config(filename=filename))
except FileNotFoundError as e:
if filename:
raise
else:
logger.info('Cannot find config file `%s`.' % e.filename)
# override configuration with env variables
newconfig = env_config(newconfig)
if config:
newconfig = update(newconfig, config)
set_config(newconfig) # sets bigchaindb.config
|
Run ``file_config`` and ``env_config`` if the module has not
been initialized.
|
autoconfigure
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def load_validation_plugin(name=None):
"""Find and load the chosen validation plugin.
Args:
name (string): the name of the entry_point, as advertised in the
setup.py of the providing package.
Returns:
an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules``
"""
if not name:
return BaseValidationRules
# TODO: This will return the first plugin with group `bigchaindb.validation`
# and name `name` in the active WorkingSet.
# We should probably support Requirements specs in the config, e.g.
# validation_plugin: 'my-plugin-package==0.0.1;default'
plugin = None
for entry_point in iter_entry_points('bigchaindb.validation', name):
plugin = entry_point.load()
# No matching entry_point found
if not plugin:
raise ResolutionError(
'No plugin found in group `bigchaindb.validation` with name `{}`'.
format(name))
# Is this strictness desireable?
# It will probably reduce developer headaches in the wild.
if not issubclass(plugin, (BaseValidationRules,)):
raise TypeError('object of type "{}" does not implement `bigchaindb.'
'validation.BaseValidationRules`'.format(type(plugin)))
return plugin
|
Find and load the chosen validation plugin.
Args:
name (string): the name of the entry_point, as advertised in the
setup.py of the providing package.
Returns:
an uninstantiated subclass of ``bigchaindb.validation.AbstractValidationRules``
|
load_validation_plugin
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/config_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/config_utils.py
|
Apache-2.0
|
def init_chain(self, genesis):
"""Initialize chain upon genesis or a migration"""
app_hash = ''
height = 0
known_chain = self.bigchaindb.get_latest_abci_chain()
if known_chain is not None:
chain_id = known_chain['chain_id']
if known_chain['is_synced']:
msg = (f'Got invalid InitChain ABCI request ({genesis}) - '
f'the chain {chain_id} is already synced.')
logger.error(msg)
sys.exit(1)
if chain_id != genesis.chain_id:
validators = self.bigchaindb.get_validators()
self.log_abci_migration_error(chain_id, validators)
sys.exit(1)
# set migration values for app hash and height
block = self.bigchaindb.get_latest_block()
app_hash = '' if block is None else block['app_hash']
height = 0 if block is None else block['height'] + 1
known_validators = self.bigchaindb.get_validators()
validator_set = [vutils.decode_validator(v)
for v in genesis.validators]
if known_validators and known_validators != validator_set:
self.log_abci_migration_error(known_chain['chain_id'],
known_validators)
sys.exit(1)
block = Block(app_hash=app_hash, height=height, transactions=[])
self.bigchaindb.store_block(block._asdict())
self.bigchaindb.store_validator_set(height + 1, validator_set)
abci_chain_height = 0 if known_chain is None else known_chain['height']
self.bigchaindb.store_abci_chain(abci_chain_height,
genesis.chain_id, True)
self.chain = {'height': abci_chain_height, 'is_synced': True,
'chain_id': genesis.chain_id}
return self.abci.ResponseInitChain()
|
Initialize chain upon genesis or a migration
|
init_chain
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def check_tx(self, raw_transaction):
"""Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('check_tx: %s', raw_transaction)
transaction = decode_transaction(raw_transaction)
if self.bigchaindb.is_valid_transaction(transaction):
logger.debug('check_tx: VALID')
return self.abci.ResponseCheckTx(code=CodeTypeOk)
else:
logger.debug('check_tx: INVALID')
return self.abci.ResponseCheckTx(code=CodeTypeError)
|
Validate the transaction before entry into
the mempool.
Args:
raw_tx: a raw string (in bytes) transaction.
|
check_tx
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def begin_block(self, req_begin_block):
"""Initialize list of transaction.
Args:
req_begin_block: block object which contains block header
and block hash.
"""
self.abort_if_abci_chain_is_not_synced()
chain_shift = 0 if self.chain is None else self.chain['height']
logger.debug('BEGIN BLOCK, height:%s, num_txs:%s',
req_begin_block.header.height + chain_shift,
req_begin_block.header.num_txs)
self.block_txn_ids = []
self.block_transactions = []
return self.abci.ResponseBeginBlock()
|
Initialize list of transaction.
Args:
req_begin_block: block object which contains block header
and block hash.
|
begin_block
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def deliver_tx(self, raw_transaction):
"""Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
"""
self.abort_if_abci_chain_is_not_synced()
logger.debug('deliver_tx: %s', raw_transaction)
transaction = self.bigchaindb.is_valid_transaction(
decode_transaction(raw_transaction), self.block_transactions)
if not transaction:
logger.debug('deliver_tx: INVALID')
return self.abci.ResponseDeliverTx(code=CodeTypeError)
else:
logger.debug('storing tx')
self.block_txn_ids.append(transaction.id)
self.block_transactions.append(transaction)
return self.abci.ResponseDeliverTx(code=CodeTypeOk)
|
Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction.
|
deliver_tx
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def end_block(self, request_end_block):
"""Calculate block hash using transaction ids and previous block
hash to be stored in the next block.
Args:
height (int): new height of the chain.
"""
self.abort_if_abci_chain_is_not_synced()
chain_shift = 0 if self.chain is None else self.chain['height']
height = request_end_block.height + chain_shift
self.new_height = height
# store pre-commit state to recover in case there is a crash during
# `end_block` or `commit`
logger.debug(f'Updating pre-commit state: {self.new_height}')
pre_commit_state = dict(height=self.new_height,
transactions=self.block_txn_ids)
self.bigchaindb.store_pre_commit_state(pre_commit_state)
block_txn_hash = calculate_hash(self.block_txn_ids)
block = self.bigchaindb.get_latest_block()
if self.block_txn_ids:
self.block_txn_hash = calculate_hash([block['app_hash'], block_txn_hash])
else:
self.block_txn_hash = block['app_hash']
validator_update = Election.process_block(self.bigchaindb,
self.new_height,
self.block_transactions)
return self.abci.ResponseEndBlock(validator_updates=validator_update)
|
Calculate block hash using transaction ids and previous block
hash to be stored in the next block.
Args:
height (int): new height of the chain.
|
end_block
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def commit(self):
"""Store the new height and along with block hash."""
self.abort_if_abci_chain_is_not_synced()
data = self.block_txn_hash.encode('utf-8')
# register a new block only when new transactions are received
if self.block_txn_ids:
self.bigchaindb.store_bulk_transactions(self.block_transactions)
block = Block(app_hash=self.block_txn_hash,
height=self.new_height,
transactions=self.block_txn_ids)
# NOTE: storing the block should be the last operation during commit
# this effects crash recovery. Refer BEP#8 for details
self.bigchaindb.store_block(block._asdict())
logger.debug('Commit-ing new block with hash: apphash=%s ,'
'height=%s, txn ids=%s', data, self.new_height,
self.block_txn_ids)
if self.events_queue:
event = Event(EventTypes.BLOCK_VALID, {
'height': self.new_height,
'transactions': self.block_transactions
})
self.events_queue.put(event)
return self.abci.ResponseCommit(data=data)
|
Store the new height and along with block hash.
|
commit
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/core.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/core.py
|
Apache-2.0
|
def __init__(self, event_type, event_data):
"""Creates a new event.
Args:
event_type (int): the type of the event, see
:class:`~bigchaindb.events.EventTypes`
event_data (obj): the data of the event.
"""
self.type = event_type
self.data = event_data
|
Creates a new event.
Args:
event_type (int): the type of the event, see
:class:`~bigchaindb.events.EventTypes`
event_data (obj): the data of the event.
|
__init__
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/events.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
|
Apache-2.0
|
def get_subscriber_queue(self, event_types=None):
"""Create a new queue for a specific combination of event types
and return it.
Returns:
a :class:`multiprocessing.Queue`.
Raises:
RuntimeError if called after `run`
"""
try:
self.started_queue.get(timeout=1)
raise RuntimeError('Cannot create a new subscriber queue while Exchange is running.')
except Empty:
pass
if event_types is None:
event_types = EventTypes.ALL
queue = Queue()
self.queues[event_types].append(queue)
return queue
|
Create a new queue for a specific combination of event types
and return it.
Returns:
a :class:`multiprocessing.Queue`.
Raises:
RuntimeError if called after `run`
|
get_subscriber_queue
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/events.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
|
Apache-2.0
|
def dispatch(self, event):
"""Given an event, send it to all the subscribers.
Args
event (:class:`~bigchaindb.events.EventTypes`): the event to
dispatch to all the subscribers.
"""
for event_types, queues in self.queues.items():
if event.type & event_types:
for queue in queues:
queue.put(event)
|
Given an event, send it to all the subscribers.
Args
event (:class:`~bigchaindb.events.EventTypes`): the event to
dispatch to all the subscribers.
|
dispatch
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/events.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/events.py
|
Apache-2.0
|
def filter_spent_outputs(self, outputs):
"""Remove outputs that have been spent
Args:
outputs: list of TransactionLink
"""
links = [o.to_dict() for o in outputs]
txs = list(query.get_spending_transactions(self.connection, links))
spends = {TransactionLink.from_dict(input_['fulfills'])
for tx in txs
for input_ in tx['inputs']}
return [ff for ff in outputs if ff not in spends]
|
Remove outputs that have been spent
Args:
outputs: list of TransactionLink
|
filter_spent_outputs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/fastquery.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/fastquery.py
|
Apache-2.0
|
def filter_unspent_outputs(self, outputs):
"""Remove outputs that have not been spent
Args:
outputs: list of TransactionLink
"""
links = [o.to_dict() for o in outputs]
txs = list(query.get_spending_transactions(self.connection, links))
spends = {TransactionLink.from_dict(input_['fulfills'])
for tx in txs
for input_ in tx['inputs']}
return [ff for ff in outputs if ff in spends]
|
Remove outputs that have not been spent
Args:
outputs: list of TransactionLink
|
filter_unspent_outputs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/fastquery.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/fastquery.py
|
Apache-2.0
|
def __init__(self, connection=None):
"""Initialize the Bigchain instance
A Bigchain instance has several configuration parameters (e.g. host).
If a parameter value is passed as an argument to the Bigchain
__init__ method, then that is the value it will have.
Otherwise, the parameter value will come from an environment variable.
If that environment variable isn't set, then the value
will come from the local configuration file. And if that variable
isn't in the local configuration file, then the parameter will have
its default value (defined in bigchaindb.__init__).
Args:
connection (:class:`~bigchaindb.backend.connection.Connection`):
A connection to the database.
"""
config_utils.autoconfigure()
self.mode_commit = BROADCAST_TX_COMMIT
self.mode_list = (BROADCAST_TX_ASYNC,
BROADCAST_TX_SYNC,
self.mode_commit)
self.tendermint_host = bigchaindb.config['tendermint']['host']
self.tendermint_port = bigchaindb.config['tendermint']['port']
self.endpoint = 'http://{}:{}/'.format(self.tendermint_host, self.tendermint_port)
validationPlugin = bigchaindb.config.get('validation_plugin')
if validationPlugin:
self.validation = config_utils.load_validation_plugin(validationPlugin)
else:
self.validation = BaseValidationRules
self.connection = connection if connection else backend.connect(**bigchaindb.config['database'])
|
Initialize the Bigchain instance
A Bigchain instance has several configuration parameters (e.g. host).
If a parameter value is passed as an argument to the Bigchain
__init__ method, then that is the value it will have.
Otherwise, the parameter value will come from an environment variable.
If that environment variable isn't set, then the value
will come from the local configuration file. And if that variable
isn't in the local configuration file, then the parameter will have
its default value (defined in bigchaindb.__init__).
Args:
connection (:class:`~bigchaindb.backend.connection.Connection`):
A connection to the database.
|
__init__
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def update_utxoset(self, transaction):
"""Update the UTXO set given ``transaction``. That is, remove
the outputs that the given ``transaction`` spends, and add the
outputs that the given ``transaction`` creates.
Args:
transaction (:obj:`~bigchaindb.models.Transaction`): A new
transaction incoming into the system for which the UTXO
set needs to be updated.
"""
spent_outputs = [
spent_output for spent_output in transaction.spent_outputs
]
if spent_outputs:
self.delete_unspent_outputs(*spent_outputs)
self.store_unspent_outputs(
*[utxo._asdict() for utxo in transaction.unspent_outputs]
)
|
Update the UTXO set given ``transaction``. That is, remove
the outputs that the given ``transaction`` spends, and add the
outputs that the given ``transaction`` creates.
Args:
transaction (:obj:`~bigchaindb.models.Transaction`): A new
transaction incoming into the system for which the UTXO
set needs to be updated.
|
update_utxoset
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def store_unspent_outputs(self, *unspent_outputs):
"""Store the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs.
"""
if unspent_outputs:
return backend.query.store_unspent_outputs(
self.connection, *unspent_outputs)
|
Store the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs.
|
store_unspent_outputs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def get_unspent_outputs(self):
"""Get the utxoset.
Returns:
generator of unspent_outputs.
"""
cursor = backend.query.get_unspent_outputs(self.connection)
return (record for record in cursor)
|
Get the utxoset.
Returns:
generator of unspent_outputs.
|
get_unspent_outputs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def delete_unspent_outputs(self, *unspent_outputs):
"""Deletes the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs.
"""
if unspent_outputs:
return backend.query.delete_unspent_outputs(
self.connection, *unspent_outputs)
|
Deletes the given ``unspent_outputs`` (utxos).
Args:
*unspent_outputs (:obj:`tuple` of :obj:`dict`): Variable
length tuple or list of unspent outputs.
|
delete_unspent_outputs
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def get_transactions_filtered(self, asset_id, operation=None, last_tx=None):
"""Get a list of transactions filtered on some criteria
"""
txids = backend.query.get_txids_filtered(self.connection, asset_id,
operation, last_tx)
for txid in txids:
yield self.get_transaction(txid)
|
Get a list of transactions filtered on some criteria
|
get_transactions_filtered
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def get_outputs_filtered(self, owner, spent=None):
"""Get a list of output links filtered on some criteria
Args:
owner (str): base58 encoded public_key.
spent (bool): If ``True`` return only the spent outputs. If
``False`` return only unspent outputs. If spent is
not specified (``None``) return all outputs.
Returns:
:obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s
pointing to another transaction's condition
"""
outputs = self.fastquery.get_outputs_by_public_key(owner)
if spent is None:
return outputs
elif spent is True:
return self.fastquery.filter_unspent_outputs(outputs)
elif spent is False:
return self.fastquery.filter_spent_outputs(outputs)
|
Get a list of output links filtered on some criteria
Args:
owner (str): base58 encoded public_key.
spent (bool): If ``True`` return only the spent outputs. If
``False`` return only unspent outputs. If spent is
not specified (``None``) return all outputs.
Returns:
:obj:`list` of TransactionLink: list of ``txid`` s and ``output`` s
pointing to another transaction's condition
|
get_outputs_filtered
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def get_block(self, block_id):
"""Get the block with the specified `block_id`.
Returns the block corresponding to `block_id` or None if no match is
found.
Args:
block_id (int): block id of the block to get.
"""
block = backend.query.get_block(self.connection, block_id)
latest_block = self.get_latest_block()
latest_block_height = latest_block['height'] if latest_block else 0
if not block and block_id > latest_block_height:
return
result = {'height': block_id,
'transactions': []}
if block:
transactions = backend.query.get_transactions(self.connection, block['transactions'])
result['transactions'] = [t.to_dict() for t in Transaction.from_db(self, transactions)]
return result
|
Get the block with the specified `block_id`.
Returns the block corresponding to `block_id` or None if no match is
found.
Args:
block_id (int): block id of the block to get.
|
get_block
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def get_block_containing_tx(self, txid):
"""Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int))
"""
blocks = list(backend.query.get_block_with_transaction(self.connection, txid))
if len(blocks) > 1:
logger.critical('Transaction id %s exists in multiple blocks', txid)
return [block['height'] for block in blocks]
|
Retrieve the list of blocks (block ids) containing a
transaction with transaction id `txid`
Args:
txid (str): transaction id of the transaction to query
Returns:
Block id list (list(int))
|
get_block_containing_tx
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def validate_transaction(self, tx, current_transactions=[]):
"""Validate a transaction against the current status of the database."""
transaction = tx
# CLEANUP: The conditional below checks for transaction in dict format.
# It would be better to only have a single format for the transaction
# throught the code base.
if isinstance(transaction, dict):
try:
transaction = Transaction.from_dict(tx)
except SchemaValidationError as e:
logger.warning('Invalid transaction schema: %s', e.__cause__.message)
return False
except ValidationError as e:
logger.warning('Invalid transaction (%s): %s', type(e).__name__, e)
return False
return transaction.validate(self, current_transactions)
|
Validate a transaction against the current status of the database.
|
validate_transaction
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def migrate_abci_chain(self):
"""Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
`chain-X` => `chain-X-migrated-at-height-5`.
`chain-X-migrated-at-height-5` => `chain-X-migrated-at-height-21`.
If there is no known chain (we are at genesis), the function returns.
"""
latest_chain = self.get_latest_abci_chain()
if latest_chain is None:
return
block = self.get_latest_block()
suffix = '-migrated-at-height-'
chain_id = latest_chain['chain_id']
block_height_str = str(block['height'])
new_chain_id = chain_id.split(suffix)[0] + suffix + block_height_str
self.store_abci_chain(block['height'] + 1, new_chain_id, False)
|
Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
`chain-X` => `chain-X-migrated-at-height-5`.
`chain-X-migrated-at-height-5` => `chain-X-migrated-at-height-21`.
If there is no known chain (we are at genesis), the function returns.
|
migrate_abci_chain
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/lib.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/lib.py
|
Apache-2.0
|
def setup_logging():
"""Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`bigchaindb.config` at the moment this decorator
is invoked.
"""
logging_configs = DEFAULT_LOGGING_CONFIG
new_logging_configs = bigchaindb.config['log']
if 'file' in new_logging_configs:
filename = new_logging_configs['file']
logging_configs['handlers']['file']['filename'] = filename
if 'error_file' in new_logging_configs:
error_filename = new_logging_configs['error_file']
logging_configs['handlers']['errors']['filename'] = error_filename
if 'level_console' in new_logging_configs:
level = _normalize_log_level(new_logging_configs['level_console'])
logging_configs['handlers']['console']['level'] = level
if 'level_logfile' in new_logging_configs:
level = _normalize_log_level(new_logging_configs['level_logfile'])
logging_configs['handlers']['file']['level'] = level
if 'fmt_console' in new_logging_configs:
fmt = new_logging_configs['fmt_console']
logging_configs['formatters']['console']['format'] = fmt
if 'fmt_logfile' in new_logging_configs:
fmt = new_logging_configs['fmt_logfile']
logging_configs['formatters']['file']['format'] = fmt
if 'datefmt_console' in new_logging_configs:
fmt = new_logging_configs['datefmt_console']
logging_configs['formatters']['console']['datefmt'] = fmt
if 'datefmt_logfile' in new_logging_configs:
fmt = new_logging_configs['datefmt_logfile']
logging_configs['formatters']['file']['datefmt'] = fmt
log_levels = new_logging_configs.get('granular_levels', {})
for logger_name, level in log_levels.items():
level = _normalize_log_level(level)
try:
logging_configs['loggers'][logger_name]['level'] = level
except KeyError:
logging_configs['loggers'][logger_name] = {'level': level}
set_logging_config(logging_configs)
|
Function to configure log hadlers.
.. important::
Configuration, if needed, should be applied before invoking this
decorator, as starting the subscriber process for logging will
configure the root logger for the child process based on the
state of :obj:`bigchaindb.config` at the moment this decorator
is invoked.
|
setup_logging
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/log.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/log.py
|
Apache-2.0
|
def validate(self, bigchain, current_transactions=[]):
"""Validate transaction spend
Args:
bigchain (BigchainDB): an instantiated bigchaindb.BigchainDB object.
Returns:
The transaction (Transaction) if the transaction is valid else it
raises an exception describing the reason why the transaction is
invalid.
Raises:
ValidationError: If the transaction is invalid
"""
input_conditions = []
if self.operation == Transaction.CREATE:
duplicates = any(txn for txn in current_transactions if txn.id == self.id)
if bigchain.is_committed(self.id) or duplicates:
raise DuplicateTransaction('transaction `{}` already exists'
.format(self.id))
if not self.inputs_valid(input_conditions):
raise InvalidSignature('Transaction signature is invalid.')
elif self.operation == Transaction.TRANSFER:
self.validate_transfer_inputs(bigchain, current_transactions)
return self
|
Validate transaction spend
Args:
bigchain (BigchainDB): an instantiated bigchaindb.BigchainDB object.
Returns:
The transaction (Transaction) if the transaction is valid else it
raises an exception describing the reason why the transaction is
invalid.
Raises:
ValidationError: If the transaction is invalid
|
validate
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/models.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/models.py
|
Apache-2.0
|
def merkleroot(hashes):
"""Computes the merkle root for a given list.
Args:
hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree.
Returns:
str: Merkle root in hexadecimal form.
"""
# XXX TEMPORARY -- MUST REVIEW and possibly CHANGE
# The idea here is that the UTXO SET would be empty and this function
# would be invoked to compute the merkle root, and since there is nothing,
# i.e. an empty list, then the hash of the empty string is returned.
# This seems too easy but maybe that is good enough? TO REVIEW!
if not hashes:
return sha3_256(b'').hexdigest()
# XXX END TEMPORARY -- MUST REVIEW ...
if len(hashes) == 1:
return hexlify(hashes[0]).decode()
if len(hashes) % 2 == 1:
hashes.append(hashes[-1])
parent_hashes = [
sha3_256(hashes[i] + hashes[i+1]).digest()
for i in range(0, len(hashes)-1, 2)
]
return merkleroot(parent_hashes)
|
Computes the merkle root for a given list.
Args:
hashes (:obj:`list` of :obj:`bytes`): The leaves of the tree.
Returns:
str: Merkle root in hexadecimal form.
|
merkleroot
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/tendermint_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/tendermint_utils.py
|
Apache-2.0
|
def public_key64_to_address(base64_public_key):
"""Note this only compatible with Tendermint 0.19.x"""
ed25519_public_key = public_key_from_base64(base64_public_key)
encoded_public_key = amino_encoded_public_key(ed25519_public_key)
return hashlib.new('ripemd160', encoded_public_key).hexdigest().upper()
|
Note this only compatible with Tendermint 0.19.x
|
public_key64_to_address
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/tendermint_utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/tendermint_utils.py
|
Apache-2.0
|
def condition_details_has_owner(condition_details, owner):
"""Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherwise
"""
if 'subconditions' in condition_details:
result = condition_details_has_owner(condition_details['subconditions'], owner)
if result:
return True
elif isinstance(condition_details, list):
for subcondition in condition_details:
result = condition_details_has_owner(subcondition, owner)
if result:
return True
else:
if 'public_key' in condition_details \
and owner == condition_details['public_key']:
return True
return False
|
Check if the public_key of owner is in the condition details
as an Ed25519Fulfillment.public_key
Args:
condition_details (dict): dict with condition details
owner (str): base58 public key of owner
Returns:
bool: True if the public key is found in the condition details, False otherwise
|
condition_details_has_owner
|
python
|
bigchaindb/bigchaindb
|
bigchaindb/utils.py
|
https://github.com/bigchaindb/bigchaindb/blob/master/bigchaindb/utils.py
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.