VirtualBox

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

Last change on this file since 99516 was 99064, checked in by vboxsync, 21 months ago

manual/Makefile.kmk: Cleaning up html and qhelp outputting. The latter doesn't need an extra copy of the Docbook version of the images, since DITA-OT copies the necessary images to qhelp/topics/images/. bugref:10348 bugref:10302

  • Property svn:eol-style set to LF
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
File size: 9.6 KB
Line 
1#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3# $Id: htmlhelp-qthelp.py 99064 2023-03-20 12:01:53Z 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 full_html_path = os.path.join(folder, html_file_name)
57 file_content = open(full_html_path, encoding='utf-8').read()
58
59 class html_parser(HTMLParser):
60 def __init__(self):
61 HTMLParser.__init__(self)
62 self.a_tag = []
63 def handle_starttag(self, tag, attrs):
64 if tag != 'div' and tag != 'a':
65 return
66 if tag == 'a':
67 for a in attrs:
68 if a[0] == 'name':
69 self.a_tag.append(a[1])
70
71 parser = html_parser()
72 parser.feed(file_content)
73 for k in parser.a_tag:
74 line = '<keyword name="' + k + '" id="' + k + '" ref="' + html_file_name + '#' + k + '"/>'
75 keywords_section_lines.append(line)
76 keywords_section_lines.append('</keywords>')
77 return keywords_section_lines
78
79def create_image_list(folder):
80 """
81 find the png files under topics/images folder and create a part of the
82 qhelp project file with <file> tags
83 """
84 sFullImageFolderPath = os.path.join(folder, 'topics', 'images');
85 if not os.path.isdir(sFullImageFolderPath):
86 logging.error('Image subfolder "topics/images" is not found under "%s"!', folder)
87 sys.exit(1);
88 return ['<file>topics/images/%s</file>' % sFile for sFile in os.listdir(sFullImageFolderPath)];
89
90def create_html_list(folder, list_file):
91 """
92 open files list and read the list of html files from there
93 """
94 global html_files
95 html_file_lines = []
96 if not list_file in os.listdir(folder):
97 logging.error('Could not find the file "%s" in "%s"', list_file, folder)
98 return html_file_lines
99 full_path = os.path.join(folder, list_file)
100 with open(full_path, encoding='utf-8') as file:
101 lines = file.readlines()
102
103 # first search for the [FILES] marker then collect .html lines
104 marker_found = 0
105 for line in lines:
106 if '[FILES]' in line:
107 marker_found = 1
108 continue
109 if marker_found == 0:
110 continue
111 if '.html' in line:
112 html_file_lines.append('<file>' + line.strip('\n') + '</file>')
113 html_files.append(line.strip('\n'))
114 return html_file_lines
115
116
117def create_files_section(folder, list_file):
118 files_section_lines = ['<files>']
119 files_section_lines += create_image_list(folder)
120 files_section_lines += create_html_list(folder, list_file)
121 files_section_lines.append('</files>')
122 return files_section_lines
123
124def parse_param_tag(line):
125 label = 'value="'
126 start = line.find(label)
127 if start == -1:
128 return ''
129 start += len(label)
130 end = line.find('"', start)
131 if end == -1:
132 return ''
133 return line[start:end]
134
135def parse_object_tag(lines, index):
136 """
137 look at next two lines. they are supposed to look like the following
138 <param name="Name" value="Oracle VM VirtualBox">
139 <param name="Local" value="index.html">
140 parse out value fields and return
141 title="Oracle VM VirtualBox" ref="index.html
142 """
143 result = ''
144 if index + 2 > len(lines):
145 logging.warning('Not enough tags after this one "%s"', lines[index])
146 return result
147 if not re.match(r'^\s*<param', lines[index + 1], re.IGNORECASE) \
148 or not re.match(r'^\s*<param', lines[index + 2], re.IGNORECASE):
149 logging.warning('Skipping the line "%s" since next two tags are supposed to be param tags', lines[index])
150 return result
151 title = parse_param_tag(lines[index + 1])
152 ref = parse_param_tag(lines[index + 2])
153 global open_section_tags
154 if title and ref:
155 open_section_tags += 1
156 result = '<section title="' + title + '" ref="' + ref + '">'
157 else:
158 logging.warning('Title or ref part is empty for the tag "%s"', lines[index])
159 return result
160
161def parse_non_object_tag(lines, index):
162 """
163 parse any string other than staring with <OBJECT
164 decide if <section> tag should be closed
165 """
166
167 if index + 1 > len(lines):
168 return ''
169 global open_section_tags
170 if open_section_tags <= 0:
171 return ''
172 # replace </OBJECT with </section only if the next tag is not <UL
173 if re.match(r'^\s*</OBJECT', lines[index], re.IGNORECASE):
174 if not re.match(r'^\s*<UL', lines[index + 1], re.IGNORECASE):
175 open_section_tags -= 1
176 return '</section>'
177 elif re.match(r'^\s*</UL', lines[index], re.IGNORECASE):
178 open_section_tags -= 1
179 return '</section>'
180 return ''
181
182def parse_line(lines, index):
183 result = ''
184
185 # if the line starts with <OBJECT
186 if re.match(r'^\s*<OBJECT', lines[index], re.IGNORECASE):
187 result = parse_object_tag(lines, index)
188 else:
189 result = parse_non_object_tag(lines, index)
190 return result
191
192def create_toc(folder, toc_file):
193 """
194 parse TOC file. assuming all the relevant information
195 is stored in tags and attributes. whatever is outside of
196 <... > pairs is filtered out. we also assume < ..> are not nested
197 and each < matches to a >
198 """
199 toc_string_list = []
200 content = [x[2] for x in os.walk(folder)]
201 if toc_file not in content[0]:
202 logging.error('Could not find toc file "%s" under "%s"', toc_file, folder)
203 return toc_string_list
204 full_path = os.path.join(folder, toc_file)
205 with open(full_path, encoding='utf-8') as file:
206 content = file.read()
207
208 # convert the file string into a list of tags there by eliminating whatever
209 # char reside outside of tags.
210 char_pos = 0
211 tag_list = []
212 while char_pos < len(content):
213 start = content.find('<', char_pos)
214 if start == -1:
215 break
216 end = content.find('>', start)
217 if end == -1 or end >= len(content) - 1:
218 break
219 char_pos = end
220 tag_list.append(content[start:end +1])
221
222 # # insert new line chars. to make sure each line includes at most one tag
223 # content = re.sub(r'>.*?<', r'>\n<', content)
224 # lines = content.split('\n')
225 toc_string_list.append('<toc>')
226 for index, _ in enumerate(tag_list):
227 str = parse_line(tag_list, index)
228 if str:
229 toc_string_list.append(str)
230 toc_string_list.append('</toc>')
231 toc_string = '\n'.join(toc_string_list)
232
233 return toc_string_list
234
235def usage(iExitCode):
236 print('htmlhelp-qthelp.py -d <helphtmlfolder> -o <outputfilename>')
237 return iExitCode
238
239def main(argv):
240 # Parse arguments.
241 helphtmlfolder = ''
242 output_filename = ''
243 list_file = ''
244 toc_file = ''
245 try:
246 opts, _ = getopt.getopt(argv[1:], "hd:o:f:t:")
247 except getopt.GetoptError as err:
248 logging.error(str(err))
249 return usage(2)
250 for opt, arg in opts:
251 if opt == '-h':
252 return usage(0)
253 if opt == "-d":
254 helphtmlfolder = arg
255 print(helphtmlfolder)
256 elif opt == "-f":
257 list_file = arg
258 elif opt == "-t":
259 toc_file = arg
260 print(toc_file)
261 elif opt == "-o":
262 output_filename = arg
263 # check supplied helphtml folder argument
264 if not helphtmlfolder:
265 logging.error('No helphtml folder is provided. Exiting')
266 return usage(2)
267 if not os.path.exists(helphtmlfolder):
268 logging.error('folder "%s" does not exist. Exiting', helphtmlfolder)
269 return usage(2)
270 helphtmlfolder = os.path.normpath(helphtmlfolder)
271
272 # check supplied output file name
273 if not output_filename:
274 logging.error('No filename for output is given. Exiting')
275 return usage(2)
276
277 out_xml_lines = ['<?xml version="1.0" encoding="UTF-8"?>',
278 '<QtHelpProject version="1.0">',
279 '<namespace>org.virtualbox</namespace>',
280 '<virtualFolder>doc</virtualFolder>',
281 '<filterSection>']
282 out_xml_lines += create_toc(helphtmlfolder, toc_file)
283 out_xml_lines += create_files_section(helphtmlfolder, list_file)
284 out_xml_lines += create_keywords_section(helphtmlfolder)
285 out_xml_lines += ['</filterSection>', '</QtHelpProject>']
286
287 with open(output_filename, 'wb') as out_file:
288 out_file.write('\n'.join(out_xml_lines).encode('utf8'))
289 return 0
290
291if __name__ == '__main__':
292 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