File: ZopeViews.py

package info (click to toggle)
boa-constructor 0.4.4cvs20050714-4
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 10,080 kB
  • ctags: 9,175
  • sloc: python: 56,189; sh: 545; makefile: 40
file content (304 lines) | stat: -rw-r--r-- 11,415 bytes parent folder | download
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#-----------------------------------------------------------------------------
# Name:        ZopeViews.py
# Purpose:     Custom views for Zope models
#
# Author:      Riaan Booysen
#
# Created:     2001
# RCS-ID:      $Id: ZopeViews.py,v 1.11 2005/05/18 12:50:20 riaan Exp $
# Copyright:   (c) 2001 - 2005
# Licence:     GPL
#-----------------------------------------------------------------------------
print 'importing ZopeLib.ZopeViews'

import os, time

import wx

from Views.EditorViews import HTMLView, ListCtrlView
from Views.SourceViews import EditorStyledTextCtrl
from Views.StyledTextCtrls import DebuggingViewSTCMix
from Models.HTMLSupport import BaseHTMLStyledTextCtrlMix

import Utils, ErrorStack

from ExternalLib import xmlrpclib

# Can be extended by plug-ins, used by syntax highlighted styles
zope_additional_attributes = ''

# XXX This is expensive and will really need to delay generatePage until View
# XXX is focused (like ExploreView)
# XXX The HTML control does not interact well with Zope.

class ZopeHTMLStyledTextCtrlMix(BaseHTMLStyledTextCtrlMix):
    def __init__(self, wId):
        BaseHTMLStyledTextCtrlMix.__init__(self, wId)

        zope_dtml_elements = 'dtml-var dtml-in dtml-if dtml-elif dtml-else dtml-unless '\
        'dtml-with dtml-let dtml-call dtml-comment dtml-tree dtml-try dtml-except '\
        'dtml-raise dtml-finally dtml-sqlvar '

        zope_zsql_tags = 'params '

        zope_attributes=\
        'sequence-key sequence-item sequence-start sequence-end sequence-odd '

        self.keywords = self.keywords + ' public !doctype '+ zope_dtml_elements +\
              zope_zsql_tags + zope_attributes + zope_additional_attributes

        self.setStyles()

class ZopeHTMLSourceView(EditorStyledTextCtrl, ZopeHTMLStyledTextCtrlMix):
    viewName = 'ZopeHTML'
    breakBmp = 'Images/Debug/Breakpoints.png'
    defaultEOL = '\n'
    def __init__(self, parent, model, actions=()):
        wxID_ZOPEHTMLSOURCEVIEW = wx.NewId()
        EditorStyledTextCtrl.__init__(self, parent, wxID_ZOPEHTMLSOURCEVIEW,
          model, (('Refresh', self.OnRefresh, '-', 'Refresh'),) + actions, -1)
        ZopeHTMLStyledTextCtrlMix.__init__(self, wxID_ZOPEHTMLSOURCEVIEW)
        self.active = True

class ZopeDebugHTMLSourceView(ZopeHTMLSourceView, DebuggingViewSTCMix):
    breakBmp = 'Images/Debug/Breakpoints.png'
    defaultEOL = '\n'
    def __init__(self, parent, model, actions=()):
        ZopeHTMLSourceView.__init__(self, parent, model,
      (('Toggle breakpoint', self.OnSetBreakPoint, self.breakBmp, 'ToggleBrk'),)
        )

        from Views.PySourceView import brkPtMrk, tmpBrkPtMrk, disabledBrkPtMrk, \
                                       stepPosMrk, symbolMrg
        DebuggingViewSTCMix.__init__(self, (brkPtMrk, tmpBrkPtMrk,
              disabledBrkPtMrk, stepPosMrk))
        self.setupDebuggingMargin(symbolMrg)

        self.active = True

    def OnMarginClick(self, event):
        DebuggingViewSTCMix.OnMarginClick(self, event)

    def refreshCtrl(self):
        ZopeHTMLSourceView.refreshCtrl(self)
        self.setInitialBreakpoints()

class ZopeHTMLView(HTMLView):
    viewName = 'View'
    def generatePage(self):
        import urllib
        url = 'http://%s:%d/%s'%(self.model.transport.properties['host'],
              self.model.transport.properties['httpport'],
              self.model.transport.whole_name())
        f = urllib.urlopen(url)
        s = f.read()
        return s

class ZopeUndoView(ListCtrlView):
    viewName = 'Undo'
    undoBmp = 'Images/Shared/Undo.png'

    def __init__(self, parent, model):
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT,
          (('Undo', self.OnUndo, self.undoBmp, ''),), -1)
        self.addReportColumns( (('Action', 300), ('User', 75), ('Date', 130)) )

        self.active = True

        self.undoIds = []

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)

        try:
            undos = self.model.transport.getUndoableTransactions()
        except xmlrpclib.Fault, error:
            wx.LogError(Utils.html2txt(error.faultString))
        else:
            i = 0
            self.undoIds = []
            for undo in undos:
                self.addReportItems(i, (undo['description'], undo['user_name'], str(undo['time'])) )
                self.undoIds.append(undo['id'])
                i = i + 1

            self.pastelise()

    def OnUndo(self, event):
        if self.selected != -1:
            try:
                self.model.transport.undoTransaction([self.undoIds[self.selected]])
            except xmlrpclib.Fault, error:
                wx.LogError(Utils.html2txt(error.faultString))
            except xmlrpclib.ProtocolError, error:
                if error.errmsg == 'Moved Temporarily':
                    # This is actually a successful move
                    self.refreshCtrl()
                else:
                    wx.LogError(Utils.html2txt(error.errmsg))
            else:
                self.refreshCtrl()

