view orpg/gametree/nodehandlers/core.py @ 228:24769389a7ba alpha

Traipse Alpha 'OpenRPG' {100612-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 (Preparing to close updates) New Features: New to Map, can re-order Grid, Miniatures, and Whiteboard layer draw order Fixes: Fix to InterParse that was causing an Infernal Loop with Namespace Internal Fix to XML data, removed old Minidom and switched to Element Tree Fix to Server that was causing eternal attempt to find a Server ID, in Register Rooms thread Fix to metaservers.xml file not being created
author sirebral
date Sat, 12 Jun 2010 04:38:29 -0500
parents b633f4c64aae
children
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: core.py
# Author: Chris Davis
# Maintainer:
# Version:
#   $Id: core.py,v Traipse 'Ornery-Orc' prof.ebral Exp $
#
# Description: The file contains code for the core nodehanlers
#

__version__ = "$Id: core.py,v Traipse 'Ornery-Orc' prof.ebral Exp $"

from nodehandler_version import NODEHANDLER_VERSION
from orpg.tools.InterParse import Parse

try:
    from orpg.orpg_windows import *
    from orpg.dirpath import dir_struct
    from orpg.orpgCore import component
    import webbrowser, os
    from orpg.mapper import map
    from wx import DisplaySize
except:
    import wx

from xml.etree.ElementTree import ElementTree, Element, tostring, XML
from orpg.tools.orpg_log import debug

#html defaults
TH_BG = "#E9E9E9"
##########################
## base node handler
##########################
class node_handler:
    """ Base nodehandler with virtual functions and standard implmentations """
    def __init__(self,xml,tree_node):
        self.xml = xml
        self.mytree_node = tree_node
        self.tree = component.get('tree')
        self.frame = component.get('frame')
        self.chat = component.get('chat')
        self.drag = True
        self.myeditor = None # designing
        self.myviewer = None # prett print
        self.mywindow = None # using
        # call version hook
        self.on_version(self.xml.get("version"))
        # set to current version
        self.xml.set("version",NODEHANDLER_VERSION)
        # null events
        self.frame_size = None
        self.frame_pos  = None
        try:
            frame = self.xml.get("frame")
            if len(frame):
                (sx,sy,px,py) = [int(value) for value in frame.split(',')]
                self.frame_size = (sx, sy)
                (maxx, maxy) = DisplaySize()
                if px < maxx-80 and py < maxy-50: self.frame_pos  = (px, py) #if it's off screen ignore the saved pos
        except: pass

    def on_version(self,old_version):
        ## added version control code here or implement a new on_version in your derived class.
        ## always call the base class on_version !
        pass

    def on_rclick(self,evt):
        self.tree.do_std_menu(evt,self)

    def on_ldclick(self,evt):
        return 0

    def usefulness(self,text):
        if text=="useful": self.xml.set('status',"useful")
        elif text=="useless": self.xml.set('status',"useless")
        elif text=="indifferent": self.xml.set('status',"indifferent")

    def on_design(self,evt):
        try:
            self.myeditor.Show()
            self.myeditor.Raise()
        except:
            del self.myeditor
            if self.create_designframe():
                self.myeditor.Show()
                self.myeditor.Raise()
            else: return
        wx.CallAfter(self.myeditor.Layout)

    def create_designframe(self):
        title = self.xml.get('name') + " Editor"
        self.myeditor = wx.Frame(None, -1, title)
        self.myeditor.Freeze()
        if wx.Platform == '__WXMSW__':
            icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO)
            self.myeditor.SetIcon(icon)
            del icon

        self.myeditor.panel = self.get_design_panel(self.myeditor)
        if self.myeditor.panel == None:
            self.myeditor.Destroy()
            return False
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.myeditor.panel, 1, wx.EXPAND)

        self.myeditor.SetSizer(sizer)
        self.myeditor.SetAutoLayout(True)

        (x, y) = self.myeditor.GetSize()
        if x < 400: x = 400
        if y < 400: y = 400

        self.myeditor.SetSize((x, y))
        self.myeditor.Layout()
        self.myeditor.Thaw()
        return True

    def on_use(self, evt):
        try:
            self.mywindow.Show()
            self.mywindow.Raise()
        except:
            del self.mywindow
            if self.create_useframe():
                self.mywindow.SetSize(self.frame_size)
                if self.frame_pos: self.mywindow.SetPosition(self.frame_pos)
                self.mywindow.Show()
                self.mywindow.Raise()
            else: return
        wx.CallAfter(self.mywindow.Layout)

    def create_useframe(self):
        caption = self.xml.get('name', '')
        self.mywindow = wx.Frame(None, -1, caption)
        self.mywindow.Freeze()
        if wx.Platform == '__WXMSW__':
            icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO)
            self.mywindow.SetIcon(icon)
            del icon
        self.mywindow.panel = self.get_use_panel(self.mywindow)
        if self.mywindow.panel == None:
            self.mywindow.Destroy()
            return False
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.mywindow.panel, 2, wx.EXPAND)

        self.mywindow.SetSizer(sizer)
        self.mywindow.SetAutoLayout(True)

        if self.frame_size is None:
            self.frame_size = self.mywindow.GetSize()
            if self.frame_size.x < 400: self.frame_size.x = 400
            if self.frame_size.y < 400: self.frame_size.y = 400

        self.mywindow.Layout()
        self.mywindow.Thaw()
        self.mywindow.Bind(wx.EVT_CLOSE, self.close_useframe)
        return True

    def close_useframe(self, evt):
        self.frame_size = self.mywindow.GetSize()
        self.frame_pos  = self.mywindow.GetPosition()
        frame_values = str(self.frame_size.x)+','+str(self.frame_size.y)+','+str(self.frame_pos.x)+','+str(self.frame_pos.y)
        self.xml.set("frame", frame_values)
        self.mywindow.Destroy()


    def on_html_view(self,evt):
        try: self.myviewer.Raise()
        except:
            caption = self.xml.get('name')
            self.myviewer = wx.Frame(None, -1, caption)
            if wx.Platform == '__WXMSW__':
                icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO)
                self.myviewer.SetIcon(icon)
                del icon
            self.myviewer.panel = self.get_html_panel(self.myviewer)
            self.myviewer.Show()

    def map_aware(self):
        return 0

    def can_clone(self):
        return 1;

    def on_del(self,evt):
        print "on del"

    def on_new_data(self,xml):
        pass

    def get_scaled_bitmap(self,x,y):
        return None

    def on_send_to_map(self,evt):
        pass

    def on_send_to_chat(self,evt):
        self.chat.ParsePost(self.tohtml(),True,True)

    def on_drop(self, evt):
        drag_obj = self.tree.drag_obj
        if drag_obj == self or self.tree.is_parent_node(self.mytree_node, drag_obj.mytree_node):
            return
        drop_xml = self.tree.drag_obj.delete()
        parent_node = self.tree.GetItemParent(self.mytree_node)
        prev_sib = self.tree.GetPrevSibling(self.mytree_node)
        if parent_node == self.tree.root: parent_xml = self.tree.GetPyData(parent_node)
        else: parent_xml = self.tree.GetPyData(parent_node).xml
        for i in range(len(parent_xml)):
            if parent_xml[i] is self.xml:
                parent_xml.insert(i, drop_xml)
                break
        if not prev_sib.IsOk():
            prev_sib = parent_node
        self.tree.load_xml(drop_xml, parent_node, prev_sib)

    def get_tree(self):
        family = []
        test = treenode
        while test != self.tree.root:
            test = self.tree.GetItemParent(test)
            parent = self.tree.GetItemText(test)
            family.append(parent)
        return family

    def toxml(self,pretty=0):
        return tostring(self.xml) #toxml(self.master_dom,pretty)

    def tohtml(self):
        return self.xml.get("name")

    def delete(self):
        """ removes the tree_node and xml_node, and returns the removed xml_node """
        parent_node = self.tree.GetItemParent(self.mytree_node)
        if parent_node == self.tree.root: parent_xml = self.tree.GetPyData(parent_node)
        else: parent_xml = self.tree.GetPyData(parent_node).xml
        parent_xml.remove(self.xml)
        self.tree.Delete(self.mytree_node)
        return self.xml

    def rename(self,name):
        if len(name):
            self.tree.SetItemText(self.mytree_node,name)
            self.xml.set('name', name)

    def change_icon(self,icon):
        self.xml.set("icon",icon)
        self.tree.SetItemImage(self.mytree_node, self.tree.icons[icon])
        self.tree.SetItemImage(self.mytree_node, self.tree.icons[icon], wx.TreeItemIcon_Selected)
        self.tree.Refresh()

    def on_save(self,evt):
        f = wx.FileDialog(self.tree,"Select a file", orpg.dirpath.dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE)
        if f.ShowModal() == wx.ID_OK: ElementTree(self.xml).write(f.GetPath())
        f.Destroy()

    def get_design_panel(self,parent):
        return None

    def get_use_panel(self,parent):
        return None

    def get_html_panel(self,parent):
        html_str = "<html><body bgcolor=\"#FFFFFF\" >"+self.tohtml()+"</body></html>"
        wnd = wx.html.HtmlWindow(parent,-1)
        html_str = Parse.Dice(html_str)
        wnd.SetPage(html_str)
        return wnd

    def get_size_constraint(self):
        return 0

    def about(self):
        """html_str = "<b>"+ self.xml.get('class')
        html_str += " Applet</b><br />by Chris Davis<br />chris@rpgarchive.com"
        return html_str"""
        text = self.xml.get('class') + ' Applet\n'
        text += 'by Chris Davis chris@rpgarchive.com'
        return text

    def get_value(self):
        return None

