def _write_log_pass_content_in_html( logical_file: LogicalFile.LogicalFile, xhtml_stream: XmlWrite.XhtmlStream, # Used for anchor logical_file_index: int, number_of_preceeding_eflrs: int, *, frame_slice: Slice.Slice) -> typing.Tuple[HTMLFrameArraySummary]: assert logical_file.has_log_pass ret = [] lp: LogPass.LogPass = logical_file.log_pass frame_array: LogPass.FrameArray for fa, frame_array in enumerate(lp.frame_arrays): anchor = _anchor(logical_file_index, number_of_preceeding_eflrs, fa) with XmlWrite.Element(xhtml_stream, 'a', {'id': anchor}): pass with XmlWrite.Element(xhtml_stream, 'h3'): xhtml_stream.characters( f'Frame Array: {stringify.stringify_object_by_type(frame_array.ident)} [{fa}/{len(lp.frame_arrays)}]' ) ret.append( _write_frame_array_in_html( logical_file, frame_array, frame_slice, anchor, xhtml_stream, )) return tuple(ret)
def write_logical_file_to_xml(logical_file_index: int, logical_file: LogicalFile, xml_stream: XmlWrite.XmlStream, private: bool) -> None: with XmlWrite.Element( xml_stream, 'LogicalFile', { 'has_log_pass': str(logical_file.has_log_pass), 'index': f'{logical_file_index:d}', # 'schema_version': XML_SCHEMA_VERSION, }): for position, eflr in logical_file.eflrs: attrs = { 'vr_position': f'0x{position.vr_position:x}', 'lrsh_position': f'0x{position.lrsh_position:x}', 'lr_type': f'{eflr.lr_type:d}', 'set_type': f'{eflr.set.type.decode("ascii")}', 'set_name': f'{eflr.set.name.decode("ascii")}', 'object_count': f'{len(eflr.objects):d}' } with XmlWrite.Element(xml_stream, 'EFLR', attrs): if private or LogicalRecord.Types.is_public(eflr.lr_type): for obj in eflr.objects: _write_xml_eflr_object(obj, xml_stream) if logical_file.has_log_pass: log_pass_to_XML(logical_file.log_pass, logical_file.iflr_position_map, xml_stream)
def test_08(self): """TestXmlWrite.test_08(): raise during write.""" myF = io.StringIO() try: with XmlWrite.XmlStream(myF) as xS: with XmlWrite.Element(xS, 'Root', {'version': '12.0'}): self.assertRaises(XmlWrite.ExceptionXmlEndElement, xS.endElement, 'NotRoot') with XmlWrite.Element(xS, 'E', {'attr_1': '1'}): xS._elemStk.pop() xS._elemStk.append('F') raise Exception('Some exception') except Exception as e: print(e) else: print('No exception raised') # print() # print(myF.getvalue()) self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <Root version="12.0"> <E attr_1="1"/> </Root> """)
def test_01(self): """TestXhtmlWrite.test_01(): simple example.""" myF = io.StringIO() with XmlWrite.XhtmlStream(myF) as xS: with XmlWrite.Element(xS, 'head'): with XmlWrite.Element(xS, 'title'): xS.characters('Virtual Library') with XmlWrite.Element(xS, 'body'): with XmlWrite.Element(xS, 'p'): xS.characters('Moved to ') with XmlWrite.Element(xS, 'a', {'href': 'http://example.org/'}): xS.characters('example.org') xS.characters('.') #print #print myF.getvalue() self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Virtual Library</title> </head> <body> <p>Moved to <a href="http://example.org/">example.org</a>.</p> </body> </html> """)
def xml_write_value(xml_stream: XmlWrite.XmlStream, value: typing.Any) -> None: """Write a value to the XML stream with specific type as an attribute. This writes either a <Value> or an <ObjectName> element.""" if isinstance(value, RepCode.ObjectName): with XmlWrite.Element(xml_stream, 'ObjectName', xml_object_name_attributes(value)): pass else: if isinstance(value, bytes): typ = 'bytes' # print('TRACE: xml_write_value()', value) _value = value.decode('latin-1') #, errors='ignore') elif isinstance(value, float): typ = 'float' _value = str(value) elif isinstance(value, int): typ = 'int' _value = str(value) elif isinstance(value, RepCode.DateTime): typ = 'TotalDepth.RP66V1.core.RepCode.DateTime' _value = str(value) elif isinstance(value, str): # pragma: no cover typ = 'str' _value = value else: typ = 'unknown' _value = str(value) with XmlWrite.Element(xml_stream, 'Value', { 'type': typ, 'value': _value }): pass
def test_06(self): """TestXmlWrite.test_06(): encoded text in 'latin-1'.""" myF = io.StringIO() with XmlWrite.XmlStream(myF, 'latin-1') as xS: with XmlWrite.Element(xS, 'Root'): with XmlWrite.Element(xS, 'A'): xS.characters("""<&>"'""") with XmlWrite.Element(xS, 'A'): xS.characters('%s' % chr(147)) with XmlWrite.Element(xS, 'A'): xS.characters(chr(65)) with XmlWrite.Element(xS, 'A'): xS.characters(chr(128)) # print() # print(myF.getvalue()) self.assertEqual( """<?xml version='1.0' encoding="latin-1"?> <Root> <A><&>"'</A> <A>“</A> <A>A</A> <A>€</A> </Root> """, myF.getvalue(), )
def writeHTML(self, theFilePath, theDesc): """Write the index.html table.""" lenCmnPref = os.path.commonprefix([t[0] for t in self._plotS]).rfind( os.sep) + 1 # Put the plot summary data into a DictTree myTree = DictTree.DictTreeHtmlTable() for aPlt in self._plotS: key = (aPlt[0][lenCmnPref:], ) + aPlt[1:3] myTree.add([str(s) for s in key], aPlt[3]) # Write CSS with open( os.path.join(os.path.dirname(theFilePath), self.CSS_FILE_PATH), 'w') as f: f.write(CSS_CONTENT_INDEX) # Write the index with XmlWrite.XhtmlStream(open(theFilePath, 'w')) as myS: with XmlWrite.Element(myS, 'head'): with XmlWrite.Element( myS, 'link', { 'href': self.CSS_FILE_PATH, 'type': "text/css", 'rel': "stylesheet", }): pass with XmlWrite.Element(myS, 'title'): myS.characters('LIS plots in SVG') with XmlWrite.Element(myS, 'h1'): myS.characters('PlotLogPasses: {:s}'.format(theDesc)) with XmlWrite.Element(myS, 'table', {'border': '1'}): self._writeHTMLTh(myS) self._writeIndexTableRows(myS, myTree, theFilePath)
def writeHtmlFileAnchor(theS, theLineNum, theText='', theClass=None): """Write an anchor to the stream.""" with XmlWrite.Element(theS, 'a', {'name': "%d" % theLineNum}): if theText: if theClass is None: theS.characters(theText) else: with XmlWrite.Element(theS, 'span', {'class': theClass}): theS.characters(theText)
def frame_array_to_XML(frame_array: LogPass.FrameArray, iflr_data: typing.Sequence[IFLRReference], xml_stream: XmlWrite.XmlStream) -> None: """Writes a XML FrameArray node suitable for RP66V1. Example: .. code-block:: xml <FrameArray C="0" I="0B" O="11" description=""> <Channels channel_count="9"> <Channel C="0" I="DEPT" O="11" count="1" dimensions="1" long_name="MWD Tool Measurement Depth" rep_code="2" units="0.1 in"/> <Channel C="0" I="INC" O="11" count="1" dimensions="1" long_name="Inclination" rep_code="2" units="deg"/> <Channel C="0" I="AZI" O="11" count="1" dimensions="1" long_name="Azimuth" rep_code="2" units="deg"/> ... </Channels> <IFLR count="83"> <FrameNumbers count="83" rle_len="1"> <RLE datum="1" repeat="82" stride="1"/> </FrameNumbers> <LRSH count="83" rle_len="2"> <RLE datum="0x14ac" repeat="61" stride="0x30"/> <RLE datum="0x2050" repeat="20" stride="0x30"/> </LRSH> <Xaxis count="83" rle_len="42"> <RLE datum="0.0" repeat="1" stride="75197.0"/> <RLE datum="154724.0" repeat="1" stride="79882.0"/> </Xaxis> </IFLR> </FrameArray> """ frame_array_attrs = { 'O': f'{frame_array.ident.O}', 'C': f'{frame_array.ident.C}', 'I': f'{frame_array.ident.I.decode("ascii")}', 'description': frame_array.description.decode('ascii'), 'x_axis': frame_array.channels[0].ident.I.decode("ascii"), 'x_units': frame_array.channels[0].units.decode("ascii"), } with XmlWrite.Element(xml_stream, 'FrameArray', frame_array_attrs): with XmlWrite.Element(xml_stream, 'Channels', {'count': f'{len(frame_array)}'}): for channel in frame_array.channels: frame_channel_to_XML(channel, xml_stream) with XmlWrite.Element(xml_stream, 'IFLR', {'count': f'{len(iflr_data)}'}): # Frame number output rle = Rle.create_rle(v.frame_number for v in iflr_data) xml_rle_write(rle, 'FrameNumbers', xml_stream, hex_output=False) # IFLR file position rle = Rle.create_rle(v.logical_record_position.lrsh_position for v in iflr_data) xml_rle_write(rle, 'LRSH', xml_stream, hex_output=True) # Xaxis output rle = Rle.create_rle(v.x_axis for v in iflr_data) xml_rle_write(rle, 'Xaxis', xml_stream, hex_output=False)
def _HTMLVerbatim(self, theIe, theFi, theS): self._HTMLEntryBasic(theIe, theS) theIe.setLogicalRecord(theFi) myLr = theIe.logicalRecord assert (myLr is not None) with XmlWrite.Element(theS, 'p'): theS.characters('Verbatim bytes [{:d}]:'.format(len(myLr.bytes))) with XmlWrite.Element(theS, 'pre', {'class': 'verbatim'}): theS.characters(myLr.bytes.decode('ascii', 'replace'))
def write_logical_file_sequence_to_xml(logical_index: LogicalFile.LogicalIndex, output_stream: typing.TextIO, private: bool) -> None: """Takes a LogicalIndex and writes the index to an XML stream.""" with XmlWrite.XmlStream(output_stream) as xml_stream: with XmlWrite.Element( xml_stream, 'RP66V1FileIndex', { 'path': logical_index.id, 'size': f'{os.path.getsize(logical_index.id):d}', 'schema_version': XML_SCHEMA_VERSION, 'utc_file_mtime': str( datetime.datetime.utcfromtimestamp( os.stat(logical_index.id).st_mtime)), 'utc_now': str(datetime.datetime.utcnow()), 'creator': f'{__name__}', }): with XmlWrite.Element( xml_stream, 'StorageUnitLabel', { 'sequence_number': str(logical_index.storage_unit_label. storage_unit_sequence_number), 'dlis_version': logical_index.storage_unit_label.dlis_version.decode( 'ascii'), 'storage_unit_structure': logical_index.storage_unit_label. storage_unit_structure.decode('ascii'), 'maximum_record_length': str(logical_index.storage_unit_label. maximum_record_length), 'storage_set_identifier': logical_index.storage_unit_label. storage_set_identifier.decode('ascii'), }): pass with XmlWrite.Element( xml_stream, 'LogicalFiles', {'count': f'{len(logical_index.logical_files):d}'}): for lf, logical_file in enumerate(logical_index.logical_files): write_logical_file_to_xml(lf, logical_file, xml_stream, private) # Visible records at the end rle_visible_records = Rle.create_rle( logical_index.visible_record_positions) xml_rle_write(rle_visible_records, 'VisibleRecords', xml_stream, hex_output=True)
def _writeHtmlToc(self, myFi, myIdx, theS): """Write the table of contents at the top of the page.""" with XmlWrite.Element(theS, 'a', {'name' : 'toc'}): pass with XmlWrite.Element(theS, 'h1', {}): theS.characters('Logical records in {:s}'.format(myFi.fileId)) for anIdx in myIdx.genAll(): with XmlWrite.Element(theS, 'p', {}): theS.literal(' ' * 8 * self._retIndentDepth(anIdx)) with XmlWrite.Element(theS, 'a', {'href' : '#{:d}'.format(anIdx.tell)}): theS.characters(anIdx.tocStr())
def _HTMLGeneralTable(self, theS, theTitleS, theTab): """Create a table. theTitleS is a list of titles, theTab is a list of lists.""" with XmlWrite.Element(theS, 'table', {'class' : "monospace"}): with XmlWrite.Element(theS, 'tr', {}): for v in theTitleS: with XmlWrite.Element(theS, 'th', {'class' : "monospace"}): theS.characters(v) for row in theTab: with XmlWrite.Element(theS, 'tr', {}): for v in row: with XmlWrite.Element(theS, 'td', {'class' : "monospace"}): theS.characters(v)
def _write_x_axis_summary(x_axis: XAxis.XAxis, xhtml_stream: XmlWrite.XhtmlStream) -> None: # Parent section is heading h3 # with XmlWrite.Element(xhtml_stream, 'h4'): # xhtml_stream.characters('X Axis summary (all IFLRs)') with XmlWrite.Element(xhtml_stream, 'h4'): xhtml_stream.characters('X Axis') units = x_axis.units.decode('ascii') x_axis_table = [ ['X Axis', 'Value'], ['Channel', f'{x_axis.ident}'], ['Long Name', f'{x_axis.long_name.decode("ascii")}'], ['Minimum', f'{x_axis.summary.min} [{units}]'], ['Maximum', f'{x_axis.summary.max} [{units}]'], ['Frame Count', f'{x_axis.summary.count}'], ] html_write_table(x_axis_table, xhtml_stream, class_style='monospace') with XmlWrite.Element(xhtml_stream, 'h4'): xhtml_stream.characters('X Axis Spacing') with XmlWrite.Element(xhtml_stream, 'p'): xhtml_stream.characters(f'Definitions: {XAxis.SPACING_DEFINITIONS}') x_spacing_table = [ ['X Axis Spacing', 'Value'], ] if x_axis.summary.spacing is not None: spacing = x_axis.summary.spacing x_spacing_table.append(['Minimum', f'{spacing.min} [{units}]']) x_spacing_table.append(['Mean', f'{spacing.mean} [{units}]']) x_spacing_table.append(['Median', f'{spacing.median} [{units}]']) x_spacing_table.append(['Maximum', f'{spacing.max} [{units}]']) if spacing.median != 0: x_spacing_table.append([ 'Range', f'{spacing.max - spacing.min} ({(spacing.max - spacing.min) / spacing.median:%}) [{units}]' ]) else: x_spacing_table.append( ['Range', f'{spacing.max - spacing.min} [{units}]']) x_spacing_table.append(['Std. Dev.', f'{spacing.std} [{units}]']) x_spacing_table.append( ['Count of Normal', f'{spacing.counts.norm:,d}']) x_spacing_table.append( ['Count of Duplicate', f'{spacing.counts.dupe:,d}']) x_spacing_table.append( ['Count of Skipped', f'{spacing.counts.skip:,d}']) x_spacing_table.append(['Count of Back', f'{spacing.counts.back:,d}']) html_write_table(x_spacing_table, xhtml_stream, class_style='monospace') if x_axis.summary.spacing is not None: with XmlWrite.Element(xhtml_stream, 'p'): xhtml_stream.characters('Frame spacing frequency:') with XmlWrite.Element(xhtml_stream, 'pre'): xhtml_stream.characters(x_axis.summary.spacing.histogram_str())
def writeDictTreeAsTable(theS, theDt, tableAttrs, includeKeyTail): """Writes a DictTreeHtmlTable object as a table, for example as a directory structure. The key list in the DictTreeHtmlTable object is the path to the file i.e. os.path.abspath(p).split(os.sep) and the value is expected to be a pair of (link, nav_text) or None.""" # Write: <table border="2" width="100%"> # Propogate table class attribute myAttrs = {} try: myAttrs['class'] = tableAttrs['class'] except KeyError: pass with XmlWrite.Element(theS, 'table', tableAttrs): for anEvent in theDt.genColRowEvents(): if anEvent == theDt.ROW_OPEN: # Write out the '<tr>' element theS.startElement('tr', {}) elif anEvent == theDt.ROW_CLOSE: # Write out the '</tr>' element theS.endElement('tr') else: #print 'TRACE: anEvent', anEvent k, v, r, c = anEvent # Write '<td rowspan="%d" colspan="%d">%s</td>' % (r, c, txt[-1]) myTdAttrs = {} myTdAttrs.update(myAttrs) if r > 1: myTdAttrs['rowspan'] = "%d" % r if c > 1: myTdAttrs['colspan'] = "%d" % c with XmlWrite.Element(theS, 'td', myTdAttrs): if v is not None: if includeKeyTail: theS.characters('%s:' % k[-1]) # Output depending on the type of the value if isinstance(v, list): for h, n in v: theS.characters(' ') with XmlWrite.Element(theS, 'a', {'href': h}): # Write the nav text theS.characters('%s' % n) elif isinstance(v, tuple) and len(v) == 2: with XmlWrite.Element(theS, 'a', {'href': v[0]}): # Write the nav text theS.characters(v[1]) else: # Treat as string theS.characters(str(v)) else: theS.characters(k[-1])
def _writeCols(self, theS, theObj): """Write the columns after the first one. theObj is expected to have certain attributes...""" with XmlWrite.Element(theS, 'td', {'align' : 'right'}): theS.characters('{:.3f}'.format(theObj.lisSize / 1024**2)) with XmlWrite.Element(theS, 'td', {'align' : 'right'}): theS.characters('{:d}'.format(theObj.numLr)) with XmlWrite.Element(theS, 'td', {'align' : 'right'}): theS.characters('{:.3f}'.format(theObj.cpuTime)) if theObj.cpuTime != 0: with XmlWrite.Element(theS, 'td', {'align' : 'right'}): theS.characters('{:.3f}'.format(theObj.lisSize / (theObj.cpuTime * 1024**2))) else: with XmlWrite.Element(theS, 'td', {'align' : 'right'}): theS.characters('N/A')
def test_02(self): """TestXmlWrite.test_02(): mixed content.""" myF = io.StringIO() with XmlWrite.XmlStream(myF) as xS: with XmlWrite.Element(xS, 'Root', {'version': '12.0'}): with XmlWrite.Element(xS, 'A', {'attr_1': '1'}): xS.characters('<&>') #print #print myF.getvalue() self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <Root version="12.0"> <A attr_1="1"><&></A> </Root> """)
def _writeValues(self, theS, theVal, theFilePath): assert(theVal is not None) for i, aVal in enumerate(theVal): myValAttrs = {} if i in (4, 6): # Curve list and link myValAttrs = {'align' : 'left'} else: myValAttrs = {'align' : 'right'} with XmlWrite.Element(theS, 'td', myValAttrs): if i == len(theVal)-1: with XmlWrite.Element(theS, 'a', {'href' : self.retRelPath(os.path.dirname(theFilePath), aVal)}): theS.characters(os.path.basename(aVal)) else: theS.characters(str(aVal))
def test_01(self): """TestXmlWrite.test_01(): simple elements.""" myF = io.StringIO() with XmlWrite.XmlStream(myF) as xS: with XmlWrite.Element(xS, 'Root', {'version': '12.0'}): with XmlWrite.Element(xS, 'A', {'attr_1': '1'}): pass #print #print myF.getvalue() self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <Root version="12.0"> <A attr_1="1"/> </Root> """)
def test_03(self): """TestXmlWrite.test_03(): processing instruction.""" myF = io.StringIO() with XmlWrite.XmlStream(myF) as xS: with XmlWrite.Element(xS, 'Root', {'version': '12.0'}): with XmlWrite.Element(xS, 'A', {'attr_1': '1'}): xS.pI('Do <&> this') #print #print myF.getvalue() self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <Root version="12.0"> <A attr_1="1"><?Do <&> this?></A> </Root> """)
def test_07(self): """TestSVGlWriter.test_07(): text. Based on http://www.w3.org/TR/2003/REC-SVG11-20030114/text.html#TextElement""" myF = io.StringIO() myViewPort = Coord.Box( Coord.Dim(12, 'cm'), Coord.Dim(4, 'cm'), ) with SVGWriter.SVGWriter(myF, myViewPort, {'viewBox': "0 0 1000 300"}) as xS: with XmlWrite.Element(xS, 'desc'): xS.characters("Example text01 - 'Hello, out there' in blue") myPt = Coord.Pt(Coord.baseUnitsDim(250), Coord.baseUnitsDim(150)) with SVGWriter.SVGText(xS, myPt, "Verdans", 55, {'fill': "blue"}): xS.characters('Hello, out there') #xS.comment(" Show outline of canvas using 'rect' element ") myPt = Coord.Pt(Coord.baseUnitsDim(1), Coord.baseUnitsDim(1)) myBx = Coord.Box(Coord.baseUnitsDim(998), Coord.baseUnitsDim(298)) with SVGWriter.SVGRect(xS, myPt, myBx, { 'fill': "none", 'stroke': "blue", 'stroke-width': "2" }): pass # print() # print(myF.getvalue()) self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg height="4.000cm" version="1.1" viewBox="0 0 1000 300" width="12.000cm" xmlns="http://www.w3.org/2000/svg"> <desc>Example text01 - 'Hello, out there' in blue</desc> <text fill="blue" font-family="Verdans" font-size="55" x="250.000px" y="150.000px">Hello, out there</text> <rect fill="none" height="298.000px" stroke="blue" stroke-width="2" width="998.000px" x="1.000px" y="1.000px"/> </svg> """)
def test_03(self): """TestSVGlWriter.test_03(): an elipse. Based on http://www.w3.org/TR/2003/REC-SVG11-20030114/shapes.html#EllipseElement""" myF = io.StringIO() myViewPort = Coord.Box( Coord.Dim(12, 'cm'), Coord.Dim(4, 'cm'), ) with SVGWriter.SVGWriter(myF, myViewPort) as xS: with XmlWrite.Element(xS, 'desc'): xS.characters('Example ellipse01 - examples of ellipses') #xS.comment(" Show outline of canvas using 'rect' element ") myPt = Coord.Pt(Coord.baseUnitsDim(1), Coord.baseUnitsDim(1)) myBx = Coord.Box(Coord.baseUnitsDim(1198), Coord.baseUnitsDim(398)) with SVGWriter.SVGRect(xS, myPt, myBx, {'fill':"none", 'stroke':"blue",'stroke-width':"2"}): pass myPt = Coord.Pt(Coord.baseUnitsDim(600), Coord.baseUnitsDim(200)) myRadX = Coord.baseUnitsDim(250) myRadY = Coord.baseUnitsDim(100) with SVGWriter.SVGElipse(xS, myPt, myRadX, myRadY, {'fill':"red", 'stroke':"blue",'stroke-width':"10"}): pass #print #print myF.getvalue() # self.maxDiff = None self.assertEqual(myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg height="4cm" version="1.1" width="12cm" xmlns="http://www.w3.org/2000/svg"> <desc>Example ellipse01 - examples of ellipses</desc> <rect fill="none" height="398px" stroke="blue" stroke-width="2" width="1198px" x="1px" y="1px"/> <elipse cx="600px" cy="200px" fill="red" rx="250px" ry="100px" stroke="blue" stroke-width="10"/> </svg> """)
def xml_rle_write(rle: Rle.RLE, element_name: str, xml_stream: XmlWrite.XmlStream, hex_output: bool) -> None: with XmlWrite.Element(xml_stream, element_name, { 'count': f'{rle.num_values():d}', 'rle_len': f'{len(rle):d}', }): for rle_item in rle.rle_items: attrs = { 'datum': f'0x{rle_item.datum:x}' if hex_output else f'{rle_item.datum}', 'stride': f'0x{rle_item.stride:x}' if hex_output else f'{rle_item.stride}', 'repeat': f'{rle_item.repeat:d}', } with XmlWrite.Element(xml_stream, 'RLE', attrs): pass
def _write_xml_eflr_object(obj: LogicalRecord.EFLR.Object, xml_stream: XmlWrite.XmlStream) -> None: with XmlWrite.Element(xml_stream, 'Object', xml_object_name_attributes(obj.name)): for attr in obj.attrs: attr_atributes = { 'label': attr.label.decode('ascii'), 'count': f'{attr.count:d}', 'rc': f'{attr.rep_code:d}', # TODO: Remove this as duplicate? 'rc_ascii': f'{RepCode.REP_CODE_INT_TO_STR[attr.rep_code]}', 'units': attr.units.decode('ascii'), } with XmlWrite.Element(xml_stream, 'Attribute', attr_atributes): if attr.value is not None: for v in attr.value: xml_write_value(xml_stream, v)
def test_05(self): """TestXmlWrite.test_05(): raise on endElement missmatch.""" myF = io.StringIO() with XmlWrite.XmlStream(myF) as xS: with XmlWrite.Element(xS, 'Root', {'version': '12.0'}): self.assertRaises(XmlWrite.ExceptionXmlEndElement, xS.endElement, 'NotRoot') with XmlWrite.Element(xS, 'A', {'attr_1': '1'}): self.assertRaises(XmlWrite.ExceptionXmlEndElement, xS.endElement, 'NotA') #print #print myF.getvalue() self.assertEqual( myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <Root version="12.0"> <A attr_1="1"/> </Root> """)
def html_write_table(table_as_strings: typing.List[typing.List[str]], xhtml_stream: XmlWrite.XhtmlStream, class_style) -> None: if len(table_as_strings): with XmlWrite.Element(xhtml_stream, 'table', {'class': class_style}): with XmlWrite.Element(xhtml_stream, 'tr', {}): for cell in table_as_strings[0]: with XmlWrite.Element(xhtml_stream, 'th', {'class': class_style}): xhtml_stream.characters(cell) for row in table_as_strings[1:]: with XmlWrite.Element(xhtml_stream, 'tr', {}): for cell in row: with XmlWrite.Element(xhtml_stream, 'td', {'class': class_style}): assert isinstance( cell, str ), f'{cell} is not a string but {type(cell)}' xhtml_stream.charactersWithBr(cell)
def test_05(self): """TestSVGlWriter.test_05(): a polyline. Based on http://www.w3.org/TR/2003/REC-SVG11-20030114/shapes.html#PolylineElement""" myF = io.StringIO() myViewPort = Coord.Box( Coord.Dim(12, 'cm'), Coord.Dim(4, 'cm'), ) with SVGWriter.SVGWriter(myF, myViewPort, {'viewBox' : "0 0 1200 400"}) as xS: with XmlWrite.Element(xS, 'desc'): xS.characters('Example line01 - lines expressed in user coordinates') #xS.comment(" Show outline of canvas using 'rect' element ") myPt = Coord.Pt(Coord.baseUnitsDim(1), Coord.baseUnitsDim(1)) myBx = Coord.Box(Coord.baseUnitsDim(1198), Coord.baseUnitsDim(398)) with SVGWriter.SVGRect(xS, myPt, myBx, {'fill':"none", 'stroke':"blue",'stroke-width':"2"}): pass # Make a group with SVGWriter.SVGPolyline( xS, [ Coord.Pt(Coord.baseUnitsDim(50), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(150), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(150), Coord.baseUnitsDim(325)), Coord.Pt(Coord.baseUnitsDim(250), Coord.baseUnitsDim(325)), Coord.Pt(Coord.baseUnitsDim(250), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(350), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(350), Coord.baseUnitsDim(250)), Coord.Pt(Coord.baseUnitsDim(450), Coord.baseUnitsDim(250)), Coord.Pt(Coord.baseUnitsDim(450), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(550), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(550), Coord.baseUnitsDim(175)), Coord.Pt(Coord.baseUnitsDim(650), Coord.baseUnitsDim(175)), Coord.Pt(Coord.baseUnitsDim(650), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(750), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(750), Coord.baseUnitsDim(100)), Coord.Pt(Coord.baseUnitsDim(850), Coord.baseUnitsDim(100)), Coord.Pt(Coord.baseUnitsDim(850), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(950), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(950), Coord.baseUnitsDim(25)), Coord.Pt(Coord.baseUnitsDim(1050), Coord.baseUnitsDim(25)), Coord.Pt(Coord.baseUnitsDim(1050), Coord.baseUnitsDim(375)), Coord.Pt(Coord.baseUnitsDim(1150), Coord.baseUnitsDim(375)), ], {'fill' : 'none', 'stroke' : 'blue', 'stroke-width' : "5"} ): pass # print() # print(myF.getvalue()) # self.maxDiff = None self.assertEqual(myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg height="4cm" version="1.1" viewBox="0 0 1200 400" width="12cm" xmlns="http://www.w3.org/2000/svg"> <desc>Example line01 - lines expressed in user coordinates</desc> <rect fill="none" height="398px" stroke="blue" stroke-width="2" width="1198px" x="1px" y="1px"/> <polyline fill="none" points="50,375 150,375 150,325 250,325 250,375 350,375 350,250 450,250 450,375 550,375 550,175 650,175 650,375 750,375 750,100 850,100 850,375 950,375 950,25 1050,25 1050,375 1150,375" stroke="blue" stroke-width="5"/> </svg> """)
def writeFilePathsAsTable(valueType, theS, theKvS, tableStyle, fnTd): """Writes file paths as a table, for example as a directory structure. valueType - The type of the value: None | 'list' | 'set' theKvS - A list of pairs (file_path, value). tableStyle - The style used for the table. fnTd - A callback function that is executed for a <td> element when there is a non-None value. This is called with the following arguments: * theS - The HTML stream. * attrs - A map of attrs that include the rowspan/colspan for the <td> * k - The key as a list of path components. * v - The value given by the caller. """ myDict = DictTree.DictTreeHtmlTable(valueType) for k, v in theKvS: myDict.add(pathSplit(k), v) # Propagate table class attribute with XmlWrite.Element(theS, 'table', {'class': tableStyle}): for anEvent in myDict.genColRowEvents(): if anEvent == myDict.ROW_OPEN: # Write out the '<tr>' element theS.startElement('tr', {}) elif anEvent == myDict.ROW_CLOSE: # Write out the '</tr>' element theS.endElement('tr') else: #print 'TRACE: anEvent', anEvent k, v, r, c = anEvent # Write '<td rowspan="%d" colspan="%d">%s</td>' % (r, c, txt[-1]) myTdAttrs = {'class': tableStyle} if r > 1: myTdAttrs['rowspan'] = "%d" % r if c > 1: myTdAttrs['colspan'] = "%d" % c if v is not None: fnTd(theS, myTdAttrs, k, v) else: with XmlWrite.Element(theS, 'td', myTdAttrs): # Write out part of the file name theS.characters(k[-1])
def html_write_file_info(path_in: str, xhtml_stream: XmlWrite.XhtmlStream) -> None: with XmlWrite.Element(xhtml_stream, 'h2'): xhtml_stream.characters('File information') table = [ ['KEY', 'VALUE'], ['File Path:', path_in], ['File size:', f'{os.path.getsize(path_in):,d}'], ] html_write_table(table, xhtml_stream, class_style='monospace')
def _write_top_level_index_table_body( index_file_path: str, dict_tree: DictTree.DictTreeHtmlTable, xhtml_stream: XmlWrite.XhtmlStream) -> None: strip_out_path = len(os.path.dirname(index_file_path)) + 1 for event in dict_tree.genColRowEvents(): if event == dict_tree.ROW_OPEN: # Write out the '<tr>' element xhtml_stream.startElement('tr', {'class': 'filetable'}) elif event == dict_tree.ROW_CLOSE: # Write out the '</tr>' element xhtml_stream.endElement('tr') else: td_attrs = {'class': 'filetable'} if event.row_span > 1: td_attrs['rowspan'] = f'{event.row_span:d}' if event.col_span > 1: td_attrs['colspan'] = f'{event.col_span:d}' if event.node is None: with XmlWrite.Element(xhtml_stream, 'td', td_attrs): possible_index_file = os.path.join( *event.branch) + os.sep + INDEX_FILE if os.path.exists(possible_index_file): xhtml_stream.comment( f' Writing event branch[-1] with link to {INDEX_FILE} ' ) with XmlWrite.Element( xhtml_stream, 'a', {'href': possible_index_file[strip_out_path:]}): xhtml_stream.characters(f'{str(event.branch[-1])}') else: xhtml_stream.comment( f' Writing event branch[-1] without link to absent {possible_index_file}' ) xhtml_stream.characters(f'{str(event.branch[-1])}') else: node: HTMLResult = event.node with XmlWrite.Element(xhtml_stream, 'td', td_attrs): xhtml_stream.comment(' Writing event.node with link ') with XmlWrite.Element( xhtml_stream, 'a', {'href': f'{node.path_output[strip_out_path:]}'}): xhtml_stream.characters(str(event.branch[-1]))