Initial commit
This commit is contained in:
commit
57fc3525eb
7311 files changed
+1291398
No files matched your search
@@ -0,0 +1,79 @@
|
||||
# win32traceutil like utility for Pythonwin
|
||||
import _thread
|
||||
|
||||
import win32api
|
||||
import win32event
|
||||
import win32trace
|
||||
from pywin.framework import winout
|
||||
|
||||
outputWindow = None
|
||||
|
||||
|
||||
def CollectorThread(stopEvent, file):
|
||||
win32trace.InitRead()
|
||||
handle = win32trace.GetHandle()
|
||||
# Run this thread at a lower priority to the main message-loop (and printing output)
|
||||
# thread can keep up
|
||||
import win32process
|
||||
|
||||
win32process.SetThreadPriority(
|
||||
win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL
|
||||
)
|
||||
|
||||
try:
|
||||
while 1:
|
||||
rc = win32event.WaitForMultipleObjects(
|
||||
(handle, stopEvent), 0, win32event.INFINITE
|
||||
)
|
||||
if rc == win32event.WAIT_OBJECT_0:
|
||||
# About the only char we can't live with is \0!
|
||||
file.write(win32trace.read().replace("\0", "<null>"))
|
||||
else:
|
||||
# Stop event
|
||||
break
|
||||
finally:
|
||||
win32trace.TermRead()
|
||||
print("Thread dieing")
|
||||
|
||||
|
||||
class WindowOutput(winout.WindowOutput):
|
||||
def __init__(self, *args):
|
||||
winout.WindowOutput.__init__(*(self,) + args)
|
||||
self.hStopThread = win32event.CreateEvent(None, 0, 0, None)
|
||||
_thread.start_new(CollectorThread, (self.hStopThread, self))
|
||||
|
||||
def _StopThread(self):
|
||||
win32event.SetEvent(self.hStopThread)
|
||||
self.hStopThread = None
|
||||
|
||||
def Close(self):
|
||||
self._StopThread()
|
||||
winout.WindowOutput.Close(self)
|
||||
# def OnViewDestroy(self, frame):
|
||||
# return winout.WindowOutput.OnViewDestroy(self, frame)
|
||||
# def Create(self, title=None, style = None):
|
||||
# rc = winout.WindowOutput.Create(self, title, style)
|
||||
# return rc
|
||||
|
||||
|
||||
def MakeOutputWindow():
|
||||
# Note that it will not show until the first string written or
|
||||
# you pass bShow = 1
|
||||
global outputWindow
|
||||
if outputWindow is None:
|
||||
title = "Python Trace Collector"
|
||||
# queueingFlag doesn't matter, as all output will come from new thread
|
||||
outputWindow = WindowOutput(title, title)
|
||||
# Let people know what this does!
|
||||
msg = """\
|
||||
# This window will display output from any programs that import win32traceutil
|
||||
# win32com servers registered with '--debug' are in this category.
|
||||
"""
|
||||
outputWindow.write(msg)
|
||||
# force existing window open
|
||||
outputWindow.write("")
|
||||
return outputWindow
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
MakeOutputWindow()
|
||||
Whitespace-only changes.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,323 @@
|
||||
import glob
|
||||
import os
|
||||
import pyclbr
|
||||
|
||||
import commctrl
|
||||
import pywin.framework.scriptutils
|
||||
import regutil
|
||||
import win32api
|
||||
import win32con
|
||||
import win32ui
|
||||
from pywin.mfc import afxres, dialog
|
||||
|
||||
from . import hierlist
|
||||
|
||||
|
||||
class HLIErrorItem(hierlist.HierListItem):
|
||||
def __init__(self, text):
|
||||
self.text = text
|
||||
hierlist.HierListItem.__init__(self)
|
||||
|
||||
def GetText(self):
|
||||
return self.text
|
||||
|
||||
|
||||
class HLICLBRItem(hierlist.HierListItem):
|
||||
def __init__(self, name: str, file, lineno, suffix=""):
|
||||
# If the 'name' object itself has a .name, use it. Not sure
|
||||
# how this happens, but seems pyclbr related.
|
||||
# See PyWin32 bug 817035
|
||||
self.name = getattr(name, "name", name)
|
||||
self.file = file
|
||||
self.lineno = lineno
|
||||
self.suffix = suffix
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.name < other.name
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.name == other.name
|
||||
|
||||
def GetText(self):
|
||||
return self.name + self.suffix
|
||||
|
||||
def TakeDefaultAction(self):
|
||||
if self.file:
|
||||
pywin.framework.scriptutils.JumpToDocument(
|
||||
self.file, self.lineno, bScrollToTop=1
|
||||
)
|
||||
else:
|
||||
win32ui.SetStatusText("The source of this object is unknown")
|
||||
|
||||
def PerformItemSelected(self):
|
||||
if self.file is None:
|
||||
msg = f"{self.name} - source can not be located."
|
||||
else:
|
||||
msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file)
|
||||
win32ui.SetStatusText(msg)
|
||||
|
||||
|
||||
class HLICLBRClass(HLICLBRItem):
|
||||
def __init__(self, clbrclass, suffix=""):
|
||||
try:
|
||||
name = clbrclass.name
|
||||
file = clbrclass.file
|
||||
lineno = clbrclass.lineno
|
||||
self.super = clbrclass.super
|
||||
self.methods = clbrclass.methods
|
||||
except AttributeError:
|
||||
name = clbrclass
|
||||
file = lineno = None
|
||||
self.super = []
|
||||
self.methods = {}
|
||||
HLICLBRItem.__init__(self, name, file, lineno, suffix)
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
for c in self.super:
|
||||
ret.append(HLICLBRClass(c, " (Parent class)"))
|
||||
for meth, lineno in self.methods.items():
|
||||
ret.append(HLICLBRMethod(meth, self.file, lineno, " (method)"))
|
||||
return ret
|
||||
|
||||
def IsExpandable(self):
|
||||
return len(self.methods) + len(self.super)
|
||||
|
||||
def GetBitmapColumn(self):
|
||||
return 21
|
||||
|
||||
|
||||
class HLICLBRFunction(HLICLBRClass):
|
||||
def GetBitmapColumn(self):
|
||||
return 22
|
||||
|
||||
|
||||
class HLICLBRMethod(HLICLBRItem):
|
||||
def GetBitmapColumn(self):
|
||||
return 22
|
||||
|
||||
|
||||
class HLIModuleItem(hierlist.HierListItem):
|
||||
def __init__(self, path):
|
||||
hierlist.HierListItem.__init__(self)
|
||||
self.path = path
|
||||
|
||||
def GetText(self):
|
||||
return os.path.split(self.path)[1] + " (module)"
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def TakeDefaultAction(self):
|
||||
win32ui.GetApp().OpenDocumentFile(self.path)
|
||||
|
||||
def GetBitmapColumn(self):
|
||||
col = 4 # Default
|
||||
try:
|
||||
if win32api.GetFileAttributes(self.path) & win32con.FILE_ATTRIBUTE_READONLY:
|
||||
col = 5
|
||||
except win32api.error:
|
||||
pass
|
||||
return col
|
||||
|
||||
def GetSubList(self):
|
||||
mod, path = pywin.framework.scriptutils.GetPackageModuleName(self.path)
|
||||
win32ui.SetStatusText("Building class list - please wait...", 1)
|
||||
win32ui.DoWaitCursor(1)
|
||||
try:
|
||||
try:
|
||||
reader = pyclbr.readmodule_ex # Post 1.5.2 interface.
|
||||
extra_msg = " or functions"
|
||||
except AttributeError:
|
||||
reader = pyclbr.readmodule
|
||||
extra_msg = ""
|
||||
data = reader(mod, [path])
|
||||
if data:
|
||||
ret = []
|
||||
for item in data.values():
|
||||
if (
|
||||
item.__class__ != pyclbr.Class
|
||||
): # ie, it is a pyclbr Function instance (only introduced post 1.5.2)
|
||||
ret.append(HLICLBRFunction(item, " (function)"))
|
||||
else:
|
||||
ret.append(HLICLBRClass(item, " (class)"))
|
||||
ret.sort()
|
||||
return ret
|
||||
else:
|
||||
return [HLIErrorItem(f"No Python classes{extra_msg} in module.")]
|
||||
finally:
|
||||
win32ui.DoWaitCursor(0)
|
||||
win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
|
||||
|
||||
|
||||
def MakePathSubList(path):
|
||||
ret = []
|
||||
for filename in glob.glob(os.path.join(path, "*")):
|
||||
if os.path.isdir(filename) and os.path.isfile(
|
||||
os.path.join(filename, "__init__.py")
|
||||
):
|
||||
ret.append(HLIDirectoryItem(filename, os.path.split(filename)[1]))
|
||||
else:
|
||||
if os.path.splitext(filename)[1].lower() in [".py", ".pyw"]:
|
||||
ret.append(HLIModuleItem(filename))
|
||||
return ret
|
||||
|
||||
|
||||
class HLIDirectoryItem(hierlist.HierListItem):
|
||||
def __init__(self, path, displayName=None, bSubDirs=0):
|
||||
hierlist.HierListItem.__init__(self)
|
||||
self.path = path
|
||||
self.bSubDirs = bSubDirs
|
||||
if displayName:
|
||||
self.displayName = displayName
|
||||
else:
|
||||
self.displayName = path
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def GetText(self):
|
||||
return self.displayName
|
||||
|
||||
def GetSubList(self):
|
||||
ret = MakePathSubList(self.path)
|
||||
if (
|
||||
os.path.split(self.path)[1] == "win32com"
|
||||
): # Complete and utter hack for win32com.
|
||||
try:
|
||||
path = win32api.GetFullPathName(
|
||||
os.path.join(self.path, "..\\win32comext")
|
||||
)
|
||||
ret.extend(MakePathSubList(path))
|
||||
except win32ui.error:
|
||||
pass
|
||||
return ret
|
||||
|
||||
|
||||
class HLIProjectRoot(hierlist.HierListItem):
|
||||
def __init__(self, projectName, displayName=None):
|
||||
hierlist.HierListItem.__init__(self)
|
||||
self.projectName = projectName
|
||||
self.displayName = displayName or projectName
|
||||
|
||||
def GetText(self):
|
||||
return self.displayName
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def GetSubList(self):
|
||||
paths = regutil.GetRegisteredNamedPath(self.projectName)
|
||||
pathList = paths.split(";")
|
||||
if len(pathList) == 1: # Single dir - don't bother putting the dir in
|
||||
ret = MakePathSubList(pathList[0])
|
||||
else:
|
||||
ret = list(map(HLIDirectoryItem, pathList))
|
||||
return ret
|
||||
|
||||
|
||||
class HLIRoot(hierlist.HierListItem):
|
||||
def __init__(self):
|
||||
hierlist.HierListItem.__init__(self)
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def GetSubList(self):
|
||||
keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath"
|
||||
hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr)
|
||||
try:
|
||||
ret = []
|
||||
ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path.
|
||||
index = 0
|
||||
while 1:
|
||||
try:
|
||||
ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index)))
|
||||
index += 1
|
||||
except win32api.error:
|
||||
break
|
||||
return ret
|
||||
finally:
|
||||
win32api.RegCloseKey(hKey)
|
||||
|
||||
|
||||
class dynamic_browser(dialog.Dialog):
|
||||
style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE
|
||||
cs = (
|
||||
win32con.WS_CHILD
|
||||
| win32con.WS_VISIBLE
|
||||
| commctrl.TVS_HASLINES
|
||||
| commctrl.TVS_LINESATROOT
|
||||
| commctrl.TVS_HASBUTTONS
|
||||
)
|
||||
|
||||
dt = [
|
||||
["Python Projects", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")],
|
||||
["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs],
|
||||
]
|
||||
|
||||
def __init__(self, hli_root):
|
||||
dialog.Dialog.__init__(self, self.dt)
|
||||
self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER)
|
||||
self.HookMessage(self.on_size, win32con.WM_SIZE)
|
||||
|
||||
def OnInitDialog(self):
|
||||
self.hier_list.HierInit(self)
|
||||
return dialog.Dialog.OnInitDialog(self)
|
||||
|
||||
def on_size(self, params):
|
||||
lparam = params[3]
|
||||
w = win32api.LOWORD(lparam)
|
||||
h = win32api.HIWORD(lparam)
|
||||
self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h))
|
||||
|
||||
|
||||
def BrowseDialog():
|
||||
root = HLIRoot()
|
||||
if not root.IsExpandable():
|
||||
raise TypeError(
|
||||
"Browse() argument must have __dict__ attribute, or be a Browser supported type"
|
||||
)
|
||||
|
||||
dlg = dynamic_browser(root)
|
||||
dlg.CreateWindow()
|
||||
|
||||
|
||||
def DockableBrowserCreator(parent):
|
||||
root = HLIRoot()
|
||||
hl = hierlist.HierListWithItems(root, win32ui.IDB_BROWSER_HIER)
|
||||
|
||||
style = (
|
||||
win32con.WS_CHILD
|
||||
| win32con.WS_VISIBLE
|
||||
| win32con.WS_BORDER
|
||||
| commctrl.TVS_HASLINES
|
||||
| commctrl.TVS_LINESATROOT
|
||||
| commctrl.TVS_HASBUTTONS
|
||||
)
|
||||
|
||||
control = win32ui.CreateTreeCtrl()
|
||||
control.CreateWindow(style, (0, 0, 150, 300), parent, win32ui.IDC_LIST1)
|
||||
list = hl.HierInit(parent, control)
|
||||
return control
|
||||
|
||||
|
||||
def DockablePathBrowser():
|
||||
import pywin.docking.DockingBar
|
||||
|
||||
bar = pywin.docking.DockingBar.DockingBar()
|
||||
bar.CreateWindow(
|
||||
win32ui.GetMainFrame(), DockableBrowserCreator, "Path Browser", 0x8E0A
|
||||
)
|
||||
bar.SetBarStyle(
|
||||
bar.GetBarStyle()
|
||||
| afxres.CBRS_TOOLTIPS
|
||||
| afxres.CBRS_FLYBY
|
||||
| afxres.CBRS_SIZE_DYNAMIC
|
||||
)
|
||||
bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
|
||||
win32ui.GetMainFrame().DockControlBar(bar)
|
||||
|
||||
|
||||
# The "default" entry point
|
||||
Browse = DockablePathBrowser
|
||||
@@ -0,0 +1,492 @@
|
||||
# basic module browser.
|
||||
|
||||
# usage:
|
||||
# >>> import browser
|
||||
# >>> browser.Browse()
|
||||
# or
|
||||
# >>> browser.Browse(your_module)
|
||||
import sys
|
||||
import types
|
||||
|
||||
import __main__
|
||||
import win32ui
|
||||
from pywin.mfc import dialog
|
||||
|
||||
from . import hierlist
|
||||
|
||||
special_names = ["__doc__", "__name__", "__self__"]
|
||||
|
||||
|
||||
#
|
||||
# HierList items
|
||||
class HLIPythonObject(hierlist.HierListItem):
|
||||
def __init__(self, myobject=None, name=None):
|
||||
hierlist.HierListItem.__init__(self)
|
||||
self.myobject = myobject
|
||||
self.knownExpandable = None
|
||||
if name:
|
||||
self.name = name
|
||||
else:
|
||||
try:
|
||||
self.name = myobject.__name__
|
||||
except (AttributeError, TypeError):
|
||||
try:
|
||||
r = repr(myobject)
|
||||
if len(r) > 20:
|
||||
r = r[:20] + "..."
|
||||
self.name = r
|
||||
except (AttributeError, TypeError):
|
||||
self.name = "???"
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.name < other.name
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.name == other.name
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
f"{self.__class__.__name__}(name={self.name!r}, object={self.myobject!r})"
|
||||
)
|
||||
|
||||
def GetText(self):
|
||||
try:
|
||||
return f"{self.name} ({self.GetHLIType()})"
|
||||
except AttributeError:
|
||||
return f"{self.name} = {self.myobject!r}"
|
||||
|
||||
def InsertDocString(self, lst):
|
||||
ob = None
|
||||
try:
|
||||
ob = self.myobject.__doc__
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
# I don't quite grok descriptors enough to know how to
|
||||
# best hook them up. Eg:
|
||||
# >>> object.__getattribute__.__class__.__doc__
|
||||
# <attribute '__doc__' of 'wrapper_descriptor' objects>
|
||||
if ob and isinstance(ob, str):
|
||||
lst.insert(0, HLIDocString(ob, "Doc"))
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
try:
|
||||
for key, ob in self.myobject.__dict__.items():
|
||||
if key not in special_names:
|
||||
ret.append(MakeHLI(ob, key))
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
try:
|
||||
for name in self.myobject.__methods__:
|
||||
ret.append(HLIMethod(name)) # no MakeHLI, as can't auto detect
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
try:
|
||||
for member in self.myobject.__members__:
|
||||
if not member in special_names:
|
||||
ret.append(MakeHLI(getattr(self.myobject, member), member))
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
ret.sort()
|
||||
self.InsertDocString(ret)
|
||||
return ret
|
||||
|
||||
# if the has a dict, it is expandable.
|
||||
def IsExpandable(self):
|
||||
if self.knownExpandable is None:
|
||||
self.knownExpandable = self.CalculateIsExpandable()
|
||||
return self.knownExpandable
|
||||
|
||||
def CalculateIsExpandable(self):
|
||||
if hasattr(self.myobject, "__doc__"):
|
||||
return 1
|
||||
try:
|
||||
for key in self.myobject.__dict__:
|
||||
if key not in special_names:
|
||||
return 1
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
try:
|
||||
self.myobject.__methods__
|
||||
return 1
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
try:
|
||||
for item in self.myobject.__members__:
|
||||
if item not in special_names:
|
||||
return 1
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
return 0
|
||||
|
||||
def GetBitmapColumn(self):
|
||||
if self.IsExpandable():
|
||||
return 0
|
||||
else:
|
||||
return 4
|
||||
|
||||
def TakeDefaultAction(self):
|
||||
ShowObject(self.myobject, self.name)
|
||||
|
||||
|
||||
class HLIDocString(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "DocString"
|
||||
|
||||
def GetText(self):
|
||||
return self.myobject.strip()
|
||||
|
||||
def IsExpandable(self):
|
||||
return 0
|
||||
|
||||
def GetBitmapColumn(self):
|
||||
return 6
|
||||
|
||||
|
||||
class HLIModule(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Module"
|
||||
|
||||
|
||||
class HLIFrame(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Stack Frame"
|
||||
|
||||
|
||||
class HLITraceback(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Traceback"
|
||||
|
||||
|
||||
class HLIClass(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Class"
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
for base in self.myobject.__bases__:
|
||||
ret.append(MakeHLI(base, "Base class: " + base.__name__))
|
||||
ret.extend(HLIPythonObject.GetSubList(self))
|
||||
return ret
|
||||
|
||||
|
||||
class HLIMethod(HLIPythonObject):
|
||||
# myobject is just a string for methods.
|
||||
def GetHLIType(self):
|
||||
return "Method"
|
||||
|
||||
def GetText(self):
|
||||
return "Method: " + self.myobject + "()"
|
||||
|
||||
|
||||
class HLICode(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Code"
|
||||
|
||||
def IsExpandable(self):
|
||||
return self.myobject
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
ret.append(MakeHLI(self.myobject.co_consts, "Constants (co_consts)"))
|
||||
ret.append(MakeHLI(self.myobject.co_names, "Names (co_names)"))
|
||||
ret.append(MakeHLI(self.myobject.co_filename, "Filename (co_filename)"))
|
||||
ret.append(MakeHLI(self.myobject.co_argcount, "Number of args (co_argcount)"))
|
||||
ret.append(MakeHLI(self.myobject.co_varnames, "Param names (co_varnames)"))
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
class HLIInstance(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Instance"
|
||||
|
||||
def GetText(self):
|
||||
return (
|
||||
str(self.name)
|
||||
+ " (Instance of class "
|
||||
+ str(self.myobject.__class__.__name__)
|
||||
+ ")"
|
||||
)
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
ret.append(MakeHLI(self.myobject.__class__))
|
||||
ret.extend(HLIPythonObject.GetSubList(self))
|
||||
return ret
|
||||
|
||||
|
||||
class HLIBuiltinFunction(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Builtin Function"
|
||||
|
||||
|
||||
class HLIFunction(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Function"
|
||||
|
||||
def IsExpandable(self):
|
||||
return 1
|
||||
|
||||
def GetSubList(self):
|
||||
ret = [
|
||||
MakeHLI(self.myobject.__code__, "Code"),
|
||||
MakeHLI(self.myobject.__globals__, "Globals"),
|
||||
]
|
||||
self.InsertDocString(ret)
|
||||
return ret
|
||||
|
||||
|
||||
class HLISeq(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Sequence (abstract!)"
|
||||
|
||||
def IsExpandable(self):
|
||||
return len(self.myobject) > 0
|
||||
|
||||
def GetSubList(self):
|
||||
ret = []
|
||||
pos = 0
|
||||
for item in self.myobject:
|
||||
ret.append(MakeHLI(item, f"[{pos}]"))
|
||||
pos += 1
|
||||
self.InsertDocString(ret)
|
||||
return ret
|
||||
|
||||
|
||||
class HLIList(HLISeq):
|
||||
def GetHLIType(self):
|
||||
return "List"
|
||||
|
||||
|
||||
class HLITuple(HLISeq):
|
||||
def GetHLIType(self):
|
||||
return "Tuple"
|
||||
|
||||
|
||||
class HLIDict(HLIPythonObject):
|
||||
def GetHLIType(self):
|
||||
return "Dict"
|
||||
|
||||
def IsExpandable(self):
|
||||
try:
|
||||
self.myobject.__doc__
|
||||
return 1
|
||||
except (AttributeError, TypeError):
|
||||
return len(self.myobject) > 0
|
||||
|
||||
def GetSubList(self):
|
||||
ret = [MakeHLI(self.myobject[key], str(key)) for key in sorted(self.myobject)]
|
||||
self.InsertDocString(ret)
|
||||
return ret
|
||||
|
||||
|
||||
# strings and Unicode have builtin methods, but we don't really want to see these
|
||||
class HLIString(HLIPythonObject):
|
||||
def IsExpandable(self):
|
||||
return 0
|
||||
|
||||
|
||||
TypeMap = {
|
||||
type: HLIClass,
|
||||
types.FunctionType: HLIFunction,
|
||||
tuple: HLITuple,
|
||||
dict: HLIDict,
|
||||
list: HLIList,
|
||||
types.ModuleType: HLIModule,
|
||||
types.CodeType: HLICode,
|
||||
types.BuiltinFunctionType: HLIBuiltinFunction,
|
||||
types.FrameType: HLIFrame,
|
||||
types.TracebackType: HLITraceback,
|
||||
str: HLIString,
|
||||
int: HLIPythonObject,
|
||||
bool: HLIPythonObject,
|
||||
float: HLIPythonObject,
|
||||
}
|
||||
|
||||
|
||||
def MakeHLI(ob, name=None):
|
||||
try:
|
||||
cls = TypeMap[type(ob)]
|
||||
except KeyError:
|
||||
# hrmph - this check gets more and more bogus as Python
|
||||
# improves. It's possible we should just *always* use
|
||||
# HLIInstance?
|
||||
if hasattr(ob, "__class__"): # 'new style' class
|
||||
cls = HLIInstance
|
||||
else:
|
||||
cls = HLIPythonObject
|
||||
return cls(ob, name)
|
||||
|
||||
|
||||
#########################################
|
||||
#
|
||||
# Dialog related.
|
||||
|
||||
|
||||
class DialogShowObject(dialog.Dialog):
|
||||
def __init__(self, object, title):
|
||||
self.object = object
|
||||
self.title = title
|
||||
dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT)
|
||||
|
||||
def OnInitDialog(self):
|
||||
import re
|
||||
|
||||
self.SetWindowText(self.title)
|
||||
self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
|
||||
try:
|
||||
strval = str(self.object)
|
||||
except:
|
||||
t, v, tb = sys.exc_info()
|
||||
strval = f"Exception getting object value\n\n{t}:{v}"
|
||||
tb = None
|
||||
strval = re.sub(r"\n", "\r\n", strval)
|
||||
self.edit.ReplaceSel(strval)
|
||||
|
||||
|
||||
def ShowObject(object, title):
|
||||
dlg = DialogShowObject(object, title)
|
||||
dlg.DoModal()
|
||||
|
||||
|
||||
# And some mods for a sizable dialog from Sam Rushing!
|
||||
import commctrl
|
||||
import win32api
|
||||
import win32con
|
||||
|
||||
|
||||
class dynamic_browser(dialog.Dialog):
|
||||
style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE
|
||||
cs = (
|
||||
win32con.WS_CHILD
|
||||
| win32con.WS_VISIBLE
|
||||
| commctrl.TVS_HASLINES
|
||||
| commctrl.TVS_LINESATROOT
|
||||
| commctrl.TVS_HASBUTTONS
|
||||
)
|
||||
|
||||
dt = [
|
||||
["Python Object Browser", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")],
|
||||
["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs],
|
||||
]
|
||||
|
||||
def __init__(self, hli_root):
|
||||
dialog.Dialog.__init__(self, self.dt)
|
||||
self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER)
|
||||
self.HookMessage(self.on_size, win32con.WM_SIZE)
|
||||
|
||||
def OnInitDialog(self):
|
||||
self.hier_list.HierInit(self)
|
||||
return dialog.Dialog.OnInitDialog(self)
|
||||
|
||||
def OnOK(self):
|
||||
self.hier_list.HierTerm()
|
||||
self.hier_list = None
|
||||
return self._obj_.OnOK()
|
||||
|
||||
def OnCancel(self):
|
||||
self.hier_list.HierTerm()
|
||||
self.hier_list = None
|
||||
return self._obj_.OnCancel()
|
||||
|
||||
def on_size(self, params):
|
||||
lparam = params[3]
|
||||
w = win32api.LOWORD(lparam)
|
||||
h = win32api.HIWORD(lparam)
|
||||
self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h))
|
||||
|
||||
|
||||
def Browse(ob=__main__):
|
||||
"Browse the argument, or the main dictionary"
|
||||
root = MakeHLI(ob, "root")
|
||||
if not root.IsExpandable():
|
||||
raise TypeError(
|
||||
"Browse() argument must have __dict__ attribute, or be a Browser supported type"
|
||||
)
|
||||
|
||||
dlg = dynamic_browser(root)
|
||||
dlg.CreateWindow()
|
||||
return dlg
|
||||
|
||||
|
||||
#
|
||||
#
|
||||
# Classes for using the browser in an MDI window, rather than a dialog
|
||||
#
|
||||
from pywin.mfc import docview
|
||||
|
||||
|
||||
class BrowserTemplate(docview.DocTemplate):
|
||||
def __init__(self):
|
||||
docview.DocTemplate.__init__(
|
||||
self, win32ui.IDR_PYTHONTYPE, BrowserDocument, None, BrowserView
|
||||
)
|
||||
|
||||
def OpenObject(self, root): # Use this instead of OpenDocumentFile.
|
||||
# Look for existing open document
|
||||
for doc in self.GetDocumentList():
|
||||
if doc.root == root:
|
||||
doc.GetFirstView().ActivateFrame()
|
||||
return doc
|
||||
# not found - new one.
|
||||
doc = BrowserDocument(self, root)
|
||||
frame = self.CreateNewFrame(doc)
|
||||
doc.OnNewDocument()
|
||||
self.InitialUpdateFrame(frame, doc, 1)
|
||||
return doc
|
||||
|
||||
|
||||
class BrowserDocument(docview.Document):
|
||||
def __init__(self, template, root):
|
||||
docview.Document.__init__(self, template)
|
||||
self.root = root
|
||||
self.SetTitle("Browser: " + root.name)
|
||||
|
||||
def OnOpenDocument(self, name):
|
||||
raise TypeError("This template can not open files")
|
||||
return 0
|
||||
|
||||
|
||||
class BrowserView(docview.TreeView):
|
||||
def OnInitialUpdate(self):
|
||||
import commctrl
|
||||
|
||||
rc = self._obj_.OnInitialUpdate()
|
||||
list = hierlist.HierListWithItems(
|
||||
self.GetDocument().root,
|
||||
win32ui.IDB_BROWSER_HIER,
|
||||
win32ui.AFX_IDW_PANE_FIRST,
|
||||
)
|
||||
list.HierInit(self.GetParent())
|
||||
list.SetStyle(
|
||||
commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
|
||||
)
|
||||
return rc
|
||||
|
||||
|
||||
template = None
|
||||
|
||||
|
||||
def MakeTemplate():
|
||||
global template
|
||||
if template is None:
|
||||
template = (
|
||||
BrowserTemplate()
|
||||
) # win32ui.IDR_PYTHONTYPE, BrowserDocument, None, BrowserView)
|
||||
|
||||
|
||||
def BrowseMDI(ob=__main__):
|
||||
"""Browse an object using an MDI window."""
|
||||
|
||||
MakeTemplate()
|
||||
root = MakeHLI(ob, repr(ob))
|
||||
if not root.IsExpandable():
|
||||
raise TypeError(
|
||||
"Browse() argument must have __dict__ attribute, or be a Browser supported type"
|
||||
)
|
||||
|
||||
template.OpenObject(root)
|
||||
@@ -0,0 +1,353 @@
|
||||
# hierlist
|
||||
#
|
||||
# IMPORTANT - Please read before using.
|
||||
|
||||
# This module exposes an API for a Hierarchical Tree Control.
|
||||
# Previously, a custom tree control was included in Pythonwin which
|
||||
# has an API very similar to this.
|
||||
|
||||
# The current control used is the common "Tree Control". This module exists now
|
||||
# to provide an API similar to the old control, but for the new Tree control.
|
||||
|
||||
# If you need to use the Tree Control, you may still find this API a reasonable
|
||||
# choice. However, you should investigate using the tree control directly
|
||||
# to provide maximum flexibility (but with extra work).
|
||||
from __future__ import annotations
|
||||
|
||||
import commctrl
|
||||
import win32api
|
||||
import win32con
|
||||
import win32ui
|
||||
from pywin.mfc import dialog, object
|
||||
from win32api import RGB
|
||||
|
||||
|
||||
# helper to get the text of an arbitrary item
|
||||
def GetItemText(item):
|
||||
if isinstance(item, (tuple, list)):
|
||||
use = item[0]
|
||||
else:
|
||||
use = item
|
||||
if isinstance(use, str):
|
||||
return use
|
||||
else:
|
||||
return repr(item)
|
||||
|
||||
|
||||
class HierDialog(dialog.Dialog):
|
||||
def __init__(
|
||||
self,
|
||||
title,
|
||||
hierList,
|
||||
bitmapID=win32ui.IDB_HIERFOLDERS,
|
||||
dlgID=win32ui.IDD_TREE,
|
||||
dll=None,
|
||||
childListBoxID=win32ui.IDC_LIST1,
|
||||
):
|
||||
dialog.Dialog.__init__(self, dlgID, dll) # reuse this dialog.
|
||||
self.hierList = hierList
|
||||
self.dlgID = dlgID
|
||||
self.title = title
|
||||
|
||||
# self.childListBoxID = childListBoxID
|
||||
def OnInitDialog(self):
|
||||
self.SetWindowText(self.title)
|
||||
self.hierList.HierInit(self)
|
||||
return dialog.Dialog.OnInitDialog(self)
|
||||
|
||||
|
||||
class HierList(object.Object):
|
||||
def __init__(
|
||||
self, root, bitmapID=win32ui.IDB_HIERFOLDERS, listBoxId=None, bitmapMask=None
|
||||
): # used to create object.
|
||||
self.listControl = None
|
||||
self.bitmapID = bitmapID
|
||||
self.root = root
|
||||
self.listBoxId = listBoxId
|
||||
self.itemHandleMap = {}
|
||||
self.filledItemHandlesMap = {}
|
||||
self.bitmapMask = bitmapMask
|
||||
|
||||
def __getattr__(self, attr):
|
||||
try:
|
||||
return getattr(self.listControl, attr)
|
||||
except AttributeError:
|
||||
return object.Object.__getattr__(self, attr)
|
||||
|
||||
def ItemFromHandle(self, handle):
|
||||
return self.itemHandleMap[handle]
|
||||
|
||||
def SetStyle(self, newStyle):
|
||||
hwnd = self.listControl.GetSafeHwnd()
|
||||
style = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
|
||||
win32api.SetWindowLong(hwnd, win32con.GWL_STYLE, (style | newStyle))
|
||||
|
||||
def HierInit(self, parent, listControl=None): # Used when window first exists.
|
||||
# this also calls "Create" on the listbox.
|
||||
# params - id of listbbox, ID of bitmap, size of bitmaps
|
||||
if self.bitmapMask is None:
|
||||
bitmapMask = RGB(0, 0, 255)
|
||||
else:
|
||||
bitmapMask = self.bitmapMask
|
||||
self.imageList = win32ui.CreateImageList(self.bitmapID, 16, 0, bitmapMask)
|
||||
if listControl is None:
|
||||
if self.listBoxId is None:
|
||||
self.listBoxId = win32ui.IDC_LIST1
|
||||
self.listControl = parent.GetDlgItem(self.listBoxId)
|
||||
else:
|
||||
self.listControl = listControl
|
||||
lbid = listControl.GetDlgCtrlID()
|
||||
assert self.listBoxId is None or self.listBoxId == lbid, (
|
||||
"An invalid listbox control ID has been specified (specified as {}, but exists as {})".format(
|
||||
self.listBoxId, lbid
|
||||
)
|
||||
)
|
||||
self.listBoxId = lbid
|
||||
self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL)
|
||||
# self.list.AttachObject(self)
|
||||
|
||||
parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW)
|
||||
parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW)
|
||||
parent.HookNotify(self.OnTreeItemDoubleClick, commctrl.NM_DBLCLK)
|
||||
self.notify_parent = parent
|
||||
|
||||
if self.root:
|
||||
self.AcceptRoot(self.root)
|
||||
|
||||
def DeleteAllItems(self):
|
||||
self.listControl.DeleteAllItems()
|
||||
self.root = None
|
||||
self.itemHandleMap = {}
|
||||
self.filledItemHandlesMap = {}
|
||||
|
||||
def HierTerm(self):
|
||||
# Don't want notifies as we kill the list.
|
||||
parent = self.notify_parent # GetParentFrame()
|
||||
parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW)
|
||||
parent.HookNotify(None, commctrl.TVN_SELCHANGEDW)
|
||||
parent.HookNotify(None, commctrl.NM_DBLCLK)
|
||||
|
||||
self.DeleteAllItems()
|
||||
self.listControl = None
|
||||
self.notify_parent = None # Break a possible cycle
|
||||
|
||||
def OnTreeItemDoubleClick(self, info, extra):
|
||||
(hwndFrom, idFrom, code) = info
|
||||
if idFrom != self.listBoxId:
|
||||
return None
|
||||
item = self.itemHandleMap[self.listControl.GetSelectedItem()]
|
||||
self.TakeDefaultAction(item)
|
||||
return 1
|
||||
|
||||
def OnTreeItemExpanding(self, info, extra):
|
||||
(hwndFrom, idFrom, code) = info
|
||||
if idFrom != self.listBoxId:
|
||||
return None
|
||||
action, itemOld, itemNew, pt = extra
|
||||
itemHandle = itemNew[0]
|
||||
if itemHandle not in self.filledItemHandlesMap:
|
||||
item = self.itemHandleMap[itemHandle]
|
||||
self.AddSubList(itemHandle, self.GetSubList(item))
|
||||
self.filledItemHandlesMap[itemHandle] = None
|
||||
return 0
|
||||
|
||||
def OnTreeItemSelChanged(self, info, extra):
|
||||
(hwndFrom, idFrom, code) = info
|
||||
if idFrom != self.listBoxId:
|
||||
return None
|
||||
action, itemOld, itemNew, pt = extra
|
||||
itemHandle = itemNew[0]
|
||||
item = self.itemHandleMap[itemHandle]
|
||||
self.PerformItemSelected(item)
|
||||
return 1
|
||||
|
||||
def AddSubList(self, parentHandle, subItems):
|
||||
for item in subItems:
|
||||
self.AddItem(parentHandle, item)
|
||||
|
||||
def AddItem(self, parentHandle, item, hInsertAfter=commctrl.TVI_LAST):
|
||||
text = self.GetText(item)
|
||||
if self.IsExpandable(item):
|
||||
cItems = 1 # Trick it !!
|
||||
else:
|
||||
cItems = 0
|
||||
bitmapCol = self.GetBitmapColumn(item)
|
||||
bitmapSel = self.GetSelectedBitmapColumn(item)
|
||||
if bitmapSel is None:
|
||||
bitmapSel = bitmapCol
|
||||
hitem = self.listControl.InsertItem(
|
||||
parentHandle,
|
||||
hInsertAfter,
|
||||
(None, None, None, text, bitmapCol, bitmapSel, cItems, 0),
|
||||
)
|
||||
self.itemHandleMap[hitem] = item
|
||||
return hitem
|
||||
|
||||
def _GetChildHandles(self, handle):
|
||||
ret = []
|
||||
try:
|
||||
handle = self.listControl.GetChildItem(handle)
|
||||
while 1:
|
||||
ret.append(handle)
|
||||
handle = self.listControl.GetNextItem(handle, commctrl.TVGN_NEXT)
|
||||
except win32ui.error:
|
||||
# out of children
|
||||
pass
|
||||
return ret
|
||||
|
||||
def Refresh(self, hparent=None):
|
||||
# Attempt to refresh the given item's sub-entries, but maintain the tree state
|
||||
# (ie, the selected item, expanded items, etc)
|
||||
if hparent is None:
|
||||
hparent = commctrl.TVI_ROOT
|
||||
if hparent not in self.filledItemHandlesMap:
|
||||
# This item has never been expanded, so no refresh can possibly be required.
|
||||
return
|
||||
root_item = self.itemHandleMap[hparent]
|
||||
old_handles = self._GetChildHandles(hparent)
|
||||
old_items = list(map(self.ItemFromHandle, old_handles))
|
||||
new_items = self.GetSubList(root_item)
|
||||
# Now an inefficient technique for synching the items.
|
||||
inew = 0
|
||||
hAfter = commctrl.TVI_FIRST
|
||||
for iold in range(len(old_items)):
|
||||
inewlook = inew
|
||||
matched = 0
|
||||
while inewlook < len(new_items):
|
||||
if old_items[iold] == new_items[inewlook]:
|
||||
matched = 1
|
||||
break
|
||||
inewlook += 1
|
||||
if matched:
|
||||
# Insert the new items.
|
||||
# print("Inserting after", old_items[iold], old_handles[iold])
|
||||
for i in range(inew, inewlook):
|
||||
# print(f"Inserting index {i} ({new_items[i]})")
|
||||
hAfter = self.AddItem(hparent, new_items[i], hAfter)
|
||||
|
||||
inew = inewlook + 1
|
||||
# And recursively refresh iold
|
||||
hold = old_handles[iold]
|
||||
if hold in self.filledItemHandlesMap:
|
||||
self.Refresh(hold)
|
||||
else:
|
||||
# Remove the deleted items.
|
||||
# print(f"Deleting {iold} ({old_items[iold]})")
|
||||
hdelete = old_handles[iold]
|
||||
# First recurse and remove the children from the map.
|
||||
for hchild in self._GetChildHandles(hdelete):
|
||||
del self.itemHandleMap[hchild]
|
||||
if hchild in self.filledItemHandlesMap:
|
||||
del self.filledItemHandlesMap[hchild]
|
||||
self.listControl.DeleteItem(hdelete)
|
||||
hAfter = old_handles[iold]
|
||||
# Fill any remaining new items:
|
||||
for newItem in new_items[inew:]:
|
||||
# print("Inserting new item", newItem)
|
||||
self.AddItem(hparent, newItem)
|
||||
|
||||
def AcceptRoot(self, root):
|
||||
self.listControl.DeleteAllItems()
|
||||
self.itemHandleMap = {commctrl.TVI_ROOT: root}
|
||||
self.filledItemHandlesMap = {commctrl.TVI_ROOT: root}
|
||||
subItems = self.GetSubList(root)
|
||||
self.AddSubList(0, subItems)
|
||||
|
||||
def GetBitmapColumn(self, item):
|
||||
if self.IsExpandable(item):
|
||||
return 0
|
||||
else:
|
||||
return 4
|
||||
|
||||
def GetSelectedBitmapColumn(self, item) -> int | None:
|
||||
return 0
|
||||
|
||||
def CheckChangedChildren(self):
|
||||
return self.listControl.CheckChangedChildren()
|
||||
|
||||
def GetText(self, item):
|
||||
return GetItemText(item)
|
||||
|
||||
def PerformItemSelected(self, item):
|
||||
try:
|
||||
win32ui.SetStatusText("Selected " + self.GetText(item))
|
||||
except win32ui.error: # No status bar!
|
||||
pass
|
||||
|
||||
def TakeDefaultAction(self, item):
|
||||
win32ui.MessageBox("Got item " + self.GetText(item))
|
||||
|
||||
|
||||
##########################################################################
|
||||
#
|
||||
# Classes for use with separate HierListItems.
|
||||
#
|
||||
#
|
||||
class HierListWithItems(HierList):
|
||||
def __init__(
|
||||
self, root, bitmapID=win32ui.IDB_HIERFOLDERS, listBoxID=None, bitmapMask=None
|
||||
): # used to create object.
|
||||
HierList.__init__(self, root, bitmapID, listBoxID, bitmapMask)
|
||||
|
||||
def DelegateCall(self, fn):
|
||||
return fn()
|
||||
|
||||
def GetBitmapColumn(self, item):
|
||||
rc = self.DelegateCall(item.GetBitmapColumn)
|
||||
if rc is None:
|
||||
rc = HierList.GetBitmapColumn(self, item)
|
||||
return rc
|
||||
|
||||
def GetSelectedBitmapColumn(self, item):
|
||||
return self.DelegateCall(item.GetSelectedBitmapColumn)
|
||||
|
||||
def IsExpandable(self, item):
|
||||
return self.DelegateCall(item.IsExpandable)
|
||||
|
||||
def GetText(self, item):
|
||||
return self.DelegateCall(item.GetText)
|
||||
|
||||
def GetSubList(self, item):
|
||||
return self.DelegateCall(item.GetSubList)
|
||||
|
||||
def PerformItemSelected(self, item):
|
||||
func = getattr(item, "PerformItemSelected", None)
|
||||
if func is None:
|
||||
return HierList.PerformItemSelected(self, item)
|
||||
else:
|
||||
return self.DelegateCall(func)
|
||||
|
||||
def TakeDefaultAction(self, item):
|
||||
func = getattr(item, "TakeDefaultAction", None)
|
||||
if func is None:
|
||||
return HierList.TakeDefaultAction(self, item)
|
||||
else:
|
||||
return self.DelegateCall(func)
|
||||
|
||||
|
||||
# A hier list item - for use with a HierListWithItems
|
||||
class HierListItem:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def GetText(self):
|
||||
pass
|
||||
|
||||
def GetSubList(self):
|
||||
pass
|
||||
|
||||
def IsExpandable(self):
|
||||
pass
|
||||
|
||||
def GetBitmapColumn(self):
|
||||
return None # indicate he should do it.
|
||||
|
||||
def GetSelectedBitmapColumn(self):
|
||||
return None # same as other
|
||||
|
||||
def __lt__(self, other):
|
||||
# we want unrelated items to be sortable...
|
||||
return id(self) < id(other)
|
||||
|
||||
def __eq__(self, other):
|
||||
return False
|
||||
@@ -0,0 +1,382 @@
|
||||
# Regedit - a Registry Editor for Python
|
||||
|
||||
import commctrl
|
||||
import regutil
|
||||
import win32api
|
||||
import win32con
|
||||
import win32ui
|
||||
from pywin.mfc import dialog, docview, window
|
||||
|
||||
from . import hierlist
|
||||
|
||||
|
||||
def SafeApply(fn, args, err_desc=""):
|
||||
try:
|
||||
fn(*args)
|
||||
return 1
|
||||
except win32api.error as exc:
|
||||
msg = "Error " + err_desc + "\r\n\r\n" + exc.strerror
|
||||
win32ui.MessageBox(msg)
|
||||
return 0
|
||||
|
||||
|
||||
class SplitterFrame(window.MDIChildWnd):
|
||||
def __init__(self):
|
||||
# call base CreateFrame
|
||||
self.images = None
|
||||
window.MDIChildWnd.__init__(self)
|
||||
|
||||
def OnCreateClient(self, cp, context):
|
||||
splitter = win32ui.CreateSplitter()
|
||||
doc = context.doc
|
||||
frame_rect = self.GetWindowRect()
|
||||
size = ((frame_rect[2] - frame_rect[0]), (frame_rect[3] - frame_rect[1]) // 2)
|
||||
sub_size = (size[0] // 3, size[1])
|
||||
splitter.CreateStatic(self, 1, 2)
|
||||
# CTreeControl view
|
||||
self.keysview = RegistryTreeView(doc)
|
||||
# CListControl view
|
||||
self.valuesview = RegistryValueView(doc)
|
||||
|
||||
splitter.CreatePane(self.keysview, 0, 0, (sub_size))
|
||||
splitter.CreatePane(self.valuesview, 0, 1, (0, 0)) # size ignored.
|
||||
splitter.SetRowInfo(0, size[1], 0)
|
||||
# Setup items in the imagelist
|
||||
|
||||
return 1
|
||||
|
||||
def OnItemDoubleClick(self, info, extra):
|
||||
(hwndFrom, idFrom, code) = info
|
||||
if idFrom == win32ui.AFX_IDW_PANE_FIRST:
|
||||
# Tree control
|
||||
return None
|
||||
elif idFrom == win32ui.AFX_IDW_PANE_FIRST + 1:
|
||||
item = self.keysview.SelectedItem()
|
||||
self.valuesview.EditValue(item)
|
||||
return 0
|
||||
# List control
|
||||
else:
|
||||
return None # Pass it on
|
||||
|
||||
def PerformItemSelected(self, item):
|
||||
return self.valuesview.UpdateForRegItem(item)
|
||||
|
||||
def OnDestroy(self, msg):
|
||||
window.MDIChildWnd.OnDestroy(self, msg)
|
||||
if self.images:
|
||||
self.images.DeleteImageList()
|
||||
self.images = None
|
||||
|
||||
|
||||
class RegistryTreeView(docview.TreeView):
|
||||
def OnInitialUpdate(self):
|
||||
rc = self._obj_.OnInitialUpdate()
|
||||
self.frame = self.GetParent().GetParent()
|
||||
self.hierList = hierlist.HierListWithItems(
|
||||
self.GetHLIRoot(), win32ui.IDB_HIERFOLDERS, win32ui.AFX_IDW_PANE_FIRST
|
||||
)
|
||||
self.hierList.HierInit(self.frame, self.GetTreeCtrl())
|
||||
self.hierList.SetStyle(
|
||||
commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
|
||||
)
|
||||
self.hierList.PerformItemSelected = self.PerformItemSelected
|
||||
|
||||
self.frame.HookNotify(self.frame.OnItemDoubleClick, commctrl.NM_DBLCLK)
|
||||
self.frame.HookNotify(self.OnItemRightClick, commctrl.NM_RCLICK)
|
||||
|
||||
# self.HookMessage(self.OnItemRightClick, win32con.WM_RBUTTONUP)
|
||||
|
||||
def GetHLIRoot(self):
|
||||
doc = self.GetDocument()
|
||||
regroot = doc.root
|
||||
subkey = doc.subkey
|
||||
return HLIRegistryKey(regroot, subkey, "Root")
|
||||
|
||||
def OnItemRightClick(self, notify_data, extra):
|
||||
# First select the item we right-clicked on.
|
||||
pt = self.ScreenToClient(win32api.GetCursorPos())
|
||||
flags, hItem = self.HitTest(pt)
|
||||
if hItem == 0 or commctrl.TVHT_ONITEM & flags == 0:
|
||||
return None
|
||||
self.Select(hItem, commctrl.TVGN_CARET)
|
||||
|
||||
menu = win32ui.CreatePopupMenu()
|
||||
menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1000, "Add Key")
|
||||
menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1001, "Add Value")
|
||||
menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1002, "Delete Key")
|
||||
self.HookCommand(self.OnAddKey, 1000)
|
||||
self.HookCommand(self.OnAddValue, 1001)
|
||||
self.HookCommand(self.OnDeleteKey, 1002)
|
||||
menu.TrackPopupMenu(win32api.GetCursorPos()) # track at mouse position.
|
||||
return None
|
||||
|
||||
def OnDeleteKey(self, command, code):
|
||||
hitem = self.hierList.GetSelectedItem()
|
||||
item = self.hierList.ItemFromHandle(hitem)
|
||||
msg = f"Are you sure you wish to delete the key '{item.keyName}'?"
|
||||
id = win32ui.MessageBox(msg, None, win32con.MB_YESNO)
|
||||
if id != win32con.IDYES:
|
||||
return
|
||||
if SafeApply(
|
||||
win32api.RegDeleteKey, (item.keyRoot, item.keyName), "deleting registry key"
|
||||
):
|
||||
# Get the items parent.
|
||||
try:
|
||||
hparent = self.GetParentItem(hitem)
|
||||
except win32ui.error:
|
||||
hparent = None
|
||||
self.hierList.Refresh(hparent)
|
||||
|
||||
def OnAddKey(self, command, code):
|
||||
val = dialog.GetSimpleInput("New key name", "", "Add new key")
|
||||
if val is None:
|
||||
return # cancelled.
|
||||
hitem = self.hierList.GetSelectedItem()
|
||||
item = self.hierList.ItemFromHandle(hitem)
|
||||
if SafeApply(win32api.RegCreateKey, (item.keyRoot, item.keyName + "\\" + val)):
|
||||
self.hierList.Refresh(hitem)
|
||||
|
||||
def OnAddValue(self, command, code):
|
||||
val = dialog.GetSimpleInput("New value", "", "Add new value")
|
||||
if val is None:
|
||||
return # cancelled.
|
||||
hitem = self.hierList.GetSelectedItem()
|
||||
item = self.hierList.ItemFromHandle(hitem)
|
||||
if SafeApply(
|
||||
win32api.RegSetValue, (item.keyRoot, item.keyName, win32con.REG_SZ, val)
|
||||
):
|
||||
# Simply re-select the current item to refresh the right spitter.
|
||||
self.PerformItemSelected(item)
|
||||
|
||||
# self.Select(hitem, commctrl.TVGN_CARET)
|
||||
|
||||
def PerformItemSelected(self, item):
|
||||
return self.frame.PerformItemSelected(item)
|
||||
|
||||
def SelectedItem(self):
|
||||
return self.hierList.ItemFromHandle(self.hierList.GetSelectedItem())
|
||||
|
||||
def SearchSelectedItem(self):
|
||||
handle = self.hierList.GetChildItem(0)
|
||||
while 1:
|
||||
# print("State is", self.hierList.GetItemState(handle, -1))
|
||||
if self.hierList.GetItemState(handle, commctrl.TVIS_SELECTED):
|
||||
# print("Item is ", self.hierList.ItemFromHandle(handle))
|
||||
return self.hierList.ItemFromHandle(handle)
|
||||
handle = self.hierList.GetNextSiblingItem(handle)
|
||||
|
||||
|
||||
class RegistryValueView(docview.ListView):
|
||||
def OnInitialUpdate(self):
|
||||
hwnd = self._obj_.GetSafeHwnd()
|
||||
style = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
|
||||
win32api.SetWindowLong(
|
||||
hwnd,
|
||||
win32con.GWL_STYLE,
|
||||
(style & ~commctrl.LVS_TYPEMASK) | commctrl.LVS_REPORT,
|
||||
)
|
||||
|
||||
itemDetails = (commctrl.LVCFMT_LEFT, 100, "Name", 0)
|
||||
self.InsertColumn(0, itemDetails)
|
||||
itemDetails = (commctrl.LVCFMT_LEFT, 500, "Data", 0)
|
||||
self.InsertColumn(1, itemDetails)
|
||||
|
||||
def UpdateForRegItem(self, item):
|
||||
self.DeleteAllItems()
|
||||
hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
|
||||
try:
|
||||
valNum = 0
|
||||
ret = []
|
||||
while 1:
|
||||
try:
|
||||
res = win32api.RegEnumValue(hkey, valNum)
|
||||
except win32api.error:
|
||||
break
|
||||
name = res[0]
|
||||
if not name:
|
||||
name = "(Default)"
|
||||
self.InsertItem(valNum, name)
|
||||
self.SetItemText(valNum, 1, str(res[1]))
|
||||
valNum += 1
|
||||
finally:
|
||||
win32api.RegCloseKey(hkey)
|
||||
|
||||
def EditValue(self, item):
|
||||
# Edit the current value
|
||||
class EditDialog(dialog.Dialog):
|
||||
def __init__(self, item):
|
||||
self.item = item
|
||||
dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT)
|
||||
|
||||
def OnInitDialog(self):
|
||||
self.SetWindowText("Enter new value")
|
||||
self.GetDlgItem(win32con.IDCANCEL).ShowWindow(win32con.SW_SHOW)
|
||||
self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
|
||||
# Modify the edit windows style
|
||||
style = win32api.GetWindowLong(
|
||||
self.edit.GetSafeHwnd(), win32con.GWL_STYLE
|
||||
)
|
||||
style &= ~win32con.ES_WANTRETURN
|
||||
win32api.SetWindowLong(
|
||||
self.edit.GetSafeHwnd(), win32con.GWL_STYLE, style
|
||||
)
|
||||
self.edit.SetWindowText(str(self.item))
|
||||
self.edit.SetSel(-1)
|
||||
return dialog.Dialog.OnInitDialog(self)
|
||||
|
||||
def OnDestroy(self, msg):
|
||||
self.newvalue = self.edit.GetWindowText()
|
||||
|
||||
try:
|
||||
index = self.GetNextItem(-1, commctrl.LVNI_SELECTED)
|
||||
except win32ui.error:
|
||||
return # No item selected.
|
||||
|
||||
if index == 0:
|
||||
keyVal = ""
|
||||
else:
|
||||
keyVal = self.GetItemText(index, 0)
|
||||
# Query for a new value.
|
||||
try:
|
||||
newVal = self.GetItemsCurrentValue(item, keyVal)
|
||||
except TypeError as details:
|
||||
win32ui.MessageBox(details)
|
||||
return
|
||||
|
||||
d = EditDialog(newVal)
|
||||
if d.DoModal() == win32con.IDOK:
|
||||
try:
|
||||
self.SetItemsCurrentValue(item, keyVal, d.newvalue)
|
||||
except win32api.error as exc:
|
||||
win32ui.MessageBox("Error setting value\r\n\n%s" % exc.strerror)
|
||||
self.UpdateForRegItem(item)
|
||||
|
||||
def GetItemsCurrentValue(self, item, valueName):
|
||||
hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
|
||||
try:
|
||||
val, type = win32api.RegQueryValueEx(hkey, valueName)
|
||||
if type != win32con.REG_SZ:
|
||||
raise TypeError("Only strings can be edited")
|
||||
return val
|
||||
finally:
|
||||
win32api.RegCloseKey(hkey)
|
||||
|
||||
def SetItemsCurrentValue(self, item, valueName, value):
|
||||
# ** Assumes already checked is a string.
|
||||
hkey = win32api.RegOpenKey(
|
||||
item.keyRoot, item.keyName, 0, win32con.KEY_SET_VALUE
|
||||
)
|
||||
try:
|
||||
win32api.RegSetValueEx(hkey, valueName, 0, win32con.REG_SZ, value)
|
||||
finally:
|
||||
win32api.RegCloseKey(hkey)
|
||||
|
||||
|
||||
class RegTemplate(docview.DocTemplate):
|
||||
def __init__(self):
|
||||
docview.DocTemplate.__init__(
|
||||
self, win32ui.IDR_PYTHONTYPE, None, SplitterFrame, None
|
||||
)
|
||||
|
||||
# def InitialUpdateFrame(self, frame, doc, makeVisible=1):
|
||||
# self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler.
|
||||
# frame.InitialUpdateFrame(doc, makeVisible)
|
||||
|
||||
def OpenRegistryKey(
|
||||
self, root=None, subkey=None
|
||||
): # Use this instead of OpenDocumentFile.
|
||||
# Look for existing open document
|
||||
if root is None:
|
||||
root = regutil.GetRootKey()
|
||||
if subkey is None:
|
||||
subkey = regutil.BuildDefaultPythonKey()
|
||||
for doc in self.GetDocumentList():
|
||||
if doc.root == root and doc.subkey == subkey:
|
||||
doc.GetFirstView().ActivateFrame()
|
||||
return doc
|
||||
# not found - new one.
|
||||
doc = RegDocument(self, root, subkey)
|
||||
frame = self.CreateNewFrame(doc)
|
||||
doc.OnNewDocument()
|
||||
self.InitialUpdateFrame(frame, doc, 1)
|
||||
return doc
|
||||
|
||||
|
||||
class RegDocument(docview.Document):
|
||||
def __init__(self, template, root, subkey):
|
||||
docview.Document.__init__(self, template)
|
||||
self.root = root
|
||||
self.subkey = subkey
|
||||
self.SetTitle("Registry Editor: " + subkey)
|
||||
|
||||
def OnOpenDocument(self, name):
|
||||
raise TypeError("This template can not open files")
|
||||
return 0
|
||||
|
||||
|
||||
class HLIRegistryKey(hierlist.HierListItem):
|
||||
def __init__(self, keyRoot, keyName, userName):
|
||||
self.keyRoot = keyRoot
|
||||
self.keyName = keyName
|
||||
self.userName = userName
|
||||
hierlist.HierListItem.__init__(self)
|
||||
|
||||
def __lt__(self, other):
|
||||
return self.name < other.name
|
||||
|
||||
def __eq__(self, other):
|
||||
return (
|
||||
self.keyRoot == other.keyRoot
|
||||
and self.keyName == other.keyName
|
||||
and self.userName == other.userName
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return "<{} with root={}, key={}>".format(
|
||||
self.__class__.__name__,
|
||||
self.keyRoot,
|
||||
self.keyName,
|
||||
)
|
||||
|
||||
def GetText(self):
|
||||
return self.userName
|
||||
|
||||
def IsExpandable(self):
|
||||
# All keys are expandable, even if they currently have zero children.
|
||||
return 1
|
||||
|
||||
## hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
|
||||
## try:
|
||||
## keys, vals, dt = win32api.RegQueryInfoKey(hkey)
|
||||
## return (keys>0)
|
||||
## finally:
|
||||
## win32api.RegCloseKey(hkey)
|
||||
|
||||
def GetSubList(self):
|
||||
hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
|
||||
win32ui.DoWaitCursor(1)
|
||||
try:
|
||||
keyNum = 0
|
||||
ret = []
|
||||
while 1:
|
||||
try:
|
||||
key = win32api.RegEnumKey(hkey, keyNum)
|
||||
except win32api.error:
|
||||
break
|
||||
ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key))
|
||||
keyNum += 1
|
||||
finally:
|
||||
win32api.RegCloseKey(hkey)
|
||||
win32ui.DoWaitCursor(0)
|
||||
return ret
|
||||
|
||||
|
||||
template = RegTemplate()
|
||||
|
||||
|
||||
def EditRegistry(root=None, key=None):
|
||||
doc = template.OpenRegistryKey(root, key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
EditRegistry()
|
||||
@@ -0,0 +1,80 @@
|
||||
# (sort-of) Registry editor
|
||||
import commctrl
|
||||
import win32con
|
||||
from pywin.mfc import dialog
|
||||
|
||||
|
||||
class RegistryControl:
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
|
||||
|
||||
class RegEditPropertyPage(dialog.PropertyPage):
|
||||
IDC_LISTVIEW = 1000
|
||||
|
||||
def GetTemplate(self):
|
||||
"Return the template used to create this dialog"
|
||||
|
||||
w = 152 # Dialog width
|
||||
h = 122 # Dialog height
|
||||
SS_STD = win32con.WS_CHILD | win32con.WS_VISIBLE
|
||||
FRAMEDLG_STD = win32con.WS_CAPTION | win32con.WS_SYSMENU
|
||||
style = (
|
||||
FRAMEDLG_STD
|
||||
| win32con.WS_VISIBLE
|
||||
| win32con.DS_SETFONT
|
||||
| win32con.WS_MINIMIZEBOX
|
||||
)
|
||||
template = [
|
||||
[self.caption, (0, 0, w, h), style, None, (8, "Helv")],
|
||||
]
|
||||
lvStyle = (
|
||||
SS_STD
|
||||
| commctrl.LVS_EDITLABELS
|
||||
| commctrl.LVS_REPORT
|
||||
| commctrl.LVS_AUTOARRANGE
|
||||
| commctrl.LVS_ALIGNLEFT
|
||||
| win32con.WS_BORDER
|
||||
| win32con.WS_TABSTOP
|
||||
)
|
||||
template.append(
|
||||
["SysListView32", "", self.IDC_LISTVIEW, (10, 10, 185, 100), lvStyle]
|
||||
)
|
||||
return template
|
||||
|
||||
|
||||
class RegistryPage(RegEditPropertyPage):
|
||||
def __init__(self):
|
||||
self.caption = "Path"
|
||||
RegEditPropertyPage.__init__(self, self.GetTemplate())
|
||||
|
||||
def OnInitDialog(self):
|
||||
self.listview = self.GetDlgItem(self.IDC_LISTVIEW)
|
||||
RegEditPropertyPage.OnInitDialog(self)
|
||||
# Setup the listview columns
|
||||
itemDetails = (commctrl.LVCFMT_LEFT, 100, "App", 0)
|
||||
self.listview.InsertColumn(0, itemDetails)
|
||||
itemDetails = (commctrl.LVCFMT_LEFT, 1024, "Paths", 0)
|
||||
self.listview.InsertColumn(1, itemDetails)
|
||||
|
||||
index = self.listview.InsertItem(0, "App")
|
||||
self.listview.SetItemText(index, 1, "Path")
|
||||
|
||||
|
||||
class RegistrySheet(dialog.PropertySheet):
|
||||
def __init__(self, title):
|
||||
dialog.PropertySheet.__init__(self, title)
|
||||
self.HookMessage(self.OnActivate, win32con.WM_ACTIVATE)
|
||||
|
||||
def OnActivate(self, msg):
|
||||
print("OnAcivate")
|
||||
|
||||
|
||||
def t():
|
||||
ps = RegistrySheet("Registry Settings")
|
||||
ps.AddPage(RegistryPage())
|
||||
ps.DoModal()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
t()
|
||||
Reference in new issue
Block a user