PLCOpenEditor.py
author etisserant
Tue, 19 Aug 2008 18:06:41 +0200
changeset 233 de7ddb376150
parent 231 fc2d6cbb8b39
child 235 7b58a3b5b6ec
permissions -rw-r--r--
Now generated global variable declaration is done in one separate block. Also "fixed" (masked?) problem when deleting blocks with invalid type
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#This file is part of PLCOpenEditor, a library implementing an IEC 61131-3 editor
#based on the plcopen standard. 
#
#Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD
#
#See COPYING file for copyrights details.
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#General Public License for more details.
#
#You should have received a copy of the GNU General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from datetime import datetime
import wx, wx.grid

if wx.VERSION >= (2, 8, 0):
    import wx.aui

from SFCViewer import *
from LDViewer import *
from Viewer import *
from TextViewer import *
from RessourceEditor import *
from DataTypeEditor import *
from PLCControler import *
from plcopen.structures import LOCATIONDATATYPES

import os, re, platform, sys, time, traceback, getopt

base_folder = os.path.split(sys.path[0])[0]
sys.path.append(base_folder)
from docutils import *

from types import TupleType

__version__ = "$Revision$"

CWD = os.path.split(os.path.realpath(__file__))[0]

[ID_PLCOPENEDITOR, ID_PLCOPENEDITORPROJECTTREE, 
 ID_PLCOPENEDITORMAINSPLITTER, ID_PLCOPENEDITORSECONDSPLITTER, 
 ID_PLCOPENEDITOREDITORPANEL, ID_PLCOPENEDITORTABSOPENED, 
 ID_PLCOPENEDITORTOOLBAR, ID_PLCOPENEDITORDEFAULTTOOLBAR, 
 ID_PLCOPENEDITORSFCTOOLBAR, ID_PLCOPENEDITORFBDTOOLBAR, 
 ID_PLCOPENEDITORLDTOOLBAR,
] = [wx.NewId() for _init_ctrls in range(11)]

[ID_PLCOPENEDITORFILEMENUGENERATE, 
] = [wx.NewId() for _init_coll_FileMenu_Items in range(1)]

[ID_PLCOPENEDITOREDITMENUADDDATATYPE, ID_PLCOPENEDITOREDITMENUADDFUNCTION,
 ID_PLCOPENEDITOREDITMENUADDFUNCTIONBLOCK, ID_PLCOPENEDITOREDITMENUADDPROGRAM,
 ID_PLCOPENEDITOREDITMENUADDCONFIGURATION, 
] = [wx.NewId() for _init_coll_EditMenu_Items in range(5)]


#-------------------------------------------------------------------------------
#                            ToolBars definitions
#-------------------------------------------------------------------------------


[ID_PLCOPENEDITORTOOLBARSELECTION, ID_PLCOPENEDITORTOOLBARCOMMENT,
 ID_PLCOPENEDITORTOOLBARVARIABLE, ID_PLCOPENEDITORTOOLBARBLOCK,
 ID_PLCOPENEDITORTOOLBARCONNECTION, ID_PLCOPENEDITORTOOLBARWIRE,
 ID_PLCOPENEDITORTOOLBARPOWERRAIL, ID_PLCOPENEDITORTOOLBARRUNG,
 ID_PLCOPENEDITORTOOLBARCOIL, ID_PLCOPENEDITORTOOLBARCONTACT,
 ID_PLCOPENEDITORTOOLBARBRANCH, ID_PLCOPENEDITORTOOLBARINITIALSTEP,
 ID_PLCOPENEDITORTOOLBARSTEP, ID_PLCOPENEDITORTOOLBARTRANSITION,
 ID_PLCOPENEDITORTOOLBARACTIONBLOCK, ID_PLCOPENEDITORTOOLBARDIVERGENCE,
 ID_PLCOPENEDITORTOOLBARJUMP,
] = [wx.NewId() for _init_coll_DefaultToolBar_Items in range(17)]

ToolBarItems = {
    "FBD" : [(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
              ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool",
              "add_comment.png", "Create a new comment"),
             (True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
              ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool",
              "add_variable.png", "Create a new variable"),
             (True, FREEDRAWING_MODE|DRIVENDRAWING_MODE,
              ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool",
              "add_block.png", "Create a new block"),
             (True, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool", 
              "add_connection.png", "Create a new connection")],
    "LD"  : [(True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool", 
              "add_comment.png", "Create a new comment"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARPOWERRAIL, "OnPowerRailTool", 
              "add_powerrail.png", "Create a new power rail"),
             (False, DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARRUNG, "OnRungTool", 
              "add_rung.png", "Create a new rung"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCOIL, "OnCoilTool", 
              "add_coil.png", "Create a new coil"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCONTACT, "OnContactTool", 
              "add_contact.png", "Create a new contact"),
             (False, DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARBRANCH, "OnBranchTool", 
              "add_branch.png", "Create a new branch"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool", 
              "add_variable.png", "Create a new variable"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool", 
              "add_block.png", "Create a new block"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool", 
              "add_connection.png", "Create a new connection")],
    "SFC" : [(True, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCOMMENT, "OnCommentTool", 
              "add_comment.png", "Create a new comment"),
             (True, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARINITIALSTEP, "OnInitialStepTool", 
              "add_initial_step.png", "Create a new initial step"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARSTEP, "OnStepTool", 
              "add_step.png", "Create a new step"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARTRANSITION, "OnTransitionTool", 
              "add_transition.png", "Create a new transition"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARACTIONBLOCK, "OnActionBlockTool", 
              "add_action.png", "Create a new action block"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARDIVERGENCE, "OnDivergenceTool", 
              "add_divergence.png", "Create a new divergence"),
             (False, FREEDRAWING_MODE|DRIVENDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARJUMP, "OnJumpTool", 
              "add_jump.png", "Create a new jump"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARVARIABLE, "OnVariableTool", 
              "add_variable.png", "Create a new variable"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARBLOCK, "OnBlockTool", 
              "add_block.png", "Create a new block"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCONNECTION, "OnConnectionTool", 
              "add_connection.png", "Create a new connection"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARPOWERRAIL, "OnPowerRailTool", 
              "add_powerrail.png", "Create a new power rail"),
             (True, FREEDRAWING_MODE, 
              ID_PLCOPENEDITORTOOLBARCONTACT, "OnContactTool", 
              "add_contact.png", "Create a new contact")],
    "ST"  : [],
    "IL"  : []
}

def GenerateBitmap(icon1_name, icon2_name = None):
    if icon2_name is None:
        return wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon1_name))
    else:
        icon1 = wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon1_name))
        icon2 = wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%icon2_name))
        width = icon1.GetWidth() + icon2.GetWidth() - 1
        height = max(icon1.GetHeight(), icon2.GetHeight())
        tmp_bitmap = wx.EmptyBitmap(width, height)
        dc = wx.MemoryDC()
        dc.SelectObject(tmp_bitmap)
        dc.Clear()
        dc.DrawBitmap(icon1, 0, 0)
        dc.DrawBitmap(icon2, icon1.GetWidth() - 1, 0)
        return tmp_bitmap

def AppendMenu(parent, help, id, kind, text):
    if wx.VERSION >= (2, 6, 0):
        parent.Append(help=help, id=id, kind=kind, text=text)
    else:
        parent.Append(helpString=help, id=id, kind=kind, item=text)

if wx.VERSION >= (2, 8, 0):
    base_class = wx.aui.AuiMDIParentFrame
else:
    base_class = wx.Frame

class PLCOpenEditor(base_class):
    
    CopyBuffer = None
    
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_MenuBar_Menus(self, parent):
        parent.Append(menu=self.FileMenu, title=u'File')
        parent.Append(menu=self.EditMenu, title=u'Edit')
        parent.Append(menu=self.HelpMenu, title=u'Help')

    def _init_coll_FileMenu_Items(self, parent):
        if self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_NEW,
                  kind=wx.ITEM_NORMAL, text=u'New\tCTRL+N')
            AppendMenu(parent, help='', id=wx.ID_OPEN,
                  kind=wx.ITEM_NORMAL, text=u'Open\tCTRL+O')
        AppendMenu(parent, help='', id=wx.ID_CLOSE,
              kind=wx.ITEM_NORMAL, text=u'Close Tab\tCTRL+W')
        if self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_CLOSE_ALL,
                  kind=wx.ITEM_NORMAL, text=u'Close Project')
            parent.AppendSeparator()
        AppendMenu(parent, help='', id=wx.ID_SAVE,
              kind=wx.ITEM_NORMAL, text=u'Save\tCTRL+S')
        if self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_SAVEAS,
                  kind=wx.ITEM_NORMAL, text=u'Save As...\tCTRL+SHIFT+S')
            AppendMenu(parent, help='', id=ID_PLCOPENEDITORFILEMENUGENERATE,
                  kind=wx.ITEM_NORMAL, text=u'Generate Program\tCTRL+G')
            parent.AppendSeparator()
        AppendMenu(parent, help='', id=wx.ID_PAGE_SETUP,
              kind=wx.ITEM_NORMAL, text=u'Page Setup')
        AppendMenu(parent, help='', id=wx.ID_PREVIEW,
              kind=wx.ITEM_NORMAL, text=u'Preview')
        AppendMenu(parent, help='', id=wx.ID_PRINT,
              kind=wx.ITEM_NORMAL, text=u'Print')
        parent.AppendSeparator()
        AppendMenu(parent, help='', id=wx.ID_PROPERTIES,
              kind=wx.ITEM_NORMAL, text=u'Properties')
        parent.AppendSeparator()
        if self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_EXIT,
                  kind=wx.ITEM_NORMAL, text=u'Quit\tCTRL+Q')
        else:
            AppendMenu(parent, help='', id=wx.ID_CLOSE_ALL,
                  kind=wx.ITEM_NORMAL, text=u'Close\tCTRL+Q')
        
        if self.ModeSolo:
            self.Bind(wx.EVT_MENU, self.OnNewProjectMenu, id=wx.ID_NEW)
            self.Bind(wx.EVT_MENU, self.OnOpenProjectMenu, id=wx.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.OnCloseTabMenu, id=wx.ID_CLOSE)
        if self.ModeSolo:
            self.Bind(wx.EVT_MENU, self.OnCloseProjectMenu, id=wx.ID_CLOSE_ALL)
        self.Bind(wx.EVT_MENU, self.OnSaveProjectMenu, id=wx.ID_SAVE)
        if self.ModeSolo:
            self.Bind(wx.EVT_MENU, self.OnSaveProjectAsMenu, id=wx.ID_SAVEAS)
            self.Bind(wx.EVT_MENU, self.OnGenerateProgramMenu,
                  id=ID_PLCOPENEDITORFILEMENUGENERATE)
        self.Bind(wx.EVT_MENU, self.OnPageSetupMenu, id=wx.ID_PAGE_SETUP)
        self.Bind(wx.EVT_MENU, self.OnPreviewMenu, id=wx.ID_PREVIEW)
        self.Bind(wx.EVT_MENU, self.OnPrintMenu, id=wx.ID_PRINT)
        self.Bind(wx.EVT_MENU, self.OnPropertiesMenu, id=wx.ID_PROPERTIES)
        if self.ModeSolo:
            self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_EXIT)
        else:
            self.Bind(wx.EVT_MENU, self.OnQuitMenu, id=wx.ID_CLOSE_ALL)
    
    def _init_coll_EditMenu_Items(self, parent):
        AppendMenu(parent, help='', id=wx.ID_REFRESH,
              kind=wx.ITEM_NORMAL, text=u'Refresh\tCTRL+R')
        if not self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_CLEAR,
                  kind=wx.ITEM_NORMAL, text=u'Clear Errors\tCTRL+K')
        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')
        parent.AppendSeparator()
        AppendMenu(parent, help='', id=wx.ID_CUT,
              kind=wx.ITEM_NORMAL, text=u'Cut\tCTRL+X')
        AppendMenu(parent, help='', id=wx.ID_COPY,
              kind=wx.ITEM_NORMAL, text=u'Copy\tCTRL+C')
        AppendMenu(parent, help='', id=wx.ID_PASTE,
              kind=wx.ITEM_NORMAL, text=u'Paste\tCTRL+V')
        parent.AppendSeparator()
        addmenu = wx.Menu(title='')
        parent.AppendMenu(wx.ID_ADD, "Add Element", addmenu)
        AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDDATATYPE,
              kind=wx.ITEM_NORMAL, text=u'Data Type')
        AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDFUNCTION,
              kind=wx.ITEM_NORMAL, text=u'Function')
        AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDFUNCTIONBLOCK,
              kind=wx.ITEM_NORMAL, text=u'Function Block')
        AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDPROGRAM,
              kind=wx.ITEM_NORMAL, text=u'Program')
        AppendMenu(addmenu, help='', id=ID_PLCOPENEDITOREDITMENUADDCONFIGURATION,
              kind=wx.ITEM_NORMAL, text=u'Configuration')
        AppendMenu(parent, help='', id=wx.ID_DELETE,
              kind=wx.ITEM_NORMAL, text=u'Delete')
        self.Bind(wx.EVT_MENU, self.OnRefreshMenu, id=wx.ID_REFRESH)
        if not self.ModeSolo:
            self.Bind(wx.EVT_MENU, self.OnClearErrorsMenu, id=wx.ID_CLEAR)
        self.Bind(wx.EVT_MENU, self.OnUndoMenu, id=wx.ID_UNDO)
        self.Bind(wx.EVT_MENU, self.OnRedoMenu, id=wx.ID_REDO)
        self.Bind(wx.EVT_MENU, self.OnCutMenu, id=wx.ID_CUT)
        self.Bind(wx.EVT_MENU, self.OnCopyMenu, id=wx.ID_COPY)
        self.Bind(wx.EVT_MENU, self.OnPasteMenu, id=wx.ID_PASTE)
        self.Bind(wx.EVT_MENU, self.OnAddDataTypeMenu,
              id=ID_PLCOPENEDITOREDITMENUADDDATATYPE)
        self.Bind(wx.EVT_MENU, self.GenerateAddPouFunction("function"),
              id=ID_PLCOPENEDITOREDITMENUADDFUNCTION)
        self.Bind(wx.EVT_MENU, self.GenerateAddPouFunction("functionBlock"),
              id=ID_PLCOPENEDITOREDITMENUADDFUNCTIONBLOCK)
        self.Bind(wx.EVT_MENU, self.GenerateAddPouFunction("program"),
              id=ID_PLCOPENEDITOREDITMENUADDPROGRAM)
        self.Bind(wx.EVT_MENU, self.OnAddConfigurationMenu,
              id=ID_PLCOPENEDITOREDITMENUADDCONFIGURATION)
        self.Bind(wx.EVT_MENU, self.OnDeleteMenu, id=wx.ID_DELETE)

    def _init_coll_HelpMenu_Items(self, parent):
        AppendMenu(parent, help='', id=wx.ID_HELP, 
            kind=wx.ITEM_NORMAL, text=u'PLCOpenEditor\tF1')
        #AppendMenu(parent, help='', id=wx.ID_HELP_CONTENTS,
        #      kind=wx.ITEM_NORMAL, text=u'PLCOpen\tF2')
        #AppendMenu(parent, help='', id=wx.ID_HELP_CONTEXT,
        #      kind=wx.ITEM_NORMAL, text=u'IEC 61131-3\tF3')
        if self.ModeSolo:
            AppendMenu(parent, help='', id=wx.ID_ABOUT,
                  kind=wx.ITEM_NORMAL, text=u'About')
        self.Bind(wx.EVT_MENU, self.OnPLCOpenEditorMenu, id=wx.ID_HELP)
        #self.Bind(wx.EVT_MENU, self.OnPLCOpenMenu, id=wx.ID_HELP_CONTENTS)
        self.Bind(wx.EVT_MENU, self.OnAboutMenu, id=wx.ID_ABOUT)

    def _init_utils(self):
        self.MenuBar = wx.MenuBar()

        self.FileMenu = wx.Menu(title='')
        self.EditMenu = wx.Menu(title='')
        self.HelpMenu = wx.Menu(title='')
        
        self._init_coll_MenuBar_Menus(self.MenuBar)
        self._init_coll_FileMenu_Items(self.FileMenu)
        self._init_coll_EditMenu_Items(self.EditMenu)
        self._init_coll_HelpMenu_Items(self.HelpMenu)
        
    def _init_ctrls(self, prnt):
        if wx.VERSION >= (2, 8, 0):
            wx.aui.AuiMDIParentFrame.__init__(self, winid=ID_PLCOPENEDITOR, name=u'PLCOpenEditor', 
                  parent=prnt, pos=wx.DefaultPosition, size=wx.Size(1000, 600),
                  style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN, title=u'PLCOpenEditor')
        else:
            wx.Frame.__init__(self, id=ID_PLCOPENEDITOR, name=u'PLCOpenEditor',
                  parent=prnt, pos=wx.DefaultPosition, size=wx.Size(1000, 600),
                  style=wx.DEFAULT_FRAME_STYLE, title=u'PLCOpenEditor')
        self._init_utils()
        self.SetClientSize(wx.Size(1000, 600))
        self.SetMenuBar(self.MenuBar)
        self.Bind(wx.EVT_CLOSE, self.OnCloseFrame)
        
        if wx.VERSION >= (2, 8, 0):
            self.AUIManager = wx.aui.AuiManager(self)
            self.AUIManager.SetDockSizeConstraint(0.5, 0.5)
            self.Panes = {}
        
        if wx.VERSION < (2, 8, 0):
            self.MainSplitter = wx.SplitterWindow(id=ID_PLCOPENEDITORMAINSPLITTER,
                  name='MainSplitter', parent=self, point=wx.Point(0, 0),
                  size=wx.Size(0, 0), style=wx.SP_3D)
            self.MainSplitter.SetNeedUpdating(True)
            self.MainSplitter.SetMinimumPaneSize(1)
            
            self.ProjectTree = wx.TreeCtrl(id=ID_PLCOPENEDITORPROJECTTREE,
                  name='treeCtrl1', parent=self.MainSplitter, pos=wx.Point(0, 0),
                  size=wx.Size(-1, -1),
                  style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS|wx.TR_SINGLE|wx.SUNKEN_BORDER)
        else:
            self.ProjectTree = wx.TreeCtrl(id=ID_PLCOPENEDITORPROJECTTREE,
                  name='treeCtrl1', parent=self, pos=wx.Point(0, 0),
                  size=wx.Size(200, -1),
                  style=wx.TR_HAS_BUTTONS|wx.TR_EDIT_LABELS|wx.TR_SINGLE|wx.SUNKEN_BORDER)
            self.AUIManager.AddPane(self.ProjectTree, wx.aui.AuiPaneInfo().Caption("Project Tree").Left().Layer(1).BestSize(wx.Size(200, 500)).CloseButton(False))
        if wx.Platform == '__WXMSW__':
            self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnProjectTreeRightUp,
                  id=ID_PLCOPENEDITORPROJECTTREE)
            self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnProjectTreeItemSelected,
                  id=ID_PLCOPENEDITORPROJECTTREE)
        else:
            if wx.VERSION >= (2, 6, 0):
                self.ProjectTree.Bind(wx.EVT_RIGHT_UP, self.OnProjectTreeRightUp)
                self.ProjectTree.Bind(wx.EVT_LEFT_UP, self.OnProjectTreeLeftUp)
            else:
                wx.EVT_RIGHT_UP(self.ProjectTree, self.OnProjectTreeRightUp)
                wx.EVT_LEFT_UP(self.ProjectTree, self.OnProjectTreeLeftUp)
            self.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnProjectTreeItemChanging,
                  id=ID_PLCOPENEDITORPROJECTTREE)
        self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnProjectTreeBeginDrag,
              id=ID_PLCOPENEDITORPROJECTTREE)
        self.Bind(wx.EVT_TREE_BEGIN_LABEL_EDIT, self.OnProjectTreeItemBeginEdit,
              id=ID_PLCOPENEDITORPROJECTTREE)
        self.Bind(wx.EVT_TREE_END_LABEL_EDIT, self.OnProjectTreeItemEndEdit,
              id=ID_PLCOPENEDITORPROJECTTREE)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnProjectTreeItemActivated,
              id=ID_PLCOPENEDITORPROJECTTREE)
        
        if wx.VERSION < (2, 8, 0):
            self.ToolBar = self.CreateToolBar(wx.TB_HORIZONTAL|wx.TB_FLAT|wx.NO_BORDER, 
                  ID_PLCOPENEDITORTOOLBAR, 'ToolBar')
            self.ToolBar.SetToolBitmapSize(wx.Size(25, 25))
            self.ToolBar.AddRadioTool(ID_PLCOPENEDITORTOOLBARSELECTION, 
                  wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, "Select an object")
            self.ToolBar.Realize()
        else:
            ToolBar = wx.ToolBar(self, ID_PLCOPENEDITORTOOLBAR, wx.DefaultPosition, wx.DefaultSize,
                    wx.TB_FLAT | wx.TB_NODIVIDER | wx.NO_BORDER)
            ToolBar.SetToolBitmapSize(wx.Size(25, 25))
            ToolBar.AddRadioTool(ID_PLCOPENEDITORTOOLBARSELECTION, 
                  wx.Bitmap(os.path.join(CWD, 'Images', 'select.png')), wx.NullBitmap, "Select an object")
            ToolBar.Realize()
            self.Panes["ToolBar"] = ToolBar
            self.AUIManager.AddPane(ToolBar, wx.aui.AuiPaneInfo().
                      Name("ToolBar").Caption("Toolbar").
                      ToolbarPane().Top().
                      LeftDockable(False).RightDockable(False))
        
        self.Bind(wx.EVT_TOOL, self.OnSelectionTool, 
              id=ID_PLCOPENEDITORTOOLBARSELECTION)
            
        if wx.VERSION < (2, 8, 0):
            self.SecondSplitter = wx.SplitterWindow(id=ID_PLCOPENEDITORSECONDSPLITTER,
                  name='SecondSplitter', parent=self.MainSplitter, point=wx.Point(0, 0),
                  size=wx.Size(0, 0), style=wx.SP_3D)
            self.SecondSplitter.SetMinimumPaneSize(1)
            
            self.MainSplitter.SplitVertically(self.ProjectTree, self.SecondSplitter, 200)
            
            self.TabsOpened = wx.Notebook(id=ID_PLCOPENEDITORTABSOPENED,
                  name='TabsOpened', parent=self.SecondSplitter, pos=wx.Point(0,
                  0), size=wx.Size(0, 0), style=0)
            if wx.VERSION >= (2, 6, 0):
                self.TabsOpened.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
                    self.OnPouSelectedChanged, id=ID_PLCOPENEDITORTABSOPENED)
            else:
                wx.EVT_NOTEBOOK_PAGE_CHANGED(self.TabsOpened, ID_PLCOPENEDITORTABSOPENED,
                    self.OnPouSelectedChanged)
        
        if wx.VERSION < (2, 8, 0):
            self.VariablePanelIndexer = VariablePanelIndexer(self.SecondSplitter, self, self.Controler)
            
            self.SecondSplitter.SplitHorizontally(self.TabsOpened, self.VariablePanelIndexer, -200)
        else:
            self.VariablePanelIndexer = VariablePanelIndexer(self, self, self.Controler)
            self.AUIManager.AddPane(self.VariablePanelIndexer, wx.aui.AuiPaneInfo().Caption("Variable Panel").Bottom().Layer(0).BestSize(wx.Size(800, 200)).CloseButton(False))
            
            self.AUIManager.Update()
        
    def __init__(self, parent, controler = None, fileOpen = None):
        self.ModeSolo = controler == None
        if self.ModeSolo:
            self.Controler = PLCControler()
            if fileOpen is not None:
                self.Controler.OpenXMLFile(fileOpen)
        else:
            self.Controler = controler
        
        self._init_ctrls(parent)
        
        self.SetIcon(wx.Icon(os.path.join(CWD,"Images","poe.ico"),wx.BITMAP_TYPE_ICO))
        
        self.TreeImageList = wx.ImageList(16, 16)
        self.TreeImageDict = {}
        for language in LANGUAGES:
            self.TreeImageDict[language]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%language)))
        
        for imgname, itemtype in [
            #editables
            ("PROJECT",        ITEM_PROJECT),
            #("POU",            ITEM_POU),
            #("VARIABLE",       ITEM_VARIABLE),
            ("TRANSITION",     ITEM_TRANSITION),
            ("ACTION",         ITEM_ACTION),
            ("CONFIGURATION",  ITEM_CONFIGURATION),
            ("RESOURCE",       ITEM_RESOURCE),
            ("DATATYPE",       ITEM_DATATYPE),
            # uneditables
            ("DATATYPES",      ITEM_DATATYPES),
            ("FUNCTION",       ITEM_FUNCTION),
            ("FUNCTIONBLOCK",  ITEM_FUNCTIONBLOCK),
            ("PROGRAM",        ITEM_PROGRAM),
            ("TRANSITIONS",    ITEM_TRANSITIONS),
            ("ACTIONS",        ITEM_ACTIONS),
            ("CONFIGURATIONS", ITEM_CONFIGURATIONS),
            ("RESOURCES",      ITEM_RESOURCES),
            ("PROPERTIES",     ITEM_PROPERTIES)]:
            self.TreeImageDict[itemtype]=self.TreeImageList.Add(wx.Bitmap(os.path.join(CWD, 'Images', '%s.png'%imgname)))
        self.ProjectTree.AssignImageList(self.TreeImageList)
        
        self.CurrentToolBar = []
        self.CurrentLanguage = ""
        self.SelectedItem = None
        self.Errors = []
        self.DrawingMode = FREEDRAWING_MODE
        #self.DrawingMode = DRIVENDRAWING_MODE
        
        self.PrintData = wx.PrintData()
        self.PrintData.SetPaperId(wx.PAPER_A4)
        self.PrintData.SetPrintMode(wx.PRINT_MODE_PRINTER)
        self.PageSetupData = wx.PageSetupDialogData(self.PrintData)
        self.PageSetupData.SetMarginTopLeft(wx.Point(10, 15))
        self.PageSetupData.SetMarginBottomRight(wx.Point(10, 20))
        
        if not self.ModeSolo or fileOpen is not None:
            self.RefreshProjectTree()
        
        self.RefreshFileMenu()
        self.RefreshEditMenu()
        self.RefreshTitle()
        self.RefreshToolBar()

    def ResetSelectedItem(self):
        self.SelectedItem = None

    def OnPageClose(self, event):
        selected = self.GetPageSelection()
        if selected >= 0:
            tagname = self.GetPage(selected).GetTagName()
            self.VariablePanelIndexer.RemoveVariablePanel(tagname)
            if self.GetPageCount() > 0:
                new_index = min(selected, self.GetPageCount() - 1)
                tagname = self.GetPage(new_index).GetTagName()
                self.SetPageSelection(new_index)
                self.VariablePanelIndexer.ChangeVariablePanel(tagname)
            self.RefreshTitle()
            self.RefreshFileMenu()
            self.RefreshEditMenu()
            self.RefreshToolBar()
        event.Skip()

    def GetCopyBuffer(self):
        return PLCOpenEditor.CopyBuffer
    
    def SetCopyBuffer(self, element):
        PLCOpenEditor.CopyBuffer = element
        self.RefreshEditMenu()

    def GetDrawingMode(self):
        return self.DrawingMode

    def RefreshTitle(self):
        if self.Controler.HasOpenedProject() > 0:
            self.SetTitle("PLCOpenEditor - %s"%self.Controler.GetFilename())
        else:
            self.SetTitle("PLCOpenEditor")

    def ShowProperties(self):
        old_values = self.Controler.GetProjectProperties()
        dialog = ProjectDialog(self)
        dialog.SetValues(old_values)
        if dialog.ShowModal() == wx.ID_OK:
            new_values = dialog.GetValues()
            new_values["creationDateTime"] = old_values["creationDateTime"]
            if new_values != old_values:
                self.Controler.SetProjectProperties(None, new_values)
                self.RefreshTitle()
                self.RefreshFileMenu()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
                for i in xrange(self.GetPageCount()):
                    editor = self.GetPage(i)
                    editor.RefreshScaling()
        dialog.Destroy()

    def OnCloseFrame(self, event):
        if not self.ModeSolo and getattr(self, "_onclose", None) is not None:
            self.AUIManager.UnInit()
            self._onclose()
            event.Skip()
        elif not self.Controler.ProjectIsSaved():
            dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
            answer = dialog.ShowModal()
            dialog.Destroy()
            if answer == wx.ID_YES:
                self.SaveProject()
                event.Skip()
            elif answer == wx.ID_NO:
                self.Controler.Reset()
                self.AUIManager.UnInit()
                event.Skip()
            else:
                event.Veto()
        else:
            event.Skip()

