folder_view.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. # This is a port of the Vista SDK "FolderView" sample, and associated
  2. # notes at http://shellrevealed.com/blogs/shellblog/archive/2007/03/15/Shell-Namespace-Extension_3A00_-Creating-and-Using-the-System-Folder-View-Object.aspx
  3. # A key difference to shell_view.py is that this version uses the default
  4. # IShellView provided by the shell (via SHCreateShellFolderView) rather
  5. # than our own.
  6. # XXX - sadly, it doesn't work quite like the original sample. Oh well,
  7. # another day...
  8. import sys
  9. import os
  10. import pickle
  11. import random
  12. import win32api
  13. import winxpgui as win32gui # the needs vista, let alone xp!
  14. import win32con
  15. import winerror
  16. import commctrl
  17. import pythoncom
  18. from win32com.util import IIDToInterfaceName
  19. from win32com.server.exception import COMException
  20. from win32com.server.util import wrap as _wrap
  21. from win32com.server.util import NewEnum as _NewEnum
  22. from win32com.shell import shell, shellcon
  23. from win32com.axcontrol import axcontrol # IObjectWithSite
  24. from win32com.propsys import propsys
  25. GUID=pythoncom.MakeIID
  26. # If set, output spews to the win32traceutil collector...
  27. debug=0
  28. # wrap a python object in a COM pointer
  29. def wrap(ob, iid=None):
  30. return _wrap(ob, iid, useDispatcher=(debug>0))
  31. def NewEnum(seq, iid):
  32. return _NewEnum(seq, iid=iid, useDispatcher=(debug>0))
  33. # The sample makes heavy use of "string ids" (ie, integer IDs defined in .h
  34. # files, loaded at runtime from a (presumably localized) DLL. We cheat.
  35. _sids = {} # strings, indexed bystring_id,
  36. def LoadString(sid):
  37. return _sids[sid]
  38. # fn to create a unique string ID
  39. _last_ids = 0
  40. def _make_ids(s):
  41. global _last_ids
  42. _last_ids += 1
  43. _sids[_last_ids] = s
  44. return _last_ids
  45. # These strings are what the user sees and would be localized.
  46. # XXX - its possible that the shell might persist these values, so
  47. # this scheme wouldn't really be suitable in a real ap.
  48. IDS_UNSPECIFIED = _make_ids("unspecified")
  49. IDS_SMALL = _make_ids("small")
  50. IDS_MEDIUM = _make_ids("medium")
  51. IDS_LARGE = _make_ids("large")
  52. IDS_CIRCLE = _make_ids("circle")
  53. IDS_TRIANGLE = _make_ids("triangle")
  54. IDS_RECTANGLE = _make_ids("rectangle")
  55. IDS_POLYGON = _make_ids("polygon")
  56. IDS_DISPLAY = _make_ids("Display")
  57. IDS_DISPLAY_TT = _make_ids("Display the item.")
  58. IDS_SETTINGS = _make_ids("Settings")
  59. IDS_SETTING1 = _make_ids("Setting 1")
  60. IDS_SETTING2 = _make_ids("Setting 2")
  61. IDS_SETTING3 = _make_ids("Setting 3")
  62. IDS_SETTINGS_TT = _make_ids("Modify settings.")
  63. IDS_SETTING1_TT = _make_ids("Modify setting 1.")
  64. IDS_SETTING2_TT = _make_ids("Modify setting 2.")
  65. IDS_SETTING3_TT = _make_ids("Modify setting 3.")
  66. IDS_LESSTHAN5 = _make_ids("Less Than 5")
  67. IDS_5ORGREATER = _make_ids("Five or Greater")
  68. del _make_ids, _last_ids
  69. # Other misc resource stuff
  70. IDI_ICON1 = 100
  71. IDI_SETTINGS = 101
  72. # The sample defines a number of "category ids". Each one gets
  73. # its own GUID.
  74. CAT_GUID_NAME=GUID("{de094c9d-c65a-11dc-ba21-005056c00008}")
  75. CAT_GUID_SIZE=GUID("{de094c9e-c65a-11dc-ba21-005056c00008}")
  76. CAT_GUID_SIDES=GUID("{de094c9f-c65a-11dc-ba21-005056c00008}")
  77. CAT_GUID_LEVEL=GUID("{de094ca0-c65a-11dc-ba21-005056c00008}")
  78. # The next category guid is NOT based on a column (see
  79. # ViewCategoryProvider::EnumCategories()...)
  80. CAT_GUID_VALUE="{de094ca1-c65a-11dc-ba21-005056c00008}"
  81. GUID_Display=GUID("{4d6c2fdd-c689-11dc-ba21-005056c00008}")
  82. GUID_Settings=GUID("{4d6c2fde-c689-11dc-ba21-005056c00008}")
  83. GUID_Setting1=GUID("{4d6c2fdf-c689-11dc-ba21-005056c00008}")
  84. GUID_Setting2=GUID("{4d6c2fe0-c689-11dc-ba21-005056c00008}")
  85. GUID_Setting3=GUID("{4d6c2fe1-c689-11dc-ba21-005056c00008}")
  86. # Hrm - not sure what to do about the std keys.
  87. # Probably need a simple parser for propkey.h
  88. PKEY_ItemNameDisplay = ("{B725F130-47EF-101A-A5F1-02608C9EEBAC}", 10)
  89. PKEY_PropList_PreviewDetails = ("{C9944A21-A406-48FE-8225-AEC7E24C211B}", 8)
  90. # Not sure what the "3" here refers to - docs say PID_FIRST_USABLE (2) be
  91. # used. Presumably it is the 'propID' value in the .propdesc file!
  92. # note that the following GUIDs are also references in the .propdesc file
  93. PID_SOMETHING=3
  94. # These are our 'private' PKEYs
  95. # Col 2, name="Sample.AreaSize"
  96. PKEY_Sample_AreaSize=("{d6f5e341-c65c-11dc-ba21-005056c00008}", PID_SOMETHING)
  97. # Col 3, name="Sample.NumberOfSides"
  98. PKEY_Sample_NumberOfSides = ("{d6f5e342-c65c-11dc-ba21-005056c00008}", PID_SOMETHING)
  99. # Col 4, name="Sample.DirectoryLevel"
  100. PKEY_Sample_DirectoryLevel = ("{d6f5e343-c65c-11dc-ba21-005056c00008}", PID_SOMETHING)
  101. # We construct a PIDL from a pickle of a dict - turn it back into a
  102. # dict (we should *never* be called with a PIDL that the last elt is not
  103. # ours, so it is safe to assume we created it (assume->"ass" = "u" + "me" :)
  104. def pidl_to_item(pidl):
  105. # Note that only the *last* elt in the PIDL is certainly ours,
  106. # but it contains everything we need encoded as a dict.
  107. return pickle.loads(pidl[-1])
  108. # Start of msdn sample port...
  109. # make_item_enum replaces the sample's entire EnumIDList.cpp :)
  110. def make_item_enum(level, flags):
  111. pidls = []
  112. nums = """zero one two three four five size seven eight nine ten""".split()
  113. for i, name in enumerate(nums):
  114. size = random.randint(0,255)
  115. sides = 1
  116. while sides in [1,2]:
  117. sides = random.randint(0,5)
  118. is_folder = (i % 2) != 0
  119. # check the flags say to include it.
  120. # (This seems strange; if you ask the same folder for, but appear
  121. skip = False
  122. if not (flags & shellcon.SHCONTF_STORAGE):
  123. if is_folder:
  124. skip = not (flags & shellcon.SHCONTF_FOLDERS)
  125. else:
  126. skip = not (flags & shellcon.SHCONTF_NONFOLDERS)
  127. if not skip:
  128. data = dict(name=name, size=size, sides=sides, level=level, is_folder=is_folder)
  129. pidls.append([pickle.dumps(data)])
  130. return NewEnum(pidls, shell.IID_IEnumIDList)
  131. # start of Utils.cpp port
  132. def DisplayItem(shell_item_array, hwnd_parent=0):
  133. # Get the first ShellItem and display its name
  134. if shell_item_array is None:
  135. msg = "You must select something!"
  136. else:
  137. si = shell_item_array.GetItemAt(0)
  138. name = si.GetDisplayName(shellcon.SIGDN_NORMALDISPLAY)
  139. msg = "%d items selected, first is %r" % (shell_item_array.GetCount(), name)
  140. win32gui.MessageBox(hwnd_parent, msg, "Hello", win32con.MB_OK)
  141. # end of Utils.cpp port
  142. # start of sample's FVCommands.cpp port
  143. class Command:
  144. def __init__(self, guid, ids, ids_tt, idi, flags, callback, children):
  145. self.guid = guid; self.ids = ids; self.ids_tt = ids_tt
  146. self.idi = idi; self.flags = flags; self.callback = callback;
  147. self.children = children
  148. assert not children or isinstance(children[0], Command)
  149. def tuple(self):
  150. return self.guid, self.ids, self.ids_tt, self.idi, self.flags, self.callback, self.children
  151. # command callbacks - called back directly by us - see ExplorerCommand.Invoke
  152. def onDisplay(items, bindctx):
  153. DisplayItem(items)
  154. def onSetting1(items, bindctx):
  155. win32gui.MessageBox(0, LoadString(IDS_SETTING1), "Hello", win32con.MB_OK)
  156. def onSetting2(items, bindctx):
  157. win32gui.MessageBox(0, LoadString(IDS_SETTING2), "Hello", win32con.MB_OK)
  158. def onSetting3(items, bindctx):
  159. win32gui.MessageBox(0, LoadString(IDS_SETTING3), "Hello", win32con.MB_OK)
  160. taskSettings = [
  161. Command(GUID_Setting1, IDS_SETTING1, IDS_SETTING1_TT, IDI_SETTINGS, 0, onSetting1, None),
  162. Command(GUID_Setting2, IDS_SETTING2, IDS_SETTING2_TT, IDI_SETTINGS, 0, onSetting2, None),
  163. Command(GUID_Setting3, IDS_SETTING3, IDS_SETTING3_TT, IDI_SETTINGS, 0, onSetting3, None),
  164. ]
  165. tasks = [
  166. Command(GUID_Display, IDS_DISPLAY, IDS_DISPLAY_TT, IDI_ICON1, 0, onDisplay, None ),
  167. Command(GUID_Settings, IDS_SETTINGS, IDS_SETTINGS_TT, IDI_SETTINGS, shellcon.ECF_HASSUBCOMMANDS, None, taskSettings),
  168. ]
  169. class ExplorerCommandProvider:
  170. _com_interfaces_ = [shell.IID_IExplorerCommandProvider]
  171. _public_methods_ = shellcon.IExplorerCommandProvider_Methods
  172. def GetCommands(self, site, iid):
  173. items = [wrap(ExplorerCommand(t)) for t in tasks]
  174. return NewEnum(items, shell.IID_IEnumExplorerCommand)
  175. class ExplorerCommand:
  176. _com_interfaces_ = [shell.IID_IExplorerCommand]
  177. _public_methods_ = shellcon.IExplorerCommand_Methods
  178. def __init__(self, cmd):
  179. self.cmd = cmd
  180. # The sample also appears to ignore the pidl args!?
  181. def GetTitle(self, pidl):
  182. return LoadString(self.cmd.ids)
  183. def GetToolTip(self, pidl):
  184. return LoadString(self.cmd.ids_tt)
  185. def GetIcon(self, pidl):
  186. # Return a string of the usual "dll,resource_id" format
  187. # todo - just return any ".ico that comes with python" + ",0" :)
  188. raise COMException(hresult=winerror.E_NOTIMPL)
  189. def GetState(self, shell_items, slow_ok):
  190. return shellcon.ECS_ENABLED
  191. def GetFlags(self):
  192. return self.cmd.flags
  193. def GetCanonicalName(self):
  194. return self.cmd.guid
  195. def Invoke(self, items, bind_ctx):
  196. # If no function defined - just return S_OK
  197. if self.cmd.callback:
  198. self.cmd.callback(items, bind_ctx)
  199. else:
  200. print "No callback for command ", LoadString(self.cmd.ids)
  201. def EnumSubCommands(self):
  202. if not self.cmd.children:
  203. return None
  204. items = [wrap(ExplorerCommand(c))
  205. for c in self.cmd.children]
  206. return NewEnum(items, shell.IID_IEnumExplorerCommand)
  207. # end of sample's FVCommands.cpp port
  208. # start of sample's Category.cpp port
  209. class FolderViewCategorizer:
  210. _com_interfaces_ = [shell.IID_ICategorizer]
  211. _public_methods_ = shellcon.ICategorizer_Methods
  212. description = None # subclasses should set their own
  213. def __init__(self, shell_folder):
  214. self.sf = shell_folder
  215. # Determines the relative order of two items in their item identifier lists.
  216. def CompareCategory(self, flags, cat1, cat2):
  217. return cat1-cat2
  218. # Retrieves the name of a categorizer, such as "Group By Device
  219. # Type", that can be displayed in the user interface.
  220. def GetDescription(self, cch):
  221. return self.description
  222. # Retrieves information about a category, such as the default
  223. # display and the text to display in the user interface.
  224. def GetCategoryInfo(self, catid):
  225. # Note: this isn't always appropriate! See overrides below
  226. return 0, str(catid) # ????
  227. class FolderViewCategorizer_Name(FolderViewCategorizer):
  228. description = "Alphabetical"
  229. def GetCategory(self, pidls):
  230. ret = []
  231. for pidl in pidls:
  232. val = self.sf.GetDetailsEx(pidl, PKEY_ItemNameDisplay)
  233. ret.append(val)
  234. return ret
  235. class FolderViewCategorizer_Size(FolderViewCategorizer):
  236. description = "Group By Size"
  237. def GetCategory(self, pidls):
  238. ret = []
  239. for pidl in pidls:
  240. # Why don't we just get the size of the PIDL?
  241. val = self.sf.GetDetailsEx(pidl, PKEY_Sample_AreaSize)
  242. val = int(val) # it probably came in a VT_BSTR variant
  243. if val < 255//3:
  244. cid = IDS_SMALL
  245. elif val < 2 * 255 // 3:
  246. cid = IDS_MEDIUM
  247. else:
  248. cid = IDS_LARGE
  249. ret.append(cid)
  250. return ret
  251. def GetCategoryInfo(self, catid):
  252. return 0, LoadString(catid)
  253. class FolderViewCategorizer_Sides(FolderViewCategorizer):
  254. description = "Group By Sides"
  255. def GetCategory(self, pidls):
  256. ret = []
  257. for pidl in pidls:
  258. val = self.sf.GetDetailsEx(pidl, PKEY_ItemNameDisplay)
  259. if val==0:
  260. cid = IDS_CIRCLE
  261. elif val==3:
  262. cid = IDS_TRIANGLE
  263. elif val==4:
  264. cid = IDS_RECTANGLE
  265. elif val==5:
  266. cid = IDS_POLYGON
  267. else:
  268. cid = IDS_UNSPECIFIED
  269. ret.append(cid)
  270. return ret
  271. def GetCategoryInfo(self, catid):
  272. return 0, LoadString(catid)
  273. class FolderViewCategorizer_Value(FolderViewCategorizer):
  274. description = "Group By Value"
  275. def GetCategory(self, pidls):
  276. ret = []
  277. for pidl in pidls:
  278. val = self.sf.GetDetailsEx(pidl, PKEY_ItemNameDisplay)
  279. if val in "one two three four".split():
  280. ret.append(IDS_LESSTHAN5)
  281. else:
  282. ret.append(IDS_5ORGREATER)
  283. return ret
  284. def GetCategoryInfo(self, catid):
  285. return 0, LoadString(catid)
  286. class FolderViewCategorizer_Level(FolderViewCategorizer):
  287. description = "Group By Value"
  288. def GetCategory(self, pidls):
  289. return [self.sf.GetDetailsEx(pidl, PKEY_Sample_DirectoryLevel) for pidl in pidls]
  290. class ViewCategoryProvider:
  291. _com_interfaces_ = [shell.IID_ICategoryProvider]
  292. _public_methods_ = shellcon.ICategoryProvider_Methods
  293. def __init__(self, shell_folder):
  294. self.shell_folder = shell_folder
  295. def CanCategorizeOnSCID(self, pkey):
  296. return pkey in [PKEY_ItemNameDisplay, PKEY_Sample_AreaSize,
  297. PKEY_Sample_NumberOfSides, PKEY_Sample_DirectoryLevel]
  298. # Creates a category object.
  299. def CreateCategory(self, guid, iid):
  300. if iid == shell.IID_ICategorizer:
  301. if guid == CAT_GUID_NAME:
  302. klass = FolderViewCategorizer_Name
  303. elif guid == CAT_GUID_SIDES:
  304. klass = FolderViewCategorizer_Sides
  305. elif guid == CAT_GUID_SIZE:
  306. klass = FolderViewCategorizer_Size
  307. elif guid == CAT_GUID_VALUE:
  308. klass = FolderViewCategorizer_Value
  309. elif guid == CAT_GUID_LEVEL:
  310. klass = FolderViewCategorizer_Level
  311. else:
  312. raise COMException(hresult=winerror.E_INVALIDARG)
  313. return wrap(klass(self.shell_folder))
  314. raise COMException(hresult=winerror.E_NOINTERFACE)
  315. # Retrieves the enumerator for the categories.
  316. def EnumCategories(self):
  317. # These are additional categories beyond the columns
  318. seq = [CAT_GUID_VALUE]
  319. return NewEnum(seq, pythoncom.IID_IEnumGUID)
  320. # Retrieves a globally unique identifier (GUID) that represents
  321. # the categorizer to use for the specified Shell column.
  322. def GetCategoryForSCID(self, scid):
  323. if scid==PKEY_ItemNameDisplay:
  324. guid = CAT_GUID_NAME
  325. elif scid == PKEY_Sample_AreaSize:
  326. guid = CAT_GUID_SIZE
  327. elif scid == PKEY_Sample_NumberOfSides:
  328. guid = CAT_GUID_SIDES
  329. elif scid == PKEY_Sample_DirectoryLevel:
  330. guid = CAT_GUID_LEVEL
  331. elif scid == pythoncom.IID_NULL:
  332. # This can be called with a NULL
  333. # format ID. This will happen if you have a category,
  334. # not based on a column, that gets stored in the
  335. # property bag. When a return is made to this item,
  336. # it will call this function with a NULL format id.
  337. guid = CAT_GUID_VALUE
  338. else:
  339. raise COMException(hresult=winerror.E_INVALIDARG)
  340. return guid
  341. # Retrieves the name of the specified category. This is where
  342. # additional categories that appear under the column
  343. # related categories in the UI, get their display names.
  344. def GetCategoryName(self, guid, cch):
  345. if guid == CAT_GUID_VALUE:
  346. return "Value"
  347. raise COMException(hresult=winerror.E_FAIL)
  348. # Enables the folder to override the default grouping.
  349. def GetDefaultCategory(self):
  350. return CAT_GUID_LEVEL, (pythoncom.IID_NULL, 0)
  351. # end of sample's Category.cpp port
  352. # start of sample's ContextMenu.cpp port
  353. MENUVERB_DISPLAY = 0
  354. folderViewImplContextMenuIDs = [
  355. ("display", MENUVERB_DISPLAY, 0, ),
  356. ]
  357. class ContextMenu:
  358. _reg_progid_ = "Python.ShellFolderSample.ContextMenu"
  359. _reg_desc_ = "Python FolderView Context Menu"
  360. _reg_clsid_ = "{fed40039-021f-4011-87c5-6188b9979764}"
  361. _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu, axcontrol.IID_IObjectWithSite]
  362. _public_methods_ = shellcon.IContextMenu_Methods + shellcon.IShellExtInit_Methods + ["GetSite", "SetSite"]
  363. _context_menu_type_ = "PythonFolderViewSampleType"
  364. def __init__(self):
  365. self.site = None
  366. self.dataobj = None
  367. def Initialize(self, folder, dataobj, hkey):
  368. self.dataobj = dataobj
  369. def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
  370. s = LoadString(IDS_DISPLAY);
  371. win32gui.InsertMenu(hMenu, indexMenu, win32con.MF_BYPOSITION, idCmdFirst + MENUVERB_DISPLAY, s);
  372. indexMenu += 1
  373. # other verbs could go here...
  374. # indicate that we added one verb.
  375. return 1
  376. def InvokeCommand(self, ci):
  377. mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
  378. # this seems very convuluted, but its what the sample does :)
  379. for verb_name, verb_id, flag in folderViewImplContextMenuIDs:
  380. if isinstance(verb, int):
  381. matches = verb==verb_id
  382. else:
  383. matches = verb==verb_name
  384. if matches:
  385. break
  386. else:
  387. assert False, ci # failed to find our ID
  388. if verb_id == MENUVERB_DISPLAY:
  389. sia = shell.SHCreateShellItemArrayFromDataObject(self.dataobj)
  390. DisplayItem(hwnd, sia)
  391. else:
  392. assert False, ci # Got some verb we weren't expecting?
  393. def GetCommandString(self, cmd, typ):
  394. raise COMException(hresult=winerror.E_NOTIMPL)
  395. def SetSite(self, site):
  396. self.site = site
  397. def GetSite(self, iid):
  398. return self.site
  399. # end of sample's ContextMenu.cpp port
  400. # start of sample's ShellFolder.cpp port
  401. class ShellFolder:
  402. _com_interfaces_ = [shell.IID_IBrowserFrameOptions,
  403. pythoncom.IID_IPersist,
  404. shell.IID_IPersistFolder,
  405. shell.IID_IPersistFolder2,
  406. shell.IID_IShellFolder,
  407. shell.IID_IShellFolder2,
  408. ]
  409. _public_methods_ = shellcon.IBrowserFrame_Methods + \
  410. shellcon.IPersistFolder2_Methods + \
  411. shellcon.IShellFolder2_Methods
  412. _reg_progid_ = "Python.ShellFolderSample.Folder2"
  413. _reg_desc_ = "Python FolderView sample"
  414. _reg_clsid_ = "{bb8c24ad-6aaa-4cec-ac5e-c429d5f57627}"
  415. max_levels = 5
  416. def __init__(self, level=0):
  417. self.current_level = level
  418. self.pidl = None # set when Initialize is called
  419. def ParseDisplayName(self, hwnd, reserved, displayName, attr):
  420. #print "ParseDisplayName", displayName
  421. raise COMException(hresult=winerror.E_NOTIMPL)
  422. def EnumObjects(self, hwndOwner, flags):
  423. if self.current_level >= self.max_levels:
  424. return None
  425. return make_item_enum(self.current_level+1, flags)
  426. def BindToObject(self, pidl, bc, iid):
  427. tail = pidl_to_item(pidl)
  428. # assert tail['is_folder'], "BindToObject should only be called on folders?"
  429. # *sob*
  430. # No point creating object just to have QI fail.
  431. if iid not in ShellFolder._com_interfaces_:
  432. raise COMException(hresult=winerror.E_NOTIMPL)
  433. child = ShellFolder(self.current_level+1)
  434. # hrmph - not sure what multiple PIDLs here mean?
  435. # assert len(pidl)==1, pidl # expecting just relative child PIDL
  436. child.Initialize(self.pidl + pidl)
  437. return wrap(child, iid)
  438. def BindToStorage(self, pidl, bc, iid):
  439. return self.BindToObject(pidl, bc, iid)
  440. def CompareIDs(self, param, id1, id2):
  441. return 0 # XXX - todo - implement this!
  442. def CreateViewObject(self, hwnd, iid):
  443. if iid == shell.IID_IShellView:
  444. com_folder = wrap(self)
  445. return shell.SHCreateShellFolderView(com_folder)
  446. elif iid == shell.IID_ICategoryProvider:
  447. return wrap(ViewCategoryProvider(self))
  448. elif iid == shell.IID_IContextMenu:
  449. ws = wrap(self)
  450. dcm = (hwnd, None, self.pidl, ws, None)
  451. return shell.SHCreateDefaultContextMenu(dcm, iid)
  452. elif iid == shell.IID_IExplorerCommandProvider:
  453. return wrap(ExplorerCommandProvider())
  454. else:
  455. raise COMException(hresult=winerror.E_NOINTERFACE)
  456. def GetAttributesOf(self, pidls, attrFlags):
  457. assert len(pidls)==1, "sample only expects 1 too!"
  458. assert len(pidls[0])==1, "expect relative pidls!"
  459. item = pidl_to_item(pidls[0])
  460. flags = 0
  461. if item['is_folder']:
  462. flags |= shellcon.SFGAO_FOLDER
  463. if item['level'] < self.max_levels:
  464. flags |= shellcon.SFGAO_HASSUBFOLDER
  465. return flags
  466. # Retrieves an OLE interface that can be used to carry out
  467. # actions on the specified file objects or folders.
  468. def GetUIObjectOf(self, hwndOwner, pidls, iid, inout):
  469. assert len(pidls)==1, "oops - arent expecting more than one!"
  470. assert len(pidls[0])==1, "assuming relative pidls!"
  471. item = pidl_to_item(pidls[0])
  472. if iid == shell.IID_IContextMenu:
  473. ws = wrap(self)
  474. dcm = (hwndOwner, None, self.pidl, ws, pidls)
  475. return shell.SHCreateDefaultContextMenu(dcm, iid)
  476. elif iid == shell.IID_IExtractIconW:
  477. dxi = shell.SHCreateDefaultExtractIcon()
  478. # dxi is IDefaultExtractIconInit
  479. if item['is_folder']:
  480. dxi.SetNormalIcon("shell32.dll", 4)
  481. else:
  482. dxi.SetNormalIcon("shell32.dll", 1)
  483. # just return the dxi - let Python QI for IID_IExtractIconW
  484. return dxi
  485. elif iid == pythoncom.IID_IDataObject:
  486. return shell.SHCreateDataObject(self.pidl, pidls, None, iid);
  487. elif iid == shell.IID_IQueryAssociations:
  488. elts = []
  489. if item['is_folder']:
  490. elts.append((shellcon.ASSOCCLASS_FOLDER, None, None))
  491. elts.append((shellcon.ASSOCCLASS_PROGID_STR, None, ContextMenu._context_menu_type_))
  492. return shell.AssocCreateForClasses(elts, iid)
  493. raise COMException(hresult=winerror.E_NOINTERFACE)
  494. # Retrieves the display name for the specified file object or subfolder.
  495. def GetDisplayNameOf(self, pidl, flags):
  496. item = pidl_to_item(pidl)
  497. if flags & shellcon.SHGDN_FORPARSING:
  498. if flags & shellcon.SHGDN_INFOLDER:
  499. return item['name']
  500. else:
  501. if flags & shellcon.SHGDN_FORADDRESSBAR:
  502. sigdn = shellcon.SIGDN_DESKTOPABSOLUTEEDITING
  503. else:
  504. sigdn = shellcon.SIGDN_DESKTOPABSOLUTEPARSING
  505. parent = shell.SHGetNameFromIDList(self.pidl, sigdn)
  506. return parent + "\\" + item['name']
  507. else:
  508. return item['name']
  509. def SetNameOf(self, hwndOwner, pidl, new_name, flags):
  510. raise COMException(hresult=winerror.E_NOTIMPL)
  511. def GetClassID(self):
  512. return self._reg_clsid_
  513. # IPersistFolder method
  514. def Initialize(self, pidl):
  515. self.pidl = pidl
  516. # IShellFolder2 methods
  517. def EnumSearches(self):
  518. raise COMException(hresult=winerror.E_NOINTERFACE)
  519. # Retrieves the default sorting and display columns.
  520. def GetDefaultColumn(self, dwres):
  521. # result is (sort, display)
  522. return 0, 0
  523. # Retrieves the default state for a specified column.
  524. def GetDefaultColumnState(self, iCol):
  525. if iCol < 3:
  526. return shellcon.SHCOLSTATE_ONBYDEFAULT | shellcon.SHCOLSTATE_TYPE_STR
  527. raise COMException(hresult=winerror.E_INVALIDARG)
  528. # Requests the GUID of the default search object for the folder.
  529. def GetDefaultSearchGUID(self):
  530. raise COMException(hresult=winerror.E_NOTIMPL)
  531. # Helper function for getting the display name for a column.
  532. def _GetColumnDisplayName(self, pidl, pkey):
  533. item = pidl_to_item(pidl)
  534. is_folder = item['is_folder']
  535. if pkey == PKEY_ItemNameDisplay:
  536. val = item['name']
  537. elif pkey == PKEY_Sample_AreaSize and not is_folder:
  538. val = "%d Sq. Ft." % item['size']
  539. elif pkey == PKEY_Sample_NumberOfSides and not is_folder:
  540. val = str(item['sides']) # not sure why str()
  541. elif pkey == PKEY_Sample_DirectoryLevel:
  542. val = str(item['level'])
  543. else:
  544. val = ''
  545. return val
  546. # Retrieves detailed information, identified by a
  547. # property set ID (FMTID) and property ID (PID),
  548. # on an item in a Shell folder.
  549. def GetDetailsEx(self, pidl, pkey):
  550. item = pidl_to_item(pidl)
  551. is_folder = item['is_folder']
  552. if not is_folder and pkey == PKEY_PropList_PreviewDetails:
  553. return "prop:Sample.AreaSize;Sample.NumberOfSides;Sample.DirectoryLevel"
  554. return self._GetColumnDisplayName(pidl, pkey)
  555. # Retrieves detailed information, identified by a
  556. # column index, on an item in a Shell folder.
  557. def GetDetailsOf(self, pidl, iCol):
  558. key = self.MapColumnToSCID(iCol);
  559. if pidl is None:
  560. data = [(commctrl.LVCFMT_LEFT, "Name"),
  561. (commctrl.LVCFMT_CENTER, "Size"),
  562. (commctrl.LVCFMT_CENTER, "Sides"),
  563. (commctrl.LVCFMT_CENTER, "Level"),]
  564. if iCol >= len(data):
  565. raise COMException(hresult=winerror.E_FAIL)
  566. fmt, val = data[iCol]
  567. else:
  568. fmt = 0 # ?
  569. val = self._GetColumnDisplayName(pidl, key)
  570. cxChar = 24
  571. return fmt, cxChar, val
  572. # Converts a column name to the appropriate
  573. # property set ID (FMTID) and property ID (PID).
  574. def MapColumnToSCID(self, iCol):
  575. data = [PKEY_ItemNameDisplay, PKEY_Sample_AreaSize,
  576. PKEY_Sample_NumberOfSides, PKEY_Sample_DirectoryLevel]
  577. if iCol >= len(data):
  578. raise COMException(hresult=winerror.E_FAIL)
  579. return data[iCol]
  580. # IPersistFolder2 methods
  581. # Retrieves the PIDLIST_ABSOLUTE for the folder object.
  582. def GetCurFolder(self):
  583. # The docs say this is OK, but I suspect its a problem in this case :)
  584. #assert self.pidl, "haven't been initialized?"
  585. return self.pidl
  586. # end of sample's ShellFolder.cpp port
  587. def get_schema_fname():
  588. me = win32api.GetFullPathName(__file__)
  589. sc = os.path.splitext(me)[0] + ".propdesc"
  590. assert os.path.isfile(sc), sc
  591. return sc
  592. def DllRegisterServer():
  593. import _winreg
  594. if sys.getwindowsversion()[0] < 6:
  595. print "This sample only works on Vista"
  596. sys.exit(1)
  597. key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE,
  598. "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" \
  599. "Explorer\\Desktop\\Namespace\\" + \
  600. ShellFolder._reg_clsid_)
  601. _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellFolder._reg_desc_)
  602. # And special shell keys under our CLSID
  603. key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
  604. "CLSID\\" + ShellFolder._reg_clsid_ + "\\ShellFolder")
  605. # 'Attributes' is an int stored as a binary! use struct
  606. attr = shellcon.SFGAO_FOLDER | shellcon.SFGAO_HASSUBFOLDER | \
  607. shellcon.SFGAO_BROWSABLE
  608. import struct
  609. s = struct.pack("i", attr)
  610. _winreg.SetValueEx(key, "Attributes", 0, _winreg.REG_BINARY, s)
  611. # register the context menu handler under the FolderViewSampleType type.
  612. keypath = "%s\\shellex\\ContextMenuHandlers\\%s" % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_)
  613. key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, keypath)
  614. _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ContextMenu._reg_clsid_)
  615. propsys.PSRegisterPropertySchema(get_schema_fname())
  616. print ShellFolder._reg_desc_, "registration complete."
  617. def DllUnregisterServer():
  618. import _winreg
  619. paths = [
  620. "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_,
  621. "%s\\shellex\\ContextMenuHandlers\\%s" % (ContextMenu._context_menu_type_, ContextMenu._reg_desc_),
  622. ]
  623. for path in paths:
  624. try:
  625. _winreg.DeleteKey(_winreg.HKEY_LOCAL_MACHINE, path)
  626. except WindowsError, details:
  627. import errno
  628. if details.errno != errno.ENOENT:
  629. print "FAILED to remove %s: %s" % (path, details)
  630. propsys.PSUnregisterPropertySchema(get_schema_fname())
  631. print ShellFolder._reg_desc_, "unregistration complete."
  632. if __name__=='__main__':
  633. from win32com.server import register
  634. register.UseCommandLine(ShellFolder, ContextMenu,
  635. debug = debug,
  636. finalize_register = DllRegisterServer,
  637. finalize_unregister = DllUnregisterServer)