P_TITLE = 10
P_BODY = 20

class text_edit_panel(wx.Panel):
    def __init__(self, parent, handler):
        wx.Panel.__init__(self, parent, -1)
        self.handler = handler
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.text = {   P_TITLE : wx.TextCtrl(self, P_TITLE, handler.xml.get('name')),
                        P_BODY : html_text_edit(self,P_BODY,handler.text,self.on_text)
                      }
        sizer.Add(wx.StaticText(self, -1, "Title:"), 0, wx.EXPAND)
        sizer.Add(self.text[P_TITLE], 0, wx.EXPAND)
        sizer.Add(wx.StaticText(self, -1, "Text Body:"), 0, wx.EXPAND)
        sizer.Add(self.text[P_BODY], 1, wx.EXPAND)
        self.sizer = sizer
        self.outline = wx.StaticBox(self,-1,"Text Block")
        self.Bind(wx.EVT_TEXT, self.on_text, id=P_TITLE)

    def on_text(self,evt):
        id = evt.GetId()
        if id == P_TITLE:
            txt = self.text[id].GetValue()
            #  The following block strips out 8-bit characters
            u_txt = ""
            bad_txt_found = 0
            for c in txt:
                if ord(c) < 128: u_txt += c
                else: bad_txt_found = 1
            if bad_txt_found:
                wx.MessageBox("Some non 7-bit ASCII characters found and stripped","Warning!")
            txt = u_txt
            if txt != "":
                self.handler.xml.set('name',txt)
                self.handler.rename(txt)
        elif id == P_BODY:
            txt = self.text[id].get_text()
            u_txt = ""
            bad_txt_found = 0
            for c in txt:
                if ord(c) < 128: u_txt += c
                else: bad_txt_found = 1
            if bad_txt_found:
                wx.MessageBox("Some non 7-bit ASCII characters found and stripped","Warning!")
            txt = u_txt
            print txt, self.handler, self.handler.xml
            self.handler.text._set_nodeValue(txt)



