view orpg/gametree/nodehandlers/rpg_grid.py @ 175:fd6415b8243e alpha

Traipse Alpha 'OpenRPG' {100112-01} Traipse is a distribution of OpenRPG that is designed to be easy to setup and go. Traipse also makes it easy for developers to work on code without fear of sacrifice. 'Ornery-Orc' continues the trend of 'Grumpy' and adds fixes to the code. 'Ornery-Orc's main goal is to offer more advanced features and enhance the productivity of the user. Update Summary (Keeping up with Beta) New Features: Added Bookmarks Added 'boot' command to remote admin Added confirmation window for sent nodes Minor changes to allow for portability to an OpenSUSE linux OS Miniatures Layer pop up box allows users to turn off Mini labels, from FlexiRPG Zoom Mouse plugin added Images added to Plugin UI Switching to Element Tree Map efficiency, from FlexiRPG Added Status Bar to Update Manager New TrueDebug Class in orpg_log (See documentation for usage) Portable Mercurial Tip of the Day added, from Core and community New Reference Syntax added for custom PC sheets New Child Reference for gametree New Parent Reference for gametree New Gametree Recursion method, mapping, context sensitivity, and effeciency.. New Features node with bonus nodes and Node Referencing help added Dieroller structure from Core Added 7th Sea die roller method; ie [7k3] = [7d10.takeHighest(3).open(10)] New 'Mythos' System die roller added Added new vs. die roller method for WoD; ie [3v3] = [3d10.vs(3)]. Includes support for Mythos roller New EZ_Tree Reference system. Push a button, Traipse the tree, get a reference (Alpha!!) Fixes: Fix to Text based Server Fix to Remote Admin Commands Fix to Pretty Print, from Core Fix to Splitter Nodes not being created Fix to massive amounts of images loading, from Core Fix to Map from gametree not showing to all clients Fix to gametree about menus Fix to Password Manager check on startup Fix to PC Sheets from tool nodes. They now use the tabber_panel Fixed Whiteboard ID to prevent random line or text deleting. Modified ID's to prevent non updated clients from ruining the fix. default_manifest.xml renamed to default_upmana.xml Fix to Update Manager; cleaner clode for saved repositories Fixes made to Settings Panel and no reactive settings when Ok is pressed Fixes to Alternity roller's attack roll. Uses a simple Tuple instead of a Splice Fix to Use panel of Forms and Tabbers. Now longer enters design mode
author sirebral
date Tue, 12 Jan 2010 19:51:39 -0600
parents ff6cbd2b7620
children 537a6bbac9bd
line wrap: on
line source

# Copyright (C) 2000-2001 The OpenRPG Project
#
#        openrpg-dev@lists.sourceforge.net
#
# This program 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 of the License, or
# (at your option) any later version.
#
# This program 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 program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# --
#
# File: rpg_grid.py
# Author: Chris Davis
# Maintainer:
# Version:
#   $Id: rpg_grid.py,v 1.20 2006/11/15 12:11:24 digitalxero Exp $
#
# Description: The file contains code for the grid nodehanlers
#

__version__ = "$Id: rpg_grid.py,v 1.20 2006/11/15 12:11:24 digitalxero Exp $"

from core import *
from forms import *

