def plt_patch(node: minidom.Element, trans_parent_trans: mtransforms.Transform, style: dict, constructor: callable, ids: dict, no_draw: bool = False) -> mpatches.Patch: """ add a node to the figure by calling the provided constructor """ trans_node = parseTransformation(node.getAttribute("transform")) style = get_inline_style(node, get_css_style(node, ids["css"], style)) patch = constructor(node, trans_node + trans_parent_trans + plt.gca().transData, style, ids) if not isinstance(patch, list): patch = [patch] for p in patch: if not getattr(p, "is_marker", False): style = apply_style(style, p) p.style = style #p.set_transform(p.get_transform() + plt.gca().transData) p.trans_parent = trans_parent_trans p.trans_node = parseTransformation(node.getAttribute("transform")) if not no_draw and not styleNoDisplay(style): plt.gca().add_patch(p) if node.getAttribute("id") != "": ids[node.getAttribute("id")] = patch return patch
def parseTime_(element: Element, rateInfo: RateInfo_): start = TtmlTextParser.parseTimeAttribute_(element.getAttribute('begin'), rateInfo) end = TtmlTextParser.parseTimeAttribute_(element.getAttribute('end'), rateInfo) duration = TtmlTextParser.parseTimeAttribute_(element.getAttribute('dur'), rateInfo) if end is None and duration is not None: end = start + duration return start, end
def __positionAndSetupDiagramFrame( self, umlFrame: UmlDiagramsFrame, documentNode: Element, ): xStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_SCROLL_POSITION_X) yStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_SCROLL_POSITION_Y) scrollPosX: int = PyutUtils.secureInteger(xStr) scrollPosY: int = PyutUtils.secureInteger(yStr) umlFrame.Scroll(scrollPosX, scrollPosY) xPerUnitStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_PIXELS_PER_UNIT_X) yPerUnitStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_PIXELS_PER_UNIT_Y) pixelsPerUnitX: int = PyutUtils.secureInteger(xPerUnitStr) pixelsPerUnitY: int = PyutUtils.secureInteger(yPerUnitStr) if pixelsPerUnitX != 0 and pixelsPerUnitY != 0: umlFrame.SetScrollRate(xstep=pixelsPerUnitX, ystep=pixelsPerUnitY)
def patch_circle(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict) -> mpatches.Circle: """ draw a svg circle node as a circle patch element into the figure (with the given transformation and style) """ if node.getAttribute("d") != "": return patch_path(node, trans, style, ids) return mpatches.Circle(xy=(float(node.getAttribute("cx")), float(node.getAttribute("cy"))), radius=float(node.getAttribute("r")), transform=trans)
def __init__(self, dom_element: Element) -> None: self._dom_element = dom_element message_cdata = dom_element.getElementsByTagName('log4j:message')[0].firstChild message_cdata_string = '' if message_cdata is not None: message_cdata_string = message_cdata.data throwable_list = self._dom_element.getElementsByTagName('log4j:throwable') if len(throwable_list) == 1: throwable_element = throwable_list[0] else: throwable_element = dom_element.ownerDocument.createElementNS('log4j', 'throwable') location_info_list = self._dom_element.getElementsByTagName('log4j:locationInfo') if len(location_info_list) == 1: location_info_element = location_info_list[0] else: location_info_element = self._dom_element.ownerDocument.createElementNS('log4j', 'locationInfo') location_info = DomLocationInfo(location_info_element) Event.__init__( self, dom_element.getAttribute("logger"), dom_element.getAttribute("timestamp"), dom_element.getAttribute("level"), dom_element.getAttribute("thread"), message_cdata_string, throwable_element, location_info )
def get_inline_style(node: minidom.Element, base_style: dict = None) -> dict: """ update the basestyle with the style defined by the style property of the node """ style = {} if base_style is not None: style.update(base_style) attribute_names = [ "alignment-baseline", "baseline-shift", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-rendering", "cursor", "direction", "display", "dominant-baseline", "fill", "fill-opacity", "fill-rule", "filter", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "glyph-orientation-horizontal", "glyph-orientation-vertical", "image-rendering", "letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "overflow", "paint-order", "pointer-events", "shape-rendering", "stop-color", "stop-opacity", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", "text-overflow", "text-rendering", "unicode-bidi", "vector-effect", "visibility", "white-space", "word-spacing", "writing-mode" ] for name in attribute_names: value = node.getAttribute(name) if value != "": style[name] = value for element in node.getAttribute("style").split(";"): if element == "": continue key, value = element.split(":", 1) style[key] = value return style
def __init__(self, dom_element: Element) -> None: LocationInfo.__init__( self, dom_element.getAttribute("class"), dom_element.getAttribute("method"), dom_element.getAttribute("file"), dom_element.getAttribute("line"), )
def _getParam(self, domElement: Element) -> PyutParam: pyutParam: PyutParam = PyutParam(name=domElement.getAttribute('name'), theParameterType=domElement.getAttribute('type')) if domElement.hasAttribute('defaultValue'): pyutParam.setDefaultValue(domElement.getAttribute('defaultValue')) return pyutParam
def from_dom(cls, xml: minidom.Element, param: TypeDescriptor, registry: ObjectRegistry): return cls( param.value_from_xml_element(xml_first_element_child(xml), registry), FrameTime.parse_string(xml.getAttribute("time"), registry), Interpolation(xml.getAttribute("before")), Interpolation(xml.getAttribute("after")))
def from_xml(_, x: minidom.Element): fill = not x.hasAttribute("fill") or not x.getAttribute( "fill") == "none" center = Point(float(x.getAttribute("cx")), float(x.getAttribute("cy"))) radius = Radius(float(x.getAttribute("r"))) return SVGCircle(center, radius, fill=fill)
def patch_ellipse(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict) -> mpatches.Ellipse: """ draw a svg ellipse node as a ellipse patch element into the figure (with the given transformation and style) """ if node.getAttribute("d") != "": return patch_path(node, trans, style, ids) return mpatches.Ellipse(xy=(float(node.getAttribute("cx")), float(node.getAttribute("cy"))), width=float(node.getAttribute("rx"))*2, height=float(node.getAttribute("ry"))*2, transform=trans)
def parse_version_from_dom(dom: Element) -> AppVersion: try: version_code = int(dom.getAttribute("android:versionCode")) except ValueError: version_code = None return AppVersion( code=version_code, name=dom.getAttribute("android:versionName") )
def from_xml(_, x: minidom.Element): fill = not x.hasAttribute("fill") or not x.getAttribute( "fill") == "none" start_pos = Point(float(x.getAttribute("x1") or 0.), float(x.getAttribute("y1") or 0.)) end_pos = Point(float(x.getAttribute("x2") or 0.), float(x.getAttribute("y2") or 0.)) return SVGLine(start_pos, end_pos, fill=fill)
def from_xml(cls, x: minidom.Element): fill = not x.hasAttribute("fill") or not x.getAttribute( "fill") == "none" args = extract_args(x.getAttribute("points")) assert len( args ) % 2 == 0, f"Expected even number of arguments for SVGPolyline: {len(args)} given" points = [Point(x, args[2 * i + 1]) for i, x in enumerate(args[::2])] return cls(points, fill=fill)
def patch_rect(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict) -> mpatches.Rectangle: """ draw a svg rectangle node as a rectangle patch element into the figure (with the given transformation and style) """ if node.getAttribute("d") != "": return patch_path(node, trans, style, ids) return mpatches.Rectangle(xy=(float(node.getAttribute("x")), float(node.getAttribute("y"))), width=float(node.getAttribute("width")), height=float(node.getAttribute("height")), transform=trans)
def cascade_element_style( element: MinidomElement, inherited: dict[str, str], ) -> dict[str, str]: """Collect the element's style attributes based upon both its inheritance and its own attributes. SVG uses cascading element styles. A closer ancestor's style takes precedence over a more distant ancestor's style. In order to correctly calculate the styles, the attributes are passed down through the inheritance tree, updating where necessary. Note that this method only copies the values and does not parse them. See :meth:`parse_color_string` for converting from SVG attributes to manim keyword arguments. Parameters ---------- element : :class:`MinidomElement` Element of the SVG parse tree inherited : :class:`dict` Dictionary of SVG attributes inherited from the parent element. Returns ------- :class:`dict` Dictionary mapping svg attributes to values with `element`'s values overriding inherited values. """ style = inherited.copy() # cascade the regular elements. for attr in CASCADING_STYLING_ATTRIBUTES: entry = element.getAttribute(attr) if entry: style[attr] = entry # the style attribute should be handled separately in order to # break it up nicely. furthermore, style takes priority over other # attributes in the same element. style_specs = element.getAttribute("style") if style_specs: for style_spec in style_specs.split(";"): try: key, value = style_spec.split(":") except ValueError as e: if not style_spec.strip(): # there was just a stray semicolon at the end, producing an emptystring pass else: raise e else: style[key.strip()] = value.strip() return style
def plt_draw_text(node: minidom.Element, trans: mtransforms.Transform, style: dict, ids: dict, no_draw: bool = False): """ draw a svg text node as a text patch element into the figure (with the given transformation and style) """ trans = parseTransformation( node.getAttribute("transform")) + trans + plt.gca().transData trans = mtransforms.Affine2D([[1, 0, 0], [0, -1, 0], [0, 0, 1]]) + trans pos = np.array([ svgUnitToMpl(node.getAttribute("x")), -svgUnitToMpl(node.getAttribute("y")) ]) style = get_inline_style(node, get_css_style(node, ids["css"], style)) text_content = "" patch_list = [] for child in node.childNodes: text_content += child.firstChild.nodeValue if 1: style_child = get_inline_style( child, get_css_style(child, ids["css"], style)) pos_child = pos.copy() if child.getAttribute("x") != "": pos_child = np.array([ svgUnitToMpl(child.getAttribute("x")), -svgUnitToMpl(child.getAttribute("y")) ]) if child.getAttribute("dx") != "": pos_child[0] += svgUnitToMpl(child.getAttribute("dx")) if child.getAttribute("dy") != "": pos_child[1] -= svgUnitToMpl(child.getAttribute("dy")) path1 = TextPath(pos_child, child.firstChild.nodeValue, prop=font_properties_from_style(style_child)) patch = mpatches.PathPatch(path1, transform=trans) apply_style(style_child, patch) if not no_draw and not styleNoDisplay(style_child): plt.gca().add_patch(patch) if child.getAttribute("id") != "": ids[child.getAttribute("id")] = patch patch_list.append(patch) else: text = plt.text(float(child.getAttribute("x")), float(child.getAttribute("y")), child.firstChild.nodeValue, transform=trans) apply_style(style, text) if node.getAttribute("id") != "": ids[node.getAttribute("id")] = patch_list
def from_xml(_, x: minidom.Element): fill = not x.hasAttribute("fill") or not x.getAttribute( "fill") == "none" xy = Point(0.) if x.hasAttribute("x"): xy.pos[0] = float(x.getAttribute("x")) if x.hasAttribute("y"): xy.pos[1] = float(x.getAttribute("y")) wh = Size(float(x.getAttribute("width")), float(x.getAttribute("height"))) return SVGRectangle(xy, wh, fill=fill)
def _getParam(self, xmlParam: Element) -> ParameterDefinition: paramName: str = xmlParam.getAttribute(ATTR_NAME) paramType: str = xmlParam.getAttribute(ATTR_TYPE) defaultValue: str = xmlParam.getAttribute(ATTR_DEFAULT_VALUE) self.logger.debug(f'{paramName=} {paramType=} {defaultValue=}') parameterDefinition: ParameterDefinition = ParameterDefinition( name=paramName, parameterType=paramType) parameterDefinition.defaultValue = defaultValue return parameterDefinition
def from_xml(x: minidom.Element): # fill = not x.hasAttribute("fill") or not x.getAttribute("fill") == "none" # filling = Filling.OUTLINE if not x.hasAttribute("filling") else int(x.getAttribute("filling")) fill = SVGPath.parse_color(x.getAttribute("fill")) stroke = SVGPath.parse_color(x.getAttribute('stroke')) dasharray = x.getAttribute('dasharray') stroke_width = x.getAttribute('stroke-width') s = x.getAttribute('d') return SVGPath.from_str(s, fill=fill, stroke=stroke, dasharray=dasharray, stroke_width=stroke_width)
def build_manifest_from_dom(file: File, extended_processing: bool, dom: Element) -> AndroidManifest: if extended_processing: application = dom.getElementsByTagName("application")[0] activities = AndroidManifestParser.parse_activities_from_dom(application) services = AndroidManifestParser.parse_services_from_dom(application) receivers = AndroidManifestParser.parse_broadcast_receivers_from_dom(application) else: activities = [] services = [] receivers = [] return AndroidManifest( filename=file.get_file_name(), size=file.get_size(), md5hash=file.get_md5(), sha1hash=file.get_sha1(), sha256hash=file.get_sha256(), sha512hash=file.get_sha512(), package_name=dom.getAttribute("package"), version=AndroidManifestParser.parse_version_from_dom(dom), sdk=AndroidManifestParser.parse_sdk_from_dom(dom), permissions=AndroidManifestParser.__parse_list_from_dom( dom, tag="uses-permission", attribute="android:name" ), activities=activities, services=services, receivers=receivers )
def ellipse_to_mobject(self, circle_element: MinidomElement, style: dict): """Creates a stretched Circle VMobject from a SVG <circle> path command. Parameters ---------- circle_element : :class:`minidom.Element` A SVG circle path command. style : :class:`dict` Style specification, using the SVG names for properties. Returns ------- Circle A Circle VMobject """ x, y, rx, ry = [ self.attribute_to_float(circle_element.getAttribute(key)) if circle_element.hasAttribute(key) else 0.0 for key in ("cx", "cy", "rx", "ry") ] return ( Circle(**parse_style(style)) .scale(rx * RIGHT + ry * UP) .shift(x * RIGHT + y * DOWN) )
def _polygon_to_mobject(self, polygon_element: MinidomElement, style: dict): """Constructs a VMobject from a SVG <polygon> element. Parameters ---------- polygon_element : :class:`minidom.Element` An SVG polygon element. style : :class:`dict` Style specification, using the SVG names for properties. Returns ------- SVGPathMobject A VMobject representing the polygon. """ # This seems hacky... yes it is. path_string = polygon_element.getAttribute("points").lstrip() for digit in string.digits: path_string = path_string.replace(" " + digit, " L" + digit) path_string = "M" + path_string if polygon_element.tagName == "polygon": path_string = path_string + "Z" return self._path_string_to_mobject(path_string, style)
def _getParam(self, domElement: Element) -> PyutParam: """ Args: domElement: The xml element tht is a parameter Returns: A parameter model object """ pyutParam: PyutParam = PyutParam(name=domElement.getAttribute(PyutXmlConstants.ATTR_NAME), theParameterType=domElement.getAttribute(PyutXmlConstants.ATTR_TYPE)) if domElement.hasAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE): pyutParam.setDefaultValue(domElement.getAttribute(PyutXmlConstants.ATTR_DEFAULT_VALUE)) return pyutParam
def __getAttachmentPoint(self, xmlOglInterface: Element) -> SelectAnchorPoint: attachmentPointStr: str = xmlOglInterface.getAttribute( PyutXmlConstants.ATTR_LOLLIPOP_ATTACHMENT_POINT) xStr: str = xmlOglInterface.getAttribute(PyutXmlConstants.ATTR_X) yStr: str = xmlOglInterface.getAttribute(PyutXmlConstants.ATTR_Y) x: float = PyutUtils.secureFloat(xStr) y: float = PyutUtils.secureFloat(yStr) attachmentPoint: AttachmentPoint = AttachmentPoint.toEnum( attachmentPointStr) anchorPoint: SelectAnchorPoint = SelectAnchorPoint( x=x, y=y, attachmentPoint=attachmentPoint) return anchorPoint
def from_xml(self, obj, parent: minidom.Element, registry: ObjectRegistry): xml_str = parent.getAttribute(self.name) if xml_str: if xml_str.startswith(":") and xml_str[1:] in registry.registry: value = ValueReference.from_registry(xml_str[1:], registry) else: value = value_from_xml_string(xml_str, self.type, registry) setattr(obj, self.att_name, value)
def get_css_style(node: minidom.Element, css_list: list, base_style: dict) -> dict: """ update the base_style with the style definitions from the stylesheet that are applicable to the node defined by the classes or id of the node """ style = {} if base_style is not None: style.update(base_style) classes = node.getAttribute("class").split() for css in css_list: css_condition, css_style = css if css_condition[0] == "." and css_condition[1:] in classes: style.update(css_style) elif css_condition[0] == "#" and css_condition[1:] == node.getAttribute("id"): style.update(css_style) elif css_condition == node.tagName: style.update(css_style) return style
def _getAttachmentPoint(self, xmlOglInterface: Element, parent: OglClass) -> SelectAnchorPoint: attachmentPointStr: str = xmlOglInterface.getAttribute(PyutXmlConstants.ATTR_LOLLIPOP_ATTACHMENT_POINT) attachmentPoint: AttachmentPoint = AttachmentPoint.toEnum(attachmentPointStr) attachPosition: OglPosition = self._determineAttachmentPoint(attachmentPoint=attachmentPoint, oglClass=parent) anchorPoint: SelectAnchorPoint = SelectAnchorPoint(x=attachPosition.x, y=attachPosition.y, attachmentPoint=attachmentPoint, parent=parent) return anchorPoint
def parseCueRegion_(regionElement: Element, styles: List[Element], globalExtent: str): region = CueRegion() _id = regionElement.getAttribute('xml:id') if not _id: log.warning('TtmlTextParser parser encountered a region with no id. Region will be ignored.') return None region.id = _id globalResults = None if globalExtent: globalResults = percentValues_.findall(globalExtent) or pixelValues_.findall(globalExtent) if globalResults is not None and len(globalResults) == 2: globalWidth = int(globalResults[0][0]) globalHeight = int(globalResults[0][1]) else: globalWidth = None globalHeight = None results = None percentage = None extent = TtmlTextParser.getStyleAttributeFromRegion_(regionElement, styles, 'extent') if extent: percentage = percentValues_.findall(extent) results = percentage or pixelValues_.findall(extent) if results is not None: region.width = int(results[0][0]) region.height = int(results[0][1]) if not percentage: if globalWidth is not None: region.width = region.width * 100 / globalWidth if globalHeight is not None: region.height = region.height * 100 / globalHeight if percentage or globalWidth is not None: region.widthUnits = units.PERCENTAGE else: region.widthUnits = units.PX if percentage or globalHeight is not None: region.heightUnits = units.PERCENTAGE else: region.heightUnits = units.PX origin = TtmlTextParser.getStyleAttributeFromRegion_(regionElement, styles, 'origin') if origin: percentage = percentValues_.findall(origin) results = percentage or pixelValues_.findall(origin) if len(results) > 0: region.viewportAnchorX = int(results[0][0]) region.viewportAnchorY = int(results[0][1]) if len(percentage) == 0: if globalHeight is not None: region.viewportAnchorY = region.viewportAnchorY * 100 / globalHeight if globalWidth is not None: region.viewportAnchorX = region.viewportAnchorX * 100 / globalHeight if percentage or globalWidth is not None: region.viewportAnchorUnits = units.PERCENTAGE else: region.viewportAnchorUnits = units.PX return region
def edit_fill(element: Element, fill_color: str) -> None: """Change fill in element. Usaly wrapped in partial with fixed element.""" style = element.getAttribute('style') new_style = [] for css in style.split(';'): term, value = [v.strip() for v in css.split(':')] if term == 'fill': new_style.append('{}:{}'.format(term, fill_color)) else: new_style.append(css) element.setAttribute('style', ';'.join(new_style))