app.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. # App.py
  2. # Application stuff.
  3. # The application is responsible for managing the main frame window.
  4. #
  5. # We also grab the FileOpen command, to invoke our Python editor
  6. " The PythonWin application code. Manages most aspects of MDI, etc "
  7. import win32con
  8. import win32api
  9. import win32ui
  10. import sys
  11. import string
  12. import os
  13. from pywin.mfc import window, dialog, afxres
  14. from pywin.mfc.thread import WinApp
  15. import traceback
  16. import regutil
  17. from . import scriptutils
  18. ## NOTE: App and AppBuild should NOT be used - instead, you should contruct your
  19. ## APP class manually whenever you like (just ensure you leave these 2 params None!)
  20. ## Whoever wants the generic "Application" should get it via win32iu.GetApp()
  21. # These are "legacy"
  22. AppBuilder = None
  23. App = None # default - if used, must end up a CApp derived class.
  24. # Helpers that should one day be removed!
  25. def AddIdleHandler(handler):
  26. print("app.AddIdleHandler is deprecated - please use win32ui.GetApp().AddIdleHandler() instead.")
  27. return win32ui.GetApp().AddIdleHandler(handler)
  28. def DeleteIdleHandler(handler):
  29. print("app.DeleteIdleHandler is deprecated - please use win32ui.GetApp().DeleteIdleHandler() instead.")
  30. return win32ui.GetApp().DeleteIdleHandler(handler)
  31. # Helper for writing a Window position by name, and later loading it.
  32. def SaveWindowSize(section,rect,state=""):
  33. """ Writes a rectangle to an INI file
  34. Args: section = section name in the applications INI file
  35. rect = a rectangle in a (cy, cx, y, x) tuple
  36. (same format as CREATESTRUCT position tuples)."""
  37. left, top, right, bottom = rect
  38. if state: state = state + " "
  39. win32ui.WriteProfileVal(section,state+"left",left)
  40. win32ui.WriteProfileVal(section,state+"top",top)
  41. win32ui.WriteProfileVal(section,state+"right",right)
  42. win32ui.WriteProfileVal(section,state+"bottom",bottom)
  43. def LoadWindowSize(section, state=""):
  44. """ Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize)"""
  45. if state: state = state + " "
  46. left = win32ui.GetProfileVal(section,state+"left",0)
  47. top = win32ui.GetProfileVal(section,state+"top",0)
  48. right = win32ui.GetProfileVal(section,state+"right",0)
  49. bottom = win32ui.GetProfileVal(section,state+"bottom",0)
  50. return (left, top, right, bottom)
  51. def RectToCreateStructRect(rect):
  52. return (rect[3]-rect[1], rect[2]-rect[0], rect[1], rect[0] )
  53. # Define FrameWindow and Application objects
  54. #
  55. # The Main Frame of the application.
  56. class MainFrame(window.MDIFrameWnd):
  57. sectionPos = "Main Window"
  58. statusBarIndicators = ( afxres.ID_SEPARATOR, #// status line indicator
  59. afxres.ID_INDICATOR_CAPS,
  60. afxres.ID_INDICATOR_NUM,
  61. afxres.ID_INDICATOR_SCRL,
  62. win32ui.ID_INDICATOR_LINENUM,
  63. win32ui.ID_INDICATOR_COLNUM )
  64. def OnCreate(self, cs):
  65. self._CreateStatusBar()
  66. return 0
  67. def _CreateStatusBar(self):
  68. self.statusBar = win32ui.CreateStatusBar(self)
  69. self.statusBar.SetIndicators(self.statusBarIndicators)
  70. self.HookCommandUpdate(self.OnUpdatePosIndicator, win32ui.ID_INDICATOR_LINENUM)
  71. self.HookCommandUpdate(self.OnUpdatePosIndicator, win32ui.ID_INDICATOR_COLNUM)
  72. def OnUpdatePosIndicator(self, cmdui):
  73. editControl = scriptutils.GetActiveEditControl()
  74. value = " " * 5
  75. if editControl is not None:
  76. try:
  77. startChar, endChar = editControl.GetSel()
  78. lineNo = editControl.LineFromChar(startChar)
  79. colNo = endChar - editControl.LineIndex(lineNo)
  80. if cmdui.m_nID==win32ui.ID_INDICATOR_LINENUM:
  81. value = "%0*d" % (5, lineNo + 1)
  82. else:
  83. value = "%0*d" % (3, colNo + 1)
  84. except win32ui.error:
  85. pass
  86. cmdui.SetText(value)
  87. cmdui.Enable()
  88. def PreCreateWindow(self, cc):
  89. cc = self._obj_.PreCreateWindow(cc)
  90. pos = LoadWindowSize(self.sectionPos)
  91. self.startRect = pos
  92. if pos[2] - pos[0]:
  93. rect = RectToCreateStructRect(pos)
  94. cc = cc[0], cc[1], cc[2], cc[3], rect, cc[5], cc[6], cc[7], cc[8]
  95. return cc
  96. def OnDestroy(self, msg):
  97. # use GetWindowPlacement(), as it works even when min'd or max'd
  98. rectNow = self.GetWindowPlacement()[4]
  99. if rectNow != self.startRect:
  100. SaveWindowSize(self.sectionPos, rectNow)
  101. return 0
  102. class CApp(WinApp):
  103. " A class for the application "
  104. def __init__(self):
  105. self.oldCallbackCaller = None
  106. WinApp.__init__(self, win32ui.GetApp() )
  107. self.idleHandlers = []
  108. def InitInstance(self):
  109. " Called to crank up the app "
  110. HookInput()
  111. numMRU = win32ui.GetProfileVal("Settings","Recent File List Size", 10)
  112. win32ui.LoadStdProfileSettings(numMRU)
  113. # self._obj_.InitMDIInstance()
  114. if win32api.GetVersionEx()[0]<4:
  115. win32ui.SetDialogBkColor()
  116. win32ui.Enable3dControls()
  117. # install a "callback caller" - a manager for the callbacks
  118. # self.oldCallbackCaller = win32ui.InstallCallbackCaller(self.CallbackManager)
  119. self.LoadMainFrame()
  120. self.SetApplicationPaths()
  121. def ExitInstance(self):
  122. " Called as the app dies - too late to prevent it here! "
  123. win32ui.OutputDebug("Application shutdown\n")
  124. # Restore the callback manager, if any.
  125. try:
  126. win32ui.InstallCallbackCaller(self.oldCallbackCaller)
  127. except AttributeError:
  128. pass
  129. if self.oldCallbackCaller:
  130. del self.oldCallbackCaller
  131. self.frame=None # clean Python references to the now destroyed window object.
  132. self.idleHandlers = []
  133. # Attempt cleanup if not already done!
  134. if self._obj_: self._obj_.AttachObject(None)
  135. self._obj_ = None
  136. global App
  137. global AppBuilder
  138. App = None
  139. AppBuilder = None
  140. return 0
  141. def HaveIdleHandler(self, handler):
  142. return handler in self.idleHandlers
  143. def AddIdleHandler(self, handler):
  144. self.idleHandlers.append(handler)
  145. def DeleteIdleHandler(self, handler):
  146. self.idleHandlers.remove(handler)
  147. def OnIdle(self, count):
  148. try:
  149. ret = 0
  150. handlers = self.idleHandlers[:] # copy list, as may be modified during loop
  151. for handler in handlers:
  152. try:
  153. thisRet = handler(handler, count)
  154. except:
  155. print("Idle handler %s failed" % (repr(handler)))
  156. traceback.print_exc()
  157. print("Idle handler removed from list")
  158. try:
  159. self.DeleteIdleHandler(handler)
  160. except ValueError: # Item not in list.
  161. pass
  162. thisRet = 0
  163. ret = ret or thisRet
  164. return ret
  165. except KeyboardInterrupt:
  166. pass
  167. def CreateMainFrame(self):
  168. return MainFrame()
  169. def LoadMainFrame(self):
  170. " Create the main applications frame "
  171. self.frame = self.CreateMainFrame()
  172. self.SetMainFrame(self.frame)
  173. self.frame.LoadFrame(win32ui.IDR_MAINFRAME, win32con.WS_OVERLAPPEDWINDOW)
  174. self.frame.DragAcceptFiles() # we can accept these.
  175. self.frame.ShowWindow(win32ui.GetInitialStateRequest())
  176. self.frame.UpdateWindow()
  177. self.HookCommands()
  178. def OnHelp(self,id, code):
  179. try:
  180. if id==win32ui.ID_HELP_GUI_REF:
  181. helpFile = regutil.GetRegisteredHelpFile("Pythonwin Reference")
  182. helpCmd = win32con.HELP_CONTENTS
  183. else:
  184. helpFile = regutil.GetRegisteredHelpFile("Main Python Documentation")
  185. helpCmd = win32con.HELP_FINDER
  186. if helpFile is None:
  187. win32ui.MessageBox("The help file is not registered!")
  188. else:
  189. from . import help
  190. help.OpenHelpFile(helpFile, helpCmd)
  191. except:
  192. t, v, tb = sys.exc_info()
  193. win32ui.MessageBox("Internal error in help file processing\r\n%s: %s" % (t,v))
  194. tb = None # Prevent a cycle
  195. def DoLoadModules(self, modules):
  196. # XXX - this should go, but the debugger uses it :-(
  197. # dont do much checking!
  198. for module in modules:
  199. __import__(module)
  200. def HookCommands(self):
  201. self.frame.HookMessage(self.OnDropFiles,win32con.WM_DROPFILES)
  202. self.HookCommand(self.HandleOnFileOpen,win32ui.ID_FILE_OPEN)
  203. self.HookCommand(self.HandleOnFileNew,win32ui.ID_FILE_NEW)
  204. self.HookCommand(self.OnFileMRU,win32ui.ID_FILE_MRU_FILE1)
  205. self.HookCommand(self.OnHelpAbout,win32ui.ID_APP_ABOUT)
  206. self.HookCommand(self.OnHelp, win32ui.ID_HELP_PYTHON)
  207. self.HookCommand(self.OnHelp, win32ui.ID_HELP_GUI_REF)
  208. # Hook for the right-click menu.
  209. self.frame.GetWindow(win32con.GW_CHILD).HookMessage(self.OnRClick,win32con.WM_RBUTTONDOWN)
  210. def SetApplicationPaths(self):
  211. # Load the users/application paths
  212. new_path = []
  213. apppath=win32ui.GetProfileVal('Python','Application Path','').split(';')
  214. for path in apppath:
  215. if len(path)>0:
  216. new_path.append(win32ui.FullPath(path))
  217. for extra_num in range(1,11):
  218. apppath=win32ui.GetProfileVal('Python','Application Path %d'%extra_num,'').split(';')
  219. if len(apppath) == 0:
  220. break
  221. for path in apppath:
  222. if len(path)>0:
  223. new_path.append(win32ui.FullPath(path))
  224. sys.path = new_path + sys.path
  225. def OnRClick(self,params):
  226. " Handle right click message "
  227. # put up the entire FILE menu!
  228. menu = win32ui.LoadMenu(win32ui.IDR_TEXTTYPE).GetSubMenu(0)
  229. menu.TrackPopupMenu(params[5]) # track at mouse position.
  230. return 0
  231. def OnDropFiles(self,msg):
  232. " Handle a file being dropped from file manager "
  233. hDropInfo = msg[2]
  234. self.frame.SetActiveWindow() # active us
  235. nFiles = win32api.DragQueryFile(hDropInfo)
  236. try:
  237. for iFile in range(0,nFiles):
  238. fileName = win32api.DragQueryFile(hDropInfo, iFile)
  239. win32ui.GetApp().OpenDocumentFile( fileName )
  240. finally:
  241. win32api.DragFinish(hDropInfo);
  242. return 0
  243. # No longer used by Pythonwin, as the C++ code has this same basic functionality
  244. # but handles errors slightly better.
  245. # It all still works, tho, so if you need similar functionality, you can use it.
  246. # Therefore I havent deleted this code completely!
  247. # def CallbackManager( self, ob, args = () ):
  248. # """Manage win32 callbacks. Trap exceptions, report on them, then return 'All OK'
  249. # to the frame-work. """
  250. # import traceback
  251. # try:
  252. # ret = apply(ob, args)
  253. # return ret
  254. # except:
  255. # # take copies of the exception values, else other (handled) exceptions may get
  256. # # copied over by the other fns called.
  257. # win32ui.SetStatusText('An exception occured in a windows command handler.')
  258. # t, v, tb = sys.exc_info()
  259. # traceback.print_exception(t, v, tb.tb_next)
  260. # try:
  261. # sys.stdout.flush()
  262. # except (NameError, AttributeError):
  263. # pass
  264. # Command handlers.
  265. def OnFileMRU( self, id, code ):
  266. " Called when a File 1-n message is recieved "
  267. fileName = win32ui.GetRecentFileList()[id - win32ui.ID_FILE_MRU_FILE1]
  268. win32ui.GetApp().OpenDocumentFile(fileName)
  269. def HandleOnFileOpen( self, id, code ):
  270. " Called when FileOpen message is received "
  271. win32ui.GetApp().OnFileOpen()
  272. def HandleOnFileNew( self, id, code ):
  273. " Called when FileNew message is received "
  274. win32ui.GetApp().OnFileNew()
  275. def OnHelpAbout( self, id, code ):
  276. " Called when HelpAbout message is received. Displays the About dialog. "
  277. win32ui.InitRichEdit()
  278. dlg=AboutBox()
  279. dlg.DoModal()
  280. def _GetRegistryValue(key, val, default = None):
  281. # val is registry value - None for default val.
  282. try:
  283. hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key)
  284. return win32api.RegQueryValueEx(hkey, val)[0]
  285. except win32api.error:
  286. try:
  287. hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key)
  288. return win32api.RegQueryValueEx(hkey, val)[0]
  289. except win32api.error:
  290. return default
  291. scintilla = "Scintilla is Copyright 1998-2008 Neil Hodgson (http://www.scintilla.org)"
  292. idle = "This program uses IDLE extensions by Guido van Rossum, Tim Peters and others."
  293. contributors = "Thanks to the following people for making significant contributions: Roger Upole, Sidnei da Silva, Sam Rushing, Curt Hagenlocher, Dave Brennan, Roger Burnham, Gordon McMillan, Neil Hodgson, Laramie Leavitt. (let me know if I have forgotten you!)"
  294. # The About Box
  295. class AboutBox(dialog.Dialog):
  296. def __init__(self, idd=win32ui.IDD_ABOUTBOX):
  297. dialog.Dialog.__init__(self, idd)
  298. def OnInitDialog(self):
  299. text = "Pythonwin - Python IDE and GUI Framework for Windows.\n\n%s\n\nPython is %s\n\n%s\n\n%s\n\n%s" % (win32ui.copyright, sys.copyright, scintilla, idle, contributors)
  300. self.SetDlgItemText(win32ui.IDC_EDIT1, text)
  301. # Get the build number - written by installers.
  302. # For distutils build, read pywin32.version.txt
  303. import distutils.sysconfig
  304. site_packages = distutils.sysconfig.get_python_lib(plat_specific=1)
  305. try:
  306. build_no = open(os.path.join(site_packages, "pywin32.version.txt")).read().strip()
  307. ver = "pywin32 build %s" % build_no
  308. except EnvironmentError:
  309. ver = None
  310. if ver is None:
  311. # See if we are Part of Active Python
  312. ver = _GetRegistryValue("SOFTWARE\\ActiveState\\ActivePython", "CurrentVersion")
  313. if ver is not None:
  314. ver = "ActivePython build %s" % (ver,)
  315. if ver is None:
  316. ver = ""
  317. self.SetDlgItemText(win32ui.IDC_ABOUT_VERSION, ver)
  318. self.HookCommand(self.OnButHomePage, win32ui.IDC_BUTTON1)
  319. def OnButHomePage(self, id, code):
  320. if code == win32con.BN_CLICKED:
  321. win32api.ShellExecute(0, "open", "https://github.com/mhammond/pywin32", None, "", 1)
  322. def Win32RawInput(prompt=None):
  323. "Provide raw_input() for gui apps"
  324. # flush stderr/out first.
  325. try:
  326. sys.stdout.flush()
  327. sys.stderr.flush()
  328. except:
  329. pass
  330. if prompt is None: prompt = ""
  331. ret=dialog.GetSimpleInput(prompt)
  332. if ret==None:
  333. raise KeyboardInterrupt("operation cancelled")
  334. return ret
  335. def Win32Input(prompt=None):
  336. "Provide input() for gui apps"
  337. return eval(input(prompt))
  338. def HookInput():
  339. try:
  340. raw_input
  341. # must be py2x...
  342. sys.modules['__builtin__'].raw_input=Win32RawInput
  343. sys.modules['__builtin__'].input=Win32Input
  344. except NameError:
  345. # must be py3k
  346. import code
  347. sys.modules['builtins'].input=Win32RawInput
  348. def HaveGoodGUI():
  349. """Returns true if we currently have a good gui available.
  350. """
  351. return "pywin.framework.startup" in sys.modules
  352. def CreateDefaultGUI( appClass = None):
  353. """Creates a default GUI environment
  354. """
  355. if appClass is None:
  356. from . import intpyapp # Bring in the default app - could be param'd later.
  357. appClass = intpyapp.InteractivePythonApp
  358. # Create and init the app.
  359. appClass().InitInstance()
  360. def CheckCreateDefaultGUI():
  361. """Checks and creates if necessary a default GUI environment.
  362. """
  363. rc = HaveGoodGUI()
  364. if not rc:
  365. CreateDefaultGUI()
  366. return rc