class rpg_grid_handler(node_handler):
    """ Node handler for rpg grid tool
<nodehandler module='rpg_grid' class='rpg_grid_handler' name='sample'>
  <grid border='' autosize='1' >
    <row>
      <cell size='?'></cell>
      <cell></cell>
    </row>
    <row>
      <cell></cell>
      <cell></cell>
    </row>
  </grid>
  <macros>
    <macro name=''/>
  </macros>
</nodehandler>
    """
    def __init__(self,xml,tree_node):
        node_handler.__init__(self,xml,tree_node)
        self.grid = self.xml.find('grid')
        if self.grid.get("border") == "": self.grid.set("border","1")
        if self.grid.get("autosize") == "": self.grid.set("autosize","1")
        self.macros = self.xml.find('macros')
        self.myeditor = None
        self.refresh_rows()

    def refresh_die_macros(self):
        pass

    def refresh_rows(self):
        self.rows = {}
        tree = self.tree
        icons = self.tree.icons
        tree.CollapseAndReset(self.mytree_node)
        for row in self.grid.findall('row'):
            first_cell = row.find('cell')
            name = first_cell.text
            if name == None or name == '': name = "Row"
            new_tree_node = tree.AppendItem(self.mytree_node,name,icons['gear'],icons['gear'])
            handler = grid_row_handler(row,new_tree_node,self)
            tree.SetPyData(new_tree_node,handler)

    def tohtml(self):
        border = self.grid.get("border")
        name = self.xml.get('name')
        rows = self.grid.findall('row')
        colspan = str(len(rows[0].findall('cell')))
        html_str = "<table border=\""+border+"\" align=center><tr bgcolor=\""+TH_BG+"\" ><th colspan="+colspan+">"+name+"</th></tr>"
        for r in rows:
            cells = r.findall('cell')
            html_str += "<tr>"
            for c in cells:
                html_str += "<td >"
                text = c.text
                if text == None or text == '': text = '<br />'
                html_str += text + "</td>"
            html_str += "</tr>"
        html_str += "</table>"
        return html_str

    def get_design_panel(self,parent):
        return rpg_grid_edit_panel(parent,self)

    def get_use_panel(self,parent):
        return rpg_grid_panel(parent,self)

    def get_size_constraint(self):
        return 1

    def is_autosized(self):
        return self.grid.get("autosize")

    def set_autosize(self,autosize=1):
        self.grid.set("autosize",str(autosize))

class grid_row_handler(node_handler):
    """ Node Handler grid row.
    """
    def __init__(self,xml,tree_node,parent):
        node_handler.__init__(self,xml,tree_node)
        self.drag = False

    def on_drop(self,evt):
        pass

    def can_clone(self):
        return 0;

    def tohtml(self):
        cells = self.xml.findall('cell')
        html_str = "<table border=1 align=center><tr >"
        for c in cells: # should loop over rows first, then cells
            html_str += "<td >"
            text = c.text
            if text == '' or text is None: text = '<br />'
            html_str += text + "</td>"
            html_str += "</tr>"
        html_str += "</table>"
        return html_str

    def get_value(self):
        cells = self.xml.findall('cell')
        if len(cells) == 2: return getText(cells[1])
        else: return None

    def set_value(self, new_value):
        cells = self.xml.findall('cell')
        if len(cells) == 2:
            cells[1].text = new_value

