From 305e5f1ad149f8eaa8f1d3738039401beb93d906 2008-06-24 06:48:14 From: Barry Wark Date: 2008-06-24 06:48:14 Subject: [PATCH] pep8, second pass --- diff --git a/IPython/frontend/cocoa/cocoa_frontend.py b/IPython/frontend/cocoa/cocoa_frontend.py index 1516ed1..a4242f0 100644 --- a/IPython/frontend/cocoa/cocoa_frontend.py +++ b/IPython/frontend/cocoa/cocoa_frontend.py @@ -2,7 +2,7 @@ # -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*- """PyObjC classes to provide a Cocoa frontend to the -IPython.kernel.engineservice.EngineService. +IPython.kernel.engineservice.IEngineBase. To add an IPython interpreter to a cocoa app, instantiate an IPythonCocoaController in a XIB and connect its textView outlet to an @@ -37,7 +37,7 @@ from AppKit import NSApplicationWillTerminateNotification, NSBeep,\ from pprint import saferepr import IPython -from IPython.kernel.engineservice import EngineService, ThreadedEngineService +from IPython.kernel.engineservice import ThreadedEngineService from IPython.frontend.frontendbase import FrontEndBase from twisted.internet.threads import blockingCallFromThread @@ -77,7 +77,7 @@ class IPythonCocoaController(NSObject, FrontEndBase): self.lines = {} self.tabSpaces = 4 self.tabUsesSpaces = True - self.currentBlockID = self.nextBlockID() + self.currentBlockID = self.next_block_ID() self.blockRanges = {} # blockID=>NSRange @@ -91,19 +91,21 @@ class IPythonCocoaController(NSObject, FrontEndBase): NSLog('IPython engine started') # Register for app termination - NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( - self, - 'appWillTerminate:', - NSApplicationWillTerminateNotification, - None) + nc = NSNotificationCenter.defaultCenter() + nc.addObserver_selector_name_object_( + self, + 'appWillTerminate:', + NSApplicationWillTerminateNotification, + None) self.textView.setDelegate_(self) self.textView.enclosingScrollView().setHasVerticalRuler_(True) - self.verticalRulerView = NSRulerView.alloc().initWithScrollView_orientation_( - self.textView.enclosingScrollView(), - NSVerticalRuler) + r = NSRulerView.alloc().initWithScrollView_orientation_( + self.textView.enclosingScrollView(), + NSVerticalRuler) + self.verticalRulerView = r self.verticalRulerView.setClientView_(self.textView) - self.startCLIForTextView() + self._start_cli_banner() def appWillTerminate_(self, notification): @@ -121,7 +123,8 @@ class IPythonCocoaController(NSObject, FrontEndBase): Result ------ - Deferred result of ipython1.kernel.engineservice.IEngineInteractive.complete + Deferred result of + IPython.kernel.engineservice.IEngineBase.complete """ return self.engine.complete(token) @@ -131,31 +134,31 @@ class IPythonCocoaController(NSObject, FrontEndBase): self.waitingForEngine = True self.willChangeValueForKey_('commandHistory') d = super(IPythonCocoaController, self).execute(block, blockID) - d.addBoth(self._engineDone) - d.addCallback(self._updateUserNS) + d.addBoth(self._engine_done) + d.addCallback(self._update_user_ns) return d - def _engineDone(self, x): + def _engine_done(self, x): self.waitingForEngine = False self.didChangeValueForKey_('commandHistory') return x - def _updateUserNS(self, result): + def _update_user_ns(self, result): """Update self.userNS from self.engine's namespace""" d = self.engine.keys() - d.addCallback(self._getEngineNamepsaceValuesForKeys) + d.addCallback(self._get_engine_namespace_values_for_keys) return result - def _getEngineNamepsaceValuesForKeys(self, keys): + def _get_engine_namespace_values_for_keys(self, keys): d = self.engine.pull(keys) - d.addCallback(self._storeEngineNamespaceValues, keys=keys) + d.addCallback(self._store_engine_namespace_values, keys=keys) - def _storeEngineNamespaceValues(self, values, keys=[]): + def _store_engine_namespace_values(self, values, keys=[]): assert(len(values) == len(keys)) self.willChangeValueForKey_('userNS') for (k,v) in zip(keys,values): @@ -163,7 +166,43 @@ class IPythonCocoaController(NSObject, FrontEndBase): self.didChangeValueForKey_('userNS') - def startCLIForTextView(self): + def update_cell_prompt(self, result): + if(isinstance(result, Failure)): + blockID = result.blockID + else: + blockID = result['blockID'] + + + self.insert_text(self.input_prompt(result=result), + textRange=NSMakeRange(self.blockRanges[blockID].location,0), + scrollToVisible=False + ) + + return result + + + def render_result(self, result): + blockID = result['blockID'] + inputRange = self.blockRanges[blockID] + del self.blockRanges[blockID] + + #print inputRange,self.current_block_range() + self.insert_text('\n' + + self.output_prompt(result) + + result.get('display',{}).get('pprint','') + + '\n\n', + textRange=NSMakeRange(inputRange.location+inputRange.length, + 0)) + return result + + + def render_error(self, failure): + self.insert_text('\n\n'+str(failure)+'\n\n') + self.start_new_block() + return failure + + + def _start_cli_banner(self): """Print banner""" banner = """IPython1 %s -- An enhanced Interactive Python.""" % \ @@ -171,14 +210,108 @@ class IPythonCocoaController(NSObject, FrontEndBase): self.insert_text(banner + '\n\n') - # NSTextView/IPythonTextView delegate methods + + def start_new_block(self): + """""" + + self.currentBlockID = self.next_block_ID() + + + + def next_block_ID(self): + + return uuid.uuid4() + + def current_block_range(self): + return self.blockRanges.get(self.currentBlockID, + NSMakeRange(self.textView.textStorage().length(), + 0)) + + def currentBlock(self): + """The current block's text""" + + return self.textForRange(self.current_block_range()) + + def textForRange(self, textRange): + """textForRange""" + + ts = self.textView.textStorage() + return ts.string().substringWithRange_(textRange) + + def currentLine(self): + block = self.textForRange(self.current_block_range()) + block = block.split('\n') + return block[-1] + + + def insert_text(self, string=None, textRange=None, scrollToVisible=True): + """Insert text into textView at textRange, updating blockRanges + as necessary + """ + + if(textRange == None): + #range for end of text + textRange = NSMakeRange(self.textView.textStorage().length(), 0) + + for r in self.blockRanges.itervalues(): + intersection = NSIntersectionRange(r,textRange) + if(intersection.length == 0): #ranges don't intersect + if r.location >= textRange.location: + r.location += len(string) + else: #ranges intersect + if(r.location <= textRange.location): + assert(intersection.length == textRange.length) + r.length += textRange.length + else: + r.location += intersection.length + + self.textView.replaceCharactersInRange_withString_( + textRange, string) + self.textView.setSelectedRange_( + NSMakeRange(textRange.location+len(string), 0)) + if(scrollToVisible): + self.textView.scrollRangeToVisible_(textRange) + + + + + def replace_current_block_with_string(self, textView, string): + textView.replaceCharactersInRange_withString_( + self.current_block_range(), + string) + self.current_block_range().length = len(string) + r = NSMakeRange(textView.textStorage().length(), 0) + textView.scrollRangeToVisible_(r) + textView.setSelectedRange_(r) + + + def current_indent_string(self): + """returns string for indent or None if no indent""" + + if(len(self.currentBlock()) > 0): + lines = self.currentBlock().split('\n') + currentIndent = len(lines[-1]) - len(lines[-1]) + if(currentIndent == 0): + currentIndent = self.tabSpaces + + if(self.tabUsesSpaces): + result = ' ' * currentIndent + else: + result = '\t' * (currentIndent/self.tabSpaces) + else: + result = None + + return result + + + # NSTextView delegate methods... def textView_doCommandBySelector_(self, textView, selector): assert(textView == self.textView) NSLog("textView_doCommandBySelector_: "+selector) if(selector == 'insertNewline:'): - indent = self.currentIndentString() + indent = self.current_indent_string() if(indent): line = indent + self.currentLine() else: @@ -187,7 +320,7 @@ class IPythonCocoaController(NSObject, FrontEndBase): if(self.is_complete(self.currentBlock())): self.execute(self.currentBlock(), blockID=self.currentBlockID) - self.startNewBlock() + self.start_new_block() return True @@ -196,7 +329,7 @@ class IPythonCocoaController(NSObject, FrontEndBase): elif(selector == 'moveUp:'): prevBlock = self.get_history_previous(self.currentBlock()) if(prevBlock != None): - self.replaceCurrentBlockWithString(textView, prevBlock) + self.replace_current_block_with_string(textView, prevBlock) else: NSBeep() return True @@ -204,30 +337,30 @@ class IPythonCocoaController(NSObject, FrontEndBase): elif(selector == 'moveDown:'): nextBlock = self.get_history_next() if(nextBlock != None): - self.replaceCurrentBlockWithString(textView, nextBlock) + self.replace_current_block_with_string(textView, nextBlock) else: NSBeep() return True elif(selector == 'moveToBeginningOfParagraph:'): textView.setSelectedRange_(NSMakeRange( - self.currentBlockRange().location, + self.current_block_range().location, 0)) return True elif(selector == 'moveToEndOfParagraph:'): textView.setSelectedRange_(NSMakeRange( - self.currentBlockRange().location + \ - self.currentBlockRange().length, 0)) + self.current_block_range().location + \ + self.current_block_range().length, 0)) return True elif(selector == 'deleteToEndOfParagraph:'): if(textView.selectedRange().location <= \ - self.currentBlockRange().location): + self.current_block_range().location): # Intersect the selected range with the current line range - if(self.currentBlockRange().length < 0): + if(self.current_block_range().length < 0): self.blockRanges[self.currentBlockID].length = 0 r = NSIntersectionRange(textView.rangesForUserTextChange()[0], - self.currentBlockRange()) + self.current_block_range()) if(r.length > 0): #no intersection textView.setSelectedRange_(r) @@ -244,10 +377,10 @@ class IPythonCocoaController(NSObject, FrontEndBase): elif(selector == 'deleteBackward:'): #if we're at the beginning of the current block, ignore if(textView.selectedRange().location == \ - self.currentBlockRange().location): + self.current_block_range().location): return True else: - self.currentBlockRange().length-=1 + self.current_block_range().length-=1 return False return False @@ -266,13 +399,13 @@ class IPythonCocoaController(NSObject, FrontEndBase): for r,s in zip(ranges, replacementStrings): r = r.rangeValue() if(textView.textStorage().length() > 0 and - r.location < self.currentBlockRange().location): + r.location < self.current_block_range().location): self.insert_text(s) allow = False self.blockRanges.setdefault(self.currentBlockID, - self.currentBlockRange()).length +=\ + self.current_block_range()).length +=\ len(s) return allow @@ -289,127 +422,4 @@ class IPythonCocoaController(NSObject, FrontEndBase): return (completions,0) - - def startNewBlock(self): - """""" - - self.currentBlockID = self.nextBlockID() - - - - def nextBlockID(self): - - return uuid.uuid4() - - def currentBlockRange(self): - return self.blockRanges.get(self.currentBlockID, - NSMakeRange(self.textView.textStorage().length(), - 0)) - - def currentBlock(self): - """The current block's text""" - - return self.textForRange(self.currentBlockRange()) - - def textForRange(self, textRange): - """textForRange""" - - ts = self.textView.textStorage() - return ts.string().substringWithRange_(textRange) - - def currentLine(self): - block = self.textForRange(self.currentBlockRange()) - block = block.split('\n') - return block[-1] - - def update_cell_prompt(self, result): - if(isinstance(result, Failure)): - blockID = result.blockID - else: - blockID = result['blockID'] - - - self.insert_text(self.input_prompt(result=result), - textRange=NSMakeRange(self.blockRanges[blockID].location,0), - scrollToVisible=False - ) - - return result - - - def render_result(self, result): - blockID = result['blockID'] - inputRange = self.blockRanges[blockID] - del self.blockRanges[blockID] - - #print inputRange,self.currentBlockRange() - self.insert_text('\n' + - self.output_prompt(result) + - result.get('display',{}).get('pprint','') + - '\n\n', - textRange=NSMakeRange(inputRange.location+inputRange.length, - 0)) - return result - - - def render_error(self, failure): - self.insert_text('\n\n'+str(failure)+'\n\n') - self.startNewBlock() - return failure - - - def insert_text(self, string=None, textRange=None, scrollToVisible=True): - """Insert text into textView at textRange, updating blockRanges - as necessary - """ - - if(textRange == None): - textRange = NSMakeRange(self.textView.textStorage().length(), 0) #range for end of text - - for r in self.blockRanges.itervalues(): - intersection = NSIntersectionRange(r,textRange) - if(intersection.length == 0): #ranges don't intersect - if r.location >= textRange.location: - r.location += len(string) - else: #ranges intersect - if(r.location <= textRange.location): - assert(intersection.length == textRange.length) - r.length += textRange.length - else: - r.location += intersection.length - - self.textView.replaceCharactersInRange_withString_(textRange, string) #textStorage().string() - self.textView.setSelectedRange_(NSMakeRange(textRange.location+len(string), 0)) - if(scrollToVisible): - self.textView.scrollRangeToVisible_(textRange) - - - - def replaceCurrentBlockWithString(self, textView, string): - textView.replaceCharactersInRange_withString_(self.currentBlockRange(), - string) - self.currentBlockRange().length = len(string) - r = NSMakeRange(textView.textStorage().length(), 0) - textView.scrollRangeToVisible_(r) - textView.setSelectedRange_(r) - - - def currentIndentString(self): - """returns string for indent or None if no indent""" - - if(len(self.currentBlock()) > 0): - lines = self.currentBlock().split('\n') - currentIndent = len(lines[-1]) - len(lines[-1]) - if(currentIndent == 0): - currentIndent = self.tabSpaces - - if(self.tabUsesSpaces): - result = ' ' * currentIndent - else: - result = '\t' * (currentIndent/self.tabSpaces) - else: - result = None - - return result -