convert_css_test_suite_to_rml.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # This source file is part of RmlUi, the HTML/CSS Interface Middleware
  2. #
  3. # For the latest information, see http://github.com/mikke89/RmlUi
  4. #
  5. # Copyright (c) 2008-2014 CodePoint Ltd, Shift Technology Ltd, and contributors
  6. # Copyright (c) 2019 The RmlUi Team, and contributors
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining a copy
  9. # of this software and associated documentation files (the "Software"), to deal
  10. # in the Software without restriction, including without limitation the rights
  11. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. # copies of the Software, and to permit persons to whom the Software is
  13. # furnished to do so, subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included in all
  16. # copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. # SOFTWARE.
  25. import os
  26. import re
  27. import sys
  28. import argparse
  29. parser = argparse.ArgumentParser(description=\
  30. '''Convert the W3C CSS 2.1 test suite to RML documents for testing in RmlUi.
  31. Fetch the CSS tests archive from here: https://www.w3.org/Style/CSS/Test/CSS2.1/
  32. Extract the 'xhtml1' folder and point the 'in_dir' argument to this directory.''')
  33. parser.add_argument('in_dir',
  34. help="Input directory which contains the 'xhtml1' (.xht) files to be converted.")
  35. parser.add_argument('out_dir',
  36. help="Output directory for the converted RML files.")
  37. parser.add_argument('--clean', action='store_true',
  38. help='Will *delete* all existing *.rml files in the output directory.')
  39. parser.add_argument('--match',
  40. help="Only process file names containing the given string.")
  41. args = parser.parse_args()
  42. in_dir = args.in_dir
  43. out_dir = args.out_dir
  44. out_ref_dir = os.path.join(out_dir, r'reference')
  45. match_files = args.match
  46. if not os.path.isdir(in_dir):
  47. print("Error: Specified input directory '{}' does not exist.".format(out_dir))
  48. exit()
  49. if not os.path.exists(out_dir):
  50. try:
  51. os.mkdir(out_dir)
  52. except Exception as e:
  53. print('Error: Failed to create output directory {}'.format(out_dir))
  54. if not os.path.exists(out_ref_dir):
  55. try:
  56. os.mkdir(out_ref_dir)
  57. except Exception as e:
  58. print('Error: Failed to create reference output directory {}'.format(out_ref_dir))
  59. if not os.path.isdir(out_dir) or not os.path.isdir(out_ref_dir):
  60. print("Error: Specified output directory '{}' or reference '{}' are not directories.".format(out_dir, out_ref_dir))
  61. exit()
  62. if args.clean:
  63. print("Deleting all *.rml files in output directory '{}' and reference directory '{}'".format(out_dir, out_ref_dir))
  64. for del_dir in [out_dir, out_ref_dir]:
  65. for file in os.listdir(del_dir):
  66. path = os.path.join(del_dir, file)
  67. try:
  68. if os.path.isfile(path) and file.endswith('.rml'):
  69. os.unlink(path)
  70. except Exception as e:
  71. print('Failed to delete {}. Reason: {}'.format(path, e))
  72. def border_format(side: str, type: str, content: str):
  73. # Side: (empty)/-top/-right/-bottom/-left
  74. # Type: (empty)/-width/-style/-color
  75. content = content.replace("thick", "5px")
  76. content = content.replace("medium", "3px")
  77. content = content.replace("thin", "1px")
  78. if type == "-width" or type == "-color":
  79. return "border" + side + type + ": " + content
  80. # Convert style to width. This is not perfect, but seems to be the most used case.
  81. if type == "-style":
  82. content = content.replace("none", "0px").replace("hidden", "0px")
  83. # We may want to only match "solid" here, and cancel the test if it contains any other styles which are unsupported.
  84. content = re.sub(r'\b[a-z]+\b', '3px', content, flags = re.IGNORECASE)
  85. return "border" + side + "-width: " + content
  86. # Next are the shorthand properties, they should contain max a single size, a single style, and a single color.
  87. width = re.search(r'\b([0-9]+(\.[0-9]+)?[a-z]+|0)\b', content, flags = re.IGNORECASE)
  88. if width:
  89. width = width.group(1)
  90. style_pattern = r'none|solid|hidden|dotted|dashed|double|groove|ridge|inset|outset|sold'
  91. style = re.search(style_pattern, content, flags = re.IGNORECASE)
  92. if style:
  93. style = style.group(0)
  94. if style == "none" or style == "hidden":
  95. width = "0px"
  96. content = re.sub(style_pattern, "", content)
  97. color = re.search(r'\b([a-z]+|#[0-9a-f]+)\b', content)
  98. if color:
  99. color = color.group(1)
  100. else:
  101. color = "black"
  102. width = width or "3px"
  103. return "border" + side + ": " + width + " " + color
  104. def border_find_replace(line: str):
  105. new_line = ""
  106. prev_end = 0
  107. pattern = r"border(-(top|right|bottom|left))?(-(width|style|color))?:([^;}\"]+)([;}\"])"
  108. for match in re.finditer(pattern, line, flags = re.IGNORECASE):
  109. side = match.group(1) or ""
  110. type = match.group(3) or ""
  111. content = match.group(5)
  112. suffix = match.group(6)
  113. replacement = border_format(side, type, content) + suffix
  114. new_line += line[prev_end:match.start()] + replacement
  115. prev_end = match.end()
  116. new_line += line[prev_end:]
  117. return new_line
  118. assert( border_find_replace("margin:10px; border:20px solid black; padding:30px;") == 'margin:10px; border: 20px black; padding:30px;' )
  119. assert( border_find_replace(" border-left: 7px solid navy; border-right: 17px solid navy; } ") == ' border-left: 7px navy; border-right: 17px navy; } ' )
  120. assert( border_find_replace(" border: blue solid 3px; ") == ' border: 3px blue; ' )
  121. assert( border_find_replace(" border: solid lime; ") == ' border: 3px lime; ' )
  122. assert( border_find_replace(" border: 0; ") == ' border: 0 black; ' )
  123. assert( border_find_replace(" border-bottom: 0.25em solid green; ") == ' border-bottom: 0.25em green; ' )
  124. assert( border_find_replace(" border-width: 0; ") == ' border-width: 0; ' )
  125. assert( border_find_replace(" border-left: orange solid 1em; ") == ' border-left: 1em orange; ' )
  126. assert( border_find_replace(" border-style: solid none solid solid; ") == ' border-width: 3px 0px 3px 3px; ' )
  127. assert( border_find_replace(" border: solid; border-style: solid none solid solid; border-style: solid solid solid none; ") == ' border: 3px black; border-width: 3px 0px 3px 3px; border-width: 3px 3px 3px 0px; ' )
  128. assert( border_find_replace(" p + .set {border-top: solid orange} ") == ' p + .set {border-top: 3px orange} ' )
  129. assert( border_find_replace(r'<span style="border-right: none; border-left: none" class="outer">') == '<span style="border-right: 0px black; border-left: 0px black" class="outer">' )
  130. reference_links = []
  131. def process_file(in_file):
  132. in_path = os.path.join(in_dir, in_file)
  133. out_file = os.path.splitext(in_file)[0] + '.rml'
  134. out_path = os.path.join(out_dir, out_file)
  135. f = open(in_path, 'r', encoding="utf8")
  136. lines = f.readlines()
  137. f.close()
  138. data = ''
  139. reference_link = ''
  140. in_style = False
  141. for line in lines:
  142. if re.search(r'<style', line, flags = re.IGNORECASE):
  143. in_style = True
  144. if re.search(r'</style', line, flags = re.IGNORECASE):
  145. in_style = False
  146. if in_style:
  147. line = re.sub(r'(^|[^<])html', r'\1body', line, flags = re.IGNORECASE)
  148. reference_link_search_candidates = [
  149. r'(<link href="(reference/[^"]+))\.xht(" rel="match" ?/>)',
  150. r'(<link rel="match" href="(reference/[^"]+))\.xht(" ?/>)',
  151. ]
  152. for reference_link_search in reference_link_search_candidates:
  153. reference_link_match = re.search(reference_link_search, line, flags = re.IGNORECASE)
  154. if reference_link_match:
  155. reference_link = reference_link_match[2] + '.xht'
  156. line = re.sub(reference_link_search, r'\1.rml\3', line, flags = re.IGNORECASE)
  157. break
  158. line = re.sub(r'<!DOCTYPE[^>]*>\s*', '', line, flags = re.IGNORECASE)
  159. line = re.sub(r' xmlns="[^"]+"', '', line, flags = re.IGNORECASE)
  160. line = re.sub(r'<(/?)html[^>]*>', r'<\1rml>', line, flags = re.IGNORECASE)
  161. line = re.sub(r'^(\s*)(.*<head[^>]*>)', r'\1\2\n\1\1<link type="text/rcss" href="/../Tests/Data/style.rcss" />', line, flags = re.IGNORECASE)
  162. line = re.sub(r'direction:\s*ltr\s*;?', r'', line, flags = re.IGNORECASE)
  163. line = re.sub(r'list-style(-type)?:\s*none\s*;?', r'', line, flags = re.IGNORECASE)
  164. line = re.sub(r'max-height:\s*none;', r'max-height: -1px;', line, flags = re.IGNORECASE)
  165. line = re.sub(r'max-width:\s*none;', r'max-width: -1px;', line, flags = re.IGNORECASE)
  166. line = re.sub(r'(font(-size):[^;}\"]*)xxx-large', r'\1 2.0em', line, flags = re.IGNORECASE)
  167. line = re.sub(r'(font(-size):[^;}\"]*)xx-large', r'\1 1.7em', line, flags = re.IGNORECASE)
  168. line = re.sub(r'(font(-size):[^;}\"]*)x-large', r'\1 1.3em', line, flags = re.IGNORECASE)
  169. line = re.sub(r'(font(-size):[^;}\"]*)large', r'\1 1.15em', line, flags = re.IGNORECASE)
  170. line = re.sub(r'(font(-size):[^;}\"]*)medium', r'\1 1.0em', line, flags = re.IGNORECASE)
  171. line = re.sub(r'(font(-size):[^;}\"]*)small', r'\1 0.9em', line, flags = re.IGNORECASE)
  172. line = re.sub(r'(font(-size):[^;}\"]*)x-small', r'\1 0.7em', line, flags = re.IGNORECASE)
  173. line = re.sub(r'(font(-size):[^;}\"]*)xx-small', r'\1 0.5em', line, flags = re.IGNORECASE)
  174. line = re.sub(r'font:[^;}]*\b([0-9]+[a-z]+)\b[^;}]*([;}])', r'font-size: \1 \2', line, flags = re.IGNORECASE)
  175. line = re.sub(r'font-family:[^;}]*[;}]', r'', line, flags = re.IGNORECASE)
  176. line = re.sub(r'(line-height:)\s*normal', r'\1 1.2em', line, flags = re.IGNORECASE)
  177. line = re.sub(r'cyan', r'aqua', line, flags = re.IGNORECASE)
  178. if re.search(r'background:[^;}\"]*fixed', line, flags = re.IGNORECASE):
  179. print("File '{}' skipped since it uses unsupported background.".format(in_file))
  180. return False
  181. line = re.sub(r'background:(\s*([a-z]+|#[0-9a-f]+)\s*[;}\"])', r'background-color:\1', line, flags = re.IGNORECASE)
  182. line = border_find_replace(line)
  183. if in_style and not '<' in line:
  184. line = line.replace('&gt;', '>')
  185. flags_match = re.search(r'<meta.*name="flags" content="([^"]*)" ?/>', line, flags = re.IGNORECASE) or re.search(r'<meta.*content="([^"]*)".*name="flags".*?/>', line, flags = re.IGNORECASE)
  186. if flags_match and flags_match[1] != '' and flags_match[1] != 'interactive':
  187. print("File '{}' skipped due to flags '{}'".format(in_file, flags_match[1]))
  188. return False
  189. if re.search(r'(display:[^;]*(table|run-in|list-item))|(<table)', line, flags = re.IGNORECASE):
  190. print("File '{}' skipped since it uses tables.".format(in_file))
  191. return False
  192. if re.search(r'visibility:[^;]*collapse|z-index:\s*[0-9\.]+%', line, flags = re.IGNORECASE):
  193. print("File '{}' skipped since it uses unsupported visibility.".format(in_file))
  194. return False
  195. if re.search(r'data:|support/|<img|<iframe', line, flags = re.IGNORECASE):
  196. print("File '{}' skipped since it uses data or images.".format(in_file))
  197. return False
  198. if re.search(r'<script>', line, flags = re.IGNORECASE):
  199. print("File '{}' skipped since it uses scripts.".format(in_file))
  200. return False
  201. if in_style and re.search(r':before|:after|@media|\s\+\s', line, flags = re.IGNORECASE):
  202. print("File '{}' skipped since it uses unsupported CSS selectors.".format(in_file))
  203. return False
  204. if re.search(r'(: ?inherit ?;)|(!\s*important)|[0-9\.]+(ch|ex)[\s;}]', line, flags = re.IGNORECASE):
  205. print("File '{}' skipped since it uses unsupported CSS values.".format(in_file))
  206. return False
  207. if re.search(r'@font-face|font:|ahem', line, flags = re.IGNORECASE):
  208. print("File '{}' skipped since it uses special fonts.".format(in_file))
  209. return False
  210. if re.search(r'(direction:[^;]*[;"])|(content:[^;]*[;"])|(outline:[^;]*[;"])|(quote:[^;]*[;"])|(border-spacing:[^;]*[;"])|(border-collapse:[^;]*[;"])|(background:[^;]*[;"])|(box-sizing:[^;]*[;"])', line, flags = re.IGNORECASE)\
  211. or re.search(r'(font-variant:[^;]*[;"])|(font-kerning:[^;]*[;"])|(font-feature-settings:[^;]*[;"])|(background-image:[^;]*[;"])|(caption-side:[^;]*[;"])|(clip:[^;]*[;"])|(page-break-inside:[^;]*[;"])|(word-spacing:[^;]*[;"])', line, flags = re.IGNORECASE)\
  212. or re.search(r'(writing-mode:[^;]*[;"])|(text-orientation:[^;]*[;"])|(text-indent:[^;]*[;"])|(page-break-after:[^;]*[;"])|(column[^:]*:[^;]*[;"])|(empty-cells:[^;]*[;"])', line, flags = re.IGNORECASE):
  213. print("File '{}' skipped since it uses unsupported CSS properties.".format(in_file))
  214. return False
  215. data += line
  216. f = open(out_path, 'w', encoding="utf8")
  217. f.write(data)
  218. f.close()
  219. if reference_link:
  220. reference_links.append(reference_link)
  221. print("File '{}' processed successfully!".format(in_file))
  222. return True
  223. file_block_filters = ['charset','font','list','text-decoration','text-indent','text-transform','bidi','cursor',
  224. 'uri','stylesheet','word-spacing','table','outline','at-rule','at-import','attribute',
  225. 'style','quote','rtl','ltr','first-line','first-letter','first-page','import','border',
  226. 'chapter','character-encoding','escape','media','contain-','grid','case-insensitive',
  227. 'containing-block-initial','multicol','system-colors']
  228. def should_block(name):
  229. for file_block_filter in file_block_filters:
  230. if file_block_filter in name:
  231. print("File '{}' skipped due to unsupported feature '{}'".format(name, file_block_filter))
  232. return True
  233. return False
  234. in_dir_list = os.listdir(in_dir)
  235. if match_files:
  236. in_dir_list = [ name for name in in_dir_list if match_files in name ]
  237. total_files = len(in_dir_list)
  238. in_dir_list = [ name for name in in_dir_list if name.endswith(".xht") and not should_block(name) ]
  239. processed_files = 0
  240. processed_reference_files = 0
  241. for in_file in in_dir_list:
  242. if process_file(in_file):
  243. processed_files += 1
  244. final_reference_links = reference_links[:]
  245. total_reference_files = len(final_reference_links)
  246. reference_links.clear()
  247. for in_ref_file in final_reference_links:
  248. if process_file(in_ref_file):
  249. processed_reference_files += 1
  250. print('\nDone!\n\nTotal test files: {}\nSkipped test files: {}\nParsed test files: {}\n\nTotal reference files: {}\nSkipped reference files: {}\nIgnored alternate references: {}\nParsed reference files: {}'\
  251. .format(total_files, total_files - processed_files, processed_files, total_reference_files, total_reference_files - processed_reference_files, len(reference_links), processed_reference_files ))