DebugClients/Python3/DebugClientBase.py

branch
jsonrpc
changeset 5129
e4ab234cf071
parent 5128
b6cbdba69967
child 5131
889ed5ff7a68
diff -r b6cbdba69967 -r e4ab234cf071 DebugClients/Python3/DebugClientBase.py
--- a/DebugClients/Python3/DebugClientBase.py	Fri Sep 02 19:14:41 2016 +0200
+++ b/DebugClients/Python3/DebugClientBase.py	Fri Sep 02 19:50:20 2016 +0200
@@ -20,13 +20,12 @@
 import signal
 
 
-##import DebugProtocol
 import DebugClientCapabilities
 from DebugBase import setRecursionLimit, printerr   # __IGNORE_WARNING__
 from AsyncFile import AsyncFile, AsyncPendingWrite
 from DebugConfig import ConfigVarTypeStrings
 from FlexCompleter import Completer
-from DebugUtilities import getargvalues, formatargvalues
+from DebugUtilities import getargvalues, formatargvalues, prepareJsonCommand
 
 
 DebugClientInstance = None
@@ -189,10 +188,8 @@
         self.globalsFilterObjects = []
         self.localsFilterObjects = []
 
-##        self.pendingResponse = DebugProtocol.ResponseOK
         self._fncache = {}
         self.dircache = []
-##        self.inRawMode = False
         self.mainProcStr = None     # used for the passive mode
         self.passive = False        # used to indicate the passive mode
         self.running = None
@@ -303,8 +300,6 @@
                 d["broken"] = False
             threadList.append(d)
         
