VirtualBox

source: vbox/trunk/doc/manual/htmlhelp-qthelp.py@ 105694

Last change on this file since 105694 was 105563, checked in by vboxsync, 4 months ago

doc/htmlhelp-qthelp.py: bugref:10302. Do use iso-8859-1 encoding for the htmlhelp files because that's what dita-ot uses (and correctly puts in the meta tag) for en-us language. Note that the encoding usage is different for xhtml.

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 9.7 KB
Line 
1#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3# $Id: htmlhelp-qthelp.py 105563 2024-08-01 12:03:00Z vboxsync $
4
5"""
6A python script to create a .qhp file out of a given htmlhelp
7folder. Lots of things about the said folder is assumed. Please
8see the code and inlined comments.
9"""
10
11__copyright__ = \
12"""
13Copyright (C) 2006-2023 Oracle and/or its affiliates.
14
15This file is part of VirtualBox base platform packages, as
16available from https://www.virtualbox.org.
17
18This program is free software; you can redistribute it and/or
19modify it under the terms of the GNU General Public License
20as published by the Free Software Foundation, in version 3 of the
21License.
22
23This program is distributed in the hope that it will be useful, but
24WITHOUT ANY WARRANTY; without even the implied warranty of
25MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26General Public License for more details.
27
28You should have received a copy of the GNU General Public License
29along with this program; if not, see <https://www.gnu.org/licenses>.
30
31SPDX-License-Identifier: GPL-3.0-only
32"""
33
34import getopt
35import logging
36import os.path
37import re
38import sys
39
40if sys.version_info[0] >= 3:
41 from html.parser import HTMLParser
42else:
43 from HTMLParser import HTMLParser
44
45# number of opened and not yet closed section tags of toc section
46open_section_tags = 0
47
48html_files = []
49
50def create_keywords_section(folder):
51 """
52 use html_parser stuff to collect <a name ...> tags
53 """
54 keywords_section_lines = ['<keywords>']
55 for html_file_name in html_files:
56 # dita-ot creates htmlhelp output for en-us language in iso-8859-1 encoding, not utf-8
57 full_html_path = os.path.join(folder, html_file_name)
58 file_content = open(full_html_path, encoding='iso-8859-1').read()
59
60 class html_parser(HTMLParser):
61 def __init__(self):
62 HTMLParser.__init__(self)
63 self.a_tag = []
64 def handle_starttag(self, tag, attrs):
65 if tag != 'div' and tag != 'a':
66 return
67 if tag == 'a':
68 for a in attrs:
69 if a[0] == 'name':
70 self.a_tag.append(a[1])
71
72 parser = html_parser()
73 parser.feed(file_content)
74 for k in parser.a_tag:
75 line = '<keyword name="' + k + '" id="' + k + '" ref="' + html_file_name + '#' + k + '"/>'
76 keywords_section_lines.append(line)
77 keywords_section_lines.append('</keywords>')
78 return keywords_section_lines
79
80def create_image_list(folder):
81 """
82 find the png files under topics/images folder and create a part of the
83 qhelp project file with <file> tags
84 """
85 sFullImageFolderPath = os.path.join(folder, 'topics', 'images');
86 if not os.path.isdir(sFullImageFolderPath):
87 logging.error('Image subfolder "topics/images" is not found under "%s"!', folder)
88 sys.exit(1);
89 return ['<file>topics/images/%s</file>' % sFile for sFile in os.listdir(sFullImageFolderPath)];
90
91def create_html_list(folder, list_file):
92 """
93 open files list and read the list of html files from there
94 """
95 global html_files
96 html_file_lines = []
97 if not list_file in os.listdir(folder):
98 logging.error('Could not find the file "%s" in "%s"', list_file, folder)
99 return html_file_lines
100 full_path = os.path.join(folder, list_file)
101 with open(full_path, encoding='utf-8') as file:
102 lines = file.readlines()
103
104 # first search for the [FILES] marker then collect .html lines
105 marker_found = 0
106 for line in lines:
107 if '[FILES]' in line:
108 marker_found = 1
109 continue
110 if marker_found == 0:
111 continue
112 if '.html' in line:
113 html_file_lines.append('<file>' + line.strip('\n') + '</file>')
114 html_files.append(line.strip('\n'))
115 return html_file_lines
116
117
118def create_files_section(folder, list_file):
119 files_section_lines = ['<files>']
120 files_section_lines += create_image_list(folder)
121 files_section_lines += create_html_list(folder, list_file)
122 files_section_lines.append('</files>')
123 return files_section_lines
124
125def parse_param_tag(line):
126 label = 'value="'
127 start = line.find(label)
128 if start == -1:
129 return ''
130 start += len(label)
131 end = line.find('"', start)
132 if end == -1:
133 return ''
134 return line[start:end]
135
136def parse_object_tag(lines, index):
137 """
138 look at next two lines. they are supposed to look like the following
139 <param name="Name" value="Oracle VirtualBox">
140 <param name="Local" value="index.html">
141 parse out value fields and return
142 title="Oracle VirtualBox" ref="index.html
143 """
144 result = ''
145 if index + 2 > len(lines):
146 logging.warning('Not enough tags after this one "%s"', lines[index])
147 return result
148 if not re.match(r'^\s*<param', lines[index + 1], re.IGNORECASE) \
149 or not re.match(r'^\s*<param', lines[index + 2], re.IGNORECASE):
150 logging.warning('Skipping the line "%s" since next two tags are supposed to be param tags', lines[index])
151 return result
152 title = parse_param_tag(lines[index + 1])
153 ref = parse_param_tag(lines[index + 2])
154 global open_section_tags
155 if title and ref:
156 open_section_tags += 1
157 result = '<section title="' + title + '" ref="' + ref + '">'
158 else:
159 logging.warning('Title or ref part is empty for the tag "%s"', lines[index])
160 return result
161
162def parse_non_object_tag(lines, index):
163 """
164 parse any string other than staring with <OBJECT
165 decide if <section> tag should be closed
166 """
167
168 if index + 1 > len(lines):
169 return ''
170 global open_section_tags
171 if open_section_tags <= 0:
172 return ''
173 # replace </OBJECT with </section only if the next tag is not <UL
174 if re.match(r'^\s*</OBJECT', lines[index], re.IGNORECASE):
175 if not re.match(r'^\s*<UL', lines[index + 1], re.IGNORECASE):
176 open_section_tags -= 1
177 return '</section>'
178 elif re.match(r'^\s*</UL', lines[index], re.IGNORECASE):
179 open_section_tags -= 1
180 return '</section>'
181 return ''
182
183def parse_line(lines, index):
184 result = ''
185
186 # if the line starts with <OBJECT
187 if re.match(r'^\s*<OBJECT', lines[index], re.IGNORECASE):
188 result = parse_object_tag(lines, index)
189 else:
190 result = parse_non_object_tag(lines, index)
191 return result
192
193def create_toc(folder, toc_file):
194 """
195 parse TOC file. assuming all the relevant information
196 is stored in tags and attributes. whatever is outside of
197 <... > pairs is filtered out. we also assume < ..> are not nested
198 and each < matches to a >
199 """
200 toc_string_list = []
201 content = [x[2] for x in os.walk(folder)]
202 if toc_file not in content[0]:
203 logging.error('Could not find toc file "%s" under "%s"', toc_file, folder)
204 return toc_string_list
205 full_path = os.path.join(folder, toc_file)
206 with open(full_path, encoding='utf-8') as file:
207 content = file.read()
208
209 # convert the file string into a list of tags there by eliminating whatever
210 # char reside outside of tags.
211 char_pos = 0
212 tag_list = []
213 while char_pos < len(content):
214 start = content.find('<', char_pos)
215 if start == -1:
216 break
217 end = content.find('>', start)
218 if end == -1 or end >= len(content) - 1:
219 break
220 char_pos = end
221 tag_list.append(content[start:end +1])
222
223 # # insert new line chars. to make sure each line includes at most one tag
224 # content = re.sub(r'>.*?<', r'>\n<', content)
225 # lines = content.split('\n')
226 toc_string_list.append('<toc>')
227 for index, _ in enumerate(tag_list):
228 str = parse_line(tag_list, index)
229 if str:
230 toc_string_list.append(str)
231 toc_string_list.append('</toc>')
232 toc_string = '\n'.join(toc_string_list)
233
234 return toc_string_list
235
236def usage(iExitCode):
237 print('htmlhelp-qthelp.py -d <helphtmlfolder> -o <outputfilename>')
238 return iExitCode
239
240def main(argv):
241 # Parse arguments.
242 helphtmlfolder = ''
243 output_filename = ''
244 list_file = ''
245 toc_file = ''
246 try:
247 opts, _ = getopt.getopt(argv[1:], "hd:o:f:t:")
248 except getopt.GetoptError as err:
249 logging.error(str(err))
250 return usage(2)
251 for opt, arg in opts:
252 if opt == '-h':
253 return usage(0)
254 if opt == "-d":
255 helphtmlfolder = arg
256 print(helphtmlfolder)
257 elif opt == "-f":
258 list_file = arg
259 elif opt == "-t":
260 toc_file = arg
261 print(toc_file)
262 elif opt == "-o":
263 output_filename = arg
264 # check supplied helphtml folder argument
265 if not helphtmlfolder:
266 logging.error('No helphtml folder is provided. Exiting')
267 return usage(2)
268 if not os.path.exists(helphtmlfolder):
269 logging.error('folder "%s" does not exist. Exiting', helphtmlfolder)
270 return usage(2)
271 helphtmlfolder = os.path.normpath(helphtmlfolder)
272
273 # check supplied output file name
274 if not output_filename:
275 logging.error('No filename for output is given. Exiting')
276 return usage(2)
277
278 out_xml_lines = ['<?xml version="1.0" encoding="UTF-8"?>',
279 '<QtHelpProject version="1.0">',
280 '<namespace>org.virtualbox</namespace>',
281 '<virtualFolder>doc</virtualFolder>',
282 '<filterSection>']
283 out_xml_lines += create_toc(helphtmlfolder, toc_file)
284 out_xml_lines += create_files_section(helphtmlfolder, list_file)
285 out_xml_lines += create_keywords_section(helphtmlfolder)
286 out_xml_lines += ['</filterSection>', '</QtHelpProject>']
287
288 with open(output_filename, 'wb') as out_file:
289 out_file.write('\n'.join(out_xml_lines).encode('utf8'))
290 return 0
291
292if __name__ == '__main__':
293 sys.exit(main(sys.argv))
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette