File: python.py

package info (click to toggle)
pida 0.5.1-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 5,048 kB
  • ctags: 8,108
  • sloc: python: 39,653; ansic: 4,850; xml: 2,060; sh: 183; makefile: 152
file content (452 lines) | stat: -rw-r--r-- 14,152 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# -*- coding: utf-8 -*- 

# Copyright (c) 2007 The PIDA Project

#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

# stdlib
import sys, compiler

# gtk
import gtk

# kiwi
from kiwi.ui.objectlist import ObjectList, Column

# PIDA Imports

# core
from pida.core.service import Service
from pida.core.events import EventsConfig
from pida.core.actions import ActionsConfig, TYPE_NORMAL, TYPE_TOGGLE
from pida.core.options import OptionsConfig, OTypeString
from pida.core.features import FeaturesConfig
from pida.core.projects import ProjectController,  ProjectKeyDefinition
from pida.core.interfaces import IProjectController

# ui
from pida.ui.views import PidaView, PidaGladeView
from pida.ui.objectlist import AttrSortCombo

# utils
from pida.utils import pyflakes
from pida.utils import pythonparser
from pida.utils.gthreads import AsyncTask, GeneratorTask

# locale
from pida.core.locale import Locale
locale = Locale('python')
_ = locale.gettext

### Pyflakes

class PyflakeView(PidaView):
    
    icon_name = 'python-icon'
    label_text = _('Python Errors')

    def create_ui(self):
        self.errors_ol = ObjectList(
            Column('markup', use_markup=True)
        )
        self.errors_ol.set_headers_visible(False)
        self.errors_ol.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.add_main_widget(self.errors_ol)
        self.errors_ol.connect('double-click', self._on_errors_double_clicked)
        self.errors_ol.show_all()
        self.sort_combo = AttrSortCombo(
            self.errors_ol,
            [
                ('lineno', _('Line Number')),
                ('message_string', _('Message')),
                ('name', _('Type')),
            ],
            'lineno',
        )
        self.sort_combo.show()
        self.add_main_widget(self.sort_combo, expand=False)

    def clear_items(self):
        self.errors_ol.clear()

    def set_items(self, items):
        self.clear_items()
        for item in items:
            self.errors_ol.append(self.decorate_pyflake_message(item))

    def decorate_pyflake_message(self, msg):
        args = [('<b>%s</b>' % arg) for arg in msg.message_args]
        msg.message_string = msg.message % tuple(args)
        msg.name = msg.__class__.__name__
        msg.markup = ('<tt>%s </tt><i>%s</i>\n%s' % 
                      (msg.lineno, msg.name, msg.message_string))
        return msg

    def _on_errors_double_clicked(self, ol, item):
        self.svc.boss.editor.cmd('goto_line', line=item.lineno)

    def can_be_closed(self):
        self.svc.get_action('show_python_errors').set_active(False)


class Pyflaker(object):

    def __init__(self, svc):
        self.svc = svc
        self._view = PyflakeView(self.svc)
        self.set_current_document(None)

    def set_current_document(self, document):
        self._current = document
        if self._current is not None:
            self.refresh_view()
            self._view.get_toplevel().set_sensitive(True)
        else:
            self.set_view_items([])
            self._view.get_toplevel().set_sensitive(False)

    def refresh_view(self):
        if self.svc.is_current_python():
            task = AsyncTask(self.check_current, self.set_view_items)
            task.start()
        else:
            self._view.clear_items()

    def check_current(self):
        return self.check(self._current)

    def check(self, document):
        code_string = document.string
        filename = document.filename
        try:
            tree = compiler.parse(code_string)
        except (SyntaxError, IndentationError), e:
            msg = e
            msg.name = e.__class__.__name__
            value = sys.exc_info()[1]
            (lineno, offset, line) = value[1][1:]
            if line.endswith("\n"):
                line = line[:-1]
            msg.lineno = lineno
            msg.message_args = (line,)
            msg.message = '<tt>%%s</tt>\n<tt>%s^</tt>' % (' ' * (offset - 2))
            return [msg]
        else:
            w = pyflakes.Checker(tree, filename)
            return w.messages

    def set_view_items(self, items):
        self._view.set_items(items)

    def get_view(self):
        return self._view


