PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/Lib/site-packages/pythonwin/pywin/scintilla/document.py

https://gitlab.com/orvi2014/rcs-db-ext
Python | 275 lines | 197 code | 29 blank | 49 comment | 46 complexity | e46f835793b669500dcecdbe040c0352 MD5 | raw file
  1. import win32ui
  2. from pywin.mfc import docview
  3. from pywin import default_scintilla_encoding
  4. import scintillacon
  5. import win32con
  6. import string
  7. import os
  8. import codecs
  9. import re
  10. crlf_bytes = "\r\n".encode("ascii")
  11. lf_bytes = "\n".encode("ascii")
  12. # re from pep263 - but we use it both on bytes and strings.
  13. re_encoding_bytes = re.compile("coding[:=]\s*([-\w.]+)".encode("ascii"))
  14. re_encoding_text = re.compile("coding[:=]\s*([-\w.]+)")
  15. ParentScintillaDocument=docview.Document
  16. class CScintillaDocument(ParentScintillaDocument):
  17. "A SyntEdit document. "
  18. def __init__(self, *args):
  19. self.bom = None # the BOM, if any, read from the file.
  20. # the encoding we detected from the source. Might have
  21. # detected via the BOM or an encoding decl. Note that in
  22. # the latter case (ie, while self.bom is None), it can't be
  23. # trusted - the user may have edited the encoding decl between
  24. # open and save.
  25. self.source_encoding = None
  26. ParentScintillaDocument.__init__(self, *args)
  27. def DeleteContents(self):
  28. pass
  29. def OnOpenDocument(self, filename):
  30. # init data members
  31. #print "Opening", filename
  32. self.SetPathName(filename) # Must set this early!
  33. try:
  34. # load the text as binary we can get smart
  35. # about detecting any existing EOL conventions.
  36. f = open(filename, 'rb')
  37. try:
  38. self._LoadTextFromFile(f)
  39. finally:
  40. f.close()
  41. except IOError:
  42. rc = win32ui.MessageBox("Could not load the file from %s\n\nDo you want to create a new file?" % filename,
  43. "Pythonwin", win32con.MB_YESNO | win32con.MB_ICONWARNING)
  44. if rc == win32con.IDNO:
  45. return 0
  46. assert rc == win32con.IDYES, rc
  47. try:
  48. f = open(filename, 'wb+')
  49. try:
  50. self._LoadTextFromFile(f)
  51. finally:
  52. f.close()
  53. except IOError, e:
  54. rc = win32ui.MessageBox("Cannot create the file %s" % filename)
  55. return 1
  56. def SaveFile(self, fileName):
  57. view = self.GetFirstView()
  58. ok = view.SaveTextFile(fileName)
  59. if ok:
  60. view.SCISetSavePoint()
  61. return ok
  62. def ApplyFormattingStyles(self):
  63. self._ApplyOptionalToViews("ApplyFormattingStyles")
  64. # #####################
  65. # File related functions
  66. # Helper to transfer text from the MFC document to the control.
  67. def _LoadTextFromFile(self, f):
  68. # detect EOL mode - we don't support \r only - so find the
  69. # first '\n' and guess based on the char before.
  70. l = f.readline()
  71. l2 = f.readline()
  72. # If line ends with \r\n or has no line ending, use CRLF.
  73. if l.endswith(crlf_bytes) or not l.endswith(lf_bytes):
  74. eol_mode = scintillacon.SC_EOL_CRLF
  75. else:
  76. eol_mode = scintillacon.SC_EOL_LF
  77. # Detect the encoding - first look for a BOM, and if not found,
  78. # look for a pep263 encoding declaration.
  79. for bom, encoding in (
  80. (codecs.BOM_UTF8, "utf8"),
  81. (codecs.BOM_UTF16_LE, "utf_16_le"),
  82. (codecs.BOM_UTF16_BE, "utf_16_be"),
  83. ):
  84. if l.startswith(bom):
  85. self.bom = bom
  86. self.source_encoding = encoding
  87. l = l[len(bom):] # remove it.
  88. break
  89. else:
  90. # no bom detected - look for pep263 encoding decl.
  91. for look in (l, l2):
  92. # Note we are looking at raw bytes here: so
  93. # both the re itself uses bytes and the result
  94. # is bytes - but we need the result as a string.
  95. match = re_encoding_bytes.search(look)
  96. if match is not None:
  97. self.source_encoding = match.group(1).decode("ascii")
  98. break
  99. # reading by lines would be too slow? Maybe we can use the
  100. # incremental encoders? For now just stick with loading the
  101. # entire file in memory.
  102. text = l + l2 + f.read()
  103. # Translate from source encoding to UTF-8 bytes for Scintilla
  104. source_encoding = self.source_encoding
  105. # If we don't know an encoding, just use latin-1 to treat
  106. # it as bytes...
  107. if source_encoding is None:
  108. source_encoding = 'latin1'
  109. # we could optimize this by avoiding utf8 to-ing and from-ing,
  110. # but then we would lose the ability to handle invalid utf8
  111. # (and even then, the use of encoding aliases makes this tricky)
  112. # To create an invalid utf8 file:
  113. # >>> open(filename, "wb").write(codecs.BOM_UTF8+"bad \xa9har\r\n")
  114. try:
  115. dec = text.decode(source_encoding)
  116. except UnicodeError:
  117. print "WARNING: Failed to decode bytes from '%s' encoding - treating as latin1" % source_encoding
  118. print "WARNING: Do not modify this file - you will not be able to save it."
  119. dec = text.decode('latin1')
  120. except LookupError:
  121. print "WARNING: Invalid encoding '%s' specified - treating as latin1" % source_encoding
  122. print "WARNING: Do not modify this file - you will not be able to save it."
  123. dec = text.decode('latin1')
  124. # and put it back as utf8 - this shouldn't fail.
  125. text = dec.encode(default_scintilla_encoding)
  126. view = self.GetFirstView()
  127. if view.IsWindow():
  128. # Turn off undo collection while loading
  129. view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 0, 0)
  130. # Make sure the control isnt read-only
  131. view.SetReadOnly(0)
  132. view.SendScintilla(scintillacon.SCI_CLEARALL)
  133. view.SendMessage(scintillacon.SCI_ADDTEXT, text)
  134. view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 1, 0)
  135. view.SendScintilla(win32con.EM_EMPTYUNDOBUFFER, 0, 0)
  136. # set EOL mode
  137. view.SendScintilla(scintillacon.SCI_SETEOLMODE, eol_mode)
  138. def _SaveTextToFile(self, view, filename):
  139. s = view.GetTextRange() # already decoded from scintilla's encoding
  140. source_encoding = None
  141. if self.bom:
  142. source_encoding = self.source_encoding
  143. else:
  144. # no BOM - look for an encoding.
  145. bits = re.split("[\r\n]*", s, 3)
  146. for look in bits[:-1]:
  147. match = re_encoding_text.search(look)
  148. if match is not None:
  149. source_encoding = match.group(1)
  150. self.source_encoding = source_encoding
  151. break
  152. if source_encoding is None:
  153. source_encoding = 'latin1'
  154. ## encode data before opening file so script is not lost if encoding fails
  155. file_contents = s.encode(source_encoding)
  156. # Open in binary mode as scintilla itself ensures the
  157. # line endings are already appropriate
  158. f = open(filename, 'wb')
  159. try:
  160. if self.bom:
  161. f.write(self.bom)
  162. f.write(file_contents)
  163. finally:
  164. f.close()
  165. self.SetModifiedFlag(0)
  166. def FinalizeViewCreation(self, view):
  167. pass
  168. def HookViewNotifications(self, view):
  169. parent = view.GetParentFrame()
  170. parent.HookNotify(ViewNotifyDelegate(self, "OnBraceMatch"), scintillacon.SCN_CHECKBRACE)
  171. parent.HookNotify(ViewNotifyDelegate(self, "OnMarginClick"), scintillacon.SCN_MARGINCLICK)
  172. parent.HookNotify(ViewNotifyDelegate(self, "OnNeedShown"), scintillacon.SCN_NEEDSHOWN)
  173. parent.HookNotify(DocumentNotifyDelegate(self, "OnSavePointReached"), scintillacon.SCN_SAVEPOINTREACHED)
  174. parent.HookNotify(DocumentNotifyDelegate(self, "OnSavePointLeft"), scintillacon.SCN_SAVEPOINTLEFT)
  175. parent.HookNotify(DocumentNotifyDelegate(self, "OnModifyAttemptRO"), scintillacon.SCN_MODIFYATTEMPTRO)
  176. # Tell scintilla what characters should abort auto-complete.
  177. view.SCIAutoCStops(string.whitespace+"()[]:;+-/*=\\?'!#@$%^&,<>\"'|" )
  178. if view != self.GetFirstView():
  179. view.SCISetDocPointer(self.GetFirstView().SCIGetDocPointer())
  180. def OnSavePointReached(self, std, extra):
  181. self.SetModifiedFlag(0)
  182. def OnSavePointLeft(self, std, extra):
  183. self.SetModifiedFlag(1)
  184. def OnModifyAttemptRO(self, std, extra):
  185. self.MakeDocumentWritable()
  186. # All Marker functions are 1 based.
  187. def MarkerAdd( self, lineNo, marker ):
  188. self.GetEditorView().SCIMarkerAdd(lineNo-1, marker)
  189. def MarkerCheck(self, lineNo, marker ):
  190. v = self.GetEditorView()
  191. lineNo = lineNo - 1 # Make 0 based
  192. markerState = v.SCIMarkerGet(lineNo)
  193. return markerState & (1<<marker) != 0
  194. def MarkerToggle( self, lineNo, marker ):
  195. v = self.GetEditorView()
  196. if self.MarkerCheck(lineNo, marker):
  197. v.SCIMarkerDelete(lineNo-1, marker)
  198. else:
  199. v.SCIMarkerAdd(lineNo-1, marker)
  200. def MarkerDelete( self, lineNo, marker ):
  201. self.GetEditorView().SCIMarkerDelete(lineNo-1, marker)
  202. def MarkerDeleteAll( self, marker ):
  203. self.GetEditorView().SCIMarkerDeleteAll(marker)
  204. def MarkerGetNext(self, lineNo, marker):
  205. return self.GetEditorView().SCIMarkerNext( lineNo-1, 1 << marker )+1
  206. def MarkerAtLine(self, lineNo, marker):
  207. markerState = self.GetEditorView().SCIMarkerGet(lineNo-1)
  208. return markerState & (1<<marker)
  209. # Helper for reflecting functions to views.
  210. def _ApplyToViews(self, funcName, *args):
  211. for view in self.GetAllViews():
  212. func = getattr(view, funcName)
  213. func(*args)
  214. def _ApplyOptionalToViews(self, funcName, *args):
  215. for view in self.GetAllViews():
  216. func = getattr(view, funcName, None)
  217. if func is not None:
  218. func(*args)
  219. def GetEditorView(self):
  220. # Find the first frame with a view,
  221. # then ask it to give the editor view
  222. # as it knows which one is "active"
  223. try:
  224. frame_gev = self.GetFirstView().GetParentFrame().GetEditorView
  225. except AttributeError:
  226. return self.GetFirstView()
  227. return frame_gev()
  228. # Delegate to the correct view, based on the control that sent it.
  229. class ViewNotifyDelegate:
  230. def __init__(self, doc, name):
  231. self.doc = doc
  232. self.name = name
  233. def __call__(self, std, extra):
  234. (hwndFrom, idFrom, code) = std
  235. for v in self.doc.GetAllViews():
  236. if v.GetSafeHwnd() == hwndFrom:
  237. return getattr(v, self.name)(*(std, extra))
  238. # Delegate to the document, but only from a single view (as each view sends it seperately)
  239. class DocumentNotifyDelegate:
  240. def __init__(self, doc, name):
  241. self.doc = doc
  242. self.delegate = getattr(doc, name)
  243. def __call__(self, std, extra):
  244. (hwndFrom, idFrom, code) = std
  245. if hwndFrom == self.doc.GetEditorView().GetSafeHwnd():
  246. self.delegate(*(std, extra))