testPersist.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import pythoncom
  2. import win32com.server.util
  3. import time
  4. import win32com, sys, string, win32api, traceback
  5. import win32com.client.dynamic
  6. import win32com.client
  7. import pythoncom
  8. from win32com.axcontrol import axcontrol
  9. from pywintypes import Unicode
  10. from win32com import storagecon
  11. from win32com.test.util import CheckClean
  12. import pywintypes
  13. import win32ui
  14. import win32api, os
  15. from pywin32_testutil import str2bytes
  16. S_OK = 0
  17. import datetime
  18. if issubclass(pywintypes.TimeType, datetime.datetime):
  19. import win32timezone
  20. now = win32timezone.now()
  21. else:
  22. now = pywintypes.Time(time.time())
  23. class LockBytes:
  24. _public_methods_ = [ 'ReadAt', 'WriteAt', 'Flush', 'SetSize', 'LockRegion', 'UnlockRegion', 'Stat' ]
  25. _com_interfaces_ = [ pythoncom.IID_ILockBytes ]
  26. def __init__(self, data = ""):
  27. self.data = str2bytes(data)
  28. self.ctime = now
  29. self.mtime = now
  30. self.atime = now
  31. def ReadAt(self, offset, cb):
  32. print "ReadAt"
  33. result = self.data[offset:offset + cb]
  34. return result
  35. def WriteAt(self, offset, data):
  36. print "WriteAt " +str(offset)
  37. print "len " + str(len(data))
  38. print "data:"
  39. #print data
  40. if len(self.data) >= offset:
  41. newdata = self.data[0:offset] + data
  42. print len(newdata)
  43. if len(self.data) >= offset + len(data):
  44. newdata = newdata + self.data[offset + len(data):]
  45. print len(newdata)
  46. self.data = newdata
  47. return len(data)
  48. def Flush(self, whatsthis=0):
  49. print "Flush" + str(whatsthis)
  50. fname = os.path.join(win32api.GetTempPath(), "persist.doc")
  51. open(fname, "wb").write(self.data)
  52. return S_OK
  53. def SetSize(self, size):
  54. print "Set Size" + str(size)
  55. if size > len(self.data):
  56. self.data = self.data + str2bytes("\000" * (size - len(self.data)))
  57. else:
  58. self.data = self.data[0:size]
  59. return S_OK
  60. def LockRegion(self, offset, size, locktype):
  61. print "LockRegion"
  62. pass
  63. def UnlockRegion(self, offset, size, locktype):
  64. print "UnlockRegion"
  65. pass
  66. def Stat(self, statflag):
  67. print "returning Stat " + str(statflag)
  68. return (
  69. "PyMemBytes",
  70. storagecon.STGTY_LOCKBYTES,
  71. len(self.data),
  72. self.mtime,
  73. self.ctime,
  74. self.atime,
  75. storagecon.STGM_DIRECT|storagecon.STGM_READWRITE|storagecon.STGM_CREATE ,
  76. storagecon.STGM_SHARE_EXCLUSIVE,
  77. "{00020905-0000-0000-C000-000000000046}",
  78. 0, # statebits ?
  79. 0
  80. )
  81. class OleClientSite:
  82. _public_methods_ = [ 'SaveObject', 'GetMoniker', 'GetContainer', 'ShowObject', 'OnShowWindow', 'RequestNewObjectLayout' ]
  83. _com_interfaces_ = [ axcontrol.IID_IOleClientSite ]
  84. def __init__(self, data = ""):
  85. self.IPersistStorage = None
  86. self.IStorage = None
  87. def SetIPersistStorage(self, IPersistStorage):
  88. self.IPersistStorage = IPersistStorage
  89. def SetIStorage(self, IStorage):
  90. self.IStorage = IStorage
  91. def SaveObject(self):
  92. print "SaveObject"
  93. if self.IPersistStorage != None and self.IStorage != None:
  94. self.IPersistStorage.Save(self.IStorage,1)
  95. self.IStorage.Commit(0)
  96. return S_OK
  97. def GetMoniker(self, dwAssign, dwWhichMoniker):
  98. print "GetMoniker " + str(dwAssign) + " " + str(dwWhichMoniker)
  99. def GetContainer(self):
  100. print "GetContainer"
  101. def ShowObject(self):
  102. print "ShowObject"
  103. def OnShowWindow(self, fShow):
  104. print "ShowObject" + str(fShow)
  105. def RequestNewObjectLayout(self):
  106. print "RequestNewObjectLayout"
  107. def test():
  108. # create a LockBytes object and
  109. #wrap it as a COM object
  110. # import win32com.server.dispatcher
  111. lbcom = win32com.server.util.wrap(LockBytes(), pythoncom.IID_ILockBytes) #, useDispatcher=win32com.server.dispatcher.DispatcherWin32trace)
  112. # create a structured storage on the ILockBytes object
  113. stcom = pythoncom.StgCreateDocfileOnILockBytes(lbcom, storagecon.STGM_DIRECT| storagecon.STGM_CREATE | storagecon.STGM_READWRITE | storagecon.STGM_SHARE_EXCLUSIVE, 0)
  114. # create our ClientSite
  115. ocs = OleClientSite()
  116. # wrap it as a COM object
  117. ocscom = win32com.server.util.wrap(ocs, axcontrol.IID_IOleClientSite)
  118. # create a Word OLE Document, connect it to our site and our storage
  119. oocom=axcontrol.OleCreate("{00020906-0000-0000-C000-000000000046}",
  120. axcontrol.IID_IOleObject,
  121. 0,
  122. (0,),
  123. ocscom,
  124. stcom,
  125. )
  126. mf=win32ui.GetMainFrame()
  127. hwnd=mf.GetSafeHwnd()
  128. # Set the host and document name
  129. # for unknown reason document name becomes hostname, and document name
  130. # is not set, debugged it, but don't know where the problem is?
  131. oocom.SetHostNames("OTPython", "This is Cool")
  132. # activate the OLE document
  133. oocom.DoVerb( -1, ocscom, 0, hwnd, mf.GetWindowRect())
  134. # set the hostnames again
  135. oocom.SetHostNames("OTPython2", "ThisisCool2")
  136. # get IDispatch of Word
  137. doc=win32com.client.Dispatch(oocom.QueryInterface(pythoncom.IID_IDispatch))
  138. # get IPersistStorage of Word
  139. dpcom=oocom.QueryInterface(pythoncom.IID_IPersistStorage)
  140. # let our ClientSite know the interfaces
  141. ocs.SetIPersistStorage(dpcom)
  142. ocs.SetIStorage(stcom)
  143. # use IDispatch to do the Office Word test
  144. # pasted from TestOffice.py
  145. wrange = doc.Range()
  146. for i in range(10):
  147. wrange.InsertAfter("Hello from Python %d\n" % i)
  148. paras = doc.Paragraphs
  149. for i in range(len(paras)):
  150. paras[i]().Font.ColorIndex = i+1
  151. paras[i]().Font.Size = 12 + (4 * i)
  152. # XXX - note that
  153. # for para in paras:
  154. # para().Font...
  155. # doesnt seem to work - no error, just doesnt work
  156. # Should check if it works for VB!
  157. dpcom.Save(stcom, 0)
  158. dpcom.HandsOffStorage()
  159. # oocom.Close(axcontrol.OLECLOSE_NOSAVE) # or OLECLOSE_SAVEIFDIRTY, but it fails???
  160. #Save the ILockBytes data to "persist2.doc"
  161. lbcom.Flush()
  162. #exiting Winword will automatically update the ILockBytes data
  163. #and flush it to "%TEMP%\persist.doc"
  164. doc.Application.Quit()
  165. if __name__=='__main__':
  166. test()
  167. pythoncom.CoUninitialize()
  168. CheckClean()