#-------------------------------------------------------------------------------
#                            Notebook Unified Functions
#-------------------------------------------------------------------------------

    def GetPageCount(self):
        if wx.VERSION >= (2, 8, 0):
            notebook = self.GetNotebook()
            if notebook is not None:
                return notebook.GetPageCount()
            else:
                return 0
        else:
            return self.TabsOpened.GetPageCount()
    
    def GetPage(self, idx):
        if wx.VERSION >= (2, 8, 0):
            notebook = self.GetNotebook()
            if notebook is not None:
                return notebook.GetPage(idx).GetViewer()
            else:
                return None
        else:
            return self.TabsOpened.GetPage(idx)

    def GetPageSelection(self):
        if wx.VERSION >= (2, 8, 0):
            notebook = self.GetNotebook()
            if notebook is not None:
                return notebook.GetSelection()
            else:
                return -1
        else:
            return self.TabsOpened.GetSelection()

    def SetPageSelection(self, idx):
        if wx.VERSION >= (2, 8, 0):
            notebook = self.GetNotebook()
            if notebook is not None:
                notebook.SetSelection(idx)
        else:
            self.TabsOpened.SetSelection(idx)

    def DeletePage(self, idx):
        if wx.VERSION >= (2, 8, 0):
            notebook = self.GetNotebook()
            if notebook is not None:
                notebook.DeletePage(idx)
        else:
            self.TabsOpened.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()):
                    notebook.DeletePage(0)
        else:
            self.TabsOpened.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)
        else:
            return self.TabsOpened.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)
        else:
            return self.TabsOpened.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)
            else:
                return ""
        else:
            return self.TabsOpened.GetPageText(idx)