class ZopeSecurityView(ListCtrlView):
    viewName = 'Security'
    undoBmp = 'Images/Shared/Undo.png'

    def __init__(self, parent, model):
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT,
          (('Edit', self.OnEdit, self.undoBmp, ''),), -1)
        self.active = True

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)

        perms = self.model.transport.getPermissions()
        roles = self.model.transport.getRoles()

        colls = [('Acquired', 40), ('Permission', 275)]
        for role in roles:
            colls.append( (role, 75) )

        self.addReportColumns( colls )

        i = 0
        for perm in perms:
            self.addReportItems(*(i, ((perm['acquire'] == 'CHECKED' and '*' or '',
                  perm['name']) + tuple(map( lambda x: x['checked'] == 'CHECKED' and '*' or '',
                  perm['roles'])) )))
            i = i + 1

        self.pastelise()

    def OnEdit(self, event):
        if self.selected != -1:
            pass

class ZopeSiteErrorLogParser(ErrorStack.StackErrorParser):
    def __init__(self, lines, libPath, baseUrl):
        self.libPath = libPath
        self.baseUrl = baseUrl
        ErrorStack.StackErrorParser.__init__(self, lines)

    def parse(self):
        error = None
        lines = self.lines[:]
        while lines:
            line = lines.pop()
            if line.startswith('  Module '):
                modPath, lineNo, funcName = line[9:].split(', ')
                lineNo = int(lineNo[5:])
                modPath = modPath.strip()
                if modPath == 'Script (Python)':
                    path = lines.pop()
                    lines.pop()
                    if path.startswith('   - <PythonScript at '):
                        path = path[22:].strip()[:-1]
                        debugUrl = self.baseUrl+path+'/Script (Python)'
                        self.stack.append(
                              ErrorStack.StackEntry(debugUrl, lineNo+1, funcName))
                elif modPath.startswith('Python expression'):
                    continue
                else:
                    modPath = self.libPath+'/'+modPath.replace('.', '/')+'.py'
                    self.stack.append(ErrorStack.StackEntry(modPath, lineNo, funcName))
            elif line.startswith('   - <PythonScript at '):
                path = line[22:].strip()[:-1]
                debugUrl = self.baseUrl+path+'/Script (Python)'
                self.stack.append(
                      ErrorStack.StackEntry(debugUrl, 0, os.path.basename(path)))
            elif line.startswith('   - <ZopePageTemplate at '):
                path = line[26:].strip()[:-1]
                debugUrl = self.baseUrl+path+'/Page Template'
                self.stack.append(ErrorStack.StackEntry(debugUrl, 0,
                      os.path.basename(path)))
            elif line.startswith('   - URL: '):
                path = line[10:].strip()
                lineNo, colNo = lines.pop().split(', ')
                lineNo = int(lineNo.split()[-1])
                debugUrl = self.baseUrl+path+'/Page Template'
                self.stack.append(ErrorStack.StackEntry(debugUrl, lineNo,
                      os.path.basename(path)))
            elif line and line[0] != ' ':
                errType, errValue = line.split(': ', 1)
                lines.reverse()
                errValue = (errValue + ' '.join(lines)).strip()
                if errValue and errValue[0] == '<':
                    errValue = Utils.html2txt(errValue).replace('\n', ' ')

                error = [errType, errValue]
                break

        assert error
        self.error = error
        for entry in self.stack:
            entry.error = error


class ZopeSiteErrorLogView(ListCtrlView):
    viewName = 'Site Error Log'
    gotoTracebackBmp = 'Images/Shared/Traceback.png'
    refreshBmp = 'Images/Editor/Refresh.png'

    def __init__(self, parent, model):
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT,
          (('Open traceback', self.OnOpen, self.gotoTracebackBmp, ''),
           ('Refresh', self.OnRefresh, self.refreshBmp, 'Refresh')), 0)
        self.active = True

    logEntryIds = []
    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)

        errLogNode = self.model.transport

        try:
            entries = errLogNode.getResource().getLogEntries()
        except xmlrpclib.Fault, error:
            wx.LogError(Utils.html2txt(error.faultString))
        else:

            cols = [('Time', 150), ('User', 100), ('Type', 80),
                    ('Value', 200), ('Request URL', 350)]
            self.addReportColumns(cols)

            i = 0
            self.logEntryIds = []
            for entry in entries:
                value = entry['value']
                # pretty print html errors
                if value and value[0] == '<':
                    value = Utils.html2txt(value).replace('\n', ' ').strip()
                self.addReportItems(i, (time.ctime(entry['time']),
                      entry['username'], entry['type'], value, entry['url']) )
                self.logEntryIds.append(entry['id'])
                i = i + 1

            self.pastelise()

    def OnOpen(self, event):
        if self.selected != -1:
            logId = self.logEntryIds[self.selected]
            errLogNode = self.model.transport
            try:
                textEntry = errLogNode.getResource().getLogEntryAsText(logId)
            except xmlrpclib.Fault, error:
                wx.LogError(Utils.html2txt(error.faultString))
            else:
                lines = textEntry.split('\n')
                lines.reverse()
                top = lines.pop().strip()
                assert top == 'Traceback (innermost last):'

                props = errLogNode.properties
                libPath = props['localpath'] +'/lib/python'
                # zopedebug urls are transparently looked up in the zope
                # connections list when the transport is opened.
                baseUrl = 'zopedebug://%s:%s/'%(props['host'], props['httpport'])
                errStack = ZopeSiteErrorLogParser(lines, libPath, baseUrl)

                erroutFrm = self.model.editor.erroutFrm
                erroutFrm.updateCtrls([errStack], '', 'Error', libPath, textEntry)
                erroutFrm.display()

    def OnRefresh(self, event):
        self.refreshCtrl()