2 #A part of NonVisual Desktop Access (NVDA)
\r
3 #This file is covered by the GNU General Public License.
\r
4 #See the file COPYING for more details.
\r
5 #Copyright (C) 2010 James Teh <jamie@jantrid.net>
\r
7 """Utilities related to NVDA Key Commands documents.
\r
17 class KeyCommandsError(Exception):
\r
18 """Raised due to an error encountered in the User Guide related to generation of the Key Commands document.
\r
21 class KeyCommandsMaker(object):
\r
22 """Generates the Key Commands document from the User Guide.
\r
23 To generate a Key Commands document, create an instance and then call L{make} on it.
\r
25 Generation of the Key Commands document requires certain commands to be included in the user guide.
\r
26 These commands must begin at the start of the line and take the form::
\r
29 The kc:title command must appear first and specifies the title of the Key Commands document. For example::
\r
30 %kc:title: NVDA Key Commands
\r
32 The kc:includeconf command allows you to insert a txt2tags includeconf command in the Key Commands document. For example::
\r
33 %kc:includeconf: ../ar.t2tconf
\r
34 You may use multiple kc:includeconf commands, but they must appear before any of the other commands below.
\r
36 The rest of these commands are used to include key commands into the document.
\r
37 Appropriate headings from the User Guide will be included implicitly.
\r
39 The kc:beginInclude command begins a block of text which should be included verbatim.
\r
40 The block ends at the kc:endInclude command.
\r
43 || Name | Desktop command | Laptop command | Description |
\r
47 The kc:settingsSection command indicates the beginning of a section documenting individual settings.
\r
48 It specifies the header row for a table summarising the settings indicated by the kc:setting command (see below).
\r
49 In order, it must consist of a name column, a column for each keyboard layout and a description column.
\r
51 %kc:settingsSection: || Name | Desktop command | Laptop command | Description |
\r
53 The kc:setting command indicates a section for an individual setting.
\r
54 It must be followed by:
\r
55 * A heading containing the name of the setting;
\r
56 * A table row for each keyboard layout, or if the key is common to all layouts, a single line of text specifying the key after a colon;
\r
58 * A line describing the setting.
\r
61 ==== Braille Tethered To ====
\r
62 | Desktop command | NVDA+control+t |
\r
63 | Laptop Command | NVDA+control+t |
\r
64 This option allows you to choose whether the braille display will follow the system focus, or whether it follows the navigator object / review cursor.
\r
68 RE_COMMAND = re.compile(r"^%kc:(?P<cmd>[^:\s]+)(?:: (?P<arg>.*))?$")
\r
74 def _initClass(cls):
\r
77 # Only fetch this once.
\r
78 cls.t2tRe = txt2tags.getRegexes()
\r
80 def __init__(self, userGuideFilename,keyCommandsFileName):
\r
82 @param userGuideFilename: The file name of the User Guide to be used as input.
\r
83 @type userGuideFilename: str
\r
84 @param keyCommandsFilename: The file name of the key commands file to be output.
\r
85 @type keyCommandsFilename: str
\r
88 self.ugFn = userGuideFilename
\r
89 #: The file name of the Key Commands document that will be generated.
\r
90 #: This will be in the same directory as the User Guide.
\r
91 self.kcFn = keyCommandsFileName
\r
92 #: The current section of the key commands file.
\r
93 self._kcSect = self.KCSECT_HEADER
\r
94 #: The current stack of headings.
\r
96 #: The 0 based level of the last heading in L{_headings} written to the key commands file.
\r
97 self._kcLastHeadingLevel = -1
\r
98 #: Whether lines which aren't commands should be written to the key commands file as is.
\r
99 self._kcInclude = False
\r
100 #: The header row for settings sections.
\r
101 self._settingsHeaderRow = None
\r
102 #: The number of layouts for settings in a settings section.
\r
103 self._settingsNumLayouts = 0
\r
106 """Generate the Key Commands document.
\r
107 @postcondition: If the User Guide contains appropriate commands, the Key Commands document will be generated and saved as L{kcFn}.
\r
108 Otherwise, no file will be generated.
\r
109 @return: C{True} if a document was generated, C{False} otherwise.
\r
112 @raise KeyCommandsError:
\r
114 tKcFn=self.kcFn+'__'
\r
115 self._ug = codecs.open(self.ugFn, "r", "utf-8-sig")
\r
116 self._kc = codecs.open(tKcFn, "w", "utf-8-sig")
\r
119 with self._ug, self._kc:
\r
121 success=self._kc.tell() > 0
\r
123 os.rename(tKcFn,self.kcFn)
\r
129 for line in self._ug:
\r
130 line = line.rstrip()
\r
131 m = self.RE_COMMAND.match(line)
\r
133 self._command(**m.groupdict())
\r
136 m = self.t2tRe["numtitle"].match(line)
\r
141 if self._kcInclude:
\r
142 self._kc.write(line + LINE_END)
\r
144 def _command(self, cmd=None, arg=None):
\r
145 # Handle header commands.
\r
147 if self._kcSect > self.KCSECT_HEADER:
\r
148 raise KeyCommandsError("title command is not valid here")
\r
149 # Write the title and two blank lines to complete the txt2tags header section.
\r
150 self._kc.write(arg + LINE_END * 3)
\r
151 self._kcSect = self.KCSECT_CONFIG
\r
152 self._kc.write("%%!includeconf: ../global.t2tconf%s" % LINE_END)
\r
154 elif self._kcSect == self.KCSECT_HEADER:
\r
155 raise KeyCommandsError("title must be the first command")
\r
156 elif cmd == "includeconf":
\r
157 if self._kcSect > self.KCSECT_CONFIG:
\r
158 raise KeyCommandsError("includeconf command is not valid here")
\r
159 self._kc.write("%%!includeconf: %s%s" % (arg, LINE_END))
\r
161 elif self._kcSect == self.KCSECT_CONFIG:
\r
162 self._kc.write(LINE_END)
\r
163 self._kcSect = self.KCSECT_BODY
\r
165 if cmd == "beginInclude":
\r
166 self._writeHeadings()
\r
167 self._kcInclude = True
\r
168 elif cmd == "endInclude":
\r
169 self._kcInclude = False
\r
170 self._kc.write(LINE_END)
\r
172 elif cmd == "settingsSection":
\r
173 # The argument is the table header row for the settings section.
\r
174 self._settingsHeaderRow = arg
\r
175 # There are name and description columns.
\r
176 # Each of the remaining columns provides keystrokes for one layout.
\r
177 # There's one less delimiter than there are columns, hence subtracting 1 instead of 2.
\r
178 self._settingsNumLayouts = arg.strip("|").count("|") - 1
\r
179 elif cmd == "setting":
\r
180 self._handleSetting()
\r
183 raise KeyCommandsError("Invalid command %s" % cmd)
\r
185 def _areHeadingsPending(self):
\r
186 return self._kcLastHeadingLevel < len(self._headings) - 1
\r
188 def _writeHeadings(self):
\r
189 level = self._kcLastHeadingLevel + 1
\r
190 # Only write headings we haven't yet written.
\r
191 for level, heading in enumerate(self._headings[level:], level):
\r
192 # We don't want numbered headings in the output.
\r
193 label=heading.group("label")
\r
194 headingText = u"{id}{txt}{id}{label}".format(
\r
195 id="=" * len(heading.group("id")),
\r
196 txt=heading.group("txt"),
\r
197 label="[%s]" % label if label else "")
\r
198 # Write the heading and a blank line.
\r
199 self._kc.write(headingText + LINE_END * 2)
\r
200 self._kcLastHeadingLevel = level
\r
202 def _heading(self, m):
\r
203 # We work with 0 based heading levels.
\r
204 level = len(m.group("id")) - 1
\r
206 del self._headings[level:]
\r
209 self._headings.append(m)
\r
210 self._kcLastHeadingLevel = min(self._kcLastHeadingLevel, level - 1)
\r
212 def _handleSetting(self):
\r
213 if not self._settingsHeaderRow:
\r
214 raise KeyCommandsError("setting command cannot be used before settingsSection command")
\r
216 if self._areHeadingsPending():
\r
217 # There are new headings to write.
\r
218 # If there was a previous settings table, it ends here, so write a blank line.
\r
219 self._kc.write(LINE_END)
\r
220 self._writeHeadings()
\r
221 # New headings were written, so we need to output the header row.
\r
222 self._kc.write(self._settingsHeaderRow + LINE_END)
\r
224 # The next line should be a heading which is the name of the setting.
\r
225 line = next(self._ug)
\r
226 m = self.t2tRe["title"].match(line)
\r
228 raise KeyCommandsError("setting command must be followed by heading")
\r
229 name = m.group("txt")
\r
231 # The next few lines should be table rows for each layout.
\r
232 # Alternatively, if the key is common to all layouts, there will be a single line of text specifying the key after a colon.
\r
234 for layout in xrange(self._settingsNumLayouts):
\r
235 line = next(self._ug).strip()
\r
237 keys.append(line.split(":", 1)[1].strip())
\r
239 elif not self.t2tRe["table"].match(line):
\r
240 raise KeyCommandsError("setting command: There must be one table row for each keyboard layout")
\r
241 # This is a table row.
\r
242 # The key will be the second column.
\r
243 # TODO: Error checking.
\r
244 key = line.strip("|").split("|")[1].strip()
\r
246 if 1 == len(keys) < self._settingsNumLayouts:
\r
247 # The key has only been specified once, so it is the same in all layouts.
\r
249 keys[1:] = (key for layout in xrange(self._settingsNumLayouts - 1))
\r
251 # There should now be a blank line.
\r
252 line = next(self._ug).strip()
\r
254 raise KeyCommandsError("setting command: The keyboard shortcuts must be followed by a blank line. Multiple keys must be included in a table. Erroneous key: %s"%key)
\r
256 # Finally, the next line should be the description.
\r
257 desc = next(self._ug).strip()
\r
259 self._kc.write(u"| {name} | {keys} | {desc} |{lineEnd}".format(
\r
261 keys=u" | ".join(keys),
\r
262 desc=desc, lineEnd=LINE_END))
\r
265 """Remove the generated Key Commands document.
\r
268 os.remove(self.kcFn)
\r