#-------------------------------------------------------------------------------
#                            File Menu Functions
#-------------------------------------------------------------------------------

    def RefreshFileMenu(self):
        if self.Controler.HasOpenedProject():
            selected = self.GetPageSelection()
            if selected >= 0:
                graphic_viewer = isinstance(self.GetPage(selected), Viewer)
            else:
                graphic_viewer = False
            if self.GetPageCount() > 0:
                self.FileMenu.Enable(wx.ID_CLOSE, True)
                if graphic_viewer:
                    self.FileMenu.Enable(wx.ID_PREVIEW, True)
                    self.FileMenu.Enable(wx.ID_PRINT, True)
                else:
                    self.FileMenu.Enable(wx.ID_PREVIEW, False)
                    self.FileMenu.Enable(wx.ID_PRINT, False)
            else:
                self.FileMenu.Enable(wx.ID_CLOSE, False)
                self.FileMenu.Enable(wx.ID_PREVIEW, False)
                self.FileMenu.Enable(wx.ID_PRINT, False)
            self.FileMenu.Enable(wx.ID_SAVE, True)
            self.FileMenu.Enable(wx.ID_PAGE_SETUP, True)
            self.FileMenu.Enable(wx.ID_PROPERTIES, True)
            if self.ModeSolo:
                self.FileMenu.Enable(wx.ID_CLOSE_ALL, True)
                self.FileMenu.Enable(wx.ID_SAVEAS, True)
                self.FileMenu.Enable(ID_PLCOPENEDITORFILEMENUGENERATE, True)
        else:
            self.FileMenu.Enable(wx.ID_CLOSE, False)
            self.FileMenu.Enable(wx.ID_SAVE, False)
            self.FileMenu.Enable(wx.ID_PAGE_SETUP, False)
            self.FileMenu.Enable(wx.ID_PREVIEW, False)
            self.FileMenu.Enable(wx.ID_PRINT, False)
            self.FileMenu.Enable(wx.ID_PROPERTIES, False)
            if self.ModeSolo:
                self.FileMenu.Enable(wx.ID_CLOSE_ALL, False)
                self.FileMenu.Enable(wx.ID_SAVEAS, False)
                self.FileMenu.Enable(ID_PLCOPENEDITORFILEMENUGENERATE, False)

    def OnNewProjectMenu(self, event):
        dialog = ProjectDialog(self)
        if dialog.ShowModal() == wx.ID_OK:
            properties = dialog.GetValues()
            self.Controler.CreateNewProject(properties)
            self.RefreshTitle()
            self.RefreshFileMenu()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        event.Skip()

    def OnOpenProjectMenu(self, event):
        if not self.Controler.ProjectIsSaved():
            dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
            answer = dialog.ShowModal()
            dialog.Destroy()
            if answer == wx.ID_YES:
                self.SaveProject()
            elif answer == wx.ID_CANCEL:
                return
        filepath = self.Controler.GetFilePath()
        if filepath != "":
            directory = os.path.dirname(filepath)
        else:
            directory = os.getcwd()
        dialog = wx.FileDialog(self, "Choose a file", directory, "",  "PLCOpen files (*.xml)|*.xml|All files|*.*", wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            filepath = dialog.GetPath()
            if os.path.isfile(filepath):
                self.DeleteAllPages()
                self.VariablePanelIndexer.RemoveAllPanels()
                self.Controler.OpenXMLFile(filepath)
                self.RefreshProjectTree()
            self.RefreshTitle()
            self.RefreshFileMenu()
            self.RefreshEditMenu()
            self.RefreshToolBar()
        dialog.Destroy()
        event.Skip()

    def OnCloseTabMenu(self, event):
        selected = self.GetPageSelection()
        if selected >= 0:
            tagname = self.GetPage(selected).GetTagName()
            self.DeletePage(selected)
            self.VariablePanelIndexer.RemoveVariablePanel(tagname)
            if self.GetPageCount() > 0:
                new_index = min(selected, self.GetPageCount() - 1)
                tagname = self.GetPage(new_index).GetTagName()
                self.SetPageSelection(new_index)
                self.VariablePanelIndexer.ChangeVariablePanel(tagname)
            self.RefreshTitle()
            self.RefreshFileMenu()
            self.RefreshEditMenu()
            self.RefreshToolBar()
        event.Skip()
    
    def OnCloseProjectMenu(self, event):
        if not self.Controler.ProjectIsSaved():
            dialog = wx.MessageDialog(self, "There are changes, do you want to save?", "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
            answer = dialog.ShowModal()
            dialog.Destroy()
            if answer == wx.ID_YES:
                self.SaveProject()
            elif answer == wx.ID_CANCEL:
                return
        self.DeleteAllPages()
        self.VariablePanelIndexer.RemoveAllPanels()
        self.ProjectTree.DeleteAllItems()
        self.Controler.Reset()
        self.RefreshTitle()
        self.RefreshFileMenu()
        self.RefreshEditMenu()
        self.RefreshToolBar()
        event.Skip()

    def OnSaveProjectMenu(self, event):
        if not self.ModeSolo and getattr(self, "_onsave", None) != None:
            self._onsave()
        else:
            self.SaveProject()
        event.Skip()

    def OnSaveProjectAsMenu(self, event):
        self.SaveProjectAs()
        event.Skip()

    def OnGenerateProgramMenu(self, event):
        dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), self.Controler.GetProgramFilePath(),  "ST files (*.st)|*.st|All files|*.*", wx.SAVE|wx.CHANGE_DIR)
        if dialog.ShowModal() == wx.ID_OK:
            filepath = dialog.GetPath()
            if os.path.isdir(os.path.dirname(filepath)):
                result = self.Controler.GenerateProgram(filepath)
                if result is not None:
                    message = wx.MessageDialog(self, "Can't generate program to file %s :\n%s"%(filepath, result), "Error", wx.OK|wx.ICON_ERROR)
                    message.ShowModal()
                    message.Destroy()
                else:
                    message = wx.MessageDialog(self, "Program was successfully generated!", "Done", wx.OK|wx.ICON_INFORMATION)
                    message.ShowModal()
                    message.Destroy()
            else:
                message = wx.MessageDialog(self, "%s is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
        dialog.Destroy()
        event.Skip()

    def SaveProject(self):
        result = self.Controler.SaveXMLFile()
        if not result:
            self.SaveProjectAs()
        else:
            self.RefreshTitle()
    
    def SaveProjectAs(self):
        filepath = self.Controler.GetFilePath()
        if filepath != "":
            directory, filename = os.path.split(filepath)
        else:
            directory, filename = os.getcwd(), "%(projectName)s.xml"%self.Controler.GetProjectProperties()
        dialog = wx.FileDialog(self, "Choose a file", directory, filename,  "PLCOpen files (*.xml)|*.xml|All files|*.*", wx.SAVE|wx.OVERWRITE_PROMPT)
        if dialog.ShowModal() == wx.ID_OK:
            filepath = dialog.GetPath()
            if os.path.isdir(os.path.dirname(filepath)):
                result = self.Controler.SaveXMLFile(filepath)
                if not result:
                    message = wx.MessageDialog(self, "Can't save project to file %s!"%filepath, "Error", wx.OK|wx.ICON_ERROR)
                    message.ShowModal()
                    message.Destroy()
            else:
                message = wx.MessageDialog(self, "%s is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
            self.RefreshTitle()
        dialog.Destroy()

    def OnPageSetupMenu(self, event):
        dialog = wx.PageSetupDialog(self, self.PageSetupData)
        if dialog.ShowModal() == wx.ID_OK:
            self.PageSetupData = wx.PageSetupDialogData(dialog.GetPageSetupData())
            self.PrintData = wx.PrintData(self.PageSetupData.GetPrintData())
        dialog.Destroy()
        event.Skip()

    def OnPreviewMenu(self, event):
        selected = self.GetPageSelection()        
        if selected != -1:
            data = wx.PrintDialogData(self.PrintData)
            properties = self.Controler.GetProjectProperties()
            page_size = map(int, properties["pageSize"])
            margins = (self.PageSetupData.GetMarginTopLeft(), self.PageSetupData.GetMarginBottomRight())
            printout = GraphicPrintout(self.GetPage(selected), page_size, margins, True)
            printout2 = GraphicPrintout(self.GetPage(selected), page_size, margins, True)
            preview = wx.PrintPreview(printout, printout2, data)

            if preview.Ok():
                preview_frame = wx.PreviewFrame(preview, self, "Print preview")

                preview_frame.Initialize()
                
                preview_frame.Show(True)
        event.Skip()

    def OnPrintMenu(self, event):
        selected = self.GetPageSelection()        
        if selected != -1:
            dialog_data = wx.PrintDialogData(self.PrintData)
            dialog_data.SetToPage(1)
            properties = self.Controler.GetProjectProperties()
            page_size = map(int, properties["pageSize"])
            margins = (self.PageSetupData.GetMarginTopLeft(), self.PageSetupData.GetMarginBottomRight())
            printer = wx.Printer(dialog_data)
            printout = GraphicPrintout(self.GetPage(selected), page_size, margins)
            
            if not printer.Print(self, printout, True):
                wx.MessageBox("There was a problem printing.\nPerhaps your current printer is not set correctly?", "Printing", wx.OK)
            printout.Destroy()
        event.Skip()

    def OnPropertiesMenu(self, event):
        self.ShowProperties()
        event.Skip()

    def OnQuitMenu(self, event):
        self.Close()
        event.Skip()


#-------------------------------------------------------------------------------
#                          Edit Project Menu Functions
#-------------------------------------------------------------------------------

    def RefreshEditMenu(self):
        if self.Controler.HasOpenedProject():
            undo, redo = self.Controler.GetBufferState()
            self.EditMenu.Enable(wx.ID_UNDO, undo)
            self.EditMenu.Enable(wx.ID_REDO, redo)
        else:
            self.EditMenu.Enable(wx.ID_UNDO, False)
            self.EditMenu.Enable(wx.ID_REDO, False)
        if self.Controler.HasOpenedProject():
            if self.GetPageCount() > 0:
                self.EditMenu.Enable(wx.ID_REFRESH, True)
            else:
                self.EditMenu.Enable(wx.ID_REFRESH, False)
            self.EditMenu.Enable(wx.ID_ADD, True)
            self.EditMenu.Enable(wx.ID_DELETE, True)
        else:
            self.EditMenu.Enable(wx.ID_REFRESH, False)
            self.EditMenu.Enable(wx.ID_ADD, False)
            self.EditMenu.Enable(wx.ID_DELETE, False)
        self.EditMenu.Enable(wx.ID_CUT, True)
        self.EditMenu.Enable(wx.ID_COPY, True)
        if self.CopyBuffer is not None:
            self.EditMenu.Enable(wx.ID_PASTE, True)
        else:
            self.EditMenu.Enable(wx.ID_PASTE, False)

    def OnRefreshMenu(self, event):
        selected = self.GetPageSelection()
        if selected != -1:
            window = self.GetPage(selected)
            window.RefreshView()
            self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
        event.Skip()

    def OnClearErrorsMenu(self, event):
        self.ClearErrors()
        event.Skip()

    def OnUndoMenu(self, event):
        self.Controler.LoadPrevious()
        idxs = range(self.GetPageCount())
        idxs.reverse()
        for idx in idxs:
            tagname = self.GetPage(idx).GetTagName()
            if self.Controler.GetEditedElement(tagname) is None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
        selected = self.GetPageSelection()        
        if selected != -1:
            window = self.GetPage(selected)
            window.RefreshView()
            self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
        self.RefreshTitle()
        self.RefreshEditMenu()
        self.RefreshProjectTree()
        event.Skip()
    
    def OnRedoMenu(self, event):
        self.Controler.LoadNext()
        idxs = range(self.GetPageCount())
        idxs.reverse()
        for idx in idxs:
            tagname = self.GetPage(idx).GetTagName()
            if self.Controler.GetEditedElement(tagname) is None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
        selected = self.GetPageSelection()
        if selected != -1:
            window = self.GetPage(selected)
            window.RefreshView()
            self.VariablePanelIndexer.RefreshVariablePanel(window.GetTagName())
        self.RefreshTitle()
        self.RefreshEditMenu()
        self.RefreshProjectTree()
        event.Skip()

    def OnCutMenu(self, event):
        control = self.FindFocus()
        if isinstance(control, Viewer):
            control.Cut()
        else:
            control.ProcessEvent(event)
        event.Skip()
    
    def OnCopyMenu(self, event):
        control = self.FindFocus()
        if isinstance(control, Viewer):
            control.Copy()
        else:
            control.ProcessEvent(event)
        event.Skip()
    
    def OnPasteMenu(self, event):
        control = self.FindFocus()
        if isinstance(control, Viewer):
            control.Paste()
        else:
            control.ProcessEvent(event)
        event.Skip()
    
    def OnDeleteMenu(self, event):
        window = self.FindFocus()
        if window == self.ProjectTree:
            selected = self.ProjectTree.GetSelection()
            if selected.IsOk():
                type = self.ProjectTree.GetPyData(selected)
                tagname = ""
                if type == ITEM_DATATYPE:
                    name = self.ProjectTree.GetItemText(selected)
                    if not self.Controler.DataTypeIsUsed(name):
                        self.Controler.ProjectRemoveDataType(name)
                        tagname = self.Controler.ComputeDataTypeName(name)
                    else:
                        message = wx.MessageDialog(self, "%s is used by one or more POUs. It can't be removed!"%selected, "Error", wx.OK|wx.ICON_ERROR)
                        message.ShowModal()
                        message.Destroy()
                elif type == ITEM_POU:
                    name = self.ProjectTree.GetItemText(selected)
                    if not self.Controler.DataTypeIsUsed(name):
                        self.Controler.ProjectRemoveDataType(name)
                        tagname = self.Controler.ComputeDataTypeName(name)
                    else:
                        message = wx.MessageDialog(self, "%s is used by one or more POUs. It can't be removed!"%selected, "Error", wx.OK|wx.ICON_ERROR)
                        message.ShowModal()
                        message.Destroy()
                elif type in [ITEM_TRANSITION, ITEM_ACTION]:
                    item = self.ProjectTree.GetItemParent(selected)
                    item_type = self.ProjectTree.GetPyData(item)
                    while item_type != ITEM_POU:
                        item = self.ProjectTree.GetItemParent(item)
                        item_type = self.ProjectTree.GetPyData(item)
                    pou_name = self.ProjectTree.GetItemText(item)
                    if type == ITEM_TRANSITION:
                        transition = self.ProjectTree.GetItemText(selected)
                        self.Controler.ProjectRemovePouTransition(pou_name, transition)
                        tagname = self.Controler.ComputePouTransitionName(pou_name, transition)
                    elif type == ITEM_ACTION:
                        action = self.ProjectTree.GetItemText(selected)
                        self.Controler.ProjectRemovePouAction(pou_name, action)
                        tagname = self.Controler.ComputePouActionName(pou_name, action)
                elif type == ITEM_CONFIGURATION:
                    name = self.ProjectTree.GetItemText(selected)
                    self.Controler.ProjectRemoveConfiguration(name)
                    tagname = self.Controler.ComputeConfigurationName(name)
                elif type == ITEM_RESOURCE:
                    resource = self.ProjectTree.GetItemText(selected)
                    item = self.ProjectTree.GetItemParent(selected)
                    item_type = self.ProjectTree.GetPyData(item)
                    while item_type != ITEM_CONFIGURATION:
                        item = self.ProjectTree.GetItemParent(item)
                        item_type = self.ProjectTree.GetPyData(item)
                    config_name = self.ProjectTree.GetItemText(item)
                    self.Controler.ProjectRemoveConfigurationResource(config_name, resource)
                    tagname = self.Controler.ComputeConfigurationResourceName(config_name, selected)
                idx = self.IsOpened(tagname)
                if idx is not None:
                    self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                    self.DeletePage(idx)
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
                self.RefreshToolBar()
        elif isinstance(window, (Viewer, TextViewer)):
            event = wx.KeyEvent(wx.EVT_CHAR._getEvtType())
            event.m_keyCode = wx.WXK_DELETE
            window.ProcessEvent(event)
        event.Skip()


#-------------------------------------------------------------------------------
#                      Project Editor Panels Management Functions
#-------------------------------------------------------------------------------
    
    def OnPouSelectedChanged(self, event):
        if wx.VERSION < (2, 8, 0) or event.GetActive():
            old_selected = self.GetPageSelection()
            if old_selected >= 0:
                self.GetPage(old_selected).ResetBuffer()
            if wx.VERSION >= (2, 8, 0):
                window = event.GetEventObject().GetViewer()
            else:
                selected = event.GetSelection()
                if selected >= 0:
                    window = self.GetPage(selected)
                else:
                    window = None
            if window:
                self.SelectProjectTreeItem(window.GetTagName())
                window.RefreshView()
                self.VariablePanelIndexer.ChangeVariablePanel(window.GetTagName())
                self.RefreshFileMenu()
                self.RefreshEditMenu()
                self.RefreshToolBar()
        event.Skip()

    def RefreshEditor(self, variablepanel = True):
        selected = self.GetPageSelection()
        if selected != -1:
            window = self.GetPage(selected)
            window.RefreshView()
            if variablepanel:
                self.RefreshVariablePanel(window.GetTagName())

    def RefreshVariablePanel(self, tagname):
        self.VariablePanelIndexer.RefreshVariablePanel(tagname)

    def RefreshEditorNames(self, old_tagname, new_tagname):
        for i in xrange(self.GetPageCount()):
            editor = self.GetPage(i)
            if editor.GetTagName() == old_tagname:
                editor.SetTagName(new_tagname)
        self.VariablePanelIndexer.UpdateVariablePanelTagName(old_tagname, new_tagname)

    def IsOpened(self, tagname):
        for idx in xrange(self.GetPageCount()):
            if self.GetPage(idx).IsViewing(tagname):
                return idx
        return None

    def RefreshPageTitles(self):
        for idx in xrange(self.GetPageCount()):
            window = self.GetPage(idx)
            words = window.GetTagName().split("::")
            if words[0] == "P":
                pou_type = self.Controler.GetEditedElementType(window.GetTagName())[1].upper()
                pou_body_type = self.Controler.GetEditedElementBodyType(window.GetTagName())
                self.SetPageBitmap(idx, GenerateBitmap(pou_type, pou_body_type))
            elif words[0] == "T":
                pou_body_type = self.Controler.GetEditedElementBodyType(window.GetTagName())
                self.SetPageBitmap(idx, GenerateBitmap("TRANSITION", pou_body_type))
            elif words[0] == "A":
                pou_body_type = self.Controler.GetEditedElementBodyType(window.GetTagName())
                self.SetPageBitmap(idx, GenerateBitmap("ACTION", pou_body_type))
            elif words[0] == "C":
                self.SetPageBitmap(idx, GenerateBitmap("CONFIGURATION"))
            elif words[0] == "R":
                self.SetPageBitmap(idx, GenerateBitmap("RESOURCE"))
            elif words[0] == "D":
                self.SetPageBitmap(idx, GenerateBitmap("DATATYPE"))
            self.SetPageText(idx, "-".join(words[1:]))


#-------------------------------------------------------------------------------
#                         Project Tree Management Functions
#-------------------------------------------------------------------------------

    def RefreshProjectTree(self):
        infos = self.Controler.GetProjectInfos()
        root = self.ProjectTree.GetRootItem()
        if not root.IsOk():
            root = self.ProjectTree.AddRoot(infos["name"])
        self.GenerateTreeBranch(root, infos)
        self.ProjectTree.Expand(self.ProjectTree.GetRootItem())

    def GenerateTreeBranch(self, root, infos):
        to_delete = []
        self.ProjectTree.SetItemText(root, infos["name"])
        self.ProjectTree.SetPyData(root, infos["type"])
        if infos["tagname"] in self.Errors:
            self.ProjectTree.SetItemBackgroundColour(root, wx.Colour(255, 255, 0))
            self.ProjectTree.SetItemTextColour(root, wx.RED)
        else:
            self.ProjectTree.SetItemBackgroundColour(root, wx.WHITE)
            self.ProjectTree.SetItemTextColour(root, wx.BLACK)
        if infos["type"] == ITEM_POU :
            self.ProjectTree.SetItemImage(root,self.TreeImageDict[self.Controler.GetPouBodyType(infos["name"])])
        else:
            self.ProjectTree.SetItemImage(root,self.TreeImageDict[infos["type"]])      
            
        if wx.VERSION >= (2, 6, 0):
            item, root_cookie = self.ProjectTree.GetFirstChild(root)
        else:
            item, root_cookie = self.ProjectTree.GetFirstChild(root, 0)
        for values in infos["values"]:
            if not item.IsOk():
                item = self.ProjectTree.AppendItem(root, "")
                if wx.Platform != '__WXMSW__':
                    item, root_cookie = self.ProjectTree.GetNextChild(root, root_cookie)
            self.GenerateTreeBranch(item, values)
            item, root_cookie = self.ProjectTree.GetNextChild(root, root_cookie)
        while item.IsOk():
            to_delete.append(item)
            item, root_cookie = self.ProjectTree.GetNextChild(root, root_cookie)
        for item in to_delete:
            self.ProjectTree.Delete(item)

    def SelectProjectTreeItem(self, tagname):
        if self.ProjectTree:
            root = self.ProjectTree.GetRootItem()
            words = tagname.split("::")
            if words[0] == "D":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_DATATYPE)])
            elif words[0] == "P":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_POU)])
            elif words[0] == "T":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_POU), (words[2], ITEM_TRANSITION)])
            elif words[0] == "A":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_POU), (words[2], ITEM_ACTION)])
            elif words[0] == "C":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_CONFIGURATION)])
            elif words[0] == "R":
                return self.RecursiveProjectTreeItemSelection(root, [(words[1], ITEM_CONFIGURATION), (words[2], ITEM_RESOURCE)])
        return False

    def RecursiveProjectTreeItemSelection(self, root, items):
        found = False
        if self.ProjectTree:
            if wx.VERSION >= (2, 6, 0):
                item, root_cookie = self.ProjectTree.GetFirstChild(root)
            else:
                item, root_cookie = self.ProjectTree.GetFirstChild(root, 0)
            while item.IsOk() and not found:
                if (self.ProjectTree.GetItemText(item), self.ProjectTree.GetPyData(item)) == items[0]:
                    if len(items) == 1:
                        self.SelectedItem = item
                        self.ProjectTree.SelectItem(item)
                        wx.CallAfter(self.ResetSelectedItem)
                        return True
                    else:
                        found = self.RecursiveProjectTreeItemSelection(item, items[1:])
                else:
                    found = self.RecursiveProjectTreeItemSelection(item, items)
                item, root_cookie = self.ProjectTree.GetNextChild(root, root_cookie)
        return found

    def OnProjectTreeBeginDrag(self, event):
        if wx.Platform == '__WXMSW__':
            self.SelectedItem = event.GetItem()
        if self.SelectedItem is not None and self.ProjectTree.GetPyData(self.SelectedItem) == ITEM_POU:
            block_name = self.ProjectTree.GetItemText(self.SelectedItem)
            block_type = self.Controler.GetPouType(block_name)
            if block_type != "program":
                data = wx.TextDataObject(str((block_name, block_type, "")))
                dragSource = wx.DropSource(self.ProjectTree)
                dragSource.SetData(data)
                dragSource.DoDragDrop()
            self.ResetSelectedItem()

    def OnProjectTreeItemBeginEdit(self, event):
        selected = event.GetItem()
        if self.ProjectTree.GetPyData(selected) in ITEMS_UNEDITABLE:
            event.Veto()
        else:
            event.Skip()

    def OnProjectTreeItemEndEdit(self, event):
        message = None
        abort = False
        new_name = event.GetLabel()
        if new_name != "":
            if not TestIdentifier(new_name):
                message = "\"%s\" is not a valid identifier!"%new_name
            elif new_name.upper() in IEC_KEYWORDS:
                message = "\"%s\" is a keyword. It can't be used!"%new_name
            else:
                item = event.GetItem()
                old_name = self.ProjectTree.GetItemText(item)
                itemtype = self.ProjectTree.GetPyData(item)
                if itemtype == ITEM_PROJECT:
                    self.Controler.SetProjectProperties(name = new_name)
                elif itemtype == ITEM_DATATYPE:
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectDataTypeNames() if name != old_name]:
                        message = "\"%s\" data type already exists!"%new_name
                        abort = True
                    if not abort:
                        self.Controler.ChangeDataTypeName(old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputeDataTypeName(old_name), 
                                                self.Controler.ComputeDataTypeName(new_name))
                        self.RefreshPageTitles()
                elif itemtype == ITEM_POU:
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames() if name != old_name]:
                        message = "\"%s\" pou already exists!"%new_name
                        abort = True
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables()]:
                        messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
                        if messageDialog.ShowModal() == wx.ID_NO:
                            abort = True
                        messageDialog.Destroy()
                    if not abort:
                        self.Controler.ChangePouName(old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputePouName(old_name), 
                                                self.Controler.ComputePouName(new_name))
                        self.RefreshPageTitles()
                elif itemtype == ITEM_TRANSITION:
                    parent = self.ProjectTree.GetItemParent(item)
                    parent_type = self.ProjectTree.GetPyData(parent)
                    while parent_type != ITEM_POU:
                        parent = self.ProjectTree.GetItemParent(parent)
                        parent_type = self.ProjectTree.GetPyData(parent)
                    pou_name = self.ProjectTree.GetItemText(parent)
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames()]:
                        message = "A pou with \"%s\" as name exists!"%new_name
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(pou_name) if name != old_name]:
                        message = "A variable with \"%s\" as name already exists in this pou!"%new_name
                    else:
                        self.Controler.ChangePouTransitionName(pou_name, old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputePouTransitionName(pou_name, old_name), 
                                                self.Controler.ComputePouTransitionName(pou_name, new_name))
                        self.RefreshPageTitles()
                elif itemtype == ITEM_ACTION:
                    parent = self.ProjectTree.GetItemParent(item)
                    parent_type = self.ProjectTree.GetPyData(parent)
                    while parent_type != ITEM_POU:
                        parent = self.ProjectTree.GetItemParent(parent)
                        parent_type = self.ProjectTree.GetPyData(parent)
                    pou_name = self.ProjectTree.GetItemText(parent)
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames()]:
                        message = "A pou with \"%s\" as name exists!"%new_name
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables(pou_name) if name != old_name]:
                        message = "A variable with \"%s\" as name already exists in this pou!"%new_name
                    else:
                        self.Controler.ChangePouActionName(pou_name, old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputePouActionName(pou_name, old_name), 
                                                self.Controler.ComputePouActionName(pou_name, new_name))
                        self.RefreshPageTitles()
                elif itemtype == ITEM_CONFIGURATION:
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectConfigNames() if name != old_name]:
                        message = "\"%s\" config already exists!"%new_name
                        abort = True
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames()]:
                        messageDialog = wx.MessageDialog(self, "A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
                        if messageDialog.ShowModal() == wx.ID_NO:
                            abort = True
                        messageDialog.Destroy()
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables()]:
                        messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
                        if messageDialog.ShowModal() == wx.ID_NO:
                            abort = True
                        messageDialog.Destroy()
                    if not abort:
                        self.Controler.ChangeConfigurationName(old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputeConfigurationName(old_name), 
                                                self.Controler.ComputeConfigurationName(new_name))
                        self.RefreshPageTitles()
                elif itemtype == ITEM_RESOURCE:
                    parent = self.ProjectTree.GetItemParent(item)
                    parent_type = self.ProjectTree.GetPyData(parent)
                    while parent_type != ITEM_CONFIGURATION:
                        parent = self.ProjectTree.GetItemParent(parent)
                        parent_type = self.ProjectTree.GetPyData(parent)
                    config_name = self.ProjectTree.GetItemText(parent)
                    if new_name.upper() in [name.upper() for name in self.Controler.GetProjectConfigNames()]:
                        message = "\"%s\" config already exists!"%new_name
                        abort = True
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouNames()]:
                        messageDialog = wx.MessageDialog(self, "A pou is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
                        if messageDialog.ShowModal() == wx.ID_NO:
                            abort = True
                        messageDialog.Destroy()
                    elif new_name.upper() in [name.upper() for name in self.Controler.GetProjectPouVariables()]:
                        messageDialog = wx.MessageDialog(self, "A variable is defined with \"%s\" as name. It can generate a conflict. Do you wish to continue?"%new_name, "Error", wx.YES_NO|wx.ICON_QUESTION)
                        if messageDialog.ShowModal() == wx.ID_NO:
                            abort = True
                        messageDialog.Destroy()
                    if not abort:
                        self.Controler.ChangeConfigurationResourceName(config_name, old_name, new_name)
                        self.RefreshEditorNames(self.Controler.ComputeConfigurationResourceName(config_name, old_name), 
                                                self.Controler.ComputeConfigurationResourceName(config_name, new_name))
                        self.RefreshPageTitles()
            if message or abort:
                if message:
                    messageDialog = wx.MessageDialog(self, message, "Error", wx.OK|wx.ICON_ERROR)
                    messageDialog.ShowModal()
                    messageDialog.Destroy()
                item = event.GetItem()
                wx.CallAfter(self.ProjectTree.EditLabel, item)
                event.Veto()
            else:
                wx.CallAfter(self.RefreshProjectTree)
                selected = self.GetPageSelection()
                if selected != -1:
                    self.GetPage(selected).RefreshView()
                event.Skip()
    
    def OnProjectTreeItemActivated(self, event):
        selected = event.GetItem()
        if self.ProjectTree.IsExpanded(selected):
            self.ProjectTree.Collapse(selected)
        else:
            self.ProjectTree.Expand(selected)
        name = self.ProjectTree.GetItemText(selected)
        data = self.ProjectTree.GetPyData(selected)
        if name == "Properties":
            self.ShowProperties()
        if data == ITEM_DATATYPE:
            self.EditProjectElement(data, self.Controler.ComputeDataTypeName(name))
        elif data == ITEM_POU:
            self.EditProjectElement(data, self.Controler.ComputePouName(name))
        elif data == ITEM_CONFIGURATION:
            self.EditProjectElement(data, self.Controler.ComputeConfigurationName(name))
        elif data == ITEM_RESOURCE:
            item = self.ProjectTree.GetItemParent(selected)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_CONFIGURATION:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            config_name = self.ProjectTree.GetItemText(item)
            self.EditProjectElement(data, self.Controler.ComputeConfigurationResourceName(config_name, name))
        elif data in [ITEM_TRANSITION, ITEM_ACTION]:
            item = self.ProjectTree.GetItemParent(selected)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_POU:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            pou_name = self.ProjectTree.GetItemText(item)
            if data == ITEM_TRANSITION:
                tagname = self.Controler.ComputePouTransitionName(pou_name, name)
            elif data == ITEM_ACTION:
                tagname = self.Controler.ComputePouActionName(pou_name, name)
            self.EditProjectElement(data, tagname)
        event.Skip()
    
    def ProjectTreeItemSelect(self, select_item):
        name = self.ProjectTree.GetItemText(select_item)
        data = self.ProjectTree.GetPyData(select_item)
        if data == ITEM_DATATYPE:
            self.EditProjectElement(data, self.Controler.ComputeDataTypeName(name), True)
        elif data == ITEM_POU:
            self.EditProjectElement(data, self.Controler.ComputePouName(name), True)
        elif data == ITEM_CONFIGURATION:
            self.EditProjectElement(data, self.Controler.ComputeConfigurationName(name), True)
        elif data == ITEM_RESOURCE:
            item = self.ProjectTree.GetItemParent(select_item)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_CONFIGURATION:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            config_name = self.ProjectTree.GetItemText(item)
            self.EditProjectElement(data, self.Controler.ComputeConfigurationResourceName(config_name, name), True)
        elif data in [ITEM_TRANSITION, ITEM_ACTION]:
            item = self.ProjectTree.GetItemParent(select_item)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_POU:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            pou_name = self.ProjectTree.GetItemText(item)
            if data == ITEM_TRANSITION:
                tagname = self.Controler.ComputePouTransitionName(pou_name, name)
            elif data == ITEM_ACTION:
                tagname = self.Controler.ComputePouActionName(pou_name, name)
            self.EditProjectElement(data, tagname, True)
    
    def OnProjectTreeLeftUp(self, event):
        if self.SelectedItem is not None:
            self.ProjectTree.SelectItem(self.SelectedItem)
            self.ProjectTreeItemSelect(self.SelectedItem)
            wx.CallAfter(self.ResetSelectedItem)
        event.Skip()
    
    def OnProjectTreeItemSelected(self, event):
        self.ProjectTreeItemSelect(event.GetItem())
        event.Skip()
    
    def OnProjectTreeItemChanging(self, event):
        if self.ProjectTree.GetPyData(event.GetItem()) not in ITEMS_UNEDITABLE and self.SelectedItem is None:
            self.SelectedItem = event.GetItem()
            event.Veto()
        else:
            event.Skip()
    
    def EditProjectElement(self, elementtype, tagname, onlyopened = False):
        openedidx = self.IsOpened(tagname)
        if openedidx is not None:
            old_selected = self.GetPageSelection()
            if old_selected != openedidx:
                if old_selected >= 0:
                    self.GetPage(old_selected).ResetBuffer()
                self.SetPageSelection(openedidx)
            self.GetPage(openedidx).RefreshView()
            self.VariablePanelIndexer.ChangeVariablePanel(tagname)
            self.RefreshPageTitles()
            self.RefreshFileMenu()
            self.RefreshEditMenu()
            self.RefreshToolBar()
        elif not onlyopened:
            if wx.VERSION >= (2, 8, 0):
                if elementtype == ITEM_CONFIGURATION:
                    new_window = MDIConfigurationEditor(self, tagname, self, self.Controler)
                elif elementtype == ITEM_RESOURCE:
                    new_window = MDIResourceEditor(self, tagname, self, self.Controler)
                elif elementtype in [ITEM_POU, ITEM_TRANSITION, ITEM_ACTION]:
                    bodytype = self.Controler.GetEditedElementBodyType(tagname)
                    if bodytype == "FBD":
                        new_window = MDIViewer(self, tagname, self, self.Controler)
                        new_window.GetViewer().RefreshScaling(False)
                    elif bodytype == "LD":
                        new_window = LD_MDIViewer(self, tagname, self, self.Controler)
                        new_window.GetViewer().RefreshScaling(False)
                    elif bodytype == "SFC":
                        new_window = SFC_MDIViewer(self, tagname, self, self.Controler)
                        new_window.GetViewer().RefreshScaling(False)
                    else:
                        new_window = TextMDIViewer(self, tagname, self, self.Controler)
                        viewer = new_window.GetViewer()
                        viewer.SetTextSyntax(elementtype)
                        if bodytype == "IL":
                            viewer.SetKeywords(IL_KEYWORDS)
                        else:
                            viewer.SetKeywords(ST_KEYWORDS)
                elif elementtype == ITEM_DATATYPE:
                    new_window = MDIDataTypeEditor(self, tagname, self, self.Controler)
                new_window.Bind(wx.EVT_ACTIVATE, self.OnPouSelectedChanged)
                new_window.Bind(wx.EVT_CLOSE, self.OnPageClose)
                new_window.Layout()
            else:
                if elementtype == ITEM_CONFIGURATION:
                    new_window = ConfigurationEditor(self.TabsOpened, tagname, self, self.Controler)
                    self.TabsOpened.AddPage(new_window, "")
                elif elementtype == ITEM_RESOURCE:
                    new_window = ResourceEditor(self.TabsOpened, tagname, self, self.Controler)
                    self.TabsOpened.AddPage(new_window, "")
                elif elementtype in [ITEM_POU, ITEM_TRANSITION, ITEM_ACTION]:
                    bodytype = self.Controler.GetEditedElementBodyType(tagname)
                    if bodytype == "FBD":
                        new_window = Viewer(self.TabsOpened, tagname, self, self.Controler)
                        new_window.RefreshScaling(False)
                    elif bodytype == "LD":
                        new_window = LD_Viewer(self.TabsOpened, tagname, self, self.Controler)
                        new_window.RefreshScaling(False)
                    elif bodytype == "SFC":
                        new_window = SFC_Viewer(self.TabsOpened, tagname, self, self.Controler)
                        new_window.RefreshScaling(False)
                    else:
                        new_window = TextViewer(self.TabsOpened, tagname, self, self.Controler)
                        new_window.SetTextSyntax(elementtype)
                        if bodytype == "IL":
                            new_window.SetKeywords(IL_KEYWORDS)
                        else:
                            new_window.SetKeywords(ST_KEYWORDS)
                    self.TabsOpened.AddPage(new_window, "")
                elif elementtype == ITEM_DATATYPE:
                    new_window = DataTypeEditor(self.TabsOpened, tagname, self, self.Controler)
                    self.TabsOpened.AddPage(new_window, "")
            if elementtype == ITEM_CONFIGURATION:
                self.VariablePanelIndexer.AddVariablePanel(tagname, "config")
            elif elementtype == ITEM_RESOURCE:
                self.VariablePanelIndexer.AddVariablePanel(tagname, "resource")
            elif elementtype in [ITEM_POU, ITEM_TRANSITION, ITEM_ACTION]:
                words = tagname.split("::")
                self.VariablePanelIndexer.AddVariablePanel(tagname, self.Controler.GetPouType(words[1]))
            self.VariablePanelIndexer.ChangeVariablePanel(tagname)
            openedidx = self.IsOpened(tagname)
            old_selected = self.GetPageSelection()
            if old_selected != openedidx:
                if old_selected >= 0:
                    self.GetPage(old_selected).ResetBuffer()
            for i in xrange(self.GetPageCount()):
                window = self.GetPage(i)
                if window.GetTagName() == tagname:
                    self.SetPageSelection(i)
                    window.RefreshView()
                    window.SetFocus()
                    self.RefreshPageTitles()
                    self.RefreshFileMenu()
                    self.RefreshEditMenu()
                    self.RefreshToolBar()
    
    def OnProjectTreeRightUp(self, event):
        if wx.Platform == '__WXMSW__':
            item = event.GetItem()
        else:
            item = self.ProjectTree.GetSelection()
        name = self.ProjectTree.GetItemText(item)
        type = self.ProjectTree.GetPyData(item)
        if type == ITEM_POU:
            menu = wx.Menu(title='')
            if self.Controler.GetPouBodyType(name) == "SFC":
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Transition")
                self.Bind(wx.EVT_MENU, self.GenerateAddTransitionFunction(name), id=new_id)
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Action")
                self.Bind(wx.EVT_MENU, self.GenerateAddActionFunction(name), id=new_id)
                menu.AppendSeparator()
            new_id = wx.NewId()
            AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
            self.Bind(wx.EVT_MENU, self.OnRemovePouMenu, id=new_id)
            self.PopupMenu(menu)
        elif type == ITEM_CONFIGURATION:
            menu = wx.Menu(title='')
            new_id = wx.NewId()
            AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Resource")
            self.Bind(wx.EVT_MENU, self.GenerateAddResourceFunction(name), id=new_id)
            new_id = wx.NewId()
            AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
            self.Bind(wx.EVT_MENU, self.OnRemoveConfigurationMenu, id=new_id)
            self.PopupMenu(menu)
        elif type in [ITEM_DATATYPE, ITEM_TRANSITION, ITEM_ACTION, ITEM_RESOURCE]:
            menu = wx.Menu(title='')
            new_id = wx.NewId()
            AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Delete")
            if type == ITEM_DATATYPE:
                self.Bind(wx.EVT_MENU, self.OnRemoveDataTypeMenu, id=new_id)
            elif type == ITEM_TRANSITION:
                self.Bind(wx.EVT_MENU, self.OnRemoveTransitionMenu, id=new_id)
            elif type == ITEM_ACTION:
                self.Bind(wx.EVT_MENU, self.OnRemoveActionMenu, id=new_id)
            elif type == ITEM_RESOURCE:
                self.Bind(wx.EVT_MENU, self.OnRemoveResourceMenu, id=new_id)
            self.PopupMenu(menu)
        elif type in ITEMS_UNEDITABLE:
            if name == "Data Types":
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add DataType")
                self.Bind(wx.EVT_MENU, self.OnAddDataTypeMenu, id=new_id)
                self.PopupMenu(menu)
            elif name in ["Functions", "Function Blocks", "Programs"]:
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Pou")
                self.Bind(wx.EVT_MENU, self.GenerateAddPouFunction({"Functions" : "function", "Function Blocks" : "functionBlock", "Programs" : "program"}[name]), id=new_id)
                self.PopupMenu(menu)
            elif name == "Configurations":
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Configuration")
                self.Bind(wx.EVT_MENU, self.OnAddConfigurationMenu, id=new_id)
                self.PopupMenu(menu)
            elif name == "Transitions":
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Transition")
                parent = self.ProjectTree.GetItemParent(item)
                parent_type = self.ProjectTree.GetPyData(parent)
                while parent_type != ITEM_POU:
                    parent = self.ProjectTree.GetItemParent(parent)
                    parent_type = self.ProjectTree.GetPyData(parent)
                self.Bind(wx.EVT_MENU, self.GenerateAddTransitionFunction(self.ProjectTree.GetItemText(parent)), id=new_id)
                self.PopupMenu(menu)
            elif name == "Actions":
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Action")
                parent = self.ProjectTree.GetItemParent(item)
                parent_type = self.ProjectTree.GetPyData(parent)
                while parent_type != ITEM_POU:
                    parent = self.ProjectTree.GetItemParent(parent)
                    parent_type = self.ProjectTree.GetPyData(parent)
                self.Bind(wx.EVT_MENU, self.GenerateAddActionFunction(self.ProjectTree.GetItemText(parent)), id=new_id)
                self.PopupMenu(menu)
            elif name == "Resources":
                menu = wx.Menu(title='')
                new_id = wx.NewId()
                AppendMenu(menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text="Add Resource")
                parent = self.ProjectTree.GetItemParent(item)
                parent_type = self.ProjectTree.GetPyData(parent)
                while parent_type != ITEM_CONFIGURATION:
                    parent = self.ProjectTree.GetItemParent(parent)
                    parent_type = self.ProjectTree.GetPyData(parent)
                self.Bind(wx.EVT_MENU, self.GenerateAddResourceFunction(self.ProjectTree.GetItemText(parent)), id=new_id)
                self.PopupMenu(menu)
        event.Skip()


#-------------------------------------------------------------------------------
#                          ToolBar Management Functions
#-------------------------------------------------------------------------------

    def ResetToolBar(self):
        for item in self.CurrentToolBar:
            if wx.VERSION >= (2, 6, 0):
                self.Unbind(wx.EVT_MENU, id=item)
            else:
                self.Disconnect(id=item, eventType=wx.wxEVT_COMMAND_MENU_SELECTED) 
            
            if wx.VERSION < (2, 8, 0):
                ToolBar = self.ToolBar
            else:
                ToolBar = self.Panes["ToolBar"]
            if ToolBar:
                ToolBar.DeleteTool(item)
                ToolBar.Realize()
                if wx.VERSION >= (2, 8, 0):
                    self.AUIManager.GetPane("ToolBar").BestSize(ToolBar.GetBestSize())
                    self.AUIManager.Update()

    def RefreshToolBar(self):
        selected = self.GetPageSelection()
        if selected != -1:
            language = self.Controler.GetEditedElementBodyType(self.GetPage(selected).GetTagName())
        else:
            language = None
        if language is not None and language != self.CurrentLanguage:
            self.ResetToolBar()
            self.CurrentLanguage = language
            self.CurrentToolBar = []
            if wx.VERSION < (2, 8, 0):
                ToolBar = self.ToolBar
            else:
                ToolBar = self.Panes["ToolBar"]
            if ToolBar:
                for radio, modes, id, method, picture, help in ToolBarItems[language]:
                    if modes & self.DrawingMode:
                        if radio or self.DrawingMode == FREEDRAWING_MODE:
                            ToolBar.AddRadioTool(id, wx.Bitmap(os.path.join(CWD, "Images", picture)), wx.NullBitmap, help)
                        else:
                            ToolBar.AddSimpleTool(id, wx.Bitmap(os.path.join(CWD, "Images", picture)), help)
                        self.Bind(wx.EVT_TOOL, getattr(self, method), id=id)
                        self.CurrentToolBar.append(id)
                ToolBar.Realize()
                if wx.VERSION >= (2, 8, 0):
                    self.AUIManager.GetPane("ToolBar").BestSize(ToolBar.GetBestSize())
                    self.AUIManager.Update()
        elif not language:
            self.ResetToolBar()
            self.CurrentLanguage = language
        self.ResetCurrentMode()


#-------------------------------------------------------------------------------
#                           ToolBar Items Functions
#-------------------------------------------------------------------------------

    def ResetCurrentMode(self):
        selected = self.GetPageSelection()
        if selected != -1:
            window = self.GetPage(selected)
            window.SetMode(MODE_SELECTION)
        if wx.VERSION < (2, 8, 0):
            ToolBar = self.ToolBar
        else:
            ToolBar = self.Panes["ToolBar"]
        if ToolBar:
            ToolBar.ToggleTool(ID_PLCOPENEDITORTOOLBARSELECTION, True)
        
    def ResetToolToggle(self, id):
        if wx.VERSION < (2, 8, 0):
            tool = self.ToolBar.FindById(id)
        else:
            tool = self.Panes["ToolBar"].FindById(id)
        tool.SetToggle(False)

    def OnSelectionTool(self, event):
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_SELECTION)
        event.Skip()
    
    def OnCommentTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARCOMMENT)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_COMMENT)
        event.Skip()
    
    def OnVariableTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARVARIABLE)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_VARIABLE)
        event.Skip()
    
    def OnBlockTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARBLOCK)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_BLOCK)
        event.Skip()
        
    def OnConnectionTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARCONNECTION)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_CONNECTION)
        event.Skip()

    def OnPowerRailTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARPOWERRAIL)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_POWERRAIL)
        event.Skip()

    def OnRungTool(self, event):
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).AddLadderRung()
        event.Skip()
    
    def OnCoilTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARCOIL)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_COIL)
        event.Skip()
    
    def OnContactTool(self, event):
        if self.DrawingMode == FREEDRAWING_MODE:
            self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARCONTACT)
        selected = self.GetPageSelection()
        if selected != -1:
            if self.DrawingMode == FREEDRAWING_MODE:
                self.GetPage(selected).SetMode(MODE_CONTACT)
            else:
                self.GetPage(selected).AddLadderContact()
        event.Skip()
    
    def OnBranchTool(self, event): 
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).AddLadderBranch()
        event.Skip()    
    
    def OnInitialStepTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARINITIALSTEP)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_INITIALSTEP)
        event.Skip()
    
    def OnStepTool(self, event):
        if self.GetDrawingMode() == FREEDRAWING_MODE:
            self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARSTEP)
        selected = self.GetPageSelection()
        if selected != -1:
            if self.GetDrawingMode() == FREEDRAWING_MODE:
                self.GetPage(selected).SetMode(MODE_STEP)
            else:
                self.GetPage(selected).AddStep()
        event.Skip()

    def OnActionBlockTool(self, event):
        if self.GetDrawingMode() == FREEDRAWING_MODE:
            self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARACTIONBLOCK)
        selected = self.GetPageSelection()
        if selected != -1:
            if self.GetDrawingMode() == FREEDRAWING_MODE:
                self.GetPage(selected).SetMode(MODE_ACTION)
            else:
                self.GetPage(selected).AddStepAction()
        event.Skip()

    def OnTransitionTool(self, event):
        self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARTRANSITION)
        selected = self.GetPageSelection()
        if selected != -1:
            self.GetPage(selected).SetMode(MODE_TRANSITION)
        event.Skip()

    def OnDivergenceTool(self, event):
        if self.GetDrawingMode() == FREEDRAWING_MODE:
            self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARDIVERGENCE)
        selected = self.GetPageSelection()
        if selected != -1:
            if self.GetDrawingMode() == FREEDRAWING_MODE:
                self.GetPage(selected).SetMode(MODE_DIVERGENCE)
            else:
                self.GetPage(selected).AddDivergence()
        event.Skip()
    
    def OnJumpTool(self, event):
        if self.GetDrawingMode() == FREEDRAWING_MODE:
            self.ResetToolToggle(ID_PLCOPENEDITORTOOLBARJUMP)
        selected = self.GetPageSelection()
        if selected != -1:
            if self.GetDrawingMode() == FREEDRAWING_MODE:
                self.GetPage(selected).SetMode(MODE_JUMP)
            else:
                self.GetPage(selected).AddJump()
        event.Skip()


