Debian Codegraph @

src/calibre/gui2/css_transform_rules.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
3
4 from qt.core import QComboBox, QDialogButtonBox, QHBoxLayout, QLabel, QLineEdit, QMenu, QPushButton, QSize, QTextCursor, QVBoxLayout, QWidget, pyqtSignal
5
6 from calibre.ebooks.css_transform_rules import (
7 ACTION_MAP,
8 MATCH_TYPE_MAP,
9 compile_rules,
10 export_rules,
11 import_rules,
12 safe_parser,
13 transform_sheet,
14 validate_rule,
15 )
16 from calibre.gui2 import choose_files, choose_save_file, elided_text, error_dialog
17 from calibre.gui2.tag_mapper import RuleEdit as RE
18 from calibre.gui2.tag_mapper import RuleEditDialog as RuleEditDialogBase
19 from calibre.gui2.tag_mapper import RuleItem as RuleItemBase
20 from calibre.gui2.tag_mapper import Rules as RulesBase
21 from calibre.gui2.tag_mapper import RulesDialog as RulesDialogBase
22 from calibre.gui2.tag_mapper import SaveLoadMixin
23 from calibre.gui2.widgets2 import Dialog
24 from calibre.utils.config import JSONConfig
25 from calibre.utils.localization import _, localize_user_manual_link
26
27
28 class RuleEdit(QWidget): # {{{
29 MSG = _('Create the rule below, the rule can be used to transform style properties')
30
31 def __init__(self, parent=None):
32 QWidget.__init__(self, parent)
33 self.l = l = QVBoxLayout(self)
34 self.h = h = QHBoxLayout()
35
36 self.la = la = QLabel(self.MSG)
37 la.setWordWrap(True)
38 l.addWidget(la)
39 l.addLayout(h)
40 english_sentence = '{preamble} {property} {match_type} {query}'
41 sentence = _('{preamble} {property} {match_type} {query}')
42 if set(sentence.split()) != set(english_sentence.split()):
43 sentence = english_sentence
44 parts = sentence.split()
45 for clause in parts:
46 if clause == '{preamble}':
47 self.preamble = w = QLabel(_('If the &property:'))
48 elif clause == '{property}':
49 self.property_widget = w = QLineEdit(self)
50 w.setToolTip(
51 _(
52 'The name of a CSS property, for example: font-size\n'
53 'Do not use shorthand properties, they will not work.\n'
54 'For instance use margin-top, not margin.'
55 )
56 )
57 elif clause == '{match_type}':
58 self.match_type = w = QComboBox(self)
59 for action, text in MATCH_TYPE_MAP.items():
60 w.addItem(text, action)
61 w.currentIndexChanged.connect(self.update_state)
62 elif clause == '{query}':
63 self.query = w = QLineEdit(self)
64 h.addWidget(w)
65 if clause is not parts[-1]:
66 h.addWidget(QLabel('\xa0'))
67 self.preamble.setBuddy(self.property_widget)
68
69 self.h2 = h = QHBoxLayout()
70 l.addLayout(h)
71 english_sentence = '{action} {action_data}'
72 sentence = _('{action} {action_data}')
73 if set(sentence.split()) != set(english_sentence.split()):
74 sentence = english_sentence
75 parts = sentence.split()
76 for clause in parts:
77 if clause == '{action}':
78 self.action = w = QComboBox(self)
79 for action, text in ACTION_MAP.items():
80 w.addItem(text, action)
81 w.currentIndexChanged.connect(self.update_state)
82 elif clause == '{action_data}':
83 self.action_data = w = QLineEdit(self)
84 h.addWidget(w)
85 if clause is not parts[-1]:
86 h.addWidget(QLabel('\xa0'))
87
88 self.regex_help = la = QLabel('<p>' + RE.REGEXP_HELP_TEXT % localize_user_manual_link('https://manual.calibre-ebook.com/regexp.html'))
89 la.setOpenExternalLinks(True)
90 la.setWordWrap(True)
91 l.addWidget(la)
92 l.addStretch(10)
93
94 self.update_state()
95
96 def sizeHint(self):
97 a = QWidget.sizeHint(self)
98 a.setHeight(a.height() + 75)
99 a.setWidth(a.width() + 100)
100 return a
101
102 def update_state(self):
103 r = self.rule
104 self.action_data.setVisible(r['action'] != 'remove')
105 tt = _('The CSS property value')
106 mt = r['match_type']
107 self.query.setVisible(mt != '*')
108 if 'matches' in mt:
109 tt = _('A regular expression')
110 elif mt in '< > <= >='.split():
111 tt = _(
112 'Either a CSS length, such as 10pt or a unit less number. If a unit less'
113 ' number is used it will be compared with the CSS value using whatever unit'
114 ' the value has. Note that comparison automatically converts units, except'
115 ' for relative units like percentage or em, for which comparison fails'
116 ' if the units are different.'
117 )
118 self.query.setToolTip(tt)
119 tt = ''
120 ac = r['action']
121 if ac == 'append':
122 tt = _(
123 'CSS properties to add to the rule that contains the matching style. You'
124 ' can specify more than one property, separated by semi-colons, for example:'
125 ' color:red; font-weight: bold'
126 )
127 elif ac in '+=*/':
128 tt = _('A number')
129 self.action_data.setToolTip(tt)
130 self.regex_help.setVisible('matches' in mt)
131
132 @property
133 def rule(self):
134 return {
135 'property': self.property_widget.text().strip().lower(),
136 'match_type': self.match_type.currentData(),
137 'query': self.query.text().strip(),
138 'action': self.action.currentData(),
139 'action_data': self.action_data.text().strip(),
140 }
141
142 @rule.setter
143 def rule(self, rule):
144 def sc(name):
145 c = getattr(self, name)
146 idx = c.findData(str(rule.get(name, '')))
147 idx = max(idx, 0)
148 c.setCurrentIndex(idx)
149
150 sc('action'), sc('match_type')
151 self.property_widget.setText(str(rule.get('property', '')).strip())
152 self.query.setText(str(rule.get('query', '')).strip())
153 self.action_data.setText(str(rule.get('action_data', '')).strip())
154 self.update_state()
155
156 def validate(self):
157 rule = self.rule
158 title, msg = validate_rule(rule)
159 if msg is not None and title is not None:
160 error_dialog(self, title, msg, show=True)
161 return False
162 return True
163
164
165 # }}}
166
167
168 class RuleEditDialog(RuleEditDialogBase): # {{{
169 PREFS_NAME = 'edit-css-transform-rule'
170 DIALOG_TITLE = _('Edit rule')
171 RuleEditClass = RuleEdit
172
173
174 # }}}
175
176
177 class RuleItem(RuleItemBase): # {{{
178 @staticmethod
179 def text_from_rule(rule, parent):
180 try:
181 query = elided_text(rule['query'], font=parent.font(), width=200, pos='right')
182 text = _('If the property <i>{property}</i> <b>{match_type}</b> <b>{query}</b><br>{action}').format(
183 property=rule['property'],
184 action=ACTION_MAP[rule['action']],
185 match_type=MATCH_TYPE_MAP[rule['match_type']],
186 query=query,
187 )
188 if rule['action_data']:
189 ad = elided_text(rule['action_data'], font=parent.font(), width=200, pos='right')
190 text += f' <code>{ad}</code>'
191 except Exception:
192 import traceback
193
194 traceback.print_exc()
195 text = _('This rule is invalid, please remove it')
196 return text
197
198
199 # }}}
200
201
202 class Rules(RulesBase): # {{{
203 RuleItemClass = RuleItem
204 RuleEditDialogClass = RuleEditDialog
205
206 MSG = _('You can specify rules to transform styles here. Click the "Add rule" button below to get started.')
207
208
209 # }}}
210
211
212 class Tester(Dialog): # {{{
213 DIALOG_TITLE = _('Test style transform rules')
214 PREFS_NAME = 'test-style-transform-rules'
215 LABEL = _('Enter a CSS stylesheet below and click the "Test" button')
216 SYNTAX = 'css'
217 RESULTS = '/* {} */\n\n'.format(_('Resulting stylesheet'))
218
219 def __init__(self, rules, parent=None):
220 self.rules = self.compile_rules(rules)
221 Dialog.__init__(self, self.DIALOG_TITLE, self.PREFS_NAME, parent=parent)
222
223 def compile_rules(self, rules):
224 return compile_rules(rules)
225
226 def setup_ui(self):
227 from calibre.gui2.tweak_book.editor.text import TextEdit
228
229 self.l = l = QVBoxLayout(self)
230 self.bb.setStandardButtons(QDialogButtonBox.StandardButton.Close)
231 self.la = la = QLabel(self.LABEL)
232 l.addWidget(la)
233 self.css = t = TextEdit(self)
234 t.load_text('', self.SYNTAX)
235 la.setBuddy(t)
236 c = t.textCursor()
237 c.movePosition(QTextCursor.MoveOperation.End)
238 t.setTextCursor(c)
239 self.h = h = QHBoxLayout()
240 l.addLayout(h)
241 h.addWidget(t)
242 self.test_button = b = QPushButton(_('&Test'), self)
243 b.clicked.connect(self.do_test)
244 h.addWidget(b)
245 self.result_widget = la = TextEdit(self)
246 la.setReadOnly(True)
247 l.addWidget(la)
248 l.addWidget(self.bb)
249
250 @property
251 def value(self):
252 return self.css.toPlainText()
253
254 def do_test(self):
255 decl = safe_parser().parseString(self.value)
256 transform_sheet(self.rules, decl)
257 css = decl.cssText
258 if isinstance(css, bytes):
259 css = css.decode('utf-8')
260 self.set_result(css)
261
262 def set_result(self, css):
263 self.result_widget.load_text(self.RESULTS + css, self.SYNTAX)
264
265 def sizeHint(self):
266 return QSize(800, 600)
267
268
269 # }}}
270
271
272 class RulesDialog(RulesDialogBase): # {{{
273 DIALOG_TITLE = _('Edit style transform rules')
274 PREFS_NAME = 'edit-style-transform-rules'
275 PREFS_OBJECT_NAME = 'style-transform-rules'
276 RulesClass = Rules
277 TesterClass = Tester
278
279 def __init__(self, *args, **kw):
280 # This has to be loaded on instantiation as it can be shared by
281 # multiple processes
282 self.PREFS_OBJECT = JSONConfig(self.PREFS_OBJECT_NAME)
283 RulesDialogBase.__init__(self, *args, **kw)
284
285
286 # }}}
287
288
289 class RulesWidget(QWidget, SaveLoadMixin): # {{{
290 changed = pyqtSignal()
291 PREFS_NAME = 'style-transform-rules'
292 INITIAL_FILE_NAME = 'css-rules.txt'
293 DIR_SAVE_NAME = 'export-style-transform-rules'
294 export_func = export_rules
295 import_func = import_rules
296 TesterClass = Tester
297 RulesClass = Rules
298
299 def __init__(self, parent=None):
300 self.loaded_ruleset = None
301 QWidget.__init__(self, parent)
302 self.PREFS_OBJECT = JSONConfig(self.PREFS_NAME)
303 l = QVBoxLayout(self)
304 self.rules_widget = w = self.RulesClass(self)
305 w.changed.connect(self.changed.emit)
306 l.addWidget(w)
307 self.h = h = QHBoxLayout()
308 l.addLayout(h)
309 self.export_button = b = QPushButton(_('E&xport'), self)
310 b.setToolTip(_('Export these rules to a file'))
311 b.clicked.connect(self.export_rules)
312 h.addWidget(b)
313 self.import_button = b = QPushButton(_('&Import'), self)
314 b.setToolTip(_('Import previously exported rules'))
315 b.clicked.connect(self.import_rules)
316 h.addWidget(b)
317 self.test_button = b = QPushButton(_('&Test rules'), self)
318 b.clicked.connect(self.test_rules)
319 h.addWidget(b)
320 h.addStretch(10)
321 self.save_button = b = QPushButton(_('&Save'), self)
322 b.setToolTip(_('Save this ruleset for later re-use'))
323 b.clicked.connect(self.save_ruleset)
324 h.addWidget(b)
325 self.load_button = b = QPushButton(_('&Load'), self)
326 self.load_menu = QMenu(self)
327 b.setMenu(self.load_menu)
328 b.setToolTip(_('Load a previously saved ruleset'))
329 b.clicked.connect(self.load_ruleset)
330 h.addWidget(b)
331 self.build_load_menu()
332
333 def export_rules(self):
334 rules = self.rules_widget.rules
335 if not rules:
336 return error_dialog(self, _('No rules'), _('There are no rules to export'), show=True)
337 path = choose_save_file(self, self.DIR_SAVE_NAME, _('Choose file for exported rules'), initial_filename=self.INITIAL_FILE_NAME)
338 if path:
339 f = self.__class__.export_func
340 raw = f(rules)
341 with open(path, 'wb') as f:
342 f.write(raw)
343
344 def import_rules(self):
345 paths = choose_files(self, self.DIR_SAVE_NAME, _('Choose file to import rules from'), select_only_single_file=True)
346 if paths:
347 func = self.__class__.import_func
348 with open(paths[0], 'rb') as f:
349 rules = func(f.read())
350 self.rules_widget.rules = list(rules) + list(self.rules_widget.rules)
351 self.changed.emit()
352
353 def load_ruleset(self, name):
354 SaveLoadMixin.load_ruleset(self, name)
355 self.changed.emit()
356
357 def test_rules(self):
358 self.TesterClass(self.rules_widget.rules, self).exec()
359
360 @property
361 def rules(self):
362 return self.rules_widget.rules
363
364 @rules.setter
365 def rules(self, val):
366 try:
367 self.rules_widget.rules = val or []
368 except Exception:
369 import traceback
370
371 traceback.print_exc()
372 self.rules_widget.rules = []
373
374
375 # }}}
376
377 if __name__ == '__main__':
378 from calibre.gui2 import Application
379
380 app = Application([])
381 d = RulesDialog()
382 d.rules = [
383 {'property': 'color', 'match_type': '*', 'query': '', 'action': 'change', 'action_data': 'green'},
384 ]
385 d.exec()
386 from pprint import pprint
387
388 pprint(d.rules)
389 del d, app