home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_1794 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  15.2 KB  |  397 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __docformat__ = 'restructuredtext en'
  5. import sys
  6. import objc
  7. from IPython.external import guid
  8. from Foundation import NSObject, NSMutableArray, NSMutableDictionary, NSLog, NSNotificationCenter, NSMakeRange, NSLocalizedString, NSIntersectionRange, NSString, NSAutoreleasePool
  9. from AppKit import NSApplicationWillTerminateNotification, NSBeep, NSTextView, NSRulerView, NSVerticalRuler
  10. from pprint import saferepr
  11. import IPython
  12. from IPython.kernel.engineservice import ThreadedEngineService
  13. from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase
  14. from twisted.internet.threads import blockingCallFromThread
  15. from twisted.python.failure import Failure
  16.  
  17. class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService):
  18.     
  19.     def wrapped_execute(self, msg, lines):
  20.         
  21.         try:
  22.             p = NSAutoreleasePool.alloc().init()
  23.             result = super(AutoreleasePoolWrappedThreadedEngineService, self).wrapped_execute(msg, lines)
  24.         finally:
  25.             p.drain()
  26.  
  27.         return result
  28.  
  29.  
  30.  
  31. class Cell(NSObject):
  32.     blockNumber = objc.ivar().unsigned_long()
  33.     blockID = objc.ivar()
  34.     inputBlock = objc.ivar()
  35.     output = objc.ivar()
  36.  
  37.  
  38. class CellBlock(object):
  39.     
  40.     def __init__(self, inputPromptRange, inputRange = None, outputPromptRange = None, outputRange = None):
  41.         super(CellBlock, self).__init__()
  42.         self.inputPromptRange = inputPromptRange
  43.         self.inputRange = inputRange
  44.         self.outputPromptRange = outputPromptRange
  45.         self.outputRange = outputRange
  46.  
  47.     
  48.     def update_ranges_for_insertion(self, text, textRange):
  49.         for r in [
  50.             self.inputPromptRange,
  51.             self.inputRange,
  52.             self.outputPromptRange,
  53.             self.outputRange]:
  54.             if r == None:
  55.                 continue
  56.             
  57.             intersection = NSIntersectionRange(r, textRange)
  58.             if intersection.length == 0:
  59.                 if r.location >= textRange.location:
  60.                     r.location += len(text)
  61.                 
  62.             r.location >= textRange.location
  63.             if r.location > textRange.location:
  64.                 offset = len(text) - intersection.length
  65.                 r.length -= offset
  66.                 r.location += offset
  67.                 continue
  68.             r
  69.             if r.location == textRange.location:
  70.                 r.length += len(text) - intersection.length
  71.                 continue
  72.             r
  73.             r.length -= intersection.length
  74.         
  75.  
  76.     
  77.     def update_ranges_for_deletion(self, textRange):
  78.         for r in [
  79.             self.inputPromptRange,
  80.             self.inputRange,
  81.             self.outputPromptRange,
  82.             self.outputRange]:
  83.             if r == None:
  84.                 continue
  85.             
  86.             intersection = NSIntersectionRange(r, textRange)
  87.             if intersection.length == 0:
  88.                 if r.location >= textRange.location:
  89.                     r.location -= textRange.length
  90.                 
  91.             r.location >= textRange.location
  92.             if r.location > textRange.location:
  93.                 offset = intersection.length
  94.                 r.length -= offset
  95.                 r.location += offset
  96.                 continue
  97.             r
  98.             if r.location == textRange.location:
  99.                 r.length += intersection.length
  100.                 continue
  101.             r
  102.             r.length -= intersection.length
  103.         
  104.  
  105.     
  106.     def __repr__(self):
  107.         return 'CellBlock(' + str((self.inputPromptRange, self.inputRange, self.outputPromptRange, self.outputRange)) + ')'
  108.  
  109.  
  110.  
  111. class IPythonCocoaController(NSObject, AsyncFrontEndBase):
  112.     userNS = objc.ivar()
  113.     waitingForEngine = objc.ivar().bool()
  114.     textView = objc.IBOutlet()
  115.     
  116.     def init(self):
  117.         self = super(IPythonCocoaController, self).init()
  118.         AsyncFrontEndBase.__init__(self, engine = AutoreleasePoolWrappedThreadedEngineService())
  119.         if self != None:
  120.             self._common_init()
  121.         
  122.         return self
  123.  
  124.     
  125.     def _common_init(self):
  126.         self.userNS = NSMutableDictionary.dictionary()
  127.         self.waitingForEngine = False
  128.         self.lines = { }
  129.         self.tabSpaces = 4
  130.         self.tabUsesSpaces = True
  131.         self.currentBlockID = self.next_block_ID()
  132.         self.blockRanges = { }
  133.  
  134.     
  135.     def awakeFromNib(self):
  136.         self._common_init()
  137.         self.engine.startService()
  138.         NSLog('IPython engine started')
  139.         nc = NSNotificationCenter.defaultCenter()
  140.         nc.addObserver_selector_name_object_(self, 'appWillTerminate:', NSApplicationWillTerminateNotification, None)
  141.         self.textView.setDelegate_(self)
  142.         self.textView.enclosingScrollView().setHasVerticalRuler_(True)
  143.         r = NSRulerView.alloc().initWithScrollView_orientation_(self.textView.enclosingScrollView(), NSVerticalRuler)
  144.         self.verticalRulerView = r
  145.         self.verticalRulerView.setClientView_(self.textView)
  146.         self._start_cli_banner()
  147.         self.start_new_block()
  148.  
  149.     
  150.     def appWillTerminate_(self, notification):
  151.         self.engine.stopService()
  152.  
  153.     
  154.     def complete(self, token):
  155.         return self.engine.complete(token)
  156.  
  157.     
  158.     def execute(self, block, blockID = None):
  159.         self.waitingForEngine = True
  160.         self.willChangeValueForKey_('commandHistory')
  161.         d = super(IPythonCocoaController, self).execute(block, blockID)
  162.         d.addBoth(self._engine_done)
  163.         d.addCallback(self._update_user_ns)
  164.         return d
  165.  
  166.     
  167.     def push_(self, namespace):
  168.         self.waitingForEngine = True
  169.         self.willChangeValueForKey_('commandHistory')
  170.         d = self.engine.push(namespace)
  171.         d.addBoth(self._engine_done)
  172.         d.addCallback(self._update_user_ns)
  173.  
  174.     
  175.     def pull_(self, keys):
  176.         self.waitingForEngine = True
  177.         result = blockingCallFromThread(self.engine.pull, keys)
  178.         self.waitingForEngine = False
  179.  
  180.     
  181.     def executeFileAtPath_encoding_(self, path, encoding):
  182.         (lines, err) = NSString.stringWithContentsOfFile_encoding_error_(path, encoding, None)
  183.         self.engine.execute(lines)
  184.  
  185.     executeFileAtPath_encoding_ = objc.signature('v@:@I')(executeFileAtPath_encoding_)
  186.     
  187.     def _engine_done(self, x):
  188.         self.waitingForEngine = False
  189.         self.didChangeValueForKey_('commandHistory')
  190.         return x
  191.  
  192.     
  193.     def _update_user_ns(self, result):
  194.         d = self.engine.keys()
  195.         d.addCallback(self._get_engine_namespace_values_for_keys)
  196.         return result
  197.  
  198.     
  199.     def _get_engine_namespace_values_for_keys(self, keys):
  200.         d = self.engine.pull(keys)
  201.         d.addCallback(self._store_engine_namespace_values, keys = keys)
  202.  
  203.     
  204.     def _store_engine_namespace_values(self, values, keys = []):
  205.         self.willChangeValueForKey_('userNS')
  206.         for k, v in zip(keys, values):
  207.             self.userNS[k] = saferepr(v)
  208.         
  209.         self.didChangeValueForKey_('userNS')
  210.  
  211.     
  212.     def update_cell_prompt(self, result, blockID = None):
  213.         print self.blockRanges
  214.         if isinstance(result, Failure):
  215.             prompt = self.input_prompt()
  216.         else:
  217.             prompt = self.input_prompt(number = result['number'])
  218.         r = self.blockRanges[blockID].inputPromptRange
  219.         self.insert_text(prompt, textRange = r, scrollToVisible = False)
  220.         return result
  221.  
  222.     
  223.     def render_result(self, result):
  224.         blockID = result['blockID']
  225.         inputRange = self.blockRanges[blockID].inputRange
  226.         del self.blockRanges[blockID]
  227.         self.insert_text('\n' + self.output_prompt(number = result['number']) + result.get('display', { }).get('pprint', '') + '\n\n', textRange = NSMakeRange(inputRange.location + inputRange.length, 0))
  228.         return result
  229.  
  230.     
  231.     def render_error(self, failure):
  232.         print failure
  233.         blockID = failure.blockID
  234.         inputRange = self.blockRanges[blockID].inputRange
  235.         self.insert_text('\n' + self.output_prompt() + '\n' + failure.getErrorMessage() + '\n\n', textRange = NSMakeRange(inputRange.location + inputRange.length, 0))
  236.         self.start_new_block()
  237.         return failure
  238.  
  239.     
  240.     def _start_cli_banner(self):
  241.         banner = 'IPython1 %s -- An enhanced Interactive Python.' % IPython.__version__
  242.         self.insert_text(banner + '\n\n')
  243.  
  244.     
  245.     def start_new_block(self):
  246.         self.currentBlockID = self.next_block_ID()
  247.         self.blockRanges[self.currentBlockID] = self.new_cell_block()
  248.         self.insert_text(self.input_prompt(), textRange = self.current_block_range().inputPromptRange)
  249.  
  250.     
  251.     def next_block_ID(self):
  252.         return guid.generate()
  253.  
  254.     
  255.     def new_cell_block(self):
  256.         return CellBlock(NSMakeRange(self.textView.textStorage().length(), 0), NSMakeRange(self.textView.textStorage().length(), 0))
  257.  
  258.     
  259.     def current_block_range(self):
  260.         return self.blockRanges.get(self.currentBlockID, self.new_cell_block())
  261.  
  262.     
  263.     def current_block(self):
  264.         return self.text_for_range(self.current_block_range().inputRange)
  265.  
  266.     
  267.     def text_for_range(self, textRange):
  268.         ts = self.textView.textStorage()
  269.         return ts.string().substringWithRange_(textRange)
  270.  
  271.     
  272.     def current_line(self):
  273.         block = self.text_for_range(self.current_block_range().inputRange)
  274.         block = block.split('\n')
  275.         return block[-1]
  276.  
  277.     
  278.     def insert_text(self, string = None, textRange = None, scrollToVisible = True):
  279.         if textRange == None:
  280.             textRange = NSMakeRange(self.textView.textStorage().length(), 0)
  281.         
  282.         self.textView.replaceCharactersInRange_withString_(textRange, string)
  283.         for r in self.blockRanges.itervalues():
  284.             r.update_ranges_for_insertion(string, textRange)
  285.         
  286.         self.textView.setSelectedRange_(textRange)
  287.         if scrollToVisible:
  288.             self.textView.scrollRangeToVisible_(textRange)
  289.         
  290.  
  291.     
  292.     def replace_current_block_with_string(self, textView, string):
  293.         textView.replaceCharactersInRange_withString_(self.current_block_range().inputRange, string)
  294.         self.current_block_range().inputRange.length = len(string)
  295.         r = NSMakeRange(textView.textStorage().length(), 0)
  296.         textView.scrollRangeToVisible_(r)
  297.         textView.setSelectedRange_(r)
  298.  
  299.     
  300.     def current_indent_string(self):
  301.         return self._indent_for_block(self.current_block())
  302.  
  303.     
  304.     def _indent_for_block(self, block):
  305.         lines = block.split('\n')
  306.         if len(lines) > 1:
  307.             currentIndent = len(lines[-1]) - len(lines[-1].lstrip())
  308.             if currentIndent == 0:
  309.                 currentIndent = self.tabSpaces
  310.             
  311.             if self.tabUsesSpaces:
  312.                 result = ' ' * currentIndent
  313.             else:
  314.                 result = '\t' * (currentIndent / self.tabSpaces)
  315.         else:
  316.             result = None
  317.         return result
  318.  
  319.     
  320.     def textView_doCommandBySelector_(self, textView, selector):
  321.         NSLog('textView_doCommandBySelector_: ' + selector)
  322.         if selector == 'insertNewline:':
  323.             indent = self.current_indent_string()
  324.             if indent:
  325.                 line = indent + self.current_line()
  326.             else:
  327.                 line = self.current_line()
  328.             if self.is_complete(self.current_block()):
  329.                 self.execute(self.current_block(), blockID = self.currentBlockID)
  330.                 self.start_new_block()
  331.                 return True
  332.             return False
  333.         if selector == 'moveUp:':
  334.             prevBlock = self.get_history_previous(self.current_block())
  335.             if prevBlock != None:
  336.                 self.replace_current_block_with_string(textView, prevBlock)
  337.             else:
  338.                 NSBeep()
  339.             return True
  340.         if selector == 'moveDown:':
  341.             nextBlock = self.get_history_next()
  342.             return True
  343.         if selector == 'moveToBeginningOfParagraph:':
  344.             textView.setSelectedRange_(NSMakeRange(self.current_block_range().inputRange.location, 0))
  345.             return True
  346.         if selector == 'moveToEndOfParagraph:':
  347.             textView.setSelectedRange_(NSMakeRange(self.current_block_range().inputRange.location + self.current_block_range().inputRange.length, 0))
  348.             return True
  349.         if selector == 'deleteToEndOfParagraph:':
  350.             if textView.selectedRange().location <= self.current_block_range().location:
  351.                 raise NotImplemented()
  352.             textView.selectedRange().location <= self.current_block_range().location
  353.             return False
  354.         if selector == 'insertTab:':
  355.             if len(self.current_line().strip()) == 0:
  356.                 return False
  357.             self.textView.complete_(self)
  358.             return True
  359.         selector == 'insertTab:'
  360.         if selector == 'deleteBackward:':
  361.             if textView.selectedRange().location == self.current_block_range().inputRange.location:
  362.                 return True
  363.             for r in self.blockRanges.itervalues():
  364.                 deleteRange = textView.selectedRange
  365.                 r.update_ranges_for_deletion(deleteRange)
  366.             
  367.             return False
  368.         selector == 'deleteBackward:'
  369.         return False
  370.  
  371.     
  372.     def textView_shouldChangeTextInRanges_replacementStrings_(self, textView, ranges, replacementStrings):
  373.         allow = True
  374.         for r, s in zip(ranges, replacementStrings):
  375.             r = r.rangeValue()
  376.             if textView.textStorage().length() > 0 and r.location < self.current_block_range().inputRange.location:
  377.                 self.insert_text(s)
  378.                 allow = False
  379.                 continue
  380.         
  381.         return allow
  382.  
  383.     
  384.     def textView_completions_forPartialWordRange_indexOfSelectedItem_(self, textView, words, charRange, index):
  385.         
  386.         try:
  387.             ts = textView.textStorage()
  388.             token = ts.string().substringWithRange_(charRange)
  389.             completions = blockingCallFromThread(self.complete, token)
  390.         except:
  391.             completions = objc.nil
  392.             NSBeep()
  393.  
  394.         return (completions, 0)
  395.  
  396.  
  397.