pystc.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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,
  76. wx.FONTFAMILY_MODERN,
  77. wx.FONTSTYLE_NORMAL,
  78. wx.FONTWEIGHT_NORMAL)
  79. face = font.GetFaceName()
  80. size = font.GetPointSize()
  81. # setting the monospace here to not mess with the rest of the code
  82. # TODO: review the whole styling
  83. self.faces = {'times': face,
  84. 'mono': face,
  85. 'helv': face,
  86. 'other': face,
  87. 'size': 10,
  88. 'size2': 8,
  89. }
  90. self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
  91. self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
  92. self.SetLexer(stc.STC_LEX_PYTHON)
  93. self.SetKeyWords(0, " ".join(keyword.kwlist))
  94. self.SetProperty("fold", "1")
  95. self.SetProperty("tab.timmy.whinge.level", "1")
  96. self.SetMargins(0, 0)
  97. self.SetTabWidth(4)
  98. self.SetUseTabs(False)
  99. self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
  100. self.SetEdgeColumn(78)
  101. # show line numbers
  102. self.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
  103. # supporting only 2 or 3 digit line numbers
  104. self.SetMarginWidth(1, 3 * self.faces["size2"])
  105. # setup a margin to hold fold markers
  106. self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
  107. self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
  108. self.SetMarginSensitive(2, True)
  109. self.SetMarginWidth(2, 12)
  110. # like a flattened tree control using square headers
  111. self.MarkerDefine(
  112. stc.STC_MARKNUM_FOLDEROPEN,
  113. stc.STC_MARK_BOXMINUS,
  114. "white",
  115. "#808080")
  116. self.MarkerDefine(
  117. stc.STC_MARKNUM_FOLDER,
  118. stc.STC_MARK_BOXPLUS,
  119. "white",
  120. "#808080")
  121. self.MarkerDefine(
  122. stc.STC_MARKNUM_FOLDERSUB,
  123. stc.STC_MARK_VLINE,
  124. "white",
  125. "#808080")
  126. self.MarkerDefine(
  127. stc.STC_MARKNUM_FOLDERTAIL,
  128. stc.STC_MARK_LCORNER,
  129. "white",
  130. "#808080")
  131. self.MarkerDefine(
  132. stc.STC_MARKNUM_FOLDEREND,
  133. stc.STC_MARK_BOXPLUSCONNECTED,
  134. "white",
  135. "#808080")
  136. self.MarkerDefine(
  137. stc.STC_MARKNUM_FOLDEROPENMID,
  138. stc.STC_MARK_BOXMINUSCONNECTED,
  139. "white",
  140. "#808080")
  141. self.MarkerDefine(
  142. stc.STC_MARKNUM_FOLDERMIDTAIL,
  143. stc.STC_MARK_TCORNER,
  144. "white",
  145. "#808080")
  146. self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
  147. self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
  148. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
  149. # show whitespace
  150. self.SetViewWhiteSpace(1)
  151. # make the symbols very light gray to be less distracting
  152. self.SetWhitespaceForeground(True, wx.Colour(200, 200, 200))
  153. # Make some styles, the lexer defines what each style is used
  154. # for, we just have to define what each style looks like.
  155. # This set is adapted from Scintilla sample property files.
  156. # global default styles for all languages
  157. self.StyleSetSpec(
  158. stc.STC_STYLE_DEFAULT,
  159. "face:%(helv)s,size:%(size)d" %
  160. self.faces)
  161. self.StyleClearAll() # reset all to be like the default
  162. # global default styles for all languages
  163. self.StyleSetSpec(
  164. stc.STC_STYLE_DEFAULT,
  165. "face:%(helv)s,size:%(size)d" %
  166. self.faces)
  167. self.StyleSetSpec(
  168. stc.STC_STYLE_LINENUMBER,
  169. "back:#C0C0C0,face:%(helv)s,size:%(size2)d" %
  170. self.faces)
  171. self.StyleSetSpec(
  172. stc.STC_STYLE_CONTROLCHAR,
  173. "face:%(other)s" %
  174. self.faces)
  175. self.StyleSetSpec(
  176. stc.STC_STYLE_BRACELIGHT,
  177. "fore:#FFFFFF,back:#0000FF,bold")
  178. self.StyleSetSpec(
  179. stc.STC_STYLE_BRACEBAD,
  180. "fore:#000000,back:#FF0000,bold")
  181. # Python styles
  182. # Default
  183. self.StyleSetSpec(
  184. stc.STC_P_DEFAULT,
  185. "fore:#000000,face:%(helv)s,size:%(size)d" %
  186. self.faces)
  187. # Comments
  188. self.StyleSetSpec(
  189. stc.STC_P_COMMENTLINE,
  190. "fore:#007F00,face:%(other)s,size:%(size)d" %
  191. self.faces)
  192. # Number
  193. self.StyleSetSpec(
  194. stc.STC_P_NUMBER,
  195. "fore:#007F7F,size:%(size)d" %
  196. self.faces)
  197. # String
  198. self.StyleSetSpec(
  199. stc.STC_P_STRING,
  200. "fore:#7F007F,face:%(helv)s,size:%(size)d" %
  201. self.faces)
  202. # Single quoted string
  203. self.StyleSetSpec(
  204. stc.STC_P_CHARACTER,
  205. "fore:#7F007F,face:%(helv)s,size:%(size)d" %
  206. self.faces)
  207. # Keyword
  208. self.StyleSetSpec(
  209. stc.STC_P_WORD,
  210. "fore:#00007F,bold,size:%(size)d" %
  211. self.faces)
  212. # Triple quotes
  213. self.StyleSetSpec(
  214. stc.STC_P_TRIPLE,
  215. "fore:#7F0000,size:%(size)d" %
  216. self.faces)
  217. # Triple double quotes
  218. self.StyleSetSpec(
  219. stc.STC_P_TRIPLEDOUBLE,
  220. "fore:#7F0000,size:%(size)d" %
  221. self.faces)
  222. # Class name definition
  223. self.StyleSetSpec(
  224. stc.STC_P_CLASSNAME,
  225. "fore:#0000FF,bold,underline,size:%(size)d" %
  226. self.faces)
  227. # Function or method name definition
  228. self.StyleSetSpec(
  229. stc.STC_P_DEFNAME,
  230. "fore:#007F7F,bold,size:%(size)d" %
  231. self.faces)
  232. # Operators
  233. self.StyleSetSpec(
  234. stc.STC_P_OPERATOR,
  235. "bold,size:%(size)d" %
  236. self.faces)
  237. # Identifiers
  238. self.StyleSetSpec(
  239. stc.STC_P_IDENTIFIER,
  240. "fore:#000000,face:%(helv)s,size:%(size)d" %
  241. self.faces)
  242. # Comment-blocks
  243. self.StyleSetSpec(
  244. stc.STC_P_COMMENTBLOCK,
  245. "fore:#7F7F7F,size:%(size)d" %
  246. self.faces)
  247. # End of line where string is not closed
  248. self.StyleSetSpec(
  249. stc.STC_P_STRINGEOL,
  250. "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" %
  251. self.faces)
  252. self.SetCaretForeground("BLUE")
  253. def OnKeyPressed(self, event):
  254. """Key pressed
  255. .. todo::
  256. implement code completion (see wxPython demo)
  257. """
  258. if not self.modified:
  259. self.modified = True
  260. if self.statusbar:
  261. self.statusbar.SetStatusText(
  262. _('Python script contains local modifications'), 0)
  263. event.Skip()
  264. def OnUpdateUI(self, evt):
  265. # check for matching braces
  266. braceAtCaret = -1
  267. braceOpposite = -1
  268. charBefore = None
  269. caretPos = self.GetCurrentPos()
  270. if caretPos > 0:
  271. charBefore = self.GetCharAt(caretPos - 1)
  272. styleBefore = self.GetStyleAt(caretPos - 1)
  273. # check before
  274. if charBefore and chr(
  275. charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
  276. braceAtCaret = caretPos - 1
  277. # check after
  278. if braceAtCaret < 0:
  279. charAfter = self.GetCharAt(caretPos)
  280. styleAfter = self.GetStyleAt(caretPos)
  281. if charAfter and chr(
  282. charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
  283. braceAtCaret = caretPos
  284. if braceAtCaret >= 0:
  285. braceOpposite = self.BraceMatch(braceAtCaret)
  286. if braceAtCaret != -1 and braceOpposite == -1:
  287. self.BraceBadLight(braceAtCaret)
  288. else:
  289. self.BraceHighlight(braceAtCaret, braceOpposite)
  290. def OnMarginClick(self, evt):
  291. # fold and unfold as needed
  292. if evt.GetMargin() == 2:
  293. if evt.GetShift() and evt.GetControl():
  294. self.FoldAll()
  295. else:
  296. lineClicked = self.LineFromPosition(evt.GetPosition())
  297. if self.GetFoldLevel(
  298. lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
  299. if evt.GetShift():
  300. self.SetFoldExpanded(lineClicked, True)
  301. self.Expand(lineClicked, True, True, 1)
  302. elif evt.GetControl():
  303. if self.GetFoldExpanded(lineClicked):
  304. self.SetFoldExpanded(lineClicked, False)
  305. self.Expand(lineClicked, False, True, 0)
  306. else:
  307. self.SetFoldExpanded(lineClicked, True)
  308. self.Expand(lineClicked, True, True, 100)
  309. else:
  310. self.ToggleFold(lineClicked)
  311. def FoldAll(self):
  312. lineCount = self.GetLineCount()
  313. expanding = True
  314. # find out if we are folding or unfolding
  315. for lineNum in range(lineCount):
  316. if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
  317. expanding = not self.GetFoldExpanded(lineNum)
  318. break
  319. lineNum = 0
  320. while lineNum < lineCount:
  321. level = self.GetFoldLevel(lineNum)
  322. if level & stc.STC_FOLDLEVELHEADERFLAG and \
  323. (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
  324. if expanding:
  325. self.SetFoldExpanded(lineNum, True)
  326. lineNum = self.Expand(lineNum, True)
  327. lineNum = lineNum - 1
  328. else:
  329. lastChild = self.GetLastChild(lineNum, -1)
  330. self.SetFoldExpanded(lineNum, False)
  331. if lastChild > lineNum:
  332. self.HideLines(lineNum + 1, lastChild)
  333. lineNum = lineNum + 1
  334. def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
  335. lastChild = self.GetLastChild(line, level)
  336. line = line + 1
  337. while line <= lastChild:
  338. if force:
  339. if visLevels > 0:
  340. self.ShowLines(line, line)
  341. else:
  342. self.HideLines(line, line)
  343. else:
  344. if doExpand:
  345. self.ShowLines(line, line)
  346. if level == -1:
  347. level = self.GetFoldLevel(line)
  348. if level & stc.STC_FOLDLEVELHEADERFLAG:
  349. if force:
  350. if visLevels > 1:
  351. self.SetFoldExpanded(line, True)
  352. else:
  353. self.SetFoldExpanded(line, False)
  354. line = self.Expand(line, doExpand, force, visLevels - 1)
  355. else:
  356. if doExpand and self.GetFoldExpanded(line):
  357. line = self.Expand(line, True, force, visLevels - 1)
  358. else:
  359. line = self.Expand(line, False, force, visLevels - 1)
  360. else:
  361. line = line + 1
  362. return line