class MyCellEditor(wx.grid.PyGridCellEditor):
    """
    This is a sample GridCellEditor that shows you how to make your own custom
    grid editors.  All the methods that can be overridden are show here.  The
    ones that must be overridden are marked with "*Must Override*" in the
    docstring.

    Notice that in order to call the base class version of these special
    methods we use the method name preceded by "base_".  This is because these
    methods are "virtual" in C++ so if we try to call wxGridCellEditor.Create
    for example, then when the wxPython extension module tries to call
    ptr->Create(...) then it actually calls the derived class version which
    looks up the method in this class and calls it, causing a recursion loop.
    If you don't understand any of this, don't worry, just call the "base_"
    version instead.

    ----------------------------------------------------------------------------
    This class is copied from the wxPython examples directory and was written by
    Robin Dunn.

    I have pasted it directly in and removed all references to "log"

    -- Andrew

    """
    def __init__(self):
        wx.grid.PyGridCellEditor.__init__(self)

    def Create(self, parent, id, evtHandler):
        """
        Called to create the control, which must derive from wxControl.
        *Must Override*
        """
        self._tc = wx.TextCtrl(parent, id, "", style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB)
        self._tc.SetInsertionPoint(0)
        self.SetControl(self._tc)
        if evtHandler: self._tc.PushEventHandler(evtHandler)

    def SetSize(self, rect):
        """
        Called to position/size the edit control within the cell rectangle.
        If you don't fill the cell (the rect) then be sure to override
        PaintBackground and do something meaningful there.
        """
        self._tc.SetDimensions(rect.x+1, rect.y+1, rect.width+2, rect.height+2)

    def BeginEdit(self, row, col, grid):
        """
        Fetch the value from the table and prepare the edit control
        to begin editing.  Set the focus to the edit control.
        *Must Override*
        """
        self.startValue = grid.GetTable().GetValue(row, col)
        self._tc.SetValue(self.startValue)
        self._tc.SetInsertionPointEnd()
        self._tc.SetFocus()

        # For this example, select the text
        self._tc.SetSelection(0, self._tc.GetLastPosition())

    def EndEdit(self, row, col, grid):
        """
        Complete the editing of the current cell. Returns True if the value
        has changed.  If necessary, the control may be destroyed.
        *Must Override*
        """
        changed = False
        val = self._tc.GetValue()
        if val != self.startValue:
            changed = True
            grid.GetTable().SetValue(row, col, val) # update the table

        self.startValue = ''
        self._tc.SetValue('')
        return changed

    def Reset(self):
        """
        Reset the value in the control back to its starting value.
        *Must Override*
        """
        self._tc.SetValue(self.startValue)
        self._tc.SetInsertionPointEnd()

    def IsAcceptedKey(self, evt):
        """
        Return True to allow the given key to start editing: the base class
        version only checks that the event has no modifiers.  F2 is special
        and will always start the editor.
        """
        return (not (evt.ControlDown() or evt.AltDown()) and
                evt.GetKeyCode() != wx.WXK_SHIFT)

    def StartingKey(self, evt):
        """
        If the editor is enabled by pressing keys on the grid, this will be
        called to let the editor do something about that first key if desired.
        """
        key = evt.GetKeyCode()
        ch = None
        if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
                   wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
            ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
        elif key < 256 and key >= 0 and chr(key) in string.printable:
            ch = chr(key)
            if not evt.ShiftDown(): ch = string.lower(ch)
        if ch is not None: self._tc.AppendText(ch)
        else: evt.Skip()

    def Destroy(self):
        """final cleanup"""
        self.base_Destroy()

    def Clone(self):
        """
        Create a new object which is the copy of this one
        *Must Override*
        """
        return MyCellEditor()


class rpg_grid(wx.grid.Grid):
    """grid for attacks"""
    def __init__(self, parent, handler):
        wx.grid.Grid.__init__(self, parent, -1, style=wx.SUNKEN_BORDER | wx.WANTS_CHARS)
        self.parent = parent
        self.handler = handler

        self.RegisterDataType(wx.grid.GRID_VALUE_STRING, wx.grid.GridCellStringRenderer(),MyCellEditor())

        self.rows = handler.grid.findall('row')
        rows = len(self.rows)
        cols = len(self.rows[0].findall('cell'))
        self.CreateGrid(rows,cols)
        self.SetRowLabelSize(0)
        self.SetColLabelSize(0)
        self.set_col_widths()

        for i in range(0,len(self.rows)): self.refresh_row(i)

        self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_cell_change)
        self.Bind(wx.grid.EVT_GRID_COL_SIZE, self.on_col_size)
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_DCLICK, self.on_leftdclick)


    def on_leftdclick(self,evt):
        if self.CanEnableCellControl(): self.EnableCellEditControl()

    def on_col_size(self, evt):
        col = evt.GetRowOrCol()
        cells = self.rows[0].findall('cell')
        size = self.GetColSize(col)
        cells[col].set('size',str(size))
        evt.Skip()

    def on_cell_change(self,evt):
        row = evt.GetRow()
        col = evt.GetCol()
        value = self.GetCellValue(row,col)
        cells = self.rows[row].findall('cell')
        cells[col].text = value
        if col == 0: self.handler.refresh_rows()

    def set_col_widths(self):
        cells = self.rows[0].findall('cell')
        for i in range(0,len(cells)):
            try:
                size = int(cells[i].get('size'))
                self.SetColSize(i,size)
            except: continue

    def refresh_row(self,rowi):
        cells = self.rows[rowi].findall('cell')
        for i in range(0,len(cells)):
            text = cells[i].text
            if text == None or text == '':
                text = ''
                cells[i].text = text
            self.SetCellValue(rowi,i,text)

    def add_row(self,evt=None):
        cols = self.GetNumberCols()
        row = Element('row')
        for i in range(0,cols):
            cell = Element('cell')
            cell.text = ''
            row.append(cell)
        self.handler.grid.append(row)
        self.AppendRows(1)
        self.rows = self.handler.grid.findall('row')
        self.handler.refresh_rows()

    def add_col(self,evt=None):
        for r in self.rows:
            cell = Element('cell')
            cell.text = ''
            r.append(cell)
        self.AppendCols(1)
        self.set_col_widths()

    def del_row(self,evt=None):
        num = self.GetNumberRows()
        if num == 1: return
        self.handler.grid.remove(self.handler.grid[num-1])# always remove last row -- nasty
        self.DeleteRows(num-1,1)
        self.rows = self.handler.grid.findall('row')
        self.handler.refresh_rows()

    def del_col(self,evt=None):
        num = self.GetNumberCols()
        if num == 1: return
        for r in self.rows:
            cells = r.findall('cell')
            r.remove(r[num-1])                  # always remove the last column -- nasty
        self.DeleteCols(num-1,1)
        self.set_col_widths()