class SourceView(PidaGladeView):

    gladefile = 'python-source-browser'
    locale = locale
    icon_name = 'python-icon'
    label_text = _('Source')

    def create_ui(self):
        self.source_tree.set_columns(
            [
                Column('linenumber'),
                Column('ctype_markup', use_markup=True),
                Column('nodename_markup', use_markup=True),
            ]
        )
        self.source_tree.set_headers_visible(False)
        self.sort_box = AttrSortCombo(
            self.source_tree,
            [
                ('linenumber', _('Line Number')),
                ('nodename', _('Name')),
                ('nodetype', _('Type')),
            ],
            'linenumber'
        )
        self.sort_box.show()
        self.main_vbox.pack_start(self.sort_box, expand=False)

    def clear_items(self):
        self.source_tree.clear()

    def add_node(self, node, parent):
        self.source_tree.append(parent, node)

    def can_be_closed(self):
        self.svc.get_action('show_python_source').set_active(False)

    def on_source_tree__double_click(self, tv, item):
        self.svc.boss.editor.cmd('goto_line', line=item.linenumber)


class PythonBrowser(object):

    def __init__(self, svc):
        self.svc = svc
        self._view = SourceView(self.svc)
        self.set_current_document(None)

    def set_current_document(self, document):
        self._current = document
        if self._current is not None:
            self.refresh_view()
            self._view.get_toplevel().set_sensitive(True)
        else:
            self._view.clear_items()
            self._view.get_toplevel().set_sensitive(False)

    def refresh_view(self):
        self._view.clear_items()
        if self.svc.is_current_python():
            task = GeneratorTask(self.check_current, self.add_view_node)
            task.start()

    def check_current(self):
        root_node = self.check(self._current)
        for child, parent in root_node.get_recursive_children():
            if parent is root_node:
                parent = None
            yield (child, parent)

    def check(self, document):
        code_string = document.string
        return pythonparser.get_nodes_from_string(code_string)

    def add_view_node(self, node, parent):
        self._view.add_node(node, parent)

    def get_view(self):
        return self._view


class BasePythonProjectController(ProjectController):

    attributes = [
        ProjectKeyDefinition('python_executable', _('Python Executable'), False),
    ] + ProjectController.attributes

    def get_python_executable(self):
        return self.get_option('python_executable') or 'python'


class PythonProjectController(BasePythonProjectController):

    name = 'PYTHON_CONTROLLER'

    label = _('Python Controller')

    attributes = [
        ProjectKeyDefinition('execute_file', _('File to execute'), True),
        ProjectKeyDefinition('execute_args', _('Args to execute'), False),
    ] + BasePythonProjectController.attributes

    def execute(self):
        execute_file = self.get_option('execute_file')
        execute_args = self.get_option('execute_args')
        if not execute_file:
            self.boss.get_window().error_dlg(_('Controller has no "execute_file" set'))
        else:
            commandargs = [self.get_python_executable(), execute_file]
            if execute_args is not None:
                commandargs.extend(execute_args.split())
            self.execute_commandargs(
                commandargs,
            )


class PythonDistutilstoolsController(ProjectController):
    """Controller for running a distutils command"""

    name = 'DISTUTILS_CONTROLLER'

    label = _('Distutils Controller')

    attributes = [
        ProjectKeyDefinition('command', _('Distutils command'), True),
        ProjectKeyDefinition('args', _('Args for command'), False),
    ] + BasePythonProjectController.attributes

    def execute(self):
        command = self.get_option('command')
        if not command:
            self.boss.get_window().error_dlg(_('Controller has no "command" set'))
        else:
            commandargs = [self.get_python_executable(), 'setup.py', command]
            args = self.get_option('args')
            if args:
                args = args.split()
                commandargs.extend(args)
            self.execute_commandargs(
                commandargs,
            )

    def get_python_executable(self):
        return self.get_option('python_executable') or 'python'



