Laurent@814: #!/usr/bin/env python
Laurent@814: # -*- coding: utf-8 -*-
Laurent@814: 
andrej@1571: # This file is part of Beremiz, a Integrated Development Environment for
andrej@1571: # programming IEC 61131-3 automates supporting plcopen standard and CanFestival.
Laurent@814: #
andrej@1571: # Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
Laurent@814: #
andrej@1571: # See COPYING file for copyrights details.
Laurent@814: #
andrej@1571: # This program is free software; you can redistribute it and/or
andrej@1571: # modify it under the terms of the GNU General Public License
andrej@1571: # as published by the Free Software Foundation; either version 2
andrej@1571: # of the License, or (at your option) any later version.
Laurent@814: #
andrej@1571: # This program is distributed in the hope that it will be useful,
andrej@1571: # but WITHOUT ANY WARRANTY; without even the implied warranty of
andrej@1571: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
andrej@1571: # GNU General Public License for more details.
Laurent@814: #
andrej@1571: # You should have received a copy of the GNU General Public License
andrej@1571: # along with this program; if not, write to the Free Software
andrej@1571: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
Laurent@814: 
andrej@1853: 
andrej@1853: from __future__ import absolute_import
andrej@2437: from __future__ import division
Laurent@814: import re
andrej@2456: from functools import reduce
Laurent@814: 
Laurent@814: import wx
Laurent@814: import wx.stc
andrej@2432: from six.moves import xrange
Laurent@814: 
Laurent@814: from graphics.GraphicCommons import ERROR_HIGHLIGHT, SEARCH_RESULT_HIGHLIGHT, REFRESH_HIGHLIGHT_PERIOD
andrej@1850: from plcopen.structures import ST_BLOCK_START_KEYWORDS, IEC_BLOCK_START_KEYWORDS, LOCATIONDATATYPES
andrej@1853: from editors.EditorPanel import EditorPanel
andrej@1850: from controls.CustomStyledTextCtrl import CustomStyledTextCtrl, faces, GetCursorPos
Laurent@814: 
andrej@1782: # -------------------------------------------------------------------------------
Laurent@814: #                         Textual programs Viewer class
andrej@1782: # -------------------------------------------------------------------------------
Laurent@814: 
Laurent@814: 
Laurent@814: NEWLINE = "\n"
Laurent@814: NUMBERS = [str(i) for i in xrange(10)]
Laurent@814: LETTERS = ['_']
Laurent@814: for i in xrange(26):
Laurent@814:     LETTERS.append(chr(ord('a') + i))
Laurent@814:     LETTERS.append(chr(ord('A') + i))
Laurent@814: 
Edouard@1409: [STC_PLC_WORD, STC_PLC_COMMENT, STC_PLC_NUMBER, STC_PLC_STRING,
Edouard@1409:  STC_PLC_VARIABLE, STC_PLC_PARAMETER, STC_PLC_FUNCTION, STC_PLC_JUMP,
andrej@1509:  STC_PLC_ERROR, STC_PLC_SEARCH_RESULT,
andrej@1509:  STC_PLC_EMPTY] = range(11)
Laurent@871: [SPACE, WORD, NUMBER, STRING, WSTRING, COMMENT, PRAGMA, DPRAGMA] = range(8)
Laurent@814: 
andrej@1773: [
andrej@1773:     ID_TEXTVIEWER, ID_TEXTVIEWERTEXTCTRL,
Laurent@814: ] = [wx.NewId() for _init_ctrls in range(2)]
Laurent@814: 
Laurent@814: re_texts = {}
Laurent@814: re_texts["letter"] = "[A-Za-z]"
Laurent@814: re_texts["digit"] = "[0-9]"
andrej@1734: re_texts["identifier"] = "((?:%(letter)s|(?:_(?:%(letter)s|%(digit)s)))(?:_?(?:%(letter)s|%(digit)s))*)" % re_texts
Laurent@814: IDENTIFIER_MODEL = re.compile(re_texts["identifier"])
andrej@1734: LABEL_MODEL = re.compile("[ \t\n]%(identifier)s:[ \t\n]" % re_texts)
Laurent@814: EXTENSIBLE_PARAMETER = re.compile("IN[1-9][0-9]*$")
Laurent@814: 
Laurent@814: HIGHLIGHT_TYPES = {
Laurent@814:     ERROR_HIGHLIGHT: STC_PLC_ERROR,
Laurent@814:     SEARCH_RESULT_HIGHLIGHT: STC_PLC_SEARCH_RESULT,
Laurent@814: }
Laurent@814: 
andrej@1736: 
Laurent@814: def LineStartswith(line, symbols):
andrej@1833:     return reduce(lambda x, y: x or y, map(line.startswith, symbols), False)
Laurent@814: 
andrej@1736: 
Laurent@814: class TextViewer(EditorPanel):
Edouard@1409: 
Laurent@814:     ID = ID_TEXTVIEWER
Edouard@1409: 
Laurent@814:     def _init_Editor(self, prnt):
Edouard@1409:         self.Editor = CustomStyledTextCtrl(id=ID_TEXTVIEWERTEXTCTRL,
andrej@1768:                                            parent=prnt, name="TextViewer", size=wx.Size(0, 0), style=0)
Laurent@814:         self.Editor.ParentWindow = self
Edouard@1409: 
Laurent@814:         self.Editor.CmdKeyAssign(ord('+'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_ZOOMIN)
Laurent@814:         self.Editor.CmdKeyAssign(ord('-'), wx.stc.STC_SCMOD_CTRL, wx.stc.STC_CMD_ZOOMOUT)
Edouard@1409: 
Laurent@814:         self.Editor.SetViewWhiteSpace(False)
Edouard@1409: 
Laurent@814:         self.Editor.SetLexer(wx.stc.STC_LEX_CONTAINER)
Edouard@1409: 
Laurent@814:         # Global default styles for all languages
Laurent@814:         self.Editor.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleClearAll()  # Reset all to be like the default
Edouard@1409: 
Laurent@814:         self.Editor.StyleSetSpec(wx.stc.STC_STYLE_LINENUMBER,  "back:#C0C0C0,size:%(size)d" % faces)
Laurent@814:         self.Editor.SetSelBackground(1, "#E0E0E0")
Edouard@1409: 
Laurent@814:         # Highlighting styles
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_WORD, "fore:#00007F,bold,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_VARIABLE, "fore:#7F0000,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_PARAMETER, "fore:#7F007F,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_FUNCTION, "fore:#7F7F00,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_COMMENT, "fore:#7F7F7F,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_NUMBER, "fore:#007F7F,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_STRING, "fore:#007F00,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_JUMP, "fore:#FF7FFF,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_ERROR, "fore:#FF0000,back:#FFFF00,size:%(size)d" % faces)
Laurent@814:         self.Editor.StyleSetSpec(STC_PLC_SEARCH_RESULT, "fore:#FFFFFF,back:#FFA500,size:%(size)d" % faces)
Edouard@1409: 
Laurent@814:         # Indicators styles
Laurent@814:         self.Editor.IndicatorSetStyle(0, wx.stc.STC_INDIC_SQUIGGLE)
Laurent@814:         if self.ParentWindow is not None and self.Controler is not None:
Laurent@814:             self.Editor.IndicatorSetForeground(0, wx.RED)
Laurent@814:         else:
Laurent@814:             self.Editor.IndicatorSetForeground(0, wx.WHITE)
Edouard@1409: 
Laurent@814:         # Line numbers in the margin
Laurent@814:         self.Editor.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
Laurent@814:         self.Editor.SetMarginWidth(1, 50)
Edouard@1409: 
Laurent@814:         # Folding
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPEN,    wx.stc.STC_MARK_BOXMINUS,          "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDER,        wx.stc.STC_MARK_BOXPLUS,           "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERSUB,     wx.stc.STC_MARK_VLINE,             "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERTAIL,    wx.stc.STC_MARK_LCORNER,           "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEREND,     wx.stc.STC_MARK_BOXPLUSCONNECTED,  "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPENMID, wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
Laurent@814:         self.Editor.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL, wx.stc.STC_MARK_TCORNER,           "white", "#808080")
Edouard@1409: 
Laurent@814:         # Indentation size
Laurent@814:         self.Editor.SetTabWidth(2)
Laurent@814:         self.Editor.SetUseTabs(0)
Edouard@1409: 
andrej@1742:         self.Editor.SetModEventMask(wx.stc.STC_MOD_BEFOREINSERT |
andrej@1742:                                     wx.stc.STC_MOD_BEFOREDELETE |
Laurent@814:                                     wx.stc.STC_PERFORMED_USER)
Laurent@814: 
Laurent@814:         self.Bind(wx.stc.EVT_STC_STYLENEEDED, self.OnStyleNeeded, id=ID_TEXTVIEWERTEXTCTRL)
Laurent@814:         self.Editor.Bind(wx.stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
Laurent@1126:         self.Editor.Bind(wx.stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
Laurent@814:         self.Editor.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
Laurent@814:         if self.Controler is not None:
Laurent@814:             self.Editor.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
Laurent@814:             self.Bind(wx.stc.EVT_STC_DO_DROP, self.OnDoDrop, id=ID_TEXTVIEWERTEXTCTRL)
Laurent@814:             self.Bind(wx.stc.EVT_STC_MODIFIED, self.OnModification, id=ID_TEXTVIEWERTEXTCTRL)
Edouard@1409: 
andrej@1744:     def __init__(self, parent, tagname, window, controler, debug=False, instancepath=""):
Laurent@814:         if tagname != "" and controler is not None:
Laurent@814:             self.VARIABLE_PANEL_TYPE = controler.GetPouType(tagname.split("::")[1])
Edouard@1409: 
Laurent@814:         EditorPanel.__init__(self, parent, tagname, window, controler, debug)
Edouard@1409: 
Laurent@814:         self.Keywords = []
Laurent@814:         self.Variables = {}
Laurent@814:         self.Functions = {}
Laurent@814:         self.TypeNames = []
Laurent@814:         self.Jumps = []
Laurent@814:         self.EnumeratedValues = []
Laurent@814:         self.DisableEvents = True
Laurent@814:         self.TextSyntax = None
Laurent@814:         self.CurrentAction = None
Edouard@1409: 
Laurent@814:         self.InstancePath = instancepath
Laurent@814:         self.ContextStack = []
Laurent@814:         self.CallStack = []
Edouard@1409: 
Laurent@1178:         self.ResetSearchResults()
Edouard@1409: 
Laurent@814:         self.RefreshHighlightsTimer = wx.Timer(self, -1)
Laurent@814:         self.Bind(wx.EVT_TIMER, self.OnRefreshHighlightsTimer, self.RefreshHighlightsTimer)
Edouard@1409: 
Laurent@814:     def __del__(self):
Laurent@814:         self.RefreshHighlightsTimer.Stop()
Edouard@1409: 
Laurent@814:     def GetTitle(self):
Laurent@814:         if self.Debug or self.TagName == "":
Laurent@814:             if len(self.InstancePath) > 15:
Laurent@814:                 return "..." + self.InstancePath[-12:]
Laurent@814:             return self.InstancePath
Laurent@814:         return EditorPanel.GetTitle(self)
Edouard@1409: 
Laurent@814:     def GetInstancePath(self):
Laurent@814:         return self.InstancePath
Edouard@1409: 
Laurent@814:     def IsViewing(self, tagname):
Laurent@814:         if self.Debug or self.TagName == "":
Laurent@814:             return self.InstancePath == tagname
Laurent@814:         else:
Laurent@814:             return self.TagName == tagname
Edouard@1409: 
Laurent@814:     def GetText(self):
Laurent@814:         return self.Editor.GetText()
Edouard@1409: 
Laurent@814:     def SetText(self, text):
Laurent@814:         self.Editor.SetText(text)
Edouard@1409: 
Laurent@814:     def SelectAll(self):
Laurent@814:         self.Editor.SelectAll()
Edouard@1409: 
Laurent@814:     def Colourise(self, start, end):
Laurent@814:         self.Editor.Colourise(start, end)
Edouard@1409: 
Laurent@814:     def StartStyling(self, pos, mask):
Laurent@814:         self.Editor.StartStyling(pos, mask)
Edouard@1409: 
Laurent@814:     def SetStyling(self, length, style):
Laurent@814:         self.Editor.SetStyling(length, style)
Edouard@1409: 
Laurent@814:     def GetCurrentPos(self):
Laurent@814:         return self.Editor.GetCurrentPos()
Edouard@1409: 
Laurent@1178:     def ResetSearchResults(self):
Laurent@1178:         self.Highlights = []
Laurent@1178:         self.SearchParams = None
Laurent@1178:         self.SearchResults = None
Laurent@1178:         self.CurrentFindHighlight = None
Edouard@1409: 
Laurent@814:     def OnModification(self, event):
Laurent@814:         if not self.DisableEvents:
Laurent@814:             mod_type = event.GetModificationType()
andrej@1745:             if mod_type & wx.stc.STC_MOD_BEFOREINSERT:
andrej@1743:                 if self.CurrentAction is None:
Laurent@814:                     self.StartBuffering()
Laurent@814:                 elif self.CurrentAction[0] != "Add" or self.CurrentAction[1] != event.GetPosition() - 1:
Laurent@814:                     self.Controler.EndBuffering()
Laurent@814:                     self.StartBuffering()
Laurent@814:                 self.CurrentAction = ("Add", event.GetPosition())
Laurent@814:                 wx.CallAfter(self.RefreshModel)
andrej@1745:             elif mod_type & wx.stc.STC_MOD_BEFOREDELETE:
andrej@1743:                 if self.CurrentAction is None:
Laurent@814:                     self.StartBuffering()
Laurent@814:                 elif self.CurrentAction[0] != "Delete" or self.CurrentAction[1] != event.GetPosition() + 1:
Laurent@814:                     self.Controler.EndBuffering()
Laurent@814:                     self.StartBuffering()
Laurent@814:                 self.CurrentAction = ("Delete", event.GetPosition())
Laurent@814:                 wx.CallAfter(self.RefreshModel)
Laurent@814:         event.Skip()
Edouard@1409: 
Laurent@814:     def OnDoDrop(self, event):
Laurent@814:         try:
Laurent@814:             values = eval(event.GetDragText())
andrej@1780:         except Exception:
Laurent@814:             values = event.GetDragText()
Laurent@814:         if isinstance(values, tuple):
Laurent@814:             message = None
Laurent@814:             if values[1] in ["program", "debug"]:
Laurent@814:                 event.SetDragText("")
Laurent@814:             elif values[1] in ["functionBlock", "function"]:
Laurent@814:                 blocktype = values[0]
Laurent@814:                 blockname = values[2]
Laurent@814:                 if len(values) > 3:
Laurent@814:                     blockinputs = values[3]
Laurent@814:                 else:
Laurent@814:                     blockinputs = None
Edouard@1409:                 if values[1] != "function":
Laurent@814:                     if blockname == "":
andrej@1745:                         dialog = wx.TextEntryDialog(self.ParentWindow, _("Block name"), _("Please enter a block name"), "", wx.OK | wx.CANCEL | wx.CENTRE)
Laurent@814:                         if dialog.ShowModal() == wx.ID_OK:
Laurent@814:                             blockname = dialog.GetValue()
Laurent@814:                         else:
andrej@1730:                             event.SetDragText("")
Laurent@814:                             return
Laurent@814:                         dialog.Destroy()
Laurent@814:                     if blockname.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
andrej@1734:                         message = _("\"%s\" pou already exists!") % blockname
Laurent@814:                     elif blockname.upper() in [name.upper() for name in self.Controler.GetEditedElementVariables(self.TagName, self.Debug)]:
andrej@1734:                         message = _("\"%s\" element for this pou already exists!") % blockname
Laurent@814:                     else:
Laurent@814:                         self.Controler.AddEditedElementPouVar(self.TagName, values[0], blockname)
Laurent@814:                         self.RefreshVariablePanel()
Laurent@814:                         self.RefreshVariableTree()
Laurent@814:                 blockinfo = self.Controler.GetBlockType(blocktype, blockinputs, self.Debug)
Laurent@814:                 hint = ',\n    '.join(
andrej@1878:                     [" " + fctdecl[0]+" := (*"+fctdecl[1]+"*)" for fctdecl in blockinfo["inputs"]] +
andrej@1878:                     [" " + fctdecl[0]+" => (*"+fctdecl[1]+"*)" for fctdecl in blockinfo["outputs"]])
Laurent@814:                 if values[1] == "function":
Laurent@814:                     event.SetDragText(blocktype+"(\n    "+hint+")")
Laurent@814:                 else:
Laurent@814:                     event.SetDragText(blockname+"(\n    "+hint+")")
Laurent@814:             elif values[1] == "location":
andrej@1847:                 _pou_name, pou_type = self.Controler.GetEditedElementType(self.TagName, self.Debug)
Laurent@814:                 if len(values) > 2 and pou_type == "program":
Laurent@814:                     var_name = values[3]
Edouard@1417:                     dlg = wx.TextEntryDialog(
Edouard@1417:                         self.ParentWindow,
Edouard@1417:                         _("Confirm or change variable name"),
andrej@1578:                         _('Variable Drop'), var_name)
Edouard@1417:                     dlg.SetValue(var_name)
Edouard@1417:                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
Edouard@1417:                     dlg.Destroy()
Edouard@1417:                     if var_name is None:
Edouard@1417:                         return
Edouard@1417:                     elif var_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
andrej@1734:                         message = _("\"%s\" pou already exists!") % var_name
Laurent@814:                     elif var_name.upper() in [name.upper() for name in self.Controler.GetEditedElementVariables(self.TagName, self.Debug)]:
andrej@1734:                         message = _("\"%s\" element for this pou already exists!") % var_name
Laurent@814:                     else:
Laurent@814:                         location = values[0]
Laurent@814:                         if not location.startswith("%"):
andrej@1768:                             dialog = wx.SingleChoiceDialog(
andrej@1768:                                 self.ParentWindow,
andrej@1768:                                 _("Select a variable class:"),
andrej@1768:                                 _("Variable class"),
andrej@1768:                                 [_("Input"), _("Output"), _("Memory")],
andrej@1768:                                 wx.DEFAULT_DIALOG_STYLE | wx.OK | wx.CANCEL)
Laurent@814:                             if dialog.ShowModal() == wx.ID_OK:
Laurent@814:                                 selected = dialog.GetSelection()
Laurent@814:                             else:
Laurent@814:                                 selected = None
Laurent@814:                             dialog.Destroy()
Laurent@814:                             if selected is None:
Laurent@814:                                 event.SetDragText("")
Laurent@814:                                 return
Laurent@814:                             if selected == 0:
Laurent@814:                                 location = "%I" + location
Laurent@814:                             elif selected == 1:
Laurent@814:                                 location = "%Q" + location
Laurent@814:                             else:
Laurent@814:                                 location = "%M" + location
Laurent@814:                         if values[2] is not None:
Laurent@814:                             var_type = values[2]
Laurent@814:                         else:
Laurent@814:                             var_type = LOCATIONDATATYPES.get(location[2], ["BOOL"])[0]
andrej@1768:                         self.Controler.AddEditedElementPouVar(
andrej@1768:                             self.TagName,
Edouard@1409:                             var_type, var_name,
Edouard@1406:                             location=location, description=values[4])
Laurent@814:                         self.RefreshVariablePanel()
Laurent@814:                         self.RefreshVariableTree()
Laurent@814:                         event.SetDragText(var_name)
Laurent@814:                 else:
Laurent@814:                     event.SetDragText("")
Edouard@1409:             elif values[1] == "NamedConstant":
andrej@1847:                 _pou_name, pou_type = self.Controler.GetEditedElementType(self.TagName, self.Debug)
Edouard@1409:                 if pou_type == "program":
Edouard@1409:                     initval = values[0]
Edouard@1409:                     var_name = values[3]
Edouard@1417:                     dlg = wx.TextEntryDialog(
Edouard@1417:                         self.ParentWindow,
Edouard@1417:                         _("Confirm or change variable name"),
andrej@1578:                         _('Variable Drop'), var_name)
Edouard@1417:                     dlg.SetValue(var_name)
Edouard@1417:                     var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
Edouard@1417:                     dlg.Destroy()
Edouard@1417:                     if var_name is None:
Edouard@1417:                         return
Edouard@1417:                     elif var_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
andrej@1734:                         message = _("\"%s\" pou already exists!") % var_name
Edouard@1409:                     else:
Edouard@1409:                         var_type = values[2]
Edouard@1409:                         if not var_name.upper() in [name.upper() for name in self.Controler.GetEditedElementVariables(self.TagName, self.Debug)]:
Edouard@1409:                             self.Controler.AddEditedElementPouVar(self.TagName,
Edouard@1409:                                                                   var_type,
Edouard@1409:                                                                   var_name,
Edouard@1409:                                                                   description=values[4], initval=initval)
Edouard@1409:                             self.RefreshVariablePanel()
Edouard@1409:                             self.RefreshVariableTree()
Edouard@1409:                         event.SetDragText(var_name)
Laurent@814:             elif values[1] == "Global":
Laurent@814:                 var_name = values[0]
Edouard@1417:                 dlg = wx.TextEntryDialog(
Edouard@1417:                     self.ParentWindow,
Edouard@1417:                     _("Confirm or change variable name"),
andrej@1578:                     _('Variable Drop'), var_name)
Edouard@1417:                 dlg.SetValue(var_name)
Edouard@1417:                 var_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None
Edouard@1417:                 dlg.Destroy()
Edouard@1417:                 if var_name is None:
Edouard@1417:                     return
Edouard@1417:                 elif var_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames(self.Debug)]:
andrej@1734:                     message = _("\"%s\" pou already exists!") % var_name
Laurent@814:                 else:
Laurent@814:                     if not var_name.upper() in [name.upper() for name in self.Controler.GetEditedElementVariables(self.TagName, self.Debug)]:
Laurent@814:                         self.Controler.AddEditedElementPouExternalVar(self.TagName, values[2], var_name)
Laurent@814:                         self.RefreshVariablePanel()
Laurent@814:                         self.RefreshVariableTree()
Laurent@814:                     event.SetDragText(var_name)
Laurent@814:             elif values[1] == "Constant":
Laurent@814:                 event.SetDragText(values[0])
Laurent@814:             elif values[3] == self.TagName:
Laurent@814:                 self.ResetBuffer()
Laurent@814:                 event.SetDragText(values[0])
Laurent@814:                 wx.CallAfter(self.RefreshModel)
Laurent@814:             else:
Laurent@814:                 message = _("Variable don't belong to this POU!")
Laurent@814:             if message is not None:
andrej@1745:                 dialog = wx.MessageDialog(self, message, _("Error"), wx.OK | wx.ICON_ERROR)
Laurent@814:                 dialog.ShowModal()
Laurent@814:                 dialog.Destroy()
Laurent@814:                 event.SetDragText("")
Laurent@814:         event.Skip()
Edouard@1409: 
Laurent@814:     def SetTextSyntax(self, syntax):
Laurent@814:         self.TextSyntax = syntax
Laurent@814:         if syntax in ["ST", "ALL"]:
Laurent@814:             self.Editor.SetMarginType(2, wx.stc.STC_MARGIN_SYMBOL)
Laurent@814:             self.Editor.SetMarginMask(2, wx.stc.STC_MASK_FOLDERS)
Laurent@814:             self.Editor.SetMarginSensitive(2, 1)
Laurent@814:             self.Editor.SetMarginWidth(2, 12)
Laurent@814:             if syntax == "ST":
Laurent@814:                 self.BlockStartKeywords = ST_BLOCK_START_KEYWORDS
Laurent@814:                 self.BlockEndKeywords = ST_BLOCK_START_KEYWORDS
Laurent@814:             else:
Laurent@814:                 self.BlockStartKeywords = IEC_BLOCK_START_KEYWORDS
Laurent@814:                 self.BlockEndKeywords = IEC_BLOCK_START_KEYWORDS
Laurent@814:         else:
Laurent@814:             self.BlockStartKeywords = []
Laurent@814:             self.BlockEndKeywords = []
Edouard@1409: 
Laurent@814:     def SetKeywords(self, keywords):
Laurent@814:         self.Keywords = [keyword.upper() for keyword in keywords]
Laurent@814:         self.Colourise(0, -1)
Edouard@1409: 
Laurent@814:     def RefreshJumpList(self):
surkovsv93@1637:         if self.TextSyntax == "IL":
Laurent@814:             self.Jumps = [jump.upper() for jump in LABEL_MODEL.findall(self.GetText())]
Edouard@1409: 
Laurent@814:     # Buffer the last model state
Laurent@814:     def RefreshBuffer(self):
Laurent@814:         self.Controler.BufferProject()
Laurent@814:         if self.ParentWindow:
Laurent@814:             self.ParentWindow.RefreshTitle()
Laurent@814:             self.ParentWindow.RefreshFileMenu()
Laurent@814:             self.ParentWindow.RefreshEditMenu()
Edouard@1409: 
Laurent@814:     def StartBuffering(self):
Laurent@814:         self.Controler.StartBuffering()
Laurent@814:         if self.ParentWindow:
Laurent@814:             self.ParentWindow.RefreshTitle()
Laurent@814:             self.ParentWindow.RefreshFileMenu()
Laurent@814:             self.ParentWindow.RefreshEditMenu()
Edouard@1409: 
Laurent@814:     def ResetBuffer(self):
andrej@1743:         if self.CurrentAction is not None:
Laurent@814:             self.Controler.EndBuffering()
Laurent@814:             self.CurrentAction = None
Edouard@1409: 
Laurent@814:     def GetBufferState(self):
Laurent@814:         if not self.Debug and self.TextSyntax != "ALL":
Laurent@814:             return self.Controler.GetBufferState()
Laurent@814:         return False, False
Edouard@1409: 
Laurent@814:     def Undo(self):
Laurent@814:         if not self.Debug and self.TextSyntax != "ALL":
Laurent@814:             self.Controler.LoadPrevious()
Laurent@814:             self.ParentWindow.CloseTabsWithoutModel()
Edouard@1409: 
Laurent@814:     def Redo(self):
Laurent@814:         if not self.Debug and self.TextSyntax != "ALL":
Laurent@814:             self.Controler.LoadNext()
Laurent@814:             self.ParentWindow.CloseTabsWithoutModel()
Edouard@1409: 
Laurent@814:     def HasNoModel(self):
Laurent@814:         if not self.Debug and self.TextSyntax != "ALL":
Laurent@814:             return self.Controler.GetEditedElement(self.TagName) is None
Laurent@814:         return False
Edouard@1409: 
Laurent@814:     def RefreshView(self, variablepanel=True):
Laurent@814:         EditorPanel.RefreshView(self, variablepanel)
Edouard@1409: 
Laurent@814:         if self.Controler is not None:
Laurent@814:             self.ResetBuffer()
Laurent@814:             self.DisableEvents = True
Laurent@814:             old_cursor_pos = self.GetCurrentPos()
Laurent@1060:             line = self.Editor.GetFirstVisibleLine()
Laurent@1060:             column = self.Editor.GetXOffset()
Laurent@814:             old_text = self.GetText()
Laurent@814:             new_text = self.Controler.GetEditedElementText(self.TagName, self.Debug)
Laurent@1060:             if old_text != new_text:
Laurent@1060:                 self.SetText(new_text)
Laurent@1060:                 new_cursor_pos = GetCursorPos(old_text, new_text)
Laurent@1060:                 self.Editor.LineScroll(column, line)
andrej@1743:                 if new_cursor_pos is not None:
Laurent@1060:                     self.Editor.GotoPos(new_cursor_pos)
Laurent@1060:                 else:
Laurent@1060:                     self.Editor.GotoPos(old_cursor_pos)
Laurent@1060:                 self.RefreshJumpList()
Laurent@1060:                 self.Editor.EmptyUndoBuffer()
Laurent@814:             self.DisableEvents = False
Edouard@1409: 
Laurent@814:             self.RefreshVariableTree()
Edouard@1409: 
Laurent@814:             self.TypeNames = [typename.upper() for typename in self.Controler.GetDataTypes(self.TagName, True, self.Debug)]
Laurent@814:             self.EnumeratedValues = [value.upper() for value in self.Controler.GetEnumeratedDataValues()]
Edouard@1409: 
Laurent@814:             self.Functions = {}
Laurent@814:             for category in self.Controler.GetBlockTypes(self.TagName, self.Debug):
Laurent@814:                 for blocktype in category["list"]:
Laurent@814:                     blockname = blocktype["name"].upper()
Laurent@814:                     if blocktype["type"] == "function" and blockname not in self.Keywords and blockname not in self.Variables.keys():
andrej@1847:                         interface = dict([(name, {}) for name, _type, _modifier in blocktype["inputs"] + blocktype["outputs"] if name != ''])
Laurent@814:                         for param in ["EN", "ENO"]:
andrej@1775:                             if param not in interface:
Laurent@814:                                 interface[param] = {}
andrej@1763:                         if blockname in self.Functions:
Laurent@814:                             self.Functions[blockname]["interface"].update(interface)
Laurent@814:                             self.Functions[blockname]["extensible"] |= blocktype["extensible"]
Laurent@814:                         else:
Laurent@814:                             self.Functions[blockname] = {"interface": interface,
Laurent@814:                                                          "extensible": blocktype["extensible"]}
Edouard@1409: 
Laurent@814:         self.Colourise(0, -1)
Edouard@1409: 
Laurent@814:     def RefreshVariableTree(self):
Laurent@814:         words = self.TagName.split("::")
andrej@1878:         self.Variables = self.GenerateVariableTree([
andrej@1878:             (variable.Name, variable.Type, variable.Tree)
andrej@1878:             for variable in
andrej@1878:             self.Controler.GetEditedElementInterfaceVars(
andrej@1878:                 self.TagName, True, self.Debug)
andrej@1878:         ])
Laurent@814:         if self.Controler.GetEditedElementType(self.TagName, self.Debug)[1] == "function" or words[0] == "T" and self.TextSyntax == "IL":
andrej@1847:             return_type, (var_tree, _var_dimension) = self.Controler.GetEditedElementInterfaceReturnType(self.TagName, True, self.Debug)
Laurent@814:             if return_type is not None:
Laurent@814:                 self.Variables[words[-1].upper()] = self.GenerateVariableTree(var_tree)
Laurent@814:             else:
Laurent@814:                 self.Variables[words[-1].upper()] = {}
Edouard@1409: 
Laurent@814:     def GenerateVariableTree(self, list):
Laurent@814:         tree = {}
andrej@1847:         for var_name, _var_type, (var_tree, _var_dimension) in list:
Laurent@814:             tree[var_name.upper()] = self.GenerateVariableTree(var_tree)
Laurent@814:         return tree
Edouard@1409: 
Laurent@814:     def IsValidVariable(self, name, context):
Laurent@814:         return context is not None and context.get(name, None) is not None
Laurent@814: 
Laurent@814:     def IsCallParameter(self, name, call):
Laurent@814:         if call is not None:
Edouard@1409:             return (call["interface"].get(name.upper(), None) is not None or
Laurent@814:                     call["extensible"] and EXTENSIBLE_PARAMETER.match(name.upper()) is not None)
Laurent@814:         return False
Edouard@1409: 
Laurent@814:     def RefreshLineFolding(self, line_number):
Laurent@814:         if self.TextSyntax in ["ST", "ALL"]:
Laurent@814:             level = wx.stc.STC_FOLDLEVELBASE + self.Editor.GetLineIndentation(line_number)
Laurent@814:             line = self.Editor.GetLine(line_number).strip()
Laurent@814:             if line == "":
Laurent@814:                 if line_number > 0:
Laurent@814:                     if LineStartswith(self.Editor.GetLine(line_number - 1).strip(), self.BlockEndKeywords):
Laurent@814:                         level = self.Editor.GetFoldLevel(self.Editor.GetFoldParent(line_number - 1)) & wx.stc.STC_FOLDLEVELNUMBERMASK
Laurent@814:                     else:
Laurent@814:                         level = self.Editor.GetFoldLevel(line_number - 1) & wx.stc.STC_FOLDLEVELNUMBERMASK
Laurent@814:                 if level != wx.stc.STC_FOLDLEVELBASE:
andrej@1758:                     level |= wx.stc.STC_FOLDLEVELWHITEFLAG
Laurent@814:             elif LineStartswith(line, self.BlockStartKeywords):
Laurent@814:                 level |= wx.stc.STC_FOLDLEVELHEADERFLAG
Laurent@814:             elif LineStartswith(line, self.BlockEndKeywords):
Laurent@814:                 if LineStartswith(self.Editor.GetLine(line_number - 1).strip(), self.BlockEndKeywords):
Laurent@814:                     level = self.Editor.GetFoldLevel(self.Editor.GetFoldParent(line_number - 1)) & wx.stc.STC_FOLDLEVELNUMBERMASK
Laurent@814:                 else:
Laurent@814:                     level = self.Editor.GetFoldLevel(line_number - 1) & wx.stc.STC_FOLDLEVELNUMBERMASK
Laurent@814:             self.Editor.SetFoldLevel(line_number, level)
Edouard@1409: 
Laurent@814:     def OnStyleNeeded(self, event):
Laurent@814:         self.TextChanged = True
Laurent@814:         line_number = self.Editor.LineFromPosition(self.Editor.GetEndStyled())
Laurent@814:         if line_number == 0:
Laurent@814:             start_pos = last_styled_pos = 0
Laurent@814:         else:
Laurent@814:             start_pos = last_styled_pos = self.Editor.GetLineEndPosition(line_number - 1) + 1
Laurent@814:         self.RefreshLineFolding(line_number)
Laurent@814:         end_pos = event.GetPosition()
Laurent@814:         self.StartStyling(start_pos, 0xff)
Edouard@1409: 
Laurent@814:         current_context = self.Variables
Laurent@814:         current_call = None
Edouard@1409: 
Laurent@814:         current_pos = last_styled_pos
Laurent@814:         state = SPACE
Laurent@814:         line = ""
Laurent@814:         word = ""
Laurent@814:         while current_pos < end_pos:
Laurent@814:             char = chr(self.Editor.GetCharAt(current_pos)).upper()
Laurent@814:             line += char
Laurent@814:             if char == NEWLINE:
Laurent@814:                 self.ContextStack = []
Laurent@814:                 current_context = self.Variables
Laurent@814:                 if state == COMMENT:
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_COMMENT)
Laurent@814:                 elif state == NUMBER:
Laurent@814:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:                 elif state == WORD:
Laurent@814:                     if word in self.Keywords or word in self.TypeNames:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_WORD)
Laurent@814:                     elif self.IsValidVariable(word, current_context):
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_VARIABLE)
Laurent@814:                     elif self.IsCallParameter(word, current_call):
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_PARAMETER)
Laurent@814:                     elif word in self.Functions:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_FUNCTION)
Laurent@814:                     elif self.TextSyntax == "IL" and word in self.Jumps:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_JUMP)
Laurent@814:                     elif word in self.EnumeratedValues:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:                     else:
andrej@1509:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                         if word not in ["]", ")"] and (self.GetCurrentPos() < last_styled_pos or self.GetCurrentPos() > current_pos):
Laurent@814:                             self.StartStyling(last_styled_pos, wx.stc.STC_INDICS_MASK)
Laurent@814:                             self.SetStyling(current_pos - last_styled_pos, wx.stc.STC_INDIC0_MASK)
Laurent@814:                             self.StartStyling(current_pos, 0xff)
Laurent@814:                 else:
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                 last_styled_pos = current_pos
andrej@1509:                 if (state != DPRAGMA) and (state != COMMENT):
Laurent@1108:                     state = SPACE
Laurent@814:                 line = ""
Laurent@814:                 line_number += 1
Laurent@814:                 self.RefreshLineFolding(line_number)
Laurent@814:             elif line.endswith("(*") and state != COMMENT:
andrej@1509:                 self.SetStyling(current_pos - last_styled_pos - 1, STC_PLC_EMPTY)
Laurent@814:                 last_styled_pos = current_pos
Laurent@814:                 if state == WORD:
Laurent@814:                     current_context = self.Variables
Laurent@814:                 state = COMMENT
Laurent@871:             elif line.endswith("{") and state not in [PRAGMA, DPRAGMA]:
andrej@1509:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                 last_styled_pos = current_pos
Laurent@814:                 if state == WORD:
Laurent@814:                     current_context = self.Variables
Laurent@814:                 state = PRAGMA
Laurent@871:             elif line.endswith("{{") and state == PRAGMA:
andrej@1509:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@871:                 last_styled_pos = current_pos
Laurent@871:                 state = DPRAGMA
Laurent@814:             elif state == COMMENT:
Laurent@814:                 if line.endswith("*)"):
Laurent@814:                     self.SetStyling(current_pos - last_styled_pos + 2, STC_PLC_COMMENT)
Laurent@814:                     last_styled_pos = current_pos + 1
Laurent@814:                     state = SPACE
andrej@1521:                     if len(self.CallStack) > 0:
andrej@1521:                         current_call = self.CallStack.pop()
andrej@1521:                     else:
andrej@1730:                         current_call = None
Laurent@814:             elif state == PRAGMA:
Laurent@814:                 if line.endswith("}"):
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@871:                     last_styled_pos = current_pos
Laurent@871:                     state = SPACE
Laurent@871:             elif state == DPRAGMA:
Laurent@871:                 if line.endswith("}}"):
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos + 1, STC_PLC_EMPTY)
Laurent@814:                     last_styled_pos = current_pos + 1
Laurent@814:                     state = SPACE
Laurent@814:             elif (line.endswith("'") or line.endswith('"')) and state not in [STRING, WSTRING]:
andrej@1509:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                 last_styled_pos = current_pos
Laurent@814:                 if state == WORD:
Laurent@814:                     current_context = self.Variables
Laurent@814:                 if line.endswith("'"):
Laurent@814:                     state = STRING
Laurent@814:                 else:
Laurent@814:                     state = WSTRING
Laurent@814:             elif state == STRING:
Laurent@814:                 if line.endswith("'") and not line.endswith("$'"):
Laurent@814:                     self.SetStyling(current_pos - last_styled_pos + 1, STC_PLC_STRING)
Laurent@814:                     last_styled_pos = current_pos + 1
Laurent@814:                     state = SPACE
Laurent@814:             elif state == WSTRING:
Laurent@814:                 if line.endswith('"') and not line.endswith('$"'):
Laurent@814:                     self.SetStyling(current_pos - last_styled_pos + 1, STC_PLC_STRING)
Laurent@814:                     last_styled_pos = current_pos + 1
Laurent@814:                     state = SPACE
Laurent@814:             elif char in LETTERS:
Laurent@814:                 if state == NUMBER:
Laurent@814:                     word = "#"
Laurent@814:                     state = WORD
Laurent@814:                 elif state == SPACE:
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                     word = char
Laurent@814:                     last_styled_pos = current_pos
Laurent@814:                     state = WORD
Laurent@814:                 else:
Laurent@814:                     word += char
Laurent@814:             elif char in NUMBERS or char == '.' and state != WORD:
Laurent@814:                 if state == SPACE:
andrej@1509:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                     last_styled_pos = current_pos
Laurent@814:                     state = NUMBER
Laurent@814:                 elif state == WORD and char != '.':
Laurent@814:                     word += char
Laurent@814:             elif char == '(' and state == SPACE:
Laurent@814:                 self.CallStack.append(current_call)
Laurent@814:                 current_call = None
Laurent@814:             else:
Laurent@814:                 if state == WORD:
Laurent@814:                     if word in self.Keywords or word in self.TypeNames:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_WORD)
Laurent@814:                     elif self.IsValidVariable(word, current_context):
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_VARIABLE)
Laurent@814:                     elif self.IsCallParameter(word, current_call):
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_PARAMETER)
Laurent@814:                     elif word in self.Functions:
Edouard@1409:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_FUNCTION)
Laurent@814:                     elif self.TextSyntax == "IL" and word in self.Jumps:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_JUMP)
Laurent@814:                     elif word in self.EnumeratedValues:
Laurent@814:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:                     else:
andrej@1509:                         self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:                         if word not in ["]", ")"] and (self.GetCurrentPos() < last_styled_pos or self.GetCurrentPos() > current_pos):
Laurent@814:                             self.StartStyling(last_styled_pos, wx.stc.STC_INDICS_MASK)
Laurent@814:                             self.SetStyling(current_pos - last_styled_pos, wx.stc.STC_INDIC0_MASK)
Laurent@814:                             self.StartStyling(current_pos, 0xff)
Laurent@814:                     if char == '.':
Laurent@814:                         if word != "]":
Laurent@814:                             if current_context is not None:
Laurent@814:                                 current_context = current_context.get(word, None)
Laurent@814:                             else:
Laurent@814:                                 current_context = None
Laurent@814:                     elif char == '(':
Laurent@814:                         self.CallStack.append(current_call)
Laurent@814:                         current_call = self.Functions.get(word, None)
Laurent@814:                         if current_call is None and self.IsValidVariable(word, current_context):
Laurent@814:                             current_call = {"interface": current_context.get(word, {}),
Laurent@814:                                             "extensible": False}
Laurent@814:                         current_context = self.Variables
Laurent@814:                     else:
Laurent@894:                         if char == '[' and current_context is not None:
Laurent@814:                             self.ContextStack.append(current_context.get(word, None))
Laurent@814:                         current_context = self.Variables
Edouard@1409: 
Laurent@814:                     word = ""
Laurent@814:                     last_styled_pos = current_pos
Laurent@814:                     state = SPACE
Laurent@814:                 elif state == NUMBER:
Laurent@814:                     self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:                     last_styled_pos = current_pos
Laurent@814:                     state = SPACE
Laurent@814:                 if char == ']':
Laurent@814:                     if len(self.ContextStack) > 0:
Laurent@814:                         current_context = self.ContextStack.pop()
Laurent@814:                     else:
Laurent@814:                         current_context = self.Variables
Laurent@814:                     word = char
Laurent@814:                     state = WORD
Laurent@814:                 elif char == ')':
Laurent@814:                     current_context = self.Variables
Laurent@814:                     if len(self.CallStack) > 0:
Laurent@814:                         current_call = self.CallStack.pop()
Laurent@814:                     else:
Laurent@814:                         current_call = None
Laurent@814:                     word = char
Laurent@814:                     state = WORD
Laurent@814:             current_pos += 1
Laurent@814:         if state == COMMENT:
Laurent@814:             self.SetStyling(current_pos - last_styled_pos + 2, STC_PLC_COMMENT)
Laurent@814:         elif state == NUMBER:
Laurent@814:             self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:         elif state == WORD:
Laurent@814:             if word in self.Keywords or word in self.TypeNames:
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_WORD)
Laurent@814:             elif self.IsValidVariable(word, current_context):
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_VARIABLE)
Laurent@814:             elif self.IsCallParameter(word, current_call):
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_PARAMETER)
Laurent@814:             elif self.TextSyntax == "IL" and word in self.Functions:
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_FUNCTION)
Laurent@814:             elif word in self.Jumps:
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_JUMP)
Laurent@814:             elif word in self.EnumeratedValues:
Laurent@814:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_NUMBER)
Laurent@814:             else:
andrej@1509:                 self.SetStyling(current_pos - last_styled_pos, STC_PLC_EMPTY)
Laurent@814:         else:
andrej@1509:             self.SetStyling(current_pos - start_pos, STC_PLC_EMPTY)
Laurent@814:         self.ShowHighlights(start_pos, end_pos)
Laurent@814:         event.Skip()
Edouard@1409: 
Laurent@814:     def OnMarginClick(self, event):
Laurent@814:         if event.GetMargin() == 2:
Laurent@814:             line = self.Editor.LineFromPosition(event.GetPosition())
Laurent@814:             if self.Editor.GetFoldLevel(line) & wx.stc.STC_FOLDLEVELHEADERFLAG:
Laurent@814:                 self.Editor.ToggleFold(line)
Laurent@814:         event.Skip()
Edouard@1409: 
Laurent@1126:     def OnUpdateUI(self, event):
Laurent@1262:         selected = self.Editor.GetSelectedText()
Laurent@1262:         if self.ParentWindow and selected != "":
Laurent@1262:             self.ParentWindow.SetCopyBuffer(selected, True)
Laurent@1126:         event.Skip()
Edouard@1409: 
Laurent@814:     def Cut(self):
Laurent@814:         self.ResetBuffer()
Laurent@814:         self.DisableEvents = True
Laurent@814:         self.Editor.CmdKeyExecute(wx.stc.STC_CMD_CUT)
Laurent@814:         self.DisableEvents = False
Laurent@814:         self.RefreshModel()
Laurent@814:         self.RefreshBuffer()
Edouard@1409: 
Laurent@814:     def Copy(self):
Laurent@814:         self.Editor.CmdKeyExecute(wx.stc.STC_CMD_COPY)
Laurent@1126:         if self.ParentWindow:
Laurent@1126:             self.ParentWindow.RefreshEditMenu()
Edouard@1409: 
Laurent@814:     def Paste(self):
Laurent@814:         self.ResetBuffer()
Laurent@814:         self.DisableEvents = True
Laurent@814:         self.Editor.CmdKeyExecute(wx.stc.STC_CMD_PASTE)
Laurent@814:         self.DisableEvents = False
Laurent@814:         self.RefreshModel()
Laurent@814:         self.RefreshBuffer()
Edouard@1409: 
Laurent@1057:     def Search(self, criteria):
Laurent@1057:         return self.Controler.SearchInPou(self.TagName, criteria, self.Debug)
Edouard@1409: 
Laurent@814:     def Find(self, direction, search_params):
Laurent@814:         if self.SearchParams != search_params:
Laurent@814:             self.ClearHighlights(SEARCH_RESULT_HIGHLIGHT)
Edouard@1409: 
Laurent@814:             self.SearchParams = search_params
Laurent@814:             self.SearchResults = [
Laurent@814:                 (infos[1:], start, end, SEARCH_RESULT_HIGHLIGHT)
andrej@1847:                 for infos, start, end, _text in
surkovsv93@1556:                 self.Search(search_params)]
Laurent@1057:             self.CurrentFindHighlight = None
Edouard@1409: 
Laurent@814:         if len(self.SearchResults) > 0:
Laurent@814:             if self.CurrentFindHighlight is not None:
Laurent@814:                 old_idx = self.SearchResults.index(self.CurrentFindHighlight)
Laurent@814:                 if self.SearchParams["wrap"]:
Laurent@814:                     idx = (old_idx + direction) % len(self.SearchResults)
Laurent@814:                 else:
Laurent@814:                     idx = max(0, min(old_idx + direction, len(self.SearchResults) - 1))
Laurent@814:                 if idx != old_idx:
Laurent@814:                     self.RemoveHighlight(*self.CurrentFindHighlight)
Laurent@814:                     self.CurrentFindHighlight = self.SearchResults[idx]
Laurent@814:                     self.AddHighlight(*self.CurrentFindHighlight)
Laurent@814:             else:
Laurent@814:                 self.CurrentFindHighlight = self.SearchResults[0]
Laurent@814:                 self.AddHighlight(*self.CurrentFindHighlight)
Edouard@1409: 
Laurent@814:         else:
Laurent@814:             if self.CurrentFindHighlight is not None:
Laurent@814:                 self.RemoveHighlight(*self.CurrentFindHighlight)
Laurent@814:             self.CurrentFindHighlight = None
Edouard@1409: 
Laurent@814:     def RefreshModel(self):
Laurent@814:         self.RefreshJumpList()
edouard@1904:         self.Colourise(0, -1)
Laurent@814:         self.Controler.SetEditedElementText(self.TagName, self.GetText())
Laurent@1178:         self.ResetSearchResults()
Edouard@1409: 
Laurent@814:     def OnKeyDown(self, event):
Laurent@1262:         key = event.GetKeyCode()
Laurent@814:         if self.Controler is not None:
Edouard@1409: 
Laurent@814:             if self.Editor.CallTipActive():
Laurent@814:                 self.Editor.CallTipCancel()
Edouard@1409: 
Laurent@814:             key_handled = False
Laurent@814: 
Laurent@814:             line = self.Editor.GetCurrentLine()
Laurent@814:             if line == 0:
Laurent@814:                 start_pos = 0
Laurent@814:             else:
Laurent@814:                 start_pos = self.Editor.GetLineEndPosition(line - 1) + 1
Laurent@814:             end_pos = self.GetCurrentPos()
Laurent@814:             lineText = self.Editor.GetTextRange(start_pos, end_pos).replace("\t", " ")
Edouard@1409: 
Laurent@814:             # Code completion
Laurent@814:             if key == wx.WXK_SPACE and event.ControlDown():
Edouard@1409: 
Laurent@814:                 words = lineText.split(" ")
Laurent@814:                 words = [word for i, word in enumerate(words) if word != '' or i == len(words) - 1]
Edouard@1409: 
Laurent@814:                 kw = []
Edouard@1409: 
Laurent@814:                 if self.TextSyntax == "IL":
Laurent@814:                     if len(words) == 1:
Laurent@814:                         kw = self.Keywords
Laurent@814:                     elif len(words) == 2:
Laurent@814:                         if words[0].upper() in ["CAL", "CALC", "CALNC"]:
Laurent@814:                             kw = self.Functions
Laurent@814:                         elif words[0].upper() in ["JMP", "JMPC", "JMPNC"]:
Laurent@814:                             kw = self.Jumps
Laurent@814:                         else:
Laurent@814:                             kw = self.Variables.keys()
Laurent@814:                 else:
Laurent@871:                     kw = self.Keywords + self.Variables.keys() + self.Functions.keys()
Laurent@814:                 if len(kw) > 0:
Laurent@814:                     if len(words[-1]) > 0:
Laurent@814:                         kw = [keyword for keyword in kw if keyword.startswith(words[-1])]
Laurent@814:                     kw.sort()
Laurent@814:                     self.Editor.AutoCompSetIgnoreCase(True)
Laurent@814:                     self.Editor.AutoCompShow(len(words[-1]), " ".join(kw))
Laurent@814:                 key_handled = True
Laurent@814:             elif key == wx.WXK_RETURN or key == wx.WXK_NUMPAD_ENTER:
Laurent@814:                 if self.TextSyntax in ["ST", "ALL"]:
Laurent@814:                     indent = self.Editor.GetLineIndentation(line)
Laurent@814:                     if LineStartswith(lineText.strip(), self.BlockStartKeywords):
andrej@2437:                         indent = (indent // 2 + 1) * 2
Laurent@814:                     self.Editor.AddText("\n" + " " * indent)
Laurent@814:                     key_handled = True
Laurent@814:             elif key == wx.WXK_BACK:
Laurent@814:                 if self.TextSyntax in ["ST", "ALL"]:
andrej@1613:                     if not self.Editor.GetSelectedText():
andrej@1613:                         indent = self.Editor.GetColumn(self.Editor.GetCurrentPos())
andrej@1613:                         if lineText.strip() == "" and len(lineText) > 0 and indent > 0:
andrej@1613:                             self.Editor.DelLineLeft()
andrej@2437:                             self.Editor.AddText(" " * ((max(0, indent - 1) // 2) * 2))
andrej@1613:                             key_handled = True
Laurent@814:             if not key_handled:
Laurent@814:                 event.Skip()
andrej@1548:         else:
Laurent@1262:             event.Skip()
Laurent@814: 
Laurent@814:     def OnKillFocus(self, event):
Laurent@814:         self.Editor.AutoCompCancel()
Laurent@814:         event.Skip()
Laurent@814: 
andrej@1782:     # -------------------------------------------------------------------------------
andrej@1782:     #                        Highlights showing functions
andrej@1782:     # -------------------------------------------------------------------------------
Laurent@814: 
Laurent@814:     def OnRefreshHighlightsTimer(self, event):
Laurent@814:         self.RefreshView()
Laurent@814:         event.Skip()
Laurent@814: 
Laurent@814:     def ClearHighlights(self, highlight_type=None):
Laurent@814:         EditorPanel.ClearHighlights(self, highlight_type)
Edouard@1409: 
Laurent@814:         if highlight_type is None:
Laurent@814:             self.Highlights = []
Laurent@814:         else:
Laurent@814:             highlight_type = HIGHLIGHT_TYPES.get(highlight_type, None)
Laurent@814:             if highlight_type is not None:
Laurent@814:                 self.Highlights = [(infos, start, end, highlight) for (infos, start, end, highlight) in self.Highlights if highlight != highlight_type]
Laurent@814:         self.RefreshView()
Laurent@814: 
Laurent@814:     def AddHighlight(self, infos, start, end, highlight_type):
Laurent@814:         EditorPanel.AddHighlight(self, infos, start, end, highlight_type)
Edouard@1409: 
Laurent@814:         highlight_type = HIGHLIGHT_TYPES.get(highlight_type, None)
Laurent@814:         if infos[0] == "body" and highlight_type is not None:
Laurent@814:             self.Highlights.append((infos[1], start, end, highlight_type))
Laurent@814:             self.Editor.GotoPos(self.Editor.PositionFromLine(start[0]) + start[1])
Laurent@814:             self.RefreshHighlightsTimer.Start(int(REFRESH_HIGHLIGHT_PERIOD * 1000), oneShot=True)
Laurent@814: 
Laurent@814:     def RemoveHighlight(self, infos, start, end, highlight_type):
Laurent@814:         EditorPanel.RemoveHighlight(self, infos, start, end, highlight_type)
Edouard@1409: 
Laurent@814:         highlight_type = HIGHLIGHT_TYPES.get(highlight_type, None)
andrej@1766:         if infos[0] == "body" and highlight_type is not None and \
andrej@1766:            (infos[1], start, end, highlight_type) in self.Highlights:
Laurent@814:             self.Highlights.remove((infos[1], start, end, highlight_type))
Laurent@814:             self.RefreshHighlightsTimer.Start(int(REFRESH_HIGHLIGHT_PERIOD * 1000), oneShot=True)
Edouard@1409: 
Laurent@814:     def ShowHighlights(self, start_pos, end_pos):
Laurent@814:         for indent, start, end, highlight_type in self.Highlights:
Laurent@814:             if start[0] == 0:
Laurent@814:                 highlight_start_pos = start[1] - indent
Laurent@814:             else:
Laurent@814:                 highlight_start_pos = self.Editor.GetLineEndPosition(start[0] - 1) + start[1] - indent + 1
Laurent@814:             if end[0] == 0:
Laurent@814:                 highlight_end_pos = end[1] - indent + 1
Laurent@814:             else:
Laurent@814:                 highlight_end_pos = self.Editor.GetLineEndPosition(end[0] - 1) + end[1] - indent + 2
Laurent@814:             if highlight_start_pos < end_pos and highlight_end_pos > start_pos:
Laurent@814:                 self.StartStyling(highlight_start_pos, 0xff)
Laurent@814:                 self.SetStyling(highlight_end_pos - highlight_start_pos, highlight_type)
Laurent@814:                 self.StartStyling(highlight_start_pos, 0x00)
andrej@2409:                 until_end = max(0, len(self.Editor.GetText()) - highlight_end_pos)
andrej@2409:                 self.SetStyling(until_end, wx.stc.STC_STYLE_DEFAULT)