-##        self.write("{0}{1!r}\n".format(DebugProtocol.ResponseThreadList,
-##                                       (currentId, threadList)))
         self.sendJsonCommand("ResponseThreadList", {
             "currentID": currentId,
             "threadList": threadList,
@@ -318,25 +313,13 @@
         @param echo Flag indicating echoing of the input (boolean)
         @return the entered string
         """
-##        self.write("{0}{1!r}\n".format(
-##            DebugProtocol.ResponseRaw, (prompt, echo)))
         self.sendJsonCommand("RequestRaw", {
             "prompt": prompt,
             "echo": echo,
         })
-##        self.inRawMode = True
         self.eventLoop(True)
         return self.rawLine
 
-##    def __exceptionRaised(self):
-##        """
-##        Private method called in the case of an exception.
-##        
-##        It ensures that the debug server is informed of the raised exception.
-##        """
-####        self.pendingResponse = DebugProtocol.ResponseException
-##        self.sendJsonCommand("ResponseException", {})
-##    
     def sessionClose(self, exit=True):
         """
         Public method to close the session with the debugger and optionally
@@ -349,8 +332,6 @@
         except Exception:
             pass
 
-##        # clean up asyncio.
-##        self.disconnect()
         self.debugging = False
         
         # make sure we close down our end of the socket
@@ -409,629 +390,14 @@
 
 ##        printerr(line)          ##debug
         
-        if line.startswith("{") and "jsonrpc" in line:
-            return self.handleJsonCommand(line)
-##
-##        eoc = line.find('<')
-##
-##        if eoc >= 0 and line[0] == '>':
-##            # Get the command part and any argument.
-##            cmd = line[:eoc + 1]
-##            arg = line[eoc + 1:]
-##            
-##            if cmd == DebugProtocol.RequestVariables:
-##                frmnr, scope, filter = eval(arg.replace("u'", "'"))
-##                self.__dumpVariables(int(frmnr), int(scope), filter)
-##                return
-##            
-##            if cmd == DebugProtocol.RequestVariable:
-##                var, frmnr, scope, filter = eval(arg.replace("u'", "'"))
-##                self.__dumpVariable(var, int(frmnr), int(scope), filter)
-##                return
-##            
-##            if cmd == DebugProtocol.RequestThreadList:
-##                self.__dumpThreadList()
-##                return
-##            
-##            if cmd == DebugProtocol.RequestThreadSet:
-##                tid = eval(arg)
-##                if tid in self.threads:
-##                    self.setCurrentThread(tid)
-##                    self.write(DebugProtocol.ResponseThreadSet + '\n')
-##                    stack = self.currentThread.getStack()
-##                    self.write('{0}{1!r}\n'.format(
-##                        DebugProtocol.ResponseStack, stack))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestStep:
-##                self.currentThread.step(True)
-##                self.eventExit = True
-##                return
-##
-##            if cmd == DebugProtocol.RequestStepOver:
-##                self.currentThread.step(False)
-##                self.eventExit = True
-##                return
-##            
-##            if cmd == DebugProtocol.RequestStepOut:
-##                self.currentThread.stepOut()
-##                self.eventExit = True
-##                return
-##            
-##            if cmd == DebugProtocol.RequestStepQuit:
-##                if self.passive:
-##                    self.progTerminated(42)
-##                else:
-##                    self.set_quit()
-##                    self.eventExit = True
-##                return
-##
-##            if cmd == DebugProtocol.RequestContinue:
-##                special = int(arg)
-##                self.currentThread.go(special)
-##                self.eventExit = True
-##                return
-##
-##            if cmd == DebugProtocol.RequestOK:
-##                self.write(self.pendingResponse + '\n')
-##                self.pendingResponse = DebugProtocol.ResponseOK
-##                return
-##
-##            if cmd == DebugProtocol.RequestCallTrace:
-##                if arg.strip().lower() == "on":
-##                    callTraceEnabled = True
-##                else:
-##                    callTraceEnabled = False
-##                if self.debugging:
-##                    self.callTraceEnabled = callTraceEnabled
-##                else:
-##                    self.__newCallTraceEnabled = callTraceEnabled
-##                    # remember for later
-##                return
-##            
-##            if cmd == DebugProtocol.RequestEnv:
-##                env = eval(arg.replace("u'", "'"))
-##                for key, value in env.items():
-##                    if key.endswith("+"):
-##                        if key[:-1] in os.environ:
-##                            os.environ[key[:-1]] += value
-##                        else:
-##                            os.environ[key[:-1]] = value
-##                    else:
-##                        os.environ[key] = value
-##                return
-##
-##            if cmd == DebugProtocol.RequestLoad:
-##                self._fncache = {}
-##                self.dircache = []
-##                sys.argv = []
-##                wd, fn, args, tracePython = arg.split('|')
-##                self.__setCoding(fn)
-##                sys.argv.append(fn)
-##                sys.argv.extend(eval(args))
-##                sys.path = self.__getSysPath(os.path.dirname(sys.argv[0]))
-##                if wd == '':
-##                    os.chdir(sys.path[1])
-##                else:
-##                    os.chdir(wd)
-##                tracePython = int(tracePython)
-##                self.running = sys.argv[0]
-##                self.mainFrame = None
-##                self.inRawMode = False
-##                self.debugging = True
-##                
-##                self.threads.clear()
-##                self.attachThread(mainThread=True)
-##                
-##                # set the system exception handling function to ensure, that
-##                # we report on all unhandled exceptions
-##                sys.excepthook = self.__unhandled_exception
-##                self.__interceptSignals()
-##                
-##                # clear all old breakpoints, they'll get set after we have
-##                # started
-##                self.mainThread.clear_all_breaks()
-##                
-##                self.mainThread.tracePython = tracePython
-##                
-##                # This will eventually enter a local event loop.
-##                self.debugMod.__dict__['__file__'] = self.running
-##                sys.modules['__main__'] = self.debugMod
-##                code = self.__compileFileSource(self.running)
-##                if code:
-##                    self.callTraceEnabled = self.__newCallTraceEnabled
-##                    res = self.mainThread.run(code, self.debugMod.__dict__)
-##                    self.progTerminated(res)
-##                return
-##
-##            if cmd == DebugProtocol.RequestRun:
-##                sys.argv = []
-##                wd, fn, args = arg.split('|')
-##                self.__setCoding(fn)
-##                sys.argv.append(fn)
-##                sys.argv.extend(eval(args))
-##                sys.path = self.__getSysPath(os.path.dirname(sys.argv[0]))
-##                if wd == '':
-##                    os.chdir(sys.path[1])
-##                else:
-##                    os.chdir(wd)
-##
-##                self.running = sys.argv[0]
-##                self.mainFrame = None
-##                self.botframe = None
-##                self.inRawMode = False
-##                
-##                self.threads.clear()
-##                self.attachThread(mainThread=True)
-##                
-##                # set the system exception handling function to ensure, that
-##                # we report on all unhandled exceptions
-##                sys.excepthook = self.__unhandled_exception
-##                self.__interceptSignals()
-##                
-##                self.mainThread.tracePython = False
-##                
-##                self.debugMod.__dict__['__file__'] = sys.argv[0]
-##                sys.modules['__main__'] = self.debugMod
-##                res = 0
-##                code = self.__compileFileSource(self.running)
-##                if code:
-##                    try:
-##                        exec(code, self.debugMod.__dict__)
-##                    except SystemExit as exc:
-##                        res = exc.code
-##                        atexit._run_exitfuncs()
-##                    self.writestream.flush()
-##                    self.progTerminated(res)
-##                return
-##
-##            if cmd == DebugProtocol.RequestProfile:
-##                sys.setprofile(None)
-##                import PyProfile
-##                sys.argv = []
-##                wd, fn, args, erase = arg.split('|')
-##                self.__setCoding(fn)
-##                sys.argv.append(fn)
-##                sys.argv.extend(eval(args))
-##                sys.path = self.__getSysPath(os.path.dirname(sys.argv[0]))
-##                if wd == '':
-##                    os.chdir(sys.path[1])
-##                else:
-##                    os.chdir(wd)
-##
-##                # set the system exception handling function to ensure, that
-##                # we report on all unhandled exceptions
-##                sys.excepthook = self.__unhandled_exception
-##                self.__interceptSignals()
-##                
-##                # generate a profile object
-##                self.prof = PyProfile.PyProfile(sys.argv[0])
-##                
-##                if int(erase):
-##                    self.prof.erase()
-##                self.debugMod.__dict__['__file__'] = sys.argv[0]
-##                sys.modules['__main__'] = self.debugMod
-##                fp = open(sys.argv[0], encoding=self.__coding)
-##                try:
-##                    script = fp.read()
-##                finally:
-##                    fp.close()
-##                if script:
-##                    if not script.endswith('\n'):
-##                        script += '\n'
-##                    self.running = sys.argv[0]
-##                    res = 0
-##                    try:
-##                        self.prof.run(script)
-##                    except SystemExit as exc:
-##                        res = exc.code
-##                        atexit._run_exitfuncs()
-##                    self.prof.save()
-##                    self.writestream.flush()
-##                    self.progTerminated(res)
-##                return
-##
-##            if cmd == DebugProtocol.RequestCoverage:
-##                from coverage import coverage
-##                sys.argv = []
-##                wd, fn, args, erase = arg.split('@@')
-##                self.__setCoding(fn)
-##                sys.argv.append(fn)
-##                sys.argv.extend(eval(args))
-##                sys.path = self.__getSysPath(os.path.dirname(sys.argv[0]))
-##                if wd == '':
-##                    os.chdir(sys.path[1])
-##                else:
-##                    os.chdir(wd)
-##                
-##                # set the system exception handling function to ensure, that
-##                # we report on all unhandled exceptions
-##                sys.excepthook = self.__unhandled_exception
-##                self.__interceptSignals()
-##                
-##                # generate a coverage object
-##                self.cover = coverage(
-##                    auto_data=True,
-##                    data_file="{0}.coverage".format(
-##                        os.path.splitext(sys.argv[0])[0]))
-##                
-##                if int(erase):
-##                    self.cover.erase()
-##                sys.modules['__main__'] = self.debugMod
-##                self.debugMod.__dict__['__file__'] = sys.argv[0]
-##                fp = open(sys.argv[0], encoding=self.__coding)
-##                try:
-##                    script = fp.read()
-##                finally:
-##                    fp.close()
-##                if script:
-##                    if not script.endswith('\n'):
-##                        script += '\n'
-##                    code = compile(script, sys.argv[0], 'exec')
-##                    self.running = sys.argv[0]
-##                    res = 0
-##                    self.cover.start()
-##                    try:
-##                        exec(code, self.debugMod.__dict__)
-##                    except SystemExit as exc:
-##                        res = exc.code
-##                        atexit._run_exitfuncs()
-##                    self.cover.stop()
-##                    self.cover.save()
-##                    self.writestream.flush()
-##                    self.progTerminated(res)
-##                return
-##
-##            if cmd == DebugProtocol.RequestShutdown:
-##                self.sessionClose()
-##                return
-##            
-##            if cmd == DebugProtocol.RequestBreak:
-##                fn, line, temporary, set, cond = arg.split('@@')
-##                line = int(line)
-##                set = int(set)
-##                temporary = int(temporary)
-##
-##                if set:
-##                    if cond == 'None' or cond == '':
-##                        cond = None
-##                    else:
-##                        try:
-##                            compile(cond, '<string>', 'eval')
-##                        except SyntaxError:
-##                            self.write('{0}{1},{2:d}\n'.format(
-##                                       DebugProtocol.ResponseBPConditionError,
-##                                       fn, line))
-##                            return
-##                    self.mainThread.set_break(fn, line, temporary, cond)
-##                else:
-##                    self.mainThread.clear_break(fn, line)
-##
-##                return
-##            
-##            if cmd == DebugProtocol.RequestBreakEnable:
-##                fn, line, enable = arg.split(',')
-##                line = int(line)
-##                enable = int(enable)
-##                
-##                bp = self.mainThread.get_break(fn, line)
-##                if bp is not None:
-##                    if enable:
-##                        bp.enable()
-##                    else:
-##                        bp.disable()
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestBreakIgnore:
-##                fn, line, count = arg.split(',')
-##                line = int(line)
-##                count = int(count)
-##                
-##                bp = self.mainThread.get_break(fn, line)
-##                if bp is not None:
-##                    bp.ignore = count
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestWatch:
-##                cond, temporary, set = arg.split('@@')
-##                set = int(set)
-##                temporary = int(temporary)
-##
-##                if set:
-##                    if not cond.endswith('??created??') and \
-##                       not cond.endswith('??changed??'):
-##                        try:
-##                            compile(cond, '<string>', 'eval')
-##                        except SyntaxError:
-##                            self.write('{0}{1}\n'.format(
-##                                DebugProtocol.ResponseWPConditionError, cond))
-##                            return
-##                    self.mainThread.set_watch(cond, temporary)
-##                else:
-##                    self.mainThread.clear_watch(cond)
-##
-##                return
-##            
-##            if cmd == DebugProtocol.RequestWatchEnable:
-##                cond, enable = arg.split(',')
-##                enable = int(enable)
-##                
-##                bp = self.mainThread.get_watch(cond)
-##                if bp is not None:
-##                    if enable:
-##                        bp.enable()
-##                    else:
-##                        bp.disable()
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestWatchIgnore:
-##                cond, count = arg.split(',')
-##                count = int(count)
-##                
-##                bp = self.mainThread.get_watch(cond)
-##                if bp is not None:
-##                    bp.ignore = count
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestEval:
-##                try:
-##                    value = eval(
-##                        arg,
-##                        self.currentThread.getCurrentFrame().f_globals,
-##                        self.currentThread.getFrameLocals(self.framenr))
-##                    self.currentThread.storeFrameLocals(self.framenr)
-##                except Exception:
-##                    # Report the exception and the traceback
-##                    try:
-##                        type, value, tb = sys.exc_info()
-##                        sys.last_type = type
-##                        sys.last_value = value
-##                        sys.last_traceback = tb
-##                        tblist = traceback.extract_tb(tb)
-##                        del tblist[:1]
-##                        list = traceback.format_list(tblist)
-##                        if list:
-##                            list.insert(0, "Traceback (innermost last):\n")
-##                            list[len(list):] = \
-##                                traceback.format_exception_only(type, value)
-##                    finally:
-##                        tblist = tb = None
-##
-##                    for l in list:
-##                        self.write(l)
-##
-##                    self.write(DebugProtocol.ResponseException + '\n')
-##                
-##                else:
-##                    self.write(str(value) + '\n')
-##                    self.write(DebugProtocol.ResponseOK + '\n')
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestExec:
-##                _globals = self.currentThread.getCurrentFrame().f_globals
-##                _locals = self.currentThread.getFrameLocals(self.framenr)
-##                try:
-##                    code = compile(arg + '\n', '<stdin>', 'single')
-##                    exec(code, _globals, _locals)
-##                    self.currentThread.storeFrameLocals(self.framenr)
-##                except Exception:
-##                    # Report the exception and the traceback
-##                    try:
-##                        type, value, tb = sys.exc_info()
-##                        sys.last_type = type
-##                        sys.last_value = value
-##                        sys.last_traceback = tb
-##                        tblist = traceback.extract_tb(tb)
-##                        del tblist[:1]
-##                        list = traceback.format_list(tblist)
-##                        if list:
-##                            list.insert(0, "Traceback (innermost last):\n")
-##                            list[len(list):] = \
-##                                traceback.format_exception_only(type, value)
-##                    finally:
-##                        tblist = tb = None
-##
-##                    for l in list:
-##                        self.write(l)
-##
-##                    self.write(DebugProtocol.ResponseException + '\n')
-##                
-##                return
-##            
-##            if cmd == DebugProtocol.RequestBanner:
-##                self.write('{0}{1}\n'.format(DebugProtocol.ResponseBanner,
-##                           str(("Python {0}".format(sys.version),
-##                                socket.gethostname(), self.variant))))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestCapabilities:
-##                self.write('{0}{1:d}, "Python3"\n'.format(
-##                    DebugProtocol.ResponseCapabilities,
-##                    self.__clientCapabilities()))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestCompletion:
-##                self.__completionList(arg.replace("u'", "'"))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestSetFilter:
-##                scope, filterString = eval(arg.replace("u'", "'"))
-##                self.__generateFilterObjects(int(scope), filterString)
-##                return
-##            
-##            if cmd == DebugProtocol.RequestUTPrepare:
-##                fn, tn, tfn, failed, cov, covname, erase = arg.split('|')
-##                sys.path.insert(0, os.path.dirname(os.path.abspath(fn)))
-##                os.chdir(sys.path[0])
-##                failed = eval(failed)
-##
-##                # set the system exception handling function to ensure, that
-##                # we report on all unhandled exceptions
-##                sys.excepthook = self.__unhandled_exception
-##                self.__interceptSignals()
-##                
-##                try:
-##                    import unittest
-##                    utModule = imp.load_source(tn, fn)
-##                    try:
-##                        if failed:
-##                            self.test = unittest.defaultTestLoader\
-##                                .loadTestsFromNames(failed, utModule)
-##                        else:
-##                            self.test = unittest.defaultTestLoader\
-##                                .loadTestsFromName(tfn, utModule)
-##                    except AttributeError:
-##                        self.test = unittest.defaultTestLoader\
-##                            .loadTestsFromModule(utModule)
-##                except Exception:
-##                    exc_type, exc_value, exc_tb = sys.exc_info()
-##                    self.write('{0}{1}\n'.format(
-##                        DebugProtocol.ResponseUTPrepared,
-##                        str((0, str(exc_type), str(exc_value)))))
-##                    self.__exceptionRaised()
-##                    return
-##                
-##                # generate a coverage object
-##                if int(cov):
-##                    from coverage import coverage
-##                    self.cover = coverage(
-##                        auto_data=True,
-##                        data_file="{0}.coverage".format(
-##                            os.path.splitext(covname)[0]))
-##                    if int(erase):
-##                        self.cover.erase()
-##                else:
-##                    self.cover = None
-##                
-##                self.write('{0}{1}\n'.format(
-##                    DebugProtocol.ResponseUTPrepared,
-##                    str((self.test.countTestCases(), "", ""))))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestUTRun:
-##                from DCTestResult import DCTestResult
-##                self.testResult = DCTestResult(self)
-##                if self.cover:
-##                    self.cover.start()
-##                self.test.run(self.testResult)
-##                if self.cover:
-##                    self.cover.stop()
-##                    self.cover.save()
-##                self.write('{0}\n'.format(DebugProtocol.ResponseUTFinished))
-##                return
-##            
-##            if cmd == DebugProtocol.RequestUTStop:
-##                self.testResult.stop()
-##                return
-##        
-##            if cmd == DebugProtocol.ResponseForkTo:
-##                # this results from a separate event loop
-##                self.fork_child = (arg == 'child')
-##                self.eventExit = True
-##                return
-##            
-##            if cmd == DebugProtocol.RequestForkMode:
-##                self.fork_auto, self.fork_child = eval(arg)
-##                return
-##        
-##        # If we are handling raw mode input then reset the mode and break out
-##        # of the current event loop.
-##        if self.inRawMode:
-##            self.inRawMode = False
-##            self.rawLine = line
-##            self.eventExit = True
-##            return
-##
-##        if self.buffer:
-##            self.buffer = self.buffer + '\n' + line
-##        else:
-##            self.buffer = line
-##
-##        try:
-##            code = self.compile_command(self.buffer, self.readstream.name)
-##        except (OverflowError, SyntaxError, ValueError):
-##            # Report the exception
-##            sys.last_type, sys.last_value, sys.last_traceback = sys.exc_info()
-##            for l in traceback.format_exception_only(
-##                    sys.last_type, sys.last_value):
-##                self.write(l)
-##            self.buffer = ''
-##        else:
-##            if code is None:
-##                self.pendingResponse = DebugProtocol.ResponseContinue
-##            else:
-##                self.buffer = ''
-##
-##                try:
-##                    if self.running is None:
-##                        exec(code, self.debugMod.__dict__)
-##                    else:
-##                        if self.currentThread is None:
-##                            # program has terminated
-##                            self.running = None
-##                            _globals = self.debugMod.__dict__
-##                            _locals = _globals
-##                        else:
-##                            cf = self.currentThread.getCurrentFrame()
-##                            # program has terminated
-##                            if cf is None:
-##                                self.running = None
-##                                _globals = self.debugMod.__dict__
-##                                _locals = _globals
-##                            else:
-##                                frmnr = self.framenr
-##                                while cf is not None and frmnr > 0:
-##                                    cf = cf.f_back
-##                                    frmnr -= 1
-##                                _globals = cf.f_globals
-##                                _locals = \
-##                                    self.currentThread.getFrameLocals(
-##                                        self.framenr)
-##                        # reset sys.stdout to our redirector (unconditionally)
-##                        if "sys" in _globals:
-##                            __stdout = _globals["sys"].stdout
-##                            _globals["sys"].stdout = self.writestream
-##                            exec(code, _globals, _locals)
-##                            _globals["sys"].stdout = __stdout
-##                        elif "sys" in _locals:
-##                            __stdout = _locals["sys"].stdout
-##                            _locals["sys"].stdout = self.writestream
-##                            exec(code, _globals, _locals)
-##                            _locals["sys"].stdout = __stdout
-##                        else:
-##                            exec(code, _globals, _locals)
-##                        
-##                        self.currentThread.storeFrameLocals(self.framenr)
-##                except SystemExit as exc:
-##                    self.progTerminated(exc.code)
-##                except Exception:
-##                    # Report the exception and the traceback
-##                    try:
-##                        exc_type, exc_value, exc_tb = sys.exc_info()
-##                        sys.last_type = exc_type
-##                        sys.last_value = exc_value
-##                        sys.last_traceback = exc_tb
-##                        tblist = traceback.extract_tb(exc_tb)
-##                        del tblist[:1]
-##                        list = traceback.format_list(tblist)
-##                        if list:
-##                            list.insert(0, "Traceback (innermost last):\n")
-##                            list[len(list):] = traceback.format_exception_only(
-##                                exc_type, exc_value)
-##                    finally:
-##                        tblist = exc_tb = None
-##
-##                    for l in list:
-##                        self.write(l)
+        self.handleJsonCommand(line)
     
     def handleJsonCommand(self, jsonStr):
         """
         Public method to handle a command serialized as a JSON string.
+        
+        @param jsonStr string containing the command received from the IDE
+        @type str
         """
         import json
         
@@ -1113,7 +479,6 @@
             
             self.running = sys.argv[0]
             self.mainFrame = None
-##            self.inRawMode = False
             self.debugging = True
             
             self.fork_auto = params["autofork"]
@@ -1156,7 +521,6 @@
             self.running = sys.argv[0]
             self.mainFrame = None
             self.botframe = None
-##            self.inRawMode = False
             
             self.fork_auto = params["autofork"]
             self.fork_child = params["forkChild"]
@@ -1289,9 +653,6 @@
                 # Report the exception
                 sys.last_type, sys.last_value, sys.last_traceback = \
                     sys.exc_info()
-##                for l in traceback.format_exception_only(
-##                        sys.last_type, sys.last_value):
-##                    self.write(l)
                 self.sendJsonCommand("ClientOutput", {
                     "text": "".join(traceback.format_exception_only(
                         sys.last_type, sys.last_value))
@@ -1367,8 +728,6 @@
                         finally:
                             tblist = exc_tb = None
 
-##                        for l in list:
-##                            self.write(l)
                         self.sendJsonCommand("ClientOutput", {
                             "text": "".join(tlist)
                         })
@@ -1500,7 +859,6 @@
                     "exception": exc_type.__name__,
                     "message": str(exc_value),
                 })
-##                self.__exceptionRaised()
                 return
             
             # generate a coverage object
@@ -1540,23 +898,17 @@
             self.fork_child = (params["target"] == 'child')
             self.eventExit = True
     
-    def sendJsonCommand(self, command, params):
+    def sendJsonCommand(self, method, params):
         """
-        Public method to send a single command to the client.
+        Public method to send a single command or response to the IDE.
         
-        @param command command name to be sent
+        @param method command or response command name to be sent
         @type str
-        @param params dictionary of named parameters for the command
+        @param params dictionary of named parameters for the command or
+            response
         @type dict
         """
-        import json
-        
-        commandDict = {
-            "jsonrpc": "2.0",
-            "method": command,
-            "params": params,
-        }
-        cmd = json.dumps(commandDict) + '\n'
+        cmd = prepareJsonCommand(method, params)
         
         self.writestream.write_p(cmd)
         self.writestream.flush()
@@ -1603,7 +955,7 @@
         
         @param event trace event (call or return)
         @type str
-        @param fromstr pre-formatted origin info
+        @param fromStr pre-formatted origin info
         @type str
         @param toStr pre-formatted target info
         @type str
@@ -1623,7 +975,7 @@
         @param exceptionMessage message of the exception
         @type str
         @param stack stack trace information
-        @param list
+        @type list
         """
         self.sendJsonCommand("ResponseException", {
             "type": exceptionType,
@@ -1682,20 +1034,11 @@
             return (
                 self.clientCapabilities & ~DebugClientCapabilities.HasProfiler)
     
-##    def write(self, s):
-##        """
-##        Public method to write data to the output stream.
-##        
-##        @param s data to be written (string)
-##        """
-##        self.writestream.write_p(s)
-##        self.writestream.flush()
-##
     def readReady(self, stream):
         """
         Public method called when there is data ready to be read.
         
-        @param fd file descriptor of the file that has data to be read (int)
+        @param stream file like object that has data to be written
         """
         try:
             got = stream.readline_p()
@@ -1720,7 +1063,7 @@
         """
         Public method called when we are ready to write data.
         
-        @param fd file descriptor of the file that has data to be written (int)
+        @param stream file like object that has data to be written
         """
         stream.write_p("")
         stream.flush()
@@ -1731,7 +1074,6 @@
         """
         global DebugClientInstance
 
-##        self.setDescriptors(self.readstream, self.writestream)
         DebugClientInstance = self
         self.__receiveBuffer = ""
 
@@ -1911,14 +1253,11 @@
         else:
             fargs = ""
         
-##        siglist = [message, [filename, linenr, ffunc, fargs]]
-##        
-##        self.write("{0}{1}".format(DebugProtocol.ResponseSignal, str(siglist)))
         self.sendJsonCommand("ResponseSignal", {
             "message": message,
-            "filename": filename, 
-            "linenumber": linenr, 
-            "function": ffunc, 
+            "filename": filename,
+            "linenumber": linenr,
+            "function": ffunc,
             "arguments": fargs,
         })
     
@@ -2015,7 +1354,6 @@
         if self.running:
             self.set_quit()
             self.running = None
-##            self.write('{0}{1:d}\n'.format(DebugProtocol.ResponseExit, status))
             self.sendJsonCommand("ResponseExit", {
                 "status": status,
                 "message": message,
@@ -2066,8 +1404,6 @@
             vlist = self.__formatVariablesList(keylist, dict, scope, filter)
             varlist.extend(vlist)
         
-##        self.write('{0}{1}\n'.format(
-##            DebugProtocol.ResponseVariables, str(varlist)))
         self.sendJsonCommand("ResponseVariables", {
             "scope": scope,
             "variables": varlist,
@@ -2355,8 +1691,6 @@
                 except Exception:
                     pass
         
-##        self.write('{0}{1}\n'.format(
-##            DebugProtocol.ResponseVariable, str(varlist)))
         self.sendJsonCommand("ResponseVariable", {
             "scope": scope,
             "variable": var,
@@ -2657,11 +1991,9 @@
             pass
         self.__getCompletionList(text, self.complete, completions)
         
-##        self.write("{0}{1}||{2}\n".format(DebugProtocol.ResponseCompletion,
-##                                          str(list(completions)), text))
         self.sendJsonCommand("ResponseCompletion", {
             "completions": list(completions),
-            "text": text, 
+            "text": text,
         })
 
     def __getCompletionList(self, text, completer, completions):
@@ -2727,7 +2059,6 @@
         self._fncache = {}
         self.dircache = []
         self.mainFrame = None
-##        self.inRawMode = False
         self.debugging = True
         
         self.attachThread(mainThread=True)
@@ -2780,13 +2111,10 @@
         self.running = sys.argv[0]
         self.__setCoding(self.running)
         self.mainFrame = None
-##        self.inRawMode = False
         self.debugging = True
         
         self.passive = True
         self.sendPassiveStartup(self.running, exceptions)
-##        self.write("{0}{1}|{2:d}\n".format(
-##            DebugProtocol.PassiveStartup, self.running, exceptions))
         self.__interact()
         
         self.attachThread(mainThread=True)
@@ -2943,7 +2271,6 @@
         @return process ID (integer)
         """
         if not self.fork_auto:
-##            self.write(DebugProtocol.RequestForkTo + '\n')
             self.sendJsonCommand("RequestForkTo", {})
             self.eventLoop(True)
         pid = DebugClientOrigFork()

eric ide

mercurial