Templates/TemplateViewer.py

changeset 0
de9c2efb9d02
child 12
1d8dd9706f46
equal deleted inserted replaced
-1:000000000000 0:de9c2efb9d02
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2005 - 2009 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing a template viewer and associated classes.
8 """
9
10 import datetime
11 import os
12 import sys
13 import re
14 import cStringIO
15
16 from PyQt4.QtCore import *
17 from PyQt4.QtGui import *
18
19 from E4Gui.E4Application import e4App
20
21 from TemplatePropertiesDialog import TemplatePropertiesDialog
22 from TemplateMultipleVariablesDialog import TemplateMultipleVariablesDialog
23 from TemplateSingleVariableDialog import TemplateSingleVariableDialog
24
25 import Preferences
26
27 from E4XML.XMLUtilities import make_parser
28 from E4XML.XMLErrorHandler import XMLErrorHandler, XMLFatalParseError
29 from E4XML.XMLEntityResolver import XMLEntityResolver
30 from E4XML.TemplatesHandler import TemplatesHandler
31 from E4XML.TemplatesWriter import TemplatesWriter
32
33 import UI.PixmapCache
34 import Utilities
35
36 from E4Gui.E4Application import e4App
37
38 class TemplateGroup(QTreeWidgetItem):
39 """
40 Class implementing a template group.
41 """
42 def __init__(self, parent, name, language = "All"):
43 """
44 Constructor
45
46 @param parent parent widget of the template group (QWidget)
47 @param name name of the group (string)
48 @param language programming language for the group (string)
49 """
50 self.name = name
51 self.language = language
52 self.entries = {}
53
54 QTreeWidgetItem.__init__(self, parent, [name])
55
56 if Preferences.getTemplates("ShowTooltip"):
57 self.setToolTip(0, language)
58
59 def setName(self, name):
60 """
61 Public method to update the name of the group.
62
63 @param name name of the group (string)
64 """
65 self.name = name
66 self.setText(0, name)
67
68 def getName(self):
69 """
70 Public method to get the name of the group.
71
72 @return name of the group (string)
73 """
74 return self.name
75
76 def setLanguage(self, language):
77 """
78 Public method to update the name of the group.
79
80 @param language programming language for the group (string)
81 """
82 self.language = language
83 if Preferences.getTemplates("ShowTooltip"):
84 self.setToolTip(0, language)
85
86 def getLanguage(self):
87 """
88 Public method to get the name of the group.
89
90 @return language of the group (string)
91 """
92 return self.language
93
94 def addEntry(self, name, description, template, quiet = False):
95 """
96 Public method to add a template entry to this group.
97
98 @param name name of the entry (string)
99 @param description description of the entry to add (string)
100 @param template template text of the entry (string)
101 @param quiet flag indicating quiet operation (boolean)
102 """
103 if name in self.entries:
104 if not quiet:
105 QMessageBox.critical(None,
106 QApplication.translate("TemplateGroup", "Add Template"),
107 QApplication.translate("TemplateGroup",
108 """<p>The group <b>{0}</b> already contains a"""
109 """ template named <b>{1}</b>.</p>""")\
110 .format(self.name, name))
111 return
112
113 self.entries[name] = TemplateEntry(self, name, description, template)
114
115 if Preferences.getTemplates("AutoOpenGroups") and not self.isExpanded():
116 self.setExpanded(True)
117
118 def removeEntry(self, name):
119 """
120 Public method to remove a template entry from this group.
121
122 @param name name of the entry to be removed (string)
123 """
124 if name in self.entries:
125 index = self.indexOfChild(self.entries[name])
126 self.takeChild(index)
127 del self.entries[name]
128
129 if len(self.entries) == 0:
130 if Preferences.getTemplates("AutoOpenGroups") and self.isExpanded():
131 self.setExpanded(False)
132
133 def removeAllEntries(self):
134 """
135 Public method to remove all template entries of this group.
136 """
137 for name in self.entries.keys()[:]:
138 self.removeEntry(name)
139
140 def hasEntry(self, name):
141 """
142 Public method to check, if the group has an entry with the given name.
143
144 @param name name of the entry to check for (string)
145 @return flag indicating existence (boolean)
146 """
147 return name in self.entries
148
149 def getEntry(self, name):
150 """
151 Public method to get an entry.
152
153 @param name name of the entry to retrieve (string)
154 @return reference to the entry (TemplateEntry)
155 """
156 try:
157 return self.entries[name]
158 except KeyError:
159 return None
160
161 def getEntryNames(self, beginning):
162 """
163 Public method to get the names of all entries, who's name starts with the
164 given string.
165
166 @param beginning string denoting the beginning of the template name
167 (string)
168 @return list of entry names found (list of strings)
169 """
170 names = []
171 for name in self.entries:
172 if name.startswith(beginning):
173 names.append(name)
174
175 return names
176
177 def getAllEntries(self):
178 """
179 Public method to retrieve all entries.
180
181 @return list of all entries (list of TemplateEntry)
182 """
183 return self.entries.values()
184
185 class TemplateEntry(QTreeWidgetItem):
186 """
187 Class immplementing a template entry.
188 """
189 def __init__(self, parent, name, description, templateText):
190 """
191 Constructor
192
193 @param parent parent widget of the template entry (QWidget)
194 @param name name of the entry (string)
195 @param description descriptive text for the template (string)
196 @param templateText text of the template entry (string)
197 """
198 self.name = name
199 self.description = description
200 self.template = templateText
201 self.__extractVariables()
202
203 QTreeWidgetItem.__init__(self, parent, [self.__displayText()])
204 if Preferences.getTemplates("ShowTooltip"):
205 self.setToolTip(0, self.template)
206
207 def __displayText(self):
208 """
209 Private method to generate the display text.
210
211 @return display text (string)
212 """
213 if self.description:
214 txt = "{0} - {1}".format(self.name, self.description)
215 else:
216 txt = self.name
217 return txt
218
219 def setName(self, name):
220 """
221 Public method to update the name of the entry.
222
223 @param name name of the entry (string)
224 """
225 self.name = name
226 self.setText(0, self.__displayText())
227
228 def getName(self):
229 """
230 Public method to get the name of the entry.
231
232 @return name of the entry (string)
233 """
234 return self.name
235
236 def setDescription(self, description):
237 """
238 Public method to update the description of the entry.
239
240 @param description description of the entry (string)
241 """
242 self.description = description
243 self.setText(0, self.__displayText())
244
245 def getDescription(self):
246 """
247 Public method to get the description of the entry.
248
249 @return description of the entry (string)
250 """
251 return self.description
252
253 def getGroupName(self):
254 """
255 Public method to get the name of the group this entry belongs to.
256
257 @return name of the group containing this entry (string)
258 """
259 return self.parent().getName()
260
261 def setTemplateText(self, templateText):
262 """
263 Public method to update the template text.
264
265 @param templateText text of the template entry (string)
266 """
267 self.template = templateText
268 self.__extractVariables()
269 if Preferences.getTemplates("ShowTooltip"):
270 self.setToolTip(0, self.template)
271
272 def getTemplateText(self):
273 """
274 Public method to get the template text.
275
276 @return the template text (string)
277 """
278 return self.template
279
280 def getExpandedText(self, varDict, indent):
281 """
282 Public method to get the template text with all variables expanded.
283
284 @param varDict dictionary containing the texts of each variable
285 with the variable name as key.
286 @param indent indentation of the line receiving he expanded
287 template text (string)
288 @return a tuple of the expanded template text (string), the
289 number of lines (integer) and the length of the last line (integer)
290 """
291 txt = self.template
292 for var, val in varDict.items():
293 if var in self.formatedVariables:
294 txt = self.__expandFormattedVariable(var, val, txt)
295 else:
296 txt = txt.replace(var, val)
297 sepchar = Preferences.getTemplates("SeparatorChar")
298 txt = txt.replace("%s%s" % (sepchar, sepchar), sepchar)
299 prefix = "%s%s" % (os.linesep, indent)
300 trailingEol = txt.endswith(os.linesep)
301 lines = txt.splitlines()
302 lineCount = len(lines)
303 lineLen = len(lines[-1])
304 txt = prefix.join(lines).lstrip()
305 if trailingEol:
306 txt = "%s%s" % (txt, os.linesep)
307 lineCount += 1
308 lineLen = 0
309 return txt, lineCount, lineLen
310
311 def __expandFormattedVariable(self, var, val, txt):
312 """
313 Private method to expand a template variable with special formatting.
314
315 @param var template variable name (string)
316 @param val value of the template variable (string)
317 @param txt template text (string)
318 """
319 t = ""
320 for line in txt.splitlines():
321 ind = line.find(var)
322 if ind >= 0:
323 format = var[1:-1].split(':', 1)[1]
324 if format == 'rl':
325 prefix = line[:ind]
326 postfix = line [ind + len(var):]
327 for v in val.splitlines():
328 t = "%s%s%s%s%s" % (t, os.linesep, prefix, v, postfix)
329 elif format == 'ml':
330 indent = line.replace(line.lstrip(), "")
331 prefix = line[:ind]
332 postfix = line[ind + len(var):]
333 count = 0
334 for v in val.splitlines():
335 if count:
336 t = "%s%s%s%s" % (t, os.linesep, indent, v)
337 else:
338 t = "%s%s%s%s" % (t, os.linesep, prefix, v)
339 count += 1
340 t = "%s%s" % (t, postfix)
341 else:
342 t = "%s%s%s" % (t, os.linesep, line)
343 else:
344 t = "%s%s%s" % (t, os.linesep, line)
345 return "".join(t.splitlines(1)[1:])
346
347 def getVariables(self):
348 """
349 Public method to get the list of variables.
350
351 @return list of variables (list of strings)
352 """
353 return self.variables
354
355 def __extractVariables(self):
356 """
357 Private method to retrieve the list of variables.
358 """
359 sepchar = Preferences.getTemplates("SeparatorChar")
360 variablesPattern = \
361 re.compile(r"""\%s[a-zA-Z][a-zA-Z0-9_]*(?::(?:ml|rl))?\%s""" % \
362 (sepchar, sepchar))
363 variables = variablesPattern.findall(self.template)
364 self.variables = []
365 self.formatedVariables = []
366 for var in variables:
367 if not var in self.variables:
368 self.variables.append(var)
369 if var.find(':') >= 0 and not var in self.formatedVariables:
370 self.formatedVariables.append(var)
371
372 class TemplateViewer(QTreeWidget):
373 """
374 Class implementing the template viewer.
375 """
376 def __init__(self, parent, viewmanager):
377 """
378 Constructor
379
380 @param parent the parent (QWidget)
381 @param viewmanager reference to the viewmanager object
382 """
383 QTreeWidget.__init__(self, parent)
384
385 self.viewmanager = viewmanager
386 self.groups = {}
387
388 self.setHeaderLabels(["Template"])
389 self.header().hide()
390 self.header().setSortIndicator(0, Qt.AscendingOrder)
391 self.setRootIsDecorated(True)
392 self.setAlternatingRowColors(True)
393
394 self.__menu = QMenu(self)
395 self.applyAct = \
396 self.__menu.addAction(self.trUtf8("Apply"), self.__templateItemActivated)
397 self.__menu.addSeparator()
398 self.__menu.addAction(self.trUtf8("Add entry..."), self.__addEntry)
399 self.__menu.addAction(self.trUtf8("Add group..."), self.__addGroup)
400 self.__menu.addAction(self.trUtf8("Edit..."), self.__edit)
401 self.__menu.addAction(self.trUtf8("Remove"), self.__remove)
402 self.__menu.addSeparator()
403 self.__menu.addAction(self.trUtf8("Save"), self.__save)
404 self.__menu.addAction(self.trUtf8("Import..."), self.__import)
405 self.__menu.addAction(self.trUtf8("Export..."), self.__export)
406 self.__menu.addSeparator()
407 self.__menu.addAction(self.trUtf8("Help about Templates..."), self.__showHelp)
408 self.__menu.addSeparator()
409 self.__menu.addAction(self.trUtf8("Configure..."), self.__configure)
410
411 self.__backMenu = QMenu(self)
412 self.__backMenu.addAction(self.trUtf8("Add group..."), self.__addGroup)
413 self.__backMenu.addSeparator()
414 self.__backMenu.addAction(self.trUtf8("Save"), self.__save)
415 self.__backMenu.addAction(self.trUtf8("Import..."), self.__import)
416 self.__backMenu.addAction(self.trUtf8("Export..."), self.__export)
417 self.__backMenu.addSeparator()
418 self.__backMenu.addAction(self.trUtf8("Help about Templates..."), self.__showHelp)
419 self.__backMenu.addSeparator()
420 self.__backMenu.addAction(self.trUtf8("Configure..."), self.__configure)
421
422 self.setContextMenuPolicy(Qt.CustomContextMenu)
423 self.connect(self, SIGNAL("customContextMenuRequested(const QPoint &)"),
424 self.__showContextMenu)
425 self.connect(self, SIGNAL("itemActivated(QTreeWidgetItem *, int)"),
426 self.__templateItemActivated)
427
428 self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))
429
430 def __resort(self):
431 """
432 Private method to resort the tree.
433 """
434 self.sortItems(self.sortColumn(), self.header().sortIndicatorOrder())
435
436 def __templateItemActivated(self, itm = None, col = 0):
437 """
438 Private slot to handle the activation of an item.
439
440 @param itm reference to the activated item (QTreeWidgetItem)
441 @param col column the item was activated in (integer)
442 """
443 itm = self.currentItem()
444 if isinstance(itm, TemplateEntry):
445 self.applyTemplate(itm)
446
447 def __showContextMenu(self, coord):
448 """
449 Private slot to show the context menu of the list.
450
451 @param coord the position of the mouse pointer (QPoint)
452 """
453 itm = self.itemAt(coord)
454 coord = self.mapToGlobal(coord)
455 if itm is None:
456 self.__backMenu.popup(coord)
457 else:
458 self.applyAct.setEnabled(self.viewmanager.activeWindow() is not None)
459 self.__menu.popup(coord)
460
461 def __addEntry(self):
462 """
463 Private slot to handle the Add Entry context menu action.
464 """
465 itm = self.currentItem()
466 if isinstance(itm, TemplateGroup):
467 groupName = itm.getName()
468 else:
469 groupName = itm.getGroupName()
470
471 dlg = TemplatePropertiesDialog(self)
472 dlg.setSelectedGroup(groupName)
473 if dlg.exec_() == QDialog.Accepted:
474 name, description, groupName, template = dlg.getData()
475 self.addEntry(groupName, name, description, template)
476
477 def __addGroup(self):
478 """
479 Private slot to handle the Add Group context menu action.
480 """
481 dlg = TemplatePropertiesDialog(self, True)
482 if dlg.exec_() == QDialog.Accepted:
483 name, language = dlg.getData()
484 self.addGroup(name, language)
485
486 def __edit(self):
487 """
488 Private slot to handle the Edit context menu action.
489 """
490 itm = self.currentItem()
491 if isinstance(itm, TemplateEntry):
492 editGroup = False
493 else:
494 editGroup = True
495 dlg = TemplatePropertiesDialog(self, editGroup, itm)
496 if dlg.exec_() == QDialog.Accepted:
497 if editGroup:
498 name, language = dlg.getData()
499 self.changeGroup(itm.getName(), name, language)
500 else:
501 name, description, groupName, template = dlg.getData()
502 self.changeEntry(itm, name, groupName, description, template)
503
504 def __remove(self):
505 """
506 Private slot to handle the Remove context menu action.
507 """
508 itm = self.currentItem()
509 res = QMessageBox.question(self,
510 self.trUtf8("Remove Template"),
511 self.trUtf8("""<p>Do you really want to remove <b>{0}</b>?</p>""")\
512 .format(itm.getName()),
513 QMessageBox.StandardButtons(\
514 QMessageBox.No | \
515 QMessageBox.Yes),
516 QMessageBox.No)
517 if res != QMessageBox.Yes:
518 return
519
520 if isinstance(itm, TemplateGroup):
521 self.removeGroup(itm)
522 else:
523 self.removeEntry(itm)
524
525 def __save(self):
526 """
527 Private slot to handle the Save context menu action.
528 """
529 self.writeTemplates()
530
531 def __import(self):
532 """
533 Private slot to handle the Import context menu action.
534 """
535 fn = QFileDialog.getOpenFileName(\
536 self,
537 self.trUtf8("Import Templates"),
538 "",
539 self.trUtf8("Templates Files (*.e3c *.e4c);; All Files (*)"))
540
541 if fn:
542 self.readTemplates(fn)
543
544 def __export(self):
545 """
546 Private slot to handle the Export context menu action.
547 """
548 fn, selectedFilter = QFileDialog.getSaveFileNameAndFilter(\
549 self,
550 self.trUtf8("Export Templates"),
551 "",
552 self.trUtf8("Templates Files (*.e4c);; All Files (*)"),
553 "",
554 QFileDialog.Options(QFileDialog.DontConfirmOverwrite))
555
556 if fn:
557 ext = QFileInfo(fn).suffix()
558 if not ext:
559 ex = selectedFilter.split("(*")[1].split(")")[0]
560 if ex:
561 fn += ex
562 self.writeTemplates(fn)
563
564 def __showHelp(self):
565 """
566 Private method to show some help.
567 """
568 QMessageBox.information(self,
569 self.trUtf8("Template Help"),
570 self.trUtf8("""<p><b>Template groups</b> are a means of grouping individual"""
571 """ templates. Groups have an attribute that specifies,"""
572 """ which programming language they apply for."""
573 """ In order to add template entries, at least one group"""
574 """ has to be defined.</p>"""
575 """<p><b>Template entries</b> are the actual templates."""
576 """ They are grouped by the template groups. Help about"""
577 """ how to define them is available in the template edit"""
578 """ dialog. There is an example template available in the"""
579 """ Examples subdirectory of the eric4 distribution.</p>"""))
580
581 def __getPredefinedVars(self):
582 """
583 Private method to return predefined variables.
584
585 @return dictionary of predefined variables and their values
586 """
587 project = e4App().getObject("Project")
588 editor = self.viewmanager.activeWindow()
589 today = datetime.datetime.now().date()
590 sepchar = Preferences.getTemplates("SeparatorChar")
591 if sepchar == '%':
592 sepchar = '%%'
593 keyfmt = sepchar + "%s" + sepchar
594 varValues = {keyfmt % 'date': today.isoformat(),
595 keyfmt % 'year': str(today.year)}
596
597 if project.name:
598 varValues[keyfmt % 'project_name'] = project.name
599
600 path_name = editor.getFileName()
601 if path_name:
602 dir_name, file_name = os.path.split(path_name)
603 base_name, ext = os.path.splitext(file_name)
604 if ext:
605 ext = ext[1:]
606 varValues.update({
607 keyfmt % 'path_name': path_name,
608 keyfmt % 'dir_name': dir_name,
609 keyfmt % 'file_name': file_name,
610 keyfmt % 'base_name': base_name,
611 keyfmt % 'ext': ext
612 })
613 return varValues
614
615 def applyTemplate(self, itm):
616 """
617 Public method to apply the template.
618
619 @param itm reference to the template item to apply (TemplateEntry)
620 """
621 editor = self.viewmanager.activeWindow()
622 if editor is None:
623 return
624
625 ok = False
626 vars = itm.getVariables()
627 varValues = self.__getPredefinedVars()
628
629 # Remove predefined variables from list so user doesn't have to fill
630 # these values out in the dialog.
631 for v in varValues.keys():
632 if v in vars:
633 vars.remove(v)
634
635 if vars:
636 if Preferences.getTemplates("SingleDialog"):
637 dlg = TemplateMultipleVariablesDialog(vars, self)
638 if dlg.exec_() == QDialog.Accepted:
639 varValues.update(dlg.getVariables())
640 ok = True
641 else:
642 for var in vars:
643 dlg = TemplateSingleVariableDialog(var, self)
644 if dlg.exec_() == QDialog.Accepted:
645 varValues[var] = dlg.getVariable()
646 else:
647 return
648 del dlg
649 ok = True
650 else:
651 ok = True
652
653 if ok:
654 line = editor.text(editor.getCursorPosition()[0])\
655 .replace(os.linesep, "")
656 indent = line.replace(line.lstrip(), "")
657 txt, lines, count = itm.getExpandedText(varValues, indent)
658 # It should be done in this way to allow undo
659 editor.beginUndoAction()
660 if editor.hasSelectedText():
661 editor.removeSelectedText()
662 line, index = editor.getCursorPosition()
663 editor.insert(txt)
664 editor.setCursorPosition(line + lines - 1,
665 count and index + count or 0)
666 editor.endUndoAction()
667 editor.setFocus()
668
669 def applyNamedTemplate(self, templateName):
670 """
671 Public method to apply a template given a template name.
672
673 @param templateName name of the template item to apply (string)
674 """
675 for group in self.groups.values():
676 template = group.getEntry(templateName)
677 if template is not None:
678 self.applyTemplate(template)
679 break
680
681 def addEntry(self, groupName, name, description, template, quiet = False):
682 """
683 Public method to add a template entry.
684
685 @param groupName name of the group to add to (string)
686 @param name name of the entry to add (string)
687 @param description description of the entry to add (string)
688 @param template template text of the entry (string)
689 @param quiet flag indicating quiet operation (boolean)
690 """
691 self.groups[groupName].addEntry(name, description, template, quiet = quiet)
692 self.__resort()
693
694 def addGroup(self, name, language = "All"):
695 """
696 Public method to add a group.
697
698 @param name name of the group to be added (string)
699 @param language programming language for the group (string)
700 """
701 if name not in self.groups:
702 self.groups[name] = TemplateGroup(self, name, language)
703 self.__resort()
704
705 def changeGroup(self, oldname, newname, language = "All"):
706 """
707 Public method to rename a group.
708
709 @param oldname old name of the group (string)
710 @param newname new name of the group (string)
711 @param language programming language for the group (string)
712 """
713 if oldname != newname:
714 if newname in self.groups:
715 QMessageBox.warning(self,
716 self.trUtf8("Edit Template Group"),
717 self.trUtf8("""<p>A template group with the name"""
718 """ <b>{0}</b> already exists.</p>""")\
719 .format(newname))
720 return
721
722 self.groups[newname] = self.groups[oldname]
723 del self.groups[oldname]
724 self.groups[newname].setName(newname)
725
726 self.groups[newname].setLanguage(language)
727 self.__resort()
728
729 def getAllGroups(self):
730 """
731 Public method to get all groups.
732
733 @return list of all groups (list of TemplateGroup)
734 """
735 return self.groups.values()
736
737 def getGroupNames(self):
738 """
739 Public method to get all group names.
740
741 @return list of all group names (list of strings)
742 """
743 groups = sorted(self.groups.keys()[:])
744 return groups
745
746 def removeGroup(self, itm):
747 """
748 Public method to remove a group.
749
750 @param itm template group to be removed (TemplateGroup)
751 """
752 name = itm.getName()
753 itm.removeAllEntries()
754 index = self.indexOfTopLevelItem(itm)
755 self.takeTopLevelItem(index)
756 del self.groups[name]
757
758 def removeEntry(self, itm):
759 """
760 Public method to remove a template entry.
761
762 @param itm template entry to be removed (TemplateEntry)
763 """
764 groupName = itm.getGroupName()
765 self.groups[groupName].removeEntry(itm.getName())
766
767 def changeEntry(self, itm, name, groupName, description, template):
768 """
769 Public method to change a template entry.
770
771 @param itm template entry to be changed (TemplateEntry)
772 @param name new name for the entry (string)
773 @param groupName name of the group the entry should belong to
774 (string)
775 @param description description of the entry (string)
776 @param template template text of the entry (string)
777 """
778 if itm.getGroupName() != groupName:
779 # move entry to another group
780 self.groups[itm.getGroupName()].removeEntry(itm.getName())
781 self.groups[groupName].addEntry(name, description, template)
782 return
783
784 if itm.getName() != name:
785 # entry was renamed
786 self.groups[groupName].removeEntry(itm.getName())
787 self.groups[groupName].addEntry(name, description, template)
788 return
789
790 tmpl = self.groups[groupName].getEntry(name)
791 tmpl.setDescription(description)
792 tmpl.setTemplateText(template)
793 self.__resort()
794
795 def writeTemplates(self, filename = None):
796 """
797 Public method to write the templates data to an XML file (.e4c).
798
799 @param filename name of a templates file to read (string)
800 """
801 try:
802 if filename is None:
803 filename = os.path.join(Utilities.getConfigDir(), "eric4templates.e4c")
804 f = open(filename, "wb")
805
806 TemplatesWriter(f, self).writeXML()
807
808 f.close()
809 except IOError:
810 QMessageBox.critical(None,
811 self.trUtf8("Save templates"),
812 self.trUtf8("<p>The templates file <b>{0}</b> could not be written.</p>")
813 .format(filename))
814
815 def readTemplates(self, filename = None):
816 """
817 Public method to read in the templates file (.e4c)
818
819 @param filename name of a templates file to read (string)
820 """
821 try:
822 if filename is None:
823 filename = os.path.join(Utilities.getConfigDir(), "eric4templates.e4c")
824 if not os.path.exists(filename):
825 return
826 f = open(filename, "rb")
827 line = f.readline()
828 dtdLine = f.readline()
829 f.close()
830 except IOError:
831 QMessageBox.critical(None,
832 self.trUtf8("Read templates"),
833 self.trUtf8("<p>The templates file <b>{0}</b> could not be read.</p>")
834 .format(filename))
835 return
836
837 # now read the file
838 if line.startswith('<?xml'):
839 parser = make_parser(dtdLine.startswith("<!DOCTYPE"))
840 handler = TemplatesHandler(templateViewer = self)
841 er = XMLEntityResolver()
842 eh = XMLErrorHandler()
843
844 parser.setContentHandler(handler)
845 parser.setEntityResolver(er)
846 parser.setErrorHandler(eh)
847
848 try:
849 f = open(filename, "rb")
850 try:
851 try:
852 parser.parse(f)
853 except UnicodeEncodeError:
854 f.seek(0)
855 buf = cStringIO.StringIO(f.read())
856 parser.parse(buf)
857 finally:
858 f.close()
859 except IOError:
860 QMessageBox.critical(None,
861 self.trUtf8("Read templates"),
862 self.trUtf8("<p>The templates file <b>{0}</b> could not be read.</p>")
863 .format(filename))
864 return
865 except XMLFatalParseError:
866 pass
867
868 eh.showParseMessages()
869 else:
870 QMessageBox.critical(None,
871 self.trUtf8("Read templates"),
872 self.trUtf8("<p>The templates file <b>{0}</b> has an"
873 " unsupported format.</p>")
874 .format(filename))
875
876 def __configure(self):
877 """
878 Private method to open the configuration dialog.
879 """
880 e4App().getObject("UserInterface").showPreferences("templatesPage")
881
882 def hasTemplate(self, entryName):
883 """
884 Public method to check, if an entry of the given name exists.
885
886 @param entryName name of the entry to check for (string)
887 @return flag indicating the existence (boolean)
888 """
889 for group in self.groups.values():
890 if group.hasEntry(entryName):
891 return True
892
893 return False
894
895 def getTemplateNames(self, start):
896 """
897 Public method to get the names of templates starting with the given string.
898
899 @param start start string of the name (string)
900 @return sorted list of matching template names (list of strings)
901 """
902 names = []
903 for group in self.groups.values():
904 names.extend(group.getEntryNames(start))
905 return sorted(names)

eric ide

mercurial