--- a/controls/DebugVariablePanel/DebugVariableGraphicPanel.py Thu May 30 13:23:21 2013 +0200
+++ b/controls/DebugVariablePanel/DebugVariableGraphicPanel.py Fri May 31 00:07:21 2013 +0200
@@ -23,7 +23,6 @@
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from types import TupleType
-from time import time as gettime
import math
import numpy
@@ -33,88 +32,44 @@
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot
-from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
-from matplotlib.backends.backend_agg import FigureCanvasAgg
-from mpl_toolkits.mplot3d import Axes3D
-color_cycle = ['r', 'b', 'g', 'm', 'y', 'k']
-cursor_color = '#800080'
-
-from editors.DebugViewer import DebugViewer, REFRESH_PERIOD
-from dialogs.ForceVariableDialog import ForceVariableDialog
+
+from editors.DebugViewer import DebugViewer
from util.BitmapLibrary import GetBitmap
from DebugVariableItem import DebugVariableItem
-from GraphButton import GraphButton
+from DebugVariableTextViewer import DebugVariableTextViewer
+from DebugVariableGraphicViewer import *
class DebugVariableDropTarget(wx.TextDropTarget):
- def __init__(self, parent, control=None):
+ def __init__(self, parent):
wx.TextDropTarget.__init__(self)
self.ParentWindow = parent
- self.ParentControl = control
def __del__(self):
self.ParentWindow = None
- self.ParentControl = None
def OnDragOver(self, x, y, d):
- if self.ParentControl is not None:
- self.ParentControl.OnMouseDragging(x, y)
- else:
- self.ParentWindow.RefreshHighlight(x, y)
+ self.ParentControl.OnMouseDragging(x, y)
+ self.ParentWindow.RefreshHighlight(x, y)
return wx.TextDropTarget.OnDragOver(self, x, y, d)
def OnDropText(self, x, y, data):
message = None
try:
values = eval(data)
+ if not isinstance(values, TupleType):
+ raise
except:
message = _("Invalid value \"%s\" for debug variable")%data
values = None
- if not isinstance(values, TupleType):
- message = _("Invalid value \"%s\" for debug variable")%data
- values = None
-
+
if message is not None:
wx.CallAfter(self.ShowMessage, message)
- elif values is not None and values[1] == "debug":
- if self.ParentControl is not None:
- width, height = self.ParentControl.GetSize()
- target_idx = self.ParentControl.GetIndex()
- merge_type = GRAPH_PARALLEL
- if isinstance(self.ParentControl, DebugVariableGraphic):
- if self.ParentControl.Is3DCanvas():
- if y > height / 2:
- target_idx += 1
- if len(values) > 1 and values[2] == "move":
- self.ParentWindow.MoveValue(values[0], target_idx)
- else:
- self.ParentWindow.InsertValue(values[0], target_idx, force=True)
-
- else:
- rect = self.ParentControl.GetAxesBoundingBox()
- if rect.InsideXY(x, y):
- merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height)
- if merge_rect.InsideXY(x, y):
- merge_type = GRAPH_ORTHOGONAL
- wx.CallAfter(self.ParentWindow.MergeGraphs, values[0], target_idx, merge_type, force=True)
- else:
- if y > height / 2:
- target_idx += 1
- if len(values) > 2 and values[2] == "move":
- self.ParentWindow.MoveValue(values[0], target_idx)
- else:
- self.ParentWindow.InsertValue(values[0], target_idx, force=True)
- else:
- if y > height / 2:
- target_idx += 1
- if len(values) > 2 and values[2] == "move":
- self.ParentWindow.MoveValue(values[0], target_idx)
- else:
- self.ParentWindow.InsertValue(values[0], target_idx, force=True)
-
- elif len(values) > 2 and values[2] == "move":
+
+ elif values[1] == "debug":
+ if len(values) > 2 and values[2] == "move":
self.ParentWindow.MoveValue(values[0])
else:
self.ParentWindow.InsertValue(values[0], force=True)
@@ -141,32 +96,8 @@
[("%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)]
-GRAPH_PARALLEL, GRAPH_ORTHOGONAL = range(2)
-
SCROLLBAR_UNIT = 10
-#CANVAS_HIGHLIGHT_TYPES
-[HIGHLIGHT_NONE,
- HIGHLIGHT_BEFORE,
- HIGHLIGHT_AFTER,
- HIGHLIGHT_LEFT,
- HIGHLIGHT_RIGHT,
- HIGHLIGHT_RESIZE] = range(6)
-
-HIGHLIGHT_DROP_PEN = wx.Pen(wx.Colour(0, 128, 255))
-HIGHLIGHT_DROP_BRUSH = wx.Brush(wx.Colour(0, 128, 255, 128))
-HIGHLIGHT_RESIZE_PEN = wx.Pen(wx.Colour(200, 200, 200))
-HIGHLIGHT_RESIZE_BRUSH = wx.Brush(wx.Colour(200, 200, 200))
-
-#CANVAS_SIZE_TYPES
-[SIZE_MINI, SIZE_MIDDLE, SIZE_MAXI] = [0, 100, 200]
-
-DEFAULT_CANVAS_HEIGHT = 200.
-CANVAS_BORDER = (20., 10.)
-CANVAS_PADDING = 8.5
-VALUE_LABEL_HEIGHT = 17.
-AXES_LABEL_HEIGHT = 12.75
-
def compute_mask(x, y):
mask = []
for xp, yp in zip(x, y):
@@ -186,932 +117,6 @@
next_tick = min(next_tick, data[0][0])
return next_tick
-def OrthogonalData(item, start_tick, end_tick):
- data = item.GetData(start_tick, end_tick)
- min_value, max_value = item.GetValueRange()
- if min_value is not None and max_value is not None:
- center = (min_value + max_value) / 2.
- range = max(1.0, max_value - min_value)
- else:
- center = 0.5
- range = 1.0
- return data, center - range * 0.55, center + range * 0.55
-
-class DebugVariableViewer:
-
- def __init__(self, window, items=[]):
- self.ParentWindow = window
- self.Items = items
-
- self.Highlight = HIGHLIGHT_NONE
- self.Buttons = []
-
- def __del__(self):
- self.ParentWindow = None
-
- def GetIndex(self):
- return self.ParentWindow.GetViewerIndex(self)
-
- def GetItem(self, variable):
- for item in self.Items:
- if item.GetVariable() == variable:
- return item
- return None
-
- def GetItems(self):
- return self.Items
-
- def GetVariables(self):
- if len(self.Items) > 1:
- variables = [item.GetVariable() for item in self.Items]
- if self.GraphType == GRAPH_ORTHOGONAL:
- return tuple(variables)
- return variables
- return self.Items[0].GetVariable()
-
- def AddItem(self, item):
- self.Items.append(item)
-
- def RemoveItem(self, item):
- if item in self.Items:
- self.Items.remove(item)
-
- def Clear(self):
- for item in self.Items:
- self.ParentWindow.RemoveDataConsumer(item)
- self.Items = []
-
- def IsEmpty(self):
- return len(self.Items) == 0
-
- def UnregisterObsoleteData(self):
- for item in self.Items[:]:
- iec_path = item.GetVariable()
- if self.ParentWindow.GetDataType(iec_path) is None:
- self.ParentWindow.RemoveDataConsumer(item)
- self.RemoveItem(item)
- else:
- self.ParentWindow.AddDataConsumer(iec_path.upper(), item)
- item.RefreshVariableType()
-
- def ResetData(self):
- for item in self.Items:
- item.ResetData()
-
- def RefreshViewer(self):
- pass
-
- def SetHighlight(self, highlight):
- if self.Highlight != highlight:
- self.Highlight = highlight
- return True
- return False
-
- def GetButtons(self):
- return self.Buttons
-
- def HandleButtons(self, x, y):
- for button in self.GetButtons():
- if button.HitTest(x, y):
- button.ProcessCallback()
- return True
- return False
-
- def IsOverButton(self, x, y):
- for button in self.GetButtons():
- if button.HitTest(x, y):
- return True
- return False
-
- def ShowButtons(self, show):
- for button in self.Buttons:
- if show:
- button.Show()
- else:
- button.Hide()
- self.RefreshButtonsState()
- self.ParentWindow.ForceRefresh()
-
- def RefreshButtonsState(self, refresh_positions=False):
- if self:
- width, height = self.GetSize()
- if refresh_positions:
- offset = 0
- buttons = self.Buttons[:]
- buttons.reverse()
- for button in buttons:
- if button.IsEnabled():
- w, h = button.GetSize()
- button.SetPosition(width - 5 - w - offset, 5)
- offset += w + 2
- self.ParentWindow.ForceRefresh()
-
- def DrawCommonElements(self, dc, buttons=None):
- width, height = self.GetSize()
-
- dc.SetPen(HIGHLIGHT_DROP_PEN)
- dc.SetBrush(HIGHLIGHT_DROP_BRUSH)
- if self.Highlight in [HIGHLIGHT_BEFORE]:
- dc.DrawLine(0, 1, width - 1, 1)
- elif self.Highlight in [HIGHLIGHT_AFTER]:
- dc.DrawLine(0, height - 1, width - 1, height - 1)
-
- if buttons is None:
- buttons = self.Buttons
- for button in buttons:
- button.Draw(dc)
-
- if self.ParentWindow.IsDragging():
- destBBox = self.ParentWindow.GetDraggingAxesClippingRegion(self)
- srcPos = self.ParentWindow.GetDraggingAxesPosition(self)
- if destBBox.width > 0 and destBBox.height > 0:
- srcPanel = self.ParentWindow.DraggingAxesPanel
- srcBBox = srcPanel.GetAxesBoundingBox()
-
- if destBBox.x == 0:
- srcX = srcBBox.x - srcPos.x
- else:
- srcX = srcBBox.x
- if destBBox.y == 0:
- srcY = srcBBox.y - srcPos.y
- else:
- srcY = srcBBox.y
-
- srcBmp = _convert_agg_to_wx_bitmap(srcPanel.get_renderer(), None)
- srcDC = wx.MemoryDC()
- srcDC.SelectObject(srcBmp)
-
- dc.Blit(destBBox.x, destBBox.y,
- int(destBBox.width), int(destBBox.height),
- srcDC, srcX, srcY)
-
- def OnEnter(self, event):
- self.ShowButtons(True)
- event.Skip()
-
- def OnLeave(self, event):
- if self.Highlight != HIGHLIGHT_RESIZE or self.CanvasStartSize is None:
- x, y = event.GetPosition()
- width, height = self.GetSize()
- if (x <= 0 or x >= width - 1 or
- y <= 0 or y >= height - 1):
- self.ShowButtons(False)
- event.Skip()
-
- def OnCloseButton(self):
- wx.CallAfter(self.ParentWindow.DeleteValue, self)
-
- def OnForceButton(self):
- wx.CallAfter(self.ForceValue, self.Items[0])
-
- def OnReleaseButton(self):
- wx.CallAfter(self.ReleaseValue, self.Items[0])
-
- def OnResizeWindow(self, event):
- wx.CallAfter(self.RefreshButtonsState, True)
- event.Skip()
-
- def OnMouseDragging(self, x, y):
- xw, yw = self.GetPosition()
- self.ParentWindow.RefreshHighlight(x + xw, y + yw)
-
- def OnDragging(self, x, y):
- width, height = self.GetSize()
- if y < height / 2:
- if self.ParentWindow.IsViewerFirst(self):
- self.SetHighlight(HIGHLIGHT_BEFORE)
- else:
- self.SetHighlight(HIGHLIGHT_NONE)
- self.ParentWindow.HighlightPreviousViewer(self)
- else:
- self.SetHighlight(HIGHLIGHT_AFTER)
-
- def OnEraseBackground(self, event):
- pass
-
- def OnResize(self, event):
- wx.CallAfter(self.RefreshButtonsState, True)
- event.Skip()
-
- def ForceValue(self, item):
- iec_path = item.GetVariable()
- iec_type = self.ParentWindow.GetDataType(iec_path)
- if iec_type is not None:
- dialog = ForceVariableDialog(self, iec_type, str(item.GetValue()))
- if dialog.ShowModal() == wx.ID_OK:
- self.ParentWindow.ForceDataValue(iec_path.upper(), dialog.GetValue())
-
- def ReleaseValue(self, item):
- iec_path = item.GetVariable().upper()
- self.ParentWindow.ReleaseDataValue(iec_path)
-
-
-class DebugVariableText(DebugVariableViewer, wx.Panel):
-
- def __init__(self, parent, window, items=[]):
- DebugVariableViewer.__init__(self, window, items)
-
- wx.Panel.__init__(self, parent)
- self.SetBackgroundColour(wx.WHITE)
- self.SetDropTarget(DebugVariableDropTarget(window, self))
- self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
- self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
- self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
- self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
- self.Bind(wx.EVT_SIZE, self.OnResize)
- self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
- self.Bind(wx.EVT_PAINT, self.OnPaint)
-
- self.SetMinSize(wx.Size(0, 25))
-
- for bitmap, callback in [("force", self.OnForceButton),
- ("release", self.OnReleaseButton),
- ("delete_graph", self.OnCloseButton)]:
- self.Buttons.append(GraphButton(0, 0, bitmap, callback))
-
- self.ShowButtons(False)
-
- def RefreshViewer(self):
- width, height = self.GetSize()
- bitmap = wx.EmptyBitmap(width, height)
-
- dc = wx.BufferedDC(wx.ClientDC(self), bitmap)
- dc.Clear()
- dc.BeginDrawing()
-
- gc = wx.GCDC(dc)
-
- item_name = self.Items[0].GetVariable(self.ParentWindow.GetVariableNameMask())
- w, h = gc.GetTextExtent(item_name)
- gc.DrawText(item_name, 20, (height - h) / 2)
-
- if self.Items[0].IsForced():
- gc.SetTextForeground(wx.BLUE)
- self.Buttons[0].Disable()
- self.Buttons[1].Enable()
- else:
- self.Buttons[1].Disable()
- self.Buttons[0].Enable()
- self.RefreshButtonsState(True)
-
- item_value = self.Items[0].GetValue()
- w, h = gc.GetTextExtent(item_value)
- gc.DrawText(item_value, width - 40 - w, (height - h) / 2)
-
- self.DrawCommonElements(gc)
-
- gc.EndDrawing()
-
- def OnLeftDown(self, event):
- width, height = self.GetSize()
- item_name = self.Items[0].GetVariable(self.ParentWindow.GetVariableNameMask())
- w, h = self.GetTextExtent(item_name)
- x, y = event.GetPosition()
- rect = wx.Rect(20, (height - h) / 2, w, h)
- if rect.InsideXY(x, y):
- data = wx.TextDataObject(str((self.Items[0].GetVariable(), "debug", "move")))
- dragSource = wx.DropSource(self)
- dragSource.SetData(data)
- dragSource.DoDragDrop()
- else:
- event.Skip()
-
- def OnLeftUp(self, event):
- x, y = event.GetPosition()
- wx.CallAfter(self.HandleButtons, x, y)
- event.Skip()
-
- def OnPaint(self, event):
- self.RefreshViewer()
- event.Skip()
-
-class DebugVariableGraphic(DebugVariableViewer, FigureCanvas):
-
- def __init__(self, parent, window, items, graph_type):
- DebugVariableViewer.__init__(self, window, items)
-
- self.CanvasSize = SIZE_MINI
- self.GraphType = graph_type
- self.CursorTick = None
- self.MouseStartPos = None
- self.StartCursorTick = None
- self.CanvasStartSize = None
- self.ContextualButtons = []
- self.ContextualButtonsItem = None
-
- self.Figure = matplotlib.figure.Figure(facecolor='w')
- self.Figure.subplotpars.update(top=0.95, left=0.1, bottom=0.1, right=0.95)
-
- FigureCanvas.__init__(self, parent, -1, self.Figure)
- self.SetWindowStyle(wx.WANTS_CHARS)
- self.SetBackgroundColour(wx.WHITE)
- self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
- self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
- self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
- self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
- self.Bind(wx.EVT_SIZE, self.OnResize)
-
- canvas_size = self.GetCanvasMinSize()
- self.SetMinSize(canvas_size)
- self.SetDropTarget(DebugVariableDropTarget(self.ParentWindow, self))
- self.mpl_connect('button_press_event', self.OnCanvasButtonPressed)
- self.mpl_connect('motion_notify_event', self.OnCanvasMotion)
- self.mpl_connect('button_release_event', self.OnCanvasButtonReleased)
- self.mpl_connect('scroll_event', self.OnCanvasScroll)
-
- for size, bitmap in zip([SIZE_MINI, SIZE_MIDDLE, SIZE_MAXI],
- ["minimize_graph", "middle_graph", "maximize_graph"]):
- self.Buttons.append(GraphButton(0, 0, bitmap, self.GetOnChangeSizeButton(size)))
- for bitmap, callback in [("export_graph_mini", self.OnExportGraphButton),
- ("delete_graph", self.OnCloseButton)]:
- self.Buttons.append(GraphButton(0, 0, bitmap, callback))
-
- self.ResetGraphics()
- self.RefreshLabelsPosition(canvas_size.height)
- self.ShowButtons(False)
-
- def draw(self, drawDC=None):
- FigureCanvasAgg.draw(self)
-
- self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
- self.bitmap.UseAlpha()
- width, height = self.GetSize()
- bbox = self.GetAxesBoundingBox()
-
- destDC = wx.MemoryDC()
- destDC.SelectObject(self.bitmap)
-
- destGC = wx.GCDC(destDC)
-
- destGC.BeginDrawing()
- if self.Highlight == HIGHLIGHT_RESIZE:
- destGC.SetPen(HIGHLIGHT_RESIZE_PEN)
- destGC.SetBrush(HIGHLIGHT_RESIZE_BRUSH)
- destGC.DrawRectangle(0, height - 5, width, 5)
- else:
- destGC.SetPen(HIGHLIGHT_DROP_PEN)
- destGC.SetBrush(HIGHLIGHT_DROP_BRUSH)
- if self.Highlight == HIGHLIGHT_LEFT:
- destGC.DrawRectangle(bbox.x, bbox.y,
- bbox.width / 2, bbox.height)
- elif self.Highlight == HIGHLIGHT_RIGHT:
- destGC.DrawRectangle(bbox.x + bbox.width / 2, bbox.y,
- bbox.width / 2, bbox.height)
-
- self.DrawCommonElements(destGC, self.Buttons + self.ContextualButtons)
-
- destGC.EndDrawing()
-
- self._isDrawn = True
- self.gui_repaint(drawDC=drawDC)
-
- def GetButtons(self):
- return self.Buttons + self.ContextualButtons
-
- def PopupContextualButtons(self, item, rect, style=wx.RIGHT):
- if self.ContextualButtonsItem is not None and item != self.ContextualButtonsItem:
- self.DismissContextualButtons()
-
- if self.ContextualButtonsItem is None:
- self.ContextualButtonsItem = item
-
- if self.ContextualButtonsItem.IsForced():
- self.ContextualButtons.append(
- GraphButton(0, 0, "release", self.OnReleaseButton))
- for bitmap, callback in [("force", self.OnForceButton),
- ("export_graph_mini", self.OnExportItemGraphButton),
- ("delete_graph", self.OnRemoveItemButton)]:
- self.ContextualButtons.append(GraphButton(0, 0, bitmap, callback))
-
- offset = 0
- buttons = self.ContextualButtons[:]
- if style in [wx.TOP, wx.LEFT]:
- buttons.reverse()
- for button in buttons:
- w, h = button.GetSize()
- if style in [wx.LEFT, wx.RIGHT]:
- if style == wx.LEFT:
- x = rect.x - w - offset
- else:
- x = rect.x + rect.width + offset
- y = rect.y + (rect.height - h) / 2
- offset += w
- else:
- x = rect.x + (rect.width - w ) / 2
- if style == wx.TOP:
- y = rect.y - h - offset
- else:
- y = rect.y + rect.height + offset
- offset += h
- button.SetPosition(x, y)
- self.ParentWindow.ForceRefresh()
-
- def DismissContextualButtons(self):
- if self.ContextualButtonsItem is not None:
- self.ContextualButtonsItem = None
- self.ContextualButtons = []
- self.ParentWindow.ForceRefresh()
-
- def IsOverContextualButton(self, x, y):
- for button in self.ContextualButtons:
- if button.HitTest(x, y):
- return True
- return False
-
- def SetMinSize(self, size):
- wx.Window.SetMinSize(self, size)
- wx.CallAfter(self.RefreshButtonsState)
-
- def GetOnChangeSizeButton(self, size):
- def OnChangeSizeButton():
- self.CanvasSize = size
- self.SetCanvasSize(200, self.CanvasSize)
- return OnChangeSizeButton
-
- def OnExportGraphButton(self):
- self.ExportGraph()
-
- def OnForceButton(self):
- wx.CallAfter(self.ForceValue,
- self.ContextualButtonsItem)
- self.DismissContextualButtons()
-
- def OnReleaseButton(self):
- wx.CallAfter(self.ReleaseValue,
- self.ContextualButtonsItem)
- self.DismissContextualButtons()
-
- def OnExportItemGraphButton(self):
- wx.CallAfter(self.ExportGraph,
- self.ContextualButtonsItem)
- self.DismissContextualButtons()
-
- def OnRemoveItemButton(self):
- wx.CallAfter(self.ParentWindow.DeleteValue, self,
- self.ContextualButtonsItem)
- self.DismissContextualButtons()
-
- def RefreshLabelsPosition(self, height):
- canvas_ratio = 1. / height
- graph_ratio = 1. / ((1.0 - (CANVAS_BORDER[0] + CANVAS_BORDER[1]) * canvas_ratio) * height)
-
- self.Figure.subplotpars.update(
- top= 1.0 - CANVAS_BORDER[1] * canvas_ratio,
- bottom= CANVAS_BORDER[0] * canvas_ratio)
-
- if self.GraphType == GRAPH_PARALLEL or self.Is3DCanvas():
- num_item = len(self.Items)
- for idx in xrange(num_item):
- if not self.Is3DCanvas():
- self.AxesLabels[idx].set_position(
- (0.05,
- 1.0 - (CANVAS_PADDING + AXES_LABEL_HEIGHT * idx) * graph_ratio))
- self.Labels[idx].set_position(
- (0.95,
- CANVAS_PADDING * graph_ratio +
- (num_item - idx - 1) * VALUE_LABEL_HEIGHT * graph_ratio))
- else:
- self.AxesLabels[0].set_position((0.1, CANVAS_PADDING * graph_ratio))
- self.Labels[0].set_position((0.95, CANVAS_PADDING * graph_ratio))
- self.AxesLabels[1].set_position((0.05, 2 * CANVAS_PADDING * graph_ratio))
- self.Labels[1].set_position((0.05, 1.0 - CANVAS_PADDING * graph_ratio))
-
- self.Figure.subplots_adjust()
-
- def GetCanvasMinSize(self):
- return wx.Size(200,
- CANVAS_BORDER[0] + CANVAS_BORDER[1] +
- 2 * CANVAS_PADDING + VALUE_LABEL_HEIGHT * len(self.Items))
-
- def SetCanvasSize(self, width, height):
- height = max(height, self.GetCanvasMinSize()[1])
- self.SetMinSize(wx.Size(width, height))
- self.RefreshLabelsPosition(height)
- self.RefreshButtonsState()
- self.ParentWindow.RefreshGraphicsSizer()
-
- def GetAxesBoundingBox(self, absolute=False):
- width, height = self.GetSize()
- ax, ay, aw, ah = self.figure.gca().get_position().bounds
- bbox = wx.Rect(ax * width, height - (ay + ah) * height - 1,
- aw * width + 2, ah * height + 1)
- if absolute:
- xw, yw = self.GetPosition()
- bbox.x += xw
- bbox.y += yw
- return bbox
-
- def OnCanvasButtonPressed(self, event):
- width, height = self.GetSize()
- x, y = event.x, height - event.y
- if not self.IsOverButton(x, y):
- if event.inaxes == self.Axes:
- item_idx = None
- for i, t in ([pair for pair in enumerate(self.AxesLabels)] +
- [pair for pair in enumerate(self.Labels)]):
- (x0, y0), (x1, y1) = t.get_window_extent().get_points()
- rect = wx.Rect(x0, height - y1, x1 - x0, y1 - y0)
- if rect.InsideXY(x, y):
- item_idx = i
- break
- if item_idx is not None:
- self.ShowButtons(False)
- self.DismissContextualButtons()
- xw, yw = self.GetPosition()
- self.ParentWindow.StartDragNDrop(self,
- self.Items[item_idx], x + xw, y + yw, x + xw, y + yw)
- elif not self.Is3DCanvas():
- self.MouseStartPos = wx.Point(x, y)
- if event.button == 1 and event.inaxes == self.Axes:
- self.StartCursorTick = self.CursorTick
- self.HandleCursorMove(event)
- elif event.button == 2 and self.GraphType == GRAPH_PARALLEL:
- width, height = self.GetSize()
- start_tick, end_tick = self.ParentWindow.GetRange()
- self.StartCursorTick = start_tick
-
- elif event.button == 1 and event.y <= 5:
- self.MouseStartPos = wx.Point(x, y)
- self.CanvasStartSize = self.GetSize()
-
- def OnCanvasButtonReleased(self, event):
- if self.ParentWindow.IsDragging():
- width, height = self.GetSize()
- xw, yw = self.GetPosition()
- self.ParentWindow.StopDragNDrop(
- self.ParentWindow.DraggingAxesPanel.Items[0].GetVariable(),
- xw + event.x,
- yw + height - event.y)
- else:
- self.MouseStartPos = None
- self.StartCursorTick = None
- self.CanvasStartSize = None
- width, height = self.GetSize()
- self.HandleButtons(event.x, height - event.y)
- if event.y > 5 and self.SetHighlight(HIGHLIGHT_NONE):
- self.SetCursor(wx.NullCursor)
- self.ParentWindow.ForceRefresh()
-
- def OnCanvasMotion(self, event):
- width, height = self.GetSize()
- if self.ParentWindow.IsDragging():
- xw, yw = self.GetPosition()
- self.ParentWindow.MoveDragNDrop(
- xw + event.x,
- yw + height - event.y)
- else:
- if not self.Is3DCanvas():
- if event.button == 1 and self.CanvasStartSize is None:
- if event.inaxes == self.Axes:
- if self.MouseStartPos is not None:
- self.HandleCursorMove(event)
- elif self.MouseStartPos is not None and len(self.Items) == 1:
- xw, yw = self.GetPosition()
- self.ParentWindow.SetCursorTick(self.StartCursorTick)
- self.ParentWindow.StartDragNDrop(self,
- self.Items[0],
- event.x + xw, height - event.y + yw,
- self.MouseStartPos.x + xw, self.MouseStartPos.y + yw)
- elif event.button == 2 and self.GraphType == GRAPH_PARALLEL and self.MouseStartPos is not None:
- start_tick, end_tick = self.ParentWindow.GetRange()
- rect = self.GetAxesBoundingBox()
- self.ParentWindow.SetCanvasPosition(
- self.StartCursorTick + (self.MouseStartPos.x - event.x) *
- (end_tick - start_tick) / rect.width)
-
- if event.button == 1 and self.CanvasStartSize is not None:
- width, height = self.GetSize()
- self.SetCanvasSize(width,
- self.CanvasStartSize.height + height - event.y - self.MouseStartPos.y)
-
- elif event.button in [None, "up", "down"]:
- if self.GraphType == GRAPH_PARALLEL:
- orientation = [wx.RIGHT] * len(self.AxesLabels) + [wx.LEFT] * len(self.Labels)
- elif len(self.AxesLabels) > 0:
- orientation = [wx.RIGHT, wx.TOP, wx.LEFT, wx.BOTTOM]
- else:
- orientation = [wx.LEFT] * len(self.Labels)
- item_idx = None
- item_style = None
- for (i, t), style in zip([pair for pair in enumerate(self.AxesLabels)] +
- [pair for pair in enumerate(self.Labels)],
- orientation):
- (x0, y0), (x1, y1) = t.get_window_extent().get_points()
- rect = wx.Rect(x0, height - y1, x1 - x0, y1 - y0)
- if rect.InsideXY(event.x, height - event.y):
- item_idx = i
- item_style = style
- break
- if item_idx is not None:
- self.PopupContextualButtons(self.Items[item_idx], rect, item_style)
- return
- if not self.IsOverContextualButton(event.x, height - event.y):
- self.DismissContextualButtons()
-
- if event.y <= 5:
- if self.SetHighlight(HIGHLIGHT_RESIZE):
- self.SetCursor(wx.StockCursor(wx.CURSOR_SIZENS))
- self.ParentWindow.ForceRefresh()
- else:
- if self.SetHighlight(HIGHLIGHT_NONE):
- self.SetCursor(wx.NullCursor)
- self.ParentWindow.ForceRefresh()
-
- def OnCanvasScroll(self, event):
- if event.inaxes is not None and event.guiEvent.ControlDown():
- if self.GraphType == GRAPH_ORTHOGONAL:
- start_tick, end_tick = self.ParentWindow.GetRange()
- tick = (start_tick + end_tick) / 2.
- else:
- tick = event.xdata
- self.ParentWindow.ChangeRange(int(-event.step) / 3, tick)
- self.ParentWindow.VetoScrollEvent = True
-
- def OnDragging(self, x, y):
- width, height = self.GetSize()
- bbox = self.GetAxesBoundingBox()
- if bbox.InsideXY(x, y) and not self.Is3DCanvas():
- rect = wx.Rect(bbox.x, bbox.y, bbox.width / 2, bbox.height)
- if rect.InsideXY(x, y):
- self.SetHighlight(HIGHLIGHT_LEFT)
- else:
- self.SetHighlight(HIGHLIGHT_RIGHT)
- elif y < height / 2:
- if self.ParentWindow.IsViewerFirst(self):
- self.SetHighlight(HIGHLIGHT_BEFORE)
- else:
- self.SetHighlight(HIGHLIGHT_NONE)
- self.ParentWindow.HighlightPreviousViewer(self)
- else:
- self.SetHighlight(HIGHLIGHT_AFTER)
-
- def OnLeave(self, event):
- if self.CanvasStartSize is None and self.SetHighlight(HIGHLIGHT_NONE):
- self.SetCursor(wx.NullCursor)
- self.ParentWindow.ForceRefresh()
- DebugVariableViewer.OnLeave(self, event)
-
- KEY_CURSOR_INCREMENT = {
- wx.WXK_LEFT: -1,
- wx.WXK_RIGHT: 1,
- wx.WXK_UP: -10,
- wx.WXK_DOWN: 10}
- def OnKeyDown(self, event):
- if self.CursorTick is not None:
- move = self.KEY_CURSOR_INCREMENT.get(event.GetKeyCode(), None)
- if move is not None:
- self.ParentWindow.MoveCursorTick(move)
- event.Skip()
-
- def HandleCursorMove(self, event):
- start_tick, end_tick = self.ParentWindow.GetRange()
- cursor_tick = None
- if self.GraphType == GRAPH_ORTHOGONAL:
- x_data = self.Items[0].GetData(start_tick, end_tick)
- y_data = self.Items[1].GetData(start_tick, end_tick)
- if len(x_data) > 0 and len(y_data) > 0:
- length = min(len(x_data), len(y_data))
- d = numpy.sqrt((x_data[:length,1]-event.xdata) ** 2 + (y_data[:length,1]-event.ydata) ** 2)
- cursor_tick = x_data[numpy.argmin(d), 0]
- else:
- data = self.Items[0].GetData(start_tick, end_tick)
- if len(data) > 0:
- cursor_tick = data[numpy.argmin(numpy.abs(data[:,0] - event.xdata)), 0]
- if cursor_tick is not None:
- self.ParentWindow.SetCursorTick(cursor_tick)
-
- def OnAxesMotion(self, event):
- if self.Is3DCanvas():
- current_time = gettime()
- if current_time - self.LastMotionTime > REFRESH_PERIOD:
- self.LastMotionTime = current_time
- Axes3D._on_move(self.Axes, event)
-
- def ResetGraphics(self):
- self.Figure.clear()
- if self.Is3DCanvas():
- self.Axes = self.Figure.gca(projection='3d')
- self.Axes.set_color_cycle(['b'])
- self.LastMotionTime = gettime()
- setattr(self.Axes, "_on_move", self.OnAxesMotion)
- self.Axes.mouse_init()
- self.Axes.tick_params(axis='z', labelsize='small')
- else:
- self.Axes = self.Figure.gca()
- self.Axes.set_color_cycle(color_cycle)
- self.Axes.tick_params(axis='x', labelsize='small')
- self.Axes.tick_params(axis='y', labelsize='small')
- self.Plots = []
- self.VLine = None
- self.HLine = None
- self.Labels = []
- self.AxesLabels = []
- if not self.Is3DCanvas():
- text_func = self.Axes.text
- else:
- text_func = self.Axes.text2D
- if self.GraphType == GRAPH_PARALLEL or self.Is3DCanvas():
- num_item = len(self.Items)
- for idx in xrange(num_item):
- if num_item == 1:
- color = 'k'
- else:
- color = color_cycle[idx % len(color_cycle)]
- if not self.Is3DCanvas():
- self.AxesLabels.append(
- text_func(0, 0, "", size='small',
- verticalalignment='top',
- color=color,
- transform=self.Axes.transAxes))
- self.Labels.append(
- text_func(0, 0, "", size='large',
- horizontalalignment='right',
- color=color,
- transform=self.Axes.transAxes))
- else:
- self.AxesLabels.append(
- self.Axes.text(0, 0, "", size='small',
- transform=self.Axes.transAxes))
- self.Labels.append(
- self.Axes.text(0, 0, "", size='large',
- horizontalalignment='right',
- transform=self.Axes.transAxes))
- self.AxesLabels.append(
- self.Axes.text(0, 0, "", size='small',
- rotation='vertical',
- verticalalignment='bottom',
- transform=self.Axes.transAxes))
- self.Labels.append(
- self.Axes.text(0, 0, "", size='large',
- rotation='vertical',
- verticalalignment='top',
- transform=self.Axes.transAxes))
- width, height = self.GetSize()
- self.RefreshLabelsPosition(height)
-
- def AddItem(self, item):
- DebugVariableViewer.AddItem(self, item)
- self.ResetGraphics()
-
- def RemoveItem(self, item):
- DebugVariableViewer.RemoveItem(self, item)
- if not self.IsEmpty():
- if len(self.Items) == 1:
- self.GraphType = GRAPH_PARALLEL
- self.ResetGraphics()
-
- def UnregisterObsoleteData(self):
- DebugVariableViewer.UnregisterObsoleteData(self)
- if not self.IsEmpty():
- self.ResetGraphics()
-
- def Is3DCanvas(self):
- return self.GraphType == GRAPH_ORTHOGONAL and len(self.Items) == 3
-
- def SetCursorTick(self, cursor_tick):
- self.CursorTick = cursor_tick
-
- def RefreshViewer(self, refresh_graphics=True):
-
- if refresh_graphics:
- start_tick, end_tick = self.ParentWindow.GetRange()
-
- if self.GraphType == GRAPH_PARALLEL:
- min_value = max_value = None
-
- for idx, item in enumerate(self.Items):
- data = item.GetData(start_tick, end_tick)
- if data is not None:
- item_min_value, item_max_value = item.GetValueRange()
- if min_value is None:
- min_value = item_min_value
- elif item_min_value is not None:
- min_value = min(min_value, item_min_value)
- if max_value is None:
- max_value = item_max_value
- elif item_max_value is not None:
- max_value = max(max_value, item_max_value)
-
- if len(self.Plots) <= idx:
- self.Plots.append(
- self.Axes.plot(data[:, 0], data[:, 1])[0])
- else:
- self.Plots[idx].set_data(data[:, 0], data[:, 1])
-
- if min_value is not None and max_value is not None:
- y_center = (min_value + max_value) / 2.
- y_range = max(1.0, max_value - min_value)
- else:
- y_center = 0.5
- y_range = 1.0
- x_min, x_max = start_tick, end_tick
- y_min, y_max = y_center - y_range * 0.55, y_center + y_range * 0.55
-
- if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
- if self.VLine is None:
- self.VLine = self.Axes.axvline(self.CursorTick, color=cursor_color)
- else:
- self.VLine.set_xdata((self.CursorTick, self.CursorTick))
- self.VLine.set_visible(True)
- else:
- if self.VLine is not None:
- self.VLine.set_visible(False)
- else:
- min_start_tick = reduce(max, [item.GetData()[0, 0]
- for item in self.Items
- if len(item.GetData()) > 0], 0)
- start_tick = max(start_tick, min_start_tick)
- end_tick = max(end_tick, min_start_tick)
- x_data, x_min, x_max = OrthogonalData(self.Items[0], start_tick, end_tick)
- y_data, y_min, y_max = OrthogonalData(self.Items[1], start_tick, end_tick)
- if self.CursorTick is not None:
- x_cursor, x_forced = self.Items[0].GetValue(self.CursorTick, raw=True)
- y_cursor, y_forced = self.Items[1].GetValue(self.CursorTick, raw=True)
- length = 0
- if x_data is not None and y_data is not None:
- length = min(len(x_data), len(y_data))
- if len(self.Items) < 3:
- if x_data is not None and y_data is not None:
- if len(self.Plots) == 0:
- self.Plots.append(
- self.Axes.plot(x_data[:, 1][:length],
- y_data[:, 1][:length])[0])
- else:
- self.Plots[0].set_data(
- x_data[:, 1][:length],
- y_data[:, 1][:length])
-
- if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
- if self.VLine is None:
- self.VLine = self.Axes.axvline(x_cursor, color=cursor_color)
- else:
- self.VLine.set_xdata((x_cursor, x_cursor))
- if self.HLine is None:
- self.HLine = self.Axes.axhline(y_cursor, color=cursor_color)
- else:
- self.HLine.set_ydata((y_cursor, y_cursor))
- self.VLine.set_visible(True)
- self.HLine.set_visible(True)
- else:
- if self.VLine is not None:
- self.VLine.set_visible(False)
- if self.HLine is not None:
- self.HLine.set_visible(False)
- else:
- while len(self.Axes.lines) > 0:
- self.Axes.lines.pop()
- z_data, z_min, z_max = OrthogonalData(self.Items[2], start_tick, end_tick)
- if self.CursorTick is not None:
- z_cursor, z_forced = self.Items[2].GetValue(self.CursorTick, raw=True)
- if x_data is not None and y_data is not None and z_data is not None:
- length = min(length, len(z_data))
- self.Axes.plot(x_data[:, 1][:length],
- y_data[:, 1][:length],
- zs = z_data[:, 1][:length])
- self.Axes.set_zlim(z_min, z_max)
- if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
- for kwargs in [{"xs": numpy.array([x_min, x_max])},
- {"ys": numpy.array([y_min, y_max])},
- {"zs": numpy.array([z_min, z_max])}]:
- for param, value in [("xs", numpy.array([x_cursor, x_cursor])),
- ("ys", numpy.array([y_cursor, y_cursor])),
- ("zs", numpy.array([z_cursor, z_cursor]))]:
- kwargs.setdefault(param, value)
- kwargs["color"] = cursor_color
- self.Axes.plot(**kwargs)
-
- self.Axes.set_xlim(x_min, x_max)
- self.Axes.set_ylim(y_min, y_max)
-
- variable_name_mask = self.ParentWindow.GetVariableNameMask()
- if self.CursorTick is not None:
- values, forced = apply(zip, [item.GetValue(self.CursorTick) for item in self.Items])
- else:
- values, forced = apply(zip, [(item.GetValue(), item.IsForced()) for item in self.Items])
- labels = [item.GetVariable(variable_name_mask) for item in self.Items]
- styles = map(lambda x: {True: 'italic', False: 'normal'}[x], forced)
- if self.Is3DCanvas():
- for idx, label_func in enumerate([self.Axes.set_xlabel,
- self.Axes.set_ylabel,
- self.Axes.set_zlabel]):
- label_func(labels[idx], fontdict={'size': 'small','color': color_cycle[idx]})
- else:
- for label, text in zip(self.AxesLabels, labels):
- label.set_text(text)
- for label, value, style in zip(self.Labels, values, styles):
- label.set_text(value)
- label.set_style(style)
-
- self.draw()
-
- def ExportGraph(self, item=None):
- if item is not None:
- variables = [(item, [entry for entry in item.GetData()])]
- else:
- variables = [(item, [entry for entry in item.GetData()])
- for item in self.Items]
- self.ParentWindow.CopyDataToClipboard(variables)
-
class DebugVariableGraphicPanel(wx.Panel, DebugViewer):
def __init__(self, parent, producer, window):
@@ -1290,13 +295,13 @@
def UpdateCursorTick(self):
for panel in self.GraphicPanels:
- if isinstance(panel, DebugVariableGraphic):
+ 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 = DebugVariableGraphic(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ 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))
@@ -1323,7 +328,7 @@
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.OnDragging(x_mouse - x, y_mouse - y)
+ panel.RefreshHighlight(x_mouse - x, y_mouse - y)
else:
panel.SetHighlight(HIGHLIGHT_NONE)
if wx.Platform == "__WXMSW__":
@@ -1370,7 +375,7 @@
if bbox.InsideXY(x_mouse, y_mouse):
panel.ShowButtons(True)
merge_type = GRAPH_PARALLEL
- if isinstance(panel, DebugVariableText) or panel.Is3DCanvas():
+ if isinstance(panel, DebugVariableTextViewer) or panel.Is3DCanvas():
if y_mouse > yw + height / 2:
idx += 1
wx.CallAfter(self.MoveValue, variable, idx)
@@ -1423,7 +428,7 @@
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, DebugVariableGraphic):
+ if isinstance(panel, DebugVariableGraphicViewer):
panel.RefreshViewer(refresh_graphics)
else:
panel.RefreshViewer()
@@ -1463,8 +468,8 @@
self.SetTickTime(self.DataProducer.GetTicktime())
for panel in self.GraphicPanels:
- panel.UnregisterObsoleteData()
- if panel.IsEmpty():
+ panel.UnsubscribeObsoleteData()
+ if panel.ItemsIsEmpty():
if panel.HasCapture():
panel.ReleaseMouse()
self.GraphicPanels.remove(panel)
@@ -1625,11 +630,11 @@
if result is not None or force:
if item.IsNumVariable():
- panel = DebugVariableGraphic(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
if self.CursorTick is not None:
panel.SetCursorTick(self.CursorTick)
else:
- panel = DebugVariableText(self.GraphicsWindow, self, [item])
+ panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
if idx is not None:
self.GraphicPanels.insert(idx, panel)
else:
@@ -1651,19 +656,19 @@
if source_panel is not None:
source_panel.RemoveItem(item)
source_size = source_panel.GetSize()
- if source_panel.IsEmpty():
+ if source_panel.ItemsIsEmpty():
if source_panel.HasCapture():
source_panel.ReleaseMouse()
self.GraphicPanels.remove(source_panel)
source_panel.Destroy()
if item.IsNumVariable():
- panel = DebugVariableGraphic(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
+ panel = DebugVariableGraphicViewer(self.GraphicsWindow, self, [item], GRAPH_PARALLEL)
panel.SetCanvasSize(source_size.width, source_size.height)
if self.CursorTick is not None:
panel.SetCursorTick(self.CursorTick)
else:
- panel = DebugVariableText(self.GraphicsWindow, self, [item])
+ panel = DebugVariableTextViewer(self.GraphicsWindow, self, [item])
self.GraphicPanels.insert(idx, panel)
self.ResetVariableNameMask()
self.RefreshGraphicsSizer()
@@ -1699,7 +704,7 @@
if source_panel is not None:
source_panel.RemoveItem(source_item)
- if source_panel.IsEmpty():
+ if source_panel.ItemsIsEmpty():
if source_panel.HasCapture():
source_panel.ReleaseMouse()
self.GraphicPanels.remove(source_panel)
@@ -1730,14 +735,14 @@
if source_idx is not None:
if item is None:
- source_panel.Clear()
+ source_panel.ClearItems()
source_panel.Destroy()
self.GraphicPanels.remove(source_panel)
self.ResetVariableNameMask()
self.RefreshGraphicsSizer()
else:
source_panel.RemoveItem(item)
- if source_panel.IsEmpty():
+ if source_panel.ItemsIsEmpty():
source_panel.Destroy()
self.GraphicPanels.remove(source_panel)
self.ResetVariableNameMask()
@@ -1749,7 +754,7 @@
self.StartTick = 0
self.Fixed = False
for panel in self.GraphicPanels:
- panel.ResetData()
+ panel.ResetItemsData()
self.ResetCursorTick()
def RefreshGraphicsWindowScrollbars(self):
@@ -1773,7 +778,7 @@
size = self.GetSize()
for panel in self.GraphicPanels:
panel_size = panel.GetSize()
- if (isinstance(panel, DebugVariableGraphic) and
+ if (isinstance(panel, DebugVariableGraphicViewer) and
panel.GraphType == GRAPH_ORTHOGONAL and
panel_size.width == panel_size.height):
panel.SetCanvasSize(size.width, size.width)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/controls/DebugVariablePanel/DebugVariableGraphicViewer.py Fri May 31 00:07:21 2013 +0200
@@ -0,0 +1,763 @@
+#!/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
+from time import time as gettime
+import numpy
+
+import wx
+
+import matplotlib
+matplotlib.use('WX')
+import matplotlib.pyplot
+from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
+from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
+from matplotlib.backends.backend_agg import FigureCanvasAgg
+from mpl_toolkits.mplot3d import Axes3D
+
+from editors.DebugViewer import REFRESH_PERIOD
+
+from DebugVariableItem import DebugVariableItem
+from DebugVariableViewer import *
+from GraphButton import GraphButton
+
+GRAPH_PARALLEL, GRAPH_ORTHOGONAL = range(2)
+
+#CANVAS_SIZE_TYPES
+[SIZE_MINI, SIZE_MIDDLE, SIZE_MAXI] = [0, 100, 200]
+
+DEFAULT_CANVAS_HEIGHT = 200.
+CANVAS_BORDER = (20., 10.)
+CANVAS_PADDING = 8.5
+VALUE_LABEL_HEIGHT = 17.
+AXES_LABEL_HEIGHT = 12.75
+
+COLOR_CYCLE = ['r', 'b', 'g', 'm', 'y', 'k']
+CURSOR_COLOR = '#800080'
+
+def OrthogonalData(item, start_tick, end_tick):
+ data = item.GetData(start_tick, end_tick)
+ min_value, max_value = item.GetValueRange()
+ if min_value is not None and max_value is not None:
+ center = (min_value + max_value) / 2.
+ range = max(1.0, max_value - min_value)
+ else:
+ center = 0.5
+ range = 1.0
+ return data, center - range * 0.55, center + range * 0.55
+
+class DebugVariableDropTarget(wx.TextDropTarget):
+
+ def __init__(self, parent, window):
+ wx.TextDropTarget.__init__(self)
+ self.ParentControl = parent
+ self.ParentWindow = window
+
+ def __del__(self):
+ self.ParentControl = None
+ self.ParentWindow = None
+
+ def OnDragOver(self, x, y, d):
+ self.ParentControl.OnMouseDragging(x, y)
+ return wx.TextDropTarget.OnDragOver(self, x, y, d)
+
+ def OnDropText(self, x, y, data):
+ message = None
+ try:
+ values = eval(data)
+ if not isinstance(values, TupleType):
+ raise
+ except:
+ message = _("Invalid value \"%s\" for debug variable")%data
+ values = None
+
+ if message is not None:
+ wx.CallAfter(self.ShowMessage, message)
+
+ elif values[1] == "debug":
+ width, height = self.ParentControl.GetSize()
+ target_idx = self.ParentControl.GetIndex()
+ merge_type = GRAPH_PARALLEL
+ if self.ParentControl.Is3DCanvas():
+ if y > height / 2:
+ target_idx += 1
+ if len(values) > 1 and values[2] == "move":
+ self.ParentWindow.MoveValue(values[0], target_idx)
+ else:
+ self.ParentWindow.InsertValue(values[0], target_idx, force=True)
+
+ else:
+ rect = self.ParentControl.GetAxesBoundingBox()
+ if rect.InsideXY(x, y):
+ merge_rect = wx.Rect(rect.x, rect.y, rect.width / 2., rect.height)
+ if merge_rect.InsideXY(x, y):
+ merge_type = GRAPH_ORTHOGONAL
+ wx.CallAfter(self.ParentWindow.MergeGraphs, values[0], target_idx, merge_type, force=True)
+ else:
+ if y > height / 2:
+ target_idx += 1
+ if len(values) > 2 and values[2] == "move":
+ self.ParentWindow.MoveValue(values[0], target_idx)
+ else:
+ self.ParentWindow.InsertValue(values[0], target_idx, force=True)
+
+ def OnLeave(self):
+ self.ParentWindow.ResetHighlight()
+ return wx.TextDropTarget.OnLeave(self)
+
+ def ShowMessage(self, message):
+ dialog = wx.MessageDialog(self.ParentWindow, message, _("Error"), wx.OK|wx.ICON_ERROR)
+ dialog.ShowModal()
+ dialog.Destroy()
+
+
+class DebugVariableGraphicViewer(DebugVariableViewer, FigureCanvas):
+
+ def __init__(self, parent, window, items, graph_type):
+ DebugVariableViewer.__init__(self, window, items)
+
+ self.CanvasSize = SIZE_MINI
+ self.GraphType = graph_type
+ self.CursorTick = None
+ self.MouseStartPos = None
+ self.StartCursorTick = None
+ self.CanvasStartSize = None
+ self.ContextualButtons = []
+ self.ContextualButtonsItem = None
+
+ self.Figure = matplotlib.figure.Figure(facecolor='w')
+ self.Figure.subplotpars.update(top=0.95, left=0.1, bottom=0.1, right=0.95)
+
+ FigureCanvas.__init__(self, parent, -1, self.Figure)
+ self.SetWindowStyle(wx.WANTS_CHARS)
+ self.SetBackgroundColour(wx.WHITE)
+ self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
+ self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
+ self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
+ self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
+ self.Bind(wx.EVT_SIZE, self.OnResize)
+
+ canvas_size = self.GetCanvasMinSize()
+ self.SetMinSize(canvas_size)
+ self.SetDropTarget(DebugVariableDropTarget(self, window))
+ self.mpl_connect('button_press_event', self.OnCanvasButtonPressed)
+ self.mpl_connect('motion_notify_event', self.OnCanvasMotion)
+ self.mpl_connect('button_release_event', self.OnCanvasButtonReleased)
+ self.mpl_connect('scroll_event', self.OnCanvasScroll)
+
+ for size, bitmap in zip([SIZE_MINI, SIZE_MIDDLE, SIZE_MAXI],
+ ["minimize_graph", "middle_graph", "maximize_graph"]):
+ self.Buttons.append(GraphButton(0, 0, bitmap, self.GetOnChangeSizeButton(size)))
+ for bitmap, callback in [("export_graph_mini", self.OnExportGraphButton),
+ ("delete_graph", self.OnCloseButton)]:
+ self.Buttons.append(GraphButton(0, 0, bitmap, callback))
+
+ self.ResetGraphics()
+ self.RefreshLabelsPosition(canvas_size.height)
+ self.ShowButtons(False)
+
+ def draw(self, drawDC=None):
+ FigureCanvasAgg.draw(self)
+
+ self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
+ self.bitmap.UseAlpha()
+ width, height = self.GetSize()
+ bbox = self.GetAxesBoundingBox()
+
+ destDC = wx.MemoryDC()
+ destDC.SelectObject(self.bitmap)
+
+ destGC = wx.GCDC(destDC)
+
+ destGC.BeginDrawing()
+ if self.Highlight == HIGHLIGHT_RESIZE:
+ destGC.SetPen(HIGHLIGHT_RESIZE_PEN)
+ destGC.SetBrush(HIGHLIGHT_RESIZE_BRUSH)
+ destGC.DrawRectangle(0, height - 5, width, 5)
+ else:
+ destGC.SetPen(HIGHLIGHT_DROP_PEN)
+ destGC.SetBrush(HIGHLIGHT_DROP_BRUSH)
+ if self.Highlight == HIGHLIGHT_LEFT:
+ destGC.DrawRectangle(bbox.x, bbox.y,
+ bbox.width / 2, bbox.height)
+ elif self.Highlight == HIGHLIGHT_RIGHT:
+ destGC.DrawRectangle(bbox.x + bbox.width / 2, bbox.y,
+ bbox.width / 2, bbox.height)
+
+ self.DrawCommonElements(destGC, self.GetButtons())
+
+ destGC.EndDrawing()
+
+ self._isDrawn = True
+ self.gui_repaint(drawDC=drawDC)
+
+ def GetButtons(self):
+ return self.Buttons + self.ContextualButtons
+
+ def PopupContextualButtons(self, item, rect, style=wx.RIGHT):
+ if self.ContextualButtonsItem is not None and item != self.ContextualButtonsItem:
+ self.DismissContextualButtons()
+
+ if self.ContextualButtonsItem is None:
+ self.ContextualButtonsItem = item
+
+ if self.ContextualButtonsItem.IsForced():
+ self.ContextualButtons.append(
+ GraphButton(0, 0, "release", self.OnReleaseButton))
+ for bitmap, callback in [("force", self.OnForceButton),
+ ("export_graph_mini", self.OnExportItemGraphButton),
+ ("delete_graph", self.OnRemoveItemButton)]:
+ self.ContextualButtons.append(GraphButton(0, 0, bitmap, callback))
+
+ offset = 0
+ buttons = self.ContextualButtons[:]
+ if style in [wx.TOP, wx.LEFT]:
+ buttons.reverse()
+ for button in buttons:
+ w, h = button.GetSize()
+ if style in [wx.LEFT, wx.RIGHT]:
+ x = rect.x + (- w - offset
+ if style == wx.LEFT
+ else rect.width + offset)
+ y = rect.y + (rect.height - h) / 2
+ offset += w
+ else:
+ x = rect.x + (rect.width - w ) / 2
+ y = rect.y + (- h - offset
+ if style == wx.TOP
+ else rect.height + offset)
+ offset += h
+ button.SetPosition(x, y)
+ self.ParentWindow.ForceRefresh()
+
+ def DismissContextualButtons(self):
+ if self.ContextualButtonsItem is not None:
+ self.ContextualButtonsItem = None
+ self.ContextualButtons = []
+ self.ParentWindow.ForceRefresh()
+
+ def IsOverContextualButton(self, x, y):
+ for button in self.ContextualButtons:
+ if button.HitTest(x, y):
+ return True
+ return False
+
+ def SetMinSize(self, size):
+ wx.Window.SetMinSize(self, size)
+ wx.CallAfter(self.RefreshButtonsPosition)
+
+ def GetOnChangeSizeButton(self, size):
+ def OnChangeSizeButton():
+ self.CanvasSize = size
+ self.SetCanvasSize(200, self.CanvasSize)
+ return OnChangeSizeButton
+
+ def OnExportGraphButton(self):
+ self.ExportGraph()
+
+ def OnForceButton(self):
+ self.ForceValue(self.ContextualButtonsItem)
+ self.DismissContextualButtons()
+
+ def OnReleaseButton(self):
+ self.ReleaseValue(self.ContextualButtonsItem)
+ self.DismissContextualButtons()
+
+ def OnExportItemGraphButton(self):
+ self.ExportGraph(self.ContextualButtonsItem)
+ self.DismissContextualButtons()
+
+ def OnRemoveItemButton(self):
+ wx.CallAfter(self.ParentWindow.DeleteValue, self,
+ self.ContextualButtonsItem)
+ self.DismissContextualButtons()
+
+ def OnLeave(self, event):
+ if self.Highlight != HIGHLIGHT_RESIZE or self.CanvasStartSize is None:
+ DebugVariableViewer.OnLeave(self, event)
+ else:
+ event.Skip()
+
+ def RefreshLabelsPosition(self, height):
+ canvas_ratio = 1. / height
+ graph_ratio = 1. / ((1.0 - (CANVAS_BORDER[0] + CANVAS_BORDER[1]) * canvas_ratio) * height)
+
+ self.Figure.subplotpars.update(
+ top= 1.0 - CANVAS_BORDER[1] * canvas_ratio,
+ bottom= CANVAS_BORDER[0] * canvas_ratio)
+
+ if self.GraphType == GRAPH_PARALLEL or self.Is3DCanvas():
+ num_item = len(self.Items)
+ for idx in xrange(num_item):
+ if not self.Is3DCanvas():
+ self.AxesLabels[idx].set_position(
+ (0.05,
+ 1.0 - (CANVAS_PADDING + AXES_LABEL_HEIGHT * idx) * graph_ratio))
+ self.Labels[idx].set_position(
+ (0.95,
+ CANVAS_PADDING * graph_ratio +
+ (num_item - idx - 1) * VALUE_LABEL_HEIGHT * graph_ratio))
+ else:
+ self.AxesLabels[0].set_position((0.1, CANVAS_PADDING * graph_ratio))
+ self.Labels[0].set_position((0.95, CANVAS_PADDING * graph_ratio))
+ self.AxesLabels[1].set_position((0.05, 2 * CANVAS_PADDING * graph_ratio))
+ self.Labels[1].set_position((0.05, 1.0 - CANVAS_PADDING * graph_ratio))
+
+ self.Figure.subplots_adjust()
+
+ def GetCanvasMinSize(self):
+ return wx.Size(200,
+ CANVAS_BORDER[0] + CANVAS_BORDER[1] +
+ 2 * CANVAS_PADDING + VALUE_LABEL_HEIGHT * len(self.Items))
+
+ def SetCanvasSize(self, width, height):
+ height = max(height, self.GetCanvasMinSize()[1])
+ self.SetMinSize(wx.Size(width, height))
+ self.RefreshLabelsPosition(height)
+ self.RefreshButtonsPosition()
+ self.ParentWindow.RefreshGraphicsSizer()
+
+ def GetAxesBoundingBox(self, absolute=False):
+ width, height = self.GetSize()
+ ax, ay, aw, ah = self.figure.gca().get_position().bounds
+ bbox = wx.Rect(ax * width, height - (ay + ah) * height - 1,
+ aw * width + 2, ah * height + 1)
+ if absolute:
+ xw, yw = self.GetPosition()
+ bbox.x += xw
+ bbox.y += yw
+ return bbox
+
+ def OnCanvasButtonPressed(self, event):
+ width, height = self.GetSize()
+ x, y = event.x, height - event.y
+ if not self.IsOverButton(x, y):
+ if event.inaxes == self.Axes:
+ item_idx = None
+ for i, t in ([pair for pair in enumerate(self.AxesLabels)] +
+ [pair for pair in enumerate(self.Labels)]):
+ (x0, y0), (x1, y1) = t.get_window_extent().get_points()
+ rect = wx.Rect(x0, height - y1, x1 - x0, y1 - y0)
+ if rect.InsideXY(x, y):
+ item_idx = i
+ break
+ if item_idx is not None:
+ self.ShowButtons(False)
+ self.DismissContextualButtons()
+ xw, yw = self.GetPosition()
+ self.ParentWindow.StartDragNDrop(self,
+ self.ItemsDict.values()[item_idx], x + xw, y + yw, x + xw, y + yw)
+ elif not self.Is3DCanvas():
+ self.MouseStartPos = wx.Point(x, y)
+ if event.button == 1 and event.inaxes == self.Axes:
+ self.StartCursorTick = self.CursorTick
+ self.HandleCursorMove(event)
+ elif event.button == 2 and self.GraphType == GRAPH_PARALLEL:
+ width, height = self.GetSize()
+ start_tick, end_tick = self.ParentWindow.GetRange()
+ self.StartCursorTick = start_tick
+
+ elif event.button == 1 and event.y <= 5:
+ self.MouseStartPos = wx.Point(x, y)
+ self.CanvasStartSize = self.GetSize()
+
+ def OnCanvasButtonReleased(self, event):
+ if self.ParentWindow.IsDragging():
+ width, height = self.GetSize()
+ xw, yw = self.GetPosition()
+ self.ParentWindow.StopDragNDrop(
+ self.ParentWindow.DraggingAxesPanel.ItemsDict.values()[0].GetVariable(),
+ xw + event.x,
+ yw + height - event.y)
+ else:
+ self.MouseStartPos = None
+ self.StartCursorTick = None
+ self.CanvasStartSize = None
+ width, height = self.GetSize()
+ self.HandleButton(event.x, height - event.y)
+ if event.y > 5 and self.SetHighlight(HIGHLIGHT_NONE):
+ self.SetCursor(wx.NullCursor)
+ self.ParentWindow.ForceRefresh()
+
+ def OnCanvasMotion(self, event):
+ width, height = self.GetSize()
+ if self.ParentWindow.IsDragging():
+ xw, yw = self.GetPosition()
+ self.ParentWindow.MoveDragNDrop(
+ xw + event.x,
+ yw + height - event.y)
+ else:
+ if not self.Is3DCanvas():
+ if event.button == 1 and self.CanvasStartSize is None:
+ if event.inaxes == self.Axes:
+ if self.MouseStartPos is not None:
+ self.HandleCursorMove(event)
+ elif self.MouseStartPos is not None and len(self.Items) == 1:
+ xw, yw = self.GetPosition()
+ self.ParentWindow.SetCursorTick(self.StartCursorTick)
+ self.ParentWindow.StartDragNDrop(self,
+ self.ItemsDict.values()[0],
+ event.x + xw, height - event.y + yw,
+ self.MouseStartPos.x + xw, self.MouseStartPos.y + yw)
+ elif event.button == 2 and self.GraphType == GRAPH_PARALLEL and self.MouseStartPos is not None:
+ start_tick, end_tick = self.ParentWindow.GetRange()
+ rect = self.GetAxesBoundingBox()
+ self.ParentWindow.SetCanvasPosition(
+ self.StartCursorTick + (self.MouseStartPos.x - event.x) *
+ (end_tick - start_tick) / rect.width)
+
+ if event.button == 1 and self.CanvasStartSize is not None:
+ width, height = self.GetSize()
+ self.SetCanvasSize(width,
+ self.CanvasStartSize.height + height - event.y - self.MouseStartPos.y)
+
+ elif event.button in [None, "up", "down"]:
+ if self.GraphType == GRAPH_PARALLEL:
+ orientation = [wx.RIGHT] * len(self.AxesLabels) + [wx.LEFT] * len(self.Labels)
+ elif len(self.AxesLabels) > 0:
+ orientation = [wx.RIGHT, wx.TOP, wx.LEFT, wx.BOTTOM]
+ else:
+ orientation = [wx.LEFT] * len(self.Labels)
+ item_idx = None
+ item_style = None
+ for (i, t), style in zip([pair for pair in enumerate(self.AxesLabels)] +
+ [pair for pair in enumerate(self.Labels)],
+ orientation):
+ (x0, y0), (x1, y1) = t.get_window_extent().get_points()
+ rect = wx.Rect(x0, height - y1, x1 - x0, y1 - y0)
+ if rect.InsideXY(event.x, height - event.y):
+ item_idx = i
+ item_style = style
+ break
+ if item_idx is not None:
+ self.PopupContextualButtons(self.ItemsDict.values()[item_idx], rect, item_style)
+ return
+ if not self.IsOverContextualButton(event.x, height - event.y):
+ self.DismissContextualButtons()
+
+ if event.y <= 5:
+ if self.SetHighlight(HIGHLIGHT_RESIZE):
+ self.SetCursor(wx.StockCursor(wx.CURSOR_SIZENS))
+ self.ParentWindow.ForceRefresh()
+ else:
+ if self.SetHighlight(HIGHLIGHT_NONE):
+ self.SetCursor(wx.NullCursor)
+ self.ParentWindow.ForceRefresh()
+
+ def OnCanvasScroll(self, event):
+ if event.inaxes is not None and event.guiEvent.ControlDown():
+ if self.GraphType == GRAPH_ORTHOGONAL:
+ start_tick, end_tick = self.ParentWindow.GetRange()
+ tick = (start_tick + end_tick) / 2.
+ else:
+ tick = event.xdata
+ self.ParentWindow.ChangeRange(int(-event.step) / 3, tick)
+ self.ParentWindow.VetoScrollEvent = True
+
+ def RefreshHighlight(self, x, y):
+ width, height = self.GetSize()
+ bbox = self.GetAxesBoundingBox()
+ if bbox.InsideXY(x, y) and not self.Is3DCanvas():
+ rect = wx.Rect(bbox.x, bbox.y, bbox.width / 2, bbox.height)
+ if rect.InsideXY(x, y):
+ self.SetHighlight(HIGHLIGHT_LEFT)
+ else:
+ self.SetHighlight(HIGHLIGHT_RIGHT)
+ elif y < height / 2:
+ if self.ParentWindow.IsViewerFirst(self):
+ self.SetHighlight(HIGHLIGHT_BEFORE)
+ else:
+ self.SetHighlight(HIGHLIGHT_NONE)
+ self.ParentWindow.HighlightPreviousViewer(self)
+ else:
+ self.SetHighlight(HIGHLIGHT_AFTER)
+
+ def OnLeave(self, event):
+ if self.CanvasStartSize is None and self.SetHighlight(HIGHLIGHT_NONE):
+ self.SetCursor(wx.NullCursor)
+ self.ParentWindow.ForceRefresh()
+ DebugVariableViewer.OnLeave(self, event)
+
+ KEY_CURSOR_INCREMENT = {
+ wx.WXK_LEFT: -1,
+ wx.WXK_RIGHT: 1,
+ wx.WXK_UP: -10,
+ wx.WXK_DOWN: 10}
+ def OnKeyDown(self, event):
+ if self.CursorTick is not None:
+ move = self.KEY_CURSOR_INCREMENT.get(event.GetKeyCode(), None)
+ if move is not None:
+ self.ParentWindow.MoveCursorTick(move)
+ event.Skip()
+
+ def HandleCursorMove(self, event):
+ start_tick, end_tick = self.ParentWindow.GetRange()
+ cursor_tick = None
+ items = self.ItemsDict.values()
+ if self.GraphType == GRAPH_ORTHOGONAL:
+ x_data = items[0].GetData(start_tick, end_tick)
+ y_data = items[1].GetData(start_tick, end_tick)
+ if len(x_data) > 0 and len(y_data) > 0:
+ length = min(len(x_data), len(y_data))
+ d = numpy.sqrt((x_data[:length,1]-event.xdata) ** 2 + (y_data[:length,1]-event.ydata) ** 2)
+ cursor_tick = x_data[numpy.argmin(d), 0]
+ else:
+ data = items[0].GetData(start_tick, end_tick)
+ if len(data) > 0:
+ cursor_tick = data[numpy.argmin(numpy.abs(data[:,0] - event.xdata)), 0]
+ if cursor_tick is not None:
+ self.ParentWindow.SetCursorTick(cursor_tick)
+
+ def OnAxesMotion(self, event):
+ if self.Is3DCanvas():
+ current_time = gettime()
+ if current_time - self.LastMotionTime > REFRESH_PERIOD:
+ self.LastMotionTime = current_time
+ Axes3D._on_move(self.Axes, event)
+
+ def ResetGraphics(self):
+ self.Figure.clear()
+ if self.Is3DCanvas():
+ self.Axes = self.Figure.gca(projection='3d')
+ self.Axes.set_color_cycle(['b'])
+ self.LastMotionTime = gettime()
+ setattr(self.Axes, "_on_move", self.OnAxesMotion)
+ self.Axes.mouse_init()
+ self.Axes.tick_params(axis='z', labelsize='small')
+ else:
+ self.Axes = self.Figure.gca()
+ self.Axes.set_color_cycle(COLOR_CYCLE)
+ self.Axes.tick_params(axis='x', labelsize='small')
+ self.Axes.tick_params(axis='y', labelsize='small')
+ self.Plots = []
+ self.VLine = None
+ self.HLine = None
+ self.Labels = []
+ self.AxesLabels = []
+ if not self.Is3DCanvas():
+ text_func = self.Axes.text
+ else:
+ text_func = self.Axes.text2D
+ if self.GraphType == GRAPH_PARALLEL or self.Is3DCanvas():
+ num_item = len(self.Items)
+ for idx in xrange(num_item):
+ if num_item == 1:
+ color = 'k'
+ else:
+ color = COLOR_CYCLE[idx % len(COLOR_CYCLE)]
+ if not self.Is3DCanvas():
+ self.AxesLabels.append(
+ text_func(0, 0, "", size='small',
+ verticalalignment='top',
+ color=color,
+ transform=self.Axes.transAxes))
+ self.Labels.append(
+ text_func(0, 0, "", size='large',
+ horizontalalignment='right',
+ color=color,
+ transform=self.Axes.transAxes))
+ else:
+ self.AxesLabels.append(
+ self.Axes.text(0, 0, "", size='small',
+ transform=self.Axes.transAxes))
+ self.Labels.append(
+ self.Axes.text(0, 0, "", size='large',
+ horizontalalignment='right',
+ transform=self.Axes.transAxes))
+ self.AxesLabels.append(
+ self.Axes.text(0, 0, "", size='small',
+ rotation='vertical',
+ verticalalignment='bottom',
+ transform=self.Axes.transAxes))
+ self.Labels.append(
+ self.Axes.text(0, 0, "", size='large',
+ rotation='vertical',
+ verticalalignment='top',
+ transform=self.Axes.transAxes))
+ width, height = self.GetSize()
+ self.RefreshLabelsPosition(height)
+
+ def AddItem(self, item):
+ DebugVariableViewer.AddItem(self, item)
+ self.ResetGraphics()
+
+ def RemoveItem(self, item):
+ DebugVariableViewer.RemoveItem(self, item)
+ if not self.ItemsIsEmpty():
+ if len(self.Items) == 1:
+ self.GraphType = GRAPH_PARALLEL
+ self.ResetGraphics()
+
+ def UnsubscribeObsoleteData(self):
+ DebugVariableViewer.UnsubscribeObsoleteData(self)
+ if not self.ItemsIsEmpty():
+ self.ResetGraphics()
+
+ def Is3DCanvas(self):
+ return self.GraphType == GRAPH_ORTHOGONAL and len(self.Items) == 3
+
+ def SetCursorTick(self, cursor_tick):
+ self.CursorTick = cursor_tick
+
+ def RefreshViewer(self, refresh_graphics=True):
+
+ if refresh_graphics:
+ start_tick, end_tick = self.ParentWindow.GetRange()
+
+ if self.GraphType == GRAPH_PARALLEL:
+ min_value = max_value = None
+
+ for idx, item in enumerate(self.Items):
+ data = item.GetData(start_tick, end_tick)
+ if data is not None:
+ item_min_value, item_max_value = item.GetValueRange()
+ if min_value is None:
+ min_value = item_min_value
+ elif item_min_value is not None:
+ min_value = min(min_value, item_min_value)
+ if max_value is None:
+ max_value = item_max_value
+ elif item_max_value is not None:
+ max_value = max(max_value, item_max_value)
+
+ if len(self.Plots) <= idx:
+ self.Plots.append(
+ self.Axes.plot(data[:, 0], data[:, 1])[0])
+ else:
+ self.Plots[idx].set_data(data[:, 0], data[:, 1])
+
+ if min_value is not None and max_value is not None:
+ y_center = (min_value + max_value) / 2.
+ y_range = max(1.0, max_value - min_value)
+ else:
+ y_center = 0.5
+ y_range = 1.0
+ x_min, x_max = start_tick, end_tick
+ y_min, y_max = y_center - y_range * 0.55, y_center + y_range * 0.55
+
+ if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
+ if self.VLine is None:
+ self.VLine = self.Axes.axvline(self.CursorTick, color=CURSOR_COLOR)
+ else:
+ self.VLine.set_xdata((self.CursorTick, self.CursorTick))
+ self.VLine.set_visible(True)
+ else:
+ if self.VLine is not None:
+ self.VLine.set_visible(False)
+ else:
+ min_start_tick = reduce(max, [item.GetData()[0, 0]
+ for item in self.Items
+ if len(item.GetData()) > 0], 0)
+ start_tick = max(start_tick, min_start_tick)
+ end_tick = max(end_tick, min_start_tick)
+ items = self.ItemsDict.values()
+ x_data, x_min, x_max = OrthogonalData(items[0], start_tick, end_tick)
+ y_data, y_min, y_max = OrthogonalData(items[1], start_tick, end_tick)
+ if self.CursorTick is not None:
+ x_cursor, x_forced = items[0].GetValue(self.CursorTick, raw=True)
+ y_cursor, y_forced = items[1].GetValue(self.CursorTick, raw=True)
+ length = 0
+ if x_data is not None and y_data is not None:
+ length = min(len(x_data), len(y_data))
+ if len(self.Items) < 3:
+ if x_data is not None and y_data is not None:
+ if len(self.Plots) == 0:
+ self.Plots.append(
+ self.Axes.plot(x_data[:, 1][:length],
+ y_data[:, 1][:length])[0])
+ else:
+ self.Plots[0].set_data(
+ x_data[:, 1][:length],
+ y_data[:, 1][:length])
+
+ if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
+ if self.VLine is None:
+ self.VLine = self.Axes.axvline(x_cursor, color=CURSOR_COLOR)
+ else:
+ self.VLine.set_xdata((x_cursor, x_cursor))
+ if self.HLine is None:
+ self.HLine = self.Axes.axhline(y_cursor, color=CURSOR_COLOR)
+ else:
+ self.HLine.set_ydata((y_cursor, y_cursor))
+ self.VLine.set_visible(True)
+ self.HLine.set_visible(True)
+ else:
+ if self.VLine is not None:
+ self.VLine.set_visible(False)
+ if self.HLine is not None:
+ self.HLine.set_visible(False)
+ else:
+ while len(self.Axes.lines) > 0:
+ self.Axes.lines.pop()
+ z_data, z_min, z_max = OrthogonalData(items[2], start_tick, end_tick)
+ if self.CursorTick is not None:
+ z_cursor, z_forced = items[2].GetValue(self.CursorTick, raw=True)
+ if x_data is not None and y_data is not None and z_data is not None:
+ length = min(length, len(z_data))
+ self.Axes.plot(x_data[:, 1][:length],
+ y_data[:, 1][:length],
+ zs = z_data[:, 1][:length])
+ self.Axes.set_zlim(z_min, z_max)
+ if self.CursorTick is not None and start_tick <= self.CursorTick <= end_tick:
+ for kwargs in [{"xs": numpy.array([x_min, x_max])},
+ {"ys": numpy.array([y_min, y_max])},
+ {"zs": numpy.array([z_min, z_max])}]:
+ for param, value in [("xs", numpy.array([x_cursor, x_cursor])),
+ ("ys", numpy.array([y_cursor, y_cursor])),
+ ("zs", numpy.array([z_cursor, z_cursor]))]:
+ kwargs.setdefault(param, value)
+ kwargs["color"] = CURSOR_COLOR
+ self.Axes.plot(**kwargs)
+
+ self.Axes.set_xlim(x_min, x_max)
+ self.Axes.set_ylim(y_min, y_max)
+
+ variable_name_mask = self.ParentWindow.GetVariableNameMask()
+ if self.CursorTick is not None:
+ values, forced = apply(zip, [item.GetValue(self.CursorTick) for item in self.Items])
+ else:
+ values, forced = apply(zip, [(item.GetValue(), item.IsForced()) for item in self.Items])
+ labels = [item.GetVariable(variable_name_mask) for item in self.Items]
+ styles = map(lambda x: {True: 'italic', False: 'normal'}[x], forced)
+ if self.Is3DCanvas():
+ for idx, label_func in enumerate([self.Axes.set_xlabel,
+ self.Axes.set_ylabel,
+ self.Axes.set_zlabel]):
+ label_func(labels[idx], fontdict={'size': 'small','color': COLOR_CYCLE[idx]})
+ else:
+ for label, text in zip(self.AxesLabels, labels):
+ label.set_text(text)
+ for label, value, style in zip(self.Labels, values, styles):
+ label.set_text(value)
+ label.set_style(style)
+
+ self.draw()
+
+ def ExportGraph(self, item=None):
+ if item is not None:
+ variables = [(item, [entry for entry in item.GetData()])]
+ else:
+ variables = [(item, [entry for entry in item.GetData()])
+ for item in self.Items]
+ self.ParentWindow.CopyDataToClipboard(variables)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/controls/DebugVariablePanel/DebugVariableTextViewer.py Fri May 31 00:07:21 2013 +0200
@@ -0,0 +1,274 @@
+#!/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
+
+from DebugVariableItem import DebugVariableItem
+from DebugVariableViewer import DebugVariableViewer
+from GraphButton import GraphButton
+
+#-------------------------------------------------------------------------------
+# Debug Variable Text Viewer Drop Target
+#-------------------------------------------------------------------------------
+
+"""
+Class that implements a custom drop target class for Debug Variable Text Viewer
+"""
+
+class DebugVariableTextDropTarget(wx.TextDropTarget):
+
+ def __init__(self, parent, window):
+ """
+ Constructor
+ @param parent: Reference to Debug Variable Text Viewer
+ @param window: Reference to the Debug Variable Panel
+ """
+ wx.TextDropTarget.__init__(self)
+ self.ParentControl = parent
+ self.ParentWindow = window
+
+ def __del__(self):
+ """
+ Destructor
+ """
+ # Remove reference to Debug Variable Text Viewer and Debug Variable
+ # Panel
+ self.ParentControl = None
+ 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 parent that mouse is dragged over
+ self.ParentControl.OnMouseDragging(x, y)
+
+ return wx.TextDropTarget.OnDragOver(self, x, y, d)
+
+ 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
+ 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":
+
+ # Get Before which Viewer the variable has to be moved or added
+ # according to the position of mouse in Viewer.
+ width, height = self.ParentControl.GetSize()
+ target_idx = self.ParentControl.GetIndex()
+ if y > height / 2:
+ target_idx += 1
+
+ # 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],
+ target_idx)
+
+ # Drag'n Drop was initiated by another control of Beremiz
+ else:
+ self.ParentWindow.InsertValue(values[0],
+ target_idx,
+ 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 Text Viewer Class
+#-------------------------------------------------------------------------------
+
+"""
+Class that implements a Viewer that display variable values as a text
+"""
+
+class DebugVariableTextViewer(DebugVariableViewer, wx.Panel):
+
+ def __init__(self, parent, window, items=[]):
+ """
+ Constructor
+ @param parent: Parent wx.Window of DebugVariableText
+ @param window: Reference to the Debug Variable Panel
+ @param items: List of DebugVariableItem displayed by Viewer
+ """
+ DebugVariableViewer.__init__(self, window, items)
+
+ wx.Panel.__init__(self, parent)
+ # Set panel background colour
+ self.SetBackgroundColour(wx.WHITE)
+ # Define panel drop target
+ self.SetDropTarget(DebugVariableTextDropTarget(self, window))
+
+ # Bind events
+ self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
+ self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
+ self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
+ self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
+ self.Bind(wx.EVT_SIZE, self.OnResize)
+ self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
+ self.Bind(wx.EVT_PAINT, self.OnPaint)
+
+ # Define panel min size for parent sizer layout
+ self.SetMinSize(wx.Size(0, 25))
+
+ # Add buttons to Viewer
+ for bitmap, callback in [("force", self.OnForceButton),
+ ("release", self.OnReleaseButton),
+ ("delete_graph", self.OnCloseButton)]:
+ self.Buttons.append(GraphButton(0, 0, bitmap, callback))
+
+ # Hide buttons until mouse enter Viewer
+ self.ShowButtons(False)
+
+ def RefreshViewer(self):
+ """
+ Method that refresh the content displayed by Viewer
+ """
+ # Create buffered DC for drawing in panel
+ width, height = self.GetSize()
+ bitmap = wx.EmptyBitmap(width, height)
+ dc = wx.BufferedDC(wx.ClientDC(self), bitmap)
+ dc.Clear()
+ dc.BeginDrawing()
+
+ # Get Graphics Context for DC, for anti-aliased and transparent
+ # rendering
+ gc = wx.GCDC(dc)
+
+ # Get first item
+ item = self.ItemsDict.values()[0]
+
+ # Get item variable path masked according Debug Variable Panel mask
+ item_path = item.GetVariable(
+ self.ParentWindow.GetVariableNameMask())
+
+ # Draw item variable path at Viewer left side
+ w, h = gc.GetTextExtent(item_path)
+ gc.DrawText(item_path, 20, (height - h) / 2)
+
+ # Update 'Release' button state and text color according to item forced
+ # flag value
+ item_forced = item.IsForced()
+ self.Buttons[1].Enable(item_forced)
+ self.RefreshButtonsPosition()
+ if item_forced:
+ gc.SetTextForeground(wx.BLUE)
+
+ # Draw item current value at right side of Viewer
+ item_value = item.GetValue()
+ w, h = gc.GetTextExtent(item_value)
+ gc.DrawText(item_value, width - 40 - w, (height - h) / 2)
+
+ # Draw other Viewer common elements
+ self.DrawCommonElements(gc)
+
+ gc.EndDrawing()
+
+ def OnLeftDown(self, event):
+ """
+ Function called when mouse left button is pressed
+ @param event: wx.MouseEvent
+ """
+ # Get first item
+ item = self.ItemsDict.values()[0]
+
+ # Calculate item path bounding box
+ width, height = self.GetSize()
+ item_path = item.GetVariable(
+ self.ParentWindow.GetVariableNameMask())
+ w, h = self.GetTextExtent(item_path)
+
+ # Test if mouse has been pressed in this bounding box. In that case
+ # start a move drag'n drop of item variable
+ x, y = event.GetPosition()
+ item_path_bbox = wx.Rect(20, (height - h) / 2, w, h)
+ if item_path_bbox.InsideXY(x, y):
+ data = wx.TextDataObject(str((item.GetVariable(), "debug", "move")))
+ dragSource = wx.DropSource(self)
+ dragSource.SetData(data)
+ dragSource.DoDragDrop()
+
+ # In other case handle event normally
+ else:
+ event.Skip()
+
+ def OnLeftUp(self, event):
+ """
+ Function called when mouse left button is released
+ @param event: wx.MouseEvent
+ """
+ # Execute callback on button under mouse pointer if it exists
+ x, y = event.GetPosition()
+ wx.CallAfter(self.HandleButton, x, y)
+ event.Skip()
+
+ def OnPaint(self, event):
+ """
+ Function called when redrawing Viewer content is needed
+ @param event: wx.PaintEvent
+ """
+ self.RefreshViewer()
+ event.Skip()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/controls/DebugVariablePanel/DebugVariableViewer.py Fri May 31 00:07:21 2013 +0200
@@ -0,0 +1,420 @@
+#!/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 collections import OrderedDict
+
+import wx
+
+import matplotlib
+matplotlib.use('WX')
+import matplotlib.pyplot
+from matplotlib.backends.backend_wxagg import _convert_agg_to_wx_bitmap
+
+from dialogs.ForceVariableDialog import ForceVariableDialog
+
+# Viewer highlight types
+[HIGHLIGHT_NONE,
+ HIGHLIGHT_BEFORE,
+ HIGHLIGHT_AFTER,
+ HIGHLIGHT_LEFT,
+ HIGHLIGHT_RIGHT,
+ HIGHLIGHT_RESIZE] = range(6)
+
+# Viewer highlight styles
+HIGHLIGHT_DROP_PEN = wx.Pen(wx.Colour(0, 128, 255))
+HIGHLIGHT_DROP_BRUSH = wx.Brush(wx.Colour(0, 128, 255, 128))
+HIGHLIGHT_RESIZE_PEN = wx.Pen(wx.Colour(200, 200, 200))
+HIGHLIGHT_RESIZE_BRUSH = wx.Brush(wx.Colour(200, 200, 200))
+
+#-------------------------------------------------------------------------------
+# Base Debug Variable Viewer Class
+#-------------------------------------------------------------------------------
+
+"""
+Class that implements a generic viewer that display a list of variable values
+This class has to be inherited to effectively display variable values
+"""
+
+class DebugVariableViewer:
+
+ def __init__(self, window, items=[]):
+ """
+ Constructor
+ @param window: Reference to the Debug Variable Panel
+ @param items: List of DebugVariableItem displayed by Viewer
+ """
+ self.ParentWindow = window
+ self.ItemsDict = OrderedDict([(item.GetVariable(), item)
+ for item in items])
+ self.Items = self.ItemsDict.viewvalues()
+
+ # Variable storing current highlight displayed in Viewer
+ self.Highlight = HIGHLIGHT_NONE
+ # List of buttons
+ self.Buttons = []
+
+ def __del__(self):
+ """
+ Destructor
+ """
+ # Remove reference to Debug Variable Panel
+ self.ParentWindow = None
+
+ def GetIndex(self):
+ """
+ Return position of Viewer in Debug Variable Panel
+ @return: Position of Viewer
+ """
+ return self.ParentWindow.GetViewerIndex(self)
+
+ def GetItem(self, variable):
+ """
+ Return item storing values of a variable
+ @param variable: Variable path
+ @return: Item storing values of this variable
+ """
+ return self.ItemsDict.get(variable, None)
+
+ def GetItems(self):
+ """
+ Return items displayed by Viewer
+ @return: List of items displayed in Viewer
+ """
+ return self.Items
+
+ def AddItem(self, item):
+ """
+ Add an item to the list of items displayed by Viewer
+ @param item: Item to add to the list
+ """
+ self.ItemsDict[item.GetVariable()] = item
+
+ def RemoveItem(self, item):
+ """
+ Remove an item from the list of items displayed by Viewer
+ @param item: Item to remove from the list
+ """
+ self.ItemsDict.pop(item.GetVariable(), None)
+
+ def ClearItems(self):
+ """
+ Clear list of items displayed by Viewer
+ """
+ # Unsubscribe every items of the list
+ for item in self.Items:
+ self.ParentWindow.RemoveDataConsumer(item)
+
+ # Clear list
+ self.Items.clear()
+
+ def ItemsIsEmpty(self):
+ """
+ Return if list of items displayed by Viewer is empty
+ @return: True if list is empty
+ """
+ return len(self.Items) == 0
+
+ def UnsubscribeObsoleteData(self):
+ """
+ Function that unsubscribe and remove every item that store values of
+ a variable that doesn't exist in PLC anymore
+ """
+ for item in self.ItemsDict.values()[:]:
+ iec_path = item.GetVariable()
+
+ # Check that variablepath exist in PLC
+ if self.ParentWindow.GetDataType(iec_path) is None:
+ # If not, unsubscribe and remove it
+ self.ParentWindow.RemoveDataConsumer(item)
+ self.RemoveItem(item)
+ else:
+ # If it exist, resubscribe and refresh data type
+ self.ParentWindow.AddDataConsumer(iec_path.upper(), item)
+ item.RefreshVariableType()
+
+ def ResetItemsData(self):
+ """
+ Reset data stored in every items displayed in Viewer
+ """
+ for item in self.Items:
+ item.ResetData()
+
+ def RefreshViewer(self):
+ """
+ Method that refresh the content displayed by Viewer
+ Need to be overridden by inherited classes
+ """
+ pass
+
+ def SetHighlight(self, highlight):
+ """
+ Set Highlight type displayed in Viewer
+ @return: True if highlight has changed
+ """
+ # Return immediately if highlight don't change
+ if self.Highlight == highlight:
+ return False
+
+ self.Highlight = highlight
+ return True
+
+ def GetButtons(self):
+ """
+ Return list of buttons defined in Viewer
+ @return: List of buttons
+ """
+ return self.Buttons
+
+ def IsOverButton(self, x, y):
+ """
+ Return if point is over one button of Viewer
+ @param x: X coordinate of point
+ @param y: Y coordinate of point
+ @return: button where point is over
+ """
+ for button in self.GetButtons():
+ if button.HitTest(x, y):
+ return button
+ return None
+
+ def HandleButton(self, x, y):
+ """
+ Search for the button under point and if found execute associated
+ callback
+ @param x: X coordinate of point
+ @param y: Y coordinate of point
+ @return: True if a button was found and callback executed
+ """
+ button = self.IsOverButton(x, y)
+ if button is None:
+ return False
+
+ button.ProcessCallback()
+ return True
+
+ def ShowButtons(self, show):
+ """
+ Set display state of buttons in Viewer
+ @param show: Display state (True if buttons must be displayed)
+ """
+ # Change display of every buttons
+ for button in self.Buttons:
+ button.Show(show)
+
+ # Refresh button positions
+ self.RefreshButtonsPosition()
+ self.RefreshViewer()
+
+ def RefreshButtonsPosition(self):
+ """
+ Function that refresh buttons position in Viewer
+ """
+ # Get Viewer size
+ width, height = self.GetSize()
+
+ # Buttons are align right so we calculate buttons positions in
+ # reverse order
+ buttons = self.Buttons[:]
+ buttons.reverse()
+
+ # Position offset on x coordinate
+ x_offset = 0
+ for button in buttons:
+ # Buttons are stacked right, removing those that are not active
+ if button.IsEnabled():
+ # Update button position according to button width and offset
+ # on x coordinate
+ w, h = button.GetSize()
+ button.SetPosition(width - 5 - w - x_offset, 5)
+ # Update offset on x coordinate
+ x_offset += w + 2
+
+ def DrawCommonElements(self, dc, buttons=None):
+ """
+ Function that draw common graphics for every Viewers
+ @param dc: wx.DC object corresponding to Device context where drawing
+ common graphics
+ @param buttons: List of buttons to draw if different from default
+ (default None)
+ """
+ # Get Viewer size
+ width, height = self.GetSize()
+
+ # Set dc styling for drop before or drop after highlight
+ dc.SetPen(HIGHLIGHT_DROP_PEN)
+ dc.SetBrush(HIGHLIGHT_DROP_BRUSH)
+
+ # Draw line at upper side of Viewer if highlight is drop before
+ if self.Highlight == HIGHLIGHT_BEFORE:
+ dc.DrawLine(0, 1, width - 1, 1)
+
+ # Draw line at lower side of Viewer if highlight is drop before
+ elif self.Highlight == HIGHLIGHT_AFTER:
+ dc.DrawLine(0, height - 1, width - 1, height - 1)
+
+ # If no specific buttons are defined, get default buttons
+ if buttons is None:
+ buttons = self.Buttons
+ # Draw buttons
+ for button in buttons:
+ button.Draw(dc)
+
+ # If graph dragging is processing
+ if self.ParentWindow.IsDragging():
+ destBBox = self.ParentWindow.GetDraggingAxesClippingRegion(self)
+ srcPos = self.ParentWindow.GetDraggingAxesPosition(self)
+ if destBBox.width > 0 and destBBox.height > 0:
+ srcPanel = self.ParentWindow.DraggingAxesPanel
+ srcBBox = srcPanel.GetAxesBoundingBox()
+
+ srcX = srcBBox.x - (srcPos.x if destBBox.x == 0 else 0)
+ srcY = srcBBox.y - (srcPos.y if destBBox.y == 0 else 0)
+
+ srcBmp = _convert_agg_to_wx_bitmap(
+ srcPanel.get_renderer(), None)
+ srcDC = wx.MemoryDC()
+ srcDC.SelectObject(srcBmp)
+
+ dc.Blit(destBBox.x, destBBox.y,
+ int(destBBox.width), int(destBBox.height),
+ srcDC, srcX, srcY)
+
+ def OnEnter(self, event):
+ """
+ Function called when entering Viewer
+ @param event: wx.MouseEvent
+ """
+ # Display buttons
+ self.ShowButtons(True)
+ event.Skip()
+
+ def OnLeave(self, event):
+ """
+ Function called when leaving Viewer
+ @param event: wx.MouseEvent
+ """
+ # Check that mouse position is inside Viewer and hide buttons
+ x, y = event.GetPosition()
+ width, height = self.GetSize()
+ if not (0 < x < width - 1 and 0 < y < height - 1):
+ self.ShowButtons(False)
+ event.Skip()
+
+ def OnCloseButton(self):
+ """
+ Function called when Close button is pressed
+ """
+ wx.CallAfter(self.ParentWindow.DeleteValue, self)
+
+ def OnForceButton(self):
+ """
+ Function called when Force button is pressed
+ """
+ self.ForceValue(self.ItemsDict.values()[0])
+
+ def OnReleaseButton(self):
+ """
+ Function called when Release button is pressed
+ """
+ self.ReleaseValue(self.ItemsDict.values()[0])
+
+ def OnMouseDragging(self, x, y):
+ """
+ Function called when mouse is dragged over Viewer
+ @param x: X coordinate of mouse pointer
+ @param y: Y coordinate of mouse pointer
+ """
+ xw, yw = self.GetPosition()
+ # Refresh highlight in Debug Variable Panel (highlight can be displayed
+ # in another Viewer
+ self.ParentWindow.RefreshHighlight(x + xw, y + yw)
+
+ def RefreshHighlight(self, x, y):
+ """
+ Function called by Debug Variable Panel asking Viewer to refresh
+ highlight according to mouse position
+ @param x: X coordinate of mouse pointer
+ @param y: Y coordinate of mouse pointer
+ """
+ # Get Viewer size
+ width, height = self.GetSize()
+
+ # Mouse is in the first half of Viewer
+ if y < height / 2:
+ # If Viewer is the upper one, draw drop before highlight
+ if self.ParentWindow.IsViewerFirst(self):
+ self.SetHighlight(HIGHLIGHT_BEFORE)
+
+ # Else draw drop after highlight in previous Viewer
+ else:
+ self.SetHighlight(HIGHLIGHT_NONE)
+ self.ParentWindow.HighlightPreviousViewer(self)
+
+ # Mouse is in the second half of Viewer, draw drop after highlight
+ else:
+ self.SetHighlight(HIGHLIGHT_AFTER)
+
+ def OnEraseBackground(self, event):
+ """
+ Function called when Viewer background is going to be erase
+ @param event: wx.EraseEvent
+ """
+ # Prevent flicker on Windows
+ pass
+
+ def OnResize(self, event):
+ """
+ Function called when Viewer size changed
+ @param event: wx.ResizeEvent
+ """
+ # Refresh button positions
+ self.RefreshButtonsPosition()
+ self.ParentWindow.ForceRefresh()
+ event.Skip()
+
+ def ForceValue(self, item):
+ """
+ Force value of item given
+ @param item: Item to force value
+ """
+ # Check variable data type
+ iec_path = item.GetVariable()
+ iec_type = self.ParentWindow.GetDataType(iec_path)
+ # Return immediately if not found
+ if iec_type is None:
+ return
+
+ # Open a dialog to enter varaible forced value
+ dialog = ForceVariableDialog(self, iec_type, str(item.GetValue()))
+ if dialog.ShowModal() == wx.ID_OK:
+ self.ParentWindow.ForceDataValue(iec_path.upper(),
+ dialog.GetValue())
+
+ def ReleaseValue(self, item):
+ """
+ Release value of item given
+ @param item: Item to release value
+ """
+ self.ParentWindow.ReleaseDataValue(
+ item.GetVariable().upper())
--- a/controls/DebugVariablePanel/GraphButton.py Thu May 30 13:23:21 2013 +0200
+++ b/controls/DebugVariablePanel/GraphButton.py Fri May 31 00:07:21 2013 +0200
@@ -106,7 +106,7 @@
@param enable: True if button is active in Graphic Viewer
(default True)
"""
- self.Enabled = True
+ self.Enabled = enable
def Disable(self):
"""
@@ -143,7 +143,7 @@
Call callback function if defined
"""
if self.Callback is not None:
- wx.CallAfter(self.Callback)
+ self.Callback()
def Draw(self, dc):
"""