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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import __builtin__
  5. import __main__
  6. import Queue
  7. import inspect
  8. import os
  9. import sys
  10. import thread
  11. import threading
  12. import time
  13. from signal import signal, SIGINT
  14.  
  15. try:
  16.     import ctypes
  17.     HAS_CTYPES = True
  18. except ImportError:
  19.     HAS_CTYPES = False
  20.  
  21. import IPython
  22. from IPython import ultraTB, ipapi
  23. from IPython.Magic import Magic
  24. from IPython.genutils import Term, warn, error, flag_calls, ask_yes_no
  25. from IPython.iplib import InteractiveShell
  26. from IPython.ipmaker import make_IPython
  27. from IPython.ipstruct import Struct
  28. from IPython.testing import decorators as testdec
  29. KBINT = False
  30. USE_TK = False
  31. MAIN_THREAD_ID = thread.get_ident()
  32. CODE_RUN = None
  33. GUI_TIMEOUT = 10
  34.  
  35. class IPShell:
  36.     
  37.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1, shell_class = InteractiveShell):
  38.         self.IP = make_IPython(argv, user_ns = user_ns, user_global_ns = user_global_ns, debug = debug, shell_class = shell_class)
  39.  
  40.     
  41.     def mainloop(self, sys_exit = 0, banner = None):
  42.         self.IP.mainloop(banner)
  43.         if sys_exit:
  44.             sys.exit()
  45.         
  46.  
  47.  
  48.  
  49. def kill_embedded(self, parameter_s = ''):
  50.     kill = ask_yes_no('Are you sure you want to kill this embedded instance (y/n)? [y/N] ', 'n')
  51.     if kill:
  52.         self.shell.embedded_active = False
  53.         print 'This embedded IPython will not reactivate anymore once you exit.'
  54.     
  55.  
  56.  
  57. class IPShellEmbed:
  58.     
  59.     def __init__(self, argv = None, banner = '', exit_msg = None, rc_override = None, user_ns = None):
  60.         self.set_banner(banner)
  61.         self.set_exit_msg(exit_msg)
  62.         self.set_dummy_mode(0)
  63.         self.sys_displayhook_ori = sys.displayhook
  64.         
  65.         try:
  66.             self.sys_ipcompleter_ori = sys.ipcompleter
  67.         except:
  68.             pass
  69.  
  70.         self.IP = make_IPython(argv, rc_override = rc_override, embedded = True, user_ns = user_ns)
  71.         ip = ipapi.IPApi(self.IP)
  72.         ip.expose_magic('kill_embedded', kill_embedded)
  73.         self.sys_displayhook_embed = sys.displayhook
  74.         sys.displayhook = self.sys_displayhook_ori
  75.         sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors, mode = self.IP.rc.xmode, call_pdb = self.IP.rc.pdb)
  76.         self.restore_system_completer()
  77.  
  78.     
  79.     def restore_system_completer(self):
  80.         
  81.         try:
  82.             self.IP.readline.set_completer(self.sys_ipcompleter_ori)
  83.             sys.ipcompleter = self.sys_ipcompleter_ori
  84.         except:
  85.             pass
  86.  
  87.  
  88.     
  89.     def __call__(self, header = '', local_ns = None, global_ns = None, dummy = None):
  90.         if not self.IP.embedded_active:
  91.             return None
  92.         self.IP.exit_now = False
  93.         if (dummy or dummy != 0) and self._IPShellEmbed__dummy_mode:
  94.             return None
  95.         sys.displayhook = self.sys_displayhook_embed
  96.         if self.banner and header:
  97.             format = '%s\n%s\n'
  98.         else:
  99.             format = '%s%s\n'
  100.         banner = format % (self.banner, header)
  101.         self.IP.embed_mainloop(banner, local_ns, global_ns, stack_depth = 1)
  102.         if self.exit_msg:
  103.             print self.exit_msg
  104.         
  105.         sys.displayhook = self.sys_displayhook_ori
  106.         self.restore_system_completer()
  107.  
  108.     
  109.     def set_dummy_mode(self, dummy):
  110.         if dummy not in [
  111.             0,
  112.             1,
  113.             False,
  114.             True]:
  115.             raise ValueError, 'dummy parameter must be boolean'
  116.         dummy not in [
  117.             0,
  118.             1,
  119.             False,
  120.             True]
  121.         self._IPShellEmbed__dummy_mode = dummy
  122.  
  123.     
  124.     def get_dummy_mode(self):
  125.         return self._IPShellEmbed__dummy_mode
  126.  
  127.     
  128.     def set_banner(self, banner):
  129.         self.banner = banner
  130.  
  131.     
  132.     def set_exit_msg(self, exit_msg):
  133.         self.exit_msg = exit_msg
  134.  
  135.  
  136. if HAS_CTYPES:
  137.     
  138.     def _async_raise(tid, exctype):
  139.         if not inspect.isclass(exctype):
  140.             raise TypeError('Only types can be raised (not instances)')
  141.         inspect.isclass(exctype)
  142.         res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
  143.         if res == 0:
  144.             raise ValueError('invalid thread id')
  145.         res == 0
  146.         if res != 1:
  147.             ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
  148.             raise SystemError('PyThreadState_SetAsyncExc failed')
  149.         res != 1
  150.  
  151.     
  152.     def sigint_handler(signum, stack_frame):
  153.         global KBINT
  154.         if CODE_RUN:
  155.             _async_raise(MAIN_THREAD_ID, KeyboardInterrupt)
  156.         else:
  157.             KBINT = True
  158.             print '\nKeyboardInterrupt - Press <Enter> to continue.',
  159.             Term.cout.flush()
  160.  
  161. else:
  162.     
  163.     def sigint_handler(signum, stack_frame):
  164.         global KBINT
  165.         print '\nKeyboardInterrupt - Press <Enter> to continue.',
  166.         Term.cout.flush()
  167.         KBINT = True
  168.  
  169.  
  170. class MTInteractiveShell(InteractiveShell):
  171.     isthreaded = True
  172.     
  173.     def __init__(self, name, usage = None, rc = Struct(opts = None, args = None), user_ns = None, user_global_ns = None, banner2 = '', gui_timeout = GUI_TIMEOUT, **kw):
  174.         InteractiveShell.__init__(self, name, usage, rc, user_ns, user_global_ns, banner2)
  175.         self.gui_timeout = gui_timeout
  176.         self.code_queue = Queue.Queue()
  177.         self._kill = None
  178.         on_kill = kw.get('on_kill', [])
  179.         for t in on_kill:
  180.             if not callable(t):
  181.                 raise TypeError, 'on_kill must be a list of callables'
  182.             callable(t)
  183.         
  184.         self.on_kill = on_kill
  185.         self.worker_ident = None
  186.  
  187.     
  188.     def runsource(self, source, filename = '<input>', symbol = 'single'):
  189.         global KBINT
  190.         if KBINT:
  191.             KBINT = False
  192.             return False
  193.         if self._kill:
  194.             return True
  195.         
  196.         try:
  197.             code = self.compile(source, filename, symbol)
  198.         except (OverflowError, SyntaxError, ValueError):
  199.             self._kill
  200.             self._kill
  201.             KBINT
  202.             self.showsyntaxerror(filename)
  203.             return False
  204.  
  205.         if code is None:
  206.             return True
  207.         if self.worker_ident is None or self.worker_ident == thread.get_ident():
  208.             InteractiveShell.runcode(self, code)
  209.             return False
  210.         completed_ev = threading.Event()
  211.         received_ev = threading.Event()
  212.         self.code_queue.put((code, completed_ev, received_ev))
  213.         received_ev.wait(self.gui_timeout)
  214.         return False
  215.  
  216.     
  217.     def runcode(self):
  218.         global CODE_RUN, CODE_RUN
  219.         self.worker_ident = thread.get_ident()
  220.         if self._kill:
  221.             print >>Term.cout, 'Closing threads...',
  222.             Term.cout.flush()
  223.             for tokill in self.on_kill:
  224.                 tokill()
  225.             
  226.             print >>Term.cout, 'Done.'
  227.             self._kill.set()
  228.             return True
  229.         
  230.         try:
  231.             signal(SIGINT, sigint_handler)
  232.         except SystemError:
  233.             self._kill
  234.             self._kill
  235.         except:
  236.             self._kill
  237.  
  238.         code_to_run = None
  239.         while None:
  240.             
  241.             try:
  242.                 (code_to_run, completed_ev, received_ev) = self.code_queue.get_nowait()
  243.             except Queue.Empty:
  244.                 self._kill
  245.                 self._kill
  246.                 break
  247.             except:
  248.                 self._kill
  249.  
  250.             
  251.             try:
  252.                 CODE_RUN = True
  253.                 InteractiveShell.runcode(self, code_to_run)
  254.             except KeyboardInterrupt:
  255.                 self._kill
  256.                 self._kill
  257.                 print 'Keyboard interrupted in mainloop'
  258.                 while not self.code_queue.empty():
  259.                     (code, ev1, ev2) = self.code_queue.get_nowait()
  260.                     ev1.set()
  261.                     ev2.set()
  262.                 break
  263.             except:
  264.                 self._kill
  265.             finally:
  266.                 CODE_RUN = False
  267.                 completed_ev.set()
  268.  
  269.             continue
  270.             return True
  271.  
  272.     
  273.     def kill(self):
  274.         self._kill = threading.Event()
  275.         self._kill.wait()
  276.  
  277.  
  278.  
  279. class MatplotlibShellBase:
  280.     
  281.     def _matplotlib_config(self, name, user_ns, user_global_ns = None):
  282.         import matplotlib
  283.         backends = backends
  284.         import matplotlib
  285.         matplotlib.interactive(True)
  286.         
  287.         def use(arg):
  288.             if arg in backends.interactive_bk and arg != self.mpl_backend:
  289.                 m = 'invalid matplotlib backend switch.\nThis script attempted to switch to the interactive backend: `%s`\nYour current choice of interactive backend is: `%s`\n\nSwitching interactive matplotlib backends at runtime\nwould crash the python interpreter, and IPython has blocked it.\n\nYou need to either change your choice of matplotlib backend\nby editing your .matplotlibrc file, or run this script as a \nstandalone file from the command line, not using IPython.\n' % (arg, self.mpl_backend)
  290.                 raise RuntimeError, m
  291.             arg != self.mpl_backend
  292.             self.mpl_use(arg)
  293.             self.mpl_use._called = True
  294.  
  295.         self.matplotlib = matplotlib
  296.         self.mpl_backend = matplotlib.rcParams['backend']
  297.         self.mpl_use = matplotlib.use
  298.         self.mpl_use._called = False
  299.         matplotlib.use = use
  300.         import matplotlib.pylab as pylab
  301.         self.pylab = pylab
  302.         self.pylab.show._needmain = False
  303.         self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
  304.         (user_ns, user_global_ns) = IPython.ipapi.make_user_namespaces(user_ns, user_global_ns)
  305.         exec 'import numpy\nimport numpy as np\nimport matplotlib\nimport matplotlib.pylab as pylab\ntry:\n    import matplotlib.pyplot as plt\nexcept ImportError:\n    pass\n' in user_ns
  306.         b = "\n  Welcome to pylab, a matplotlib-based Python environment.\n  For more information, type 'help(pylab)'.\n"
  307.         return (user_ns, user_global_ns, b)
  308.  
  309.     
  310.     def mplot_exec(self, fname, *where, **kw):
  311.         isInteractive = self.matplotlib.rcParams['interactive']
  312.         self.matplotlib.interactive(False)
  313.         self.safe_execfile(fname, *where, **kw)
  314.         self.matplotlib.interactive(isInteractive)
  315.         if self.pylab.draw_if_interactive.called:
  316.             self.pylab.draw()
  317.             self.pylab.draw_if_interactive.called = False
  318.         
  319.         if self.mpl_use._called:
  320.             self.matplotlib.rcParams['backend'] = self.mpl_backend
  321.         
  322.  
  323.     
  324.     def magic_run(self, parameter_s = ''):
  325.         Magic.magic_run(self, parameter_s, runner = self.mplot_exec)
  326.  
  327.     magic_run = testdec.skip_doctest(magic_run)
  328.     magic_run.__doc__ = '%s\n%s' % (Magic.magic_run.__doc__, '\n        *** Modified %run for Matplotlib, with proper interactive handling ***')
  329.  
  330.  
  331. class MatplotlibShell(MatplotlibShellBase, InteractiveShell):
  332.     
  333.     def __init__(self, name, usage = None, rc = Struct(opts = None, args = None), user_ns = None, user_global_ns = None, **kw):
  334.         (user_ns, user_global_ns, b2) = self._matplotlib_config(name, user_ns, user_global_ns)
  335.         InteractiveShell.__init__(self, name, usage, rc, user_ns, user_global_ns, banner2 = b2, **kw)
  336.  
  337.  
  338.  
  339. class MatplotlibMTShell(MatplotlibShellBase, MTInteractiveShell):
  340.     
  341.     def __init__(self, name, usage = None, rc = Struct(opts = None, args = None), user_ns = None, user_global_ns = None, **kw):
  342.         (user_ns, user_global_ns, b2) = self._matplotlib_config(name, user_ns, user_global_ns)
  343.         MTInteractiveShell.__init__(self, name, usage, rc, user_ns, user_global_ns, banner2 = b2, **kw)
  344.  
  345.  
  346.  
  347. def get_tk():
  348.     if not USE_TK or sys.modules.has_key('Tkinter'):
  349.         return None
  350.     
  351.     try:
  352.         import Tkinter
  353.     except ImportError:
  354.         sys.modules.has_key('Tkinter')
  355.         sys.modules.has_key('Tkinter')
  356.         return None
  357.  
  358.     hijack_tk()
  359.     r = Tkinter.Tk()
  360.     r.withdraw()
  361.     return r
  362.  
  363.  
  364. def hijack_tk():
  365.     
  366.     def misc_mainloop(self, n = 0):
  367.         pass
  368.  
  369.     
  370.     def tkinter_mainloop(n = 0):
  371.         pass
  372.  
  373.     import Tkinter
  374.     Tkinter.Misc.mainloop = misc_mainloop
  375.     Tkinter.mainloop = tkinter_mainloop
  376.  
  377.  
  378. def update_tk(tk):
  379.     if tk:
  380.         tk.update()
  381.     
  382.  
  383.  
  384. def hijack_wx():
  385.     
  386.     def dummy_mainloop(*args, **kw):
  387.         pass
  388.  
  389.     
  390.     try:
  391.         import wx
  392.     except ImportError:
  393.         import wxPython as wx
  394.  
  395.     ver = wx.__version__
  396.     orig_mainloop = None
  397.     if ver[:3] >= '2.5':
  398.         import wx
  399.         if hasattr(wx, '_core_'):
  400.             core = getattr(wx, '_core_')
  401.         elif hasattr(wx, '_core'):
  402.             core = getattr(wx, '_core')
  403.         else:
  404.             raise AttributeError('Could not find wx core module')
  405.         orig_mainloop = hasattr(wx, '_core_').PyApp_MainLoop
  406.         core.PyApp_MainLoop = dummy_mainloop
  407.     elif ver[:3] == '2.4':
  408.         orig_mainloop = wx.wxc.wxPyApp_MainLoop
  409.         wx.wxc.wxPyApp_MainLoop = dummy_mainloop
  410.     else:
  411.         warn('Unable to find either wxPython version 2.4 or >= 2.5.')
  412.     return orig_mainloop
  413.  
  414.  
  415. def hijack_gtk():
  416.     
  417.     def dummy_mainloop(*args, **kw):
  418.         pass
  419.  
  420.     import gtk
  421.     if gtk.pygtk_version >= (2, 4, 0):
  422.         orig_mainloop = gtk.main
  423.     else:
  424.         orig_mainloop = gtk.mainloop
  425.     gtk.mainloop = dummy_mainloop
  426.     gtk.main = dummy_mainloop
  427.     return orig_mainloop
  428.  
  429.  
  430. def hijack_qt():
  431.     
  432.     def dummy_mainloop(*args, **kw):
  433.         pass
  434.  
  435.     import qt
  436.     orig_mainloop = qt.qApp.exec_loop
  437.     qt.qApp.exec_loop = dummy_mainloop
  438.     qt.QApplication.exec_loop = dummy_mainloop
  439.     return orig_mainloop
  440.  
  441.  
  442. def hijack_qt4():
  443.     
  444.     def dummy_mainloop(*args, **kw):
  445.         pass
  446.  
  447.     QtGui = QtGui
  448.     QtCore = QtCore
  449.     import PyQt4
  450.     orig_mainloop = QtGui.qApp.exec_
  451.     QtGui.qApp.exec_ = dummy_mainloop
  452.     QtGui.QApplication.exec_ = dummy_mainloop
  453.     QtCore.QCoreApplication.exec_ = dummy_mainloop
  454.     return orig_mainloop
  455.  
  456.  
  457. class IPThread(threading.Thread):
  458.     
  459.     def run(self):
  460.         self.IP.mainloop(self._banner)
  461.         self.IP.kill()
  462.  
  463.  
  464.  
  465. class IPShellGTK(IPThread):
  466.     TIMEOUT = 100
  467.     
  468.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1, shell_class = MTInteractiveShell):
  469.         import gtk
  470.         
  471.         try:
  472.             gtk.set_interactive(False)
  473.             print 'Your PyGtk has set_interactive(), so you can use the'
  474.             print 'more stable single-threaded Gtk mode.'
  475.             print 'See https://bugs.launchpad.net/ipython/+bug/270856'
  476.         except AttributeError:
  477.             pass
  478.  
  479.         self.gtk = gtk
  480.         self.gtk_mainloop = hijack_gtk()
  481.         self.tk = get_tk()
  482.         if gtk.pygtk_version >= (2, 4, 0):
  483.             mainquit = self.gtk.main_quit
  484.         else:
  485.             mainquit = self.gtk.mainquit
  486.         self.IP = make_IPython(argv, user_ns = user_ns, user_global_ns = user_global_ns, debug = debug, shell_class = shell_class, on_kill = [
  487.             mainquit])
  488.         self._banner = None
  489.         threading.Thread.__init__(self)
  490.  
  491.     
  492.     def mainloop(self, sys_exit = 0, banner = None):
  493.         self._banner = banner
  494.         if self.gtk.pygtk_version >= (2, 4, 0):
  495.             import gobject
  496.             gobject.idle_add(self.on_timer)
  497.         else:
  498.             self.gtk.idle_add(self.on_timer)
  499.         if sys.platform != 'win32':
  500.             
  501.             try:
  502.                 if self.gtk.gtk_version[0] >= 2:
  503.                     self.gtk.gdk.threads_init()
  504.             except AttributeError:
  505.                 pass
  506.             except RuntimeError:
  507.                 error('Your pyGTK likely has not been compiled with threading support.\nThe exception printout is below.\nYou can either rebuild pyGTK with threads, or try using \nmatplotlib with a different backend (like Tk or WX).\nNote that matplotlib will most likely not work in its current state!')
  508.                 self.IP.InteractiveTB()
  509.             except:
  510.                 None<EXCEPTION MATCH>AttributeError
  511.             
  512.  
  513.         None<EXCEPTION MATCH>AttributeError
  514.         self.start()
  515.         self.gtk.gdk.threads_enter()
  516.         self.gtk_mainloop()
  517.         self.gtk.gdk.threads_leave()
  518.         self.join()
  519.  
  520.     
  521.     def on_timer(self):
  522.         update_tk(self.tk)
  523.         self.IP.runcode()
  524.         time.sleep(0.01)
  525.         return True
  526.  
  527.  
  528.  
  529. class IPShellWX(IPThread):
  530.     TIMEOUT = 100
  531.     
  532.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1, shell_class = MTInteractiveShell):
  533.         self.IP = make_IPython(argv, user_ns = user_ns, user_global_ns = user_global_ns, debug = debug, shell_class = shell_class, on_kill = [
  534.             self.wxexit])
  535.         wantedwxversion = self.IP.rc.wxversion
  536.         if wantedwxversion != '0':
  537.             
  538.             try:
  539.                 import wxversion
  540.             except ImportError:
  541.                 error('The wxversion module is needed for WX version selection')
  542.  
  543.             
  544.             try:
  545.                 wxversion.select(wantedwxversion)
  546.             self.IP.InteractiveTB()
  547.             error('Requested wxPython version %s could not be loaded' % wantedwxversion)
  548.  
  549.         
  550.         import wx
  551.         threading.Thread.__init__(self)
  552.         self.wx = wx
  553.         self.wx_mainloop = hijack_wx()
  554.         self.tk = get_tk()
  555.         self._banner = None
  556.         self.app = None
  557.  
  558.     
  559.     def wxexit(self, *args):
  560.         if self.app is not None:
  561.             self.app.agent.timer.Stop()
  562.             self.app.ExitMainLoop()
  563.         
  564.  
  565.     
  566.     def mainloop(self, sys_exit = 0, banner = None):
  567.         self._banner = banner
  568.         self.start()
  569.         
  570.         class TimerAgent((self.wx.MiniFrame,)):
  571.             wx = self.wx
  572.             IP = self.IP
  573.             tk = self.tk
  574.             
  575.             def __init__(self, parent, interval):
  576.                 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
  577.                 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos = (200, 200), size = (100, 100), style = style)
  578.                 self.Show(False)
  579.                 self.interval = interval
  580.                 self.timerId = self.wx.NewId()
  581.  
  582.             
  583.             def StartWork(self):
  584.                 self.timer = self.wx.Timer(self, self.timerId)
  585.                 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
  586.                 self.timer.Start(self.interval)
  587.  
  588.             
  589.             def OnTimer(self, event):
  590.                 update_tk(self.tk)
  591.                 self.IP.runcode()
  592.  
  593.  
  594.         
  595.         class App('App', (self.wx.App,)):
  596.             wx = self.wx
  597.             TIMEOUT = self.TIMEOUT
  598.             
  599.             def OnInit(self):
  600.                 self.agent = TimerAgent(None, self.TIMEOUT)
  601.                 self.agent.Show(False)
  602.                 self.agent.StartWork()
  603.                 return True
  604.  
  605.  
  606.         self.app = App(redirect = False)
  607.         self.wx_mainloop(self.app)
  608.         self.join()
  609.  
  610.  
  611.  
  612. class IPShellQt(IPThread):
  613.     TIMEOUT = 100
  614.     
  615.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 0, shell_class = MTInteractiveShell):
  616.         import qt
  617.         self.exec_loop = hijack_qt()
  618.         self.tk = get_tk()
  619.         self.IP = make_IPython(argv, user_ns = user_ns, user_global_ns = user_global_ns, debug = debug, shell_class = shell_class, on_kill = [
  620.             qt.qApp.exit])
  621.         self._banner = None
  622.         threading.Thread.__init__(self)
  623.  
  624.     
  625.     def mainloop(self, sys_exit = 0, banner = None):
  626.         import qt
  627.         self._banner = banner
  628.         if qt.QApplication.startingUp():
  629.             a = qt.QApplication(sys.argv)
  630.         
  631.         self.timer = qt.QTimer()
  632.         qt.QObject.connect(self.timer, qt.SIGNAL('timeout()'), self.on_timer)
  633.         self.start()
  634.         self.timer.start(self.TIMEOUT, True)
  635.         while True:
  636.             if self.IP._kill:
  637.                 break
  638.             
  639.             self.exec_loop()
  640.         self.join()
  641.  
  642.     
  643.     def on_timer(self):
  644.         update_tk(self.tk)
  645.         result = self.IP.runcode()
  646.         self.timer.start(self.TIMEOUT, True)
  647.         return result
  648.  
  649.  
  650.  
  651. class IPShellQt4(IPThread):
  652.     TIMEOUT = 100
  653.     
  654.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 0, shell_class = MTInteractiveShell):
  655.         QtCore = QtCore
  656.         QtGui = QtGui
  657.         import PyQt4
  658.         
  659.         try:
  660.             QtCore.pyqtRemoveInputHook()
  661.         except AttributeError:
  662.             pass
  663.  
  664.         if QtCore.PYQT_VERSION_STR == '4.3':
  665.             warn('PyQt4 version 4.3 detected.\nIf you experience repeated threading warnings, please update PyQt4.\n')
  666.         
  667.         self.exec_ = hijack_qt4()
  668.         self.tk = get_tk()
  669.         self.IP = make_IPython(argv, user_ns = user_ns, user_global_ns = user_global_ns, debug = debug, shell_class = shell_class, on_kill = [
  670.             QtGui.qApp.exit])
  671.         self._banner = None
  672.         threading.Thread.__init__(self)
  673.  
  674.     
  675.     def mainloop(self, sys_exit = 0, banner = None):
  676.         QtCore = QtCore
  677.         QtGui = QtGui
  678.         import PyQt4
  679.         self._banner = banner
  680.         if QtGui.QApplication.startingUp():
  681.             a = QtGui.QApplication(sys.argv)
  682.         
  683.         self.timer = QtCore.QTimer()
  684.         QtCore.QObject.connect(self.timer, QtCore.SIGNAL('timeout()'), self.on_timer)
  685.         self.start()
  686.         self.timer.start(self.TIMEOUT)
  687.         while True:
  688.             if self.IP._kill:
  689.                 break
  690.             
  691.             self.exec_()
  692.         self.join()
  693.  
  694.     
  695.     def on_timer(self):
  696.         update_tk(self.tk)
  697.         result = self.IP.runcode()
  698.         self.timer.start(self.TIMEOUT)
  699.         return result
  700.  
  701.  
  702.  
  703. def _load_pylab(user_ns):
  704.     ip = IPython.ipapi.get()
  705.     if ip.options.pylab_import_all:
  706.         ip.ex('from matplotlib.pylab import *')
  707.         ip.IP.user_config_ns.update(ip.user_ns)
  708.     
  709.  
  710.  
  711. class IPShellMatplotlib(IPShell):
  712.     
  713.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1):
  714.         IPShell.__init__(self, argv, user_ns, user_global_ns, debug, shell_class = MatplotlibShell)
  715.         _load_pylab(self.IP.user_ns)
  716.  
  717.  
  718.  
  719. class IPShellMatplotlibGTK(IPShellGTK):
  720.     
  721.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1):
  722.         IPShellGTK.__init__(self, argv, user_ns, user_global_ns, debug, shell_class = MatplotlibMTShell)
  723.         _load_pylab(self.IP.user_ns)
  724.  
  725.  
  726.  
  727. class IPShellMatplotlibWX(IPShellWX):
  728.     
  729.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1):
  730.         IPShellWX.__init__(self, argv, user_ns, user_global_ns, debug, shell_class = MatplotlibMTShell)
  731.         _load_pylab(self.IP.user_ns)
  732.  
  733.  
  734.  
  735. class IPShellMatplotlibQt(IPShellQt):
  736.     
  737.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1):
  738.         IPShellQt.__init__(self, argv, user_ns, user_global_ns, debug, shell_class = MatplotlibMTShell)
  739.         _load_pylab(self.IP.user_ns)
  740.  
  741.  
  742.  
  743. class IPShellMatplotlibQt4(IPShellQt4):
  744.     
  745.     def __init__(self, argv = None, user_ns = None, user_global_ns = None, debug = 1):
  746.         IPShellQt4.__init__(self, argv, user_ns, user_global_ns, debug, shell_class = MatplotlibMTShell)
  747.         _load_pylab(self.IP.user_ns)
  748.  
  749.  
  750.  
  751. def _select_shell(argv):
  752.     global USE_TK
  753.     mpl_shell = {
  754.         'gthread': IPShellMatplotlibGTK,
  755.         'wthread': IPShellMatplotlibWX,
  756.         'qthread': IPShellMatplotlibQt,
  757.         'q4thread': IPShellMatplotlibQt4,
  758.         'tkthread': IPShellMatplotlib }
  759.     th_shell = {
  760.         'gthread': IPShellGTK,
  761.         'wthread': IPShellWX,
  762.         'qthread': IPShellQt,
  763.         'q4thread': IPShellQt4,
  764.         'tkthread': IPShell }
  765.     backends = {
  766.         'gthread': 'GTKAgg',
  767.         'wthread': 'WXAgg',
  768.         'qthread': 'QtAgg',
  769.         'q4thread': 'Qt4Agg',
  770.         'tkthread': 'TkAgg' }
  771.     all_opts = set([
  772.         'tk',
  773.         'pylab',
  774.         'gthread',
  775.         'qthread',
  776.         'q4thread',
  777.         'wthread',
  778.         'tkthread'])
  779.     user_opts = []([ s.replace('-', '') for s in argv[:3] ])
  780.     special_opts = user_opts & all_opts
  781.     if 'pylab' in special_opts:
  782.         
  783.         try:
  784.             import matplotlib
  785.         except ImportError:
  786.             None if 'tk' in special_opts else set
  787.             None if 'tk' in special_opts else set
  788.             error('matplotlib could NOT be imported!  Starting normal IPython.')
  789.             return IPShell
  790.  
  791.         special_opts.remove('pylab')
  792.         if special_opts:
  793.             th_mode = special_opts.pop()
  794.             matplotlib.rcParams['backend'] = backends[th_mode]
  795.         else:
  796.             backend = matplotlib.rcParams['backend']
  797.             if backend.startswith('GTK'):
  798.                 th_mode = 'gthread'
  799.             elif backend.startswith('WX'):
  800.                 th_mode = 'wthread'
  801.             elif backend.startswith('Qt4'):
  802.                 th_mode = 'q4thread'
  803.             elif backend.startswith('Qt'):
  804.                 th_mode = 'qthread'
  805.             else:
  806.                 th_mode = 'tkthread'
  807.         return mpl_shell[th_mode]
  808.     
  809.     try:
  810.         th_mode = special_opts.pop()
  811.     except KeyError:
  812.         'pylab' in special_opts
  813.         'pylab' in special_opts
  814.         None if 'tk' in special_opts else set
  815.         th_mode = 'tkthread'
  816.     except:
  817.         'pylab' in special_opts
  818.  
  819.     return th_shell[th_mode]
  820.  
  821.  
  822. def start(user_ns = None):
  823.     shell = _select_shell(sys.argv)
  824.     return shell(user_ns = user_ns)
  825.  
  826. IPythonShell = IPShell
  827. IPythonShellEmbed = IPShellEmbed
  828.