G_TITLE = wx.NewId()
GRID_BOR = wx.NewId()
class rpg_grid_panel(wx.Panel):
    def __init__(self, parent, handler):
        wx.Panel.__init__(self, parent, -1)
        self.handler = handler
        self.grid = rpg_grid(self,handler)
        label = handler.xml.get('name')
        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.main_sizer.Add(wx.StaticText(self, -1, label+": "), 0, wx.EXPAND)
        self.main_sizer.Add(self.grid,1,wx.EXPAND)
        self.SetSizer(self.main_sizer)
        self.SetAutoLayout(True)
        self.Fit()
        parent.SetSize(self.GetBestSize())

G_AUTO_SIZE = wx.NewId()
G_ADD_ROW = wx.NewId()
G_ADD_COL = wx.NewId()
G_DEL_ROW = wx.NewId()
G_DEL_COL = wx.NewId()
G_BUT_REF = wx.NewId()

class rpg_grid_edit_panel(wx.Panel):
    def __init__(self, parent, handler):
        wx.Panel.__init__(self, parent, -1)
        self.handler = handler
        self.grid = rpg_grid(self,handler)
        self.main_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Grid"), wx.VERTICAL)

        self.title = wx.TextCtrl(self, G_TITLE, handler.xml.get('name'))

        radio_b = wx.RadioBox(self, GRID_BOR, "Border (HTML)", choices=["no","yes"])
        border = handler.grid.get("border")
        radio_b.SetSelection(int(border))

        self.auto_size = wx.CheckBox(self, G_AUTO_SIZE, "Auto Size")
        if handler.is_autosized() == '1': self.auto_size.SetValue(True)
        else: self.auto_size.SetValue(False)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(wx.Button(self, G_ADD_ROW, "Add Row"), 1, wx.EXPAND)
        sizer.Add(wx.Size(10,10))
        sizer.Add(wx.Button(self, G_DEL_ROW, "Remove Row"), 1, wx.EXPAND)
        sizer.Add(wx.Size(10,10))
        sizer.Add(wx.Button(self, G_ADD_COL, "Add Column"), 1, wx.EXPAND)
        sizer.Add(wx.Size(10,10))
        sizer.Add(wx.Button(self, G_DEL_COL, "Remove Column"), 1, wx.EXPAND)
        sizer.Add(wx.Size(10,10))
        sizer.Add(wx.Button(self, G_BUT_REF, "Reference"), 1)

        self.main_sizer.Add(wx.StaticText(self, -1, "Title:"), 0, wx.EXPAND)
        self.main_sizer.Add(self.title, 0, wx.EXPAND)
        self.main_sizer.Add(radio_b, 0, 0)
        self.main_sizer.Add(self.auto_size, 0, 0)
        self.main_sizer.Add(self.grid,1,wx.EXPAND)
        self.main_sizer.Add(sizer,0,wx.EXPAND)

        self.SetSizer(self.main_sizer)
        self.SetAutoLayout(True)
        self.Fit()

        self.Bind(wx.EVT_TEXT, self.on_text, id=G_TITLE)
        self.Bind(wx.EVT_BUTTON, self.grid.add_row, id=G_ADD_ROW)
        self.Bind(wx.EVT_BUTTON, self.grid.del_row, id=G_DEL_ROW)
        self.Bind(wx.EVT_BUTTON, self.grid.add_col, id=G_ADD_COL)
        self.Bind(wx.EVT_BUTTON, self.grid.del_col, id=G_DEL_COL)
        self.Bind(wx.EVT_RADIOBOX, self.on_radio_box, id=GRID_BOR)
        self.Bind(wx.EVT_CHECKBOX, self.on_auto_size, id=G_AUTO_SIZE)
        self.Bind(wx.EVT_BUTTON, self.on_reference, id=G_BUT_REF)

    ## EZ_Tree Core TaS - Prof.Ebral ##
    def on_reference(self, evt, car=None):
        self.do_tree = wx.Frame(self, -1, 'Tree')
        self.ez_tree = orpg.gametree.gametree
        self.temp_wnd = self.ez_tree.game_tree(self.do_tree, self.ez_tree.EZ_REF)
        #self.temp_wnd.Bind(wx.EVT_LEFT_DCLICK, self.on_ldclick) ## Remove for Alpha ##
        self.temp_wnd.load_tree(settings.get("gametree"))
        self.do_tree.Show()

    def on_ldclick(self, evt):
        self.rename_flag = 0
        pt = evt.GetPosition()
        (item, flag) = self.temp_wnd.HitTest(pt)
        if item.IsOk():
            obj = self.temp_wnd.GetPyData(item)
            self.temp_wnd.SelectItem(item)
            start = self.handler.xml.get('map').split('::')
            end = obj.xml.get('map').split('::')
            if obj.xml.get('class') not in ['rpg_grid_handler', 'textctrl_handler']: do = 'None'
            elif end[0] == '' or start[0] != end[0]: do = 'Root'
            elif start == end: do = 'Child'
            elif start != end: do = 'Parent'
            if do == 'Root':
                complete = "!@"
                for e in end: 
                    if e != '': complete += e +'::'
                complete = complete + obj.xml.get('name') + '@!'
            elif do == 'Parent':
                while start[0] == end[0]:
                    top = start[0]
                    del end[0], start[0]
                    if len(start) == 0 or len(end) == 0: break
                complete = "!#" + top + "::"
                for e in end: complete += e +'::'
                complete = complete + obj.xml.get('name') + '#!'
            elif do == 'Child':
                while start[0] == end[0]:
                    del end[0], start[0]
                    if len(start) == 0 or len(end) == 0: break
                complete = "!!"
                for e in end: complete += e +'::'
                complete = complete + obj.xml.get('name') + '!!'
            if do != 'None': self.value_entry.AppendText(complete); self.reload_options()
        self.do_tree.Destroy()
        if do == 'None':
            wx.MessageBox('Invalid Reference', 'Error')
    #####                        #####

    def on_auto_size(self,evt):
        self.handler.set_autosize(bool2int(evt.Checked()))

    def on_radio_box(self,evt):
        id = evt.GetId()
        index = evt.GetInt()
        if id == GRID_BOR:
            self.handler.grid.set("border",str(index))

    def on_text(self,evt):
        txt = self.title.GetValue()
        if txt != "":
            self.handler.xml.set('name',txt)
            self.handler.rename(txt)