--- a/Beremiz.py Mon Oct 14 10:31:32 2013 +0200
+++ b/Beremiz.py Mon Oct 14 10:49:04 2013 +0200
@@ -141,7 +141,6 @@
from editors.EditorPanel import EditorPanel
from editors.Viewer import Viewer
from editors.TextViewer import TextViewer
-from editors.GraphicViewer import GraphicViewer
from editors.ResourceEditor import ConfigurationEditor, ResourceEditor
from editors.DataTypeEditor import DataTypeEditor
from util.MiniTextControler import MiniTextControler
@@ -617,7 +616,6 @@
if (isinstance(tab, EditorPanel) and
not isinstance(tab, (Viewer,
TextViewer,
- GraphicViewer,
ResourceEditor,
ConfigurationEditor,
DataTypeEditor))):
--- a/IDEFrame.py Mon Oct 14 10:31:32 2013 +0200
+++ b/IDEFrame.py Mon Oct 14 10:49:04 2013 +0200
@@ -6,19 +6,11 @@
import wx, wx.grid
import wx.aui
-try:
- import matplotlib
- matplotlib.use('WX')
- USE_MPL = True
-except:
- USE_MPL = False
-
from editors.EditorPanel import EditorPanel
from editors.SFCViewer import SFC_Viewer
from editors.LDViewer import LD_Viewer
from editors.TextViewer import TextViewer
from editors.Viewer import Viewer, ZOOM_FACTORS
-from editors.GraphicViewer import GraphicViewer
from editors.ResourceEditor import ConfigurationEditor, ResourceEditor
from editors.DataTypeEditor import DataTypeEditor
from PLCControler import *
@@ -27,8 +19,6 @@
from dialogs import ProjectDialog, PouDialog, PouTransitionDialog, PouActionDialog, FindInPouDialog, SearchInProjectDialog
from util.BitmapLibrary import GetBitmap
-PouInstanceVariablesPanel.USE_MPL = USE_MPL
-
# Define PLCOpenEditor controls id
[ID_PLCOPENEDITOR, ID_PLCOPENEDITORLEFTNOTEBOOK,
ID_PLCOPENEDITORBOTTOMNOTEBOOK, ID_PLCOPENEDITORRIGHTNOTEBOOK,
@@ -1954,11 +1944,7 @@
elif instance_category in ITEMS_VARIABLE:
if self.Controler.IsNumType(instance_type, True):
- if USE_MPL:
- self.AddDebugVariable(instance_path, True)
- else:
- new_window = GraphicViewer(self.TabsOpened, self, self.Controler, instance_path)
- icon = GetBitmap("GRAPH")
+ self.AddDebugVariable(instance_path, True)
else:
bodytype = self.Controler.GetEditedElementBodyType(instance_type, True)
@@ -1998,10 +1984,6 @@
def ResetGraphicViewers(self):
if self.EnableDebug:
- for i in xrange(self.TabsOpened.GetPageCount()):
- editor = self.TabsOpened.GetPage(i)
- if isinstance(editor, GraphicViewer):
- editor.ResetView()
self.DebugVariablePanel.ResetGraphicsValues()
def CloseObsoleteDebugTabs(self):
@@ -2010,12 +1992,10 @@
idxs.reverse()
for idx in idxs:
editor = self.TabsOpened.GetPage(idx)
- if isinstance(editor, (Viewer, GraphicViewer)) and editor.IsDebugging():
+ if isinstance(editor, Viewer) and editor.IsDebugging():
instance_infos = self.Controler.GetInstanceInfos(editor.GetInstancePath(), self.EnableDebug)
if instance_infos is None:
self.TabsOpened.DeletePage(idx)
- elif isinstance(editor, GraphicViewer):
- editor.ResetView(True)
else:
editor.SubscribeAllDataConsumers()
elif editor.IsDebugging():
@@ -2076,7 +2056,7 @@
menu = None
if selected != -1:
window = self.TabsOpened.GetPage(selected)
- if isinstance(window, (Viewer, TextViewer, GraphicViewer)):
+ if isinstance(window, (Viewer, TextViewer)):
if not window.IsDebugging():
menu = self.Controler.GetEditedElementBodyType(window.GetTagName())
else:
--- a/ProjectController.py Mon Oct 14 10:31:32 2013 +0200
+++ b/ProjectController.py Mon Oct 14 10:49:04 2013 +0200
@@ -1268,8 +1268,7 @@
WeakKeyDictionary(), # Callables
[], # Data storage [(tick, data),...]
"Registered", # Variable status
- None,
- buffer_list] # Forced value
+ None] # Forced value
self.IECdebug_datas[IECPath] = IECdebug_data
IECdebug_data[0][callableobj]=(args, kwargs)
--- a/controls/DebugVariablePanel/DebugVariableGraphicPanel.py Mon Oct 14 10:31:32 2013 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,958 +0,0 @@
-#!/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) 2012: 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 types import TupleType
-import math
-import numpy
-
-import wx
-import wx.lib.buttons
-
-import matplotlib
-import matplotlib.pyplot
-from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
-
-from editors.DebugViewer import DebugViewer
-from util.BitmapLibrary import GetBitmap
-
-from DebugVariableItem import DebugVariableItem
-from DebugVariableTextViewer import DebugVariableTextViewer
-from DebugVariableGraphicViewer import *
-
-MILLISECOND = 1000000 # Number of nanosecond in a millisecond
-SECOND = 1000 * MILLISECOND # Number of nanosecond in a second
-MINUTE = 60 * SECOND # Number of nanosecond in a minute
-HOUR = 60 * MINUTE # Number of nanosecond in a hour
-DAY = 24 * HOUR # Number of nanosecond in a day
-
-# List of values possible for graph range
-# Format is [(time_in_plain_text, value_in_nanosecond),...]
-RANGE_VALUES = \
- [("%dms" % i, i * MILLISECOND) for i in (10, 20, 50, 100, 200, 500)] + \
- [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \
- [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \
- [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)]
-
-# Scrollbar increment in pixel
-SCROLLBAR_UNIT = 10
-
-def compute_mask(x, y):
- return [(xp if xp == yp else "*")
- for xp, yp in zip(x, y)]
-
-def NextTick(variables):
- next_tick = None
- for item, data in variables:
- if len(data) == 0:
- continue
-
- next_tick = (data[0][0]
- if next_tick is None
- else min(next_tick, data[0][0]))
-
- return next_tick
-
-#-------------------------------------------------------------------------------
-# Debug Variable Graphic Panel Drop Target
-#-------------------------------------------------------------------------------
-
-"""
-Class that implements a custom drop target class for Debug Variable Graphic
-Panel
-"""
-
-class DebugVariableDropTarget(wx.TextDropTarget):
-
- def __init__(self, window):
- """
- Constructor
- @param window: Reference to the Debug Variable Panel
- """
- wx.TextDropTarget.__init__(self)
- self.ParentWindow = window
-
- def __del__(self):
- """
- Destructor
- """
- # Remove reference to Debug Variable Panel
- self.ParentWindow = None
-
- def OnDragOver(self, x, y, d):
- """
- Function called when mouse is dragged over Drop Target
- @param x: X coordinate of mouse pointer
- @param y: Y coordinate of mouse pointer
- @param d: Suggested default for return value
- """
- # Signal Debug Variable Panel to refresh highlight giving mouse position
- self.ParentWindow.RefreshHighlight(x, y)
- return wx.TextDropTarget.OnDragOver(self, x, y, d)
-
- def OnDropText(self, x, y, data):
- """
- Function called when mouse is released in Drop Target
- @param x: X coordinate of mouse pointer
- @param y: Y coordinate of mouse pointer
- @param data: Text associated to drag'n drop
- """
- # Signal Debug Variable Panel to reset highlight
- self.ParentWindow.ResetHighlight()
-
- message = None
-
- # Check that data is valid regarding DebugVariablePanel
- try:
- values = eval(data)
- if not isinstance(values, TupleType):
- raise ValueError
- except:
- message = _("Invalid value \"%s\" for debug variable")%data
- values = None
-
- # Display message if data is invalid
- if message is not None:
- wx.CallAfter(self.ShowMessage, message)
-
- # Data contain a reference to a variable to debug
- elif values[1] == "debug":
-
- # Drag'n Drop is an internal is an internal move inside Debug
- # Variable Panel
- if len(values) > 2 and values[2] == "move":
- self.ParentWindow.MoveValue(values[0])
-
- # Drag'n Drop was initiated by another control of Beremiz
- else:
- self.ParentWindow.InsertValue(values[0], force=True)
-
- def OnLeave(self):
- """
- Function called when mouse is leave Drop Target
- """
- # Signal Debug Variable Panel to reset highlight
- self.ParentWindow.ResetHighlight()
- return wx.TextDropTarget.OnLeave(self)
-
- def ShowMessage(self, message):
- """
- Show error message in Error Dialog
- @param message: Error message to display
- """
- dialog = wx.MessageDialog(self.ParentWindow,
- message,
- _("Error"),
- wx.OK|wx.ICON_ERROR)
- dialog.ShowModal()
- dialog.Destroy()
-
-
-#-------------------------------------------------------------------------------
-# Debug Variable Graphic Panel Class
-#-------------------------------------------------------------------------------
-
-"""
-Class that implements a Viewer that display variable values as a graphs
-"""
-
-class DebugVariableGraphicPanel(wx.Panel, DebugViewer):
-
- def __init__(self, parent, producer, window):
- """
- Constructor
- @param parent: Reference to the parent wx.Window
- @param producer: Object receiving debug value and dispatching them to
- consumers
- @param window: Reference to Beremiz frame
- """
- wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL)
-
- # Save Reference to Beremiz frame
- self.ParentWindow = window
-
- # Variable storing flag indicating that variable displayed in table
- # received new value and then table need to be refreshed
- self.HasNewData = False
-
- # Variable storing flag indicating that refresh has been forced, and
- # that next time refresh is possible, it will be done even if no new
- # data is available
- self.Force = False
-
- self.SetBackgroundColour(wx.WHITE)
-
- main_sizer = wx.BoxSizer(wx.VERTICAL)
-
- self.Ticks = numpy.array([]) # List of tick received
- self.StartTick = 0 # Tick starting range of data displayed
- self.Fixed = False # Flag that range of data is fixed
- self.CursorTick = None # Tick of cursor for displaying values
-
- self.DraggingAxesPanel = None
- self.DraggingAxesBoundingBox = None
- self.DraggingAxesMousePos = None
- self.VetoScrollEvent = False
-
- self.VariableNameMask = []
-
- self.GraphicPanels = []
-
- graphics_button_sizer = wx.BoxSizer(wx.HORIZONTAL)
- main_sizer.AddSizer(graphics_button_sizer, border=5, flag=wx.GROW|wx.ALL)
-
- range_label = wx.StaticText(self, label=_('Range:'))
- graphics_button_sizer.AddWindow(range_label, flag=wx.ALIGN_CENTER_VERTICAL)
-
- self.CanvasRange = wx.ComboBox(self, style=wx.CB_READONLY)
- self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange)
- graphics_button_sizer.AddWindow(self.CanvasRange, 1,
- border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL)
-
- self.CanvasRange.Clear()
- default_range_idx = 0
- for idx, (text, value) in enumerate(RANGE_VALUES):
- self.CanvasRange.Append(text)
- if text == "1s":
- default_range_idx = idx
- self.CanvasRange.SetSelection(default_range_idx)
-
- for name, bitmap, help in [
- ("CurrentButton", "current", _("Go to current value")),
- ("ExportGraphButton", "export_graph", _("Export graph values to clipboard"))]:
- button = wx.lib.buttons.GenBitmapButton(self,
- bitmap=GetBitmap(bitmap),
- size=wx.Size(28, 28), style=wx.NO_BORDER)
- button.SetToolTipString(help)
- setattr(self, name, button)
- self.Bind(wx.EVT_BUTTON, getattr(self, "On" + name), button)
- graphics_button_sizer.AddWindow(button, border=5, flag=wx.LEFT)
-
- self.CanvasPosition = wx.ScrollBar(self,
- size=wx.Size(0, 16), style=wx.SB_HORIZONTAL)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN,
- self.OnPositionChanging, self.CanvasPosition)
- main_sizer.AddWindow(self.CanvasPosition, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM)
-
- self.TickSizer = wx.BoxSizer(wx.HORIZONTAL)
- main_sizer.AddSizer(self.TickSizer, border=5, flag=wx.ALL|wx.GROW)
-
- self.TickLabel = wx.StaticText(self)
- self.TickSizer.AddWindow(self.TickLabel, border=5, flag=wx.RIGHT)
-
- self.MaskLabel = wx.TextCtrl(self, style=wx.TE_READONLY|wx.TE_CENTER|wx.NO_BORDER)
- self.TickSizer.AddWindow(self.MaskLabel, 1, border=5, flag=wx.RIGHT|wx.GROW)
-
- self.TickTimeLabel = wx.StaticText(self)
- self.TickSizer.AddWindow(self.TickTimeLabel)
-
- self.GraphicsWindow = wx.ScrolledWindow(self, style=wx.HSCROLL|wx.VSCROLL)
- self.GraphicsWindow.SetBackgroundColour(wx.WHITE)
- self.GraphicsWindow.SetDropTarget(DebugVariableDropTarget(self))
- self.GraphicsWindow.Bind(wx.EVT_ERASE_BACKGROUND, self.OnGraphicsWindowEraseBackground)
- self.GraphicsWindow.Bind(wx.EVT_PAINT, self.OnGraphicsWindowPaint)
- self.GraphicsWindow.Bind(wx.EVT_SIZE, self.OnGraphicsWindowResize)
- self.GraphicsWindow.Bind(wx.EVT_MOUSEWHEEL, self.OnGraphicsWindowMouseWheel)
-
- main_sizer.AddWindow(self.GraphicsWindow, 1, flag=wx.GROW)
-
- self.GraphicsSizer = wx.BoxSizer(wx.VERTICAL)
- self.GraphicsWindow.SetSizer(self.GraphicsSizer)
-
- DebugViewer.__init__(self, producer, True)
-
- self.SetSizer(main_sizer)
-
- def SetTickTime(self, ticktime=0):
- """
- Set Ticktime for calculate data range according to time range selected
- @param ticktime: Ticktime to apply to range (default: 0)
- """
- # Save ticktime
- self.Ticktime = ticktime
-
- # Set ticktime to millisecond if undefined
- if self.Ticktime == 0:
- self.Ticktime = MILLISECOND
-
- # Calculate range to apply to data
- self.CurrentRange = RANGE_VALUES[
- self.CanvasRange.GetSelection()][1] / self.Ticktime
-
- def SetDataProducer(self, producer):
- """
- Set Data Producer
- @param producer: Data Producer
- """
- DebugViewer.SetDataProducer(self, producer)
-
- # Set ticktime if data producer is available
- if self.DataProducer is not None:
- self.SetTickTime(self.DataProducer.GetTicktime())
-
- def RefreshNewData(self, *args, **kwargs):
- """
- Called to refresh Panel according to values received by variables
- Can receive any parameters (not used here)
- """
- # Refresh graphs if new data is available or refresh is forced
- if self.HasNewData or self.Force:
- self.HasNewData = False
- self.RefreshView()
-
- DebugViewer.RefreshNewData(self, *args, **kwargs)
-
- def NewDataAvailable(self, ticks, *args, **kwargs):
- """
- Called by DataProducer for each tick captured or by panel to refresh
- graphs
- @param tick: PLC tick captured
- All other parameters are passed to refresh function
- """
- # If tick given
- if ticks is not None:
- tick = ticks[-1]
-
- # Save tick as start tick for range if data is still empty
- if len(self.Ticks) == 0:
- self.StartTick = ticks[0]
-
- # Add tick to list of ticks received
- self.Ticks = numpy.append(self.Ticks, ticks)
-
- # Update start tick for range if range follow ticks received
- if not self.Fixed or tick < self.StartTick + self.CurrentRange:
- self.StartTick = max(self.StartTick, tick - self.CurrentRange)
-
- # Force refresh if graph is fixed because range of data received
- # is too small to fill data range selected
- if self.Fixed and \
- self.Ticks[-1] - self.Ticks[0] < self.CurrentRange:
- self.Force = True
-
- self.HasNewData = False
- self.RefreshView()
-
- else:
- DebugViewer.NewDataAvailable(self, ticks, *args, **kwargs)
-
- def ForceRefresh(self):
- """
- Called to force refresh of graphs
- """
- self.Force = True
- wx.CallAfter(self.NewDataAvailable, None, True)
-
- def SetCursorTick(self, cursor_tick):
- """
- Set Cursor for displaying values of items at a tick given
- @param cursor_tick: Tick of cursor
- """
- # Save cursor tick
- self.CursorTick = cursor_tick
- self.Fixed = cursor_tick is not None
- self.UpdateCursorTick()
-
- def MoveCursorTick(self, move):
- if self.CursorTick is not None:
- cursor_tick = max(self.Ticks[0],
- min(self.CursorTick + move,
- self.Ticks[-1]))
- cursor_tick_idx = numpy.argmin(numpy.abs(self.Ticks - cursor_tick))
- if self.Ticks[cursor_tick_idx] == self.CursorTick:
- cursor_tick_idx = max(0,
- min(cursor_tick_idx + abs(move) / move,
- len(self.Ticks) - 1))
- self.CursorTick = self.Ticks[cursor_tick_idx]
- self.StartTick = max(self.Ticks[
- numpy.argmin(numpy.abs(self.Ticks -
- self.CursorTick + self.CurrentRange))],
- min(self.StartTick, self.CursorTick))
- self.RefreshCanvasPosition()
- self.UpdateCursorTick()
-
- def ResetCursorTick(self):
- self.CursorTick = None
- self.Fixed = False
- self.UpdateCursorTick()
-
- def UpdateCursorTick(self):
- for panel in self.GraphicPanels:
- if isinstance(panel, DebugVariableGraphicViewer):
- panel.SetCursorTick(self.CursorTick)
- self.ForceRefresh()
-
- def StartDragNDrop(self, panel, item, x_mouse, y_mouse, x_mouse_start, y_mouse_start):
- if len(panel.GetItems()) > 1:
- self.DraggingAxesPanel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
- self.DraggingAxesPanel.SetCursorTick(self.CursorTick)
- width, height = panel.GetSize()
- self.DraggingAxesPanel.SetSize(wx.Size(width, height))
- self.DraggingAxesPanel.ResetGraphics()
- self.DraggingAxesPanel.SetPosition(wx.Point(0, -height))
- else:
- self.DraggingAxesPanel = panel
- self.DraggingAxesBoundingBox = panel.GetAxesBoundingBox(parent_coordinate=True)
- self.DraggingAxesMousePos = wx.Point(
- x_mouse_start - self.DraggingAxesBoundingBox.x,
- y_mouse_start - self.DraggingAxesBoundingBox.y)
- self.MoveDragNDrop(x_mouse, y_mouse)
-
- def MoveDragNDrop(self, x_mouse, y_mouse):
- self.DraggingAxesBoundingBox.x = x_mouse - self.DraggingAxesMousePos.x
- self.DraggingAxesBoundingBox.y = y_mouse - self.DraggingAxesMousePos.y
- self.RefreshHighlight(x_mouse, y_mouse)
-
- def RefreshHighlight(self, x_mouse, y_mouse):
- for idx, panel in enumerate(self.GraphicPanels):
- x, y = panel.GetPosition()
- width, height = panel.GetSize()
- rect = wx.Rect(x, y, width, height)
- if (rect.InsideXY(x_mouse, y_mouse) or
- idx == 0 and y_mouse < 0 or
- idx == len(self.GraphicPanels) - 1 and y_mouse > panel.GetPosition()[1]):
- panel.RefreshHighlight(x_mouse - x, y_mouse - y)
- else:
- panel.SetHighlight(HIGHLIGHT_NONE)
- if wx.Platform == "__WXMSW__":
- self.RefreshView()
- else:
- self.ForceRefresh()
-
- def ResetHighlight(self):
- for panel in self.GraphicPanels:
- panel.SetHighlight(HIGHLIGHT_NONE)
- if wx.Platform == "__WXMSW__":
- self.RefreshView()
- else:
- self.ForceRefresh()
-
- def IsDragging(self):
- return self.DraggingAxesPanel is not None
-
- def GetDraggingAxesClippingRegion(self, panel):
- x, y = panel.GetPosition()
- width, height = panel.GetSize()
- bbox = wx.Rect(x, y, width, height)
- bbox = bbox.Intersect(self.DraggingAxesBoundingBox)
- bbox.x -= x
- bbox.y -= y
- return bbox
-
- def GetDraggingAxesPosition(self, panel):
- x, y = panel.GetPosition()
- return wx.Point(self.DraggingAxesBoundingBox.x - x,
- self.DraggingAxesBoundingBox.y - y)
-
- def StopDragNDrop(self, variable, x_mouse, y_mouse):
- if self.DraggingAxesPanel not in self.GraphicPanels:
- self.DraggingAxesPanel.Destroy()
- self.DraggingAxesPanel = None
- self.DraggingAxesBoundingBox = None
- self.DraggingAxesMousePos = None
- for idx, panel in enumerate(self.GraphicPanels):
- panel.SetHighlight(HIGHLIGHT_NONE)
- xw, yw = panel.GetPosition()
- width, height = panel.GetSize()
- bbox = wx.Rect(xw, yw, width, height)
- if bbox.InsideXY(x_mouse, y_mouse):
- panel.ShowButtons(True)
- merge_type = GRAPH_PARALLEL
- if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas():
- if y_mouse > yw + height / 2:
- idx += 1
- wx.CallAfter(self.MoveValue, variable, idx, True)
- else:
- rect = panel.GetAxesBoundingBox(True)
- if rect.InsideXY(x_mouse, y_mouse):
- merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height)
- if merge_rect.InsideXY(x_mouse, y_mouse):
- merge_type = GRAPH_ORTHOGONAL
- wx.CallAfter(self.MergeGraphs, variable, idx, merge_type, force=True)
- else:
- if y_mouse > yw + height / 2:
- idx += 1
- wx.CallAfter(self.MoveValue, variable, idx, True)
- self.ForceRefresh()
- return
- width, height = self.GraphicsWindow.GetVirtualSize()
- rect = wx.Rect(0, 0, width, height)
- if rect.InsideXY(x_mouse, y_mouse):
- wx.CallAfter(self.MoveValue, variable, len(self.GraphicPanels), True)
- self.ForceRefresh()
-
- def RefreshGraphicsSizer(self):
- self.GraphicsSizer.Clear()
-
- for panel in self.GraphicPanels:
- self.GraphicsSizer.AddWindow(panel, flag=wx.GROW)
-
- self.GraphicsSizer.Layout()
- self.RefreshGraphicsWindowScrollbars()
-
- def RefreshView(self):
- self.RefreshCanvasPosition()
-
- width, height = self.GraphicsWindow.GetVirtualSize()
- bitmap = wx.EmptyBitmap(width, height)
- dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap)
- dc.Clear()
- dc.BeginDrawing()
- if self.DraggingAxesPanel is not None:
- destBBox = self.DraggingAxesBoundingBox
- srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox()
-
- srcBmp = _convert_agg_to_wx_bitmap(self.DraggingAxesPanel.get_renderer(), None)
- srcDC = wx.MemoryDC()
- srcDC.SelectObject(srcBmp)
-
- dc.Blit(destBBox.x, destBBox.y,
- int(destBBox.width), int(destBBox.height),
- srcDC, srcBBox.x, srcBBox.y)
- dc.EndDrawing()
-
- if not self.Fixed or self.Force:
- self.Force = False
- refresh_graphics = True
- else:
- refresh_graphics = False
-
- if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels:
- self.DraggingAxesPanel.RefreshViewer(refresh_graphics)
- for panel in self.GraphicPanels:
- if isinstance(panel, DebugVariableGraphicViewer):
- panel.RefreshViewer(refresh_graphics)
- else:
- panel.RefreshViewer()
-
- if self.CursorTick is not None:
- tick = self.CursorTick
- elif len(self.Ticks) > 0:
- tick = self.Ticks[-1]
- else:
- tick = None
- if tick is not None:
- self.TickLabel.SetLabel("Tick: %d" % tick)
- tick_duration = int(tick * self.Ticktime)
- not_null = False
- duration = ""
- for value, format in [(tick_duration / DAY, "%dd"),
- ((tick_duration % DAY) / HOUR, "%dh"),
- ((tick_duration % HOUR) / MINUTE, "%dm"),
- ((tick_duration % MINUTE) / SECOND, "%ds")]:
-
- if value > 0 or not_null:
- duration += format % value
- not_null = True
-
- duration += "%gms" % (float(tick_duration % SECOND) / MILLISECOND)
- self.TickTimeLabel.SetLabel("t: %s" % duration)
- else:
- self.TickLabel.SetLabel("")
- self.TickTimeLabel.SetLabel("")
- self.TickSizer.Layout()
-
- def SubscribeAllDataConsumers(self):
- DebugViewer.SubscribeAllDataConsumers(self)
-
- if self.DataProducer is not None:
- if self.DataProducer is not None:
- self.SetTickTime(self.DataProducer.GetTicktime())
-
- self.ResetCursorTick()
-
- for panel in self.GraphicPanels[:]:
- panel.SubscribeAllDataConsumers()
- if panel.ItemsIsEmpty():
- if panel.HasCapture():
- panel.ReleaseMouse()
- self.GraphicPanels.remove(panel)
- panel.Destroy()
-
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- self.ForceRefresh()
-
- def ResetView(self):
- self.UnsubscribeAllDataConsumers()
-
- self.Fixed = False
- for panel in self.GraphicPanels:
- panel.Destroy()
- self.GraphicPanels = []
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
-
- def SetCanvasPosition(self, tick):
- tick = max(self.Ticks[0], min(tick, self.Ticks[-1] - self.CurrentRange))
- self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - tick))]
- self.Fixed = True
- self.RefreshCanvasPosition()
- self.ForceRefresh()
-
- def RefreshCanvasPosition(self):
- if len(self.Ticks) > 0:
- pos = int(self.StartTick - self.Ticks[0])
- range = int(self.Ticks[-1] - self.Ticks[0])
- else:
- pos = 0
- range = 0
- self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange)
-
- def ChangeRange(self, dir, tick=None):
- current_range = self.CurrentRange
- current_range_idx = self.CanvasRange.GetSelection()
- new_range_idx = max(0, min(current_range_idx + dir, len(RANGE_VALUES) - 1))
- if new_range_idx != current_range_idx:
- self.CanvasRange.SetSelection(new_range_idx)
- self.CurrentRange = RANGE_VALUES[new_range_idx][1] / self.Ticktime
- if len(self.Ticks) > 0:
- if tick is None:
- tick = self.StartTick + self.CurrentRange / 2.
- new_start_tick = min(tick - (tick - self.StartTick) * self.CurrentRange / current_range,
- self.Ticks[-1] - self.CurrentRange)
- self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - new_start_tick))]
- self.Fixed = new_start_tick < self.Ticks[-1] - self.CurrentRange
- self.ForceRefresh()
-
- def RefreshRange(self):
- if len(self.Ticks) > 0:
- if self.Fixed and self.Ticks[-1] - self.Ticks[0] < self.CurrentRange:
- self.Fixed = False
- if self.Fixed:
- self.StartTick = min(self.StartTick, self.Ticks[-1] - self.CurrentRange)
- else:
- self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange)
- self.ForceRefresh()
-
- def OnRangeChanged(self, event):
- try:
- self.CurrentRange = RANGE_VALUES[self.CanvasRange.GetSelection()][1] / self.Ticktime
- except ValueError, e:
- self.CanvasRange.SetValue(str(self.CurrentRange))
- wx.CallAfter(self.RefreshRange)
- event.Skip()
-
- def OnCurrentButton(self, event):
- if len(self.Ticks) > 0:
- self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange)
- self.ResetCursorTick()
- event.Skip()
-
- def CopyDataToClipboard(self, variables):
- text = "tick;%s;\n" % ";".join([item.GetVariable() for item, data in variables])
- next_tick = NextTick(variables)
- while next_tick is not None:
- values = []
- for item, data in variables:
- if len(data) > 0:
- if next_tick == data[0][0]:
- var_type = item.GetVariableType()
- if var_type in ["STRING", "WSTRING"]:
- value = item.GetRawValue(int(data.pop(0)[2]))
- if var_type == "STRING":
- values.append("'%s'" % value)
- else:
- values.append('"%s"' % value)
- else:
- values.append("%.3f" % data.pop(0)[1])
- else:
- values.append("")
- else:
- values.append("")
- text += "%d;%s;\n" % (next_tick, ";".join(values))
- next_tick = NextTick(variables)
- self.ParentWindow.SetCopyBuffer(text)
-
- def OnExportGraphButton(self, event):
- items = reduce(lambda x, y: x + y,
- [panel.GetItems() for panel in self.GraphicPanels],
- [])
- variables = [(item, [entry for entry in item.GetData()])
- for item in items
- if item.IsNumVariable()]
- wx.CallAfter(self.CopyDataToClipboard, variables)
- event.Skip()
-
- def OnPositionChanging(self, event):
- if len(self.Ticks) > 0:
- self.StartTick = self.Ticks[0] + event.GetPosition()
- self.Fixed = True
- self.ForceRefresh()
- event.Skip()
-
- def GetRange(self):
- return self.StartTick, self.StartTick + self.CurrentRange
-
- def GetViewerIndex(self, viewer):
- if viewer in self.GraphicPanels:
- return self.GraphicPanels.index(viewer)
- return None
-
- def IsViewerFirst(self, viewer):
- return viewer == self.GraphicPanels[0]
-
- def HighlightPreviousViewer(self, viewer):
- if self.IsViewerFirst(viewer):
- return
- idx = self.GetViewerIndex(viewer)
- if idx is None:
- return
- self.GraphicPanels[idx-1].SetHighlight(HIGHLIGHT_AFTER)
-
- def ResetVariableNameMask(self):
- items = []
- for panel in self.GraphicPanels:
- items.extend(panel.GetItems())
- if len(items) > 1:
- self.VariableNameMask = reduce(compute_mask,
- [item.GetVariable().split('.') for item in items])
- elif len(items) > 0:
- self.VariableNameMask = items[0].GetVariable().split('.')[:-1] + ['*']
- else:
- self.VariableNameMask = []
- self.MaskLabel.ChangeValue(".".join(self.VariableNameMask))
- self.MaskLabel.SetInsertionPoint(self.MaskLabel.GetLastPosition())
-
- def GetVariableNameMask(self):
- return self.VariableNameMask
-
- def InsertValue(self, iec_path, idx = None, force=False, graph=False):
- for panel in self.GraphicPanels:
- if panel.GetItem(iec_path) is not None:
- if graph and isinstance(panel, DebugVariableTextViewer):
- self.ToggleViewerType(panel)
- return
- if idx is None:
- idx = len(self.GraphicPanels)
- item = DebugVariableItem(self, iec_path, True)
- result = self.AddDataConsumer(iec_path.upper(), item)
- if result is not None or force:
-
- self.Freeze()
- if item.IsNumVariable() and graph:
- panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
- if self.CursorTick is not None:
- panel.SetCursorTick(self.CursorTick)
- else:
- panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
- if idx is not None:
- self.GraphicPanels.insert(idx, panel)
- else:
- self.GraphicPanels.append(panel)
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- self.Thaw()
- self.ForceRefresh()
-
- def MoveValue(self, iec_path, idx = None, graph=False):
- if idx is None:
- idx = len(self.GraphicPanels)
- source_panel = None
- item = None
- for panel in self.GraphicPanels:
- item = panel.GetItem(iec_path)
- if item is not None:
- source_panel = panel
- break
- if source_panel is not None:
- source_panel_idx = self.GraphicPanels.index(source_panel)
-
- if (len(source_panel.GetItems()) == 1):
-
- if source_panel_idx < idx:
- self.GraphicPanels.insert(idx, source_panel)
- self.GraphicPanels.pop(source_panel_idx)
- elif source_panel_idx > idx:
- self.GraphicPanels.pop(source_panel_idx)
- self.GraphicPanels.insert(idx, source_panel)
- else:
- return
-
- else:
- source_panel.RemoveItem(item)
- source_size = source_panel.GetSize()
- if item.IsNumVariable() and graph:
- panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
- panel.SetCanvasHeight(source_size.height)
- if self.CursorTick is not None:
- panel.SetCursorTick(self.CursorTick)
-
- else:
- panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
-
- self.GraphicPanels.insert(idx, panel)
-
- if source_panel.ItemsIsEmpty():
- if source_panel.HasCapture():
- source_panel.ReleaseMouse()
- source_panel.Destroy()
- self.GraphicPanels.remove(source_panel)
-
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- self.ForceRefresh()
-
- def MergeGraphs(self, source, target_idx, merge_type, force=False):
- source_item = None
- source_panel = None
- for panel in self.GraphicPanels:
- source_item = panel.GetItem(source)
- if source_item is not None:
- source_panel = panel
- break
- if source_item is None:
- item = DebugVariableItem(self, source, True)
- if item.IsNumVariable():
- result = self.AddDataConsumer(source.upper(), item)
- if result is not None or force:
- source_item = item
- if source_item is not None and source_item.IsNumVariable():
- if source_panel is not None:
- source_size = source_panel.GetSize()
- else:
- source_size = None
- target_panel = self.GraphicPanels[target_idx]
- graph_type = target_panel.GraphType
- if target_panel != source_panel:
- if (merge_type == GRAPH_PARALLEL and graph_type != merge_type or
- merge_type == GRAPH_ORTHOGONAL and
- (graph_type == GRAPH_PARALLEL and len(target_panel.Items) > 1 or
- graph_type == GRAPH_ORTHOGONAL and len(target_panel.Items) >= 3)):
- return
-
- if source_panel is not None:
- source_panel.RemoveItem(source_item)
- if source_panel.ItemsIsEmpty():
- if source_panel.HasCapture():
- source_panel.ReleaseMouse()
- source_panel.Destroy()
- self.GraphicPanels.remove(source_panel)
- elif (merge_type != graph_type and len(target_panel.Items) == 2):
- target_panel.RemoveItem(source_item)
- else:
- target_panel = None
-
- if target_panel is not None:
- target_panel.AddItem(source_item)
- target_panel.GraphType = merge_type
- size = target_panel.GetSize()
- if merge_type == GRAPH_ORTHOGONAL:
- target_panel.SetCanvasHeight(size.width)
- elif source_size is not None and source_panel != target_panel:
- target_panel.SetCanvasHeight(size.height + source_size.height)
- else:
- target_panel.SetCanvasHeight(size.height)
- target_panel.ResetGraphics()
-
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- self.ForceRefresh()
-
- def DeleteValue(self, source_panel, item=None):
- source_idx = self.GetViewerIndex(source_panel)
- if source_idx is not None:
-
- if item is None:
- source_panel.ClearItems()
- source_panel.Destroy()
- self.GraphicPanels.remove(source_panel)
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- else:
- source_panel.RemoveItem(item)
- if source_panel.ItemsIsEmpty():
- source_panel.Destroy()
- self.GraphicPanels.remove(source_panel)
- self.ResetVariableNameMask()
- self.RefreshGraphicsSizer()
- if len(self.GraphicPanels) == 0:
- self.Fixed = False
- self.ResetCursorTick()
- self.ForceRefresh()
-
- def ToggleViewerType(self, panel):
- panel_idx = self.GetViewerIndex(panel)
- if panel_idx is not None:
- self.GraphicPanels.remove(panel)
- items = panel.GetItems()
- if isinstance(panel, DebugVariableGraphicViewer):
- for idx, item in enumerate(items):
- new_panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
- self.GraphicPanels.insert(panel_idx + idx, new_panel)
- else:
- new_panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, items, GRAPH_PARALLEL)
- self.GraphicPanels.insert(panel_idx, new_panel)
- panel.Destroy()
- self.RefreshGraphicsSizer()
- self.ForceRefresh()
-
- def ResetGraphicsValues(self):
- self.Ticks = numpy.array([])
- self.StartTick = 0
- for panel in self.GraphicPanels:
- panel.ResetItemsData()
- self.ResetCursorTick()
-
- def RefreshGraphicsWindowScrollbars(self):
- xstart, ystart = self.GraphicsWindow.GetViewStart()
- window_size = self.GraphicsWindow.GetClientSize()
- vwidth, vheight = self.GraphicsSizer.GetMinSize()
- posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT))
- posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT))
- self.GraphicsWindow.Scroll(posx, posy)
- self.GraphicsWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
- vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT, posx, posy)
-
- def OnGraphicsWindowEraseBackground(self, event):
- pass
-
- def OnGraphicsWindowPaint(self, event):
- self.RefreshView()
- event.Skip()
-
- def OnGraphicsWindowResize(self, event):
- size = self.GetSize()
- for panel in self.GraphicPanels:
- panel_size = panel.GetSize()
- if (isinstance(panel, DebugVariableGraphicViewer) and
- panel.GraphType == GRAPH_ORTHOGONAL and
- panel_size.width == panel_size.height):
- panel.SetCanvasHeight(size.width)
- self.RefreshGraphicsWindowScrollbars()
- self.GraphicsSizer.Layout()
- event.Skip()
-
- def OnGraphicsWindowMouseWheel(self, event):
- if self.VetoScrollEvent:
- self.VetoScrollEvent = False
- else:
- event.Skip()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/controls/DebugVariablePanel/DebugVariablePanel.py Mon Oct 14 10:49:04 2013 +0200
@@ -0,0 +1,958 @@
+#!/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) 2012: 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 types import TupleType
+import math
+import numpy
+
+import wx
+import wx.lib.buttons
+
+import matplotlib
+import matplotlib.pyplot
+from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
+
+from editors.DebugViewer import DebugViewer
+from util.BitmapLibrary import GetBitmap
+
+from DebugVariableItem import DebugVariableItem
+from DebugVariableTextViewer import DebugVariableTextViewer
+from DebugVariableGraphicViewer import *
+
+MILLISECOND = 1000000 # Number of nanosecond in a millisecond
+SECOND = 1000 * MILLISECOND # Number of nanosecond in a second
+MINUTE = 60 * SECOND # Number of nanosecond in a minute
+HOUR = 60 * MINUTE # Number of nanosecond in a hour
+DAY = 24 * HOUR # Number of nanosecond in a day
+
+# List of values possible for graph range
+# Format is [(time_in_plain_text, value_in_nanosecond),...]
+RANGE_VALUES = \
+ [("%dms" % i, i * MILLISECOND) for i in (10, 20, 50, 100, 200, 500)] + \
+ [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \
+ [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \
+ [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)]
+
+# Scrollbar increment in pixel
+SCROLLBAR_UNIT = 10
+
+def compute_mask(x, y):
+ return [(xp if xp == yp else "*")
+ for xp, yp in zip(x, y)]
+
+def NextTick(variables):
+ next_tick = None
+ for item, data in variables:
+ if len(data) == 0:
+ continue
+
+ next_tick = (data[0][0]
+ if next_tick is None
+ else min(next_tick, data[0][0]))
+
+ return next_tick
+
+#-------------------------------------------------------------------------------
+# Debug Variable Graphic Panel Drop Target
+#-------------------------------------------------------------------------------
+
+"""
+Class that implements a custom drop target class for Debug Variable Graphic
+Panel
+"""
+
+class DebugVariableDropTarget(wx.TextDropTarget):
+
+ def __init__(self, window):
+ """
+ Constructor
+ @param window: Reference to the Debug Variable Panel
+ """
+ wx.TextDropTarget.__init__(self)
+ self.ParentWindow = window
+
+ def __del__(self):
+ """
+ Destructor
+ """
+ # Remove reference to Debug Variable Panel
+ self.ParentWindow = None
+
+ def OnDragOver(self, x, y, d):
+ """
+ Function called when mouse is dragged over Drop Target
+ @param x: X coordinate of mouse pointer
+ @param y: Y coordinate of mouse pointer
+ @param d: Suggested default for return value
+ """
+ # Signal Debug Variable Panel to refresh highlight giving mouse position
+ self.ParentWindow.RefreshHighlight(x, y)
+ return wx.TextDropTarget.OnDragOver(self, x, y, d)
+
+ def OnDropText(self, x, y, data):
+ """
+ Function called when mouse is released in Drop Target
+ @param x: X coordinate of mouse pointer
+ @param y: Y coordinate of mouse pointer
+ @param data: Text associated to drag'n drop
+ """
+ # Signal Debug Variable Panel to reset highlight
+ self.ParentWindow.ResetHighlight()
+
+ message = None
+
+ # Check that data is valid regarding DebugVariablePanel
+ try:
+ values = eval(data)
+ if not isinstance(values, TupleType):
+ raise ValueError
+ except:
+ message = _("Invalid value \"%s\" for debug variable")%data
+ values = None
+
+ # Display message if data is invalid
+ if message is not None:
+ wx.CallAfter(self.ShowMessage, message)
+
+ # Data contain a reference to a variable to debug
+ elif values[1] == "debug":
+
+ # Drag'n Drop is an internal is an internal move inside Debug
+ # Variable Panel
+ if len(values) > 2 and values[2] == "move":
+ self.ParentWindow.MoveValue(values[0])
+
+ # Drag'n Drop was initiated by another control of Beremiz
+ else:
+ self.ParentWindow.InsertValue(values[0], force=True)
+
+ def OnLeave(self):
+ """
+ Function called when mouse is leave Drop Target
+ """
+ # Signal Debug Variable Panel to reset highlight
+ self.ParentWindow.ResetHighlight()
+ return wx.TextDropTarget.OnLeave(self)
+
+ def ShowMessage(self, message):
+ """
+ Show error message in Error Dialog
+ @param message: Error message to display
+ """
+ dialog = wx.MessageDialog(self.ParentWindow,
+ message,
+ _("Error"),
+ wx.OK|wx.ICON_ERROR)
+ dialog.ShowModal()
+ dialog.Destroy()
+
+
+#-------------------------------------------------------------------------------
+# Debug Variable Graphic Panel Class
+#-------------------------------------------------------------------------------
+
+"""
+Class that implements a Viewer that display variable values as a graphs
+"""
+
+class DebugVariablePanel(wx.Panel, DebugViewer):
+
+ def __init__(self, parent, producer, window):
+ """
+ Constructor
+ @param parent: Reference to the parent wx.Window
+ @param producer: Object receiving debug value and dispatching them to
+ consumers
+ @param window: Reference to Beremiz frame
+ """
+ wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL)
+
+ # Save Reference to Beremiz frame
+ self.ParentWindow = window
+
+ # Variable storing flag indicating that variable displayed in table
+ # received new value and then table need to be refreshed
+ self.HasNewData = False
+
+ # Variable storing flag indicating that refresh has been forced, and
+ # that next time refresh is possible, it will be done even if no new
+ # data is available
+ self.Force = False
+
+ self.SetBackgroundColour(wx.WHITE)
+
+ main_sizer = wx.BoxSizer(wx.VERTICAL)
+
+ self.Ticks = numpy.array([]) # List of tick received
+ self.StartTick = 0 # Tick starting range of data displayed
+ self.Fixed = False # Flag that range of data is fixed
+ self.CursorTick = None # Tick of cursor for displaying values
+
+ self.DraggingAxesPanel = None
+ self.DraggingAxesBoundingBox = None
+ self.DraggingAxesMousePos = None
+ self.VetoScrollEvent = False
+
+ self.VariableNameMask = []
+
+ self.GraphicPanels = []
+
+ graphics_button_sizer = wx.BoxSizer(wx.HORIZONTAL)
+ main_sizer.AddSizer(graphics_button_sizer, border=5, flag=wx.GROW|wx.ALL)
+
+ range_label = wx.StaticText(self, label=_('Range:'))
+ graphics_button_sizer.AddWindow(range_label, flag=wx.ALIGN_CENTER_VERTICAL)
+
+ self.CanvasRange = wx.ComboBox(self, style=wx.CB_READONLY)
+ self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange)
+ graphics_button_sizer.AddWindow(self.CanvasRange, 1,
+ border=5, flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL)
+
+ self.CanvasRange.Clear()
+ default_range_idx = 0
+ for idx, (text, value) in enumerate(RANGE_VALUES):
+ self.CanvasRange.Append(text)
+ if text == "1s":
+ default_range_idx = idx
+ self.CanvasRange.SetSelection(default_range_idx)
+
+ for name, bitmap, help in [
+ ("CurrentButton", "current", _("Go to current value")),
+ ("ExportGraphButton", "export_graph", _("Export graph values to clipboard"))]:
+ button = wx.lib.buttons.GenBitmapButton(self,
+ bitmap=GetBitmap(bitmap),
+ size=wx.Size(28, 28), style=wx.NO_BORDER)
+ button.SetToolTipString(help)
+ setattr(self, name, button)
+ self.Bind(wx.EVT_BUTTON, getattr(self, "On" + name), button)
+ graphics_button_sizer.AddWindow(button, border=5, flag=wx.LEFT)
+
+ self.CanvasPosition = wx.ScrollBar(self,
+ size=wx.Size(0, 16), style=wx.SB_HORIZONTAL)
+ self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK,
+ self.OnPositionChanging, self.CanvasPosition)
+ self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP,
+ self.OnPositionChanging, self.CanvasPosition)
+ self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN,
+ self.OnPositionChanging, self.CanvasPosition)
+ self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP,
+ self.OnPositionChanging, self.CanvasPosition)
+ self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN,
+ self.OnPositionChanging, self.CanvasPosition)
+ main_sizer.AddWindow(self.CanvasPosition, border=5, flag=wx.GROW|wx.LEFT|wx.RIGHT|wx.BOTTOM)
+
+ self.TickSizer = wx.BoxSizer(wx.HORIZONTAL)
+ main_sizer.AddSizer(self.TickSizer, border=5, flag=wx.ALL|wx.GROW)
+
+ self.TickLabel = wx.StaticText(self)
+ self.TickSizer.AddWindow(self.TickLabel, border=5, flag=wx.RIGHT)
+
+ self.MaskLabel = wx.TextCtrl(self, style=wx.TE_READONLY|wx.TE_CENTER|wx.NO_BORDER)
+ self.TickSizer.AddWindow(self.MaskLabel, 1, border=5, flag=wx.RIGHT|wx.GROW)
+
+ self.TickTimeLabel = wx.StaticText(self)
+ self.TickSizer.AddWindow(self.TickTimeLabel)
+
+ self.GraphicsWindow = wx.ScrolledWindow(self, style=wx.HSCROLL|wx.VSCROLL)
+ self.GraphicsWindow.SetBackgroundColour(wx.WHITE)
+ self.GraphicsWindow.SetDropTarget(DebugVariableDropTarget(self))
+ self.GraphicsWindow.Bind(wx.EVT_ERASE_BACKGROUND, self.OnGraphicsWindowEraseBackground)
+ self.GraphicsWindow.Bind(wx.EVT_PAINT, self.OnGraphicsWindowPaint)
+ self.GraphicsWindow.Bind(wx.EVT_SIZE, self.OnGraphicsWindowResize)
+ self.GraphicsWindow.Bind(wx.EVT_MOUSEWHEEL, self.OnGraphicsWindowMouseWheel)
+
+ main_sizer.AddWindow(self.GraphicsWindow, 1, flag=wx.GROW)
+
+ self.GraphicsSizer = wx.BoxSizer(wx.VERTICAL)
+ self.GraphicsWindow.SetSizer(self.GraphicsSizer)
+
+ DebugViewer.__init__(self, producer, True)
+
+ self.SetSizer(main_sizer)
+
+ def SetTickTime(self, ticktime=0):
+ """
+ Set Ticktime for calculate data range according to time range selected
+ @param ticktime: Ticktime to apply to range (default: 0)
+ """
+ # Save ticktime
+ self.Ticktime = ticktime
+
+ # Set ticktime to millisecond if undefined
+ if self.Ticktime == 0:
+ self.Ticktime = MILLISECOND
+
+ # Calculate range to apply to data
+ self.CurrentRange = RANGE_VALUES[
+ self.CanvasRange.GetSelection()][1] / self.Ticktime
+
+ def SetDataProducer(self, producer):
+ """
+ Set Data Producer
+ @param producer: Data Producer
+ """
+ DebugViewer.SetDataProducer(self, producer)
+
+ # Set ticktime if data producer is available
+ if self.DataProducer is not None:
+ self.SetTickTime(self.DataProducer.GetTicktime())
+
+ def RefreshNewData(self, *args, **kwargs):
+ """
+ Called to refresh Panel according to values received by variables
+ Can receive any parameters (not used here)
+ """
+ # Refresh graphs if new data is available or refresh is forced
+ if self.HasNewData or self.Force:
+ self.HasNewData = False
+ self.RefreshView()
+
+ DebugViewer.RefreshNewData(self, *args, **kwargs)
+
+ def NewDataAvailable(self, ticks, *args, **kwargs):
+ """
+ Called by DataProducer for each tick captured or by panel to refresh
+ graphs
+ @param tick: PLC tick captured
+ All other parameters are passed to refresh function
+ """
+ # If tick given
+ if ticks is not None:
+ tick = ticks[-1]
+
+ # Save tick as start tick for range if data is still empty
+ if len(self.Ticks) == 0:
+ self.StartTick = ticks[0]
+
+ # Add tick to list of ticks received
+ self.Ticks = numpy.append(self.Ticks, ticks)
+
+ # Update start tick for range if range follow ticks received
+ if not self.Fixed or tick < self.StartTick + self.CurrentRange:
+ self.StartTick = max(self.StartTick, tick - self.CurrentRange)
+
+ # Force refresh if graph is fixed because range of data received
+ # is too small to fill data range selected
+ if self.Fixed and \
+ self.Ticks[-1] - self.Ticks[0] < self.CurrentRange:
+ self.Force = True
+
+ self.HasNewData = False
+ self.RefreshView()
+
+ else:
+ DebugViewer.NewDataAvailable(self, ticks, *args, **kwargs)
+
+ def ForceRefresh(self):
+ """
+ Called to force refresh of graphs
+ """
+ self.Force = True
+ wx.CallAfter(self.NewDataAvailable, None, True)
+
+ def SetCursorTick(self, cursor_tick):
+ """
+ Set Cursor for displaying values of items at a tick given
+ @param cursor_tick: Tick of cursor
+ """
+ # Save cursor tick
+ self.CursorTick = cursor_tick
+ self.Fixed = cursor_tick is not None
+ self.UpdateCursorTick()
+
+ def MoveCursorTick(self, move):
+ if self.CursorTick is not None:
+ cursor_tick = max(self.Ticks[0],
+ min(self.CursorTick + move,
+ self.Ticks[-1]))
+ cursor_tick_idx = numpy.argmin(numpy.abs(self.Ticks - cursor_tick))
+ if self.Ticks[cursor_tick_idx] == self.CursorTick:
+ cursor_tick_idx = max(0,
+ min(cursor_tick_idx + abs(move) / move,
+ len(self.Ticks) - 1))
+ self.CursorTick = self.Ticks[cursor_tick_idx]
+ self.StartTick = max(self.Ticks[
+ numpy.argmin(numpy.abs(self.Ticks -
+ self.CursorTick + self.CurrentRange))],
+ min(self.StartTick, self.CursorTick))
+ self.RefreshCanvasPosition()
+ self.UpdateCursorTick()
+
+ def ResetCursorTick(self):
+ self.CursorTick = None
+ self.Fixed = False
+ self.UpdateCursorTick()
+
+ def UpdateCursorTick(self):
+ for panel in self.GraphicPanels:
+ if isinstance(panel, DebugVariableGraphicViewer):
+ panel.SetCursorTick(self.CursorTick)
+ self.ForceRefresh()
+
+ def StartDragNDrop(self, panel, item, x_mouse, y_mouse, x_mouse_start, y_mouse_start):
+ if len(panel.GetItems()) > 1:
+ self.DraggingAxesPanel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ self.DraggingAxesPanel.SetCursorTick(self.CursorTick)
+ width, height = panel.GetSize()
+ self.DraggingAxesPanel.SetSize(wx.Size(width, height))
+ self.DraggingAxesPanel.ResetGraphics()
+ self.DraggingAxesPanel.SetPosition(wx.Point(0, -height))
+ else:
+ self.DraggingAxesPanel = panel
+ self.DraggingAxesBoundingBox = panel.GetAxesBoundingBox(parent_coordinate=True)
+ self.DraggingAxesMousePos = wx.Point(
+ x_mouse_start - self.DraggingAxesBoundingBox.x,
+ y_mouse_start - self.DraggingAxesBoundingBox.y)
+ self.MoveDragNDrop(x_mouse, y_mouse)
+
+ def MoveDragNDrop(self, x_mouse, y_mouse):
+ self.DraggingAxesBoundingBox.x = x_mouse - self.DraggingAxesMousePos.x
+ self.DraggingAxesBoundingBox.y = y_mouse - self.DraggingAxesMousePos.y
+ self.RefreshHighlight(x_mouse, y_mouse)
+
+ def RefreshHighlight(self, x_mouse, y_mouse):
+ for idx, panel in enumerate(self.GraphicPanels):
+ x, y = panel.GetPosition()
+ width, height = panel.GetSize()
+ rect = wx.Rect(x, y, width, height)
+ if (rect.InsideXY(x_mouse, y_mouse) or
+ idx == 0 and y_mouse < 0 or
+ idx == len(self.GraphicPanels) - 1 and y_mouse > panel.GetPosition()[1]):
+ panel.RefreshHighlight(x_mouse - x, y_mouse - y)
+ else:
+ panel.SetHighlight(HIGHLIGHT_NONE)
+ if wx.Platform == "__WXMSW__":
+ self.RefreshView()
+ else:
+ self.ForceRefresh()
+
+ def ResetHighlight(self):
+ for panel in self.GraphicPanels:
+ panel.SetHighlight(HIGHLIGHT_NONE)
+ if wx.Platform == "__WXMSW__":
+ self.RefreshView()
+ else:
+ self.ForceRefresh()
+
+ def IsDragging(self):
+ return self.DraggingAxesPanel is not None
+
+ def GetDraggingAxesClippingRegion(self, panel):
+ x, y = panel.GetPosition()
+ width, height = panel.GetSize()
+ bbox = wx.Rect(x, y, width, height)
+ bbox = bbox.Intersect(self.DraggingAxesBoundingBox)
+ bbox.x -= x
+ bbox.y -= y
+ return bbox
+
+ def GetDraggingAxesPosition(self, panel):
+ x, y = panel.GetPosition()
+ return wx.Point(self.DraggingAxesBoundingBox.x - x,
+ self.DraggingAxesBoundingBox.y - y)
+
+ def StopDragNDrop(self, variable, x_mouse, y_mouse):
+ if self.DraggingAxesPanel not in self.GraphicPanels:
+ self.DraggingAxesPanel.Destroy()
+ self.DraggingAxesPanel = None
+ self.DraggingAxesBoundingBox = None
+ self.DraggingAxesMousePos = None
+ for idx, panel in enumerate(self.GraphicPanels):
+ panel.SetHighlight(HIGHLIGHT_NONE)
+ xw, yw = panel.GetPosition()
+ width, height = panel.GetSize()
+ bbox = wx.Rect(xw, yw, width, height)
+ if bbox.InsideXY(x_mouse, y_mouse):
+ panel.ShowButtons(True)
+ merge_type = GRAPH_PARALLEL
+ if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas():
+ if y_mouse > yw + height / 2:
+ idx += 1
+ wx.CallAfter(self.MoveValue, variable, idx, True)
+ else:
+ rect = panel.GetAxesBoundingBox(True)
+ if rect.InsideXY(x_mouse, y_mouse):
+ merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height)
+ if merge_rect.InsideXY(x_mouse, y_mouse):
+ merge_type = GRAPH_ORTHOGONAL
+ wx.CallAfter(self.MergeGraphs, variable, idx, merge_type, force=True)
+ else:
+ if y_mouse > yw + height / 2:
+ idx += 1
+ wx.CallAfter(self.MoveValue, variable, idx, True)
+ self.ForceRefresh()
+ return
+ width, height = self.GraphicsWindow.GetVirtualSize()
+ rect = wx.Rect(0, 0, width, height)
+ if rect.InsideXY(x_mouse, y_mouse):
+ wx.CallAfter(self.MoveValue, variable, len(self.GraphicPanels), True)
+ self.ForceRefresh()
+
+ def RefreshGraphicsSizer(self):
+ self.GraphicsSizer.Clear()
+
+ for panel in self.GraphicPanels:
+ self.GraphicsSizer.AddWindow(panel, flag=wx.GROW)
+
+ self.GraphicsSizer.Layout()
+ self.RefreshGraphicsWindowScrollbars()
+
+ def RefreshView(self):
+ self.RefreshCanvasPosition()
+
+ width, height = self.GraphicsWindow.GetVirtualSize()
+ bitmap = wx.EmptyBitmap(width, height)
+ dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap)
+ dc.Clear()
+ dc.BeginDrawing()
+ if self.DraggingAxesPanel is not None:
+ destBBox = self.DraggingAxesBoundingBox
+ srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox()
+
+ srcBmp = _convert_agg_to_wx_bitmap(self.DraggingAxesPanel.get_renderer(), None)
+ srcDC = wx.MemoryDC()
+ srcDC.SelectObject(srcBmp)
+
+ dc.Blit(destBBox.x, destBBox.y,
+ int(destBBox.width), int(destBBox.height),
+ srcDC, srcBBox.x, srcBBox.y)
+ dc.EndDrawing()
+
+ if not self.Fixed or self.Force:
+ self.Force = False
+ refresh_graphics = True
+ else:
+ refresh_graphics = False
+
+ if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels:
+ self.DraggingAxesPanel.RefreshViewer(refresh_graphics)
+ for panel in self.GraphicPanels:
+ if isinstance(panel, DebugVariableGraphicViewer):
+ panel.RefreshViewer(refresh_graphics)
+ else:
+ panel.RefreshViewer()
+
+ if self.CursorTick is not None:
+ tick = self.CursorTick
+ elif len(self.Ticks) > 0:
+ tick = self.Ticks[-1]
+ else:
+ tick = None
+ if tick is not None:
+ self.TickLabel.SetLabel("Tick: %d" % tick)
+ tick_duration = int(tick * self.Ticktime)
+ not_null = False
+ duration = ""
+ for value, format in [(tick_duration / DAY, "%dd"),
+ ((tick_duration % DAY) / HOUR, "%dh"),
+ ((tick_duration % HOUR) / MINUTE, "%dm"),
+ ((tick_duration % MINUTE) / SECOND, "%ds")]:
+
+ if value > 0 or not_null:
+ duration += format % value
+ not_null = True
+
+ duration += "%gms" % (float(tick_duration % SECOND) / MILLISECOND)
+ self.TickTimeLabel.SetLabel("t: %s" % duration)
+ else:
+ self.TickLabel.SetLabel("")
+ self.TickTimeLabel.SetLabel("")
+ self.TickSizer.Layout()
+
+ def SubscribeAllDataConsumers(self):
+ DebugViewer.SubscribeAllDataConsumers(self)
+
+ if self.DataProducer is not None:
+ if self.DataProducer is not None:
+ self.SetTickTime(self.DataProducer.GetTicktime())
+
+ self.ResetCursorTick()
+
+ for panel in self.GraphicPanels[:]:
+ panel.SubscribeAllDataConsumers()
+ if panel.ItemsIsEmpty():
+ if panel.HasCapture():
+ panel.ReleaseMouse()
+ self.GraphicPanels.remove(panel)
+ panel.Destroy()
+
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ self.ForceRefresh()
+
+ def ResetView(self):
+ self.UnsubscribeAllDataConsumers()
+
+ self.Fixed = False
+ for panel in self.GraphicPanels:
+ panel.Destroy()
+ self.GraphicPanels = []
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+
+ def SetCanvasPosition(self, tick):
+ tick = max(self.Ticks[0], min(tick, self.Ticks[-1] - self.CurrentRange))
+ self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - tick))]
+ self.Fixed = True
+ self.RefreshCanvasPosition()
+ self.ForceRefresh()
+
+ def RefreshCanvasPosition(self):
+ if len(self.Ticks) > 0:
+ pos = int(self.StartTick - self.Ticks[0])
+ range = int(self.Ticks[-1] - self.Ticks[0])
+ else:
+ pos = 0
+ range = 0
+ self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange)
+
+ def ChangeRange(self, dir, tick=None):
+ current_range = self.CurrentRange
+ current_range_idx = self.CanvasRange.GetSelection()
+ new_range_idx = max(0, min(current_range_idx + dir, len(RANGE_VALUES) - 1))
+ if new_range_idx != current_range_idx:
+ self.CanvasRange.SetSelection(new_range_idx)
+ self.CurrentRange = RANGE_VALUES[new_range_idx][1] / self.Ticktime
+ if len(self.Ticks) > 0:
+ if tick is None:
+ tick = self.StartTick + self.CurrentRange / 2.
+ new_start_tick = min(tick - (tick - self.StartTick) * self.CurrentRange / current_range,
+ self.Ticks[-1] - self.CurrentRange)
+ self.StartTick = self.Ticks[numpy.argmin(numpy.abs(self.Ticks - new_start_tick))]
+ self.Fixed = new_start_tick < self.Ticks[-1] - self.CurrentRange
+ self.ForceRefresh()
+
+ def RefreshRange(self):
+ if len(self.Ticks) > 0:
+ if self.Fixed and self.Ticks[-1] - self.Ticks[0] < self.CurrentRange:
+ self.Fixed = False
+ if self.Fixed:
+ self.StartTick = min(self.StartTick, self.Ticks[-1] - self.CurrentRange)
+ else:
+ self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange)
+ self.ForceRefresh()
+
+ def OnRangeChanged(self, event):
+ try:
+ self.CurrentRange = RANGE_VALUES[self.CanvasRange.GetSelection()][1] / self.Ticktime
+ except ValueError, e:
+ self.CanvasRange.SetValue(str(self.CurrentRange))
+ wx.CallAfter(self.RefreshRange)
+ event.Skip()
+
+ def OnCurrentButton(self, event):
+ if len(self.Ticks) > 0:
+ self.StartTick = max(self.Ticks[0], self.Ticks[-1] - self.CurrentRange)
+ self.ResetCursorTick()
+ event.Skip()
+
+ def CopyDataToClipboard(self, variables):
+ text = "tick;%s;\n" % ";".join([item.GetVariable() for item, data in variables])
+ next_tick = NextTick(variables)
+ while next_tick is not None:
+ values = []
+ for item, data in variables:
+ if len(data) > 0:
+ if next_tick == data[0][0]:
+ var_type = item.GetVariableType()
+ if var_type in ["STRING", "WSTRING"]:
+ value = item.GetRawValue(int(data.pop(0)[2]))
+ if var_type == "STRING":
+ values.append("'%s'" % value)
+ else:
+ values.append('"%s"' % value)
+ else:
+ values.append("%.3f" % data.pop(0)[1])
+ else:
+ values.append("")
+ else:
+ values.append("")
+ text += "%d;%s;\n" % (next_tick, ";".join(values))
+ next_tick = NextTick(variables)
+ self.ParentWindow.SetCopyBuffer(text)
+
+ def OnExportGraphButton(self, event):
+ items = reduce(lambda x, y: x + y,
+ [panel.GetItems() for panel in self.GraphicPanels],
+ [])
+ variables = [(item, [entry for entry in item.GetData()])
+ for item in items
+ if item.IsNumVariable()]
+ wx.CallAfter(self.CopyDataToClipboard, variables)
+ event.Skip()
+
+ def OnPositionChanging(self, event):
+ if len(self.Ticks) > 0:
+ self.StartTick = self.Ticks[0] + event.GetPosition()
+ self.Fixed = True
+ self.ForceRefresh()
+ event.Skip()
+
+ def GetRange(self):
+ return self.StartTick, self.StartTick + self.CurrentRange
+
+ def GetViewerIndex(self, viewer):
+ if viewer in self.GraphicPanels:
+ return self.GraphicPanels.index(viewer)
+ return None
+
+ def IsViewerFirst(self, viewer):
+ return viewer == self.GraphicPanels[0]
+
+ def HighlightPreviousViewer(self, viewer):
+ if self.IsViewerFirst(viewer):
+ return
+ idx = self.GetViewerIndex(viewer)
+ if idx is None:
+ return
+ self.GraphicPanels[idx-1].SetHighlight(HIGHLIGHT_AFTER)
+
+ def ResetVariableNameMask(self):
+ items = []
+ for panel in self.GraphicPanels:
+ items.extend(panel.GetItems())
+ if len(items) > 1:
+ self.VariableNameMask = reduce(compute_mask,
+ [item.GetVariable().split('.') for item in items])
+ elif len(items) > 0:
+ self.VariableNameMask = items[0].GetVariable().split('.')[:-1] + ['*']
+ else:
+ self.VariableNameMask = []
+ self.MaskLabel.ChangeValue(".".join(self.VariableNameMask))
+ self.MaskLabel.SetInsertionPoint(self.MaskLabel.GetLastPosition())
+
+ def GetVariableNameMask(self):
+ return self.VariableNameMask
+
+ def InsertValue(self, iec_path, idx = None, force=False, graph=False):
+ for panel in self.GraphicPanels:
+ if panel.GetItem(iec_path) is not None:
+ if graph and isinstance(panel, DebugVariableTextViewer):
+ self.ToggleViewerType(panel)
+ return
+ if idx is None:
+ idx = len(self.GraphicPanels)
+ item = DebugVariableItem(self, iec_path, True)
+ result = self.AddDataConsumer(iec_path.upper(), item)
+ if result is not None or force:
+
+ self.Freeze()
+ if item.IsNumVariable() and graph:
+ panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ if self.CursorTick is not None:
+ panel.SetCursorTick(self.CursorTick)
+ else:
+ panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
+ if idx is not None:
+ self.GraphicPanels.insert(idx, panel)
+ else:
+ self.GraphicPanels.append(panel)
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ self.Thaw()
+ self.ForceRefresh()
+
+ def MoveValue(self, iec_path, idx = None, graph=False):
+ if idx is None:
+ idx = len(self.GraphicPanels)
+ source_panel = None
+ item = None
+ for panel in self.GraphicPanels:
+ item = panel.GetItem(iec_path)
+ if item is not None:
+ source_panel = panel
+ break
+ if source_panel is not None:
+ source_panel_idx = self.GraphicPanels.index(source_panel)
+
+ if (len(source_panel.GetItems()) == 1):
+
+ if source_panel_idx < idx:
+ self.GraphicPanels.insert(idx, source_panel)
+ self.GraphicPanels.pop(source_panel_idx)
+ elif source_panel_idx > idx:
+ self.GraphicPanels.pop(source_panel_idx)
+ self.GraphicPanels.insert(idx, source_panel)
+ else:
+ return
+
+ else:
+ source_panel.RemoveItem(item)
+ source_size = source_panel.GetSize()
+ if item.IsNumVariable() and graph:
+ panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ panel.SetCanvasHeight(source_size.height)
+ if self.CursorTick is not None:
+ panel.SetCursorTick(self.CursorTick)
+
+ else:
+ panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
+
+ self.GraphicPanels.insert(idx, panel)
+
+ if source_panel.ItemsIsEmpty():
+ if source_panel.HasCapture():
+ source_panel.ReleaseMouse()
+ source_panel.Destroy()
+ self.GraphicPanels.remove(source_panel)
+
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ self.ForceRefresh()
+
+ def MergeGraphs(self, source, target_idx, merge_type, force=False):
+ source_item = None
+ source_panel = None
+ for panel in self.GraphicPanels:
+ source_item = panel.GetItem(source)
+ if source_item is not None:
+ source_panel = panel
+ break
+ if source_item is None:
+ item = DebugVariableItem(self, source, True)
+ if item.IsNumVariable():
+ result = self.AddDataConsumer(source.upper(), item)
+ if result is not None or force:
+ source_item = item
+ if source_item is not None and source_item.IsNumVariable():
+ if source_panel is not None:
+ source_size = source_panel.GetSize()
+ else:
+ source_size = None
+ target_panel = self.GraphicPanels[target_idx]
+ graph_type = target_panel.GraphType
+ if target_panel != source_panel:
+ if (merge_type == GRAPH_PARALLEL and graph_type != merge_type or
+ merge_type == GRAPH_ORTHOGONAL and
+ (graph_type == GRAPH_PARALLEL and len(target_panel.Items) > 1 or
+ graph_type == GRAPH_ORTHOGONAL and len(target_panel.Items) >= 3)):
+ return
+
+ if source_panel is not None:
+ source_panel.RemoveItem(source_item)
+ if source_panel.ItemsIsEmpty():
+ if source_panel.HasCapture():
+ source_panel.ReleaseMouse()
+ source_panel.Destroy()
+ self.GraphicPanels.remove(source_panel)
+ elif (merge_type != graph_type and len(target_panel.Items) == 2):
+ target_panel.RemoveItem(source_item)
+ else:
+ target_panel = None
+
+ if target_panel is not None:
+ target_panel.AddItem(source_item)
+ target_panel.GraphType = merge_type
+ size = target_panel.GetSize()
+ if merge_type == GRAPH_ORTHOGONAL:
+ target_panel.SetCanvasHeight(size.width)
+ elif source_size is not None and source_panel != target_panel:
+ target_panel.SetCanvasHeight(size.height + source_size.height)
+ else:
+ target_panel.SetCanvasHeight(size.height)
+ target_panel.ResetGraphics()
+
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ self.ForceRefresh()
+
+ def DeleteValue(self, source_panel, item=None):
+ source_idx = self.GetViewerIndex(source_panel)
+ if source_idx is not None:
+
+ if item is None:
+ source_panel.ClearItems()
+ source_panel.Destroy()
+ self.GraphicPanels.remove(source_panel)
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ else:
+ source_panel.RemoveItem(item)
+ if source_panel.ItemsIsEmpty():
+ source_panel.Destroy()
+ self.GraphicPanels.remove(source_panel)
+ self.ResetVariableNameMask()
+ self.RefreshGraphicsSizer()
+ if len(self.GraphicPanels) == 0:
+ self.Fixed = False
+ self.ResetCursorTick()
+ self.ForceRefresh()
+
+ def ToggleViewerType(self, panel):
+ panel_idx = self.GetViewerIndex(panel)
+ if panel_idx is not None:
+ self.GraphicPanels.remove(panel)
+ items = panel.GetItems()
+ if isinstance(panel, DebugVariableGraphicViewer):
+ for idx, item in enumerate(items):
+ new_panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
+ self.GraphicPanels.insert(panel_idx + idx, new_panel)
+ else:
+ new_panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, items, GRAPH_PARALLEL)
+ self.GraphicPanels.insert(panel_idx, new_panel)
+ panel.Destroy()
+ self.RefreshGraphicsSizer()
+ self.ForceRefresh()
+
+ def ResetGraphicsValues(self):
+ self.Ticks = numpy.array([])
+ self.StartTick = 0
+ for panel in self.GraphicPanels:
+ panel.ResetItemsData()
+ self.ResetCursorTick()
+
+ def RefreshGraphicsWindowScrollbars(self):
+ xstart, ystart = self.GraphicsWindow.GetViewStart()
+ window_size = self.GraphicsWindow.GetClientSize()
+ vwidth, vheight = self.GraphicsSizer.GetMinSize()
+ posx = max(0, min(xstart, (vwidth - window_size[0]) / SCROLLBAR_UNIT))
+ posy = max(0, min(ystart, (vheight - window_size[1]) / SCROLLBAR_UNIT))
+ self.GraphicsWindow.Scroll(posx, posy)
+ self.GraphicsWindow.SetScrollbars(SCROLLBAR_UNIT, SCROLLBAR_UNIT,
+ vwidth / SCROLLBAR_UNIT, vheight / SCROLLBAR_UNIT, posx, posy)
+
+ def OnGraphicsWindowEraseBackground(self, event):
+ pass
+
+ def OnGraphicsWindowPaint(self, event):
+ self.RefreshView()
+ event.Skip()
+
+ def OnGraphicsWindowResize(self, event):
+ size = self.GetSize()
+ for panel in self.GraphicPanels:
+ panel_size = panel.GetSize()
+ if (isinstance(panel, DebugVariableGraphicViewer) and
+ panel.GraphType == GRAPH_ORTHOGONAL and
+ panel_size.width == panel_size.height):
+ panel.SetCanvasHeight(size.width)
+ self.RefreshGraphicsWindowScrollbars()
+ self.GraphicsSizer.Layout()
+ event.Skip()
+
+ def OnGraphicsWindowMouseWheel(self, event):
+ if self.VetoScrollEvent:
+ self.VetoScrollEvent = False
+ else:
+ event.Skip()
--- a/controls/DebugVariablePanel/DebugVariableTablePanel.py Mon Oct 14 10:31:32 2013 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,509 +0,0 @@
-#!/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) 2012: 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 types import TupleType
-
-import wx
-import wx.lib.buttons
-
-from editors.DebugViewer import DebugViewer
-from controls import CustomGrid, CustomTable
-from dialogs.ForceVariableDialog import ForceVariableDialog
-from util.BitmapLibrary import GetBitmap
-
-from DebugVariableItem import DebugVariableItem
-
-def GetDebugVariablesTableColnames():
- """
- Function returning table column header labels
- @return: List of labels [col_label,...]
- """
- _ = lambda x : x
- return [_("Variable"), _("Value")]
-
-#-------------------------------------------------------------------------------
-# Debug Variable Table Panel
-#-------------------------------------------------------------------------------
-
-"""
-Class that implements a custom table storing value to display in Debug Variable
-Table Panel grid
-"""
-
-class DebugVariableTable(CustomTable):
-
- def GetValue(self, row, col):
- if row < self.GetNumberRows():
- return self.GetValueByName(row, self.GetColLabelValue(col, False))
- return ""
-
- def SetValue(self, row, col, value):
- if col < len(self.colnames):
- self.SetValueByName(row, self.GetColLabelValue(col, False), value)
-
- def GetValueByName(self, row, colname):
- if row < self.GetNumberRows():
- if colname == "Variable":
- return self.data[row].GetVariable()
- elif colname == "Value":
- return self.data[row].GetValue()
- return ""
-
- def SetValueByName(self, row, colname, value):
- if row < self.GetNumberRows():
- if colname == "Variable":
- self.data[row].SetVariable(value)
- elif colname == "Value":
- self.data[row].SetValue(value)
-
- def IsForced(self, row):
- if row < self.GetNumberRows():
- return self.data[row].IsForced()
- return False
-
- 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.
- """
-
- for row in range(self.GetNumberRows()):
- for col in range(self.GetNumberCols()):
- colname = self.GetColLabelValue(col, False)
- if colname == "Value":
- if self.IsForced(row):
- grid.SetCellTextColour(row, col, wx.BLUE)
- else:
- grid.SetCellTextColour(row, col, wx.BLACK)
- grid.SetReadOnly(row, col, True)
- self.ResizeRow(grid, row)
-
- def RefreshValues(self, grid):
- for col in xrange(self.GetNumberCols()):
- colname = self.GetColLabelValue(col, False)
- if colname == "Value":
- for row in xrange(self.GetNumberRows()):
- grid.SetCellValue(row, col, str(self.data[row].GetValue()))
- if self.IsForced(row):
- grid.SetCellTextColour(row, col, wx.BLUE)
- else:
- grid.SetCellTextColour(row, col, wx.BLACK)
-
- def AppendItem(self, item):
- self.data.append(item)
-
- def InsertItem(self, idx, item):
- self.data.insert(idx, item)
-
- def RemoveItem(self, item):
- self.data.remove(item)
-
- def MoveItem(self, idx, new_idx):
- self.data.insert(new_idx, self.data.pop(idx))
-
- def GetItem(self, idx):
- return self.data[idx]
-
-
-#-------------------------------------------------------------------------------
-# Debug Variable Table Panel Drop Target
-#-------------------------------------------------------------------------------
-
-"""
-Class that implements a custom drop target class for Debug Variable Table Panel
-"""
-
-class DebugVariableTableDropTarget(wx.TextDropTarget):
-
- def __init__(self, parent):
- """
- Constructor
- @param window: Reference to the Debug Variable Panel
- """
- wx.TextDropTarget.__init__(self)
- self.ParentWindow = parent
-
- def __del__(self):
- """
- Destructor
- """
- # Remove reference to Debug Variable Panel
- self.ParentWindow = None
-
- def OnDropText(self, x, y, data):
- """
- Function called when mouse is dragged over Drop Target
- @param x: X coordinate of mouse pointer
- @param y: Y coordinate of mouse pointer
- @param data: Text associated to drag'n drop
- """
- message = None
-
- # Check that data is valid regarding DebugVariablePanel
- try:
- values = eval(data)
- if not isinstance(values, TupleType):
- raise ValueError
- except:
- message = _("Invalid value \"%s\" for debug variable") % data
- values = None
-
- # Display message if data is invalid
- if message is not None:
- wx.CallAfter(self.ShowMessage, message)
-
- # Data contain a reference to a variable to debug
- elif values[1] == "debug":
- grid = self.ParentWindow.VariablesGrid
-
- # Get row where variable was dropped
- x, y = grid.CalcUnscrolledPosition(x, y)
- row = grid.YToRow(y - grid.GetColLabelSize())
-
- # If no row found add variable at table end
- if row == wx.NOT_FOUND:
- row = self.ParentWindow.Table.GetNumberRows()
-
- # Add variable to table
- self.ParentWindow.InsertValue(values[0], row, force=True)
-
- def ShowMessage(self, message):
- """
- Show error message in Error Dialog
- @param message: Error message to display
- """
- dialog = wx.MessageDialog(self.ParentWindow,
- message,
- _("Error"),
- wx.OK|wx.ICON_ERROR)
- dialog.ShowModal()
- dialog.Destroy()
-
-
-#-------------------------------------------------------------------------------
-# Debug Variable Table Panel
-#-------------------------------------------------------------------------------
-
-"""
-Class that implements a panel displaying debug variable values in a table
-"""
-
-class DebugVariableTablePanel(wx.Panel, DebugViewer):
-
- def __init__(self, parent, producer, window):
- """
- Constructor
- @param parent: Reference to the parent wx.Window
- @param producer: Object receiving debug value and dispatching them to
- consumers
- @param window: Reference to Beremiz frame
- """
- wx.Panel.__init__(self, parent, style=wx.SP_3D|wx.TAB_TRAVERSAL)
-
- # Save Reference to Beremiz frame
- self.ParentWindow = window
-
- # Variable storing flag indicating that variable displayed in table
- # received new value and then table need to be refreshed
- self.HasNewData = False
-
- DebugViewer.__init__(self, producer, True)
-
- # Construction of window layout by creating controls and sizers
-
- main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0)
- main_sizer.AddGrowableCol(0)
- main_sizer.AddGrowableRow(1)
-
- button_sizer = wx.BoxSizer(wx.HORIZONTAL)
- main_sizer.AddSizer(button_sizer, border=5,
- flag=wx.ALIGN_RIGHT|wx.ALL)
-
- # Creation of buttons for navigating in table
-
- for name, bitmap, help in [
- ("DeleteButton", "remove_element", _("Remove debug variable")),
- ("UpButton", "up", _("Move debug variable up")),
- ("DownButton", "down", _("Move debug variable down"))]:
- button = wx.lib.buttons.GenBitmapButton(self,
- bitmap=GetBitmap(bitmap),
- size=wx.Size(28, 28), style=wx.NO_BORDER)
- button.SetToolTipString(help)
- setattr(self, name, button)
- button_sizer.AddWindow(button, border=5, flag=wx.LEFT)
-
- # Creation of grid and associated table
-
- self.VariablesGrid = CustomGrid(self,
- size=wx.Size(-1, 150), style=wx.VSCROLL)
- # Define grid drop target
- self.VariablesGrid.SetDropTarget(DebugVariableTableDropTarget(self))
- self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_RIGHT_CLICK,
- self.OnVariablesGridCellRightClick)
- self.VariablesGrid.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,
- self.OnVariablesGridCellLeftClick)
- main_sizer.AddWindow(self.VariablesGrid, flag=wx.GROW)
-
- self.Table = DebugVariableTable(self, [],
- GetDebugVariablesTableColnames())
- self.VariablesGrid.SetTable(self.Table)
- self.VariablesGrid.SetButtons({"Delete": self.DeleteButton,
- "Up": self.UpButton,
- "Down": self.DownButton})
-
- # Definition of function associated to navigation buttons
-
- def _AddVariable(new_row):
- return self.VariablesGrid.GetGridCursorRow()
- setattr(self.VariablesGrid, "_AddRow", _AddVariable)
-
- def _DeleteVariable(row):
- item = self.Table.GetItem(row)
- self.RemoveDataConsumer(item)
- self.Table.RemoveItem(item)
- self.RefreshView()
- setattr(self.VariablesGrid, "_DeleteRow", _DeleteVariable)
-
- def _MoveVariable(row, move):
- new_row = max(0, min(row + move, self.Table.GetNumberRows() - 1))
- if new_row != row:
- self.Table.MoveItem(row, new_row)
- self.RefreshView()
- return new_row
- setattr(self.VariablesGrid, "_MoveRow", _MoveVariable)
-
- # Initialization of grid layout
-
- self.VariablesGrid.SetRowLabelSize(0)
-
- self.GridColSizes = [200, 100]
-
- for col in range(self.Table.GetNumberCols()):
- attr = wx.grid.GridCellAttr()
- attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
- self.VariablesGrid.SetColAttr(col, attr)
- self.VariablesGrid.SetColSize(col, self.GridColSizes[col])
-
- self.Table.ResetView(self.VariablesGrid)
- self.VariablesGrid.RefreshButtons()
-
- self.SetSizer(main_sizer)
-
- def RefreshNewData(self, *args, **kwargs):
- """
- Called to refresh Table according to values received by variables
- Can receive any parameters (not used here)
- """
- # Refresh 'Value' column of table if new data have been received since
- # last refresh
- if self.HasNewData:
- self.HasNewData = False
- self.RefreshView(only_values=True)
- DebugViewer.RefreshNewData(self, *args, **kwargs)
-
- def RefreshView(self, only_values=False):
- """
- Function refreshing table layout and values
- @param only_values: True if only 'Value' column need to be updated
- """
- # Block refresh until table layout and values are completely updated
- self.Freeze()
-
- # Update only 'value' column from table
- if only_values:
- self.Table.RefreshValues(self.VariablesGrid)
-
- # Update complete table layout refreshing table navigation buttons
- # state according to
- else:
- self.Table.ResetView(self.VariablesGrid)
- self.VariablesGrid.RefreshButtons()
-
- self.Thaw()
-
- def ResetView(self):
- """
- Function removing all variables denugged from table
- @param only_values: True if only 'Value' column need to be updated
- """
- # Unsubscribe all variables debugged
- self.UnsubscribeAllDataConsumers()
-
- # Clear table content
- self.Table.Empty()
-
- # Update table layout
- self.Freeze()
- self.Table.ResetView(self.VariablesGrid)
- self.VariablesGrid.RefreshButtons()
- self.Thaw()
-
- def SubscribeAllDataConsumers(self):
- """
- Function refreshing table layout and values
- @param only_values: True if only 'Value' column need to be updated
- """
- DebugViewer.SubscribeAllDataConsumers(self)
-
- # Navigate through variable displayed in table, removing those that
- # doesn't exist anymore in PLC
- for item in self.Table.GetData()[:]:
- iec_path = item.GetVariable()
- if self.GetDataType(iec_path) is None:
- self.RemoveDataConsumer(item)
- self.Table.RemoveItem(idx)
- else:
- self.AddDataConsumer(iec_path.upper(), item)
- item.RefreshVariableType()
-
- # Update table layout
- self.Freeze()
- self.Table.ResetView(self.VariablesGrid)
- self.VariablesGrid.RefreshButtons()
- self.Thaw()
-
- def GetForceVariableMenuFunction(self, item):
- """
- Function returning callback function for contextual menu 'Force' item
- @param item: Debug Variable item where contextual menu was opened
- @return: Callback function
- """
- def ForceVariableFunction(event):
- # Get variable path and data type
- iec_path = item.GetVariable()
- iec_type = self.GetDataType(iec_path)
-
- # Return immediately if not data type found
- if iec_type is None:
- return
-
- # Open dialog for entering value to force variable
- dialog = ForceVariableDialog(self, iec_type, str(item.GetValue()))
-
- # If valid value entered, force variable
- if dialog.ShowModal() == wx.ID_OK:
- self.ForceDataValue(iec_path.upper(), dialog.GetValue())
-
- return ForceVariableFunction
-
- def GetReleaseVariableMenuFunction(self, iec_path):
- """
- Function returning callback function for contextual menu 'Release' item
- @param iec_path: Debug Variable path where contextual menu was opened
- @return: Callback function
- """
- def ReleaseVariableFunction(event):
- # Release variable
- self.ReleaseDataValue(iec_path)
- return ReleaseVariableFunction
-
- def OnVariablesGridCellLeftClick(self, event):
- """
- Called when left mouse button is pressed on a table cell
- @param event: wx.grid.GridEvent
- """
- # Initiate a drag and drop if the cell clicked was in 'Variable' column
- if self.Table.GetColLabelValue(event.GetCol(), False) == "Variable":
- item = self.Table.GetItem(event.GetRow())
- data = wx.TextDataObject(str((item.GetVariable(), "debug")))
- dragSource = wx.DropSource(self.VariablesGrid)
- dragSource.SetData(data)
- dragSource.DoDragDrop()
-
- event.Skip()
-
- def OnVariablesGridCellRightClick(self, event):
- """
- Called when right mouse button is pressed on a table cell
- @param event: wx.grid.GridEvent
- """
- # Open a contextual menu if the cell clicked was in 'Value' column
- if self.Table.GetColLabelValue(event.GetCol(), False) == "Value":
- row = event.GetRow()
-
- # Get variable path
- item = self.Table.GetItem(row)
- iec_path = item.GetVariable().upper()
-
- # Create contextual menu
- menu = wx.Menu(title='')
-
- # Add menu items
- for text, enable, callback in [
- (_("Force value"), True,
- self.GetForceVariableMenuFunction(item)),
- # Release menu item is enabled only if variable is forced
- (_("Release value"), self.Table.IsForced(row),
- self.GetReleaseVariableMenuFunction(iec_path))]:
-
- new_id = wx.NewId()
- menu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=text)
- menu.Enable(new_id, enable)
- self.Bind(wx.EVT_MENU, callback, id=new_id)
-
- # Popup contextual menu
- self.PopupMenu(menu)
-
- menu.Destroy()
- event.Skip()
-
- def InsertValue(self, iec_path, index=None, force=False, graph=False):
- """
- Insert a new variable to debug in table
- @param iec_path: Variable path to debug
- @param index: Row where insert the variable in table (default None,
- insert at last position)
- @param force: Force insertion of variable even if not defined in
- producer side
- @param graph: Values must be displayed in graph canvas (Do nothing,
- here for compatibility with Debug Variable Graphic Panel)
- """
- # Return immediately if variable is already debugged
- for item in self.Table.GetData():
- if iec_path == item.GetVariable():
- return
-
- # Insert at last position if index not defined
- if index is None:
- index = self.Table.GetNumberRows()
-
- # Subscribe variable to producer
- item = DebugVariableItem(self, iec_path)
- result = self.AddDataConsumer(iec_path.upper(), item)
-
- # Insert variable in table if subscription done or insertion forced
- if result is not None or force:
- self.Table.InsertItem(index, item)
- self.RefreshView()
-
- def ResetGraphicsValues(self):
- """
- Called to reset graphics values when PLC is started
- (Nothing to do because no graphic values here. Defined for
- compatibility with Debug Variable Graphic Panel)
- """
- pass
-
\ No newline at end of file
--- a/controls/DebugVariablePanel/__init__.py Mon Oct 14 10:31:32 2013 +0200
+++ b/controls/DebugVariablePanel/__init__.py Mon Oct 14 10:49:04 2013 +0200
@@ -1,4 +1,1 @@
-try:
- from DebugVariableGraphicPanel import DebugVariableGraphicPanel as DebugVariablePanel
-except:
- from DebugVariableTablePanel import DebugVariableTablePanel as DebugVariablePanel
\ No newline at end of file
+from DebugVariablePanel import DebugVariablePanel
\ No newline at end of file
--- a/controls/PouInstanceVariablesPanel.py Mon Oct 14 10:31:32 2013 +0200
+++ b/controls/PouInstanceVariablesPanel.py Mon Oct 14 10:49:04 2013 +0200
@@ -114,8 +114,6 @@
class PouInstanceVariablesPanel(wx.Panel):
- USE_MPL = False
-
def __init__(self, parent, window, controller, debug):
wx.Panel.__init__(self, name='PouInstanceTreePanel',
parent=parent, pos=wx.Point(0, 0),
@@ -154,14 +152,11 @@
self.VariablesList.Bind(wx.EVT_KEY_DOWN, self.OnVariablesListKeyDown)
self.TreeRightImageList = wx.ImageList(24, 24)
- self.InstanceGraphImage = self.TreeRightImageList.Add(GetBitmap("instance_graph"))
self.EditImage = self.TreeRightImageList.Add(GetBitmap("edit"))
self.DebugInstanceImage = self.TreeRightImageList.Add(GetBitmap("debug_instance"))
self.VariablesList.SetRightImageList(self.TreeRightImageList)
self.ButtonCallBacks = {
- self.InstanceGraphImage: _ButtonCallbacks(
- self.GraphButtonCallback, None),
self.EditImage: _ButtonCallbacks(
self.EditButtonCallback, None),
self.DebugInstanceImage: _ButtonCallbacks(
@@ -246,12 +241,7 @@
text = var_infos.name
right_images = []
- if var_infos.var_class in ITEMS_VARIABLE:
- if (not self.USE_MPL and var_infos.debug and self.Debug and
- (self.Controller.IsOfType(var_infos.type, "ANY_NUM", True) or
- self.Controller.IsOfType(var_infos.type, "ANY_BIT", True))):
- right_images.append(self.InstanceGraphImage)
- elif var_infos.edit:
+ if var_infos.edit:
right_images.append(self.EditImage)
if var_infos.debug and self.Debug:
@@ -356,13 +346,6 @@
force=True,
graph=True)
- def GraphButtonCallback(self, infos):
- if self.InstanceChoice.GetSelection() != -1:
- if infos.var_class in ITEMS_VARIABLE:
- var_path = "%s.%s" % (self.InstanceChoice.GetStringSelection(),
- infos.name)
- self.ParentWindow.OpenDebugViewer(infos.var_class, var_path, infos.type)
-
def ShowInstanceChoicePopup(self):
self.InstanceChoice.SetFocusFromKbd()
size = self.InstanceChoice.GetSize()
--- a/editors/GraphicViewer.py Mon Oct 14 10:31:32 2013 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,543 +0,0 @@
-#!/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
-
-import numpy
-import math
-
-import wx
-import wx.lib.plot as plot
-import wx.lib.buttons
-
-from graphics.GraphicCommons import MODE_SELECTION, MODE_MOTION
-from editors.DebugViewer import DebugViewer
-from editors.EditorPanel import EditorPanel
-from util.BitmapLibrary import GetBitmap
-
-colours = ['blue', 'red', 'green', 'yellow', 'orange', 'purple', 'brown', 'cyan',
- 'pink', 'grey']
-markers = ['circle', 'dot', 'square', 'triangle', 'triangle_down', 'cross', 'plus', 'circle']
-
-
-#-------------------------------------------------------------------------------
-# Debug Variable Graphic Viewer class
-#-------------------------------------------------------------------------------
-
-SECOND = 1000000000
-MINUTE = 60 * SECOND
-HOUR = 60 * MINUTE
-
-ZOOM_VALUES = map(lambda x:("x %.1f" % x, x), [math.sqrt(2) ** i for i in xrange(8)])
-RANGE_VALUES = map(lambda x: (str(x), x), [25 * 2 ** i for i in xrange(6)])
-TIME_RANGE_VALUES = [("%ds" % i, i * SECOND) for i in (1, 2, 5, 10, 20, 30)] + \
- [("%dm" % i, i * MINUTE) for i in (1, 2, 5, 10, 20, 30)] + \
- [("%dh" % i, i * HOUR) for i in (1, 2, 3, 6, 12, 24)]
-
-class GraphicViewer(EditorPanel, DebugViewer):
-
- def _init_Editor(self, prnt):
- self.Editor = wx.Panel(prnt)
-
- main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=0)
- main_sizer.AddGrowableCol(0)
- main_sizer.AddGrowableRow(0)
-
- self.Canvas = plot.PlotCanvas(self.Editor, name='Canvas')
- def _axisInterval(spec, lower, upper):
- if spec == 'border':
- if lower == upper:
- return lower - 0.5, upper + 0.5
- else:
- border = (upper - lower) * 0.05
- return lower - border, upper + border
- else:
- return plot.PlotCanvas._axisInterval(self.Canvas, spec, lower, upper)
- self.Canvas._axisInterval = _axisInterval
- self.Canvas.SetYSpec('border')
- self.Canvas.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnCanvasLeftDown)
- self.Canvas.canvas.Bind(wx.EVT_LEFT_UP, self.OnCanvasLeftUp)
- self.Canvas.canvas.Bind(wx.EVT_MIDDLE_DOWN, self.OnCanvasMiddleDown)
- self.Canvas.canvas.Bind(wx.EVT_MIDDLE_UP, self.OnCanvasMiddleUp)
- self.Canvas.canvas.Bind(wx.EVT_MOTION, self.OnCanvasMotion)
- self.Canvas.canvas.Bind(wx.EVT_SIZE, self.OnCanvasResize)
- main_sizer.AddWindow(self.Canvas, 0, border=0, flag=wx.GROW)
-
- range_sizer = wx.FlexGridSizer(cols=10, hgap=5, rows=1, vgap=0)
- range_sizer.AddGrowableCol(5)
- range_sizer.AddGrowableRow(0)
- main_sizer.AddSizer(range_sizer, 0, border=5, flag=wx.GROW|wx.ALL)
-
- range_label = wx.StaticText(self.Editor, label=_('Range:'))
- range_sizer.AddWindow(range_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
-
- self.CanvasRange = wx.ComboBox(self.Editor,
- size=wx.Size(100, 28), style=wx.CB_READONLY)
- self.Bind(wx.EVT_COMBOBOX, self.OnRangeChanged, self.CanvasRange)
- range_sizer.AddWindow(self.CanvasRange, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
-
- zoom_label = wx.StaticText(self.Editor, label=_('Zoom:'))
- range_sizer.AddWindow(zoom_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
-
- self.CanvasZoom = wx.ComboBox(self.Editor,
- size=wx.Size(70, 28), style=wx.CB_READONLY)
- self.Bind(wx.EVT_COMBOBOX, self.OnZoomChanged, self.CanvasZoom)
- range_sizer.AddWindow(self.CanvasZoom, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
-
- position_label = wx.StaticText(self.Editor, label=_('Position:'))
- range_sizer.AddWindow(position_label, 0, border=0, flag=wx.ALIGN_CENTER_VERTICAL)
-
- self.CanvasPosition = wx.ScrollBar(self.Editor,
- size=wx.Size(0, 16), style=wx.SB_HORIZONTAL)
- self.CanvasPosition.SetScrollbar(0, 10, 100, 10)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_THUMBTRACK,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEUP,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_LINEDOWN,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEUP,
- self.OnPositionChanging, self.CanvasPosition)
- self.CanvasPosition.Bind(wx.EVT_SCROLL_PAGEDOWN,
- self.OnPositionChanging, self.CanvasPosition)
- range_sizer.AddWindow(self.CanvasPosition, 0, border=5, flag=wx.GROW|wx.ALL)
-
- self.ResetButton = wx.lib.buttons.GenBitmapButton(self.Editor,
- bitmap=GetBitmap("reset"), size=wx.Size(28, 28), style=wx.NO_BORDER)
- self.ResetButton.SetToolTipString(_("Clear the graph values"))
- self.Bind(wx.EVT_BUTTON, self.OnResetButton, self.ResetButton)
- range_sizer.AddWindow(self.ResetButton, 0, border=0, flag=0)
-
- self.CurrentButton = wx.lib.buttons.GenBitmapButton(self.Editor,
- bitmap=GetBitmap("current"), size=wx.Size(28, 28), style=wx.NO_BORDER)
- self.CurrentButton.SetToolTipString(_("Go to current value"))
- self.Bind(wx.EVT_BUTTON, self.OnCurrentButton, self.CurrentButton)
- range_sizer.AddWindow(self.CurrentButton, 0, border=0, flag=0)
-
- self.ResetZoomOffsetButton = wx.lib.buttons.GenBitmapButton(self.Editor,
- bitmap=GetBitmap("fit"), size=wx.Size(28, 28), style=wx.NO_BORDER)
- self.ResetZoomOffsetButton.SetToolTipString(_("Reset zoom and offset"))
- self.Bind(wx.EVT_BUTTON, self.OnResetZoomOffsetButton,
- self.ResetZoomOffsetButton)
- range_sizer.AddWindow(self.ResetZoomOffsetButton, 0, border=0, flag=0)
-
- self.ExportGraphButton = wx.lib.buttons.GenBitmapButton(self.Editor,
- bitmap=GetBitmap("export_graph"), size=wx.Size(28, 28), style=wx.NO_BORDER)
- self.ExportGraphButton.SetToolTipString(_("Export graph values to clipboard"))
- self.Bind(wx.EVT_BUTTON, self.OnExportGraphButtonClick,
- self.ExportGraphButton)
- range_sizer.AddWindow(self.ExportGraphButton, 0, border=0, flag=0)
-
- self.Editor.SetSizer(main_sizer)
-
- self.Editor.Bind(wx.EVT_MOUSEWHEEL, self.OnCanvasMouseWheel)
-
- def __init__(self, parent, window, producer, instancepath = ""):
- EditorPanel.__init__(self, parent, "", window, None)
- DebugViewer.__init__(self, producer, True, False)
-
- self.InstancePath = instancepath
- self.RangeValues = None
- self.CursorIdx = None
- self.LastCursor = None
- self.CurrentMousePos = None
- self.CurrentMotionValue = None
- self.Dragging = False
-
- # Initialize Viewer mode to Selection mode
- self.Mode = MODE_SELECTION
-
- self.Data = numpy.array([]).reshape(0, 2)
- self.StartTick = 0
- self.StartIdx = 0
- self.EndIdx = 0
- self.MinValue = None
- self.MaxValue = None
- self.YCenter = 0
- self.CurrentZoom = 1.0
- self.Fixed = False
- self.Ticktime = self.DataProducer.GetTicktime()
- self.RefreshCanvasRange()
-
- for zoom_txt, zoom in ZOOM_VALUES:
- self.CanvasZoom.Append(zoom_txt)
- self.CanvasZoom.SetSelection(0)
-
- self.AddDataConsumer(self.InstancePath.upper(), self)
-
- def __del__(self):
- DebugViewer.__del__(self)
- self.RemoveDataConsumer(self)
-
- def GetTitle(self):
- if len(self.InstancePath) > 15:
- return "..." + self.InstancePath[-12:]
- return self.InstancePath
-
- # Changes Viewer mode
- def SetMode(self, mode):
- if self.Mode != mode or mode == MODE_SELECTION:
- if self.Mode == MODE_MOTION:
- wx.CallAfter(self.Canvas.canvas.SetCursor, wx.NullCursor)
- self.Mode = mode
- if self.Mode == MODE_MOTION:
- wx.CallAfter(self.Canvas.canvas.SetCursor, wx.StockCursor(wx.CURSOR_HAND))
-
- def ResetView(self, register=False):
- self.Data = numpy.array([]).reshape(0, 2)
- self.StartTick = 0
- self.StartIdx = 0
- self.EndIdx = 0
- self.MinValue = None
- self.MaxValue = None
- self.CursorIdx = None
- self.Fixed = False
- self.Ticktime = self.DataProducer.GetTicktime()
- if register:
- self.AddDataConsumer(self.InstancePath.upper(), self)
- self.ResetLastCursor()
- self.RefreshCanvasRange()
- self.RefreshView()
-
- def RefreshNewData(self, *args, **kwargs):
- self.RefreshView(*args, **kwargs)
- DebugViewer.RefreshNewData(self)
-
- def GetNearestData(self, tick, adjust):
- ticks = self.Data[:, 0]
- new_cursor = numpy.argmin(abs(ticks - tick))
- if adjust == -1 and ticks[new_cursor] > tick and new_cursor > 0:
- new_cursor -= 1
- elif adjust == 1 and ticks[new_cursor] < tick and new_cursor < len(ticks):
- new_cursor += 1
- return new_cursor
-
- def GetBounds(self):
- if self.StartIdx is None or self.EndIdx is None:
- self.StartIdx = self.GetNearestData(self.StartTick, -1)
- self.EndIdx = self.GetNearestData(self.StartTick + self.CurrentRange, 1)
-
- def ResetBounds(self):
- self.StartIdx = None
- self.EndIdx = None
-
- def RefreshCanvasRange(self):
- if self.Ticktime == 0 and self.RangeValues != RANGE_VALUES:
- self.RangeValues = RANGE_VALUES
- self.CanvasRange.Clear()
- for text, value in RANGE_VALUES:
- self.CanvasRange.Append(text)
- self.CanvasRange.SetStringSelection(RANGE_VALUES[0][0])
- self.CurrentRange = RANGE_VALUES[0][1]
- elif self.RangeValues != TIME_RANGE_VALUES:
- self.RangeValues = TIME_RANGE_VALUES
- self.CanvasRange.Clear()
- for text, value in TIME_RANGE_VALUES:
- self.CanvasRange.Append(text)
- self.CanvasRange.SetStringSelection(TIME_RANGE_VALUES[0][0])
- self.CurrentRange = TIME_RANGE_VALUES[0][1] / self.Ticktime
-
- def RefreshView(self, force=False):
- self.Freeze()
- if force or not self.Fixed or (len(self.Data) > 0 and self.StartTick + self.CurrentRange > self.Data[-1, 0]):
- if (self.MinValue is not None and
- self.MaxValue is not None and
- self.MinValue != self.MaxValue):
- Yrange = float(self.MaxValue - self.MinValue) / self.CurrentZoom
- else:
- Yrange = 2. / self.CurrentZoom
-
- if not force and not self.Fixed and len(self.Data) > 0:
- self.YCenter = max(self.Data[-1, 1] - Yrange / 2,
- min(self.YCenter,
- self.Data[-1, 1] + Yrange / 2))
-
- var_name = self.InstancePath.split(".")[-1]
-
- self.GetBounds()
- self.VariableGraphic = plot.PolyLine(self.Data[self.StartIdx:self.EndIdx + 1],
- legend=var_name, colour=colours[0])
- self.GraphicsObject = plot.PlotGraphics([self.VariableGraphic], _("%s Graphics") % var_name, _("Tick"), _("Values"))
- self.Canvas.Draw(self.GraphicsObject,
- xAxis=(self.StartTick, self.StartTick + self.CurrentRange),
- yAxis=(self.YCenter - Yrange * 1.1 / 2., self.YCenter + Yrange * 1.1 / 2.))
-
- # Reset and draw cursor
- self.ResetLastCursor()
- self.RefreshCursor()
-
- self.RefreshScrollBar()
-
- self.Thaw()
-
- def GetInstancePath(self):
- return self.InstancePath
-
- def IsViewing(self, tagname):
- return self.InstancePath == tagname
-
- def NewValue(self, tick, value, forced=False):
- value = {True:1., False:0.}.get(value, float(value))
- self.Data = numpy.append(self.Data, [[float(tick), value]], axis=0)
- if self.MinValue is None:
- self.MinValue = value
- else:
- self.MinValue = min(self.MinValue, value)
- if self.MaxValue is None:
- self.MaxValue = value
- else:
- self.MaxValue = max(self.MaxValue, value)
- if not self.Fixed or tick < self.StartTick + self.CurrentRange:
- self.GetBounds()
- while int(self.Data[self.StartIdx, 0]) < tick - self.CurrentRange:
- self.StartIdx += 1
- self.EndIdx += 1
- self.StartTick = self.Data[self.StartIdx, 0]
- self.NewDataAvailable(None)
-
- def RefreshScrollBar(self):
- if len(self.Data) > 0:
- self.GetBounds()
- pos = int(self.Data[self.StartIdx, 0] - self.Data[0, 0])
- range = int(self.Data[-1, 0] - self.Data[0, 0])
- else:
- pos = 0
- range = 0
- self.CanvasPosition.SetScrollbar(pos, self.CurrentRange, range, self.CurrentRange)
-
- def RefreshRange(self):
- if len(self.Data) > 0:
- if self.Fixed and self.Data[-1, 0] - self.Data[0, 0] < self.CurrentRange:
- self.Fixed = False
- self.ResetBounds()
- if self.Fixed:
- self.StartTick = min(self.StartTick, self.Data[-1, 0] - self.CurrentRange)
- else:
- self.StartTick = max(self.Data[0, 0], self.Data[-1, 0] - self.CurrentRange)
- self.RefreshView(True)
-
- def OnRangeChanged(self, event):
- try:
- if self.Ticktime == 0:
- self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1]
- else:
- self.CurrentRange = self.RangeValues[self.CanvasRange.GetSelection()][1] / self.Ticktime
- except ValueError, e:
- self.CanvasRange.SetValue(str(self.CurrentRange))
- wx.CallAfter(self.RefreshRange)
- event.Skip()
-
- def OnZoomChanged(self, event):
- self.CurrentZoom = ZOOM_VALUES[self.CanvasZoom.GetSelection()][1]
- wx.CallAfter(self.RefreshView, True)
- event.Skip()
-
- def OnPositionChanging(self, event):
- if len(self.Data) > 0:
- self.ResetBounds()
- self.StartTick = self.Data[0, 0] + event.GetPosition()
- self.Fixed = True
- self.NewDataAvailable(None, True)
- event.Skip()
-
- def OnResetButton(self, event):
- self.Fixed = False
- self.ResetView()
- event.Skip()
-
- def OnCurrentButton(self, event):
- if len(self.Data) > 0:
- self.ResetBounds()
- self.StartTick = max(self.Data[0, 0], self.Data[-1, 0] - self.CurrentRange)
- self.Fixed = False
- self.NewDataAvailable(None, True)
- event.Skip()
-
- def OnResetZoomOffsetButton(self, event):
- if len(self.Data) > 0:
- self.YCenter = (self.MaxValue + self.MinValue) / 2
- else:
- self.YCenter = 0.0
- self.CurrentZoom = 1.0
- self.CanvasZoom.SetSelection(0)
- wx.CallAfter(self.RefreshView, True)
- event.Skip()
-
- def OnExportGraphButtonClick(self, event):
- data_copy = self.Data[:]
- text = "tick;%s;\n" % self.InstancePath
- for tick, value in data_copy:
- text += "%d;%.3f;\n" % (tick, value)
- self.ParentWindow.SetCopyBuffer(text)
- event.Skip()
-
- def OnCanvasLeftDown(self, event):
- self.Fixed = True
- self.Canvas.canvas.CaptureMouse()
- if len(self.Data) > 0:
- if self.Mode == MODE_SELECTION:
- self.Dragging = True
- pos = self.Canvas.PositionScreenToUser(event.GetPosition())
- self.CursorIdx = self.GetNearestData(pos[0], -1)
- self.RefreshCursor()
- elif self.Mode == MODE_MOTION:
- self.GetBounds()
- self.CurrentMousePos = event.GetPosition()
- self.CurrentMotionValue = self.Data[self.StartIdx, 0]
- event.Skip()
-
- def OnCanvasLeftUp(self, event):
- self.Dragging = False
- if self.Mode == MODE_MOTION:
- self.CurrentMousePos = None
- self.CurrentMotionValue = None
- if self.Canvas.canvas.HasCapture():
- self.Canvas.canvas.ReleaseMouse()
- event.Skip()
-
- def OnCanvasMiddleDown(self, event):
- self.Fixed = True
- self.Canvas.canvas.CaptureMouse()
- if len(self.Data) > 0:
- self.GetBounds()
- self.CurrentMousePos = event.GetPosition()
- self.CurrentMotionValue = self.Data[self.StartIdx, 0]
- event.Skip()
-
- def OnCanvasMiddleUp(self, event):
- self.CurrentMousePos = None
- self.CurrentMotionValue = None
- if self.Canvas.canvas.HasCapture():
- self.Canvas.canvas.ReleaseMouse()
- event.Skip()
-
- def OnCanvasMotion(self, event):
- if self.Mode == MODE_SELECTION and self.Dragging:
- pos = self.Canvas.PositionScreenToUser(event.GetPosition())
- graphics, xAxis, yAxis = self.Canvas.last_draw
- self.CursorIdx = self.GetNearestData(max(xAxis[0], min(pos[0], xAxis[1])), -1)
- self.RefreshCursor()
- elif self.CurrentMousePos is not None and len(self.Data) > 0:
- oldpos = self.Canvas.PositionScreenToUser(self.CurrentMousePos)
- newpos = self.Canvas.PositionScreenToUser(event.GetPosition())
- self.CurrentMotionValue += oldpos[0] - newpos[0]
- self.YCenter += oldpos[1] - newpos[1]
- self.ResetBounds()
- self.StartTick = max(self.Data[0, 0], min(self.CurrentMotionValue, self.Data[-1, 0] - self.CurrentRange))
- self.CurrentMousePos = event.GetPosition()
- self.NewDataAvailable(None, True)
- event.Skip()
-
- def OnCanvasMouseWheel(self, event):
- if self.CurrentMousePos is None:
- rotation = event.GetWheelRotation() / event.GetWheelDelta()
- if event.ShiftDown():
- current = self.CanvasRange.GetSelection()
- new = max(0, min(current - rotation, len(self.RangeValues) - 1))
- if new != current:
- if self.Ticktime == 0:
- self.CurrentRange = self.RangeValues[new][1]
- else:
- self.CurrentRange = self.RangeValues[new][1] / self.Ticktime
- self.CanvasRange.SetStringSelection(self.RangeValues[new][0])
- wx.CallAfter(self.RefreshRange)
- else:
- current = self.CanvasZoom.GetSelection()
- new = max(0, min(current + rotation, len(ZOOM_VALUES) - 1))
- if new != current:
- self.CurrentZoom = ZOOM_VALUES[new][1]
- self.CanvasZoom.SetStringSelection(ZOOM_VALUES[new][0])
- wx.CallAfter(self.RefreshView, True)
- event.Skip()
-
- def OnCanvasResize(self, event):
- self.ResetLastCursor()
- wx.CallAfter(self.RefreshCursor)
- event.Skip()
-
- ## Reset the last cursor
- def ResetLastCursor(self):
- self.LastCursor = None
-
- ## Draw the cursor on graphic
- # @param dc The draw canvas
- # @param cursor The cursor parameters
- def DrawCursor(self, dc, cursor, value):
- if self.StartTick <= cursor <= self.StartTick + self.CurrentRange:
- # Prepare temporary dc for drawing
- width = self.Canvas._Buffer.GetWidth()
- height = self.Canvas._Buffer.GetHeight()
- tmp_Buffer = wx.EmptyBitmap(width, height)
- dcs = wx.MemoryDC()
- dcs.SelectObject(tmp_Buffer)
- dcs.Clear()
- dcs.BeginDrawing()
-
- dcs.SetPen(wx.Pen(wx.RED))
- dcs.SetBrush(wx.Brush(wx.RED, wx.SOLID))
- dcs.SetFont(self.Canvas._getFont(self.Canvas._fontSizeAxis))
-
- # Calculate clipping region
- graphics, xAxis, yAxis = self.Canvas.last_draw
- p1 = numpy.array([xAxis[0], yAxis[0]])
- p2 = numpy.array([xAxis[1], yAxis[1]])
- cx, cy, cwidth, cheight = self.Canvas._point2ClientCoord(p1, p2)
-
- px, py = self.Canvas.PositionUserToScreen((float(cursor), 0.))
-
- # Draw line cross drawing for diaplaying time cursor
- dcs.DrawLine(px, cy + 1, px, cy + cheight - 1)
-
- lines = ("X:%d\nY:%f" % (cursor, value)).splitlines()
-
- wtext = 0
- for line in lines:
- w, h = dcs.GetTextExtent(line)
- wtext = max(wtext, w)
-
- offset = 0
- for line in lines:
- # Draw time cursor date
- dcs.DrawText(line, min(px + 3, cx + cwidth - wtext), cy + 3 + offset)
- w, h = dcs.GetTextExtent(line)
- offset += h
-
- dcs.EndDrawing()
-
- #this will erase if called twice
- dc.Blit(0, 0, width, height, dcs, 0, 0, wx.EQUIV) #(NOT src) XOR dst
-
- ## Refresh the variable cursor.
- # @param dc The draw canvas
- def RefreshCursor(self, dc=None):
- if self:
- if dc is None:
- dc = wx.BufferedDC(wx.ClientDC(self.Canvas.canvas), self.Canvas._Buffer)
-
- # Erase previous time cursor if drawn
- if self.LastCursor is not None:
- self.DrawCursor(dc, *self.LastCursor)
-
- # Draw new time cursor
- if self.CursorIdx is not None:
- self.LastCursor = self.Data[self.CursorIdx]
- self.DrawCursor(dc, *self.LastCursor)