##########################
## node loader
##########################
class node_loader(node_handler):
    """ clones childe node and insert it at top of tree
        <nodehandler name='?'  module='core' class='node_loader'  />
    """
    def __init__(self,xml,tree_node):
        node_handler.__init__(self,xml,tree_node)

    def on_rclick(self,evt):
        pass

    def on_ldclick(self,evt):
        title = self.xml.get('name')
        new_xml = XML(tostring(self.xml[0]))
        self.tree.root_xml.insert(0, new_xml)
        tree_node = self.tree.load_xml(new_xml,self.tree.root,self.tree.root)
        return 1

##########################
## file loader
##########################

class file_loader(node_handler):
    """ loads file and insert into game tree
        <nodehandler name='?'  module='core' class='file_loader'  >
        <file name="file_name.xml" />
        </nodehandler>
    """
    def __init__(self,xml,tree_node):
        node_handler.__init__(self,xml,tree_node)
        self.file_node = self.xml[0]
        self.frame = component.get('frame')

    def on_ldclick(self,evt):
        file_name = self.file_node.get("name")
        try: self.tree.insert_xml(open(orpg.dirpath.dir_struct["nodes"] + file_name,"r").read())
        except: wx.MessageBox('Invalid File', 'Error')
        return 1

    def on_design(self,evt):
        tlist = ['Title','File Name']
        vlist = [self.xml.get("name"),
                  self.file_node.get("name")]
        dlg = orpgMultiTextEntry(self.tree.GetParent(),tlist,vlist,"File Loader Edit")
        if dlg.ShowModal() == wx.ID_OK:
            vlist = dlg.get_values()
            self.file_node.set('name', vlist[1])
            self.xml.set('name', vlist[0])
            self.tree.SetItemText(self.mytree_node,vlist[0])
        dlg.Destroy()

##########################
## URL loader
##########################

class url_loader(node_handler):
    """ loads file from url and insert into game tree
        <nodehandler name='?'  module='core' class='url_loader'  >
        <file name="http://file_name.xml" />
        </nodehandler>
    """
    def __init__(self,xml,tree_node):
        node_handler.__init__(self,xml,tree_node)
        self.file_node = self.xml[0]
        self.frame = component.get('frame')

    def on_ldclick(self,evt):
        file_name = self.file_node.get("url")
        file = urllib.urlopen(file_name)
        self.tree.insert_xml(file.read())
        return 1

    def on_design(self,evt):
        tlist = ['Title','URL']
        vlist = [self.xml.get("name"),
                 self.file_node.get("url")]
        dlg = orpgMultiTextEntry(self.tree.GetParent(),tlist,vlist,"File Loader Edit")
        if dlg.ShowModal() == wx.ID_OK:
            vlist = dlg.get_values()
            self.file_node.set('url', vlist[1])
            self.xml.set('name', vlist[0])
            self.tree.SetItemText(self.mytree_node,vlist[0])
        dlg.Destroy()


##########################
## minature map loader
##########################
class min_map(node_handler):
    """ clones childe node and insert it at top of tree
        <nodehandler name='?'  module='core' class='min_map'  />
    """
    def __init__(self,xml,tree_node):
        node_handler.__init__(self,xml,tree_node)
        self.map = component.get('map')
        self.mapdata = self.xml.find('map')

    def on_ldclick(self,evt):
        if (component.get('session').my_role() != component.get('session').ROLE_GM):
            component.get('chat').InfoPost("You must be a GM to use this feature")
            return
        self.map.new_data(tostring(self.mapdata))
        component.get('session').send(tostring(self.mapdata))
        self.map.canvas.send_map_data()
        return 1