pystc.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. """
  2. @package gui_core.pystc
  3. @brief Python styled text control widget
  4. Classes:
  5. - pystc::PyStc
  6. (C) 2012-2020 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. @author Anna Petrasova <kratochanna gmail.com> (dark theme)
  11. """
  12. import keyword
  13. import wx
  14. from wx import stc
  15. def SetDarkMode(pystc):
  16. """Configure color for dark mode. Adapted from Monokai theme in Spyder."""
  17. dark = {
  18. "background": "#282828",
  19. "foreground": "#ddddda",
  20. "line_foreground": "#C8C8C8",
  21. "line_background": "#4D4D4D",
  22. "comment": "#75715e",
  23. "string": "#e6db74",
  24. "keyword": "#f92672",
  25. "definition": "#a6e22e",
  26. "number": "#ae81ff",
  27. "builtin": "#ae81ff",
  28. "instance": "#ddddda",
  29. "whitespace": "#969696",
  30. }
  31. # Default style
  32. pystc.StyleSetSpec(
  33. stc.STC_STYLE_DEFAULT,
  34. "back:{b},fore:{f}".format(b=dark["background"], f=dark["foreground"]),
  35. )
  36. pystc.StyleClearAll()
  37. pystc.SetSelForeground(
  38. True, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
  39. )
  40. pystc.SetSelBackground(True, wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
  41. pystc.SetCaretForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
  42. pystc.SetWhitespaceForeground(True, wx.Colour(dark["whitespace"]))
  43. # Built in styles
  44. pystc.StyleSetSpec(
  45. stc.STC_STYLE_LINENUMBER,
  46. "fore:{f},back:{b}".format(
  47. f=dark["line_foreground"], b=dark["line_background"]
  48. ),
  49. )
  50. pystc.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#0000FF,back:#FFFF88")
  51. pystc.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#FF0000,back:#FFFF88")
  52. # Python styles
  53. pystc.StyleSetSpec(stc.STC_P_DEFAULT, "fore:{}".format(dark["foreground"]))
  54. pystc.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:{}".format(dark["comment"]))
  55. pystc.StyleSetSpec(stc.STC_P_STRING, "fore:{}".format(dark["string"]))
  56. pystc.StyleSetSpec(stc.STC_P_CHARACTER, "fore:{}".format(dark["string"]))
  57. pystc.StyleSetSpec(stc.STC_P_WORD, "fore:{}".format(dark["keyword"]))
  58. pystc.StyleSetSpec(stc.STC_P_TRIPLE, "fore:{}".format(dark["string"]))
  59. pystc.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:{}".format(dark["string"]))
  60. pystc.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:{}".format(dark["definition"]))
  61. pystc.StyleSetSpec(stc.STC_P_DEFNAME, "fore:{}".format(dark["definition"]))
  62. pystc.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:{}".format(dark["comment"]))
  63. class PyStc(stc.StyledTextCtrl):
  64. """Styled Python output (see gmodeler::frame::PythonPanel for
  65. usage)
  66. Based on StyledTextCtrl_2 from wxPython demo
  67. """
  68. def __init__(self, parent, id=wx.ID_ANY, statusbar=None):
  69. stc.StyledTextCtrl.__init__(self, parent, id)
  70. self.parent = parent
  71. self.statusbar = statusbar
  72. self.modified = False # content modified ?
  73. # this is supposed to get monospace
  74. font = wx.Font(
  75. 9, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL
  76. )
  77. face = font.GetFaceName()
  78. size = font.GetPointSize()
  79. # setting the monospace here to not mess with the rest of the code
  80. # TODO: review the whole styling
  81. self.faces = {
  82. "times": face,
  83. "mono": face,
  84. "helv": face,
  85. "other": face,
  86. "size": 10,
  87. "size2": 8,
  88. }
  89. self.CmdKeyAssign(ord("B"), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
  90. self.CmdKeyAssign(ord("N"), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
  91. self.SetLexer(stc.STC_LEX_PYTHON)
  92. self.SetKeyWords(0, " ".join(keyword.kwlist))
  93. self.SetProperty("fold", "1")
  94. self.SetProperty("tab.timmy.whinge.level", "1")
  95. self.SetMargins(0, 0)
  96. self.SetTabWidth(4)
  97. self.SetUseTabs(False)
  98. self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
  99. self.SetEdgeColumn(78)
  100. # show line numbers
  101. self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
  102. # supporting only 2 or 3 digit line numbers
  103. self.SetMarginWidth(1, 3 * self.faces["size2"])
  104. # setup a margin to hold fold markers
  105. self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
  106. self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
  107. self.SetMarginSensitive(2, True)
  108. self.SetMarginWidth(2, 12)
  109. # like a flattened tree control using square headers
  110. self.MarkerDefine(
  111. stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080"
  112. )
  113. self.MarkerDefine(
  114. stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080"
  115. )
  116. self.MarkerDefine(
  117. stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080"
  118. )
  119. self.MarkerDefine(
  120. stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080"
  121. )
  122. self.MarkerDefine(
  123. stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080"
  124. )
  125. self.MarkerDefine(
  126. stc.STC_MARKNUM_FOLDEROPENMID,
  127. stc.STC_MARK_BOXMINUSCONNECTED,
  128. "white",
  129. "#808080",
  130. )
  131. self.MarkerDefine(
  132. stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080"
  133. )
  134. self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
  135. self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
  136. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  137. # show whitespace
  138. self.SetViewWhiteSpace(1)
  139. # make the symbols very light gray to be less distracting
  140. self.SetWhitespaceForeground(True, wx.Colour(200, 200, 200))
  141. # Make some styles, the lexer defines what each style is used
  142. # for, we just have to define what each style looks like.
  143. # This set is adapted from Scintilla sample property files.
  144. # global default styles for all languages
  145. self.StyleSetSpec(
  146. stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces
  147. )
  148. self.StyleClearAll() # reset all to be like the default
  149. # global default styles for all languages
  150. self.StyleSetSpec(
  151. stc.STC_STYLE_DEFAULT, "face:%(helv)s,size:%(size)d" % self.faces
  152. )
  153. self.StyleSetSpec(
  154. stc.STC_STYLE_LINENUMBER,
  155. "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % self.faces,
  156. )
  157. self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % self.faces)
  158. self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
  159. self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
  160. # Python styles
  161. # Default
  162. self.StyleSetSpec(
  163. stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces
  164. )
  165. # Comments
  166. self.StyleSetSpec(
  167. stc.STC_P_COMMENTLINE,
  168. "fore:#007F00,face:%(other)s,size:%(size)d" % self.faces,
  169. )
  170. # Number
  171. self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % self.faces)
  172. # String
  173. self.StyleSetSpec(
  174. stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces
  175. )
  176. # Single quoted string
  177. self.StyleSetSpec(
  178. stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % self.faces
  179. )
  180. # Keyword
  181. self.StyleSetSpec(
  182. stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % self.faces
  183. )
  184. # Triple quotes
  185. self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % self.faces)
  186. # Triple double quotes
  187. self.StyleSetSpec(
  188. stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % self.faces
  189. )
  190. # Class name definition
  191. self.StyleSetSpec(
  192. stc.STC_P_CLASSNAME,
  193. "fore:#0000FF,bold,underline,size:%(size)d" % self.faces,
  194. )
  195. # Function or method name definition
  196. self.StyleSetSpec(
  197. stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % self.faces
  198. )
  199. # Operators
  200. self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % self.faces)
  201. # Identifiers
  202. self.StyleSetSpec(
  203. stc.STC_P_IDENTIFIER,
  204. "fore:#000000,face:%(helv)s,size:%(size)d" % self.faces,
  205. )
  206. # Comment-blocks
  207. self.StyleSetSpec(
  208. stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % self.faces
  209. )
  210. # End of line where string is not closed
  211. self.StyleSetSpec(
  212. stc.STC_P_STRINGEOL,
  213. "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces,
  214. )
  215. self.SetCaretForeground("BLUE")
  216. def OnKeyPressed(self, event):
  217. """Key pressed
  218. .. todo::
  219. implement code completion (see wxPython demo)
  220. """
  221. if not self.modified:
  222. self.modified = True
  223. if self.statusbar:
  224. self.statusbar.SetStatusText(
  225. _("Python script contains local modifications"), 0
  226. )
  227. event.Skip()
  228. def OnUpdateUI(self, evt):
  229. # check for matching braces
  230. braceAtCaret = -1
  231. braceOpposite = -1
  232. charBefore = None
  233. caretPos = self.GetCurrentPos()
  234. if caretPos > 0:
  235. charBefore = self.GetCharAt(caretPos - 1)
  236. styleBefore = self.GetStyleAt(caretPos - 1)
  237. # check before
  238. if (
  239. charBefore
  240. and chr(charBefore) in "[]{}()"
  241. and styleBefore == stc.STC_P_OPERATOR
  242. ):
  243. braceAtCaret = caretPos - 1
  244. # check after
  245. if braceAtCaret < 0:
  246. charAfter = self.GetCharAt(caretPos)
  247. styleAfter = self.GetStyleAt(caretPos)
  248. if (
  249. charAfter
  250. and chr(charAfter) in "[]{}()"
  251. and styleAfter == stc.STC_P_OPERATOR
  252. ):
  253. braceAtCaret = caretPos
  254. if braceAtCaret >= 0:
  255. braceOpposite = self.BraceMatch(braceAtCaret)
  256. if braceAtCaret != -1 and braceOpposite == -1:
  257. self.BraceBadLight(braceAtCaret)
  258. else:
  259. self.BraceHighlight(braceAtCaret, braceOpposite)
  260. def OnMarginClick(self, evt):
  261. # fold and unfold as needed
  262. if evt.GetMargin() == 2:
  263. if evt.GetShift() and evt.GetControl():
  264. self.FoldAll()
  265. else:
  266. lineClicked = self.LineFromPosition(evt.GetPosition())
  267. if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
  268. if evt.GetShift():
  269. self.SetFoldExpanded(lineClicked, True)
  270. self.Expand(lineClicked, True, True, 1)
  271. elif evt.GetControl():
  272. if self.GetFoldExpanded(lineClicked):
  273. self.SetFoldExpanded(lineClicked, False)
  274. self.Expand(lineClicked, False, True, 0)
  275. else:
  276. self.SetFoldExpanded(lineClicked, True)
  277. self.Expand(lineClicked, True, True, 100)
  278. else:
  279. self.ToggleFold(lineClicked)
  280. def FoldAll(self):
  281. lineCount = self.GetLineCount()
  282. expanding = True
  283. # find out if we are folding or unfolding
  284. for lineNum in range(lineCount):
  285. if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
  286. expanding = not self.GetFoldExpanded(lineNum)
  287. break
  288. lineNum = 0
  289. while lineNum < lineCount:
  290. level = self.GetFoldLevel(lineNum)
  291. if (
  292. level & stc.STC_FOLDLEVELHEADERFLAG
  293. and (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE
  294. ):
  295. if expanding:
  296. self.SetFoldExpanded(lineNum, True)
  297. lineNum = self.Expand(lineNum, True)
  298. lineNum = lineNum - 1
  299. else:
  300. lastChild = self.GetLastChild(lineNum, -1)
  301. self.SetFoldExpanded(lineNum, False)
  302. if lastChild > lineNum:
  303. self.HideLines(lineNum + 1, lastChild)
  304. lineNum = lineNum + 1
  305. def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
  306. lastChild = self.GetLastChild(line, level)
  307. line = line + 1
  308. while line <= lastChild:
  309. if force:
  310. if visLevels > 0:
  311. self.ShowLines(line, line)
  312. else:
  313. self.HideLines(line, line)
  314. else:
  315. if doExpand:
  316. self.ShowLines(line, line)
  317. if level == -1:
  318. level = self.GetFoldLevel(line)
  319. if level & stc.STC_FOLDLEVELHEADERFLAG:
  320. if force:
  321. if visLevels > 1:
  322. self.SetFoldExpanded(line, True)
  323. else:
  324. self.SetFoldExpanded(line, False)
  325. line = self.Expand(line, doExpand, force, visLevels - 1)
  326. else:
  327. if doExpand and self.GetFoldExpanded(line):
  328. line = self.Expand(line, True, force, visLevels - 1)
  329. else:
  330. line = self.Expand(line, False, force, visLevels - 1)
  331. else:
  332. line = line + 1
  333. return line