class PythonFeatures(FeaturesConfig):

    def subscribe_foreign_features(self):
        self.subscribe_foreign_feature('project', IProjectController,
            PythonProjectController)
        self.subscribe_foreign_feature('project', IProjectController,
            PythonDistutilstoolsController)


class PythonOptionsConfig(OptionsConfig):

    def create_options(self):
        self.create_option(
            'python_for_executing',
            _('Python Executable for executing'),
            OTypeString,
            'python',
            _('The Python executable when executing a module'),
        )


class PythonEventsConfig(EventsConfig):

    def subscribe_foreign_events(self):
        self.subscribe_foreign_event('buffer', 'document-changed', self.on_document_changed)
        self.subscribe_foreign_event('buffer', 'document-saved', self.on_document_changed)

    def on_document_changed(self, document):
        self.svc.set_current_document(document)

class PythonActionsConfig(ActionsConfig):
    
    def create_actions(self):
        self.create_action(
            'execute_python',
            TYPE_NORMAL,
            _('Execute Python Module'),
            _('Execute the current Python module in a shell'),
            gtk.STOCK_EXECUTE,
            self.on_python_execute,
        )

        self.create_action(
            'show_python_errors',
            TYPE_TOGGLE,
            _('Python Error Viewer'),
            _('Show the python error browser'),
            'error',
            self.on_show_errors,
        )

        self.create_action(
            'show_python_source',
            TYPE_TOGGLE,
            _('Python Source Viewer'),
            _('Show the python source browser'),
            'info',
            self.on_show_source,
        )

    def on_python_execute(self, action):
        self.svc.execute_current_document()

    def on_show_errors(self, action):
        if action.get_active():
            self.svc.show_errors()
        else:
            self.svc.hide_errors()

    def on_show_source(self, action):
        if action.get_active():
            self.svc.show_source()
        else:
            self.svc.hide_source()


# Service class
class Python(Service):
    """Service for all things Python""" 

    events_config = PythonEventsConfig
    actions_config = PythonActionsConfig
    options_config = PythonOptionsConfig
    features_config = PythonFeatures

    def pre_start(self):
        """Start the service"""
        self._current = None
        self._pyflaker = Pyflaker(self)
        self._pysource = PythonBrowser(self)
        self.execute_action = self.get_action('execute_python')
        self.execute_action.set_sensitive(False)

    def set_current_document(self, document):
        self._current = document
        if self.is_current_python():
            self._pyflaker.set_current_document(document)
            self._pysource.set_current_document(document)
            self.execute_action.set_sensitive(True)
        else:
            self._pyflaker.set_current_document(None)
            self._pysource.set_current_document(None)
            self.execute_action.set_sensitive(False)

    def is_current_python(self):
        if self._current is not None:
            return self._current.filename.endswith('.py')
        else:
            return False

    def execute_current_document(self):
        python_ex = self.opt('python_for_executing')
        self.boss.cmd('commander', 'execute',
            commandargs=[python_ex, self._current.filename],
            cwd = self._current.directory,
            )

    def show_errors(self):
        self.boss.cmd('window', 'add_view',
            paned='Plugin', view=self._pyflaker.get_view())

    def hide_errors(self):
        self.boss.cmd('window', 'remove_view',
            view=self._pyflaker.get_view())

    def show_source(self):
        self.boss.cmd('window', 'add_view',
            paned='Plugin', view=self._pysource.get_view())

    def hide_source(self):
        self.boss.cmd('window', 'remove_view',
            view=self._pysource.get_view())

    def stop(self):
        if self.get_action('show_python_source').get_active():
            self.hide_source()
        if self.get_action('show_python_errors').get_active():
            self.hide_errors()

# Required Service attribute for service loading
Service = Python



# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: