--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/plugins/c_ext/CFileEditor.py Fri May 23 10:31:26 2008 +0200
@@ -0,0 +1,1161 @@
+if wx.Platform == '__WXMSW__': + faces = { 'times': 'Times New Roman', + 'mono' : 'Courier New', + 'other': 'Comic Sans MS', + faces = { 'times': 'Times', + 'other': 'new century schoolbook', +if wx.VERSION >= (2, 8, 0): + class MDICppEditor(wx.aui.AuiMDIChildFrame): + def __init__(self, parent, name, window, controler): + wx.aui.AuiMDIChildFrame.__init__(self, parent, -1, title = name) + sizer = wx.BoxSizer(wx.HORIZONTAL) + self.Viewer = CppEditor(self, name, window, controler) + sizer.AddWindow(self.Viewer, 1, border=0, flag=wx.GROW) + class MDIVariablesEditor(wx.aui.AuiMDIChildFrame): + def __init__(self, parent, name, window, controler): + wx.aui.AuiMDIChildFrame.__init__(self, parent, -1, title = name) + sizer = wx.BoxSizer(wx.HORIZONTAL) + self.Viewer = VariablesEditor(self, window, controler) + sizer.AddWindow(self.Viewer, 1, border=0, flag=wx.GROW) +def AppendMenu(parent, help, id, kind, text): + if wx.VERSION >= (2, 6, 0): + parent.Append(help=help, id=id, kind=kind, text=text) + parent.Append(helpString=help, id=id, kind=kind, item=text) +] = [wx.NewId() for _init_ctrls in range(1)] +CPP_KEYWORDS = ["asm", "auto", "bool", "break", "case", "catch", "char", "class", + "const", "const_cast", "continue", "default", "delete", "do", "double", + "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", + "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", + "namespace", "new", "operator", "private", "protected", "public", "register", + "reinterpret_cast", "return", "short", "signed", "sizeof", "static", + "static_cast", "struct", "switch", "template", "this", "throw", "true", "try", + "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", + "void", "volatile", "wchar_t", "while"] +def GetCursorPos(old, new): + common_length = min(old_length, new_length) + for i in xrange(common_length): + if old_length < new_length: + if common_length > 0 and old[i] != new[i]: + return i + new_length - old_length + return i + new_length - old_length + 1 + elif old_length > new_length or i < min(old_length, new_length) - 1: + if common_length > 0 and old[i] != new[i]: +class CppEditor(stc.StyledTextCtrl): + def __init__(self, parent, name, window, controler): + stc.StyledTextCtrl.__init__(self, parent, ID_CPPEDITOR, wx.DefaultPosition, + self.SetMarginType(1, stc.STC_MARGIN_NUMBER) + self.SetMarginWidth(1, 25) + self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) + self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) + self.SetLexer(stc.STC_LEX_CPP) + self.SetKeyWords(0, " ".join(CPP_KEYWORDS)) + self.SetProperty("fold", "1") + self.SetProperty("tab.timmy.whinge.level", "1") + self.SetViewWhiteSpace(False) + #self.SetBufferedDraw(False) + #self.SetEOLMode(stc.STC_EOL_CRLF) + #self.SetUseAntiAliasing(True) + self.SetEdgeMode(stc.STC_EDGE_BACKGROUND) + # Setup a margin to hold fold markers + #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? + self.SetMarginType(2, stc.STC_MARGIN_SYMBOL) + self.SetMarginMask(2, stc.STC_MASK_FOLDERS) + self.SetMarginSensitive(2, True) + self.SetMarginWidth(2, 12) + if self.fold_symbols == 0: + # Arrow pointing right for contracted folders, arrow pointing down for expanded + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_ARROWDOWN, "black", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_ARROW, "black", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "black", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "black", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black") + elif self.fold_symbols == 1: + # Plus for contracted folders, minus for expanded + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_MINUS, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_PLUS, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black") + elif self.fold_symbols == 2: + # Like a flattened tree control using circular headers and curved joins + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_CIRCLEMINUS, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_CIRCLEPLUS, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNERCURVE, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_CIRCLEMINUSCONNECTED, "white", "#404040") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNERCURVE, "white", "#404040") + elif self.fold_symbols == 3: + # Like a flattened tree control using square headers + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080") + self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080") + self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI) + self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick) + self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed) + # Make some styles, The lexer defines what each style is used for, we + # just have to define what each style looks like. This set is adapted from + # Scintilla sample property files. + # Global default styles for all languages + self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces) + self.StyleClearAll() # Reset all to be like the default + # Global default styles for all languages + self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces) + self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces) + self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces) + self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold") + self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold") + self.StyleSetSpec(stc.STC_C_COMMENT, 'fore:#408060') + self.StyleSetSpec(stc.STC_C_COMMENTLINE, 'fore:#408060') + self.StyleSetSpec(stc.STC_C_COMMENTDOC, 'fore:#408060') + self.StyleSetSpec(stc.STC_C_NUMBER, 'fore:#0076AE') + self.StyleSetSpec(stc.STC_C_WORD, 'bold,fore:#800056') + self.StyleSetSpec(stc.STC_C_STRING, 'fore:#2a00ff') + self.StyleSetSpec(stc.STC_C_PREPROCESSOR, 'bold,fore:#800056') + self.StyleSetSpec(stc.STC_C_OPERATOR, 'bold') + self.StyleSetSpec(stc.STC_C_STRINGEOL, 'back:#FFD5FF') + # register some images for use in the AutoComplete box. + #self.RegisterImage(1, images.getSmilesBitmap()) + wx.ArtProvider.GetBitmap(wx.ART_DELETE, size=(16,16))) + wx.ArtProvider.GetBitmap(wx.ART_NEW, size=(16,16))) + wx.ArtProvider.GetBitmap(wx.ART_COPY, size=(16,16))) + self.Controler = controler + self.ParentWindow = window + self.DisableEvents = True + self.CurrentAction = None + self.SetModEventMask(wx.stc.STC_MOD_BEFOREINSERT|wx.stc.STC_MOD_BEFOREDELETE) + self.Bind(wx.stc.EVT_STC_DO_DROP, self.OnDoDrop, id=ID_CPPEDITOR) + self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) + self.Bind(wx.stc.EVT_STC_MODIFIED, self.OnModification, id=ID_CPPEDITOR) + def OnModification(self, event): + if not self.DisableEvents: + mod_type = event.GetModificationType() + if not (mod_type&wx.stc.STC_PERFORMED_UNDO or mod_type&wx.stc.STC_PERFORMED_REDO): + if mod_type&wx.stc.STC_MOD_BEFOREINSERT: + if self.CurrentAction == None: + elif self.CurrentAction[0] != "Add" or self.CurrentAction[1] != event.GetPosition() - 1: + self.Controler.EndBuffering() + self.CurrentAction = ("Add", event.GetPosition()) + elif mod_type&wx.stc.STC_MOD_BEFOREDELETE: + if self.CurrentAction == None: + elif self.CurrentAction[0] != "Delete" or self.CurrentAction[1] != event.GetPosition() + 1: + self.Controler.EndBuffering() + self.CurrentAction = ("Delete", event.GetPosition()) + def OnDoDrop(self, event): + wx.CallAfter(self.RefreshModel) + def IsViewing(self, name): + return self.Name == name + # Buffer the last model state + def RefreshBuffer(self): + self.Controler.BufferCFile() + self.ParentWindow.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + def StartBuffering(self): + self.Controler.StartBuffering() + self.ParentWindow.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + if self.CurrentAction != None: + self.Controler.EndBuffering() + self.CurrentAction = None + self.DisableEvents = True + old_cursor_pos = self.GetCurrentPos() + old_text = self.GetText() + new_text = self.Controler.GetPartText(self.Name) + new_cursor_pos = GetCursorPos(old_text, new_text) + if new_cursor_pos != None: + self.GotoPos(new_cursor_pos) + self.GotoPos(old_cursor_pos) + self.DisableEvents = False + def RefreshModel(self): + self.Controler.SetPartText(self.Name, self.GetText()) + def OnKeyPressed(self, event): + if self.CallTipActive(): + key = event.GetKeyCode() + if key == 32 and event.ControlDown(): + pos = self.GetCurrentPos() +## self.CallTipSetBackground("yellow") +## self.CallTipShow(pos, 'lots of of text: blah, blah, blah\n\n' +## 'show some suff, maybe parameters..\n\n' +## 'fubar(param1, param2)') + self.AutoCompSetIgnoreCase(False) # so this needs to match + # Images are specified with a appended "?type" + self.AutoCompShow(0, " ".join([word + "?1" for word in CPP_KEYWORDS])) + wx.CallAfter(self.RefreshModel) + def OnKillFocus(self, event): + def OnUpdateUI(self, evt): + # check for matching braces + caretPos = self.GetCurrentPos() + charBefore = self.GetCharAt(caretPos - 1) + styleBefore = self.GetStyleAt(caretPos - 1) + if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR: + braceAtCaret = caretPos - 1 + charAfter = self.GetCharAt(caretPos) + styleAfter = self.GetStyleAt(caretPos) + if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR: + braceAtCaret = caretPos + braceOpposite = self.BraceMatch(braceAtCaret) + if braceAtCaret != -1 and braceOpposite == -1: + self.BraceBadLight(braceAtCaret) + self.BraceHighlight(braceAtCaret, braceOpposite) + #pt = self.PointFromPosition(braceOpposite) + #self.Refresh(True, wxRect(pt.x, pt.y, 5,5)) + def OnMarginClick(self, evt): + # fold and unfold as needed + if evt.GetMargin() == 2: + if evt.GetShift() and evt.GetControl(): + lineClicked = self.LineFromPosition(evt.GetPosition()) + if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG: + self.SetFoldExpanded(lineClicked, True) + self.Expand(lineClicked, True, True, 1) + if self.GetFoldExpanded(lineClicked): + self.SetFoldExpanded(lineClicked, False) + self.Expand(lineClicked, False, True, 0) + self.SetFoldExpanded(lineClicked, True) + self.Expand(lineClicked, True, True, 100) + self.ToggleFold(lineClicked) + lineCount = self.GetLineCount() + # find out if we are folding or unfolding + for lineNum in range(lineCount): + if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG: + expanding = not self.GetFoldExpanded(lineNum) + while lineNum < lineCount: + level = self.GetFoldLevel(lineNum) + if level & stc.STC_FOLDLEVELHEADERFLAG and \ + (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE: + self.SetFoldExpanded(lineNum, True) + lineNum = self.Expand(lineNum, True) + lastChild = self.GetLastChild(lineNum, -1) + self.SetFoldExpanded(lineNum, False) + if lastChild > lineNum: + self.HideLines(lineNum+1, lastChild) + def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): + lastChild = self.GetLastChild(line, level) + while line <= lastChild: + self.ShowLines(line, line) + self.HideLines(line, line) + self.ShowLines(line, line) + level = self.GetFoldLevel(line) + if level & stc.STC_FOLDLEVELHEADERFLAG: + self.SetFoldExpanded(line, True) + self.SetFoldExpanded(line, False) + line = self.Expand(line, doExpand, force, visLevels-1) + if doExpand and self.GetFoldExpanded(line): + line = self.Expand(line, True, force, visLevels-1) + line = self.Expand(line, False, force, visLevels-1) +#------------------------------------------------------------------------------- +# Helper for VariablesGrid values +#------------------------------------------------------------------------------- +class VariablesTable(wx.grid.PyGridTableBase): + A custom wxGrid Table using user supplied data + def __init__(self, parent, data, colnames): + # The base class must be initialized *first* + wx.grid.PyGridTableBase.__init__(self) + self.colnames = colnames + # we need to store the row length and collength to + # see if the table has changed size + self._rows = self.GetNumberRows() + self._cols = self.GetNumberCols() + def GetNumberCols(self): + return len(self.colnames) + def GetNumberRows(self): + def GetColLabelValue(self, col): + if col < len(self.colnames): + return self.colnames[col] + def GetRowLabelValues(self, row): + def GetValue(self, row, col): + if row < self.GetNumberRows(): + return str(self.data[row].get(self.GetColLabelValue(col), "")) + def GetValueByName(self, row, colname): + if row < self.GetNumberRows(): + return self.data[row].get(colname, None) + def SetValue(self, row, col, value): + if col < len(self.colnames): + self.data[row][self.GetColLabelValue(col)] = value + def SetValueByName(self, row, colname, value): + if row < self.GetNumberRows(): + self.data[row][colname] = value + def ResetView(self, grid): + (wxGrid) -> Reset the grid view. Call this to + update the grid if rows and columns have been added or deleted + for current, new, delmsg, addmsg in [ + (self._rows, self.GetNumberRows(), wx.grid.GRIDTABLE_NOTIFY_ROWS_DELETED, wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED), + (self._cols, self.GetNumberCols(), wx.grid.GRIDTABLE_NOTIFY_COLS_DELETED, wx.grid.GRIDTABLE_NOTIFY_COLS_APPENDED), + msg = wx.grid.GridTableMessage(self,delmsg,new,current-new) + grid.ProcessTableMessage(msg) + msg = wx.grid.GridTableMessage(self,addmsg,new-current) + grid.ProcessTableMessage(msg) + self.UpdateValues(grid) + self._rows = self.GetNumberRows() + self._cols = self.GetNumberCols() + # update the column rendering scheme + self._updateColAttrs(grid) + # update the scrollbars and the displayed part of the grid + grid.AdjustScrollbars() + def UpdateValues(self, grid): + """Update all displayed values""" + # This sends an event to the grid table to update all of the values + msg = wx.grid.GridTableMessage(self, wx.grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES) + grid.ProcessTableMessage(msg) + def _updateColAttrs(self, grid): + wxGrid -> update the column attributes to add the + appropriate renderer given the column name. + Otherwise default to the default renderer. + for row in range(self.GetNumberRows()): + for col in range(self.GetNumberCols()): + colname = self.GetColLabelValue(col) + grid.SetReadOnly(row, col, False) + editor = wx.grid.GridCellTextEditor() + elif colname == "Class": + editor = wx.grid.GridCellChoiceEditor() + editor.SetParameters("input,output") + elif colname == "Type": + grid.SetReadOnly(row, col, True) + grid.SetCellEditor(row, col, editor) + grid.SetCellRenderer(row, col, renderer) + grid.SetCellBackgroundColour(row, col, wx.WHITE) + def SetData(self, data): + def GetCurrentIndex(self): + return self.CurrentIndex + def SetCurrentIndex(self, index): + self.CurrentIndex = index + def AppendRow(self, row_content): + self.data.append(row_content) + def RemoveRow(self, row_index): + self.data.pop(row_index) + def MoveRow(self, row_index, move, grid): + new_index = max(0, min(row_index + move, len(self.data) - 1)) + if new_index != row_index: + self.data.insert(new_index, self.data.pop(row_index)) + grid.SetGridCursor(new_index, grid.GetGridCursorCol()) + def GetRow(self, row_index): + return self.data[row_index] +[ID_VARIABLESEDITOR, ID_VARIABLESEDITORVARIABLESGRID, + ID_VARIABLESEDITORADDVARIABLEBUTTON, ID_VARIABLESEDITORDELETEVARIABLEBUTTON, + ID_VARIABLESEDITORUPVARIABLEBUTTON, ID_VARIABLESEDITORDOWNVARIABLEBUTTON +] = [wx.NewId() for _init_ctrls in range(6)] +class VariablesEditor(wx.Panel): + if wx.VERSION < (2, 6, 0): + def Bind(self, event, function, id = None): + event(self, id, function) + def _init_coll_MainSizer_Growables(self, parent): + parent.AddGrowableCol(0) + parent.AddGrowableRow(0) + def _init_coll_MainSizer_Items(self, parent): + parent.AddWindow(self.VariablesGrid, 0, border=0, flag=wx.GROW) + parent.AddSizer(self.ButtonsSizer, 0, border=0, flag=wx.GROW) + def _init_coll_ButtonsSizer_Growables(self, parent): + parent.AddGrowableCol(0) + parent.AddGrowableRow(0) + def _init_coll_ButtonsSizer_Items(self, parent): + parent.AddWindow(self.AddVariableButton, 0, border=0, flag=wx.ALIGN_RIGHT) + parent.AddWindow(self.DeleteVariableButton, 0, border=0, flag=0) + parent.AddWindow(self.UpVariableButton, 0, border=0, flag=0) + parent.AddWindow(self.DownVariableButton, 0, border=0, flag=0) + def _init_sizers(self): + self.MainSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=4) + self.ButtonsSizer = wx.FlexGridSizer(cols=5, hgap=5, rows=1, vgap=0) + self._init_coll_MainSizer_Growables(self.MainSizer) + self._init_coll_MainSizer_Items(self.MainSizer) + self._init_coll_ButtonsSizer_Growables(self.ButtonsSizer) + self._init_coll_ButtonsSizer_Items(self.ButtonsSizer) + self.SetSizer(self.MainSizer) + def _init_ctrls(self, prnt): + wx.Panel.__init__(self, id=ID_VARIABLESEDITOR, name='', parent=prnt, + size=wx.Size(0, 0), style=wx.SUNKEN_BORDER) + self.VariablesGrid = wx.grid.Grid(id=ID_VARIABLESEDITORVARIABLESGRID, + name='VariablesGrid', parent=self, pos=wx.Point(0, 0), + size=wx.Size(-1, -1), style=wx.VSCROLL) + self.VariablesGrid.SetFont(wx.Font(12, 77, wx.NORMAL, wx.NORMAL, False, + self.VariablesGrid.SetLabelFont(wx.Font(10, 77, wx.NORMAL, wx.NORMAL, + if wx.VERSION >= (2, 5, 0): + self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnVariablesGridCellChange) + self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnVariablesGridCellLeftClick) + self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, self.OnVariablesGridEditorShown) + wx.grid.EVT_GRID_CELL_CHANGE(self.VariablesGrid, self.OnVariablesGridCellChange) + wx.grid.EVT_GRID_CELL_LEFT_CLICK(self.VariablesGrid, self.OnVariablesGridCellLeftClick) + wx.grid.EVT_GRID_EDITOR_SHOWN(self.VariablesGrid, self.OnVariablesGridEditorShown) + self.AddVariableButton = wx.Button(id=ID_VARIABLESEDITORADDVARIABLEBUTTON, label='Add Variable', + name='AddVariableButton', parent=self, pos=wx.Point(0, 0), + size=wx.Size(122, 32), style=0) + self.Bind(wx.EVT_BUTTON, self.OnAddVariableButton, id=ID_VARIABLESEDITORADDVARIABLEBUTTON) + self.DeleteVariableButton = wx.Button(id=ID_VARIABLESEDITORDELETEVARIABLEBUTTON, label='Delete Variable', + name='DeleteVariableButton', parent=self, pos=wx.Point(0, 0), + size=wx.Size(122, 32), style=0) + self.Bind(wx.EVT_BUTTON, self.OnDeleteVariableButton, id=ID_VARIABLESEDITORDELETEVARIABLEBUTTON) + self.UpVariableButton = wx.Button(id=ID_VARIABLESEDITORUPVARIABLEBUTTON, label='^', + name='UpVariableButton', parent=self, pos=wx.Point(0, 0), + size=wx.Size(32, 32), style=0) + self.Bind(wx.EVT_BUTTON, self.OnUpVariableButton, id=ID_VARIABLESEDITORUPVARIABLEBUTTON) + self.DownVariableButton = wx.Button(id=ID_VARIABLESEDITORDOWNVARIABLEBUTTON, label='v', + name='DownVariableButton', parent=self, pos=wx.Point(0, 0), + size=wx.Size(32, 32), style=0) + self.Bind(wx.EVT_BUTTON, self.OnDownVariableButton, id=ID_VARIABLESEDITORDOWNVARIABLEBUTTON) + def __init__(self, parent, window, controler): + self._init_ctrls(parent) + self.ParentWindow = window + self.Controler = controler + self.VariablesDefaultValue = {"Name" : "", "Class" : "input", "Type" : ""} + self.Table = VariablesTable(self, [], ["#", "Name", "Class", "Type"]) + self.ColAlignements = [wx.ALIGN_RIGHT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT] + self.ColSizes = [40, 200, 150, 150] + self.VariablesGrid.SetTable(self.Table) + self.VariablesGrid.SetRowLabelSize(0) + for col in range(self.Table.GetNumberCols()): + attr = wx.grid.GridCellAttr() + attr.SetAlignment(self.ColAlignements[col], wx.ALIGN_CENTRE) + self.VariablesGrid.SetColAttr(col, attr) + self.VariablesGrid.SetColSize(col, self.ColSizes[col]) + self.Table.ResetView(self.VariablesGrid) + def IsViewing(self, name): + return name == "Variables" + def RefreshModel(self): + self.Controler.SetVariables(self.Table.GetData()) + # Buffer the last model state + def RefreshBuffer(self): + self.Controler.BufferCFile() + self.ParentWindow.RefreshTitle() + self.ParentWindow.RefreshEditMenu() + self.Table.SetData(self.Controler.GetVariables()) + self.Table.ResetView(self.VariablesGrid) + def OnAddVariableButton(self, event): + self.Table.AppendRow(self.VariablesDefaultValue.copy()) + def OnDeleteVariableButton(self, event): + row = self.VariablesGrid.GetGridCursorRow() + self.Table.RemoveRow(row) + def OnUpVariableButton(self, event): + row = self.VariablesGrid.GetGridCursorRow() + self.Table.MoveRow(row, -1, self.VariablesGrid) + def OnDownVariableButton(self, event): + row = self.VariablesGrid.GetGridCursorRow() + self.Table.MoveRow(row, 1, self.VariablesGrid) + def OnVariablesGridCellChange(self, event): + def OnVariablesGridEditorShown(self, event): + row, col = event.GetRow(), event.GetCol() + if self.Table.GetColLabelValue(col) == "Type": + type_menu = wx.Menu(title='') + base_menu = wx.Menu(title='') + for base_type in self.Controler.GetBaseTypes(): + AppendMenu(base_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=base_type) + self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(base_type), id=new_id) + type_menu.AppendMenu(wx.NewId(), "Base Types", base_menu) + datatype_menu = wx.Menu(title='') + for datatype in self.Controler.GetDataTypes(basetypes = False): + AppendMenu(datatype_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=datatype) + self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(datatype), id=new_id) + type_menu.AppendMenu(wx.NewId(), "User Data Types", datatype_menu) + rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col)) + self.VariablesGrid.PopupMenuXY(type_menu, rect.x + rect.width, rect.y + self.VariablesGrid.GetColLabelSize()) + def GetVariableTypeFunction(self, base_type): + def VariableTypeFunction(event): + row = self.VariablesGrid.GetGridCursorRow() + self.Table.SetValueByName(row, "Type", base_type) + self.Table.ResetView(self.VariablesGrid) + return VariableTypeFunction + def OnVariablesGridCellLeftClick(self, event): + if event.GetCol() == 0: + if self.Table.GetValueByName(row, "Class") == "input": + if self.Table.GetValueByName(i, "Class") == "input": + if self.Table.GetValueByName(i, "Class") == "input": + data_type = self.Table.GetValueByName(row, "Type") + base_location = ".".join(map(lambda x:str(x), self.Controler.GetCurrentLocation())) + location = "%s%s%s.%d"%(dir, self.Controler.GetSizeOfType(data_type), base_location, num) + data = wx.TextDataObject(str((location, "location", data_type))) + dragSource = wx.DropSource(self.VariablesGrid) + dragSource.SetData(data) + dragSource.DoDragDrop() +#------------------------------------------------------------------------------- +# SVGUIEditor Main Frame Class +#------------------------------------------------------------------------------- +if wx.VERSION >= (2, 8, 0): + base_class = wx.aui.AuiMDIParentFrame +CFILE_PARTS = ["Includes", "Variables", "Globals", "Init", "CleanUp", "Retrieve", +[ID_CFILEEDITOR, ID_CFILEEDITORMAINSPLITTER, + ID_CFILEEDITORCFILETREE, CFILEEDITORPARTSOPENED, +] = [wx.NewId() for _init_ctrls in range(4)] +class CFileEditor(base_class): + if wx.VERSION < (2, 6, 0): + def Bind(self, event, function, id = None): + event(self, id, function) + def _init_coll_EditMenu_Items(self, parent): + AppendMenu(parent, help='', id=wx.ID_REFRESH, + kind=wx.ITEM_NORMAL, text=u'Refresh\tCTRL+R') + AppendMenu(parent, help='', id=wx.ID_UNDO, + kind=wx.ITEM_NORMAL, text=u'Undo\tCTRL+Z') + AppendMenu(parent, help='', id=wx.ID_REDO, + kind=wx.ITEM_NORMAL, text=u'Redo\tCTRL+Y') + self.Bind(wx.EVT_MENU, self.OnRefreshMenu, id=wx.ID_REFRESH) + self.Bind(wx.EVT_MENU, self.OnUndoMenu, id=wx.ID_UNDO) + self.Bind(wx.EVT_MENU, self.OnRedoMenu, id=wx.ID_REDO) + def _init_coll_MenuBar_Menus(self, parent): + parent.Append(menu=self.EditMenu, title=u'&Edit') + self.MenuBar = wx.MenuBar() + self.EditMenu = wx.Menu(title='') + self._init_coll_MenuBar_Menus(self.MenuBar) + self._init_coll_EditMenu_Items(self.EditMenu) + def _init_ctrls(self, prnt): + if wx.VERSION >= (2, 8, 0): + wx.aui.AuiMDIParentFrame.__init__(self, winid=ID_CFILEEDITOR, name=u'CFileEditor', + parent=prnt, pos=wx.DefaultPosition, size=wx.Size(800, 650), + style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN, title=u'CFileEditor') + wx.Frame.__init__(self, id=ID_CFILEEDITOR, name=u'CFileEditor', + parent=prnt, pos=wx.DefaultPosition, size=wx.Size(800, 650), + style=wx.DEFAULT_FRAME_STYLE, title=u'CFileEditor') + self.SetClientSize(wx.Size(1000, 600)) + self.SetMenuBar(self.MenuBar) + self.Bind(wx.EVT_CLOSE, self.OnCloseFrame) + self.Bind(wx.EVT_MENU, self.OnSaveMenu, id=wx.ID_SAVE) + accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL, 83, wx.ID_SAVE)]) + self.SetAcceleratorTable(accel) + if wx.VERSION >= (2, 8, 0): + self.AUIManager = wx.aui.AuiManager(self) + self.AUIManager.SetDockSizeConstraint(0.5, 0.5) + if wx.VERSION < (2, 8, 0): + self.MainSplitter = wx.SplitterWindow(id=ID_CFILEEDITORMAINSPLITTER, + name='MainSplitter', parent=self, point=wx.Point(0, 0), + size=wx.Size(-1, -1), style=wx.SP_3D) + self.MainSplitter.SetNeedUpdating(True) + self.MainSplitter.SetMinimumPaneSize(1) + self.CFileTree = wx.TreeCtrl(id=ID_CFILEEDITORCFILETREE, + name='CFileTree', parent=self.MainSplitter, pos=wx.Point(0, 0), + size=wx.Size(-1, -1), style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER) + self.CFileTree = wx.TreeCtrl(id=ID_CFILEEDITORCFILETREE, + name='CFileTree', parent=self, pos=wx.Point(0, 0), + size=wx.Size(-1, -1), style=wx.TR_HAS_BUTTONS|wx.TR_SINGLE|wx.SUNKEN_BORDER) + self.AUIManager.AddPane(self.CFileTree, wx.aui.AuiPaneInfo().Caption("CFile Tree").Left().Layer(1).BestSize(wx.Size(200, 500)).CloseButton(False)) + self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnCFileTreeItemSelected, + id=ID_CFILEEDITORCFILETREE) + self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnCFileTreeItemActivated, + id=ID_CFILEEDITORCFILETREE) + if wx.VERSION < (2, 8, 0): + self.PartsOpened = wx.Notebook(id=ID_CFILEEDITORPARTSOPENED, + name='PartsOpened', parent=self.MainSplitter, pos=wx.Point(0, + 0), size=wx.Size(0, 0), style=0) + if wx.VERSION >= (2, 6, 0): + self.PartsOpened.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, + self.OnPartSelectedChanged, id=CFILEEDITORPARTSOPENED) + wx.EVT_NOTEBOOK_PAGE_CHANGED(self.PartsOpened, CFILEEDITORPARTSOPENED, + self.OnPartSelectedChanged) + self.MainSplitter.SplitVertically(self.ProjectTree, self.PartsOpened, 200) + self.StatusBar = wx.StatusBar( name='HelpBar', + parent=self, style=wx.ST_SIZEGRIP) + self.SetStatusBar(self.StatusBar) + if wx.VERSION >= (2, 8, 0): + self.AUIManager.Update() + def __init__(self, parent, controler): + self._init_ctrls(parent) + self.Controler = controler + def OnCloseFrame(self, event): + if wx.VERSION >= (2, 8, 0): + self.AUIManager.UnInit() + if getattr(self, "_onclose", None) is not None: + def OnCloseTabMenu(self, event): + selected = self.GetPageSelection() + self.DeletePage(selected) + def OnSaveMenu(self, event): + if getattr(self, "_onsave", None) != None: +#------------------------------------------------------------------------------- +# Notebook Unified Functions +#------------------------------------------------------------------------------- + def GetPageCount(self): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.GetPageCount() + return self.PartsOpened.GetPageCount() + def GetPage(self, idx): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.GetPage(idx).GetViewer() + return self.PartsOpened.GetPage(idx) + def GetPageSelection(self): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.GetSelection() + return self.PartsOpened.GetSelection() + def SetPageSelection(self, idx): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + notebook.SetSelection(idx) + self.PartsOpened.SetSelection(idx) + def DeletePage(self, idx): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + notebook.DeletePage(idx) + self.PartsOpened.DeletePage(idx) + def DeleteAllPages(self): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + for idx in xrange(notebook.GetPageCount()): + self.PartsOpened.DeleteAllPages() + def SetPageText(self, idx, text): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.SetPageText(idx, text) + return self.PartsOpened.SetPageText(idx, text) + def SetPageBitmap(self, idx, bitmap): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.SetPageBitmap(idx, bitmap) + return self.PartsOpened.SetPageImage(idx, bitmap) + def GetPageText(self, idx): + if wx.VERSION >= (2, 8, 0): + notebook = self.GetNotebook() + if notebook is not None: + return notebook.GetPageText(idx) + return self.PartsOpened.GetPageText(idx) + def IsOpened(self, name): + for idx in xrange(self.GetPageCount()): + if self.GetPage(idx).IsViewing(name): + def RefreshTitle(self): + self.SetTitle("CFileEditor - %s"%self.Controler.GetFilename()) +#------------------------------------------------------------------------------- +# Edit Project Menu Functions +#------------------------------------------------------------------------------- + def RefreshEditMenu(self): + undo, redo = self.Controler.GetBufferState() + self.EditMenu.Enable(wx.ID_UNDO, undo) + self.EditMenu.Enable(wx.ID_REDO, redo) + def OnRefreshMenu(self, event): + selected = self.GetPageSelection() + window = self.GetPage(selected) + def OnUndoMenu(self, event): + self.Controler.LoadPrevious() + selected = self.GetPageSelection() + window = self.GetPage(selected) + def OnRedoMenu(self, event): + self.Controler.LoadNext() + selected = self.GetPageSelection() + window = self.GetPage(selected) +#------------------------------------------------------------------------------- +# CFile Editor Panels Management Functions +#------------------------------------------------------------------------------- + def OnPartSelectedChanged(self, event): + if wx.VERSION < (2, 8, 0) or event.GetActive(): + old_selected = self.GetPageSelection() + self.GetPage(old_selected).ResetBuffer() + if wx.VERSION >= (2, 8, 0): + window = event.GetEventObject().GetViewer() + selected = event.GetSelection() + window = self.GetPage(selected) +#------------------------------------------------------------------------------- +# CFile Tree Management Functions +#------------------------------------------------------------------------------- + def InitCFileTree(self): + root = self.CFileTree.AddRoot("C File") + for name in CFILE_PARTS: + self.CFileTree.AppendItem(root, name) + self.CFileTree.Expand(root) + def OnCFileTreeItemActivated(self, event): + self.EditCFilePart(self.CFileTree.GetItemText(event.GetItem())) + def OnCFileTreeItemSelected(self, event): + select_item = event.GetItem() + self.EditCFilePart(self.CFileTree.GetItemText(event.GetItem()), True) + def EditCFilePart(self, name, onlyopened = False): + openedidx = self.IsOpened(name) + if openedidx is not None: + old_selected = self.GetPageSelection() + if old_selected != openedidx: + self.GetPage(old_selected).ResetBuffer() + self.SetPageSelection(openedidx) + self.GetPage(openedidx).RefreshView() + if wx.VERSION >= (2, 8, 0): + if name == "Variables": + new_window = MDIVariablesEditor(self, name, self, self.Controler) + new_window = MDICppEditor(self, name, self, self.Controler) + new_window.Bind(wx.EVT_ACTIVATE, self.OnPartSelectedChanged) + if name == "Variables": + new_window = VariablesEditor(self.TabsOpened, self, self.Controler) + self.TabsOpened.AddPage(new_window, name) + new_window = CppEditor(self.TabsOpened, name, self, self.Controler) + self.TabsOpened.AddPage(new_window, name) + openedidx = self.IsOpened(name) + old_selected = self.GetPageSelection() + if old_selected != openedidx: + self.GetPage(old_selected).ResetBuffer() + for i in xrange(self.GetPageCount()): + window = self.GetPage(i) + if window.IsViewing(name): + self.SetPageSelection(i) --- a/plugins/c_ext/CppSTC.py Tue May 06 15:22:18 2008 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,359 +0,0 @@
-#----------------------------------------------------------------------
-## This version of the editor has been set up to edit Python source
-## code. Here is a copy of wxPython/demo/Main.py to play with.
-#----------------------------------------------------------------------
-if wx.Platform == '__WXMSW__':
- faces = { 'times': 'Times New Roman',
- 'mono' : 'Courier New',
- 'other': 'Comic Sans MS',
- faces = { 'times': 'Times',
- 'other': 'new century schoolbook',
-#----------------------------------------------------------------------
-class CppSTC(stc.StyledTextCtrl):
- def __init__(self, parent, ID,
- pos=wx.DefaultPosition, size=wx.DefaultSize,
- stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)
- self.CmdKeyAssign(ord('B'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN)
- self.CmdKeyAssign(ord('N'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT)
- self.SetLexer(stc.STC_LEX_CPP)
- #self.SetKeyWords(0, " ".join(keyword.kwlist))
- self.SetProperty("fold", "1")
- self.SetProperty("tab.timmy.whinge.level", "1")
- self.SetViewWhiteSpace(False)
- #self.SetBufferedDraw(False)
- #self.SetEOLMode(stc.STC_EOL_CRLF)
- #self.SetUseAntiAliasing(True)
- self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
- # Setup a margin to hold fold markers
- #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER?
- self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
- self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
- self.SetMarginSensitive(2, True)
- self.SetMarginWidth(2, 12)
- if self.fold_symbols == 0:
- # Arrow pointing right for contracted folders, arrow pointing down for expanded
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_ARROWDOWN, "black", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_ARROW, "black", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "black", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "black", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black")
- elif self.fold_symbols == 1:
- # Plus for contracted folders, minus for expanded
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_MINUS, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_PLUS, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_EMPTY, "white", "black")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_EMPTY, "white", "black")
- elif self.fold_symbols == 2:
- # Like a flattened tree control using circular headers and curved joins
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_CIRCLEMINUS, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_CIRCLEPLUS, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNERCURVE, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_CIRCLEMINUSCONNECTED, "white", "#404040")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNERCURVE, "white", "#404040")
- elif self.fold_symbols == 3:
- # Like a flattened tree control using square headers
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN, stc.STC_MARK_BOXMINUS, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDER, stc.STC_MARK_BOXPLUS, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB, stc.STC_MARK_VLINE, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL, stc.STC_MARK_LCORNER, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND, stc.STC_MARK_BOXPLUSCONNECTED, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID, stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
- self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL, stc.STC_MARK_TCORNER, "white", "#808080")
- self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI)
- self.Bind(stc.EVT_STC_MARGINCLICK, self.OnMarginClick)
- self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPressed)
- # Make some styles, The lexer defines what each style is used for, we
- # just have to define what each style looks like. This set is adapted from
- # Scintilla sample property files.
- # Global default styles for all languages
- self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces)
- self.StyleClearAll() # Reset all to be like the default
- # Global default styles for all languages
- self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "face:%(mono)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(helv)s,size:%(size2)d" % faces)
- self.StyleSetSpec(stc.STC_STYLE_CONTROLCHAR, "face:%(other)s" % faces)
- self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, "fore:#FFFFFF,back:#0000FF,bold")
- self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, "fore:#000000,back:#FF0000,bold")
- self.StyleSetSpec(stc.STC_C_COMMENT, 'fore:#dcc000')
- self.StyleSetSpec(stc.STC_C_COMMENTLINE, 'fore:#dcc000')
- self.StyleSetSpec(stc.STC_C_COMMENTDOC, 'fore:#dcc000')
- self.StyleSetSpec(stc.STC_C_NUMBER, 'fore:#0076AE')
- self.StyleSetSpec(stc.STC_C_WORD, 'bold,fore:#004080')
- self.StyleSetSpec(stc.STC_C_STRING, 'fore:#800080')
- self.StyleSetSpec(stc.STC_C_PREPROCESSOR, 'fore:#808000')
- self.StyleSetSpec(stc.STC_C_OPERATOR, 'bold')
- self.StyleSetSpec(stc.STC_C_STRINGEOL, 'back:#FFD5FF')
- self.StyleSetSpec(stc.STC_P_DEFAULT, "fore:#000000,face:%(helv)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_COMMENTLINE, "fore:#007F00,face:%(other)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_NUMBER, "fore:#007F7F,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_STRING, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_CHARACTER, "fore:#7F007F,face:%(helv)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_WORD, "fore:#00007F,bold,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_TRIPLE, "fore:#7F0000,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, "fore:#7F0000,size:%(size)d" % faces)
- # Class name definition
- self.StyleSetSpec(stc.STC_P_CLASSNAME, "fore:#0000FF,bold,underline,size:%(size)d" % faces)
- # Function or method name definition
- self.StyleSetSpec(stc.STC_P_DEFNAME, "fore:#007F7F,bold,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_OPERATOR, "bold,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_IDENTIFIER, "fore:#000000,face:%(helv)s,size:%(size)d" % faces)
- self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, "fore:#7F7F7F,size:%(size)d" % faces)
- # End of line where string is not closed
- self.StyleSetSpec(stc.STC_P_STRINGEOL, "fore:#000000,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % faces)
- self.SetCaretForeground("BLUE")
- # register some images for use in the AutoComplete box.
- #self.RegisterImage(1, images.getSmilesBitmap())
- wx.ArtProvider.GetBitmap(wx.ART_DELETE, size=(16,16)))
- wx.ArtProvider.GetBitmap(wx.ART_NEW, size=(16,16)))
- wx.ArtProvider.GetBitmap(wx.ART_COPY, size=(16,16)))
- def OnKeyPressed(self, event):
- if self.CallTipActive():
- if key == 32 and event.ControlDown():
- pos = self.GetCurrentPos()
- self.CallTipSetBackground("yellow")
- self.CallTipShow(pos, 'lots of of text: blah, blah, blah\n\n'
- 'show some suff, maybe parameters..\n\n'
- 'fubar(param1, param2)')
- #for x in range(50000):
- # lst.append('%05d' % x)
- #self.AutoCompShow(0, st)
- #kw = keyword.kwlist[:]
- kw.append("__init__?3")
- kw.append("this_is_a_longer_value")
- #kw.append("this_is_a_much_much_much_much_much_much_much_longer_value")
- kw.sort() # Python sorts are case sensitive
- self.AutoCompSetIgnoreCase(False) # so this needs to match
- # Images are specified with a appended "?type"
- for i in range(len(kw)):
- if kw[i] in keyword.kwlist:
- self.AutoCompShow(0, " ".join(kw))
- def OnUpdateUI(self, evt):
- # check for matching braces
- caretPos = self.GetCurrentPos()
- charBefore = self.GetCharAt(caretPos - 1)
- styleBefore = self.GetStyleAt(caretPos - 1)
- if charBefore and chr(charBefore) in "[]{}()" and styleBefore == stc.STC_P_OPERATOR:
- braceAtCaret = caretPos - 1
- charAfter = self.GetCharAt(caretPos)
- styleAfter = self.GetStyleAt(caretPos)
- if charAfter and chr(charAfter) in "[]{}()" and styleAfter == stc.STC_P_OPERATOR:
- braceAtCaret = caretPos
- braceOpposite = self.BraceMatch(braceAtCaret)
- if braceAtCaret != -1 and braceOpposite == -1:
- self.BraceBadLight(braceAtCaret)
- self.BraceHighlight(braceAtCaret, braceOpposite)
- #pt = self.PointFromPosition(braceOpposite)
- #self.Refresh(True, wxRect(pt.x, pt.y, 5,5))
- def OnMarginClick(self, evt):
- # fold and unfold as needed
- if evt.GetMargin() == 2:
- if evt.GetShift() and evt.GetControl():
- lineClicked = self.LineFromPosition(evt.GetPosition())
- if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
- self.SetFoldExpanded(lineClicked, True)
- self.Expand(lineClicked, True, True, 1)
- if self.GetFoldExpanded(lineClicked):
- self.SetFoldExpanded(lineClicked, False)
- self.Expand(lineClicked, False, True, 0)
- self.SetFoldExpanded(lineClicked, True)
- self.Expand(lineClicked, True, True, 100)
- self.ToggleFold(lineClicked)
- lineCount = self.GetLineCount()
- # find out if we are folding or unfolding
- for lineNum in range(lineCount):
- if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
- expanding = not self.GetFoldExpanded(lineNum)
- while lineNum < lineCount:
- level = self.GetFoldLevel(lineNum)
- if level & stc.STC_FOLDLEVELHEADERFLAG and \
- (level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
- self.SetFoldExpanded(lineNum, True)
- lineNum = self.Expand(lineNum, True)
- lastChild = self.GetLastChild(lineNum, -1)
- self.SetFoldExpanded(lineNum, False)
- if lastChild > lineNum:
- self.HideLines(lineNum+1, lastChild)
- def Expand(self, line, doExpand, force=False, visLevels=0, level=-1):
- lastChild = self.GetLastChild(line, level)
- while line <= lastChild:
- self.ShowLines(line, line)
- self.HideLines(line, line)
- self.ShowLines(line, line)
- level = self.GetFoldLevel(line)
- if level & stc.STC_FOLDLEVELHEADERFLAG:
- self.SetFoldExpanded(line, True)
- self.SetFoldExpanded(line, False)
- line = self.Expand(line, doExpand, force, visLevels-1)
- if doExpand and self.GetFoldExpanded(line):
- line = self.Expand(line, True, force, visLevels-1)
- line = self.Expand(line, False, force, visLevels-1)
--- a/plugins/c_ext/c_ext.py Tue May 06 15:22:18 2008 +0200
+++ b/plugins/c_ext/c_ext.py Fri May 23 10:31:26 2008 +0200
@@ -1,16 +1,106 @@
-from CppSTC import CppSTC
from plugger import PlugTemplate
+from CFileEditor import CFileEditor +from xml.dom import minidom +CFileClasses = GenerateClassesFromXSD(os.path.join(os.path.dirname(__file__), "cext_xsd.xsd")) +#------------------------------------------------------------------------------- +#------------------------------------------------------------------------------- +Class implementing a buffer of changes made on the current editing model + # Constructor initialising buffer + def __init__(self, currentstate, issaved = False): + # if current state is defined + # Initialising buffer with currentstate at the first place + for i in xrange(UNDO_BUFFER_LENGTH): + self.Buffer.append(currentstate) + self.Buffer.append(None) + # Initialising index of state saved + # Add a new state in buffer + def Buffering(self, currentstate): + self.CurrentIndex = (self.CurrentIndex + 1) % UNDO_BUFFER_LENGTH + self.Buffer[self.CurrentIndex] = currentstate + # Actualising buffer limits + self.MaxIndex = self.CurrentIndex + if self.MinIndex == self.CurrentIndex: + # If the removed state was the state saved, there is no state saved in the buffer + if self.LastSave == self.MinIndex: + self.MinIndex = (self.MinIndex + 1) % UNDO_BUFFER_LENGTH + self.MinIndex = max(self.MinIndex, 0) + # Return current state of buffer + return self.Buffer[self.CurrentIndex] + # Change current state to previous in buffer and return new current state + if self.CurrentIndex != self.MinIndex: + self.CurrentIndex = (self.CurrentIndex - 1) % UNDO_BUFFER_LENGTH + return self.Buffer[self.CurrentIndex] + # Change current state to next in buffer and return new current state + if self.CurrentIndex != self.MaxIndex: + self.CurrentIndex = (self.CurrentIndex + 1) % UNDO_BUFFER_LENGTH + return self.Buffer[self.CurrentIndex] + # Return True if current state is the first in buffer + return self.CurrentIndex == self.MinIndex + # Return True if current state is the last in buffer + return self.CurrentIndex == self.MaxIndex + # Note that current state is saved + def CurrentSaved(self): + self.LastSave = self.CurrentIndex + # Return True if current state is saved + def IsCurrentSaved(self): + return self.LastSave == self.CurrentIndex +TYPECONVERSION = {"BOOL" : "X", "SINT" : "B", "INT" : "W", "DINT" : "D", "LINT" : "L", + "USINT" : "B", "UINT" : "W", "UDINT" : "D", "ULINT" : "L", "REAL" : "D", "LREAL" : "L", + "STRING" : "B", "BYTE" : "B", "WORD" : "W", "DWORD" : "D", "LWORD" : "L", "WSTRING" : "W"} XSD = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <xsd:element name="C_Extension">
+ <xsd:element name="CExtension"> - <xsd:attribute name="C_Files" type="xsd:string" use="optional" default="myfile.c"/>
<xsd:attribute name="CFLAGS" type="xsd:string" use="required"/>
<xsd:attribute name="LDFLAGS" type="xsd:string" use="required"/>
@@ -18,105 +108,117 @@
- self.CheckCFilesExist()
+ filepath = self.CFileName() - def CheckCFilesExist(self):
- for CFile in self.CFileNames():
- if not os.path.isfile(CFile):
+ self.CFile = CFileClasses["CFile"]() + self.CFileBuffer = UndoBuffer(self.Copy(self.CFile), False) + if os.path.isfile(filepath): + xmlfile = open(filepath, 'r') + tree = minidom.parse(xmlfile) + for child in tree.childNodes: + if child.nodeType == tree.ELEMENT_NODE and child.nodeName == "CFile": + self.CFile.loadXMLTree(child, ["xmlns", "xmlns:xsi", "xsi:schemaLocation"]) + self.CFileBuffer = UndoBuffer(self.Copy(self.CFile), True) - def CFileBaseNames(self):
- Returns list of C files base names, out of C_Extension.C_Files, coma separated list
- return map(str.strip,str(self.C_Extension.getC_Files()).split(','))
+ return os.path.join(self.PlugPath(), "cfile.xml") + if self.CFileBuffer.IsCurrentSaved(): - def CFileName(self, fn):
- return os.path.join(self.PlugPath(),fn)
+ def GetBaseTypes(self): + return self.GetPlugRoot().GetBaseTypes()
- Returns list of full C files paths, out of C_Extension.C_Files, coma separated list
- return map(self.CFileName, self.CFileBaseNames())
+ def GetDataTypes(self, basetypes = False): + return self.GetPlugRoot().GetDataTypes(basetypes = basetypes) + def GetSizeOfType(self, type): + return TYPECONVERSION[self.GetPlugRoot().GetBaseType(type)] - def SetParamsAttribute(self, path, value, logger):
- Take actions if C_Files changed
- # Get a C files list before changes
- oldnames = self.CFileNames()
- res = PlugTemplate.SetParamsAttribute(self, path, value, logger)
- # If changes was about C files,
- if path == "C_Extension.C_Files":
- # Create files if did not exist
- self.CheckCFilesExist()
- newnames = self.CFileNames()
- # Move unused files into trash (temporary directory)
- for oldfile in oldnames:
- if oldfile not in newnames:
- # define new "trash" name
- trashname = os.path.join(tempfile.gettempdir(),os.path.basename(oldfile))
- shutil.move(oldfile, trashname)
- logger.write_warning("\"%s\" moved to \"%s\"\n"%(oldfile, trashname))
+ def SetVariables(self, variables): + self.CFile.variables.setvariable([]) + variable = CFileClasses["variables_variable"]() + variable.setname(var["Name"]) + variable.settype(var["Type"]) + variable.setclass(var["Class"]) + self.CFile.variables.appendvariable(variable) + def GetVariables(self): + for var in self.CFile.variables.getvariable(): + datas.append({"Name" : var.getname(), "Type" : var.gettype(), "Class" : var.getclass()})
+ def SetPartText(self, name, text): + self.CFile.includes.settext(text) + elif name == "Globals": + self.CFile.globals.settext(text) + self.CFile.initFunction.settext(text) + elif name == "CleanUp": + self.CFile.cleanUpFunction.settext(text) + elif name == "Retrieve": + self.CFile.retrieveFunction.settext(text) + elif name == "Publish": + self.CFile.publishFunction.settext(text) + def GetPartText(self, name): + return self.CFile.includes.gettext() + elif name == "Globals": + return self.CFile.globals.gettext() + return self.CFile.initFunction.gettext() + elif name == "CleanUp": + return self.CFile.cleanUpFunction.gettext() + elif name == "Retrieve": + return self.CFile.retrieveFunction.gettext() + elif name == "Publish": + return self.CFile.publishFunction.gettext() def _OpenView(self, logger):
- lst = self.CFileBaseNames()
- dlg = wx.MultiChoiceDialog( self.GetPlugRoot().AppFrame,
- "Choose C files to Edit :",
- if (dlg.ShowModal() == wx.ID_OK):
- selections = dlg.GetSelections()
- for selected in [lst[x] for x in selections]:
- if selected not in self._Views:
- # keep track of selected name as static for later close
- def _onclose(evt, sel = selected):
- New_View = wx.Frame(self.GetPlugRoot().AppFrame,-1,selected)
- New_View.Bind(wx.EVT_CLOSE, _onclose)
- ed = CppSTC(New_View, wx.NewId())
- ed.SetText(open(self.CFileName(selected)).read())
- ed.SetMarginType(1, stc.STC_MARGIN_NUMBER)
- ed.SetMarginWidth(1, 25)
- self._Views[selected] = New_View
+ self.GetPlugRoot().SaveProject() + self._View = CFileEditor(self.GetPlugRoot().AppFrame, self) + self._View._onclose = _onclose + self._View._onsave = _onsave "tooltip" : "Edit C File",
- {"name" : "Import C File",
- "tooltip" : "Import C File",
- "method" : "_OpenView"}
- def SaveCView(self, name):
- f = open(self.CFileName(name),'w')
- f.write(self._Views[name].ed.GetText())
+ filepath = self.CFileName()
- for name in self._Views:
+ text = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + extras = {"xmlns":"http://www.w3.org/2001/XMLSchema", + "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance", + "xsi:schemaLocation" : "cext_xsd.xsd"} + text += self.CFile.generateXMLText("CFile", 0, extras) + xmlfile = open(filepath,"w") + self.CFileBuffer.CurrentSaved() def PlugGenerate_C(self, buildpath, locations, logger):
@@ -135,26 +237,126 @@
current_location = self.GetCurrentLocation()
# define a unique name for the generated C file
location_str = "_".join(map(lambda x:str(x), current_location))
- for CFile in self.CFileBaseNames():
- Gen_Cfile_path = os.path.join(buildpath, "CFile_%s_%s.c"%(location_str, os.path.splitext(CFile)[0]))
- f = open(Gen_Cfile_path,'w')
- f.write("/* Header generated by Beremiz c_ext plugin */\n")
- f.write("#include \"iec_std_lib.h\"\n")
- f.write("#define EXT_C_INIT __init_%s\n"%location_str)
- f.write("#define EXT_C_CLEANUP __init_%s\n"%location_str)
- f.write("#define EXT_C_PUBLISH __init_%s\n"%location_str)
- f.write("#define EXT_C_RETRIEVE __init_%s\n"%location_str)
- f.write(loc["IEC_TYPE"]+" "+loc["NAME"]+";\n")
- f.write("/* End of header generated by Beremiz c_ext plugin */\n\n")
- src_file = open(self.CFileName(CFile),'r')
- f.write(src_file.read())
- res.append((Gen_Cfile_path,str(self.C_Extension.getCFLAGS())))
- return res,str(self.C_Extension.getLDFLAGS()),True
+ text = "/* Code generated by Beremiz c_ext plugin */\n\n" + text += "/* User includes */\n" + text += self.CFile.includes.gettext() + text += """/* Beremiz c_ext plugin includes */ + #include "iec_std_lib.h" + for variable in self.CFile.variables.variable: + var = {"Name" : variable.getname(), "Type" : variable.gettype()} + if variable.getclass() == "input": + var["location"] = "__I%s%s_%d"%(self.GetSizeOfType(var["Type"]), location_str, inputs) + var["location"] = "__Q%s%s_%d"%(self.GetSizeOfType(var["Type"]), location_str, outputs) + text += "/* Beremiz c_ext plugin user variables definition */\n" + text += "#ifdef _WINDOWS_H\n" + base_types = self.GetPlugRoot().GetBaseTypes() + if var["Type"] in base_types: + text += "%s%s %s;\n"%(prefix, var["Type"], var["location"]) + text += "%s %s;\n"%(var["Type"], var["location"]) + text += "/* User variables reference */\n" + text += "#define %s %s;\n"%(var["Name"], var["location"]) + # Adding user global variables and routines + text += "/* User internal user variables and routines */\n" + text += self.CFile.globals.gettext() + # Adding Beremiz plugin functions + text += "/* Beremiz plugin functions */\n" + text += "int __init_%s(int argc,char **argv)\n{\n"%location_str + text += self.CFile.initFunction.gettext() + text += "void __cleanup_%s()\n{\n"%location_str + text += self.CFile.cleanUpFunction.gettext() + text += "void __retrieve_%s()\n{\n"%location_str + text += self.CFile.retrieveFunction.gettext() + text += "void __publish_%s()\n{\n"%location_str + text += self.CFile.publishFunction.gettext() + Gen_Cfile_path = os.path.join(buildpath, "CFile_%s.c"%location_str) + cfile = open(Gen_Cfile_path,'w') + if wx.Platform == '__WXMSW__': + matiec_flags = " -I../../matiec/lib" + matiec_flags = " -I../matiec/lib" + return [(Gen_Cfile_path, str(self.CExtension.getCFLAGS() + matiec_flags))],str(self.CExtension.getLDFLAGS()),True +#------------------------------------------------------------------------------- +# Current Buffering Management Functions +#------------------------------------------------------------------------------- + Return a copy of the project + return cPickle.loads(cPickle.dumps(model)) + self.CFileBuffer.Buffering(self.Copy(self.CFile)) + def StartBuffering(self): + self.CFileBuffer.Buffering(self.CFile) + def EndBuffering(self): + self.CFile = self.Copy(self.CFile) + def CFileIsSaved(self): + return self.CFileBuffer.IsCurrentSaved() + def LoadPrevious(self): + self.CFile = self.Copy(self.CFileBuffer.Previous()) + self.CFile = self.Copy(self.CFileBuffer.Next()) + def GetBufferState(self): + first = self.CFileBuffer.IsFirst() + last = self.CFileBuffer.IsLast() + return not first, not last PlugChildsTypes = [("C_File",_Cfile, "C file")]
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/plugins/c_ext/cext_xsd.xsd Fri May 23 10:31:26 2008 +0200
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?> +<xsd:schema targetNamespace="cext_xsd.xsd" + xmlns:cext="cext_xsd.xsd" + xmlns:xsd="http://www.w3.org/2001/XMLSchema" + elementFormDefault="qualified" + attributeFormDefault="unqualified"> + <xsd:element name="CFile"> + <xsd:element name="includes" type="cext:CCode"/> + <xsd:element name="variables"> + <xsd:element name="variable" minOccurs="0" maxOccurs="unbounded"> + <xsd:attribute name="name" type="xsd:string" use="required"/> + <xsd:attribute name="type" type="xsd:string" use="required"/> + <xsd:attribute name="class" use="required"> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="input"/> + <xsd:enumeration value="output"/> + <xsd:element name="globals" type="cext:CCode"/> + <xsd:element name="initFunction" type="cext:CCode"/> + <xsd:element name="cleanUpFunction" type="cext:CCode"/> + <xsd:element name="retrieveFunction" type="cext:CCode"/> + <xsd:element name="publishFunction" type="cext:CCode"/> + <xsd:complexType name="CCode"> + <xsd:documentation>Formatted text according to parts of XHTML 1.1</xsd:documentation> + <xsd:any namespace="http://www.w3.org/1999/xhtml" processContents="lax"/>