def FindObject(self, item): tree = view.tree if not item or item == tree.root: return None if item == self.item: return self.object # Traverse tree until we reach the root or the test object items = [item] while 1: item = tree.GetItemParent(item) if item == tree.root: return None # item outside if the test subtree elif item == self.item: break else: items.append(item) # Now traverse back, searching children obj = self.object comp = Manager.getNodeComp(tree.GetPyData(self.item)) while items and obj: if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)): return None parentItem = item item = items.pop() index = tree.ItemIndex(item) obj = comp.getChildObject(tree.GetPyData(parentItem), obj, index) node = tree.GetPyData(item) comp = Manager.getNodeComp(node) return obj
def FindObjectRect(self, item): tree = view.tree if not item or item == tree.root: return None if item == self.item: # top-level comp = Manager.getNodeComp(tree.GetPyData(item)) rects = comp.getRect(self.object) if rects: # Make rects relative to the object offset = wx.Point(-rects[0].GetLeft(),-rects[0].GetTop()) [r.Offset(offset) for r in rects] return rects # Traverse tree until we reach the root or the test object items = [item] while 1: item = tree.GetItemParent(item) if item == self.item: break elif item == tree.root: return None # item outside of the test subtree else: items.append(item) # Now traverse back from parents to children obj = self.object offset = wx.Point(0,0) rects = None comp = Manager.getNodeComp(tree.GetPyData(self.item)) while items and obj: if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)): return None parentItem = item if rects: parentRect = rects[0] parent = obj item = items.pop() index = tree.ItemIndexWin(item) obj = comp.getChildObject(tree.GetPyData(parentItem), parent, index) if isinstance(parent, wx.Notebook) and index != parent.GetSelection(): parent.SetSelection(index) node = tree.GetPyData(item) comp = Manager.getNodeComp(node) rects = comp.getRect(obj) if not rects: return None r = rects[0] if isinstance(parent, wx.Sizer) and parentRect: sizerItem = parent.GetChildren()[index] flag = sizerItem.GetFlag() border = sizerItem.GetBorder() if border != 0: x = (r.GetLeft() + r.GetRight()) / 2 if flag & wx.TOP: rects.append(wx.Rect(x, r.GetTop() - border, 0, border)) if flag & wx.BOTTOM: rects.append(wx.Rect(x, r.GetBottom() + 1, 0, border)) y = (r.GetTop() + r.GetBottom()) / 2 if flag & wx.LEFT: rects.append(wx.Rect(r.GetLeft() - border, y, border, 0)) if flag & wx.RIGHT: rects.append(wx.Rect(r.GetRight() + 1, y, border, 0)) if isinstance(obj, wx.Notebook) and items: offset += obj.GetClientRect().GetTopLeft() elif isinstance(obj, wx.Window) and items: offset += r.GetTopLeft() [r.Offset(offset) for r in rects] return rects
def OnData(self, x, y, d): view.testWin.RemoveHighlightDT() self.onHL = self.left = False self.GetData() id = int(self.do.GetDataHere()) d, other = self.WhereToDrop(x, y, d) if d != wx.DragNone and other: obj, item = other g.Presenter.setData(item) comp = Manager.findById(id) mouseState = wx.GetMouseState() forceSibling = mouseState.ControlDown() forceInsert = mouseState.ShiftDown() g.Presenter.updateCreateState(forceSibling, forceInsert) if not g.Presenter.checkCompatibility(comp): return wx.DragNone item = g.Presenter.create(comp) node = view.tree.GetPyData(item) parentItem = view.tree.GetItemParent(item) parentNode = view.tree.GetPyData(parentItem) parentComp = Manager.getNodeComp(parentNode) # If pos if not set by default and parent is not a sizer, set pos to # drop coordinates if 'pos' in comp.attributes and not comp.getAttribute(node, 'pos') \ and parentComp.isContainer() and \ not parentComp.isSizer(): # Calc relative coords rect = view.testWin.FindObjectRect(parentItem) x -= rect[0].x y -= rect[0].y comp.addAttribute(node, 'pos', '%d,%d' % (x, y)) g.Presenter.setData(item) view.frame.SetStatusText('Object created') return d
def AddNode(self, parent, node): # Append tree item try: comp = Manager.getNodeComp(node, None) className = comp.klass except: className = node.getAttribute('class') # Try to create some generic component on-the-fly attributes = [] isContainer = False for n in node.childNodes: if is_object(n): isContainer = True elif n.nodeType == node.ELEMENT_NODE and not n.tagName in attributes: attributes.append(n.tagName) if isContainer: comp = Container(className, 'unknown', attributes) else: comp = Component(className, 'unknown', attributes) Manager.register(comp) wx.LogWarning( 'Unknown component class "%s", registered as generic' % className) item = self.AppendItem(parent, comp.getTreeText(node), image=comp.getTreeImageId(node), data=wx.TreeItemData(node)) self.SetItemStyle(item, node) # Try to find children objects if comp.isContainer(): for n in filter(is_object, node.childNodes): self.AddNode(item, comp.getTreeNode(n))
def OnData(self, x, y, d): view.testWin.RemoveHighlightDT() self.onHL = self.left = False self.GetData() id = int(self.do.GetDataHere()) d,other = self.WhereToDrop(x, y, d) if d != wx.DragNone and other: obj,item = other g.Presenter.setData(item) comp = Manager.findById(id) mouseState = wx.GetMouseState() forceSibling = mouseState.ControlDown() forceInsert = mouseState.ShiftDown() g.Presenter.updateCreateState(forceSibling, forceInsert) if not g.Presenter.checkCompatibility(comp): return wx.DragNone item = g.Presenter.create(comp) node = view.tree.GetPyData(item) parentItem = view.tree.GetItemParent(item) parentNode = view.tree.GetPyData(parentItem) parentComp = Manager.getNodeComp(parentNode) # If pos if not set by default and parent is not a sizer, set pos to # drop coordinates if 'pos' in comp.attributes and not comp.getAttribute(node, 'pos') \ and parentComp.isContainer() and \ not parentComp.isSizer(): # Calc relative coords rect = view.testWin.FindObjectRect(parentItem) x -= rect[0].x y -= rect[0].y comp.addAttribute(node, 'pos', '%d,%d' % (x, y)) g.Presenter.setData(item) view.frame.SetStatusText('Object created') return d
def AddNode(self, parent, node): # Append tree item try: comp = Manager.getNodeComp(node, None) className = comp.klass except: className = node.getAttribute('class') # Try to create some generic component on-the-fly attributes = [] isContainer = False for n in node.childNodes: if is_object(n): isContainer = True elif n.nodeType == node.ELEMENT_NODE and not n.tagName in attributes: attributes.append(n.tagName) if isContainer: comp = Container(className, 'unknown', attributes) else: comp = Component(className, 'unknown', attributes) Manager.register(comp) wx.LogWarning('Unknown component class "%s", registered as generic' % className) item = self.AppendItem(parent, comp.getTreeText(node), image=comp.getTreeImageId(node), data=wx.TreeItemData(node)) self.SetItemStyle(item, node) # Try to find children objects if comp.isContainer(): for n in filter(is_object, node.childNodes): self.AddNode(item, comp.getTreeNode(n))
def paste(self): success = success_node = False if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): try: data = wx.CustomDataObject("XRCED_elem") if wx.TheClipboard.IsSupported(data.GetFormat()): try: success = wx.TheClipboard.GetData(data) except: # there is a problem if XRCED_node is in clipboard # but previous SetData was for XRCED pass if not success: # try other format data = wx.CustomDataObject("XRCED_node") if wx.TheClipboard.IsSupported(data.GetFormat()): success_node = wx.TheClipboard.GetData(data) finally: wx.TheClipboard.Close() if not success and not success_node: wx.MessageBox("There is no data in the clipboard in the required format", "Error") return # XML representation of element or node value string data = cPickle.loads(data.GetData()) implicit = None if success: if type(data) is list: node = Model.parseString(data[0]) implicit = Model.parseString(data[1]) else: node = Model.parseString(data) else: node = Model.dom.createComment(data) comp = Manager.getNodeComp(node) # Check compatibility if not self.checkCompatibility(comp): node.unlink() return item = view.tree.GetSelection() if item and not self.applied: self.update(item) item = self.create(comp, node) if implicit: # copy parameters for implicit node if possible parentNode = view.tree.GetPyData(view.tree.GetItemParent(item)) parentComp = Manager.getNodeComp(parentNode) if parentComp.requireImplicit(node) and parentComp.implicitKlass == implicit.getAttribute("class"): parentComp.copyImplicitAttributes(implicit, node.parentNode, parentComp) implicit.unlink() # Add children for n in filter(is_object, node.childNodes): view.tree.AddNode(item, comp.getTreeNode(n)) self.setModified() return item
def FindObjectRect(self, item): tree = view.tree if not item or item == tree.root: return None # Traverse tree until we reach the root or the test object items = [item] while 1: item = tree.GetItemParent(item) if item == tree.root: return None # item outside if the test subtree elif item == self.item: break else: items.append(item) # Now traverse back from parents to children obj = self.object offset = wx.Point(0, 0) rects = None comp = Manager.getNodeComp(tree.GetPyData(self.item)) while items and obj: if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)): return None parentItem = item if rects: parentRect = rects[0] parent = obj item = items.pop() index = tree.ItemIndex(item) obj = comp.getChildObject(tree.GetPyData(parentItem), parent, index) node = tree.GetPyData(item) comp = Manager.getNodeComp(node) rects = comp.getRect(obj) if not rects: return None r = rects[0] if isinstance(parent, wx.Sizer) and parentRect: #rect.append(parentRect) sizerItem = parent.GetChildren()[index] flag = sizerItem.GetFlag() border = sizerItem.GetBorder() if border != 0: x = (r.GetLeft() + r.GetRight()) / 2 if flag & wx.TOP: rects.append(wx.Rect(x, r.GetTop() - border, 0, border)) if flag & wx.BOTTOM: rects.append(wx.Rect(x, r.GetBottom() + 1, 0, border)) y = (r.GetTop() + r.GetBottom()) / 2 if flag & wx.LEFT: rects.append( wx.Rect(r.GetLeft() - border, y, border, 0)) if flag & wx.RIGHT: rects.append(wx.Rect(r.GetRight() + 1, y, border, 0)) if isinstance(obj, wx.Window) and items: offset += r.GetTopLeft() if isinstance(obj, wx.Notebook) and items: offset += obj.GetClientRect().GetTopLeft() [r.Offset(offset) for r in rects] return rects
def createTestWin(self, item): TRACE('createTestWin') # Create a window with this resource node = view.tree.GetPyData(item) # Close old window, remember where it was comp = Manager.getNodeComp(node) # Create memory XML file elem = node.cloneNode(True) if not node.hasAttribute('name'): name = 'noname' else: name = node.getAttribute('name') elem.setAttribute('name', STD_NAME) Model.setTestElem(elem) Model.saveTestMemoryFile() xmlFlags = 0 if not g.conf.useSubclassing: xmlFlags |= xrc.XRC_NO_SUBCLASSING # Use translations if encoding is not specified if not Model.dom.encoding: xmlFlags |= xrc.XRC_USE_LOCALE res = xrc.EmptyXmlResource(xmlFlags) xrc.XmlResource.Set(res) # set as global # Init other handlers Manager.addXmlHandlers(res) Manager.preload(res) # Same module list res.Load('memory:test.xrc') object = None testWin = view.testWin try: try: frame, object = comp.makeTestWin(res, name) if not object: # skip the rest raise EOFError # Reset previous tree item and locate tool if testWin.item: view.tree.SetItemBold(testWin.item, False) testWin.SetView(frame, object, item) testWin.Show() view.tree.SetItemBold(item, True) except EOFError: pass except NotImplementedError: wx.LogError('Test window not implemented for %s' % node.getAttribute('class')) logger.exception('error creating test view') except: logger.exception('error creating test view') wx.LogError('Error creating test view') if get_debug(): raise finally: # Cleanup res.Unload(TEST_FILE) xrc.XmlResource.Set(None) wx.MemoryFSHandler.RemoveFile(TEST_FILE)
def createRef(self, ref, child=None): '''Create object_ref element node.''' if child is None: child = Model.createRefNode(ref) refNode = Model.findResource(ref) if refNode: comp = Manager.getNodeComp(refNode) else: comp = Manager.getNodeComp(child) self.create(comp, child)
def AddNode(self, parent, node): # Append tree item try: comp = Manager.getNodeComp(node, None) className = comp.klass except: className = node.getAttribute('class') # Try to create some generic component on-the-fly attributes = [] isContainer = False for n in node.childNodes: if is_object(n): isContainer = True elif n.nodeType == node.ELEMENT_NODE and not n.tagName in attributes: attributes.append(n.tagName) if isContainer: comp = Container(className, 'unknown', attributes) else: comp = Component(className, 'unknown', attributes) Manager.register(comp) wx.LogWarning( 'Unknown component class "%s", registered as generic' % className) item = self.AppendItem(parent, comp.getTreeText(node), image=comp.getTreeImageId(node), data=wx.TreeItemData(node)) self.SetItemStyle(item, node) # Try to find children objects if comp.isContainer(): for n in filter(is_object, node.childNodes): self.AddNode(item, comp.getTreeNode(n)) elif node.nodeType == node.COMMENT_NODE: if node.data and node.data[0] == '%' and g.conf.allowExec != 'no': if g.conf.allowExec == 'ask' and Model.allowExec is None: say = wx.MessageBox( '''This file contains executable comment directives. \ Allow to execute?''', 'Warning', wx.ICON_EXCLAMATION | wx.YES_NO) if say == wx.YES: Model.allowExec = True else: Model.allowExec = False if g.conf.allowExec == 'yes' or Model.allowExec: code = node.data[1:] # skip '%' try: exec code in globals(), self.locals except: wx.LogError('exec error: "%s"' % code) logger.exception("execution of in-line comment failed")
def moveLeft(self): parentItem = view.tree.GetItemParent(self.item) grandParentItem = view.tree.GetItemParent(parentItem) parent = view.tree.GetPyData(parentItem) grandParent = view.tree.GetPyData(grandParentItem) if grandParent is Model.mainNode: grandParentComp = Manager.rootComponent else: grandParentComp = Manager.getNodeComp(grandParent) if not grandParentComp.canHaveChild(self.comp): wx.LogError('Incompatible parent/child: parent is %s, child is %s!' % (grandParentComp.klass, self.comp.klass)) return node = view.tree.GetPyData(self.item) nextItem = view.tree.GetNextSibling(parentItem) self.container.removeChild(parent, node) if nextItem: nextNode = view.tree.GetPyData(nextItem) grandParentComp.insertBefore(grandParent, node, nextNode) else: grandParentComp.appendChild(grandParent, node) index = view.tree.ItemFullIndex(self.item) self.flushSubtree(grandParentItem, grandParent) index.pop() index[-1] += 1 self.item = view.tree.ItemAtFullIndex(index) self.setModified() view.tree.SelectItem(self.item)
def setData(self, item): '''Set data and view for current tree item.''' self.item = item if item == view.tree.root: TRACE('setData: root node') self.container = None self.comp = Manager.rootComponent self.panels = view.panel.SetData(self.container, self.comp, Model.mainNode) else: node = view.tree.GetPyData(item) if node.nodeType != node.COMMENT_NODE: TRACE('setData: %s', node.getAttribute('class')) self.comp = Manager.getNodeComp(node) parentItem = view.tree.GetItemParent(item) parentNode = view.tree.GetPyData(parentItem) if parentNode == Model.mainNode: self.container = Manager.rootComponent else: parentClass = parentNode.getAttribute('class') self.container = Manager.components[parentClass] self.panels = view.panel.SetData(self.container, self.comp, node) # Create new pending undo self.createUndoEdit(self.item) if view.testWin.IsShown(): self.highlight(item)
def __init__(self, parent): if wx.Platform == '__WXGTK__': wx.PyPanel.__init__(self, parent, -1, style=wx.RAISED_BORDER | wx.WANTS_CHARS) else: wx.PyPanel.__init__(self, parent, -1, style=wx.WANTS_CHARS) self.bg = wx.Colour(115, 180, 215) # Top sizer sizer = wx.BoxSizer(wx.VERTICAL) # Use toolbook or foldpanelbar depending of preferences if g.conf.toolPanelType == 'TB': self.tp = wx.Toolbook(self, -1, style=wx.BK_TOP) sizer.Add(self.tp, 1, wx.EXPAND) # Image list thumbSize = g.conf.toolThumbSize il = wx.ImageList(thumbSize, thumbSize, True) # Default Id 0 il.Add(images.ToolPanel_Default.GetImage().Scale( thumbSize, thumbSize).ConvertToBitmap()) self.il = il self.tp.AssignImageList(il) elif g.conf.toolPanelType == 'FPB': self.tp = fpb.FoldPanelBar(self, -1, wx.DefaultPosition, wx.DefaultSize, agwStyle=fpb.FPB_VERTICAL) sizer.Add(self.tp, 1, wx.EXPAND) self.panels = [] for name in Manager.panelNames: panelData = Manager.getPanelData(name) if not panelData: continue try: im = Manager.panelImages[name] imageId = il.Add( im.Scale(thumbSize, thumbSize).ConvertToBitmap()) except: imageId = 0 panel = self.AddPanel(name) self.panels.append(panel) for pos, span, comp, bmp in panelData: self.AddButton(panel, pos, span, comp.id, bmp, comp.klass) panel.Fit() if g.conf.toolPanelType == 'TB': self.tp.AddPage(panel, '', imageId=imageId) else: p = self.tp.AddFoldPanel(name, collapsed=False) p.SetBackgroundColour(self.bg) panel.Reparent(p) p.AddWindow(panel, fpb.FPB_ALIGN_WIDTH) self.tp.Fit() self.SetSizer(sizer) # Allow to be resized in horizontal direction only # Events # wx.EVT_KEY_DOWN(self, self.OnKeyDown) # wx.EVT_KEY_UP(self, self.OnKeyUp) self.drag = None
def setData(self, item): """Set data and view for current tree item.""" self.item = item if item == view.tree.root: TRACE("setData: root node") self.container = None self.comp = Manager.rootComponent # self.panels = [] # view.panel.Clear() self.panels = view.panel.SetData(self.container, self.comp, Model.mainNode) else: node = view.tree.GetPyData(item) TRACE("setData: %s", node.getAttribute("class")) self.comp = Manager.getNodeComp(node) parentItem = view.tree.GetItemParent(item) parentNode = view.tree.GetPyData(parentItem) if parentNode == Model.mainNode: self.container = Manager.rootComponent else: parentClass = parentNode.getAttribute("class") self.container = Manager.components[parentClass] self.panels = view.panel.SetData(self.container, self.comp, node) # Create new pending undo self.createUndoEdit(self.item) if view.testWin.IsShown(): self.highlight(item)
def undo(self): Presenter.unselect() # Updating DOM. Find parent node first parentItem = view.tree.ItemAtFullIndex(self.itemIndex[:-1]) parentNode = view.tree.GetPyData(parentItem) parentComp = Manager.getNodeComp(parentNode) nextItem = view.tree.ItemAtFullIndex(self.itemIndex) if nextItem: nextNode = parentComp.getTreeOrImplicitNode(view.tree.GetPyData(nextItem)) else: nextNode = None # Insert before next parentNode.insertBefore(self.node, nextNode) # Remember test window item if view.testWin.item is not None: testItemIndex = view.tree.ItemFullIndex(view.testWin.item) # Update tree and presenter view.tree.FlushSubtree(parentItem, parentNode) view.tree.SetFullState(self.state) # Restore test window item if view.testWin.item is not None: view.testWin.item = view.tree.ItemAtFullIndex(testItemIndex) item = view.tree.ItemAtFullIndex(self.itemIndex) view.tree.EnsureVisible(item) # This will generate events view.tree.SelectItem(item)
def undo(self): Presenter.unselect() # Updating DOM. Find parent node first parentItem = view.tree.ItemAtFullIndex(self.itemIndex[:-1]) parentNode = view.tree.GetPyData(parentItem) parentComp = Manager.getNodeComp(parentNode) nextItem = view.tree.ItemAtFullIndex(self.itemIndex) if nextItem: nextNode = parentComp.getTreeOrImplicitNode( view.tree.GetPyData(nextItem)) else: nextNode = None # Insert before next parentNode.insertBefore(self.node, nextNode) # Remember test window item if view.testWin.item is not None: testItemIndex = view.tree.ItemFullIndex(view.testWin.item) # Update tree and presenter view.tree.FlushSubtree(parentItem, parentNode) view.tree.SetFullState(self.state) # Restore test window item if view.testWin.item is not None: view.testWin.item = view.tree.ItemAtFullIndex(testItemIndex) item = view.tree.ItemAtFullIndex(self.itemIndex) view.tree.EnsureVisible(item) # This will generate events view.tree.SelectItem(item)
def moveLeft(self): parentItem = view.tree.GetItemParent(self.item) grandParentItem = view.tree.GetItemParent(parentItem) parent = view.tree.GetPyData(parentItem) grandParent = view.tree.GetPyData(grandParentItem) if grandParent is Model.mainNode: grandParentComp = Manager.rootComponent else: grandParentComp = Manager.getNodeComp(grandParent) if not grandParentComp.canHaveChild(self.comp): wx.LogError( 'Incompatible parent/child: parent is %s, child is %s!' % (grandParentComp.klass, self.comp.klass)) return node = view.tree.GetPyData(self.item) nextItem = view.tree.GetNextSibling(parentItem) self.container.removeChild(parent, node) if nextItem: nextNode = view.tree.GetPyData(nextItem) grandParentComp.insertBefore(grandParent, node, nextNode) else: grandParentComp.appendChild(grandParent, node) index = view.tree.ItemFullIndex(self.item) self.flushSubtree(grandParentItem, grandParent) index.pop() index[-1] += 1 self.item = view.tree.ItemAtFullIndex(index) self.setModified() view.tree.SelectItem(self.item)
def OnComponentReplace(self, evt): '''Hadnler for creating new elements.''' comp = Manager.findById(evt.GetId() - ID.SHIFT) item = self.tree.GetSelection() index = self.tree.ItemFullIndex(item) oldComp = Presenter.comp oldNode = Presenter.replace(comp) g.undoMan.RegisterUndo(undo.UndoReplace(index, oldComp, oldNode))
def AddNode(self, parent, node): # Append tree item try: comp = Manager.getNodeComp(node, None) className = comp.klass except: className = node.getAttribute("class") # Try to create some generic component on-the-fly attributes = [] isContainer = False for n in node.childNodes: if is_element(n): isContainer = True elif n.nodeType == node.ELEMENT_NODE and not n.tagName in attributes: attributes.append(n.tagName) if isContainer: comp = Container(className, "unknown", attributes) else: comp = Component(className, "unknown", attributes) Manager.register(comp) wx.LogWarning('Unknown component class "%s", registered as generic' % className) item = self.AppendItem( parent, comp.getTreeText(node), image=comp.getTreeImageId(node), data=wx.TreeItemData(node) ) self.SetItemStyle(item, node) # Try to find children objects if comp.isContainer(): for n in filter(is_object, node.childNodes): self.AddNode(item, comp.getTreeNode(n)) elif node.nodeType == node.COMMENT_NODE: if node.data and node.data[0] == "%" and g.conf.allowExec != "no": if g.conf.allowExec == "ask" and Model.allowExec is None: say = wx.MessageBox( """This file contains executable comment directives. \ Allow to execute?""", "Warning", wx.ICON_EXCLAMATION | wx.YES_NO, ) if say == wx.YES: Model.allowExec = True else: Model.allowExec = False if g.conf.allowExec == "yes" or Model.allowExec: code = node.data[1:] # skip '%' self.ExecCode(code)
def OnComponentCreate(self, evt): '''Hadnler for creating new elements.''' comp = Manager.findById(evt.GetId()) g.undoMan.RegisterUndo(undo.UndoGlobal()) # !!! TODO if comp.groups[0] == 'component': node = Model.createComponentNode('Component') Presenter.create(comp, node) else: Presenter.create(comp)
def createRef(self, ref, child=None): """Create object_ref element node.""" if child is None: child = Model.createRefNode(ref) refNode = Model.findResource(ref) if not refNode: return None comp = Manager.getNodeComp(refNode) self.create(comp, child)
def OnComponentCreate(self, evt): '''Hadnler for creating new elements.''' state = self.tree.GetFullState() # state just before comp = Manager.findById(evt.GetId()) if comp.groups[0] == 'component': node = Model.createComponentNode('Component') item = Presenter.create(comp, node) else: item = Presenter.create(comp) itemIndex = self.tree.ItemFullIndex(item) g.undoMan.RegisterUndo(undo.UndoPasteCreate(itemIndex, state))
def __init__(self, parent): if wx.Platform == "__WXGTK__": wx.Panel.__init__(self, parent, -1, style=wx.RAISED_BORDER | wx.WANTS_CHARS) else: wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS) self.bg = wx.Colour(115, 180, 215) # Top sizer sizer = wx.BoxSizer(wx.VERTICAL) # Use toolbook or foldpanelbar depending of preferences if g.conf.toolPanelType == "TB": self.tp = wx.Toolbook(self, -1, style=wx.BK_TOP) sizer.Add(self.tp, 1, wx.EXPAND) # Image list thumbSize = g.conf.toolThumbSize il = wx.ImageList(thumbSize, thumbSize, True) # Default Id 0 il.Add(images.getToolPanel_DefaultImage().Scale(thumbSize, thumbSize).ConvertToBitmap()) self.il = il self.tp.AssignImageList(il) elif g.conf.toolPanelType == "FPB": self.tp = fpb.FoldPanelBar( self, -1, wx.DefaultPosition, wx.DefaultSize, fpb.FPB_DEFAULT_STYLE | fpb.FPB_VERTICAL ) sizer.Add(self.tp, 1, wx.EXPAND) self.panels = [] for name in Manager.panelNames: panelData = Manager.getPanelData(name) if not panelData: continue try: im = Manager.panelImages[name] imageId = il.Add(im.Scale(thumbSize, thumbSize).ConvertToBitmap()) except: imageId = 0 panel = self.AddPanel(name) self.panels.append(panel) for pos, span, comp, bmp in panelData: self.AddButton(panel, pos, span, comp.id, bmp, comp.klass) panel.Fit() if g.conf.toolPanelType == "TB": self.tp.AddPage(panel, "", imageId=imageId) else: p = self.tp.AddFoldPanel(name, collapsed=False) p.SetBackgroundColour(self.bg) panel.Reparent(p) p.AddWindow(panel, fpb.FPB_ALIGN_WIDTH) self.tp.Fit() self.SetSizerAndFit(sizer) # Allow to be resized in horizontal direction only # Events # wx.EVT_KEY_DOWN(self, self.OnKeyDown) # wx.EVT_KEY_UP(self, self.OnKeyUp) self.drag = None
def paste(self): success = success_node = False if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): try: data = wx.CustomDataObject('XRCED_elem') if wx.TheClipboard.IsSupported(data.GetFormat()): try: success = wx.TheClipboard.GetData(data) except: # there is a problem if XRCED_node is in clipboard # but previous SetData was for XRCED pass if not success: # try other format data = wx.CustomDataObject('XRCED_node') if wx.TheClipboard.IsSupported(data.GetFormat()): success_node = wx.TheClipboard.GetData(data) finally: wx.TheClipboard.Close() if not success and not success_node: wx.MessageBox( "There is no data in the clipboard in the required format", "Error") return # XML representation of element or node value string data = cPickle.loads(data.GetData()) if success: node = Model.parseString(data) comp = Manager.getNodeComp(node) else: node = Model.dom.createComment(data) raise NotImplementedError # Check compatibility if not self.checkCompatibility(comp): node.unlink() return item = view.tree.GetSelection() if item and not self.applied: self.update(item) item = self.create(comp, node) # Add children for n in filter(is_object, node.childNodes): view.tree.AddNode(item, comp.getTreeNode(n)) self.setModified() return item
def undo(self): # Updating DOM. Find parent node first parentItem = view.tree.ItemAtFullIndex(self.itemIndex[:-1]) parentNode = view.tree.GetPyData(parentItem) parentComp = Manager.getNodeComp(parentNode) nextItem = view.tree.ItemAtFullIndex(self.itemIndex) if nextItem: nextNode = parentComp.getTreeOrImplicitNode(view.tree.GetPyData(nextItem)) else: nextNode = None # Insert before next parentNode.insertBefore(self.node, nextNode) # Update tree and presenter view.tree.Flush() view.tree.SetFullState(self.states) item = view.tree.ItemAtFullIndex(self.itemIndex) view.tree.EnsureVisible(item) # This will generate events view.tree.SelectItem(item)
def moveRight(self): parentItem = view.tree.GetItemParent(self.item) parent = view.tree.GetPyData(parentItem) newParent = view.tree.GetPyData(view.tree.GetPrevSibling(self.item)) newParentComp = Manager.getNodeComp(newParent) if not newParentComp.canHaveChild(self.comp): wx.LogError('Incompatible parent/child: parent is %s, child is %s!' % (newParentComp.klass, self.comp.klass)) return node = view.tree.GetPyData(self.item) self.container.removeChild(parent, node) newParentComp.appendChild(newParent, node) index = view.tree.ItemFullIndex(self.item) n = view.tree.GetChildrenCount(view.tree.GetPrevSibling(self.item)) self.flushSubtree(parentItem, parent) index[-1] -= 1 index.append(n) self.item = view.tree.ItemAtFullIndex(index) self.setModified() view.tree.SelectItem(self.item)
def moveRight(self): parentItem = view.tree.GetItemParent(self.item) parent = view.tree.GetPyData(parentItem) newParent = view.tree.GetPyData(view.tree.GetPrevSibling(self.item)) newParentComp = Manager.getNodeComp(newParent) if not newParentComp.canHaveChild(self.comp): wx.LogError( 'Incompatible parent/child: parent is %s, child is %s!' % (newParentComp.klass, self.comp.klass)) return node = view.tree.GetPyData(self.item) self.container.removeChild(parent, node) newParentComp.appendChild(newParent, node) index = view.tree.ItemFullIndex(self.item) n = view.tree.GetChildrenCount(view.tree.GetPrevSibling(self.item)) self.flushSubtree(parentItem, parent) index[-1] -= 1 index.append(n) self.item = view.tree.ItemAtFullIndex(index) self.setModified() view.tree.SelectItem(self.item)
def createTestWin(self, item): TRACE('createTestWin') # Create a window with this resource node = view.tree.GetPyData(item) # Execute "pragma" comment node if node.nodeType == node.COMMENT_NODE: if node.data and node.data[0] == '%' and g.conf.allowExec != 'no': say = wx.NO if g.conf.allowExec == 'ask' and Model.allowExec is None: say = wx.MessageBox('Execute comment directive?', 'Warning', wx.ICON_EXCLAMATION | wx.YES_NO) if g.conf.allowExec == 'yes' or say == wx.YES: code = node.data[1:] # skip '%' view.tree.ExecCode(code) return # Close old window, remember where it was comp = Manager.getNodeComp(node) # Create memory XML file elem = node.cloneNode(True) if not node.hasAttribute('name'): name = 'noname' else: name = node.getAttribute('name') elem.setAttribute('name', STD_NAME) Model.setTestElem(elem) Model.saveTestMemoryFile() xmlFlags = 0 if not g.conf.useSubclassing: xmlFlags |= xrc.XRC_NO_SUBCLASSING # Use translations if encoding is not specified if not Model.dom.encoding: xmlFlags |= xrc.XRC_USE_LOCALE res = xrc.EmptyXmlResource(xmlFlags) xrc.XmlResource.Set(res) # set as global # Init other handlers Manager.addXmlHandlers(res) Manager.preload(res) # Same module list res.Load('memory:test.xrc') object = None testWin = view.testWin try: try: frame, object = comp.makeTestWin(res, name) if not object: # skip the rest raise EOFError # Reset previous tree item and locate tool if testWin.item: view.tree.SetItemBold(testWin.item, False) testWin.SetView(frame, object, item) testWin.Show() view.tree.SetItemBold(item, True) except EOFError: pass except NotImplementedError: wx.LogError('Test window not implemented for %s' % node.getAttribute('class')) logger.exception('error creating test view') except: logger.exception('error creating test view') wx.LogError('Error creating test view') if get_debug(): raise finally: # Cleanup res.Unload(TEST_FILE) xrc.XmlResource.Set(None) wx.MemoryFSHandler.RemoveFile(TEST_FILE)
def createTestWin(self, item): TRACE('createTestWin') # Create a window with this resource node = view.tree.GetPyData(item) # Execute "pragma" comment node if node.nodeType == node.COMMENT_NODE: if node.data and node.data[0] == '%' and g.conf.allowExec != 'no': say = wx.NO if g.conf.allowExec == 'ask' and Model.allowExec is None: say = wx.MessageBox('Execute comment directive?', 'Warning', wx.ICON_EXCLAMATION | wx.YES_NO) if g.conf.allowExec == 'yes' or say == wx.YES: code = node.data[1:] # skip '%' view.tree.ExecCode(code) return # Close old window, remember where it was comp = Manager.getNodeComp(node) # Use parent object if the current one does not support test view testWinItem = item while not comp.isTestable: testWinItem = view.tree.GetItemParent(testWinItem) node = view.tree.GetPyData(testWinItem) comp = Manager.getNodeComp(node) # Create memory XML file elem = node.cloneNode(True) if not node.hasAttribute('name'): name = 'noname' else: name = node.getAttribute('name') elem.setAttribute('name', STD_NAME) Model.setTestElem(elem) Model.saveTestMemoryFile() xmlFlags = 0 if not g.conf.useSubclassing: xmlFlags |= xrc.XRC_NO_SUBCLASSING # Use translations if encoding is not specified if not Model.dom.encoding: xmlFlags |= xrc.XRC_USE_LOCALE res = xrc.EmptyXmlResource(xmlFlags) xrc.XmlResource.Set(res) # set as global # Init other handlers Manager.addXmlHandlers(res) Manager.preload(res) # Same module list res.Load('memory:test.xrc') testWin = view.testWin try: try: frame, object = comp.makeTestWin(res, name) if not object: # skip the rest raise EOFError # Reset previous tree item and locate tool if testWin.item: view.tree.SetItemBold(testWin.item, False) testWin.SetView(frame, object, testWinItem) testWin.Show() view.tree.SetItemBold(testWinItem, True) # For reused frame, object is not positioned immediately wx.CallAfter(self.highlight, item) except EOFError: pass except TestWinError: wx.LogError('Test window could not be created for %s' % node.getAttribute('class')) logger.exception('error creating test view') except: wx.LogError('Error creating test view') logger.exception('error creating test view') if get_debug(): raise finally: # Cleanup res.Unload(TEST_FILE) xrc.XmlResource.Set(None) wx.MemoryFSHandler.RemoveFile(TEST_FILE)
def OnComponentReplace(self, evt): '''Hadnler for creating new elements.''' comp = Manager.findById(evt.GetId() - ID.SHIFT) g.undoMan.RegisterUndo(undo.UndoGlobal()) # !!! TODO Presenter.replace(comp)
def paste(self): success = success_node = False if wx.TheClipboard.IsOpened() or wx.TheClipboard.Open(): try: data = wx.CustomDataObject('XRCED_elem') if wx.TheClipboard.IsSupported(data.GetFormat()): try: success = wx.TheClipboard.GetData(data) except: # there is a problem if XRCED_node is in clipboard # but previous SetData was for XRCED pass if not success: # try other format data = wx.CustomDataObject('XRCED_node') if wx.TheClipboard.IsSupported(data.GetFormat()): success_node = wx.TheClipboard.GetData(data) finally: wx.TheClipboard.Close() if not success and not success_node: wx.MessageBox( "There is no data in the clipboard in the required format", "Error") return # XML representation of element or node value string data = cPickle.loads(data.GetData()) implicit = None if success: if type(data) is list: node = Model.parseString(data[0]) implicit = Model.parseString(data[1]) else: node = Model.parseString(data) else: node = Model.dom.createComment(data) comp = Manager.getNodeComp(node) # Check compatibility if not self.checkCompatibility(comp): node.unlink() return item = view.tree.GetSelection() if item and not self.applied: self.update(item) item = self.create(comp, node) if implicit: # copy parameters for implicit node if possible parentNode = view.tree.GetPyData(view.tree.GetItemParent(item)) parentComp = Manager.getNodeComp(parentNode) if parentComp.requireImplicit(node) and \ parentComp.implicitKlass == implicit.getAttribute('class'): parentComp.copyImplicitAttributes(implicit, node.parentNode, parentComp) implicit.unlink() # Add children for n in filter(is_object, node.childNodes): view.tree.AddNode(item, comp.getTreeNode(n)) self.setModified() return item
def createComment(self): '''Create comment node.''' node = Model.createCommentNode() comp = Manager.getNodeComp(node) self.create(comp, node)
def FindObjectRect(self, item): tree = view.tree if not item or item == tree.root: return None if item == self.item: # top-level comp = Manager.getNodeComp(tree.GetPyData(item)) rects = comp.getRect(self.object) if not self.frame and rects: # Make rects relative to the object (for top-level windows) offset = wx.Point(-rects[0].GetLeft(),-rects[0].GetTop()) [r.Offset(offset) for r in rects] return rects # Traverse tree until we reach the root or the test object items = [item] while 1: item = tree.GetItemParent(item) if item == self.item: break elif item == tree.root: return None # item outside of the test subtree else: items.append(item) # Now traverse back from parents to children obj = self.object if self.frame: # Maybe GetClientAreaOrigin should not return (0,0) for panels with borders offset = obj.ClientToScreen((0,0)) - self.frame.panel.ClientToScreen((0,0)) else: offset = wx.Point(0,0) rects = None comp = Manager.getNodeComp(tree.GetPyData(self.item)) while items and obj: if not (isinstance(obj, wx.Window) or isinstance(obj, wx.Sizer)): return None parentItem = item if rects: parentRect = rects[0] parent = obj item = items.pop() index = tree.ItemIndexWin(item) obj = comp.getChildObject(tree.GetPyData(parentItem), parent, index) if isinstance(parent, wx.Notebook) and index != parent.GetSelection(): parent.SetSelection(index) node = tree.GetPyData(item) comp = Manager.getNodeComp(node) rects = comp.getRect(obj) if not rects: return None r = rects[0] if isinstance(parent, wx.Sizer) and parentRect: sizerItem = parent.GetChildren()[index] flag = sizerItem.GetFlag() border = sizerItem.GetBorder() if border != 0: x = (r.GetLeft() + r.GetRight()) / 2 if flag & wx.TOP: rects.append(wx.Rect(x, r.GetTop() - border, 0, border)) if flag & wx.BOTTOM: rects.append(wx.Rect(x, r.GetBottom() + 1, 0, border)) y = (r.GetTop() + r.GetBottom()) / 2 if flag & wx.LEFT: rects.append(wx.Rect(r.GetLeft() - border, y, border, 0)) if flag & wx.RIGHT: rects.append(wx.Rect(r.GetRight() + 1, y, border, 0)) if isinstance(obj, wx.Notebook) and items: offset += obj.GetClientRect().GetTopLeft() elif isinstance(obj, wx.Window) and items: offset += r.GetTopLeft() [r.Offset(offset) for r in rects] return rects
def OnInit(self): # Check version if wx.VERSION[:3] < MinWxVersion: wx.LogWarning('''\ This version of XRCed may not work correctly on your version of wxWidgets. \ Please upgrade wxWidgets to %d.%d.%d or higher.''' % MinWxVersion) g.undoMan = undo.UndoManager() Manager.init() parser = OptionParser(prog=progname, version='%s version %s' % (ProgName, version), usage='%prog [options] [XRC file]') parser.add_option('-d', '--debug', action='store_true', help='add Debug command to Help menu') parser.add_option('-m', '--meta', action='store_true', dest = 'meta', help='activate meta-components') parser.add_option('-v', '--verbose', action='store_true', help='verbose messages') # Process command-line arguments options, args = parser.parse_args() if options.debug: set_debug(True) if options.verbose: set_verbose(True) if options.meta: g.useMeta = True import meta Manager.register(meta.Component) Manager.setMenu(meta.Component, 'TOP_LEVEL', 'component', 'component plugin') self.SetAppName(progname) self.ReadConfig() # Add handlers wx.FileSystem.AddHandler(wx.MemoryFSHandler()) self.toolArtProvider = view.ToolArtProvider() wx.ArtProvider.Push(self.toolArtProvider) # Load standard plugins first plugin.load_plugins(os.path.join(g.basePath, 'plugins')) # ... and then from user-defined dirs plugin.load_plugins_from_dirs() # Setup MVP view.create_view() Presenter.init() Listener.Install(view.frame, view.tree, view.panel, view.toolFrame, view.testWin) if args: path = args[0] # Change current directory dir = os.path.dirname(path) if dir: os.chdir(dir) path = os.path.basename(path) if os.path.isfile(path): Presenter.open(path) else: # Future name Presenter.path = path # Force update title Presenter.setModified(False) view.frame.Show() if not g.useAUI: if not g.conf.embedPanel: view.frame.miniFrame.Show() if g.conf.showToolPanel: Listener.toolFrame.Show() return True
def OnInit(self): if USE_INSPECTOR: self.Init() # Check version if wx.VERSION[:3] < MinWxVersion: wx.LogWarning('''\ This version of XRCed may not work correctly on your version of wxWidgets. \ Please upgrade wxWidgets to %d.%d.%d or higher.''' % MinWxVersion) g.undoMan = undo.UndoManager() Manager.init() parser = OptionParser(prog=progname, version='%s version %s' % (ProgName, version), usage='%prog [options] [XRC file]') parser.add_option('-d', '--debug', action='store_true', help='add Debug command to Help menu') parser.add_option('-m', '--meta', action='store_true', dest='meta', help='activate meta-components') parser.add_option('-v', '--verbose', action='store_true', help='verbose messages') # Process command-line arguments options, args = parser.parse_args() if options.debug: set_debug(True) if options.verbose: set_verbose(True) if options.meta: g.useMeta = True import meta Manager.register(meta.Component) Manager.setMenu(meta.Component, 'TOP_LEVEL', 'component', 'component plugin') self.SetAppName(progname) self.ReadConfig() # Add handlers wx.FileSystem.AddHandler(wx.MemoryFSHandler()) self.toolArtProvider = view.ToolArtProvider() wx.ArtProvider.Push(self.toolArtProvider) # Load standard plugins first plugin.load_plugins(os.path.join(g.basePath, 'plugins')) # ... and then from user-defined dirs plugin.load_plugins_from_dirs() # Setup MVP view.create_view() Presenter.init() Listener.Install(view.frame, view.tree, view.panel, view.toolFrame, view.testWin) if args: path = args[0] # Change current directory dir = os.path.dirname(path) if dir: os.chdir(dir) path = os.path.basename(path) if os.path.isfile(path): Presenter.open(path) else: # Future name Presenter.path = path # Force update title Presenter.setModified(False) view.frame.Show() if not g.useAUI: if not g.conf.embedPanel: view.frame.miniFrame.Show() if g.conf.showToolPanel: Listener.toolFrame.Show() return True
def createTestWin(self, item): TRACE("createTestWin") # Create a window with this resource node = view.tree.GetPyData(item) # Execute "pragma" comment node if node.nodeType == node.COMMENT_NODE: if node.data and node.data[0] == "%" and g.conf.allowExec != "no": say = wx.NO if g.conf.allowExec == "ask" and Model.allowExec is None: say = wx.MessageBox("Execute comment directive?", "Warning", wx.ICON_EXCLAMATION | wx.YES_NO) if g.conf.allowExec == "yes" or say == wx.YES: code = node.data[1:] # skip '%' view.tree.ExecCode(code) return # Close old window, remember where it was comp = Manager.getNodeComp(node) # Use parent object if the current one does not support test view testWinItem = item while not comp.isTestable: testWinItem = view.tree.GetItemParent(testWinItem) node = view.tree.GetPyData(testWinItem) comp = Manager.getNodeComp(node) # Create memory XML file elem = node.cloneNode(True) if not node.hasAttribute("name"): name = "noname" else: name = node.getAttribute("name") elem.setAttribute("name", STD_NAME) Model.setTestElem(elem) Model.saveTestMemoryFile() xmlFlags = 0 if not g.conf.useSubclassing: xmlFlags |= xrc.XRC_NO_SUBCLASSING # Use translations if encoding is not specified if not Model.dom.encoding: xmlFlags |= xrc.XRC_USE_LOCALE res = xrc.EmptyXmlResource(xmlFlags) xrc.XmlResource.Set(res) # set as global # Init other handlers Manager.addXmlHandlers(res) Manager.preload(res) # Same module list res.Load("memory:test.xrc") testWin = view.testWin try: try: frame, object = comp.makeTestWin(res, name) if not object: # skip the rest raise EOFError # Reset previous tree item and locate tool if testWin.item: view.tree.SetItemBold(testWin.item, False) testWin.SetView(frame, object, testWinItem) testWin.Show() view.tree.SetItemBold(testWinItem, True) # For reused frame, object is not positioned immediately wx.CallAfter(self.highlight, item) except EOFError: pass except TestWinError: wx.LogError("Test window could not be created for %s" % node.getAttribute("class")) logger.exception("error creating test view") except: wx.LogError("Error creating test view") logger.exception("error creating test view") if get_debug(): raise finally: # Cleanup res.Unload(TEST_FILE) xrc.XmlResource.Set(None) wx.MemoryFSHandler.RemoveFile(TEST_FILE)