#-------------------------------------------------------------------------------
#                         Add Project Elements Functions
#-------------------------------------------------------------------------------

    def OnAddDataTypeMenu(self, event):
        dialog = DataTypeDialog(self, "Add a new data type", "Please enter data type name", "", wx.OK|wx.CANCEL)
        dialog.SetDataTypeNames(self.Controler.GetProjectDataTypeNames())
        if dialog.ShowModal() == wx.ID_OK:
            self.Controler.ProjectAddDataType(dialog.GetValue())
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        dialog.Destroy()
        event.Skip()

    def GenerateAddPouFunction(self, pou_type):
        def OnAddPouMenu(event):
            dialog = PouDialog(self, pou_type)
            dialog.SetPouNames(self.Controler.GetProjectPouNames())
            dialog.SetPouElementNames(self.Controler.GetProjectPouVariables())
            if dialog.ShowModal() == wx.ID_OK:
                values = dialog.GetValues()
                self.Controler.ProjectAddPou(values["pouName"], values["pouType"], values["language"])
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
            dialog.Destroy()
            event.Skip()
        return OnAddPouMenu

    def GenerateAddTransitionFunction(self, pou_name):
        def OnAddTransitionMenu(event):
            dialog = PouTransitionDialog(self)
            dialog.SetPouNames(self.Controler.GetProjectPouNames())
            dialog.SetPouElementNames(self.Controler.GetProjectPouVariables(pou_name))
            if dialog.ShowModal() == wx.ID_OK: 
                values = dialog.GetValues()
                self.Controler.ProjectAddPouTransition(pou_name, values["transitionName"], values["language"])
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
            dialog.Destroy()
            event.Skip()
        return OnAddTransitionMenu

    def GenerateAddActionFunction(self, pou_name):
        def OnAddActionMenu(event):
            dialog = PouActionDialog(self)
            dialog.SetPouNames(self.Controler.GetProjectPouNames())
            dialog.SetPouElementNames(self.Controler.GetProjectPouVariables(pou_name))
            if dialog.ShowModal() == wx.ID_OK:
                values = dialog.GetValues()
                self.Controler.ProjectAddPouAction(pou_name, values["actionName"], values["language"])
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
            dialog.Destroy()
            event.Skip()
        return OnAddActionMenu

    def OnAddConfigurationMenu(self, event):
        dialog = ConfigurationNameDialog(self, "Please enter configuration name", "Add new configuration")
        dialog.SetPouNames(self.Controler.GetProjectPouNames())
        dialog.SetPouElementNames(self.Controler.GetProjectPouVariables())
        if dialog.ShowModal() == wx.ID_OK:
            value = dialog.GetValue()
            self.Controler.ProjectAddConfiguration(value)
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        dialog.Destroy()
        event.Skip()

    def GenerateAddResourceFunction(self, config_name):
        def OnAddResourceMenu(event):
            dialog = ResourceNameDialog(self, "Please enter resource name", "Add new resource")
            dialog.SetPouNames(self.Controler.GetProjectPouNames())
            dialog.SetPouElementNames(self.Controler.GetProjectPouVariables())
            if dialog.ShowModal() == wx.ID_OK:
                value = dialog.GetValue()
                self.Controler.ProjectAddConfigurationResource(config_name, value)
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
            dialog.Destroy()
            event.Skip()
        return OnAddResourceMenu


