~barcc/gedit-debugger/trunk

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
# -*- coding: utf-8 -*-

#  Copyright © 2013-2015  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys, os
import multiprocessing.connection
import select

from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Vte

from .helper import ConnectHelper

DIRNAME = os.path.dirname(__file__)
AUTHKEY = b'Wrtlprmft'

class Listener (multiprocessing.connection.Listener):
    def accept(self, protocol):
        from multiprocessing.reduction import ForkingPickler
        obj = multiprocessing.connection.Listener.accept(self)
        def dumps(obj):
            return ForkingPickler.dumps(obj, protocol=protocol)
        def loads(buf):
            return ForkingPickler.loads(buf)
        return multiprocessing.connection.ConnectionWrapper(obj, dumps, loads)
        
        
class PythonDebugger (GObject.Object, ConnectHelper):
    __gsignals__ = {
        'stack-changed':    (GObject.SignalFlags.RUN_FIRST, None, (object, bool)),
        'break-changed':    (GObject.SignalFlags.RUN_FIRST, None, (object,)),
        'exited':           (GObject.SignalFlags.RUN_FIRST, None, ()),
    }
    
    dbg_cmd = ['python', os.path.join(DIRNAME, 'run_pdb.py')]
    pickle_protocol = 2
    
    def __init__(self, terminal):
        GObject.Object.__init__(self)
        ConnectHelper.__init__(self)
        
        self.debugger_pid = None
        self.watchid = None
        self.filename = None
        self.connection = None
        
        self.terminal = terminal
        self.connectx(self.terminal, 'child-exited', self.on_terminal_child_exited)
        
    running = property(lambda self: self.debugger_pid)
    
    def deactivate(self):
        self.disconnect_all()
        if self.watchid is not None:
            GLib.source_remove(self.watchid)
        if self.running:
            self.quit()
        if self.connection is not None:
            self.connection.close()
            self.connection = None
        self.terminal = None
        
    def start(self, filename, args, workingdir):
        assert self.debugger_pid is None
        self.filename = filename
        listener = Listener(family='AF_UNIX', authkey=AUTHKEY)
        command = self.dbg_cmd + [listener.address, self.filename]
        try:
            fork = self.terminal.fork_command_full
        except AttributeError:
            fork = self.terminal.spawn_sync
        self.debugger_pid = fork(Vte.PtyFlags.DEFAULT,
                                None, command, None, GLib.SpawnFlags.SEARCH_PATH,
                                None, None)
        self.connection = listener.accept(protocol=self.pickle_protocol)
        channel = GLib.IOChannel(self.connection.fileno())
        self.watchid = channel.add_watch(GLib.IOCondition.IN, self.on_connection_data_in)
        if args:
            self.chargs(args)
        if workingdir:
            self.chdir(workingdir)
        
    @staticmethod
    def check_execline(line):
        """Check whether specified line seems to be executable."""
        line = line.lstrip()
        if not line:
            return False
        if line[0] == '#':
            return False
        # Pdb does this test for docstrings, but because of false positives
        # and false negatives there is no much value.
        #if line.startswith(('"""', "'''")):
        #    return False
        return True  # accept line, warning: not comprehensive
        
    def on_connection_data_in(self, channel, condition):
        if self.connection is None:
            self.watchid = None
            return False
        r, w, x = select.select([self.connection.fileno()], [], [], 0)
        if not r:
            print('WARNING: on_connection_data_in, but connection not ready')
            self.watchid = channel.add_watch(GLib.IOCondition.IN, self.on_connection_data_in)
            return False
        try:
            command, args = self.connection.recv()
        except EOFError:
            self.watchid = None
            return False
        if command == 'stack':
            self.emit('stack-changed', *args)
        elif command == 'break':
            self.emit('break-changed', args)
        return True
        
    def on_terminal_child_exited(self, *unused):
        self.debugger_pid = None
        self.connection.close()
        self.connection = None
        self.emit('exited')
        
    def step(self):     self.connection.send(('step', ()))
    def next(self):     self.connection.send(('next', ()))
    def goreturn(self): self.connection.send(('return', ()))
    def run_to(self, filename, lineno):
        self.connection.send(('run_to', (filename, lineno)))
    def jump_to(self, filename, lineno):
        self.connection.send(('jump_to', (filename, lineno)))
    def cont(self, nopause=False):     self.connection.send(('continue', (nopause,)))
    def pause(self):    self.connection.send(('pause', ()))
    def bpadd(self, cnum, filename, lineno):
        self.connection.send(('break', (cnum, filename, lineno)))
    def bpclear(self, snum):
        self.connection.send(('clear', (snum,)))
    def quit(self):     self.connection.send(('quit', ()))
    def chargs(self, args):
        self.connection.send(('chargs', args))
    def chdir(self, workingdir):
        self.connection.send(('chdir', (workingdir,)))
    def inspect(self, keys):
        self.connection.send(('inspect', keys))
        
        
class Python3Debugger (PythonDebugger):
    dbg_cmd = ['python3', os.path.join(DIRNAME, 'run_pdb.py')]
    pickle_protocol = 4 if sys.version_info[:2] >= (3, 4) else 3
    
    
debuggers = {
            'python': PythonDebugger,
            'python3': Python3Debugger,
            #'application/x-executable': GNUProjectDebugger,
        }