File: template.py

package info (click to toggle)
wxglade 1%3A1.1.1%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,592 kB
  • sloc: python: 30,644; javascript: 740; makefile: 169; cpp: 99; perl: 90; lisp: 62; xml: 61; sh: 3
file content (212 lines) | stat: -rw-r--r-- 7,652 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
"""
Handles the template tags and description

@copyright: 2002-2007 Alberto Griggio
@author: Guy Rutenberg
@author: Alberto Griggio
@copyright: 2016 Carsten Grohmann
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""

import glob
import logging
import os
import wx
from xml.dom import minidom
from xml.sax import saxutils

import common
import config
import misc
import templates_ui


class Template(object):
    "A class that handles the specific aspects of template files"

    def __init__(self, filename=None):
        self.author = ''
        self.description = ''
        self.instructions = ''
        self.filename = filename

        if filename is not None:
            filexml = minidom.parse(filename)
            # we have no use for all the xml data in the file. We only care
            # about what is between the "description" tags
            templatedata = filexml.getElementsByTagName('templatedata')
            if len(templatedata):
                desc_xml = templatedata[0]
                try:
                    self.author = saxutils.unescape( desc_xml.getElementsByTagName('author')[0].firstChild.data )
                except (IndexError, AttributeError): self.author = ''
                try:
                    self.description = saxutils.unescape(
                        desc_xml.getElementsByTagName('description')[0].firstChild.data )
                except (IndexError, AttributeError): self.description = ''
                try:
                    self.instructions = saxutils.unescape(
                        desc_xml.getElementsByTagName( 'instructions')[0].firstChild.data)
                except (IndexError, AttributeError): self.instructions = ''
            else:
                self.author = ''
                self.description=''
                self.instructions=''

    def write(self, output, tabs):
        outer_tab = u'    ' * tabs
        stmt = [u'%s<templatedata>\n' % outer_tab]
        stmt += common.format_xml_tag(u'author', self.author, tabs + 1)
        stmt += common.format_xml_tag(u'description', self.description, tabs + 1)
        stmt += common.format_xml_tag(u'instructions', self.instructions, tabs + 1)
        stmt.append( u'%s</templatedata>\n' % outer_tab )
        output.extend(stmt)



class TemplateListDialog(templates_ui.TemplateListDialog):
    """\
    Class TemplateListDialog

    @ivar _logger: Class specific logging instance
    """

    def __init__(self):
        templates_ui.TemplateListDialog.__init__(self, None, -1, "")
        self.templates = []
        self.fill_template_list()
        self.selected_template = None

    def get_selected(self):
        index = self.template_names.GetSelection()
        if index >= 0:
            return self.templates[index]
        else:
            return None

    def on_open(self, event):
        self.selected_template = self.get_selected()
        self.EndModal(wx.ID_OPEN)

    def on_select_template(self, event):
        self.selected_template = self.get_selected()
        if self.selected_template is not None:
            t = Template(self.selected_template)
            self.set_template_name(self.template_names.GetStringSelection())
            self.author.SetValue(misc.wxstr(t.author))
            self.description.SetValue(misc.wxstr(t.description))
            self.instructions.SetValue(misc.wxstr(t.instructions))
            if os.path.dirname(self.selected_template) == config.templates_path:
                self.btn_delete.Disable()
                self.btn_edit.Disable()
            else:
                self.btn_delete.Enable()
                self.btn_edit.Enable()
        else:
            self.set_template_name("")
            self.author.SetValue("")
            self.description.SetValue("")
            self.instructions.SetValue("")
        if event:
            event.Skip()

    def set_template_name(self, name):
        self.template_name.SetLabel(_("wxGlade template:\n") + misc.wxstr(name))

    def on_edit(self, event):
        self.selected_template = self.get_selected()
        self.EndModal(wx.ID_EDIT)

    def on_delete(self, event):
        self.selected_template = self.get_selected()
        if self.selected_template is not None:
            name = self.template_names.GetStringSelection()
            if wx.MessageBox( _("Delete template '%s'?") % misc.wxstr(name),
                              _("Are you sure?"), style=wx.YES|wx.NO|wx.CENTRE) == wx.YES:
                try:
                    os.unlink(self.selected_template)
                except Exception:
                    logging.exception(_('Internal Error'))
                self.fill_template_list()
                self.selected_template = None

    def fill_template_list(self):
        self.templates = load_templates()
        self.template_names.Clear()
        if self.templates:
            for n in self.templates:
                self.template_names.Append( os.path.splitext(os.path.basename(n))[0] )
                # show details of first template
                self.template_names.SetSelection(0)
                self.on_select_template(None)

# end of class TemplateListDialog


def load_templates():
    "Finds all the available templates"
    if config.appdata_path != config.wxglade_path:
        extra = glob.glob( os.path.join(config.appdata_path, "templates", "*.wgt") )
    else:
        extra = []
    return sorted(glob.glob(os.path.join(config.templates_path, "*.wgt"))) + sorted(extra)


def select_template():
    "Returns the filename of a template to load"
    dlg = TemplateListDialog()
    dlg.btn_delete.Hide()
    dlg.btn_edit.Hide()
    if dlg.ShowModal() == wx.ID_OPEN:
        ret = dlg.selected_template
    else:
        ret = None
    dlg.Destroy()
    return ret


def save_template(data=None):
    "Returns an out file name and template description for saving a template"
    dlg = templates_ui.TemplateInfoDialog(None, -1, "")
    if data is not None:
        dlg.template_name.SetValue( misc.wxstr(os.path.basename(os.path.splitext(data.filename)[0])) )
        dlg.author.SetValue(misc.wxstr(data.author))
        dlg.description.SetValue(misc.wxstr(data.description))
        dlg.instructions.SetValue(misc.wxstr(data.instructions))
    ret = None
    retdata = Template()
    if dlg.ShowModal() == wx.ID_OK:
        ret = dlg.template_name.GetValue().strip()
        retdata.author = dlg.author.GetValue()
        retdata.description = dlg.description.GetValue()
        retdata.instructions = dlg.instructions.GetValue()
        if not ret:
            wx.MessageBox( _("Can't save a template with an empty name"), _("Error"), wx.OK|wx.ICON_ERROR )
    dlg.Destroy()
    name = ret
    if ret:
        template_directory = os.path.join(config.appdata_path, 'templates')
        if not os.path.exists(template_directory):
            try:
                os.makedirs(template_directory)
            except EnvironmentError:
                logging.exception( _('ERROR creating directory "%s"'), template_directory )
                return None, retdata
        ret = os.path.join(template_directory, ret + '.wgt')
    if ret and os.path.exists(ret) and \
       wx.MessageBox( _("A template called '%s' already exists:\ndo you want to overwrite it?") % name,
                      _("Question"), wx.YES|wx.NO|wx.ICON_QUESTION) != wx.YES:
        ret = None
    return ret, retdata


def manage_templates():
    dlg = TemplateListDialog()
    dlg.btn_open.Hide()
    #dlg.btn_edit.Hide()
    ret = None
    if dlg.ShowModal() == templates_ui.ID_EDIT:
        ret = dlg.selected_template
    dlg.Destroy()
    return ret