#-------------------------------------------------------------------------------
#                        Remove Project Elements Functions
#-------------------------------------------------------------------------------

    def OnRemoveDataTypeMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_DATATYPE:
            name = self.ProjectTree.GetItemText(selected)
            if not self.Controler.DataTypeIsUsed(name):
                self.Controler.ProjectRemoveDataType(name)
                tagname = self.Controler.ComputeDataTypeName(name)
                idx = self.IsOpened(tagname)
                if idx is not None:
                    self.DeletePage(idx)
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
                self.RefreshToolBar()
            else:
                message = wx.MessageDialog(self, "%s is used by one or more POUs. It can't be removed!"%selected, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
        event.Skip()

    def OnRemovePouMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_POU: 
            name = self.ProjectTree.GetItemText(selected)
            if not self.Controler.PouIsUsed(name):
                self.Controler.ProjectRemovePou(name)
                tagname = self.Controler.ComputePouName(name)
                idx = self.IsOpened(tagname)
                if idx is not None:
                    self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                    self.DeletePage(idx)
                self.RefreshTitle()
                self.RefreshEditMenu()
                self.RefreshProjectTree()
                self.RefreshToolBar()
            else:
                message = wx.MessageDialog(self, "%s is used by one or more POUs. It can't be removed!"%selected, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
        event.Skip()

    def OnRemoveConfigurationMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_CONFIGURATION: 
            name = self.ProjectTree.GetItemText(selected)
            self.Controler.ProjectRemoveConfiguration(name)
            tagname = self.Controler.ComputeConfigurationName(name)
            idx = self.IsOpened(tagname)
            if idx is not None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        event.Skip()

    def OnRemoveTransitionMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_TRANSITION: 
            transition = self.ProjectTree.GetItemText(selected)
            item = self.ProjectTree.GetItemParent(selected)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_POU:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            pou_name = self.ProjectTree.GetItemText(item)
            self.Controler.ProjectRemovePouTransition(pou_name, transition)
            tagname = self.Controler.ComputePouTransitionName(pou_name, transition)
            idx = self.IsOpened(tagname)
            if idx is not None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        event.Skip()

    def OnRemoveActionMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_ACTION: 
            action = self.ProjectTree.GetItemText(selected)
            item = self.ProjectTree.GetItemParent(selected)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_POU:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            pou_name = self.ProjectTree.GetItemText(item)
            self.Controler.ProjectRemovePouAction(pou_name, action)
            tagname = self.Controler.ComputePouActionName(pou_name, action)
            idx = self.IsOpened(tagname)
            if idx is not None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        event.Skip()

    def OnRemoveResourceMenu(self, event):
        selected = self.ProjectTree.GetSelection()
        if self.ProjectTree.GetPyData(selected) == ITEM_RESOURCE:
            resource = self.ProjectTree.GetItemText(selected)
            item = self.ProjectTree.GetItemParent(selected)
            item_type = self.ProjectTree.GetPyData(item)
            while item_type != ITEM_CONFIGURATION:
                item = self.ProjectTree.GetItemParent(item)
                item_type = self.ProjectTree.GetPyData(item)
            config_name = self.ProjectTree.GetItemText(item)
            self.Controler.ProjectRemoveConfigurationResource(config_name, resource)
            tagname = self.Controler.ComputeConfigurationResourceName(config_name, selected)
            idx = self.IsOpened(tagname)
            if idx is not None:
                self.VariablePanelIndexer.RemoveVariablePanel(tagname)
                self.DeletePage(idx)
            self.RefreshTitle()
            self.RefreshEditMenu()
            self.RefreshProjectTree()
        event.Skip()
    
    def OnPLCOpenEditorMenu(self, event):
        wx.MessageBox("No documentation available.\nComing soon.")
        #event.Skip()
        
    def OnPLCOpenMenu(self, event):
        open_pdf(os.path.join(CWD, "plcopen", "TC6_XML_V101.pdf"))
        event.Skip()
    
    def OnAboutMenu(self, event):
        OpenHtmlFrame(self,"About PLCOpenEditor", os.path.join(CWD, "doc","about.html"), wx.Size(350, 350))
        event.Skip()


#-------------------------------------------------------------------------------
#                        Errors showing functions
#-------------------------------------------------------------------------------

    def ShowError(self, infos, start, end):
        print infos
        self.EditProjectElement(self.Controler.GetElementType(infos[0]), infos[0])
        self.SelectProjectTreeItem(infos[0])
        if infos[1] == "name":
            self.Errors.append(infos[0])
            self.RefreshProjectTree()
            self.ProjectTree.Unselect()
        elif infos[1] == "variable":
            self.VariablePanelIndexer.AddVariableError(infos)
        else:
            selected = self.GetPageSelection()
            if selected != -1:
                viewer = self.GetPage(selected)
                viewer.AddShownError(infos[1:], start, end)
                viewer.RefreshView()
    
    def ClearErrors(self):
        self.Errors = []
        self.RefreshProjectTree()
        self.VariablePanelIndexer.ClearErrors()
        for i in xrange(self.GetPageCount()):
            viewer = self.GetPage(i)
            viewer.ClearErrors()
        
current_num = 0
def GetNewNum():
    global current_num
    current_num += 1
    return current_num

#-------------------------------------------------------------------------------
#                            Create Project Dialog
#-------------------------------------------------------------------------------

[ID_SCALINGPANEL, ID_SCALINGPANELXSCALE, 
 ID_SCALINGPANELYSCALE, ID_SCALINGPANELSTATICTEXT1, 
 ID_SCALINGPANELSTATICTEXT2, 
] = [wx.NewId() for _init_ctrls in range(5)]

class ScalingPanel(wx.Panel):
    
    def _init_coll_ScalingPanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
        parent.AddWindow(self.XScale, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
        parent.AddWindow(self.staticText2, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
        parent.AddWindow(self.YScale, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)

    def _init_coll_ScalingPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(1)

    def _init_sizers(self):
        self.ScalingPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=5)
        
        self._init_coll_ScalingPanelSizer_Items(self.ScalingPanelSizer)
        self._init_coll_ScalingPanelSizer_Growables(self.ScalingPanelSizer)

        self.SetSizer(self.ScalingPanelSizer)

    def _init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=ID_SCALINGPANEL,
              name='ScalingPanel', parent=prnt, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
        
        self.staticText1 = wx.StaticText(id=ID_SCALINGPANELSTATICTEXT1,
              label='X Scale:', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
        
        self.XScale = wx.SpinCtrl(id=ID_SCALINGPANELXSCALE,
              name='XScale', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0, min=0, max=2**16)
        
        self.staticText2 = wx.StaticText(id=ID_SCALINGPANELSTATICTEXT2,
              label='Y Scale:', name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
        
        self.YScale = wx.SpinCtrl(id=ID_SCALINGPANELYSCALE,
              name='YScale', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0, min=0, max=2**16)
        
        self._init_sizers()
        
    def __init__(self, parent):
        self._init_ctrls(parent)

    def SetScaling(self, x, y):
        self.XScale.SetValue(x)
        self.YScale.SetValue(y)
        
    def GetScaling(self):
        return self.XScale.GetValue(), self.YScale.GetValue()

[ID_PROJECTDIALOG, ID_PROJECTDIALOGMAINNOTEBOOK, 
 ID_PROJECTDIALOGPROJECTPANEL, ID_PROJECTDIALOGAUTHORPANEL, 
 ID_PROJECTDIALOGGRAPHICSPANEL, ID_PROJECTDIALOGMISCELLANEOUSPANEL, 
 ID_PROJECTDIALOGPROJECTNAME, ID_PROJECTDIALOGPROJECTVERSION, 
 ID_PROJECTDIALOGPRODUCTNAME, ID_PROJECTDIALOGPRODUCTVERSION, 
 ID_PROJECTDIALOGPRODUCTRELEASE, ID_PROJECTDIALOGCOMPANYNAME, 
 ID_PROJECTDIALOGCOMPANYURL, ID_PROJECTDIALOGAUTHORNAME, 
 ID_PROJECTDIALOGORGANIZATION, ID_PROJECTDIALOGLANGUAGE, 
 ID_PROJECTDIALOGCONTENTDESCRIPTION, ID_PROJECTDIALOGSCALINGNOTEBOOK, 
 ID_PROJECTDIALOGPAGEWIDTH, ID_PROJECTDIALOGPAGEHEIGHT, 
 ID_PROJECTDIALOGSTATICTEXT1, ID_PROJECTDIALOGSTATICTEXT2, 
 ID_PROJECTDIALOGSTATICTEXT3, ID_PROJECTDIALOGSTATICTEXT4, 
 ID_PROJECTDIALOGSTATICTEXT5, ID_PROJECTDIALOGSTATICTEXT6, 
 ID_PROJECTDIALOGSTATICTEXT7, ID_PROJECTDIALOGSTATICTEXT8, 
 ID_PROJECTDIALOGSTATICTEXT9, ID_PROJECTDIALOGSTATICTEXT10, 
 ID_PROJECTDIALOGSTATICTEXT11, ID_PROJECTDIALOGSTATICTEXT12, 
 ID_PROJECTDIALOGSTATICTEXT13, ID_PROJECTDIALOGSTATICTEXT14, 
 ID_PROJECTDIALOGSTATICTEXT15, 
] = [wx.NewId() for _init_ctrls in range(35)]

class ProjectDialog(wx.Dialog):
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
                
    def _init_coll_flexGridSizer1_Items(self, parent):
        parent.AddSizer(self.MainNotebook, 0, border=0, flag=wx.GROW)
        parent.AddSizer(self.ButtonSizer, 0, border=20, flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_flexGridSizer1_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_ProjectPanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
        parent.AddWindow(self.ProjectName, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
        parent.AddWindow(self.staticText2, 0, border=10, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.ProjectVersion, 0, border=10, flag=wx.GROW|wx.RIGHT)
        parent.AddWindow(self.staticText3, 0, border=10, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.ProductName, 0, border=10, flag=wx.GROW|wx.RIGHT)
        parent.AddWindow(self.staticText4, 0, border=10, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.ProductVersion, 0, border=10, flag=wx.GROW|wx.RIGHT)
        parent.AddWindow(self.staticText5, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
        parent.AddWindow(self.ProductRelease, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
        
    def _init_coll_ProjectPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(1)

    def _init_coll_AuthorPanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText6, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
        parent.AddWindow(self.CompanyName, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
        parent.AddWindow(self.staticText7, 0, border=10, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.CompanyURL, 0, border=10, flag=wx.GROW|wx.RIGHT)
        parent.AddWindow(self.staticText8, 0, border=10, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.AuthorName, 0, border=10, flag=wx.GROW|wx.RIGHT)
        parent.AddWindow(self.staticText9, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
        parent.AddWindow(self.Organization, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
    
    def _init_coll_AuthorPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
    
    def _init_coll_GraphicsPanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText12, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
        parent.AddSizer(self.GraphicsPageSizeSizer, 0, border=10, flag=wx.GROW|wx.LEFT|wx.RIGHT)
        parent.AddWindow(self.staticText15, 0, border=10, flag=wx.GROW|wx.LEFT|wx.RIGHT)
        parent.AddWindow(self.ScalingNotebook, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_GraphicsPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(3)
    
    def _init_coll_GraphicsPageSizeSizer_Items(self, parent):
        parent.AddWindow(self.staticText13, 0, border=12, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.PageWidth, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText14, 0, border=12, flag=wx.GROW|wx.LEFT)
        parent.AddWindow(self.PageHeight, 0, border=0, flag=wx.GROW)
    
    def _init_coll_GraphicsPageSizeSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
    
    def _init_coll_MiscellaneousPanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText10, 0, border=10, flag=wx.GROW|wx.TOP|wx.LEFT)
        parent.AddWindow(self.Language, 0, border=10, flag=wx.GROW|wx.TOP|wx.RIGHT)
        parent.AddWindow(self.staticText11, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.LEFT)
        parent.AddWindow(self.ContentDescription, 0, border=10, flag=wx.GROW|wx.BOTTOM|wx.RIGHT)
        
    def _init_coll_MiscellaneousPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
        parent.AddGrowableRow(1)
        
    def _init_sizers(self):
        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.ProjectPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=5, vgap=15)
        self.AuthorPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=4, vgap=15)
        self.GraphicsPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=4, vgap=5)
        self.GraphicsPageSizeSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=5)
        self.MiscellaneousPanelSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)

        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
        self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
        self._init_coll_ProjectPanelSizer_Items(self.ProjectPanelSizer)
        self._init_coll_ProjectPanelSizer_Growables(self.ProjectPanelSizer)
        self._init_coll_AuthorPanelSizer_Items(self.AuthorPanelSizer)
        self._init_coll_AuthorPanelSizer_Growables(self.AuthorPanelSizer)
        self._init_coll_GraphicsPanelSizer_Items(self.GraphicsPanelSizer)
        self._init_coll_GraphicsPanelSizer_Growables(self.GraphicsPanelSizer)
        self._init_coll_GraphicsPageSizeSizer_Items(self.GraphicsPageSizeSizer)
        self._init_coll_GraphicsPageSizeSizer_Growables(self.GraphicsPageSizeSizer)
        self._init_coll_MiscellaneousPanelSizer_Items(self.MiscellaneousPanelSizer)
        self._init_coll_MiscellaneousPanelSizer_Growables(self.MiscellaneousPanelSizer)

        self.SetSizer(self.flexGridSizer1)
        self.ProjectPanel.SetSizer(self.ProjectPanelSizer)
        self.AuthorPanel.SetSizer(self.AuthorPanelSizer)
        self.GraphicsPanel.SetSizer(self.GraphicsPanelSizer)
        self.MiscellaneousPanel.SetSizer(self.MiscellaneousPanelSizer)

    def _init_ctrls(self, prnt):
        wx.Dialog.__init__(self, id=ID_PROJECTDIALOG,
              name='ProjectDialog', parent=prnt, pos=wx.Point(376, 223),
              size=wx.Size(500, 350), style=wx.DEFAULT_DIALOG_STYLE,
              title='Create a new project')
        self.SetClientSize(wx.Size(500, 350))

        self.MainNotebook = wx.Notebook(id=ID_PROJECTDIALOGMAINNOTEBOOK,
                  name='MainNotebook', parent=self, pos=wx.Point(0,
                  0), size=wx.Size(0, 0), style=0)

        # Project Panel elements

        self.ProjectPanel = wx.Panel(id=ID_PROJECTDIALOGPROJECTPANEL,
              name='ProjectPanel', parent=self.MainNotebook, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.staticText1 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT1,
              label='Project Name (required):', name='staticText1', parent=self.ProjectPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ProjectName = wx.TextCtrl(id=ID_PROJECTDIALOGPROJECTNAME,
              name='ProjectName', parent=self.ProjectPanel, pos=wx.Point(0, 0), 
              size=wx.Size(0, 24), style=0)

        self.staticText2 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT2,
              label='Project Version (optional):', name='staticText2', parent=self.ProjectPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ProjectVersion = wx.TextCtrl(id=ID_PROJECTDIALOGPROJECTVERSION,
              name='ProjectVersion', parent=self.ProjectPanel, pos=wx.Point(0, 0), 
              size=wx.Size(0, 24), style=0)

        self.staticText3 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT3,
              label='Product Name (required):', name='staticText3', parent=self.ProjectPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ProductName = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTNAME,
              name='ProductName', parent=self.ProjectPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText4 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT4,
              label='Product Version (required):', name='staticText4', parent=self.ProjectPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ProductVersion = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTVERSION,
              name='ProductVersion', parent=self.ProjectPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText5 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT5,
              label='Product Release (optional):', name='staticText5', parent=self.ProjectPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ProductRelease = wx.TextCtrl(id=ID_PROJECTDIALOGPRODUCTRELEASE,
              name='ProductRelease', parent=self.ProjectPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.MainNotebook.AddPage(self.ProjectPanel, "Project")
        
        # Author Panel elements

        self.AuthorPanel = wx.Panel(id=ID_PROJECTDIALOGAUTHORPANEL,
              name='AuthorPanel', parent=self.MainNotebook, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.staticText6 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT6,
              label='Company Name (required):', name='staticText6', parent=self.AuthorPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.CompanyName = wx.TextCtrl(id=ID_PROJECTDIALOGCOMPANYNAME,
              name='CompanyName', parent=self.AuthorPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText7 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT7,
              label='Company URL (optional):', name='staticText7', parent=self.AuthorPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.CompanyURL = wx.TextCtrl(id=ID_PROJECTDIALOGCOMPANYURL,
              name='CompanyURL', parent=self.AuthorPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText8 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT8,
              label='Author Name (optional):', name='staticText8', parent=self.AuthorPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.AuthorName = wx.TextCtrl(id=ID_PROJECTDIALOGAUTHORNAME,
              name='AuthorName', parent=self.AuthorPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText9 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT9,
              label='Organization (optional):', name='staticText9', parent=self.AuthorPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.Organization = wx.TextCtrl(id=ID_PROJECTDIALOGORGANIZATION,
              name='Organization', parent=self.AuthorPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.MainNotebook.AddPage(self.AuthorPanel, "Author")

        # Graphics Panel elements

        self.GraphicsPanel = wx.Panel(id=ID_PROJECTDIALOGGRAPHICSPANEL,
              name='GraphicsPanel', parent=self.MainNotebook, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.staticText12 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT12,
              label='Page Size (optional):', name='staticText12', parent=self.GraphicsPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.staticText13 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT13,
              label='Width:', name='staticText13', parent=self.GraphicsPanel,
              pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
        
        self.PageWidth = wx.SpinCtrl(id=ID_PROJECTDIALOGPAGEWIDTH,
              name='PageWidth', parent=self.GraphicsPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0, min=0, max=2**16)

        self.staticText14 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT14,
              label='Height:', name='staticText14', parent=self.GraphicsPanel,
              pos=wx.Point(0, 0), size=wx.Size(150, 17), style=0)
        
        self.PageHeight = wx.SpinCtrl(id=ID_PROJECTDIALOGPAGEHEIGHT,
              name='PageHeight', parent=self.GraphicsPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0, min=0, max=2**16)
        
        self.staticText15 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT15,
              label='Scaling:', name='staticText15', parent=self.GraphicsPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)
        
        self.ScalingNotebook = wx.Notebook(id=ID_PROJECTDIALOGSCALINGNOTEBOOK,
              name='ScalingNotebook', parent=self.GraphicsPanel, pos=wx.Point(0,
              0), size=wx.Size(0, 0), style=0)
        
        self.Scalings = {}
        for language in ["FBD", "LD", "SFC"]:
            window = ScalingPanel(self.ScalingNotebook)
            self.Scalings[language] = window
            self.ScalingNotebook.AddPage(window, language)
        
        self.MainNotebook.AddPage(self.GraphicsPanel, "Graphics")

        # Miscellaneous Panel elements

        self.MiscellaneousPanel = wx.Panel(id=ID_PROJECTDIALOGMISCELLANEOUSPANEL,
              name='MiscellaneousPanel', parent=self.MainNotebook, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)

        self.staticText10 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT10,
              label='Language (optional):', name='staticText10', parent=self.MiscellaneousPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.Language = wx.Choice(id=ID_PROJECTDIALOGLANGUAGE,
              name='Language', parent=self.MiscellaneousPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText11 = wx.StaticText(id=ID_PROJECTDIALOGSTATICTEXT11,
              label='Content Description (optional):', name='staticText11', parent=self.MiscellaneousPanel,
              pos=wx.Point(0, 0), size=wx.Size(200, 17), style=0)

        self.ContentDescription = wx.TextCtrl(id=ID_PROJECTDIALOGCONTENTDESCRIPTION,
              name='ContentDescription', parent=self.MiscellaneousPanel, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=wx.TE_MULTILINE)

        self.MainNotebook.AddPage(self.MiscellaneousPanel, "Miscellaneous")

        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
        
        self._init_sizers()

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        languages = ["", "en-US", "fr-FR"]
        
        for language in languages:
            self.Language.Append(language)
        
    def OnOK(self, event):
        error = []
        if self.ProjectName.GetValue() == "":
            error.append("Project Name")
        if self.CompanyName.GetValue() == "":
            error.append("Company Name")
        if self.ProductName.GetValue() == "":
            error.append("Product Name")
        if self.ProductVersion.GetValue() == "":
            error.append("Product Version")
        if len(error) > 0:
            text = ""
            for i, item in enumerate(error):
                if i == 0:
                    text += item
                elif i == len(error) - 1:
                    text += " and %s"%item
                else:
                    text += ", %s"%item
            message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)

    def SetValues(self, values):
        for item, value in values.items():
            if item == "projectName":
                self.ProjectName.SetValue(value)
            elif item == "projectVersion":
                self.ProjectVersion.SetValue(value)
            elif item == "productName":
                self.ProductName.SetValue(value)
            elif item == "productVersion":
                self.ProductVersion.SetValue(value)
            elif item == "productRelease":
                self.ProductRelease.SetValue(value)
            elif item == "companyName":
                self.CompanyName.SetValue(value)
            elif item == "companyURL":
                self.CompanyURL.SetValue(value)
            elif item == "authorName":
                self.AuthorName.SetValue(value)
            elif item == "organization":
                self.Organization.SetValue(value)
            elif item == "language":
                self.Language.SetStringSelection(value)
            elif item == "contentDescription":
                self.ContentDescription.SetValue(value)
            elif item == "pageSize":
                self.PageWidth.SetValue(value[0])
                self.PageHeight.SetValue(value[1])
            elif item == "scaling":
                for language, (x, y) in value.items():
                    if language in self.Scalings:
                        self.Scalings[language].SetScaling(x, y)
    
    def GetValues(self):
        values = {}
        values["projectName"] = self.ProjectName.GetValue()
        if self.ProjectVersion.GetValue() != "":
            values["projectVersion"] = self.ProjectVersion.GetValue()
        values["productName"] = self.ProductName.GetValue()
        values["productVersion"] = self.ProductVersion.GetValue()
        if self.ProductRelease.GetValue() != "":
            values["productRelease"] = self.ProductRelease.GetValue()
        values["companyName"] = self.CompanyName.GetValue()
        if self.CompanyURL.GetValue() != "":
            values["companyURL"] = self.CompanyURL.GetValue()
        if self.AuthorName.GetValue() != "":
            values["authorName"] = self.AuthorName.GetValue()
        if self.Organization.GetValue() != "":
            values["organization"] = self.Organization.GetValue()
        if self.Language.GetStringSelection() != "":
            values["language"] = self.Language.GetStringSelection()
        if self.ProductRelease.GetValue() != "":
            values["contentDescription"] = self.ContentDescription.GetValue()
        values["pageSize"] = (self.PageWidth.GetValue(), self.PageHeight.GetValue())
        values["scaling"] = {}
        for language in ["FBD", "LD", "SFC"]:
            values["scaling"][language] = self.Scalings[language].GetScaling()
        return values

#-------------------------------------------------------------------------------
#                          Edit Step Name Dialog
#-------------------------------------------------------------------------------

class DataTypeDialog(wx.TextEntryDialog):

    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    

    def __init__(self, parent, message, caption = "Please enter text", defaultValue = "", 
                       style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
        wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
        
        self.DataTypeNames = []
        if wx.VERSION >= (2, 8, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(2).GetSizer().GetItem(1).GetSizer().GetAffirmativeButton().GetId())
        elif wx.VERSION >= (2, 6, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetAffirmativeButton().GetId())
        else:
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId())
    
    def OnOK(self, event):
        datatype_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
        if datatype_name == "":
            message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(datatype_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif datatype_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif datatype_name.upper() in self.DataTypeNames:
            message = wx.MessageDialog(self, "\"%s\" data type already exists!"%datatype_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)

    def SetDataTypeNames(self, datatype_names):
        self.DataTypeNames = [datatype_name.upper() for datatype_name in datatype_names]

    def GetValue(self):
        return self.GetSizer().GetItem(1).GetWindow().GetValue()

#-------------------------------------------------------------------------------
#                            Create Pou Dialog
#-------------------------------------------------------------------------------

[ID_POUDIALOG, ID_POUDIALOGPOUNAME, 
 ID_POUDIALOGPOUTYPE, ID_POUDIALOGLANGUAGE, ID_POUDIALOGSTATICTEXT1,
 ID_POUDIALOGSTATICTEXT2, ID_POUDIALOGSTATICTEXT3, 
] = [wx.NewId() for _init_ctrls in range(7)]

class PouDialog(wx.Dialog):
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_flexGridSizer1_Items(self, parent):
        parent.AddSizer(self.MainSizer, 0, border=20, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
        parent.AddSizer(self.ButtonSizer, 0, border=20, flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_flexGridSizer1_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.PouName, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.PouType, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText3, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
        
    def _init_sizers(self):
        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=3, vgap=15)

        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
        self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)

        self.SetSizer(self.flexGridSizer1)
        
    def _init_ctrls(self, prnt):
        wx.Dialog.__init__(self, id=ID_POUDIALOG,
              name='PouDialog', parent=prnt, pos=wx.Point(376, 223),
              size=wx.Size(300, 200), style=wx.DEFAULT_DIALOG_STYLE,
              title='Create a new POU')
        self.SetClientSize(wx.Size(300, 200))

        self.staticText1 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT1,
              label='POU Name:', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)

        self.PouName = wx.TextCtrl(id=ID_POUDIALOGPOUNAME,
              name='POUName', parent=self, pos=wx.Point(0, 0), 
              size=wx.Size(0, 24), style=0)

        self.staticText2 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT2,
              label='POU Type:', name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)

        self.PouType = wx.Choice(id=ID_POUDIALOGPOUTYPE,
              name='POUType', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)
        self.Bind(wx.EVT_CHOICE, self.OnTypeChanged, id=ID_POUDIALOGPOUTYPE)

        self.staticText3 = wx.StaticText(id=ID_POUDIALOGSTATICTEXT3,
              label='Language:', name='staticText3', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)

        self.Language = wx.Choice(id=ID_POUDIALOGLANGUAGE,
              name='Language', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)
        
        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
            
        self._init_sizers()

    def __init__(self, parent, pou_type = None):
        self._init_ctrls(parent)
        
        for option in ["function", "functionBlock", "program"]:
            self.PouType.Append(option)
        if pou_type is not None:
            self.PouType.SetStringSelection(pou_type)
        self.RefreshLanguage()

        self.PouNames = []
        self.PouElementNames = []

    def OnOK(self, event):
        error = []
        pou_name = self.PouName.GetValue()
        if pou_name == "":
            error.append("POU Name")
        if self.PouType.GetStringSelection() == "":
            error.append("POU Type")
        if self.Language.GetStringSelection() == "":
            error.append("Language")
        if len(error) > 0:
            text = ""
            for i, item in enumerate(error):
                if i == 0:
                    text += item
                elif i == len(error) - 1:
                    text += " and %s"%item
                else:
                    text += ", %s"%item 
            message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(pou_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif pou_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif pou_name.upper() in self.PouNames:
            message = wx.MessageDialog(self, "\"%s\" pou already exists!"%pou_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif pou_name.upper() in self.PouElementNames:
            message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%pou_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
            result = message.ShowModal()
            message.Destroy()
            if result == wx.ID_YES:
                self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_OK)

    def RefreshLanguage(self):
        selection = self.Language.GetStringSelection()
        self.Language.Clear()
        for option in ["IL","ST","LD","FBD","SFC"]:
            if option != "SFC" or self.PouType.GetStringSelection() != "function":
                self.Language.Append(option)
        if self.Language.FindString(selection) != wx.NOT_FOUND:
            self.Language.SetStringSelection(selection)

    def OnTypeChanged(self, event):
        self.RefreshLanguage()
        event.Skip()

    def SetPouNames(self, pou_names):
        self.PouNames = [pou_name.upper() for pou_name in pou_names]

    def SetPouElementNames(self, element_names):
        self.PouElementNames = [element_name.upper() for element_name in element_names]

    def SetValues(self, values):
        for item, value in values.items():
            if item == "pouName":
                self.PouName.SetValue(value)
            elif item == "pouType":
                self.PouType.SetStringSelection(value)
            elif item == "language":
                self.Language.SetStringSelection(value)
                
    def GetValues(self):
        values = {}
        values["pouName"] = self.PouName.GetValue()
        values["pouType"] = self.PouType.GetStringSelection()
        values["language"] = self.Language.GetStringSelection()
        return values


#-------------------------------------------------------------------------------
#                          Create Pou Transition Dialog
#-------------------------------------------------------------------------------

[ID_POUTRANSITIONDIALOG, ID_POUTRANSITIONDIALOGTRANSITIONNAME, 
 ID_POUTRANSITIONDIALOGLANGUAGE, ID_POUTRANSITIONDIALOGSTATICTEXT1, 
 ID_POUTRANSITIONDIALOGSTATICTEXT2,
] = [wx.NewId() for _init_ctrls in range(5)]

class PouTransitionDialog(wx.Dialog):
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_flexGridSizer1_Items(self, parent):
        parent.AddSizer(self.MainSizer, 0, border=20, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
        parent.AddSizer(self.ButtonSizer, 0, border=20, flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_flexGridSizer1_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.TransitionName, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
        
    def _init_sizers(self):
        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)

        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
        self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)

        self.SetSizer(self.flexGridSizer1)

    def _init_ctrls(self, prnt):
        wx.Dialog.__init__(self, id=ID_POUTRANSITIONDIALOG,
              name='PouTransitionDialog', parent=prnt, pos=wx.Point(376, 223),
              size=wx.Size(350, 200), style=wx.DEFAULT_DIALOG_STYLE,
              title='Create a new transition')
        self.SetClientSize(wx.Size(350, 160))

        self.staticText1 = wx.StaticText(id=ID_POUTRANSITIONDIALOGSTATICTEXT1,
              label='Transition Name:', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(120, 17), style=0)

        self.TransitionName = wx.TextCtrl(id=ID_POUTRANSITIONDIALOGTRANSITIONNAME,
              name='TransitionName', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText2 = wx.StaticText(id=ID_POUTRANSITIONDIALOGSTATICTEXT2,
              label='Language:', name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(120, 17), style=0)

        self.Language = wx.Choice(id=ID_POUTRANSITIONDIALOGLANGUAGE,
              name='Language', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)
        
        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
        
        self._init_sizers()

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        for option in ["IL","ST","LD","FBD"]:
            self.Language.Append(option)
            
        self.PouNames = []
        self.PouElementNames = []
        
    def OnOK(self, event):
        error = []
        transition_name = self.TransitionName.GetValue()
        if self.TransitionName.GetValue() == "":
            error.append("Transition Name")
        if self.Language.GetStringSelection() == "":
            error.append("Language")
        if len(error) > 0:
            text = ""
            for i, item in enumerate(error):
                if i == 0:
                    text += item
                elif i == len(error) - 1:
                    text += " and %s"%item
                else:
                    text += ", %s"%item 
            message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(transition_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif transition_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif transition_name.upper() in self.PouNames:
            message = wx.MessageDialog(self, "A pou with \"%s\" for name exists!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif transition_name.upper() in self.PouElementNames:
            message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%transition_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)
    
    def SetPouNames(self, pou_names):
        self.PouNames = [pou_name.upper() for pou_name in pou_names]
    
    def SetPouElementNames(self, pou_names):
        self.PouElementNames = [pou_name.upper() for pou_name in pou_names]
    
    def SetValues(self, values):
        for item, value in values.items():
            if item == "transitionName":
                self.TransitionName.SetValue(value)
            elif item == "language":
                self.Language.SetStringSelection(value)
                
    def GetValues(self):
        values = {}
        values["transitionName"] = self.TransitionName.GetValue()
        values["language"] = self.Language.GetStringSelection()
        return values

#-------------------------------------------------------------------------------
#                          Create Pou Action Dialog
#-------------------------------------------------------------------------------

[ID_POUACTIONDIALOG, ID_POUACTIONDIALOGACTIONNAME, 
 ID_POUACTIONDIALOGLANGUAGE, ID_POUACTIONDIALOGSTATICTEXT1, 
 ID_POUACTIONDIALOGSTATICTEXT2, 
] = [wx.NewId() for _init_ctrls in range(5)]

class PouActionDialog(wx.Dialog):
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_flexGridSizer1_Items(self, parent):
        parent.AddSizer(self.MainSizer, 0, border=20, flag=wx.GROW|wx.TOP|wx.LEFT|wx.RIGHT)
        parent.AddSizer(self.ButtonSizer, 0, border=20, flag=wx.ALIGN_RIGHT|wx.BOTTOM|wx.LEFT|wx.RIGHT)
        
    def _init_coll_flexGridSizer1_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.ActionName, 0, border=0, flag=wx.GROW)
        parent.AddWindow(self.staticText2, 0, border=4, flag=wx.GROW|wx.TOP)
        parent.AddWindow(self.Language, 0, border=0, flag=wx.GROW)
        
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(1)
        
    def _init_sizers(self):
        self.flexGridSizer1 = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=0, rows=2, vgap=15)

        self._init_coll_flexGridSizer1_Items(self.flexGridSizer1)
        self._init_coll_flexGridSizer1_Growables(self.flexGridSizer1)
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)

        self.SetSizer(self.flexGridSizer1)

    def _init_ctrls(self, prnt):
        wx.Dialog.__init__(self, id=ID_POUACTIONDIALOG,
              name='PouActionDialog', parent=prnt, pos=wx.Point(376, 223),
              size=wx.Size(320, 200), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
              title='Create a new action')
        self.SetClientSize(wx.Size(320, 160))

        self.staticText1 = wx.StaticText(id=ID_POUACTIONDIALOGSTATICTEXT1,
              label='Action Name:', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)

        self.ActionName = wx.TextCtrl(id=ID_POUACTIONDIALOGACTIONNAME,
              name='ActionName', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)

        self.staticText2 = wx.StaticText(id=ID_POUACTIONDIALOGSTATICTEXT2,
              label='Language:', name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(100, 17), style=0)

        self.Language = wx.Choice(id=ID_POUACTIONDIALOGLANGUAGE,
              name='Language', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(0, 24), style=0)
        
        self.ButtonSizer = self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.CENTRE)
        self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.ButtonSizer.GetAffirmativeButton().GetId())
        
        self._init_sizers()

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        for option in ["IL","ST","LD","FBD"]:
            self.Language.Append(option)
        
        self.PouNames = []
        self.PouElementNames = []
    
    def OnOK(self, event):
        error = []
        action_name = self.ActionName.GetValue()
        if action_name == "":
            error.append("Action Name")
        if self.Language.GetStringSelection() == "":
            error.append("Language")
        if len(error) > 0:
            text = ""
            for i, item in enumerate(error):
                if i == 0:
                    text += item
                elif i == len(error) - 1:
                    text += " and %s"%item
                else:
                    text += ", %s"%item 
            message = wx.MessageDialog(self, "Form isn't complete. %s must be filled!"%text, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(action_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif action_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif action_name.upper() in self.PouNames:
            message = wx.MessageDialog(self, "A pou with \"%s\" for name exists!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif action_name.upper() in self.PouElementNames:
            message = wx.MessageDialog(self, "\"%s\" element for this pou already exists!"%action_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        else:
            self.EndModal(wx.ID_OK)
    
    def SetPouNames(self, pou_names):
        self.PouNames = [pou_name.upper() for pou_name in pou_names]
        
    def SetPouElementNames(self, element_names):
        self.PouElementNames = [element_name.upper() for element_name in element_names]
        
    def SetValues(self, values):
        for item, value in values.items():
            if item == "actionName":
                self.ActionName.SetValue(value)
            elif item == "language":
                self.Language.SetStringSelection(value)
                
    def GetValues(self):
        values = {}
        values["actionName"] = self.ActionName.GetValue()
        values["language"] = self.Language.GetStringSelection()
        return values

#-------------------------------------------------------------------------------
#                          Configuration Name Dialog
#-------------------------------------------------------------------------------

class ConfigurationNameDialog(wx.TextEntryDialog):

    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)

    def __init__(self, parent, message, caption = "Please enter configuration name", defaultValue = "", 
                       style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
        wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
        
        self.PouNames = []
        self.PouElementNames = []
        
        if wx.VERSION >= (2, 8, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(2).GetSizer().GetItem(1).GetSizer().GetAffirmativeButton().GetId())
        elif wx.VERSION >= (2, 6, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetAffirmativeButton().GetId())
        else:
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId())
    
    def OnOK(self, event):
        config_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
        if config_name == "":
            message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(config_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif config_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif config_name.upper() in self.PouNames:
            message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%config_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif config_name.upper() in self.PouElementNames:
            message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%config_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
            result = message.ShowModal()
            message.Destroy()
            if result == wx.ID_YES:
                self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_OK)

    def SetPouNames(self, pou_names):
        self.PouNames = [pou_name.upper() for pou_name in pou_names]
    
    def SetPouElementNames(self, pou_names):
        self.PouElementNames = [pou_name.upper() for pou_name in pou_names]
    
    def GetValue(self):
        return self.GetSizer().GetItem(1).GetWindow().GetValue()

#-------------------------------------------------------------------------------
#                          Resource Name Dialog
#-------------------------------------------------------------------------------

class ResourceNameDialog(wx.TextEntryDialog):

    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)

    def __init__(self, parent, message, caption = "Please enter resource name", defaultValue = "", 
                       style = wx.OK|wx.CANCEL|wx.CENTRE, pos = wx.DefaultPosition):
        wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos)
        
        self.PouNames = []
        self.PouElementNames = []
        
        if wx.VERSION >= (2, 8, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(2).GetSizer().GetItem(1).GetSizer().GetAffirmativeButton().GetId())
        elif wx.VERSION >= (2, 6, 0):
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetAffirmativeButton().GetId())
        else:
            self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId())

    def OnOK(self, event):
        resource_name = self.GetSizer().GetItem(1).GetWindow().GetValue()
        if resource_name == "":
            message = wx.MessageDialog(self, "You must type a name!", "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif not TestIdentifier(resource_name):
            message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif resource_name.upper() in IEC_KEYWORDS:
            message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif resource_name.upper() in self.PouNames:
            message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%resource_name, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        elif resource_name.upper() in self.PouElementNames:
            message = wx.MessageDialog(self, "A pou has an element with \"%s\" for name. It can generate a conflict. Do you wish to continue?"%resource_name, "Warning", wx.YES_NO|wx.ICON_EXCLAMATION)
            result = message.ShowModal()
            message.Destroy()
            if result == wx.ID_YES:
                self.EndModal(wx.ID_OK)
        else:
            self.EndModal(wx.ID_OK)

    def SetPouNames(self, pou_names):
        self.PouNames = [pou_name.upper() for pou_name in pou_names]
    
    def SetPouElementNames(self, pou_names):
        self.PouElementNames = [pou_name.upper() for pou_name in pou_names]
    
    def GetValue(self):
        return self.GetSizer().GetItem(1).GetWindow().GetValue()

#-------------------------------------------------------------------------------
#                            Variables Editor Panel
#-------------------------------------------------------------------------------

class VariablePanelIndexer(wx.Panel):
    
    def _init_sizers(self):
        self.MainSizer = wx.BoxSizer(wx.HORIZONTAL)
        
        self.SetSizer(self.MainSizer)
    
    def _init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=wx.NewId(),
              name='VariablePanelIndexer', parent=prnt, pos=wx.Point(0, 0),
              size=wx.Size(0, 300), style=wx.TAB_TRAVERSAL)
        
        self._init_sizers()
    
    def __init__(self, parent, window, controler):
        self._init_ctrls(parent)
        
        self.ParentWindow = window
        self.Controler = controler
        
        self.VariablePanelList = {}
        self.CurrentPanel = None
        
    def AddVariablePanel(self, tagname, element_type):
        new_panel = VariablePanel(self, self.ParentWindow, self.Controler, element_type)
        new_panel.SetTagName(tagname)
        new_panel.Hide()
        new_panel.RefreshView()
        self.MainSizer.AddWindow(new_panel, 1, border=0, flag=wx.GROW)
        self.VariablePanelList[tagname] = new_panel
        
    def RemoveVariablePanel(self, tagname):
        if tagname in self.VariablePanelList:
            panel = self.VariablePanelList.pop(tagname)
            panel.Hide()
            self.MainSizer.Remove(panel)
            if self.CurrentPanel == tagname:
                self.CurrentPanel = None
    
    def RemoveAllPanels(self):
        if self.CurrentPanel is not None and self.CurrentPanel in self.VariablePanelList:
            self.VariablePanelList[self.CurrentPanel].Hide()
        self.VariablePanelList = {}
        self.MainSizer.Clear()
        self.CurrentPanel = None
    
    def UpdateVariablePanelTagName(self, old_tagname, new_tagname):
        if old_tagname in self.VariablePanelList:
            self.VariablePanelList[new_tagname] = self.VariablePanelList.pop(old_tagname)
            if self.CurrentPanel == old_tagname:
                self.CurrentPanel = new_tagname
                
    def ChangeVariablePanel(self, tagname):
        if tagname in self.VariablePanelList:
            if tagname != self.CurrentPanel:
                if self.CurrentPanel is not None:
                    self.VariablePanelList[self.CurrentPanel].Hide()
                self.CurrentPanel = tagname
                self.VariablePanelList[self.CurrentPanel].RefreshView()
                self.VariablePanelList[self.CurrentPanel].Show()
                self.MainSizer.Layout()
        else:
            if self.CurrentPanel is not None:
                self.VariablePanelList[self.CurrentPanel].Hide()
            self.CurrentPanel = None
            self.MainSizer.Layout()

    def RefreshVariablePanel(self, tagname):
        if tagname in self.VariablePanelList:
            self.VariablePanelList[self.CurrentPanel].RefreshView()

    def AddVariableError(self, infos):
        self.ChangeVariablePanel(infos[0])
        if self.CurrentPanel is not None:
            self.VariablePanelList[self.CurrentPanel].AddVariableError(infos[2:])

    def ClearErrors(self):
        for panel in self.VariablePanelList.values():
            panel.ClearErrors()

#-------------------------------------------------------------------------------
#                            Variables Editor Panel
#-------------------------------------------------------------------------------

class VariableTable(wx.grid.PyGridTableBase):
    
    """
    A custom wx.grid.Grid Table using user supplied data
    """
    def __init__(self, parent, data, colnames):
        # The base class must be initialized *first*
        wx.grid.PyGridTableBase.__init__(self)
        self.data = data
        self.old_value = None
        self.colnames = colnames
        self.Errors = {}
        self.Parent = parent
        # XXX
        # 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):
        return len(self.data)

    def GetColLabelValue(self, col):
        if col < len(self.colnames):
            return self.colnames[col]

    def GetRowLabelValues(self, row):
        return row

    def GetValue(self, row, col):
        if row < self.GetNumberRows():
            if col == 0:
                return self.data[row]["Number"]
            name = str(self.data[row].get(self.GetColLabelValue(col), ""))
            return name
    
    def SetValue(self, row, col, value):
        if col < len(self.colnames):
            colname = self.GetColLabelValue(col)
            if colname == "Name":
                self.old_value = self.data[row][colname]
            self.data[row][colname] = value
    
    def GetValueByName(self, row, colname):
        if row < self.GetNumberRows():
            return self.data[row].get(colname)

    def SetValueByName(self, row, colname, value):
        if row < self.GetNumberRows():
            self.data[row][colname] = value

    def GetOldValue(self):
        return self.old_value
    
    def ResetView(self, grid):
        """
        (wx.grid.Grid) -> Reset the grid view.   Call this to
        update the grid if rows and columns have been added or deleted
        """
        grid.BeginBatch()
        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),
        ]:
            if new < current:
                msg = wx.grid.GridTableMessage(self,delmsg,new,current-new)
                grid.ProcessTableMessage(msg)
            elif new > current:
                msg = wx.grid.GridTableMessage(self,addmsg,new-current)
                grid.ProcessTableMessage(msg)
                self.UpdateValues(grid)
        grid.EndBatch()

        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()
        grid.ForceRefresh()

    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):
        """
        wx.grid.Grid -> update the column attributes to add the
        appropriate renderer given the column name.

        Otherwise default to the default renderer.
        """
        
        typelist = None
        accesslist = None
        for row in range(self.GetNumberRows()):
            for col in range(self.GetNumberCols()):
                editor = None
                renderer = None
                colname = self.GetColLabelValue(col)
                if col != 0 and self.GetValueByName(row, "Edit"):
                    grid.SetReadOnly(row, col, False)
                    if colname == "Name":
                        if self.Parent.PouIsUsed and self.GetValueByName(row, "Class") in ["Input", "Output", "InOut"]:
                            grid.SetReadOnly(row, col, True)
                        else:
                            editor = wx.grid.GridCellTextEditor()
                            renderer = wx.grid.GridCellStringRenderer()
                    elif colname == "Initial Value":
                        editor = wx.grid.GridCellTextEditor()
                        renderer = wx.grid.GridCellStringRenderer()
                    elif colname == "Location":
                        if self.GetValueByName(row, "Class") in ["Local", "Global"]:
                            editor = wx.grid.GridCellTextEditor()
                            renderer = wx.grid.GridCellStringRenderer()
                        else:
                            grid.SetReadOnly(row, col, True)
                    elif colname == "Class":
                        if len(self.Parent.ClassList) == 1 or self.Parent.PouIsUsed and self.GetValueByName(row, "Class") in ["Input", "Output", "InOut"]:
                            grid.SetReadOnly(row, col, True)
                        else:
                            editor = wx.grid.GridCellChoiceEditor()
                            excluded = []
                            if self.Parent.PouIsUsed:
                                excluded.extend(["Input","Output","InOut"])    
                            editor.SetParameters(",".join([choice for choice in self.Parent.ClassList if choice not in excluded]))
                    elif colname in ["Retain", "Constant"]:
                        editor = wx.grid.GridCellChoiceEditor()
                        editor.SetParameters(self.Parent.OptionList)
                    elif colname == "Type":
                        editor = wx.grid.GridCellTextEditor()
                else:
                    grid.SetReadOnly(row, col, True)
                
                grid.SetCellEditor(row, col, editor)
                grid.SetCellRenderer(row, col, renderer)
                
                if row in self.Errors and self.Errors[row][0] == colname.lower():
                    grid.SetCellBackgroundColour(row, col, wx.Colour(255, 255, 0))
                    grid.SetCellTextColour(row, col, wx.RED)
                    grid.MakeCellVisible(row, col)
                else:
                    grid.SetCellTextColour(row, col, wx.BLACK)
                    grid.SetCellBackgroundColour(row, col, wx.WHITE)
    
    def SetData(self, data):
        self.data = data
    
    def GetData(self):
        return 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 GetRow(self, row_index):
        return self.data[row_index]

    def Empty(self):
        self.data = []
        self.editors = []

    def AddError(self, infos):
        self.Errors[infos[0]] = infos[1:]

    def ClearErrors(self):
        self.Errors = {}

class VariableDropTarget(wx.TextDropTarget):
    
    def __init__(self, parent):
        wx.TextDropTarget.__init__(self)
        self.ParentWindow = parent
    
    def OnDropText(self, x, y, data):
        x, y = self.ParentWindow.VariablesGrid.CalcUnscrolledPosition(x, y)
        col = self.ParentWindow.VariablesGrid.XToCol(x)
        row = self.ParentWindow.VariablesGrid.YToRow(y - self.ParentWindow.VariablesGrid.GetColLabelSize())
        if col != wx.NOT_FOUND and row != wx.NOT_FOUND:
            if self.ParentWindow.Table.GetColLabelValue(col) != "Location":
                return
            message = None
            if not self.ParentWindow.Table.GetValueByName(row, "Edit"):
                message = "Can't affect a location to a function block instance"
            elif self.ParentWindow.Table.GetValueByName(row, "Class") not in ["Local", "Global"]:
                message = "Can affect a location only to local or global variables"
            else:
                try:
                    values = eval(data)    
                except:
                    message = "Invalid value \"%s\" for location"%data
                    values = None
                if not isinstance(values, TupleType):
                    message = "Invalid value \"%s\" for location"%data
                    values = None
                if values is not None and values[1] == "location":
                    location = values[0]
                    variable_type = self.ParentWindow.Table.GetValueByName(row, "Type")
                    base_type = self.ParentWindow.Controler.GetBaseType(variable_type)
                    message = None
                    if location.startswith("%"):
                        if base_type != values[2]:
                            message = "Incompatible data types between \"%s\" and \"%s\""%(values[2], variable_type)
                        else:
                            self.ParentWindow.Table.SetValue(row, col, location)
                            self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
                            self.ParentWindow.SaveValues()
                    else:
                        if location[0].isdigit() and base_type != "BOOL":
                            message = "Incompatible size of data between \"%s\" and \"BOOL\""%location
                        elif location[0] not in LOCATIONDATATYPES:
                            message = "Unrecognized data size \"%s\""%location[0]
                        elif base_type not in LOCATIONDATATYPES[location[0]]:
                            message = "Incompatible size of data between \"%s\" and \"%s\""%(location, variable_type)
                        else:
                            dialog = wx.SingleChoiceDialog(self.ParentWindow, "Select a variable class:", "Variable class", ["Input", "Output", "Memory"], wx.OK|wx.CANCEL)
                            if dialog.ShowModal() == wx.ID_OK:
                                selected = dialog.GetSelection()
                                if selected == 0:
                                    location = "%I" + location
                                elif selected == 1:
                                    location = "%Q" + location
                                else:
                                    location = "%M" + location
                                self.ParentWindow.Table.SetValue(row, col, location)
                                self.ParentWindow.Table.ResetView(self.ParentWindow.VariablesGrid)
                                self.ParentWindow.SaveValues()
                            dialog.Destroy()
            wx.CallAfter(self.ShowMessage, message)
            
    def ShowMessage(self, message):
        if message is not None:
            message = wx.MessageDialog(self.ParentWindow, message, "Error", wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()

[ID_VARIABLEEDITORPANEL, ID_VARIABLEEDITORPANELVARIABLESGRID, 
 ID_VARIABLEEDITORPANELRETURNTYPE, ID_VARIABLEEDITORPANELCLASSFILTER, 
 ID_VARIABLEEDITORPANELADDBUTTON, ID_VARIABLEEDITORPANELDELETEBUTTON, 
 ID_VARIABLEEDITORPANELUPBUTTON, ID_VARIABLEEDITORPANELDOWNBUTTON, 
 ID_VARIABLEEDITORPANELSTATICTEXT1, ID_VARIABLEEDITORPANELSTATICTEXT2, 
 ID_VARIABLEEDITORPANELSTATICTEXT3,
] = [wx.NewId() for _init_ctrls in range(11)]

class VariablePanel(wx.Panel):
    
    if wx.VERSION < (2, 6, 0):
        def Bind(self, event, function, id = None):
            if id is not None:
                event(self, id, function)
            else:
                event(self, function)
    
    def _init_coll_MainSizer_Items(self, parent):
        parent.AddWindow(self.VariablesGrid, 0, border=0, flag=wx.GROW)
        parent.AddSizer(self.ControlPanelSizer, 0, border=0, flag=wx.GROW)
    
    def _init_coll_MainSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
    
    def _init_coll_ControlPanelSizer_Items(self, parent):
        parent.AddSizer(self.ChoicePanelSizer, 0, border=0, flag=wx.GROW)
        parent.AddSizer(self.ButtonPanelSizer, 0, border=0, flag=wx.ALIGN_CENTER)

    def _init_coll_ControlPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableRow(0)
        parent.AddGrowableRow(1)

    def _init_coll_ChoicePanelSizer_Items(self, parent):
        parent.AddWindow(self.staticText1, 0, border=0, flag=wx.ALIGN_BOTTOM)
        parent.AddWindow(self.ReturnType, 0, border=0, flag=0)
        parent.AddWindow(self.staticText2, 0, border=0, flag=wx.ALIGN_BOTTOM)
        parent.AddWindow(self.ClassFilter, 0, border=0, flag=0)

    def _init_coll_ButtonPanelSizer_Items(self, parent):
        parent.AddWindow(self.UpButton, 0, border=0, flag=0)
        parent.AddWindow(self.AddButton, 0, border=0, flag=0)
        parent.AddWindow(self.DownButton, 0, border=0, flag=0)
        parent.AddWindow(self.DeleteButton, 0, border=0, flag=0)
        
    def _init_coll_ButtonPanelSizer_Growables(self, parent):
        parent.AddGrowableCol(0)
        parent.AddGrowableCol(1)
        parent.AddGrowableCol(2)
        parent.AddGrowableCol(3)
        parent.AddGrowableRow(0)

    def _init_sizers(self):
        self.MainSizer = wx.FlexGridSizer(cols=2, hgap=10, rows=1, vgap=0)
        self.ControlPanelSizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
        self.ChoicePanelSizer = wx.GridSizer(cols=1, hgap=5, rows=4, vgap=5)
        self.ButtonPanelSizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=0)
        
        self._init_coll_MainSizer_Items(self.MainSizer)
        self._init_coll_MainSizer_Growables(self.MainSizer)
        self._init_coll_ControlPanelSizer_Items(self.ControlPanelSizer)
        self._init_coll_ControlPanelSizer_Growables(self.ControlPanelSizer)
        self._init_coll_ChoicePanelSizer_Items(self.ChoicePanelSizer)
        self._init_coll_ButtonPanelSizer_Items(self.ButtonPanelSizer)
        self._init_coll_ButtonPanelSizer_Growables(self.ButtonPanelSizer)
        
        self.SetSizer(self.MainSizer)

    def _init_ctrls(self, prnt):
        wx.Panel.__init__(self, id=ID_VARIABLEEDITORPANEL,
              name='VariableEditorPanel', parent=prnt, pos=wx.Point(0, 0),
              size=wx.Size(0, 0), style=wx.TAB_TRAVERSAL)
        
        self.staticText1 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT1,
              label='Return Type:', name='staticText1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(95, 17), style=0)

        self.ReturnType = wx.Choice(id=ID_VARIABLEEDITORPANELRETURNTYPE,
              name='ReturnType', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(145, 24), style=0)
        self.Bind(wx.EVT_CHOICE, self.OnReturnTypeChanged, id=ID_VARIABLEEDITORPANELRETURNTYPE)

        self.staticText2 = wx.StaticText(id=ID_VARIABLEEDITORPANELSTATICTEXT2,
              label='Class Filter:', name='staticText2', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(95, 17), style=0)

        self.ClassFilter = wx.Choice(id=ID_VARIABLEEDITORPANELCLASSFILTER,
              name='ClassFilter', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(145, 24), style=0)
        self.Bind(wx.EVT_CHOICE, self.OnClassFilter, id=ID_VARIABLEEDITORPANELCLASSFILTER)

        self.VariablesGrid = wx.grid.Grid(id=ID_VARIABLEEDITORPANELVARIABLESGRID,
              name='VariablesGrid', parent=self, pos=wx.Point(0, 0), 
              size=wx.Size(0, 150), style=wx.VSCROLL)
        self.VariablesGrid.SetFont(wx.Font(12, 77, wx.NORMAL, wx.NORMAL, False,
              'Sans'))
        self.VariablesGrid.SetLabelFont(wx.Font(10, 77, wx.NORMAL, wx.NORMAL,
              False, 'Sans'))
        self.VariablesGrid.SetSelectionBackground(wx.WHITE)
        self.VariablesGrid.SetSelectionForeground(wx.BLACK)
        if wx.VERSION >= (2, 6, 0):
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.OnVariablesGridCellChange)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_SELECT_CELL, self.OnVariablesGridSelectCell)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.OnVariablesGridCellLeftClick)
            self.VariablesGrid.Bind(wx.grid.EVT_GRID_EDITOR_SHOWN, self.OnVariablesGridEditorShown)
        else:
            wx.grid.EVT_GRID_CELL_CHANGE(self.VariablesGrid, self.OnVariablesGridCellChange)
            wx.grid.EVT_GRID_SELECT_CELL(self.VariablesGrid, self.OnVariablesGridSelectCell)
            wx.grid.EVT_GRID_CELL_LEFT_CLICK(self.VariablesGrid, self.OnVariablesGridCellLeftClick)
            wx.grid.EVT_GRID_EDITOR_SHOWN(self.VariablesGrid, self.OnVariablesGridEditorShown)
        self.VariablesGrid.SetDropTarget(VariableDropTarget(self))
        
        self.AddButton = wx.Button(id=ID_VARIABLEEDITORPANELADDBUTTON, label='Add',
              name='AddButton', parent=self, pos=wx.Point(345, 340),
              size=wx.Size(72, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnAddButton, id=ID_VARIABLEEDITORPANELADDBUTTON)

        self.DeleteButton = wx.Button(id=ID_VARIABLEEDITORPANELDELETEBUTTON, label='Delete',
              name='DeleteButton', parent=self, pos=wx.Point(425, 340),
              size=wx.Size(72, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnDeleteButton, id=ID_VARIABLEEDITORPANELDELETEBUTTON)

        self.UpButton = wx.Button(id=ID_VARIABLEEDITORPANELUPBUTTON, label='^',
              name='UpButton', parent=self, pos=wx.Point(505, 340),
              size=wx.Size(32, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnUpButton, id=ID_VARIABLEEDITORPANELUPBUTTON)

        self.DownButton = wx.Button(id=ID_VARIABLEEDITORPANELDOWNBUTTON, label='v',
              name='DownButton', parent=self, pos=wx.Point(545, 340),
              size=wx.Size(32, 32), style=0)
        self.Bind(wx.EVT_BUTTON, self.OnDownButton, id=ID_VARIABLEEDITORPANELDOWNBUTTON)

        self._init_sizers()

    def __init__(self, parent, window, controler, element_type):
        self._init_ctrls(parent)
        self.ParentWindow = window
        self.Controler = controler
        self.ElementType = element_type
        
        self.Filter = "All"
        self.FilterChoices = []
        self.FilterChoiceTransfer = {"All" : "All", "Interface" : "Interface", 
            "   Input" : "Input", "   Output" : "Output", "   InOut" : "InOut", 
            "   External" : "External", "Variables" : "Variables", "   Local" : "Local",
            "   Temp" : "Temp", "Global" : "Global", "Access" : "Access"}
        
        if element_type in ["config", "resource"]:
            self.DefaultTypes = {"All" : "Global"}
            self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True}
        else:
            self.DefaultTypes = {"All" : "Local", "Interface" : "Input", "Variables" : "Local"}
            self.DefaultValue = {"Name" : "", "Class" : "", "Type" : "INT", "Location" : "", "Initial Value" : "", "Retain" : "No", "Constant" : "No", "Edit" : True}
        if element_type in ["config", "resource"] or element_type in ["program", "transition", "action"]:
            self.Table = VariableTable(self, [], ["#", "Name", "Class", "Type", "Location", "Initial Value", "Retain", "Constant"])
            if element_type not in ["config", "resource"]:
                self.FilterChoices = ["All","Interface","   Input","   Output","   InOut","   External","Variables","   Local","   Temp","Global","Access"]
            else:
                self.FilterChoices = ["All","Global","Access"]
            self.ColSizes = [40, 80, 70, 80, 80, 80, 60, 70]
            self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER]
        else:
            self.Table = VariableTable(self, [], ["#", "Name", "Class", "Type", "Initial Value", "Retain", "Constant"])
            self.FilterChoices = ["All","Interface","   Input","   Output","   InOut","   External","Variables","   Local","   Temp"]
            self.ColSizes = [40, 120, 70, 80, 120, 60, 70]
            self.ColAlignements = [wx.ALIGN_CENTER, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_LEFT, wx.ALIGN_CENTER, wx.ALIGN_CENTER]
        for choice in self.FilterChoices:
            self.ClassFilter.Append(choice)
        reverse_transfer = {}
        for filter, choice in self.FilterChoiceTransfer.items():
            reverse_transfer[choice] = filter
        self.ClassFilter.SetStringSelection(reverse_transfer[self.Filter])
        self.RefreshTypeList()

        self.OptionList = "Yes,No"
        
        if element_type == "function":
            for base_type in self.Controler.GetBaseTypes():
                self.ReturnType.Append(base_type)
            self.ReturnType.Enable(True)
        else:
            self.ReturnType.Enable(False)
            self.staticText1.Hide()
            self.ReturnType.Hide()
        
        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])
    
    def SetTagName(self, tagname):
        self.TagName = tagname
    
    def RefreshView(self):
        self.PouNames = self.Controler.GetProjectPouNames()
        
        words = self.TagName.split("::")
        if self.ElementType == "config":
            self.PouIsUsed = False
            returnType = None
            self.Values = self.Controler.GetConfigurationGlobalVars(words[1])
        elif self.ElementType == "resource":
            self.PouIsUsed = False
            returnType = None
            self.Values = self.Controler.GetConfigurationResourceGlobalVars(words[1], words[2])
        else:
            self.PouIsUsed = self.Controler.PouIsUsed(words[1])
            returnType = self.Controler.GetEditedElementInterfaceReturnType(self.TagName)
            self.Values = self.Controler.GetEditedElementInterfaceVars(self.TagName)
        
        if returnType and self.ReturnType.IsEnabled():
            self.ReturnType.SetStringSelection(returnType)
        
        self.RefreshValues()
        self.RefreshButtons()
    
    def OnReturnTypeChanged(self, event):
        words = self.TagName.split("::")
        self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
        self.Controler.BufferProject()
        self.ParentWindow.RefreshTitle()
        self.ParentWindow.RefreshEditMenu()
        event.Skip()
    
    def OnClassFilter(self, event):
        self.Filter = self.FilterChoiceTransfer[self.ClassFilter.GetStringSelection()]
        self.RefreshTypeList()
        self.RefreshValues()
        self.RefreshButtons()
        event.Skip()

    def RefreshTypeList(self):
        if self.Filter == "All":
            self.ClassList = [self.FilterChoiceTransfer[choice] for choice in self.FilterChoices if self.FilterChoiceTransfer[choice] not in ["All","Interface","Variables"]]
        elif self.Filter == "Interface":
            self.ClassList = ["Input","Output","InOut","External"]
        elif self.Filter == "Variables":
            self.ClassList = ["Local","Temp"]
        else:
            self.ClassList = [self.Filter]

    def RefreshButtons(self):
        if getattr(self, "Table", None):
            table_length = len(self.Table.data)
            row_class = None
            if table_length and self.PouIsUsed:
                row = self.VariablesGrid.GetGridCursorRow()
                row_class = self.Table.GetValueByName(row, "Class")
            self.AddButton.Enable(not self.PouIsUsed or self.Filter not in ["Interface", "Input", "Output", "InOut"])
            self.DeleteButton.Enable(table_length > 0 and row_class not in ["Input", "Output", "InOut"])
            self.UpButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])
            self.DownButton.Enable(table_length > 0 and self.Filter == "All" and row_class not in ["Input", "Output", "InOut"])

    def OnAddButton(self, event):
        new_row = self.DefaultValue.copy()
        if self.Filter in self.DefaultTypes:
            new_row["Class"] = self.DefaultTypes[self.Filter]
        else:
            new_row["Class"] = self.Filter
        self.Values.append(new_row)
        self.SaveValues()
        self.RefreshValues()
        self.RefreshButtons()
        event.Skip()

    def OnDeleteButton(self, event):
        row = self.Table.GetRow(self.VariablesGrid.GetGridCursorRow())
        self.Values.remove(row)
        self.SaveValues()
        self.RefreshValues()
        self.RefreshButtons()
        event.Skip()

    def OnUpButton(self, event):
        self.MoveValue(self.VariablesGrid.GetGridCursorRow(), -1)
        self.RefreshButtons()
        event.Skip()

    def OnDownButton(self, event):
        self.MoveValue(self.VariablesGrid.GetGridCursorRow(), 1)
        self.RefreshButtons()
        event.Skip()

    def OnVariablesGridCellChange(self, event):
        row, col = event.GetRow(), event.GetCol()
        colname = self.Table.GetColLabelValue(col)
        value = self.Table.GetValue(row, col)
        if colname == "Name":
            if not TestIdentifier(value):
                message = wx.MessageDialog(self, "\"%s\" is not a valid identifier!"%value, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in IEC_KEYWORDS:
                message = wx.MessageDialog(self, "\"%s\" is a keyword. It can't be used!"%value, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in self.PouNames:
                message = wx.MessageDialog(self, "A pou with \"%s\" as name exists!"%value, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            elif value.upper() in [var["Name"].upper() for var in self.Values if var != self.Table.data[row]]:
                message = wx.MessageDialog(self, "A variable with \"%s\" as name exists in this pou!"%value, "Error", wx.OK|wx.ICON_ERROR)
                message.ShowModal()
                message.Destroy()
                event.Veto()
            else:
                self.SaveValues(False)
                old_value = self.Table.GetOldValue()
                if old_value != "":
                    self.Controler.UpdateEditedElementUsedVariable(self.TagName, old_value, value)
                self.Controler.BufferProject()
                self.ParentWindow.RefreshEditor(variablepanel = False)
                self.ParentWindow.RefreshTitle()
                self.ParentWindow.RefreshEditMenu()
                event.Skip()
        else:
            self.SaveValues()
            if colname == "Class":
                self.Table.ResetView(self.VariablesGrid)
            event.Skip()
    
    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():
                new_id = wx.NewId()
                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):
                new_id = wx.NewId()
                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)
            functionblock_menu = wx.Menu(title='')
            for functionblock_type in self.Controler.GetFunctionBlockTypes():
                new_id = wx.NewId()
                AppendMenu(functionblock_menu, help='', id=new_id, kind=wx.ITEM_NORMAL, text=functionblock_type)
                self.Bind(wx.EVT_MENU, self.GetVariableTypeFunction(functionblock_type), id=new_id)
            type_menu.AppendMenu(wx.NewId(), "Function Block Types", functionblock_menu)
            rect = self.VariablesGrid.BlockToDeviceRect((row, col), (row, col))
            self.VariablesGrid.PopupMenuXY(type_menu, rect.x + rect.width, rect.y + self.VariablesGrid.GetColLabelSize())
            event.Veto()
        else:
            event.Skip()
    
    def GetVariableTypeFunction(self, base_type):
        def VariableTypeFunction(event):
            row = self.VariablesGrid.GetGridCursorRow()
            self.Table.SetValueByName(row, "Type", base_type)
            self.Table.ResetView(self.VariablesGrid)
            self.SaveValues(False)
            self.ParentWindow.RefreshEditor(variablepanel = False)
            self.Controler.BufferProject()
            self.ParentWindow.RefreshTitle()
            self.ParentWindow.RefreshEditMenu()
            event.Skip()
        return VariableTypeFunction
    
    def OnVariablesGridCellLeftClick(self, event):
        row = event.GetRow()
        if event.GetCol() == 0 and self.Table.GetValueByName(row, "Edit"):
            row = event.GetRow()
            var_name = self.Table.GetValueByName(row, "Name")
            var_class = self.Table.GetValueByName(row, "Class")
            var_type = self.Table.GetValueByName(row, "Type")
            data = wx.TextDataObject(str((var_name, var_class, var_type, self.TagName)))
            dragSource = wx.DropSource(self.VariablesGrid)
            dragSource.SetData(data)
            dragSource.DoDragDrop()
        event.Skip()
    
    def OnVariablesGridSelectCell(self, event):
        wx.CallAfter(self.RefreshButtons)
        event.Skip()

    def MoveValue(self, value_index, move):
        new_index = max(0, min(value_index + move, len(self.Values) - 1))
        if new_index != value_index:
            self.Values.insert(new_index, self.Values.pop(value_index))
            self.RefreshValues()
            self.VariablesGrid.SetGridCursor(new_index, self.VariablesGrid.GetGridCursorCol())
        else:
            self.RefreshValues()
        self.SaveValues()

    def RefreshValues(self):
        if len(self.Table.data) > 0:
            self.VariablesGrid.SetGridCursor(0, 1)
        data = []
        for num, variable in enumerate(self.Values):
            if variable["Class"] in self.ClassList:
                variable["Number"] = num + 1
                data.append(variable)
        self.Table.SetData(data)
        self.Table.ResetView(self.VariablesGrid)

    def SaveValues(self, buffer = True):
        words = self.TagName.split("::")
        if self.ElementType == "config":
            self.Controler.SetConfigurationGlobalVars(words[1], self.Values)
        elif self.ElementType == "resource":
            self.Controler.SetConfigurationResourceGlobalVars(words[1], words[2], self.Values)
        else:
            if self.ReturnType.IsEnabled():
                self.Controler.SetPouInterfaceReturnType(words[1], self.ReturnType.GetStringSelection())
            self.Controler.SetPouInterfaceVars(words[1], self.Values)
        if buffer:
            self.Controler.BufferProject()
            self.ParentWindow.RefreshTitle()
            self.ParentWindow.RefreshEditMenu()

    def AddVariableError(self, infos):
        if isinstance(infos[0], TupleType):
            for i in xrange(*infos[0]):
                self.Table.AddError((i,) + infos[1:])
        else:
            self.Table.AddError(infos)
        self.Table.ResetView(self.VariablesGrid)

    def ClearErrors(self):
        self.Table.ClearErrors()
        self.Table.ResetView(self.VariablesGrid)

UPPER_DIV = lambda x, y: (x / y) + {True : 0, False : 1}[(x % y) == 0]

class GraphicPrintout(wx.Printout):
    def __init__(self, viewer, page_size, margins, preview = False):
        wx.Printout.__init__(self)
        self.Viewer = viewer
        self.PageSize = page_size
        if self.PageSize[0] == 0 or self.PageSize[1] == 0:
            self.PageSize = (1050, 1485)
        self.Preview = preview
        self.Margins = margins
        self.FontSize = 5
        self.TextMargin = 3
        
        maxx, maxy = viewer.GetMaxSize()
        self.PageGrid = (UPPER_DIV(maxx, self.PageSize[0]), 
                         UPPER_DIV(maxy, self.PageSize[1]))
        
    def GetPageNumber(self):
        return self.PageGrid[0] * self.PageGrid[1]
    
    def HasPage(self, page):
        return page <= self.GetPageNumber()
        
    def GetPageInfo(self):
        page_number = self.GetPageNumber()
        return (1, page_number, 1, page_number)

    def OnBeginDocument(self, startPage, endPage):
        dc = self.GetDC()
        if not self.Preview and isinstance(dc, wx.PostScriptDC):
            dc.SetResolution(720)
        super(GraphicPrintout, self).OnBeginDocument(startPage, endPage)

    def OnPrintPage(self, page):
        dc = self.GetDC()
        dc.SetUserScale(1.0, 1.0)
        dc.SetDeviceOrigin(0, 0)
        dc.printing = not self.Preview
        
        # Get the size of the DC in pixels
        ppiPrinterX, ppiPrinterY = self.GetPPIPrinter()
        ppiScreenX, ppiScreenY = self.GetPPIScreen()
        pw, ph = self.GetPageSizePixels()
        dw, dh = dc.GetSizeTuple()
        Xscale = (float(dw) * float(ppiPrinterX)) / (float(pw) * 25.4)
        Yscale = (float(dh) * float(ppiPrinterY)) / (float(ph) * 25.4)
        
        fontsize = self.FontSize * Yscale
        text_margin = self.TextMargin * Yscale
        
        margin_left = self.Margins[0].x * Xscale
        margin_top = self.Margins[0].y * Yscale
        area_width = dw - self.Margins[1].x * Xscale - margin_left
        area_height = dh - self.Margins[1].y * Yscale - margin_top
        
        dc.SetPen(wx.BLACK_PEN)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)    
        dc.DrawRectangle(margin_left, margin_top, area_width, area_height)
        
        dc.SetFont(wx.Font(fontsize, wx.DEFAULT, wx.NORMAL, wx.NORMAL))
        dc.SetTextForeground(wx.BLACK)
        block_name = " - ".join(self.Viewer.GetTagName().split("::")[1:])
        text_width, text_height = dc.GetTextExtent(block_name)
        dc.DrawText(block_name, margin_left, margin_top - text_height - self.TextMargin)
        dc.DrawText("Page: %d" % page, margin_left, margin_top + area_height + self.TextMargin)
        
        # Calculate the position on the DC for centering the graphic
        posX = area_width * ((page - 1) % self.PageGrid[0])
        posY = area_height * ((page - 1) / self.PageGrid[0])

        scaleX = float(area_width) / float(self.PageSize[0])
        scaleY = float(area_height) / float(self.PageSize[1])
        scale = min(scaleX, scaleY)

        # Set the scale and origin
        dc.SetDeviceOrigin(-posX + margin_left, -posY + margin_top)
        dc.SetClippingRegion(posX, posY, self.PageSize[0] * scale, self.PageSize[1] * scale)
        dc.SetUserScale(scale, scale)
        
        #-------------------------------------------
        
        self.Viewer.DoDrawing(dc, True)
        
        return True

