laurent@428: #!/usr/bin/env python laurent@428: # -*- coding: utf-8 -*- laurent@428: laurent@428: #This file is part of Beremiz, a Integrated Development Environment for laurent@428: #programming IEC 61131-3 automates supporting plcopen standard and CanFestival. laurent@428: # laurent@428: #Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD laurent@428: # laurent@428: #See COPYING file for copyrights details. laurent@428: # laurent@428: #This library is free software; you can redistribute it and/or laurent@428: #modify it under the terms of the GNU General Public laurent@428: #License as published by the Free Software Foundation; either laurent@428: #version 2.1 of the License, or (at your option) any later version. laurent@428: # laurent@428: #This library is distributed in the hope that it will be useful, laurent@428: #but WITHOUT ANY WARRANTY; without even the implied warranty of laurent@428: #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU laurent@428: #General Public License for more details. laurent@428: # laurent@428: #You should have received a copy of the GNU General Public laurent@428: #License along with this library; if not, write to the Free Software laurent@428: #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA laurent@428: laurent@428: __version__ = "$Revision$" laurent@428: laurent@428: import os, sys, getopt, wx laurent@428: import tempfile laurent@428: import shutil laurent@428: import random ed@446: import time laurent@428: laurent@428: CWD = os.path.split(os.path.realpath(__file__))[0] laurent@428: laurent@428: def Bpath(*args): laurent@428: return os.path.join(CWD,*args) laurent@428: laurent@428: if __name__ == '__main__': laurent@428: def usage(): laurent@428: print "\nUsage of Beremiz.py :" laurent@428: print "\n %s [Projectpath] [Buildpath]\n"%sys.argv[0] laurent@428: laurent@428: try: laurent@428: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) laurent@428: except getopt.GetoptError: laurent@428: # print help information and exit: laurent@428: usage() laurent@428: sys.exit(2) laurent@428: laurent@428: for o, a in opts: laurent@428: if o in ("-h", "--help"): laurent@428: usage() laurent@428: sys.exit() laurent@428: laurent@428: if len(args) > 2: laurent@428: usage() laurent@428: sys.exit() laurent@428: elif len(args) == 1: laurent@428: projectOpen = args[0] laurent@428: buildpath = None laurent@428: elif len(args) == 2: laurent@428: projectOpen = args[0] laurent@428: buildpath = args[1] laurent@428: else: laurent@428: projectOpen = None laurent@428: buildpath = None laurent@428: edouard@571: if os.path.exists("BEREMIZ_DEBUG"): edouard@571: __builtins__.BMZ_DBG = True edouard@571: else : edouard@571: __builtins__.BMZ_DBG = False edouard@571: edouard@571: app = wx.PySimpleApp(redirect=BMZ_DBG) laurent@428: app.SetAppName('beremiz') laurent@428: wx.InitAllImageHandlers() laurent@428: laurent@428: bmp = wx.Image(Bpath("images","splash.png")).ConvertToBitmap() laurent@428: splash=wx.SplashScreen(bmp,wx.SPLASH_CENTRE_ON_SCREEN, 1000, None) laurent@428: wx.Yield() laurent@428: laurent@428: # Import module for internationalization laurent@428: import gettext laurent@428: import __builtin__ laurent@428: laurent@428: # Get folder containing translation files laurent@428: localedir = os.path.join(CWD,"locale") laurent@428: # Get the default language laurent@428: langid = wx.LANGUAGE_DEFAULT laurent@428: # Define translation domain (name of translation files) laurent@428: domain = "Beremiz" laurent@428: laurent@428: # Define locale for wx laurent@428: loc = __builtin__.__dict__.get('loc', None) laurent@428: if loc is None: laurent@428: loc = wx.Locale(langid) laurent@428: __builtin__.__dict__['loc'] = loc laurent@428: # Define location for searching translation files laurent@428: loc.AddCatalogLookupPathPrefix(localedir) laurent@428: # Define locale domain laurent@428: loc.AddCatalog(domain) laurent@428: laurent@428: def unicode_translation(message): laurent@428: return wx.GetTranslation(message).encode("utf-8") laurent@428: laurent@428: if __name__ == '__main__': laurent@428: __builtin__.__dict__['_'] = wx.GetTranslation#unicode_translation laurent@428: laurent@428: #Quick hack to be able to find Beremiz IEC tools. Should be config params. laurent@428: base_folder = os.path.split(sys.path[0])[0] laurent@428: sys.path.append(base_folder) laurent@428: sys.path.append(os.path.join(base_folder, "plcopeneditor")) laurent@428: sys.path.append(os.path.join(base_folder, "docutils")) laurent@428: laurent@428: import wx.lib.buttons, wx.lib.statbmp laurent@428: import TextCtrlAutoComplete, cPickle laurent@428: import types, time, re, platform, time, traceback, commands laurent@428: from plugger import PluginsRoot, MATIEC_ERROR_MODEL laurent@428: from wxPopen import ProcessLogger laurent@428: laurent@428: from docutils import * laurent@428: from PLCOpenEditor import IDEFrame, Viewer, AppendMenu, TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU, TYPESTREE, INSTANCESTREE, LIBRARYTREE, SCALING laurent@428: from PLCControler import LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP, LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY laurent@428: laurent@428: SCROLLBAR_UNIT = 10 laurent@428: WINDOW_COLOUR = wx.Colour(240,240,240) laurent@428: TITLE_COLOUR = wx.Colour(200,200,220) laurent@428: CHANGED_TITLE_COLOUR = wx.Colour(220,200,220) laurent@428: CHANGED_WINDOW_COLOUR = wx.Colour(255,240,240) laurent@428: laurent@428: if wx.Platform == '__WXMSW__': laurent@428: faces = { 'times': 'Times New Roman', laurent@428: 'mono' : 'Courier New', laurent@428: 'helv' : 'Arial', laurent@428: 'other': 'Comic Sans MS', laurent@428: 'size' : 16, laurent@428: } laurent@428: else: laurent@428: faces = { 'times': 'Times', laurent@428: 'mono' : 'Courier', laurent@428: 'helv' : 'Helvetica', laurent@428: 'other': 'new century schoolbook', laurent@428: 'size' : 18, laurent@428: } laurent@428: laurent@428: # Some helpers to tweak GenBitmapTextButtons laurent@428: # TODO: declare customized classes instead. laurent@428: gen_mini_GetBackgroundBrush = lambda obj:lambda dc: wx.Brush(obj.GetParent().GetBackgroundColour(), wx.SOLID) laurent@428: gen_textbutton_GetLabelSize = lambda obj:lambda:(wx.lib.buttons.GenButton._GetLabelSize(obj)[:-1] + (False,)) laurent@428: laurent@428: def make_genbitmaptogglebutton_flat(button): laurent@428: button.GetBackgroundBrush = gen_mini_GetBackgroundBrush(button) laurent@428: button.labelDelta = 0 laurent@428: button.SetBezelWidth(0) laurent@428: button.SetUseFocusIndicator(False) laurent@428: laurent@428: # Patch wx.lib.imageutils so that gray is supported on alpha images laurent@428: import wx.lib.imageutils laurent@428: from wx.lib.imageutils import grayOut as old_grayOut laurent@428: def grayOut(anImage): laurent@428: if anImage.HasAlpha(): laurent@428: AlphaData = anImage.GetAlphaData() laurent@428: else : laurent@428: AlphaData = None laurent@428: laurent@428: old_grayOut(anImage) laurent@428: laurent@428: if AlphaData is not None: laurent@428: anImage.SetAlphaData(AlphaData) laurent@428: laurent@428: wx.lib.imageutils.grayOut = grayOut laurent@428: laurent@428: class GenBitmapTextButton(wx.lib.buttons.GenBitmapTextButton): laurent@428: def _GetLabelSize(self): laurent@428: """ used internally """ laurent@428: w, h = self.GetTextExtent(self.GetLabel()) laurent@428: if not self.bmpLabel: laurent@428: return w, h, False # if there isn't a bitmap use the size of the text laurent@428: laurent@428: w_bmp = self.bmpLabel.GetWidth()+2 laurent@428: h_bmp = self.bmpLabel.GetHeight()+2 laurent@428: height = h + h_bmp laurent@428: if w_bmp > w: laurent@428: width = w_bmp laurent@428: else: laurent@428: width = w laurent@428: return width, height, False laurent@428: laurent@428: def DrawLabel(self, dc, width, height, dw=0, dy=0): laurent@428: bmp = self.bmpLabel laurent@428: if bmp != None: # if the bitmap is used laurent@428: if self.bmpDisabled and not self.IsEnabled(): laurent@428: bmp = self.bmpDisabled laurent@428: if self.bmpFocus and self.hasFocus: laurent@428: bmp = self.bmpFocus laurent@428: if self.bmpSelected and not self.up: laurent@428: bmp = self.bmpSelected laurent@428: bw,bh = bmp.GetWidth(), bmp.GetHeight() laurent@428: if not self.up: laurent@428: dw = dy = self.labelDelta laurent@428: hasMask = bmp.GetMask() != None laurent@428: else: laurent@428: bw = bh = 0 # no bitmap -> size is zero laurent@428: laurent@428: dc.SetFont(self.GetFont()) laurent@428: if self.IsEnabled(): laurent@428: dc.SetTextForeground(self.GetForegroundColour()) laurent@428: else: laurent@428: dc.SetTextForeground(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)) laurent@428: laurent@428: label = self.GetLabel() laurent@428: tw, th = dc.GetTextExtent(label) # size of text laurent@428: if not self.up: laurent@428: dw = dy = self.labelDelta laurent@428: laurent@428: pos_x = (width-bw)/2+dw # adjust for bitmap and text to centre laurent@428: pos_y = (height-bh-th)/2+dy laurent@428: if bmp !=None: laurent@428: dc.DrawBitmap(bmp, pos_x, pos_y, hasMask) # draw bitmap if available laurent@428: pos_x = (width-tw)/2+dw # adjust for bitmap and text to centre laurent@428: pos_y += bh + 2 laurent@428: laurent@428: dc.DrawText(label, pos_x, pos_y) # draw the text laurent@428: laurent@428: laurent@428: class GenStaticBitmap(wx.lib.statbmp.GenStaticBitmap): laurent@428: """ Customized GenStaticBitmap, fix transparency redraw bug on wx2.8/win32, laurent@428: and accept image name as __init__ parameter, fail silently if file do not exist""" laurent@428: def __init__(self, parent, ID, bitmapname, laurent@428: pos = wx.DefaultPosition, size = wx.DefaultSize, laurent@428: style = 0, laurent@428: name = "genstatbmp"): laurent@428: laurent@428: bitmappath = Bpath( "images", bitmapname) laurent@428: if os.path.isfile(bitmappath): laurent@428: bitmap = wx.Bitmap(bitmappath) laurent@428: else: laurent@428: bitmap = None laurent@428: wx.lib.statbmp.GenStaticBitmap.__init__(self, parent, ID, bitmap, laurent@428: pos, size, laurent@428: style, laurent@428: name) laurent@428: laurent@428: def OnPaint(self, event): laurent@428: dc = wx.PaintDC(self) laurent@428: colour = self.GetParent().GetBackgroundColour() laurent@428: dc.SetPen(wx.Pen(colour)) laurent@428: dc.SetBrush(wx.Brush(colour )) laurent@428: dc.DrawRectangle(0, 0, *dc.GetSizeTuple()) laurent@428: if self._bitmap: laurent@428: dc.DrawBitmap(self._bitmap, 0, 0, True) laurent@428: laurent@428: laurent@428: class LogPseudoFile: laurent@428: """ Base class for file like objects to facilitate StdOut for the Shell.""" edouard@451: def __init__(self, output, risecall): laurent@428: self.red_white = wx.TextAttr("RED", "WHITE") laurent@428: self.red_yellow = wx.TextAttr("RED", "YELLOW") laurent@428: self.black_white = wx.TextAttr("BLACK", "WHITE") laurent@428: self.default_style = None laurent@428: self.output = output edouard@451: self.risecall = risecall ed@446: # to prevent rapid fire on rising log panel ed@446: self.rising_timer = 0 laurent@428: laurent@428: def write(self, s, style = None): laurent@428: if style is None : style=self.black_white laurent@428: self.output.Freeze(); laurent@428: if self.default_style != style: laurent@428: self.output.SetDefaultStyle(style) laurent@428: self.default_style = style laurent@428: self.output.AppendText(s) laurent@428: self.output.ScrollLines(s.count('\n')+1) laurent@428: self.output.ShowPosition(self.output.GetLastPosition()) laurent@428: self.output.Thaw() ed@446: newtime = time.time() ed@446: if newtime - self.rising_timer > 1: edouard@451: self.risecall() ed@446: self.rising_timer = newtime laurent@428: laurent@428: def write_warning(self, s): laurent@428: self.write(s,self.red_white) laurent@428: laurent@428: def write_error(self, s): laurent@428: self.write(s,self.red_yellow) laurent@428: edouard@569: def writeyield(self, s): edouard@569: self.write(s) edouard@569: wx.GetApp().Yield() edouard@569: laurent@428: def flush(self): laurent@428: self.output.SetValue("") laurent@428: laurent@428: def isatty(self): laurent@428: return false laurent@428: laurent@428: [ID_BEREMIZ, ID_BEREMIZMAINSPLITTER, laurent@428: ID_BEREMIZPLCCONFIG, ID_BEREMIZLOGCONSOLE, laurent@428: ID_BEREMIZINSPECTOR] = [wx.NewId() for _init_ctrls in range(5)] laurent@428: laurent@428: [ID_BEREMIZRUNMENUBUILD, ID_BEREMIZRUNMENUSIMULATE, laurent@428: ID_BEREMIZRUNMENURUN, ID_BEREMIZRUNMENUSAVELOG, laurent@428: ] = [wx.NewId() for _init_coll_EditMenu_Items in range(4)] laurent@428: laurent@428: class Beremiz(IDEFrame): laurent@428: laurent@428: def _init_coll_FileMenu_Items(self, parent): laurent@428: AppendMenu(parent, help='', id=wx.ID_NEW, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'New\tCTRL+N')) laurent@428: AppendMenu(parent, help='', id=wx.ID_OPEN, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Open\tCTRL+O')) laurent@428: AppendMenu(parent, help='', id=wx.ID_SAVE, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Save\tCTRL+S')) laurent@428: AppendMenu(parent, help='', id=wx.ID_SAVEAS, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Save as\tCTRL+SHIFT+S')) laurent@428: AppendMenu(parent, help='', id=wx.ID_CLOSE, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Close Tab\tCTRL+W')) laurent@428: AppendMenu(parent, help='', id=wx.ID_CLOSE_ALL, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Close Project')) laurent@428: parent.AppendSeparator() laurent@428: AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Page Setup')) laurent@428: AppendMenu(parent, help='', id=wx.ID_PREVIEW, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Preview')) laurent@428: AppendMenu(parent, help='', id=wx.ID_PRINT, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Print')) laurent@428: parent.AppendSeparator() laurent@428: AppendMenu(parent, help='', id=wx.ID_PROPERTIES, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Properties')) laurent@428: parent.AppendSeparator() laurent@428: AppendMenu(parent, help='', id=wx.ID_EXIT, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Quit\tCTRL+Q')) laurent@428: laurent@428: self.Bind(wx.EVT_MENU, self.OnNewProjectMenu, id=wx.ID_NEW) laurent@428: self.Bind(wx.EVT_MENU, self.OnOpenProjectMenu, id=wx.ID_OPEN) laurent@428: self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE) laurent@428: self.Bind(wx.EVT_MENU, self.OnSaveProjectAsMenu, id=wx.ID_SAVEAS) laurent@428: self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE) laurent@428: self.Bind(wx.EVT_MENU, self.OnCloseProjectMenu, id=wx.ID_CLOSE_ALL) laurent@428: self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP) laurent@428: self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW) laurent@428: self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT) laurent@428: self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES) laurent@428: self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT) laurent@428: laurent@428: def _init_coll_HelpMenu_Items(self, parent): laurent@428: parent.Append(help='', id=wx.ID_HELP, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'Beremiz\tF1')) laurent@428: parent.Append(help='', id=wx.ID_ABOUT, laurent@428: kind=wx.ITEM_NORMAL, text=_(u'About')) laurent@428: self.Bind(wx.EVT_MENU, self.OnBeremizMenu, id=wx.ID_HELP) laurent@428: self.Bind(wx.EVT_MENU, self.OnAboutMenu, id=wx.ID_ABOUT) laurent@428: laurent@428: def _init_coll_PLCConfigMainSizer_Items(self, parent): laurent@428: parent.AddSizer(self.PLCParamsSizer, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT) laurent@428: parent.AddSizer(self.PluginTreeSizer, 0, border=10, flag=wx.BOTTOM|wx.LEFT|wx.RIGHT) laurent@428: laurent@428: def _init_coll_PLCConfigMainSizer_Growables(self, parent): laurent@428: parent.AddGrowableCol(0) laurent@428: parent.AddGrowableRow(1) laurent@428: laurent@428: def _init_coll_PluginTreeSizer_Growables(self, parent): laurent@428: parent.AddGrowableCol(0) laurent@428: parent.AddGrowableCol(1) laurent@428: laurent@428: def _init_beremiz_sizers(self): laurent@428: self.PLCConfigMainSizer = wx.FlexGridSizer(cols=1, hgap=2, rows=2, vgap=2) laurent@428: self.PLCParamsSizer = wx.BoxSizer(wx.VERTICAL) laurent@428: #self.PluginTreeSizer = wx.FlexGridSizer(cols=3, hgap=0, rows=0, vgap=2) laurent@428: self.PluginTreeSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=0, vgap=2) laurent@428: laurent@428: self._init_coll_PLCConfigMainSizer_Items(self.PLCConfigMainSizer) laurent@428: self._init_coll_PLCConfigMainSizer_Growables(self.PLCConfigMainSizer) laurent@428: self._init_coll_PluginTreeSizer_Growables(self.PluginTreeSizer) laurent@428: laurent@428: self.PLCConfig.SetSizer(self.PLCConfigMainSizer) laurent@428: laurent@428: def _init_ctrls(self, prnt): laurent@428: IDEFrame._init_ctrls(self, prnt) laurent@428: laurent@428: self.Bind(wx.EVT_MENU, self.OnOpenWidgetInspector, id=ID_BEREMIZINSPECTOR) laurent@428: accel = wx.AcceleratorTable([wx.AcceleratorEntry(wx.ACCEL_CTRL|wx.ACCEL_ALT, ord('I'), ID_BEREMIZINSPECTOR)]) laurent@428: self.SetAcceleratorTable(accel) laurent@428: laurent@428: self.PLCConfig = wx.ScrolledWindow(id=ID_BEREMIZPLCCONFIG, laurent@428: name='PLCConfig', parent=self.LeftNoteBook, pos=wx.Point(0, 0), laurent@428: size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER|wx.HSCROLL|wx.VSCROLL) laurent@428: self.PLCConfig.SetBackgroundColour(wx.WHITE) laurent@428: self.PLCConfig.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@428: self.PLCConfig.Bind(wx.EVT_SIZE, self.OnMoveWindow) laurent@428: self.PLCConfig.Bind(wx.EVT_MOUSEWHEEL, self.OnPLCConfigScroll) laurent@428: self.BottomNoteBook.InsertPage(0, self.PLCConfig, _("Topology"), True) laurent@428: laurent@428: self.LogConsole = wx.TextCtrl(id=ID_BEREMIZLOGCONSOLE, value='', laurent@428: name='LogConsole', parent=self.BottomNoteBook, pos=wx.Point(0, 0), laurent@428: size=wx.Size(0, 0), style=wx.TE_MULTILINE|wx.TE_RICH2) laurent@428: self.LogConsole.Bind(wx.EVT_LEFT_DCLICK, self.OnLogConsoleDClick) laurent@428: self.BottomNoteBook.AddPage(self.LogConsole, _("Log Console")) laurent@513: self.BottomNoteBook.Split(self.BottomNoteBook.GetPageIndex(self.LogConsole), wx.RIGHT) laurent@428: laurent@428: self._init_beremiz_sizers() laurent@428: laurent@428: def __init__(self, parent, projectOpen=None, buildpath=None, plugin_root=None, debug=True): laurent@428: IDEFrame.__init__(self, parent, debug) laurent@428: self.Config = wx.ConfigBase.Get() edouard@451: self.Log = LogPseudoFile(self.LogConsole,self.RiseLogConsole) laurent@428: laurent@428: self.local_runtime = None laurent@428: self.runtime_port = None laurent@428: self.local_runtime_tmpdir = None laurent@428: laurent@428: self.DisableEvents = False laurent@428: # Variable allowing disabling of PLCConfig scroll when Popup shown laurent@428: self.ScrollingEnabled = True laurent@428: laurent@428: self.PluginInfos = {} laurent@428: laurent@428: if projectOpen is not None and os.path.isdir(projectOpen): laurent@428: self.PluginRoot = PluginsRoot(self, self.Log) laurent@428: self.Controler = self.PluginRoot laurent@428: result = self.PluginRoot.LoadProject(projectOpen, buildpath) laurent@428: if not result: laurent@428: self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE) laurent@428: self.RefreshAll() laurent@428: else: laurent@428: self.ResetView() laurent@428: self.ShowErrorMessage(result) laurent@428: else: laurent@428: self.PluginRoot = plugin_root laurent@428: self.Controler = plugin_root laurent@428: if plugin_root is not None: laurent@428: self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE) laurent@428: self.RefreshAll() laurent@490: if self.EnableDebug: laurent@490: self.DebugVariablePanel.SetDataProducer(self.PluginRoot) laurent@490: laurent@428: laurent@428: # Add beremiz's icon in top left corner of the frame laurent@428: self.SetIcon(wx.Icon(Bpath( "images", "brz.ico"), wx.BITMAP_TYPE_ICO)) laurent@428: laurent@428: self.Bind(wx.EVT_CLOSE, self.OnCloseFrame) laurent@428: laurent@428: self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU, DISPLAYMENU) laurent@428: ed@446: def RiseLogConsole(self): laurent@513: self.BottomNoteBook.SetSelection(self.BottomNoteBook.GetPageIndex(self.LogConsole)) ed@446: laurent@428: def RefreshTitle(self): laurent@428: name = _("Beremiz") laurent@428: if self.PluginRoot is not None: laurent@428: projectname = self.PluginRoot.GetProjectName() laurent@428: if self.PluginRoot.PlugTestModified(): laurent@428: projectname = "~%s~" % projectname laurent@428: self.SetTitle("%s - %s" % (name, projectname)) laurent@428: else: laurent@428: self.SetTitle(name) laurent@428: laurent@428: def StartLocalRuntime(self, taskbaricon = True): laurent@428: if self.local_runtime is None or self.local_runtime.finished: laurent@428: # create temporary directory for runtime working directory laurent@428: self.local_runtime_tmpdir = tempfile.mkdtemp() laurent@428: # choose an arbitrary random port for runtime laurent@428: self.runtime_port = int(random.random() * 1000) + 61131 laurent@428: # launch local runtime laurent@428: self.local_runtime = ProcessLogger(self.Log, laurent@428: "\"%s\" \"%s\" -p %s -i localhost %s %s"%(sys.executable, laurent@428: Bpath("Beremiz_service.py"), laurent@428: self.runtime_port, laurent@428: {False : "-x 0", True :"-x 1"}[taskbaricon], laurent@428: self.local_runtime_tmpdir), laurent@428: no_gui=False) laurent@428: self.local_runtime.spin(timeout=500, keyword = "working", kill_it = False) laurent@428: return self.runtime_port laurent@428: laurent@428: def KillLocalRuntime(self): laurent@428: if self.local_runtime is not None: laurent@428: # shutdown local runtime laurent@428: self.local_runtime.kill(gently=False) laurent@428: # clear temp dir laurent@428: shutil.rmtree(self.local_runtime_tmpdir) laurent@539: laurent@539: self.local_runtime = None laurent@428: laurent@428: def OnOpenWidgetInspector(self, evt): laurent@428: # Activate the widget inspection tool laurent@428: from wx.lib.inspection import InspectionTool laurent@428: if not InspectionTool().initialized: laurent@428: InspectionTool().Init() laurent@428: laurent@428: # Find a widget to be selected in the tree. Use either the laurent@428: # one under the cursor, if any, or this frame. laurent@428: wnd = wx.FindWindowAtPointer() laurent@428: if not wnd: laurent@428: wnd = self laurent@428: InspectionTool().Show(wnd, True) laurent@428: laurent@428: def OnLogConsoleDClick(self, event): laurent@428: wx.CallAfter(self.SearchLineForError) laurent@428: event.Skip() laurent@428: laurent@428: def SearchLineForError(self): laurent@428: if self.PluginRoot is not None: laurent@428: text = self.LogConsole.GetRange(0, self.LogConsole.GetInsertionPoint()) laurent@428: line = self.LogConsole.GetLineText(len(text.splitlines()) - 1) laurent@428: result = MATIEC_ERROR_MODEL.match(line) laurent@428: if result is not None: laurent@428: first_line, first_column, last_line, last_column, error = result.groups() laurent@428: infos = self.PluginRoot.ShowError(self.Log, laurent@428: (int(first_line), int(first_column)), laurent@428: (int(last_line), int(last_column))) laurent@429: laurent@429: ## Function displaying an Error dialog in PLCOpenEditor. laurent@429: # @return False if closing cancelled. laurent@429: def CheckSaveBeforeClosing(self, title=_("Close Project")): laurent@429: if self.PluginRoot.ProjectTestModified(): laurent@429: dialog = wx.MessageDialog(self, laurent@429: _("There are changes, do you want to save?"), laurent@429: title, laurent@429: wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION) laurent@429: answer = dialog.ShowModal() laurent@429: dialog.Destroy() laurent@429: if answer == wx.ID_YES: laurent@429: self.PluginRoot.SaveProject() laurent@429: elif answer == wx.ID_CANCEL: laurent@429: return False laurent@429: return True laurent@429: laurent@428: def OnCloseFrame(self, event): laurent@429: if self.PluginRoot is None or self.CheckSaveBeforeClosing(_("Close Application")): laurent@495: if self.PluginRoot is not None: laurent@495: self.PluginRoot.KillDebugThread() laurent@429: self.KillLocalRuntime() laurent@429: event.Skip() laurent@429: else: laurent@429: event.Veto() laurent@428: laurent@428: def OnMoveWindow(self, event): laurent@428: self.GetBestSize() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: laurent@428: def EnableScrolling(self, enable): laurent@428: self.ScrollingEnabled = enable laurent@428: laurent@428: def OnPLCConfigScroll(self, event): laurent@428: if self.ScrollingEnabled: laurent@428: event.Skip() laurent@428: laurent@428: def OnPanelLeftDown(self, event): laurent@428: focused = self.FindFocus() laurent@428: if isinstance(focused, TextCtrlAutoComplete.TextCtrlAutoComplete): laurent@428: focused.DismissListBox() laurent@428: event.Skip() laurent@428: laurent@428: def RefreshFileMenu(self): laurent@428: if self.PluginRoot is not None: laurent@428: selected = self.TabsOpened.GetSelection() laurent@428: if selected >= 0: laurent@428: graphic_viewer = isinstance(self.TabsOpened.GetPage(selected), Viewer) laurent@428: else: laurent@428: graphic_viewer = False laurent@428: if self.TabsOpened.GetPageCount() > 0: laurent@428: self.FileMenu.Enable(wx.ID_CLOSE, True) laurent@428: if graphic_viewer: laurent@428: self.FileMenu.Enable(wx.ID_PREVIEW, True) laurent@428: self.FileMenu.Enable(wx.ID_PRINT, True) laurent@428: else: laurent@428: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@428: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@428: else: laurent@428: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@428: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@428: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@428: self.FileMenu.Enable(wx.ID_PAGE_SETUP, True) laurent@499: self.FileMenu.Enable(wx.ID_SAVE, self.PluginRoot.PlugTestModified()) laurent@428: self.FileMenu.Enable(wx.ID_SAVEAS, True) laurent@428: self.FileMenu.Enable(wx.ID_PROPERTIES, True) laurent@428: self.FileMenu.Enable(wx.ID_CLOSE_ALL, True) laurent@428: else: laurent@428: self.FileMenu.Enable(wx.ID_CLOSE, False) laurent@428: self.FileMenu.Enable(wx.ID_PAGE_SETUP, False) laurent@428: self.FileMenu.Enable(wx.ID_PREVIEW, False) laurent@428: self.FileMenu.Enable(wx.ID_PRINT, False) laurent@428: self.FileMenu.Enable(wx.ID_SAVE, False) laurent@428: self.FileMenu.Enable(wx.ID_SAVEAS, False) laurent@428: self.FileMenu.Enable(wx.ID_PROPERTIES, False) laurent@428: self.FileMenu.Enable(wx.ID_CLOSE_ALL, False) laurent@428: laurent@428: def RefreshScrollBars(self): laurent@428: xstart, ystart = self.PLCConfig.GetViewStart() laurent@428: window_size = self.PLCConfig.GetClientSize() laurent@428: sizer = self.PLCConfig.GetSizer() laurent@428: if sizer: laurent@428: maxx, maxy = sizer.GetMinSize() laurent@428: self.PLCConfig.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT, laurent@428: maxx / SCROLLBAR_UNIT, maxy / SCROLLBAR_UNIT, laurent@428: max(0, min(xstart, (maxx - window_size[0]) / SCROLLBAR_UNIT)), laurent@428: max(0, min(ystart, (maxy - window_size[1]) / SCROLLBAR_UNIT))) laurent@428: laurent@428: def RefreshPLCParams(self): laurent@428: self.Freeze() laurent@428: self.ClearSizer(self.PLCParamsSizer) laurent@428: laurent@428: if self.PluginRoot is not None: laurent@428: plcwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@428: if self.PluginRoot.PlugTestModified(): laurent@428: bkgdclr = CHANGED_TITLE_COLOUR laurent@428: else: laurent@428: bkgdclr = TITLE_COLOUR laurent@428: laurent@428: if self.PluginRoot not in self.PluginInfos: laurent@428: self.PluginInfos[self.PluginRoot] = {"right_visible" : False} laurent@428: laurent@428: plcwindow.SetBackgroundColour(TITLE_COLOUR) laurent@428: plcwindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@428: self.PLCParamsSizer.AddWindow(plcwindow, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: plcwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: plcwindow.SetSizer(plcwindowsizer) laurent@428: laurent@428: st = wx.StaticText(plcwindow, -1) laurent@428: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@428: st.SetLabel(self.PluginRoot.GetProjectName()) laurent@428: plcwindowsizer.AddWindow(st, 0, border=5, flag=wx.ALL|wx.ALIGN_CENTER) laurent@428: laurent@428: addbutton_id = wx.NewId() laurent@428: addbutton = wx.lib.buttons.GenBitmapButton(id=addbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Add.png')), laurent@428: name='AddPluginButton', parent=plcwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(16, 16), style=wx.NO_BORDER) laurent@428: addbutton.SetToolTipString(_("Add a sub plugin")) laurent@428: addbutton.Bind(wx.EVT_BUTTON, self.Gen_AddPluginMenu(self.PluginRoot), id=addbutton_id) laurent@428: plcwindowsizer.AddWindow(addbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER) laurent@428: laurent@428: plcwindowmainsizer = wx.BoxSizer(wx.VERTICAL) laurent@428: plcwindowsizer.AddSizer(plcwindowmainsizer, 0, border=5, flag=wx.ALL) laurent@428: laurent@428: plcwindowbuttonsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: plcwindowmainsizer.AddSizer(plcwindowbuttonsizer, 0, border=0, flag=wx.ALIGN_CENTER) laurent@428: laurent@428: msizer = self.GenerateMethodButtonSizer(self.PluginRoot, plcwindow, not self.PluginInfos[self.PluginRoot]["right_visible"]) laurent@428: plcwindowbuttonsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: paramswindow = wx.Panel(plcwindow, -1, size=wx.Size(-1, -1), style=wx.TAB_TRAVERSAL) laurent@428: paramswindow.SetBackgroundColour(TITLE_COLOUR) laurent@428: paramswindow.Bind(wx.EVT_LEFT_DOWN, self.OnPanelLeftDown) laurent@428: plcwindowbuttonsizer.AddWindow(paramswindow, 0, border=0, flag=0) laurent@428: laurent@428: psizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: paramswindow.SetSizer(psizer) laurent@428: laurent@428: plugin_infos = self.PluginRoot.GetParamsAttributes() laurent@428: self.RefreshSizerElement(paramswindow, psizer, self.PluginRoot, plugin_infos, None, False) laurent@428: laurent@428: if not self.PluginInfos[self.PluginRoot]["right_visible"]: laurent@428: paramswindow.Hide() laurent@428: laurent@428: minimizebutton_id = wx.NewId() laurent@428: minimizebutton = wx.lib.buttons.GenBitmapToggleButton(id=minimizebutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Maximize.png')), laurent@428: name='MinimizeButton', parent=plcwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(24, 24), style=wx.NO_BORDER) laurent@428: make_genbitmaptogglebutton_flat(minimizebutton) laurent@428: minimizebutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'Minimize.png'))) laurent@428: minimizebutton.SetToggle(self.PluginInfos[self.PluginRoot]["right_visible"]) laurent@428: plcwindowbuttonsizer.AddWindow(minimizebutton, 0, border=5, flag=wx.ALL) laurent@428: laurent@428: def togglewindow(event): laurent@428: if minimizebutton.GetToggle(): laurent@428: paramswindow.Show() laurent@428: msizer.SetCols(1) laurent@428: else: laurent@428: paramswindow.Hide() laurent@428: msizer.SetCols(len(self.PluginRoot.PluginMethods)) laurent@428: self.PluginInfos[self.PluginRoot]["right_visible"] = minimizebutton.GetToggle() laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: minimizebutton.Bind(wx.EVT_BUTTON, togglewindow, id=minimizebutton_id) laurent@428: laurent@428: self.PluginInfos[self.PluginRoot]["main"] = plcwindow laurent@428: self.PluginInfos[self.PluginRoot]["params"] = paramswindow laurent@428: laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: self.Thaw() laurent@428: laurent@428: def GenerateMethodButtonSizer(self, plugin, parent, horizontal = True): laurent@428: normal_bt_font=wx.Font(faces["size"] / 3, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = faces["helv"]) laurent@428: mouseover_bt_font=wx.Font(faces["size"] / 3, wx.DEFAULT, wx.NORMAL, wx.NORMAL, underline=True, faceName = faces["helv"]) laurent@428: if horizontal: laurent@428: msizer = wx.FlexGridSizer(cols=len(plugin.PluginMethods)) laurent@428: else: laurent@428: msizer = wx.FlexGridSizer(cols=1) laurent@428: for plugin_method in plugin.PluginMethods: laurent@428: if "method" in plugin_method and plugin_method.get("shown",True): laurent@428: id = wx.NewId() laurent@428: label = plugin_method["name"] laurent@428: button = GenBitmapTextButton(id=id, parent=parent, laurent@428: bitmap=wx.Bitmap(Bpath( "%s.png"%plugin_method.get("bitmap", os.path.join("images", "Unknown")))), label=label, laurent@428: name=label, pos=wx.DefaultPosition, style=wx.NO_BORDER) laurent@428: button.SetFont(normal_bt_font) laurent@428: button.SetToolTipString(plugin_method["tooltip"]) laurent@428: button.Bind(wx.EVT_BUTTON, self.GetButtonCallBackFunction(plugin, plugin_method["method"]), id=id) laurent@428: # a fancy underline on mouseover laurent@428: def setFontStyle(b, s): laurent@428: def fn(event): laurent@428: b.SetFont(s) laurent@428: b.Refresh() laurent@428: event.Skip() laurent@428: return fn laurent@428: button.Bind(wx.EVT_ENTER_WINDOW, setFontStyle(button, mouseover_bt_font)) laurent@428: button.Bind(wx.EVT_LEAVE_WINDOW, setFontStyle(button, normal_bt_font)) laurent@428: #hack to force size to mini laurent@428: if not plugin_method.get("enabled",True): laurent@428: button.Disable() laurent@428: msizer.AddWindow(button, 0, border=0, flag=wx.ALIGN_CENTER) laurent@428: return msizer laurent@428: laurent@428: def RefreshPluginTree(self): laurent@428: self.Freeze() laurent@428: self.ClearSizer(self.PluginTreeSizer) laurent@428: if self.PluginRoot is not None: laurent@428: for child in self.PluginRoot.IECSortedChilds(): laurent@428: self.GenerateTreeBranch(child) laurent@428: if not self.PluginInfos[child]["expanded"]: laurent@428: self.CollapsePlugin(child) laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: self.Thaw() laurent@428: laurent@428: def SetPluginParamsAttribute(self, plugin, *args, **kwargs): laurent@428: res, StructChanged = plugin.SetParamsAttribute(*args, **kwargs) laurent@428: if StructChanged: laurent@428: wx.CallAfter(self.RefreshPluginTree) laurent@428: else: laurent@428: if plugin == self.PluginRoot: laurent@428: bkgdclr = CHANGED_TITLE_COLOUR laurent@428: items = ["main", "params"] laurent@428: else: laurent@428: bkgdclr = CHANGED_WINDOW_COLOUR laurent@428: items = ["left", "right", "params"] laurent@428: for i in items: laurent@428: self.PluginInfos[plugin][i].SetBackgroundColour(bkgdclr) laurent@428: self.PluginInfos[plugin][i].Refresh() laurent@505: self.RefreshFileMenu() laurent@428: return res laurent@428: laurent@428: def ExpandPlugin(self, plugin, force = False): laurent@428: for child in self.PluginInfos[plugin]["children"]: laurent@428: self.PluginInfos[child]["left"].Show() laurent@428: self.PluginInfos[child]["right"].Show() laurent@428: if force or not self.PluginInfos[child]["expanded"]: laurent@428: self.ExpandPlugin(child, force) laurent@428: if force: laurent@428: self.PluginInfos[child]["expanded"] = True laurent@428: locations_infos = self.PluginInfos[plugin].get("locations_infos", None) laurent@428: if locations_infos is not None: laurent@428: if force or locations_infos["root"]["expanded"]: laurent@428: self.ExpandLocation(locations_infos, "root", force) laurent@428: if force: laurent@428: locations_infos["root"]["expanded"] = True laurent@428: laurent@428: laurent@428: def CollapsePlugin(self, plugin, force = False): laurent@428: for child in self.PluginInfos[plugin]["children"]: laurent@428: self.PluginInfos[child]["left"].Hide() laurent@428: self.PluginInfos[child]["right"].Hide() laurent@428: self.CollapsePlugin(child, force) laurent@428: if force: laurent@428: self.PluginInfos[child]["expanded"] = False laurent@428: locations_infos = self.PluginInfos[plugin].get("locations_infos", None) laurent@428: if locations_infos is not None: laurent@428: self.CollapseLocation(locations_infos, "root", force) laurent@428: if force: laurent@428: locations_infos["root"]["expanded"] = False laurent@428: laurent@428: def ExpandLocation(self, locations_infos, group, force = False): laurent@428: for child in locations_infos[group]["children"]: laurent@428: locations_infos[child]["left"].Show() laurent@428: locations_infos[child]["right"].Show() laurent@428: if force or locations_infos[child]["expanded"]: laurent@428: self.ExpandLocation(locations_infos, child, force) laurent@428: if force: laurent@428: locations_infos[child]["expanded"] = True laurent@428: laurent@428: def CollapseLocation(self, locations_infos, group, force = False): laurent@428: for child in locations_infos[group]["children"]: laurent@428: locations_infos[child]["left"].Hide() laurent@428: locations_infos[child]["right"].Hide() laurent@428: self.CollapseLocation(locations_infos, child, force) laurent@428: if force: laurent@428: locations_infos[child]["expanded"] = False laurent@428: laurent@428: def GenerateTreeBranch(self, plugin): laurent@428: leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@428: if plugin.PlugTestModified(): laurent@428: bkgdclr=CHANGED_WINDOW_COLOUR laurent@428: else: laurent@428: bkgdclr=WINDOW_COLOUR laurent@428: laurent@428: leftwindow.SetBackgroundColour(bkgdclr) laurent@428: laurent@428: if not self.PluginInfos.has_key(plugin): laurent@428: self.PluginInfos[plugin] = {"expanded" : False, "right_visible" : False} laurent@428: laurent@428: self.PluginInfos[plugin]["children"] = plugin.IECSortedChilds() laurent@428: plugin_locations = [] laurent@428: if len(self.PluginInfos[plugin]["children"]) == 0: laurent@428: plugin_locations = plugin.GetVariableLocationTree()["children"] laurent@428: if not self.PluginInfos[plugin].has_key("locations_infos"): laurent@428: self.PluginInfos[plugin]["locations_infos"] = {"root": {"expanded" : False}} laurent@428: laurent@428: self.PluginInfos[plugin]["locations_infos"]["root"]["children"] = [] laurent@428: laurent@428: self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: leftwindowsizer = wx.FlexGridSizer(cols=1, rows=2) laurent@428: leftwindowsizer.AddGrowableCol(0) laurent@428: leftwindow.SetSizer(leftwindowsizer) laurent@428: laurent@428: leftbuttonmainsizer = wx.FlexGridSizer(cols=3, rows=1) laurent@428: leftbuttonmainsizer.AddGrowableCol(0) laurent@428: leftwindowsizer.AddSizer(leftbuttonmainsizer, 0, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT) #|wx.TOP laurent@428: laurent@428: leftbuttonsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: leftbuttonmainsizer.AddSizer(leftbuttonsizer, 0, border=5, flag=wx.GROW|wx.RIGHT) laurent@428: laurent@428: leftsizer = wx.BoxSizer(wx.VERTICAL) laurent@428: leftbuttonsizer.AddSizer(leftsizer, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: rolesizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: leftsizer.AddSizer(rolesizer, 0, border=0, flag=wx.GROW|wx.RIGHT) laurent@428: laurent@428: enablebutton_id = wx.NewId() laurent@428: enablebutton = wx.lib.buttons.GenBitmapToggleButton(id=enablebutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Disabled.png')), laurent@428: name='EnableButton', parent=leftwindow, size=wx.Size(16, 16), pos=wx.Point(0, 0), style=0)#wx.NO_BORDER) laurent@428: enablebutton.SetToolTipString(_("Enable/Disable this plugin")) laurent@428: make_genbitmaptogglebutton_flat(enablebutton) laurent@428: enablebutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'Enabled.png'))) laurent@428: enablebutton.SetToggle(plugin.MandatoryParams[1].getEnabled()) laurent@428: def toggleenablebutton(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, "BaseParams.Enabled", enablebutton.GetToggle()) laurent@428: enablebutton.SetToggle(res) laurent@428: event.Skip() laurent@428: enablebutton.Bind(wx.EVT_BUTTON, toggleenablebutton, id=enablebutton_id) laurent@428: rolesizer.AddWindow(enablebutton, 0, border=0, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: roletext = wx.StaticText(leftwindow, -1) laurent@428: roletext.SetLabel(plugin.PlugHelp) laurent@428: rolesizer.AddWindow(roletext, 0, border=5, flag=wx.RIGHT|wx.ALIGN_LEFT) laurent@428: laurent@428: plugin_IECChannel = plugin.BaseParams.getIEC_Channel() laurent@428: laurent@428: iecsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: leftsizer.AddSizer(iecsizer, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: st = wx.StaticText(leftwindow, -1) laurent@428: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@428: st.SetLabel(plugin.GetFullIEC_Channel()) laurent@428: iecsizer.AddWindow(st, 0, border=0, flag=0) laurent@428: laurent@428: updownsizer = wx.BoxSizer(wx.VERTICAL) laurent@428: iecsizer.AddSizer(updownsizer, 0, border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: if plugin_IECChannel > 0: laurent@428: ieccdownbutton_id = wx.NewId() laurent@428: ieccdownbutton = wx.lib.buttons.GenBitmapButton(id=ieccdownbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'IECCDown.png')), laurent@428: name='IECCDownButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(16, 16), style=wx.NO_BORDER) laurent@428: ieccdownbutton.Bind(wx.EVT_BUTTON, self.GetItemChannelChangedFunction(plugin, plugin_IECChannel - 1), id=ieccdownbutton_id) laurent@428: updownsizer.AddWindow(ieccdownbutton, 0, border=0, flag=wx.ALIGN_LEFT) laurent@428: laurent@428: ieccupbutton_id = wx.NewId() laurent@428: ieccupbutton = wx.lib.buttons.GenBitmapTextButton(id=ieccupbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'IECCUp.png')), laurent@428: name='IECCUpButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(16, 16), style=wx.NO_BORDER) laurent@428: ieccupbutton.Bind(wx.EVT_BUTTON, self.GetItemChannelChangedFunction(plugin, plugin_IECChannel + 1), id=ieccupbutton_id) laurent@428: updownsizer.AddWindow(ieccupbutton, 0, border=0, flag=wx.ALIGN_LEFT) laurent@428: laurent@428: adddeletesizer = wx.BoxSizer(wx.VERTICAL) laurent@428: iecsizer.AddSizer(adddeletesizer, 0, border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: deletebutton_id = wx.NewId() laurent@428: deletebutton = wx.lib.buttons.GenBitmapButton(id=deletebutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Delete.png')), laurent@428: name='DeletePluginButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(16, 16), style=wx.NO_BORDER) laurent@428: deletebutton.SetToolTipString(_("Delete this plugin")) laurent@428: deletebutton.Bind(wx.EVT_BUTTON, self.GetDeleteButtonFunction(plugin), id=deletebutton_id) laurent@428: adddeletesizer.AddWindow(deletebutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER) laurent@428: laurent@428: if len(plugin.PlugChildsTypes) > 0: laurent@428: addbutton_id = wx.NewId() laurent@428: addbutton = wx.lib.buttons.GenBitmapButton(id=addbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Add.png')), laurent@428: name='AddPluginButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(16, 16), style=wx.NO_BORDER) laurent@428: addbutton.SetToolTipString(_("Add a sub plugin")) laurent@428: addbutton.Bind(wx.EVT_BUTTON, self.Gen_AddPluginMenu(plugin), id=addbutton_id) laurent@428: adddeletesizer.AddWindow(addbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER) laurent@428: laurent@428: expandbutton_id = wx.NewId() laurent@428: expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')), laurent@428: name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(13, 13), style=wx.NO_BORDER) laurent@428: expandbutton.labelDelta = 0 laurent@428: expandbutton.SetBezelWidth(0) laurent@428: expandbutton.SetUseFocusIndicator(False) laurent@428: expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png'))) laurent@428: laurent@428: if len(self.PluginInfos[plugin]["children"]) > 0: laurent@428: expandbutton.SetToggle(self.PluginInfos[plugin]["expanded"]) laurent@428: def togglebutton(event): laurent@428: if expandbutton.GetToggle(): laurent@428: self.ExpandPlugin(plugin) laurent@428: else: laurent@428: self.CollapsePlugin(plugin) laurent@428: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@428: elif len(plugin_locations) > 0: laurent@428: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@428: expandbutton.SetToggle(locations_infos["root"]["expanded"]) laurent@428: def togglebutton(event): laurent@428: if expandbutton.GetToggle(): laurent@428: self.ExpandLocation(locations_infos, "root") laurent@428: else: laurent@428: self.CollapseLocation(locations_infos, "root") laurent@428: self.PluginInfos[plugin]["expanded"] = expandbutton.GetToggle() laurent@428: locations_infos["root"]["expanded"] = expandbutton.GetToggle() laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@428: else: laurent@428: expandbutton.Enable(False) laurent@428: iecsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: tc_id = wx.NewId() laurent@428: tc = wx.TextCtrl(leftwindow, tc_id, size=wx.Size(150, 25), style=wx.NO_BORDER) laurent@428: tc.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@428: tc.ChangeValue(plugin.MandatoryParams[1].getName()) laurent@428: tc.Bind(wx.EVT_TEXT, self.GetTextCtrlCallBackFunction(tc, plugin, "BaseParams.Name"), id=tc_id) laurent@428: iecsizer.AddWindow(tc, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@428: rightwindow.SetBackgroundColour(bkgdclr) laurent@428: laurent@428: self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: rightwindowmainsizer = wx.BoxSizer(wx.VERTICAL) laurent@428: rightwindow.SetSizer(rightwindowmainsizer) laurent@428: laurent@428: rightwindowsizer = wx.FlexGridSizer(cols=2, rows=1) laurent@428: rightwindowsizer.AddGrowableCol(1) laurent@428: rightwindowsizer.AddGrowableRow(0) laurent@428: rightwindowmainsizer.AddSizer(rightwindowsizer, 0, border=8, flag=wx.TOP|wx.GROW) laurent@428: laurent@428: msizer = self.GenerateMethodButtonSizer(plugin, rightwindow, not self.PluginInfos[plugin]["right_visible"]) laurent@428: rightwindowsizer.AddSizer(msizer, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: rightparamssizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: rightwindowsizer.AddSizer(rightparamssizer, 0, border=0, flag=wx.ALIGN_RIGHT) laurent@428: laurent@428: paramswindow = wx.Panel(rightwindow, -1, size=wx.Size(-1, -1)) laurent@428: paramswindow.SetBackgroundColour(bkgdclr) laurent@428: laurent@428: psizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: paramswindow.SetSizer(psizer) laurent@428: self.PluginInfos[plugin]["params"] = paramswindow laurent@428: laurent@428: rightparamssizer.AddWindow(paramswindow, 0, border=5, flag=wx.ALL) laurent@428: laurent@428: plugin_infos = plugin.GetParamsAttributes() laurent@428: self.RefreshSizerElement(paramswindow, psizer, plugin, plugin_infos, None, False) laurent@428: laurent@428: if not self.PluginInfos[plugin]["right_visible"]: laurent@428: paramswindow.Hide() laurent@428: laurent@428: rightminimizebutton_id = wx.NewId() laurent@428: rightminimizebutton = wx.lib.buttons.GenBitmapToggleButton(id=rightminimizebutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'Maximize.png')), laurent@428: name='MinimizeButton', parent=rightwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(24, 24), style=wx.NO_BORDER) laurent@428: make_genbitmaptogglebutton_flat(rightminimizebutton) laurent@428: rightminimizebutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'Minimize.png'))) laurent@428: rightminimizebutton.SetToggle(self.PluginInfos[plugin]["right_visible"]) laurent@428: rightparamssizer.AddWindow(rightminimizebutton, 0, border=5, flag=wx.ALL) laurent@428: laurent@428: def togglerightwindow(event): laurent@428: if rightminimizebutton.GetToggle(): laurent@428: rightparamssizer.Show(0) laurent@428: msizer.SetCols(1) laurent@428: else: laurent@428: rightparamssizer.Hide(0) laurent@428: msizer.SetCols(len(plugin.PluginMethods)) laurent@428: self.PluginInfos[plugin]["right_visible"] = rightminimizebutton.GetToggle() laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: rightminimizebutton.Bind(wx.EVT_BUTTON, togglerightwindow, id=rightminimizebutton_id) laurent@428: laurent@428: self.PluginInfos[plugin]["left"] = leftwindow laurent@428: self.PluginInfos[plugin]["right"] = rightwindow laurent@428: for child in self.PluginInfos[plugin]["children"]: laurent@428: self.GenerateTreeBranch(child) laurent@428: if not self.PluginInfos[child]["expanded"]: laurent@428: self.CollapsePlugin(child) laurent@428: if len(plugin_locations) > 0: laurent@428: locations_infos = self.PluginInfos[plugin]["locations_infos"] laurent@428: for location in plugin_locations: laurent@428: locations_infos["root"]["children"].append("root.%s" % location["name"]) laurent@428: self.GenerateLocationTreeBranch(locations_infos, "root", location) laurent@428: if not locations_infos["root"]["expanded"]: laurent@428: self.CollapseLocation(locations_infos, "root") laurent@428: laurent@428: LOCATION_BITMAP = {LOCATION_PLUGIN: "CONFIGURATION", laurent@428: LOCATION_MODULE: "RESOURCE", laurent@428: LOCATION_GROUP: "PROGRAM", laurent@428: LOCATION_VAR_INPUT: "VAR_INPUT", laurent@428: LOCATION_VAR_OUTPUT: "VAR_OUTPUT", laurent@428: LOCATION_VAR_MEMORY: "VAR_LOCAL"} laurent@428: laurent@428: def GenerateLocationTreeBranch(self, locations_infos, parent, location): laurent@428: leftwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@428: self.PluginTreeSizer.AddWindow(leftwindow, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: leftwindowsizer = wx.BoxSizer(wx.HORIZONTAL) laurent@428: leftwindow.SetSizer(leftwindowsizer) laurent@428: laurent@428: rightwindow = wx.Panel(self.PLCConfig, -1, size=wx.Size(-1, -1)) laurent@428: self.PluginTreeSizer.AddWindow(rightwindow, 0, border=0, flag=wx.GROW) laurent@428: laurent@428: location_name = "%s.%s" % (parent, location["name"]) laurent@428: if not locations_infos.has_key(location_name): laurent@428: locations_infos[location_name] = {"expanded" : False} laurent@428: laurent@428: if location["type"] in [LOCATION_PLUGIN, LOCATION_MODULE, LOCATION_GROUP]: laurent@439: if location["type"] == LOCATION_GROUP: laurent@439: leftwindow.SetBackgroundColour(wx.WHITE) laurent@439: rightwindow.SetBackgroundColour(wx.WHITE) laurent@439: else: laurent@439: leftwindow.SetBackgroundColour(WINDOW_COLOUR) laurent@439: rightwindow.SetBackgroundColour(WINDOW_COLOUR) laurent@439: laurent@428: st = wx.StaticText(leftwindow, -1) laurent@428: st.SetFont(wx.Font(faces["size"], wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@428: st.SetLabel(location["location"]) laurent@428: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT) laurent@428: laurent@428: expandbutton_id = wx.NewId() laurent@428: expandbutton = wx.lib.buttons.GenBitmapToggleButton(id=expandbutton_id, bitmap=wx.Bitmap(Bpath( 'images', 'plus.png')), laurent@428: name='ExpandButton', parent=leftwindow, pos=wx.Point(0, 0), laurent@428: size=wx.Size(13, 13), style=wx.NO_BORDER) laurent@428: expandbutton.labelDelta = 0 laurent@428: expandbutton.SetBezelWidth(0) laurent@428: expandbutton.SetUseFocusIndicator(False) laurent@428: expandbutton.SetBitmapSelected(wx.Bitmap(Bpath( 'images', 'minus.png'))) laurent@428: expandbutton.SetToggle(locations_infos[location_name]["expanded"]) laurent@428: laurent@428: if len(location["children"]) > 0: laurent@428: def togglebutton(event): laurent@428: if expandbutton.GetToggle(): laurent@428: self.ExpandLocation(locations_infos, location_name) laurent@428: else: laurent@428: self.CollapseLocation(locations_infos, location_name) laurent@428: locations_infos[location_name]["expanded"] = expandbutton.GetToggle() laurent@428: self.PLCConfigMainSizer.Layout() laurent@428: self.RefreshScrollBars() laurent@428: event.Skip() laurent@428: expandbutton.Bind(wx.EVT_BUTTON, togglebutton, id=expandbutton_id) laurent@428: else: laurent@428: expandbutton.Enable(False) laurent@428: leftwindowsizer.AddWindow(expandbutton, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: else: laurent@428: leftwindow.SetBackgroundColour(wx.WHITE) laurent@428: rightwindow.SetBackgroundColour(wx.WHITE) laurent@428: laurent@428: leftwindowsizer.Add(wx.Size(20, 16), 0) laurent@550: laurent@428: sb = wx.StaticBitmap(leftwindow, -1) laurent@439: icon = location.get("icon") laurent@439: if icon is None: laurent@439: icon = os.path.join(base_folder, "plcopeneditor", 'Images', '%s.png' % self.LOCATION_BITMAP[location["type"]]) laurent@439: sb.SetBitmap(wx.Bitmap(icon)) laurent@428: leftwindowsizer.AddWindow(sb, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: st_id = wx.NewId() laurent@428: st = wx.StaticText(leftwindow, st_id, size=wx.DefaultSize, style=wx.NO_BORDER) laurent@428: label = location["name"] laurent@428: if location["type"] in [LOCATION_VAR_INPUT, LOCATION_VAR_OUTPUT, LOCATION_VAR_MEMORY]: laurent@428: label += " (%s)" % location["location"] laurent@428: infos = location.copy() laurent@428: infos.pop("children") laurent@428: st.SetFont(wx.Font(faces["size"] * 0.5, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = faces["helv"])) laurent@550: leftcallback = self.GenerateLocationLeftDownFunction(infos) laurent@550: st.Bind(wx.EVT_LEFT_DOWN, leftcallback) laurent@550: sb.Bind(wx.EVT_LEFT_DOWN, leftcallback) laurent@439: elif location["type"] == LOCATION_GROUP: laurent@439: st.SetFont(wx.Font(faces["size"] * 0.6, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = faces["helv"])) laurent@428: else: laurent@428: st.SetFont(wx.Font(faces["size"] * 0.75, wx.DEFAULT, wx.NORMAL, wx.BOLD, faceName = faces["helv"])) laurent@428: st.SetLabel(label) laurent@428: leftwindowsizer.AddWindow(st, 0, border=5, flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL) laurent@428: laurent@428: locations_infos[location_name]["left"] = leftwindow laurent@428: locations_infos[location_name]["right"] = rightwindow laurent@428: locations_infos[location_name]["children"] = [] laurent@428: for child in location["children"]: laurent@428: child_name = "%s.%s" % (location_name, child["name"]) laurent@428: locations_infos[location_name]["children"].append(child_name) laurent@428: self.GenerateLocationTreeBranch(locations_infos, location_name, child) laurent@428: if not locations_infos[location_name]["expanded"]: laurent@428: self.CollapseLocation(locations_infos, location_name) laurent@428: laurent@428: def GenerateLocationLeftDownFunction(self, infos): laurent@428: def OnLocationLeftDownFunction(event): laurent@428: data = wx.TextDataObject(str((infos["location"], "location", infos["IEC_type"], infos["name"], infos["description"]))) laurent@428: dragSource = wx.DropSource(self) laurent@428: dragSource.SetData(data) laurent@428: dragSource.DoDragDrop() laurent@428: event.Skip() laurent@428: return OnLocationLeftDownFunction laurent@428: laurent@428: def RefreshAll(self): laurent@428: self.RefreshPLCParams() laurent@428: self.RefreshPluginTree() laurent@428: laurent@428: def GetItemChannelChangedFunction(self, plugin, value): laurent@428: def OnPluginTreeItemChannelChanged(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, "BaseParams.IEC_Channel", value) laurent@428: event.Skip() laurent@428: return OnPluginTreeItemChannelChanged laurent@428: laurent@428: def _GetAddPluginFunction(self, name, plugin): laurent@428: def OnPluginMenu(event): laurent@428: wx.CallAfter(self.AddPlugin, name, plugin) laurent@428: return OnPluginMenu laurent@428: laurent@428: def Gen_AddPluginMenu(self, plugin): laurent@428: def AddPluginMenu(event): laurent@428: main_menu = wx.Menu(title='') laurent@428: if len(plugin.PlugChildsTypes) > 0: laurent@428: for name, XSDClass, help in plugin.PlugChildsTypes: laurent@428: new_id = wx.NewId() laurent@428: main_menu.Append(help=help, id=new_id, kind=wx.ITEM_NORMAL, text=_("Append ")+help) laurent@428: self.Bind(wx.EVT_MENU, self._GetAddPluginFunction(name, plugin), id=new_id) laurent@428: self.PopupMenuXY(main_menu) laurent@428: return AddPluginMenu laurent@428: laurent@428: def GetButtonCallBackFunction(self, plugin, method): laurent@428: """ Generate the callbackfunc for a given plugin method""" laurent@428: def OnButtonClick(event): laurent@428: # Disable button to prevent re-entrant call laurent@428: event.GetEventObject().Disable() laurent@428: # Call laurent@428: getattr(plugin,method)() laurent@428: # Re-enable button laurent@428: event.GetEventObject().Enable() laurent@428: # Trigger refresh on Idle laurent@428: wx.CallAfter(self.RefreshAll) laurent@428: event.Skip() laurent@428: return OnButtonClick laurent@428: laurent@428: def GetChoiceCallBackFunction(self, choicectrl, plugin, path): laurent@428: def OnChoiceChanged(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, path, choicectrl.GetStringSelection()) laurent@428: choicectrl.SetStringSelection(res) laurent@428: event.Skip() laurent@428: return OnChoiceChanged laurent@428: laurent@428: def GetChoiceContentCallBackFunction(self, choicectrl, staticboxsizer, plugin, path): laurent@428: def OnChoiceContentChanged(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, path, choicectrl.GetStringSelection()) laurent@428: if wx.VERSION < (2, 8, 0): laurent@428: self.ParamsPanel.Freeze() laurent@428: choicectrl.SetStringSelection(res) laurent@428: infos = self.PluginRoot.GetParamsAttributes(path) laurent@428: staticbox = staticboxsizer.GetStaticBox() laurent@428: staticbox.SetLabel("%(name)s - %(value)s"%infos) laurent@428: self.RefreshSizerElement(self.ParamsPanel, staticboxsizer, infos["children"], "%s.%s"%(path, infos["name"]), selected=selected) laurent@428: self.ParamsPanelMainSizer.Layout() laurent@428: self.ParamsPanel.Thaw() laurent@428: self.ParamsPanel.Refresh() laurent@428: else: laurent@428: wx.CallAfter(self.RefreshAll) laurent@428: event.Skip() laurent@428: return OnChoiceContentChanged laurent@428: laurent@428: def GetTextCtrlCallBackFunction(self, textctrl, plugin, path): laurent@428: def OnTextCtrlChanged(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, path, textctrl.GetValue()) laurent@428: if res != textctrl.GetValue(): laurent@428: textctrl.ChangeValue(res) laurent@428: event.Skip() laurent@428: return OnTextCtrlChanged laurent@428: laurent@428: def GetCheckBoxCallBackFunction(self, chkbx, plugin, path): laurent@428: def OnCheckBoxChanged(event): laurent@428: res = self.SetPluginParamsAttribute(plugin, path, chkbx.IsChecked()) laurent@428: chkbx.SetValue(res) laurent@428: event.Skip() laurent@428: return OnCheckBoxChanged laurent@428: laurent@428: def ClearSizer(self, sizer): laurent@428: staticboxes = [] laurent@428: for item in sizer.GetChildren(): laurent@428: if item.IsSizer(): laurent@428: item_sizer = item.GetSizer() laurent@428: self.ClearSizer(item_sizer) laurent@428: if isinstance(item_sizer, wx.StaticBoxSizer): laurent@428: staticboxes.append(item_sizer.GetStaticBox()) laurent@428: sizer.Clear(True) laurent@428: for staticbox in staticboxes: laurent@428: staticbox.Destroy() laurent@428: laurent@428: def RefreshSizerElement(self, parent, sizer, plugin, elements, path, clean = True): laurent@428: if clean: laurent@428: if wx.VERSION < (2, 8, 0): laurent@428: self.ClearSizer(sizer) laurent@428: else: laurent@428: sizer.Clear(True) laurent@428: first = True laurent@428: for element_infos in elements: laurent@428: if path: laurent@428: element_path = "%s.%s"%(path, element_infos["name"]) laurent@428: else: laurent@428: element_path = element_infos["name"] laurent@428: if element_infos["type"] == "element": laurent@428: label = element_infos["name"] laurent@428: staticbox = wx.StaticBox(id=-1, label=_(label), laurent@428: name='%s_staticbox'%element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(10, 0), style=0) laurent@428: staticboxsizer = wx.StaticBoxSizer(staticbox, wx.VERTICAL) laurent@428: if first: laurent@428: sizer.AddSizer(staticboxsizer, 0, border=0, flag=wx.GROW|wx.TOP) laurent@428: else: laurent@428: sizer.AddSizer(staticboxsizer, 0, border=0, flag=wx.GROW) laurent@428: self.RefreshSizerElement(parent, staticboxsizer, plugin, element_infos["children"], element_path) laurent@428: else: laurent@428: boxsizer = wx.FlexGridSizer(cols=3, rows=1) laurent@428: boxsizer.AddGrowableCol(1) laurent@428: if first: laurent@428: sizer.AddSizer(boxsizer, 0, border=5, flag=wx.GROW|wx.ALL) laurent@428: else: laurent@428: sizer.AddSizer(boxsizer, 0, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM) laurent@428: staticbitmap = GenStaticBitmap(ID=-1, bitmapname="%s.png"%element_infos["name"], laurent@428: name="%s_bitmap"%element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(24, 24), style=0) laurent@428: boxsizer.AddWindow(staticbitmap, 0, border=5, flag=wx.RIGHT) laurent@428: label = element_infos["name"] laurent@428: statictext = wx.StaticText(id=-1, label="%s:"%_(label), laurent@428: name="%s_label"%element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.DefaultSize, style=0) laurent@428: boxsizer.AddWindow(statictext, 0, border=5, flag=wx.ALIGN_CENTER_VERTICAL|wx.RIGHT) laurent@428: id = wx.NewId() laurent@428: if isinstance(element_infos["type"], types.ListType): laurent@428: combobox = wx.ComboBox(id=id, name=element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(300, 28), style=wx.CB_READONLY) laurent@428: boxsizer.AddWindow(combobox, 0, border=0, flag=0) laurent@428: if element_infos["use"] == "optional": laurent@428: combobox.Append("") laurent@428: if len(element_infos["type"]) > 0 and isinstance(element_infos["type"][0], types.TupleType): laurent@428: for choice, xsdclass in element_infos["type"]: laurent@428: combobox.Append(choice) laurent@428: name = element_infos["name"] laurent@428: value = element_infos["value"] laurent@428: staticbox = wx.StaticBox(id=-1, label="%s - %s"%(_(name), _(value)), laurent@428: name='%s_staticbox'%element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(10, 0), style=0) laurent@428: staticboxsizer = wx.StaticBoxSizer(staticbox, wx.VERTICAL) laurent@428: sizer.AddSizer(staticboxsizer, 0, border=5, flag=wx.GROW|wx.BOTTOM) laurent@428: self.RefreshSizerElement(parent, staticboxsizer, plugin, element_infos["children"], element_path) laurent@428: callback = self.GetChoiceContentCallBackFunction(combobox, staticboxsizer, plugin, element_path) laurent@428: else: laurent@428: for choice in element_infos["type"]: laurent@428: combobox.Append(choice) laurent@428: callback = self.GetChoiceCallBackFunction(combobox, plugin, element_path) laurent@428: if element_infos["value"] is None: laurent@428: combobox.SetStringSelection("") laurent@428: else: laurent@428: combobox.SetStringSelection(element_infos["value"]) laurent@428: combobox.Bind(wx.EVT_COMBOBOX, callback, id=id) laurent@428: elif isinstance(element_infos["type"], types.DictType): laurent@428: scmin = -(2**31) laurent@428: scmax = 2**31-1 laurent@428: if "min" in element_infos["type"]: laurent@428: scmin = element_infos["type"]["min"] laurent@428: if "max" in element_infos["type"]: laurent@428: scmax = element_infos["type"]["max"] laurent@428: spinctrl = wx.SpinCtrl(id=id, name=element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(300, 25), style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT) laurent@428: spinctrl.SetRange(scmin,scmax) laurent@428: boxsizer.AddWindow(spinctrl, 0, border=0, flag=0) laurent@428: spinctrl.SetValue(element_infos["value"]) laurent@428: spinctrl.Bind(wx.EVT_SPINCTRL, self.GetTextCtrlCallBackFunction(spinctrl, plugin, element_path), id=id) laurent@428: else: laurent@428: if element_infos["type"] == "boolean": laurent@428: checkbox = wx.CheckBox(id=id, name=element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(17, 25), style=0) laurent@428: boxsizer.AddWindow(checkbox, 0, border=0, flag=0) laurent@428: checkbox.SetValue(element_infos["value"]) laurent@428: checkbox.Bind(wx.EVT_CHECKBOX, self.GetCheckBoxCallBackFunction(checkbox, plugin, element_path), id=id) laurent@428: elif element_infos["type"] in ["unsignedLong", "long","integer"]: laurent@428: if element_infos["type"].startswith("unsigned"): laurent@428: scmin = 0 laurent@428: else: laurent@428: scmin = -(2**31) laurent@428: scmax = 2**31-1 laurent@428: spinctrl = wx.SpinCtrl(id=id, name=element_infos["name"], parent=parent, laurent@428: pos=wx.Point(0, 0), size=wx.Size(300, 25), style=wx.SP_ARROW_KEYS|wx.ALIGN_RIGHT) laurent@428: spinctrl.SetRange(scmin, scmax) laurent@428: boxsizer.AddWindow(spinctrl, 0, border=0, flag=0) laurent@428: spinctrl.SetValue(element_infos["value"]) laurent@428: spinctrl.Bind(wx.EVT_SPINCTRL, self.GetTextCtrlCallBackFunction(spinctrl, plugin, element_path), id=id) laurent@428: else: laurent@428: choices = cPickle.loads(str(self.Config.Read(element_path, cPickle.dumps([""])))) laurent@428: textctrl = TextCtrlAutoComplete.TextCtrlAutoComplete(id=id, laurent@428: name=element_infos["name"], laurent@428: parent=parent, laurent@428: appframe=self, laurent@428: choices=choices, laurent@428: element_path=element_path, laurent@428: pos=wx.Point(0, 0), laurent@428: size=wx.Size(300, 25), laurent@428: style=0) laurent@428: laurent@428: boxsizer.AddWindow(textctrl, 0, border=0, flag=0) laurent@428: textctrl.ChangeValue(str(element_infos["value"])) laurent@428: textctrl.Bind(wx.EVT_TEXT, self.GetTextCtrlCallBackFunction(textctrl, plugin, element_path)) laurent@428: first = False laurent@428: laurent@428: def ResetView(self): laurent@428: IDEFrame.ResetView(self) laurent@428: self.PluginInfos = {} laurent@428: if self.PluginRoot is not None: laurent@428: self.PluginRoot.CloseProject() laurent@428: self.PluginRoot = None laurent@428: self.Log.flush() laurent@490: if self.EnableDebug: laurent@490: self.DebugVariablePanel.SetDataProducer(None) laurent@428: laurent@428: def OnNewProjectMenu(self, event): laurent@429: if self.PluginRoot is not None and not self.CheckSaveBeforeClosing(): laurent@429: return laurent@429: laurent@428: if not self.Config.HasEntry("lastopenedfolder"): laurent@428: defaultpath = os.path.expanduser("~") laurent@428: else: laurent@428: defaultpath = self.Config.Read("lastopenedfolder") laurent@428: laurent@428: dialog = wx.DirDialog(self , _("Choose a project"), defaultpath, wx.DD_NEW_DIR_BUTTON) laurent@428: if dialog.ShowModal() == wx.ID_OK: laurent@428: projectpath = dialog.GetPath() laurent@428: dialog.Destroy() laurent@428: self.Config.Write("lastopenedfolder", os.path.dirname(projectpath)) laurent@428: self.Config.Flush() laurent@428: self.ResetView() laurent@428: self.PluginRoot = PluginsRoot(self, self.Log) laurent@428: self.Controler = self.PluginRoot laurent@428: result = self.PluginRoot.NewProject(projectpath) laurent@428: if not result: laurent@490: if self.EnableDebug: laurent@490: self.DebugVariablePanel.SetDataProducer(self.PluginRoot) laurent@428: self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE) laurent@428: self.RefreshAll() laurent@428: else: laurent@428: self.ResetView() laurent@428: self.ShowErrorMessage(result) laurent@428: self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU) laurent@428: laurent@428: def OnOpenProjectMenu(self, event): laurent@429: if self.PluginRoot is not None and not self.CheckSaveBeforeClosing(): laurent@429: return laurent@429: laurent@428: if not self.Config.HasEntry("lastopenedfolder"): laurent@428: defaultpath = os.path.expanduser("~") laurent@428: else: laurent@428: defaultpath = self.Config.Read("lastopenedfolder") laurent@428: laurent@428: dialog = wx.DirDialog(self , _("Choose a project"), defaultpath, wx.DD_NEW_DIR_BUTTON) laurent@428: if dialog.ShowModal() == wx.ID_OK: laurent@428: projectpath = dialog.GetPath() laurent@428: if os.path.isdir(projectpath): laurent@428: self.Config.Write("lastopenedfolder", os.path.dirname(projectpath)) laurent@428: self.Config.Flush() laurent@428: self.ResetView() laurent@428: self.PluginRoot = PluginsRoot(self, self.Log) laurent@428: self.Controler = self.PluginRoot laurent@428: result = self.PluginRoot.LoadProject(projectpath) laurent@428: if not result: laurent@490: if self.EnableDebug: laurent@490: self.DebugVariablePanel.SetDataProducer(self.PluginRoot) laurent@428: self._Refresh(TYPESTREE, INSTANCESTREE, LIBRARYTREE) laurent@428: self.RefreshAll() laurent@428: else: laurent@428: self.ResetView() laurent@428: self.ShowErrorMessage(result) laurent@428: else: laurent@428: self.ShowErrorMessage(_("\"%s\" folder is not a valid Beremiz project\n") % projectpath) laurent@428: self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU) laurent@428: dialog.Destroy() laurent@428: laurent@428: def OnCloseProjectMenu(self, event): laurent@429: if self.PluginRoot is not None and not self.CheckSaveBeforeClosing(): laurent@429: return laurent@429: laurent@429: self.ResetView() laurent@429: self._Refresh(TITLE, TOOLBAR, FILEMENU, EDITMENU) laurent@429: self.RefreshAll() laurent@428: laurent@428: def OnSaveProjectMenu(self, event): laurent@428: if self.PluginRoot is not None: laurent@428: self.PluginRoot.SaveProject() laurent@428: self.RefreshAll() laurent@509: self._Refresh(TITLE, FILEMENU) laurent@428: laurent@428: def OnSaveProjectAsMenu(self, event): laurent@428: if self.PluginRoot is not None: laurent@428: self.PluginRoot.SaveProjectAs() laurent@428: self.RefreshAll() laurent@509: self._Refresh(TITLE, FILEMENU) laurent@428: event.Skip() laurent@428: laurent@428: def OnPropertiesMenu(self, event): laurent@428: self.ShowProperties() laurent@428: laurent@428: def OnQuitMenu(self, event): laurent@428: self.Close() laurent@428: laurent@428: def OnBeremizMenu(self, event): laurent@428: open_pdf(Bpath( "doc", "manual_beremiz.pdf")) laurent@428: laurent@428: def OnAboutMenu(self, event): laurent@428: OpenHtmlFrame(self,_("About Beremiz"), Bpath("doc","about.html"), wx.Size(550, 500)) laurent@428: laurent@428: def GetAddButtonFunction(self, plugin, window): laurent@428: def AddButtonFunction(event): laurent@428: if plugin and len(plugin.PlugChildsTypes) > 0: laurent@428: plugin_menu = wx.Menu(title='') laurent@428: for name, XSDClass, help in plugin.PlugChildsTypes: laurent@428: new_id = wx.NewId() laurent@428: plugin_menu.Append(help=help, id=new_id, kind=wx.ITEM_NORMAL, text=name) laurent@428: self.Bind(wx.EVT_MENU, self._GetAddPluginFunction(name, plugin), id=new_id) laurent@428: window_pos = window.GetPosition() laurent@428: wx.CallAfter(self.PLCConfig.PopupMenu, plugin_menu) laurent@428: event.Skip() laurent@428: return AddButtonFunction laurent@428: laurent@428: def GetDeleteButtonFunction(self, plugin): laurent@428: def DeleteButtonFunction(event): laurent@428: wx.CallAfter(self.DeletePlugin, plugin) laurent@428: event.Skip() laurent@428: return DeleteButtonFunction laurent@428: laurent@428: def AddPlugin(self, PluginType, plugin): laurent@428: if self.PluginRoot.CheckProjectPathPerm(): laurent@428: dialog = wx.TextEntryDialog(self, _("Please enter a name for plugin:"), _("Add Plugin"), "", wx.OK|wx.CANCEL) laurent@428: if dialog.ShowModal() == wx.ID_OK: laurent@428: PluginName = dialog.GetValue() laurent@428: plugin.PlugAddChild(PluginName, PluginType) laurent@505: self.PluginRoot.RefreshPluginsBlockLists() laurent@505: self.RefreshFileMenu() laurent@428: self.RefreshPluginTree() laurent@428: dialog.Destroy() laurent@428: laurent@428: def DeletePlugin(self, plugin): laurent@428: if self.PluginRoot.CheckProjectPathPerm(): laurent@428: dialog = wx.MessageDialog(self, _("Really delete plugin ?"), _("Remove plugin"), wx.YES_NO|wx.NO_DEFAULT) laurent@428: if dialog.ShowModal() == wx.ID_YES: laurent@428: self.PluginInfos.pop(plugin) laurent@428: plugin.PlugRemove() laurent@428: del plugin laurent@428: self.PluginRoot.RefreshPluginsBlockLists() laurent@505: self.RefreshFileMenu() laurent@428: self.RefreshPluginTree() laurent@428: dialog.Destroy() laurent@428: laurent@428: #------------------------------------------------------------------------------- laurent@428: # Exception Handler laurent@428: #------------------------------------------------------------------------------- laurent@428: laurent@428: Max_Traceback_List_Size = 20 laurent@428: laurent@428: def Display_Exception_Dialog(e_type, e_value, e_tb, bug_report_path): laurent@428: trcbck_lst = [] laurent@428: for i,line in enumerate(traceback.extract_tb(e_tb)): laurent@428: trcbck = " " + str(i+1) + _(". ") laurent@428: if line[0].find(os.getcwd()) == -1: laurent@428: trcbck += _("file : ") + str(line[0]) + _(", ") laurent@428: else: laurent@428: trcbck += _("file : ") + str(line[0][len(os.getcwd()):]) + _(", ") laurent@428: trcbck += _("line : ") + str(line[1]) + _(", ") + _("function : ") + str(line[2]) laurent@428: trcbck_lst.append(trcbck) laurent@428: laurent@428: # Allow clicking.... laurent@428: cap = wx.Window_GetCapture() laurent@428: if cap: laurent@428: cap.ReleaseMouse() laurent@428: laurent@428: dlg = wx.SingleChoiceDialog(None, laurent@428: _(""" laurent@428: An unhandled exception (bug) occured. Bug report saved at : laurent@428: (%s) laurent@428: greg@434: Please be kind enough to send this file to: greg@434: edouard.tisserant@gmail.com laurent@428: laurent@428: You should now restart Beremiz. laurent@428: laurent@428: Traceback: laurent@428: """) % bug_report_path + laurent@428: str(e_type) + " : " + str(e_value), laurent@428: _("Error"), laurent@428: trcbck_lst) laurent@428: try: laurent@428: res = (dlg.ShowModal() == wx.ID_OK) laurent@428: finally: laurent@428: dlg.Destroy() laurent@428: laurent@428: return res laurent@428: laurent@428: def Display_Error_Dialog(e_value): laurent@428: message = wxMessageDialog(None, str(e_value), _("Error"), wxOK|wxICON_ERROR) laurent@428: message.ShowModal() laurent@428: message.Destroy() laurent@428: laurent@428: def get_last_traceback(tb): laurent@428: while tb.tb_next: laurent@428: tb = tb.tb_next laurent@428: return tb laurent@428: laurent@428: laurent@428: def format_namespace(d, indent=' '): laurent@428: return '\n'.join(['%s%s: %s' % (indent, k, repr(v)[:10000]) for k, v in d.iteritems()]) laurent@428: laurent@428: laurent@428: ignored_exceptions = [] # a problem with a line in a module is only reported once per session laurent@428: laurent@428: def AddExceptHook(path, app_version='[No version]'):#, ignored_exceptions=[]): laurent@428: laurent@428: def handle_exception(e_type, e_value, e_traceback): laurent@428: traceback.print_exception(e_type, e_value, e_traceback) # this is very helpful when there's an exception in the rest of this func laurent@428: last_tb = get_last_traceback(e_traceback) laurent@428: ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno) laurent@428: if str(e_value).startswith("!!!"): laurent@428: Display_Error_Dialog(e_value) laurent@428: elif ex not in ignored_exceptions: laurent@428: date = time.ctime() laurent@428: bug_report_path = path+os.sep+"bug_report_"+date.replace(':','-').replace(' ','_')+".txt" laurent@428: result = Display_Exception_Dialog(e_type,e_value,e_traceback,bug_report_path) laurent@428: if result: laurent@428: ignored_exceptions.append(ex) laurent@428: info = { laurent@428: 'app-title' : wx.GetApp().GetAppName(), # app_title laurent@428: 'app-version' : app_version, laurent@428: 'wx-version' : wx.VERSION_STRING, laurent@428: 'wx-platform' : wx.Platform, laurent@428: 'python-version' : platform.python_version(), #sys.version.split()[0], laurent@428: 'platform' : platform.platform(), laurent@428: 'e-type' : e_type, laurent@428: 'e-value' : e_value, laurent@428: 'date' : date, laurent@428: 'cwd' : os.getcwd(), laurent@428: } laurent@428: if e_traceback: laurent@428: info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value) laurent@428: last_tb = get_last_traceback(e_traceback) laurent@428: exception_locals = last_tb.tb_frame.f_locals # the locals at the level of the stack trace where the exception actually occurred laurent@428: info['locals'] = format_namespace(exception_locals) laurent@428: if 'self' in exception_locals: laurent@428: info['self'] = format_namespace(exception_locals['self'].__dict__) laurent@428: laurent@428: output = open(bug_report_path,'w') laurent@428: lst = info.keys() laurent@428: lst.sort() laurent@428: for a in lst: laurent@428: output.write(a+":\n"+str(info[a])+"\n\n") laurent@428: laurent@428: #sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args) laurent@428: sys.excepthook = handle_exception laurent@428: laurent@428: if __name__ == '__main__': laurent@428: # Install a exception handle for bug reports laurent@428: AddExceptHook(os.getcwd(),__version__) laurent@428: laurent@428: frame = Beremiz(None, projectOpen, buildpath) laurent@428: frame.Show() laurent@428: splash.Close() laurent@428: app.MainLoop()