#-------------------------------------------------------------------------------
#                               Exception Handler
#-------------------------------------------------------------------------------

Max_Traceback_List_Size = 20

def Display_Exception_Dialog(e_type,e_value,e_tb):
    trcbck_lst = []
    for i,line in enumerate(traceback.extract_tb(e_tb)):
        trcbck = " " + str(i+1) + ". "
        if line[0].find(os.getcwd()) == -1:
            trcbck += "file : " + str(line[0]) + ",   "
        else:
            trcbck += "file : " + str(line[0][len(os.getcwd()):]) + ",   "
        trcbck += "line : " + str(line[1]) + ",   " + "function : " + str(line[2])
        trcbck_lst.append(trcbck)
        
    # Allow clicking....
    cap = wx.Window_GetCapture()
    if cap:
        cap.ReleaseMouse()

    dlg = wx.SingleChoiceDialog(None, 
        """
An error happens.

Click on OK for saving an error report.

Please contact LOLITech at:
+33 (0)3 29 52 95 67
bugs_PLCOpenEditor@lolitech.fr


Error:
""" +
        str(e_type) + " : " + str(e_value), 
        "Error",
        trcbck_lst)
    try:
        res = (dlg.ShowModal() == wx.ID_OK)
    finally:
        dlg.Destroy()

    return res

def Display_Error_Dialog(e_value):
    message = wx.MessageDialog(None, str(e_value), "Error", wx.OK|wx.ICON_ERROR)
    message.ShowModal()
    message.Destroy()

def get_last_traceback(tb):
    while tb.tb_next:
        tb = tb.tb_next
    return tb


def format_namespace(d, indent='    '):
    return '\n'.join(['%s%s: %s' % (indent, k, repr(v)[:10000]) for k, v in d.iteritems()])


ignored_exceptions = [] # a problem with a line in a module is only reported once per session

def AddExceptHook(path, app_version='[No version]'):#, ignored_exceptions=[]):
    
    def handle_exception(e_type, e_value, e_traceback):
        traceback.print_exception(e_type, e_value, e_traceback) # this is very helpful when there's an exception in the rest of this func
        last_tb = get_last_traceback(e_traceback)
        ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
        if str(e_value).startswith("!!!"):
            Display_Error_Dialog(e_value)
        elif ex not in ignored_exceptions:
            result = Display_Exception_Dialog(e_type,e_value,e_traceback)
            if result:
                ignored_exceptions.append(ex)
                info = {
                    'app-title' : wx.GetApp().GetAppName(), # app_title
                    'app-version' : app_version,
                    'wx-version' : wx.VERSION_STRING,
                    'wx-platform' : wx.Platform,
                    'python-version' : platform.python_version(), #sys.version.split()[0],
                    'platform' : platform.platform(),
                    'e-type' : e_type,
                    'e-value' : e_value,
                    'date' : time.ctime(),
                    'cwd' : os.getcwd(),
                    }
                if e_traceback:
                    info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value)
                    last_tb = get_last_traceback(e_traceback)
                    exception_locals = last_tb.tb_frame.f_locals # the locals at the level of the stack trace where the exception actually occurred
                    info['locals'] = format_namespace(exception_locals)
                    if 'self' in exception_locals:
                        info['self'] = format_namespace(exception_locals['self'].__dict__)
                
                output = open(path+os.sep+"bug_report_"+info['date'].replace(':','-').replace(' ','_')+".txt",'w')
                lst = info.keys()
                lst.sort()
                for a in lst:
                    output.write(a+":\n"+str(info[a])+"\n\n")

    #sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args)
    sys.excepthook = handle_exception

if __name__ == '__main__':
    def usage():
        print "\nUsage of PLCOpenEditor.py :"
        print "\n   %s [Filepath]\n"%sys.argv[0]

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()

    fileOpen = None
    if len(args) > 1:
        usage()
        sys.exit()
    elif len(args) == 1:
        fileOpen = args[0]
    
    app = wx.PySimpleApp()
    wx.InitAllImageHandlers()
    
    # Install a exception handle for bug reports
    AddExceptHook(os.getcwd(),__version__)
    
    frame = PLCOpenEditor(None, fileOpen=fileOpen)

    frame.Show()
    app.MainLoop()