comparison orpg/gametree/gametree.py @ 135:dcf4fbe09b70 beta

Traipse Beta 'OpenRPG' {091010-00} 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 (Beta) Added Bookmarks Fix to Remote Admin Commands Minor fix to text based Server Fix to Pretty Print, from Core Fix to Splitter Nodes not being created Fix to massive amounts of images loading, from Core 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 default_manifest.xml renamed to default_upmana.xml Cleaner clode for saved repositories New TrueDebug Class in orpg_log (See documentation for usage) Mercurial's hgweb folder is ported to upmana **Pretty important update that can help remove thousands of dead children from your gametree. **Children, <forms />, <group_atts />, <horizontal />, <cols />, <rows />, <height />, etc... are all tags now. Check your gametree and look for dead children!! **New Gamtree Recusion method, mapping, and context sensitivity. !!Alpha - Watch out for infinite loops!!
author sirebral
date Tue, 10 Nov 2009 14:11:28 -0600
parents 37a11fea3304
children e842a5f1b775
comparison
equal deleted inserted replaced
101:394ebb3b6a0f 135:dcf4fbe09b70
24 # $Id: gametree.py,v 1.68 2007/12/07 20:39:48 digitalxero Exp $ 24 # $Id: gametree.py,v 1.68 2007/12/07 20:39:48 digitalxero Exp $
25 # 25 #
26 # Description: The file contains code fore the game tree shell 26 # Description: The file contains code fore the game tree shell
27 # 27 #
28 28
29 from __future__ import with_statement
30
29 __version__ = "$Id: gametree.py,v 1.68 2007/12/07 20:39:48 digitalxero Exp $" 31 __version__ = "$Id: gametree.py,v 1.68 2007/12/07 20:39:48 digitalxero Exp $"
30 32
31 from orpg.orpg_wx import * 33 from orpg.orpg_wx import *
32 from orpg.orpg_windows import * 34 from orpg.orpg_windows import *
33 from orpg.orpgCore import component 35 from orpg.orpgCore import component
38 import time 40 import time
39 import os 41 import os
40 42
41 from orpg.orpg_xml import xml 43 from orpg.orpg_xml import xml
42 from orpg.tools.validate import validate 44 from orpg.tools.validate import validate
43 from orpg.tools.orpg_log import logger 45 from orpg.tools.orpg_log import logger, debug
44 from orpg.tools.decorators import debugging 46 from orpg.tools.orpg_settings import settings
45 from orpg.gametree.nodehandlers import containers, forms, dnd3e, dnd35, chatmacro 47 from orpg.gametree.nodehandlers import containers, forms, dnd3e, dnd35, chatmacro
46 from orpg.gametree.nodehandlers import map_miniature_nodehandler 48 from orpg.gametree.nodehandlers import map_miniature_nodehandler
47 from orpg.gametree.nodehandlers import minilib, rpg_grid, d20, StarWarsd20, voxchat 49 from orpg.gametree.nodehandlers import minilib, rpg_grid, d20, StarWarsd20, voxchat
48 50
49 from gametree_version import GAMETREE_VERSION 51 from gametree_version import GAMETREE_VERSION
52
53 from xml.etree.ElementTree import ElementTree, Element, parse
54 from xml.etree.ElementTree import fromstring, tostring, XML, iselement
55 from xml.parsers.expat import ExpatError
50 56
51 STD_MENU_DELETE = wx.NewId() 57 STD_MENU_DELETE = wx.NewId()
52 STD_MENU_DESIGN = wx.NewId() 58 STD_MENU_DESIGN = wx.NewId()
53 STD_MENU_USE = wx.NewId() 59 STD_MENU_USE = wx.NewId()
54 STD_MENU_PP = wx.NewId() 60 STD_MENU_PP = wx.NewId()
75 TOP_SAVE_TREE_AS = wx.NewId() 81 TOP_SAVE_TREE_AS = wx.NewId()
76 TOP_TREE_PROP = wx.NewId() 82 TOP_TREE_PROP = wx.NewId()
77 TOP_FEATURES = wx.NewId() 83 TOP_FEATURES = wx.NewId()
78 84
79 class game_tree(wx.TreeCtrl): 85 class game_tree(wx.TreeCtrl):
80 @debugging 86
81 def __init__(self, parent, id): 87 def __init__(self, parent, id):
82 wx.TreeCtrl.__init__(self,parent,id, wx.DefaultPosition, 88 wx.TreeCtrl.__init__(self,parent,id, wx.DefaultPosition,
83 wx.DefaultSize,style=wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS) 89 wx.DefaultSize,style=wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS)
84 #self.xml = component.get('xml') # 90 #self.xml = component.get('xml') #
85 self.settings = component.get('settings') 91 self.settings = component.get('settings')
101 self.Bind(wx.EVT_CHAR, self.on_char) 107 self.Bind(wx.EVT_CHAR, self.on_char)
102 self.Bind(wx.EVT_KEY_UP, self.on_key_up) 108 self.Bind(wx.EVT_KEY_UP, self.on_key_up)
103 self.id = 1 109 self.id = 1
104 self.dragging = False 110 self.dragging = False
105 self.last_save_dir = dir_struct["user"] 111 self.last_save_dir = dir_struct["user"]
112 self.tree_map = []
106 113
107 #Create tree from default if it does not exist 114 #Create tree from default if it does not exist
108 validate.config_file("tree.xml","default_tree.xml") 115 validate.config_file("tree.xml","default_tree.xml")
109 component.add("tree", self) 116 component.add("tree", self)
117
110 #build tree 118 #build tree
111 self.root = self.AddRoot("Game Tree",self.icons['gear']) 119 self.root = self.AddRoot("Game Tree", self.icons['gear'])
112 self.was_labeling = 0 120 self.was_labeling = 0
113 self.rename_flag = 0 121 self.rename_flag = 0
114 self.image_cache = {} 122 self.image_cache = {}
115 logger.debug("Exit game_tree") 123 logger.debug("Exit game_tree")
116 124
117 @debugging
118 def add_nodehandler(self, nodehandler, nodeclass): 125 def add_nodehandler(self, nodehandler, nodeclass):
119 if not self.nodehandlers.has_key(nodehandler): self.nodehandlers[nodehandler] = nodeclass 126 if not self.nodehandlers.has_key(nodehandler): self.nodehandlers[nodehandler] = nodeclass
120 else: logger.debug("Nodehandler for " + nodehandler + " already exists!") 127 else: logger.debug("Nodehandler for " + nodehandler + " already exists!")
121 128
122 @debugging
123 def remove_nodehandler(self, nodehandler): 129 def remove_nodehandler(self, nodehandler):
124 if self.nodehandlers.has_key(nodehandler): 130 if self.nodehandlers.has_key(nodehandler):
125 del self.nodehandlers[nodehandler] 131 del self.nodehandlers[nodehandler]
126 else: logger.debug("No nodehandler for " + nodehandler + " exists!") 132 else: logger.debug("No nodehandler for " + nodehandler + " exists!")
127 133
128 @debugging
129 def init_nodehandlers(self): 134 def init_nodehandlers(self):
130 self.add_nodehandler('group_handler', containers.group_handler) 135 self.add_nodehandler('group_handler', containers.group_handler)
131 self.add_nodehandler('tabber_handler', containers.tabber_handler) 136 self.add_nodehandler('tabber_handler', containers.tabber_handler)
132 self.add_nodehandler('splitter_handler', containers.splitter_handler) 137 self.add_nodehandler('splitter_handler', containers.splitter_handler)
133 self.add_nodehandler('form_handler', forms.form_handler) 138 self.add_nodehandler('form_handler', forms.form_handler)
150 self.add_nodehandler('url_loader', core.url_loader) 155 self.add_nodehandler('url_loader', core.url_loader)
151 self.add_nodehandler('min_map', core.min_map) 156 self.add_nodehandler('min_map', core.min_map)
152 157
153 # event = wxKeyEvent 158 # event = wxKeyEvent
154 # set to be called by wxWindows by EVT_CHAR macro in __init__ 159 # set to be called by wxWindows by EVT_CHAR macro in __init__
155 @debugging 160
156 def on_key_up(self, evt): 161 def on_key_up(self, evt):
157 key_code = evt.GetKeyCode() 162 key_code = evt.GetKeyCode()
158 if self.dragging and (key_code == wx.WXK_SHIFT): 163 if self.dragging and (key_code == wx.WXK_SHIFT):
159 curSelection = self.GetSelection() 164 curSelection = self.GetSelection()
160 cur = wx.StockCursor(wx.CURSOR_ARROW) 165 cur = wx.StockCursor(wx.CURSOR_ARROW)
164 self.SelectItem(curSelection) 169 self.SelectItem(curSelection)
165 if(isinstance(obj,core.node_handler)): 170 if(isinstance(obj,core.node_handler)):
166 obj.on_drop(evt) 171 obj.on_drop(evt)
167 self.drag_obj = None 172 self.drag_obj = None
168 evt.Skip() 173 evt.Skip()
169 174
170 @debugging
171 def on_char(self, evt): 175 def on_char(self, evt):
172 key_code = evt.GetKeyCode() 176 key_code = evt.GetKeyCode()
173 curSelection = self.GetSelection() # Get the current selection 177 curSelection = self.GetSelection() # Get the current selection
174 if evt.ShiftDown() and ((key_code == wx.WXK_UP) or (key_code == wx.WXK_DOWN)) and not self.dragging: 178 if evt.ShiftDown() and ((key_code == wx.WXK_UP) or (key_code == wx.WXK_DOWN)) and not self.dragging:
175 curSelection = self.GetSelection() 179 curSelection = self.GetSelection()
176 obj = self.GetPyData(curSelection) 180 obj = self.GetPyData(curSelection)
177 self.SelectItem(curSelection) 181 self.SelectItem(curSelection)
178 if(isinstance(obj,core.node_handler)): 182 if(isinstance(obj,core.node_handler)):
191 elif key_code == wx.WXK_F2: 195 elif key_code == wx.WXK_F2:
192 self.rename_flag = 1 196 self.rename_flag = 1
193 self.EditLabel(curSelection) 197 self.EditLabel(curSelection)
194 evt.Skip() 198 evt.Skip()
195 199
196 @debugging 200 def locate_valid_tree(self, error, msg): ## --Snowdog 3/05
197 def locate_valid_tree(self, error, msg, dir, filename): ## --Snowdog 3/05
198 """prompts the user to locate a new tree file or create a new one""" 201 """prompts the user to locate a new tree file or create a new one"""
199 response = wx.MessageDialog(self, msg, error, wx.YES|wx.NO|wx.ICON_ERROR) 202 response = wx.MessageDialog(self, msg, error, wx.YES|wx.NO|wx.ICON_ERROR)
200 if response == wx.YES: 203 if response == wx.YES:
201 file = None 204 file = None
202 filetypes = "Gametree (*.xml)|*.xml|All files (*.*)|*.*" 205 dlg = wx.FileDialog(self, "Locate Gametree file", dir_struct["user"],
203 dlg = wx.FileDialog(self, "Locate Gametree file", dir, filename, filetypes,wx.OPEN | wx.CHANGE_DIR) 206 filename[ ((filename.rfind(os.sep))+len(os.sep)):],
207 "Gametree (*.xml)|*.xml|All files (*.*)|*.*",
208 wx.OPEN | wx.CHANGE_DIR)
204 if dlg.ShowModal() == wx.ID_OK: file = dlg.GetPath() 209 if dlg.ShowModal() == wx.ID_OK: file = dlg.GetPath()
205 dlg.Destroy() 210 dlg.Destroy()
206 if not file: self.load_tree(error=1) 211 if not file: self.load_tree(error=1)
207 else: self.load_tree(file) 212 else: self.load_tree(file)
208 return 213 return
209 else: 214 else:
210 validate.config_file("tree.xml","default_tree.xml") 215 validate.config_file("tree.xml","default_tree.xml")
211 self.load_tree(error=1) 216 self.load_tree(error=1)
212 return 217 return
213 218
214 @debugging 219
215 def load_tree(self, filename=dir_struct["user"]+'tree.xml', error=0): 220 def load_tree(self, filename=dir_struct["user"]+'tree.xml', error=0):
216 self.settings.set_setting("gametree", filename) 221 self.settings.change("gametree", filename)
217 tmp = None 222 #check file exists
218 xml_dom = None 223 if not os.path.exists(filename):
219 xml_doc = None 224 emsg = "Gametree Missing!\n"+filename+" cannot be found.\n\n"\
225 "Would you like to locate it?\n"\
226 "(Selecting 'No' will cause a new default gametree to be generated)"
227 self.locate_valid_tree("Gametree Error", emsg)
228 return
220 try: 229 try:
221 logger.info("Reading Gametree file: " + filename + "...", True) 230 f = open(filename, "rb")
222 tmp = open(filename,"r") 231 tree = parse(f)
223 xml_doc = xml.parseXml(tmp.read()) 232 self.xml_root = tree.getroot()
224 tmp.close() 233 except:
225 if xml_doc == None: pass 234 f.close()
226 else: xml_dom = xml_doc._get_documentElement() 235 self.xml_root = None
227 logger.info("done.", True) 236 ### Alpha ### Doing some work on Gametree to add Element Tree, slowly at first.
228 237
229 except IOError: 238 if not self.xml_root:
230 emsg = "Gametree Missing!\n"+filename+" cannot be found.\n\n"\ 239 os.rename(filename,filename+".corrupt")
231 "Would you like to locate it?\n"\ 240 emsg = "Your gametree is being regenerated.\n\n"\
232 "(Selecting 'No' will cause a new default gametree to be generated)" 241 "To salvage a recent version of your gametree\n"\
233 fn = filename[ ((filename.rfind(os.sep))+len(os.sep)):] 242 "exit OpenRPG and copy the lastgood.xml file in\n"\
234 self.locate_valid_tree("Gametree Error", emsg, dir_struct["user"], fn) 243 "your myfiles directory to "+filename+ "\n"\
235 logger.general(emsg) 244 "in your myfiles directory.\n\n"\
245 "lastgood.xml WILL BE OVERWRITTEN NEXT TIME YOU RUN OPENRPG.\n\n"\
246 "Would you like to select a different gametree file to use?\n"\
247 "(Selecting 'No' will cause a new default gametree to be generated)"
248 self.locate_valid_tree("Corrupt Gametree!", emsg)
236 return 249 return
237 250
238 if not xml_dom: 251 if self.xml_root.tag != "gametree":
239 os.rename(filename,filename+".corrupt") 252 emsg = filename+" does not appear to be a valid gametree file.\n\n"\
240 fn = filename[ ((filename.rfind(os.sep))+len(os.sep)):] 253 "Would you like to select a different gametree file to use?\n"\
241 emsg = "Your gametree is being regenerated.\n\n"\ 254 "(Selecting 'No' will cause a new default gametree to be generated)"
242 "To salvage a recent version of your gametree\n"\ 255 self.locate_valid_tree("Invalid Gametree!", emsg)
243 "exit OpenRPG and copy the lastgood.xml file in\n"\
244 "your myfiles directory to "+fn+ "\n"\
245 "in your myfiles directory.\n\n"\
246 "lastgood.xml WILL BE OVERWRITTEN NEXT TIME YOU RUN OPENRPG.\n\n"\
247 "Would you like to select a different gametree file to use?\n"\
248 "(Selecting 'No' will cause a new default gametree to be generated)"
249 self.locate_valid_tree("Corrupt Gametree!", emsg, dir_struct["user"], fn)
250 logger.general(emsg)
251 return 256 return
252
253 if xml_dom._get_tagName() != "gametree":
254 fn = filename[ ((filename.rfind(os.sep))+len(os.sep)):]
255 emsg = fn+" does not appear to be a valid gametree file.\n\n"\
256 "Would you like to select a different gametree file to use?\n"\
257 "(Selecting 'No' will cause a new default gametree to be generated)"
258 self.locate_valid_tree("Invalid Gametree!", emsg, dir_struct["user"], fn)
259 logger.debug(emsg)
260 return
261
262 # get gametree version - we could write conversion code here!
263 self.master_dom = xml_dom
264 logger.debug("Master Dom Set")
265
266 try: 257 try:
267 version = self.master_dom.getAttribute("version") 258 # version = self.xml_root.get("version")
268 # see if we should load the gametree 259 # see if we should load the gametree
269 loadfeatures = int(self.settings.get_setting("LoadGameTreeFeatures")) 260 loadfeatures = int(settings.get_setting("LoadGameTreeFeatures"))
270 if loadfeatures: 261 if loadfeatures:
271 xml_dom = xml.parseXml(open(dir_struct["template"]+"feature.xml","r").read()) 262 features_tree = parse(orpg.dirpath.dir_struct["template"]+"feature.xml")
272 xml_dom = xml_dom._get_documentElement() 263 self.xml_root.append(features_tree.getroot())
273 xml_dom = self.master_dom.appendChild(xml_dom) 264 settings.change("LoadGameTreeFeatures","0")
274 self.settings.set_setting("LoadGameTreeFeatures","0")
275 265
276 ## load tree 266 ## load tree
277 logger.debug("Features loaded (if required)") 267 logger.debug("Features loaded (if required)")
278 self.CollapseAndReset(self.root) 268 self.CollapseAndReset(self.root)
279 children = self.master_dom._get_childNodes() 269 logger.note("Parsing Gametree Nodes ", True)
280 logger.info("Parsing Gametree Nodes ", True) 270 for xml_child in self.xml_root:
281 for c in children: 271 logger.note('.', True)
282 print '.', 272 self.load_xml(xml_child,self.root)
283 self.load_xml(c,self.root) 273 logger.note("done", True)
284 logger.info("done", True) 274
285 self.Expand(self.root) 275 self.Expand(self.root)
286 self.SetPyData(self.root,self.master_dom) 276 self.SetPyData(self.root,self.xml_root)
287 if error != 1: 277 if error != 1:
288 infile = open(filename, "rb") 278 with open(filename, "rb") as infile:
289 outfile = open(dir_struct["user"]+"lastgood.xml", "wb") 279 with open(dir_struct["user"]+"lastgood.xml", "wb") as outfile:
290 outfile.write(infile.read()) 280 outfile.write(infile.read())
291 else: logger.info("Not overwriting lastgood.xml file.", True) 281 else: logger.info("Not overwriting lastgood.xml file.", True)
292 282
293 except Exception, e: 283 except Exception, e:
294 logger.general(traceback.format_exc()) 284 logger.exception(traceback.format_exc())
295 wx.MessageBox("Corrupt Tree!\nYour game tree is being regenerated. To\nsalvage a recent version of your gametree\nexit OpenRPG and copy the lastgood.xml\nfile in your myfiles directory\nto "+filename+ "\nin your myfiles directory.\nlastgood.xml WILL BE OVERWRITTEN NEXT TIME YOU RUN OPENRPG.") 285 wx.MessageBox("Corrupt Tree!\nYour game tree is being regenerated. To\nsalvage a recent version of your gametree\nexit OpenRPG and copy the lastgood.xml\nfile in your myfiles directory\nto "+filename+ "\nin your myfiles directory.\nlastgood.xml WILL BE OVERWRITTEN NEXT TIME YOU RUN OPENRPG.")
296 os.rename(filename,filename+".corrupt") 286 os.rename(filename,filename+".corrupt")
297 validate.config_file("tree.xml","default_tree.xml") 287 validate.config_file("tree.xml","default_tree.xml")
298 self.load_tree(error=1) 288 self.load_tree(error=1)
299 289
300 @debugging
301 def build_std_menu(self, obj=None): 290 def build_std_menu(self, obj=None):
302 # build useful menu 291 # build useful menu
303 useful_menu = wx.Menu() 292 useful_menu = wx.Menu()
304 useful_menu.Append(STD_MENU_NODE_USEFUL,"Use&ful") 293 useful_menu.Append(STD_MENU_NODE_USEFUL,"Use&ful")
305 useful_menu.Append(STD_MENU_NODE_USELESS,"Use&less") 294 useful_menu.Append(STD_MENU_NODE_USELESS,"Use&less")
357 self.Bind(wx.EVT_MENU, self.on_save_tree, id=TOP_SAVE_TREE) 346 self.Bind(wx.EVT_MENU, self.on_save_tree, id=TOP_SAVE_TREE)
358 self.Bind(wx.EVT_MENU, self.on_load_new_tree, id=TOP_NEW_TREE) 347 self.Bind(wx.EVT_MENU, self.on_load_new_tree, id=TOP_NEW_TREE)
359 self.Bind(wx.EVT_MENU, self.on_tree_prop, id=TOP_TREE_PROP) 348 self.Bind(wx.EVT_MENU, self.on_tree_prop, id=TOP_TREE_PROP)
360 self.Bind(wx.EVT_MENU, self.on_insert_features, id=TOP_FEATURES) 349 self.Bind(wx.EVT_MENU, self.on_insert_features, id=TOP_FEATURES)
361 350
362 @debugging 351
363 def do_std_menu(self, evt, obj): 352 def do_std_menu(self, evt, obj):
364 try: self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu()) 353 try: self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu())
365 except: self.std_menu.Enable(STD_MENU_MAP, obj.map_aware()) 354 except: self.std_menu.Enable(STD_MENU_MAP, obj.map_aware())
366 self.std_menu.Enable(STD_MENU_CLONE, obj.can_clone()) 355 self.std_menu.Enable(STD_MENU_CLONE, obj.can_clone())
367 self.PopupMenu(self.std_menu) 356 self.PopupMenu(self.std_menu)
368 357
369 @debugging 358
370 def strip_html(self, player): 359 def strip_html(self, player):
371 ret_string = "" 360 ret_string = ""
372 x = 0 361 x = 0
373 in_tag = 0 362 in_tag = 0
374 for x in xrange(len(player[0])) : 363 for x in xrange(len(player[0])) :
378 else: pass 367 else: pass
379 else: ret_string = ret_string + player[0][x] 368 else: ret_string = ret_string + player[0][x]
380 logger.debug(ret_string) 369 logger.debug(ret_string)
381 return ret_string 370 return ret_string
382 371
383 @debugging 372
384 def on_receive_data(self, data, player): 373 def on_receive_data(self, data):
385 beg = string.find(data,"<tree>")
386 end = string.rfind(data,"</tree>")
387 data = data[6:end]
388 self.insert_xml(data) 374 self.insert_xml(data)
389 375
390 @debugging
391 def on_send_to_chat(self, evt): 376 def on_send_to_chat(self, evt):
392 item = self.GetSelection() 377 item = self.GetSelection()
393 obj = self.GetPyData(item) 378 obj = self.GetPyData(item)
394 obj.on_send_to_chat(evt) 379 obj.on_send_to_chat(evt)
395 380
396 @debugging
397 def on_whisper_to(self, evt): 381 def on_whisper_to(self, evt):
398 players = self.session.get_players() 382 players = self.session.get_players()
399 opts = [] 383 opts = []
400 myid = self.session.get_id() 384 myid = self.session.get_id()
401 me = None 385 me = None
414 player_ids = [] 398 player_ids = []
415 for s in selections: 399 for s in selections:
416 player_ids.append(players[s][2]) 400 player_ids.append(players[s][2])
417 self.chat.whisper_to_players(obj.tohtml(),player_ids) 401 self.chat.whisper_to_players(obj.tohtml(),player_ids)
418 402
419 @debugging 403
420 def on_export_html(self, evt): 404 def on_export_html(self, evt):
421 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","HTML (*.html)|*.html",wx.SAVE) 405 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","HTML (*.html)|*.html",wx.SAVE)
422 if f.ShowModal() == wx.ID_OK: 406 if f.ShowModal() == wx.ID_OK:
423 item = self.GetSelection() 407 item = self.GetSelection()
424 obj = self.GetPyData(item) 408 obj = self.GetPyData(item)
425 type = f.GetFilterIndex() 409 type = f.GetFilterIndex()
426 file = open(f.GetPath(),"w") 410 with open(f.GetPath(),"w") as f:
427 data = "<html><head><title>"+obj.master_dom.getAttribute("name")+"</title></head>" 411 data = "<html><head><title>"+obj.xml.get("name")+"</title></head>"
428 data += "<body bgcolor=\"#FFFFFF\" >"+obj.tohtml()+"</body></html>" 412 data += "<body bgcolor=\"#FFFFFF\" >"+obj.tohtml()+"</body></html>"
429 for tag in ("</tr>","</td>","</th>","</table>","</html>","</body>"): 413 for tag in ("</tr>","</td>","</th>","</table>","</html>","</body>"):
430 data = data.replace(tag,tag+"\n") 414 data = data.replace(tag,tag+"\n")
431 file.write(data) 415 f.write(data)
432 file.close()
433 self.last_save_dir, throwaway = os.path.split( f.GetPath() ) 416 self.last_save_dir, throwaway = os.path.split( f.GetPath() )
434 f.Destroy() 417 f.Destroy()
435 os.chdir(dir_struct["home"]) 418 os.chdir(dir_struct["home"])
436 419
437 @debugging 420
438 def indifferent(self, evt): 421 def indifferent(self, evt):
439 item = self.GetSelection() 422 item = self.GetSelection()
440 obj = self.GetPyData(item) 423 obj = self.GetPyData(item)
441 obj.usefulness("indifferent") 424 obj.usefulness("indifferent")
442 425
443 @debugging 426
444 def useful(self, evt): 427 def useful(self, evt):
445 item = self.GetSelection() 428 item = self.GetSelection()
446 obj = self.GetPyData(item) 429 obj = self.GetPyData(item)
447 obj.usefulness("useful") 430 obj.usefulness("useful")
448 431
449 @debugging 432
450 def useless(self, evt): 433 def useless(self, evt):
451 item = self.GetSelection() 434 item = self.GetSelection()
452 obj = self.GetPyData(item) 435 obj = self.GetPyData(item)
453 obj.usefulness("useless") 436 obj.usefulness("useless")
454 437
455 @debugging 438
456 def on_email(self,evt): 439 def on_email(self,evt):
457 pass 440 pass
458 441
459 @debugging 442
460 def on_send_to(self, evt): 443 def on_send_to(self, evt):
461 players = self.session.get_players() 444 players = self.session.get_players()
462 opts = [] 445 opts = []
463 myid = self.session.get_id() 446 myid = self.session.get_id()
464 me = None 447 me = None
469 players.remove(me) 452 players.remove(me)
470 dlg = orpgMultiCheckBoxDlg( None, opts, "Select Players:", "Send To", [] ) 453 dlg = orpgMultiCheckBoxDlg( None, opts, "Select Players:", "Send To", [] )
471 if dlg.ShowModal() == wx.ID_OK: 454 if dlg.ShowModal() == wx.ID_OK:
472 item = self.GetSelection() 455 item = self.GetSelection()
473 obj = self.GetPyData(item) 456 obj = self.GetPyData(item)
474 xmldata = "<tree>" + xml.toxml(obj) + "</tree>" 457 xmldata = "<tree>" + tostring(obj.xml) + "</tree>"
475 selections = dlg.get_selections() 458 selections = dlg.get_selections()
476 if len(selections) == len(opts): self.session.send(xmldata) 459 if len(selections) == len(opts): self.session.send(xmldata)
477 else: 460 else:
478 for s in selections: self.session.send(xmldata,players[s][2]) 461 for s in selections: self.session.send(xmldata,players[s][2])
479 dlg.Destroy() 462 dlg.Destroy()
480 463
481 @debugging 464
482 def on_icon(self, evt): 465 def on_icon(self, evt):
483 icons = self.icons.keys() 466 icons = self.icons.keys()
484 icons.sort() 467 icons.sort()
485 dlg = wx.SingleChoiceDialog(self,"Choose Icon?","Change Icon",icons) 468 dlg = wx.SingleChoiceDialog(self,"Choose Icon?","Change Icon",icons)
486 if dlg.ShowModal() == wx.ID_OK: 469 if dlg.ShowModal() == wx.ID_OK:
488 item = self.GetSelection() 471 item = self.GetSelection()
489 obj = self.GetPyData(item) 472 obj = self.GetPyData(item)
490 obj.change_icon(key) 473 obj.change_icon(key)
491 dlg.Destroy() 474 dlg.Destroy()
492 475
493 @debugging 476
494 def on_wizard(self, evt): 477 def on_wizard(self, evt):
495 item = self.GetSelection() 478 item = self.GetSelection()
496 obj = self.GetPyData(item) 479 obj = self.GetPyData(item)
497 name = "New " + obj.master_dom.getAttribute("name") 480 name = "New " + obj.xml_root.get("name")
498 icon = obj.master_dom.getAttribute("icon") 481 icon = obj.xml_root.get("icon")
499 xml_data = "<nodehandler name=\""+name+"\" icon=\"" + icon + "\" module=\"core\" class=\"node_loader\" >" 482 xml_data = "<nodehandler name=\""+name+"\" icon=\"" + icon + "\" module=\"core\" class=\"node_loader\" >"
500 xml_data += xml.toxml(obj) 483 xml_data += xml.toxml(obj)
501 xml_data += "</nodehandler>" 484 xml_data += "</nodehandler>"
502 self.insert_xml(xml_data) 485 self.insert_xml(xml_data)
503 logger.debug(xml_data) 486 logger.debug(xml_data)
504 487
505 @debugging 488
506 def on_clone(self, evt): 489 def on_clone(self, evt):
507 item = self.GetSelection() 490 item = self.GetSelection()
508 obj = self.GetPyData(item) 491 obj = self.GetPyData(item)
509 if obj.can_clone(): 492 if obj.can_clone():
510 parent_node = self.GetItemParent(item) 493 parent_node = self.GetItemParent(item)
511 prev_sib = self.GetPrevSibling(item) 494 prev_sib = self.GetPrevSibling(item)
512 if not prev_sib.IsOk(): prev_sib = parent_node 495 if not prev_sib.IsOk(): prev_sib = parent_node
513 xml_dom = xml.parseXml(xml.toxml(obj)) 496 clone_xml = XML(tostring(obj.xml))
514 xml_dom = xml_dom._get_firstChild() 497 if parent_node == self.root: parent_xml = self.GetPyData(parent_node)
515 parent = obj.master_dom._get_parentNode() 498 else: parent_xml = self.GetPyData(parent_node).xml
516 xml_dom = parent.insertBefore(xml_dom, obj.master_dom) 499 for i in range(len(parent_xml)):
517 self.load_xml(xml_dom, parent_node, prev_sib) 500 if parent_xml[i] is obj.xml:
518 501 parent_xml.insert(i, clone_xml)
519 @debugging 502 break
503 self.load_xml(clone_xml, parent_node, prev_sib)
504
505
520 def on_save(self, evt): 506 def on_save(self, evt):
521 """save node to a xml file""" 507 """save node to a xml file"""
522 item = self.GetSelection() 508 item = self.GetSelection()
523 obj = self.GetPyData(item) 509 obj = self.GetPyData(item)
524 obj.on_save(evt) 510 obj.on_save(evt)
525 os.chdir(dir_struct["home"]) 511 os.chdir(dir_struct["home"])
526 512
527 @debugging 513
528 def on_save_tree_as(self, evt): 514 def on_save_tree_as(self, evt):
529 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.SAVE) 515 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.SAVE)
530 if f.ShowModal() == wx.ID_OK: 516 if f.ShowModal() == wx.ID_OK:
531 self.save_tree(f.GetPath()) 517 self.save_tree(f.GetPath())
532 self.last_save_dir, throwaway = os.path.split( f.GetPath() ) 518 self.last_save_dir, throwaway = os.path.split( f.GetPath() )
533 f.Destroy() 519 f.Destroy()
534 os.chdir(dir_struct["home"]) 520 os.chdir(dir_struct["home"])
535 521
536 @debugging 522
537 def on_save_tree(self, evt=None): 523 def on_save_tree(self, evt=None):
538 filename = self.settings.get_setting("gametree") 524 filename = self.settings.get_setting("gametree")
539 self.save_tree(filename) 525 self.save_tree(filename)
540 526
541 @debugging 527
542 def save_tree(self, filename=dir_struct["user"]+'tree.xml'): 528 def save_tree(self, filename=dir_struct["user"]+'tree.xml'):
543 self.master_dom.setAttribute("version",GAMETREE_VERSION) 529 self.xml_root.set("version", GAMETREE_VERSION)
544 self.settings.set_setting("gametree",filename) 530 settings.change("gametree", filename)
545 file = open(filename,"w") 531 ElementTree(self.xml_root).write(filename)
546 file.write(xml.toxml(self.master_dom,1)) 532
547 file.close() 533
548
549 @debugging
550 def on_load_new_tree(self, evt): 534 def on_load_new_tree(self, evt):
551 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) 535 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN)
552 if f.ShowModal() == wx.ID_OK: 536 if f.ShowModal() == wx.ID_OK:
553 self.load_tree(f.GetPath()) 537 self.load_tree(f.GetPath())
554 self.last_save_dir, throwaway = os.path.split( f.GetPath() ) 538 self.last_save_dir, throwaway = os.path.split( f.GetPath() )
555 f.Destroy() 539 f.Destroy()
556 os.chdir(dir_struct["home"]) 540 os.chdir(dir_struct["home"])
557 541
558 @debugging 542
559 def on_insert_file(self, evt): 543 def on_insert_file(self, evt):
560 """loads xml file into the tree""" 544 """loads xml file into the tree"""
561 if self.last_save_dir == ".": 545 if self.last_save_dir == ".":
562 self.last_save_dir = dir_struct["user"] 546 self.last_save_dir = dir_struct["user"]
563 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) 547 f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN)
565 self.insert_xml(open(f.GetPath(),"r").read()) 549 self.insert_xml(open(f.GetPath(),"r").read())
566 self.last_save_dir, throwaway = os.path.split( f.GetPath() ) 550 self.last_save_dir, throwaway = os.path.split( f.GetPath() )
567 f.Destroy() 551 f.Destroy()
568 os.chdir(dir_struct["home"]) 552 os.chdir(dir_struct["home"])
569 553
570 @debugging 554
571 def on_insert_url(self, evt): 555 def on_insert_url(self, evt):
572 """loads xml url into the tree""" 556 """loads xml url into the tree"""
573 dlg = wx.TextEntryDialog(self,"URL?","Insert URL", "http://") 557 dlg = wx.TextEntryDialog(self,"URL?","Insert URL", "http://")
574 if dlg.ShowModal() == wx.ID_OK: 558 if dlg.ShowModal() == wx.ID_OK:
575 path = dlg.GetValue() 559 path = dlg.GetValue()
576 file = urllib.urlopen(path) 560 file = urllib.urlopen(path)
577 self.insert_xml(file.read()) 561 self.insert_xml(file.read())
578 dlg.Destroy() 562 dlg.Destroy()
579 563
580 @debugging 564
581 def on_insert_features(self, evt): 565 def on_insert_features(self, evt):
582 self.insert_xml(open(dir_struct["template"]+"feature.xml","r").read()) 566 self.insert_xml(open(dir_struct["template"]+"feature.xml","r").read())
583 567
584 @debugging 568
585 def on_tree_prop(self, evt): 569 def on_tree_prop(self, evt):
586 dlg = gametree_prop_dlg(self, self.settings) 570 dlg = gametree_prop_dlg(self, self.settings)
587 if dlg.ShowModal() == wx.ID_OK: pass 571 if dlg.ShowModal() == wx.ID_OK: pass
588 dlg.Destroy() 572 dlg.Destroy()
589 573
590 @debugging 574
591 def on_node_design(self, evt): 575 def on_node_design(self, evt):
592 item = self.GetSelection() 576 item = self.GetSelection()
593 obj = self.GetPyData(item) 577 obj = self.GetPyData(item)
594 obj.on_design(evt) 578 obj.on_design(evt)
595 579
596 @debugging 580
597 def on_node_use(self, evt): 581 def on_node_use(self, evt):
598 item = self.GetSelection() 582 item = self.GetSelection()
599 obj = self.GetPyData(item) 583 obj = self.GetPyData(item)
600 obj.on_use(evt) 584 obj.on_use(evt)
601 585
602 @debugging 586
603 def on_node_pp(self, evt): 587 def on_node_pp(self, evt):
604 item = self.GetSelection() 588 item = self.GetSelection()
605 obj = self.GetPyData(item) 589 obj = self.GetPyData(item)
606 obj.on_html_view(evt) 590 obj.on_html_view(evt)
607 591
608 @debugging 592
609 def on_del(self, evt): 593 def on_del(self, evt):
610 status_value = "none" 594 status_value = "none"
611 try: 595 try:
612 item = self.GetSelection() 596 item = self.GetSelection()
613 if item: 597 if item:
614 obj = self.GetPyData(item) 598 handler = self.GetPyData(item)
615 parent_obj = obj 599 status_value = handler.xml.get('status')
616 try: 600 name = handler.xml.get('name')
617 status_value = parent_obj.master_dom.getAttribute('status') 601 parent_item = self.GetItemParent(item)
618 name = parent_obj.master_dom.getAttribute('name') 602 while parent_item.IsOk() and status_value!="useful" and status_value!="useless":
619 except: status_value = "none"
620 parent_obj = parent_obj.master_dom._get_parentNode()
621 while status_value!="useful" and status_value!="useless":
622 try: 603 try:
623 status_value = parent_obj.getAttribute('status') 604 parent_handler = self.GetPyData(parent_item)
624 name = parent_obj.getAttribute('name') 605 status_value = parent_handler.get('status')
625 if status_value == "useless": break 606 name = parent_handler.get('name')
626 elif status_value == "useful": break 607 if status_value == "useless":
627 except: status_value = "none" 608 break
628 try: parent_obj = parent_obj._get_parentNode() 609 elif status_value == "useful":
629 except: break 610 break
611 except:
612 status_value = "none"
613 parent_item = self.GetItemParent(parent_item)
630 if status_value == "useful": 614 if status_value == "useful":
631 dlg = wx.MessageDialog(self, `name` + " And everything beneath it are considered useful. \n\nAre you sure you want to delete this item?",'Important Item',wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) 615 dlg = wx.MessageDialog(self, `name` + " And everything beneath it are considered useful. \n\nAre you sure you want to delete this item?",'Important Item',wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
632 if dlg.ShowModal() == wx.ID_YES: obj.delete() 616 if dlg.ShowModal() == wx.ID_YES: handler.delete()
633 else: obj.delete() 617 else: handler.delete()
634 except: 618 except:
635 if self.GetSelection() == self.GetRootItem(): 619 if self.GetSelection() == self.GetRootItem():
636 msg = wx.MessageDialog(None,"You can't delete the root item.","Delete Error",wx.OK) 620 msg = wx.MessageDialog(None,"You can't delete the root item.","Delete Error",wx.OK)
637 else: msg = wx.MessageDialog(None,"Unknown error deleting node.","Delete Error",wx.OK) 621 else: msg = wx.MessageDialog(None,"Unknown error deleting node.","Delete Error",wx.OK)
638 msg.ShowModal() 622 msg.ShowModal()
639 msg.Destroy() 623 msg.Destroy()
640 624
641 @debugging 625
642 def on_about(self, evt): 626 def on_about(self, evt):
643 item = self.GetSelection() 627 item = self.GetSelection()
644 obj = self.GetPyData(item) 628 obj = self.GetPyData(item)
645 about = MyAboutBox(self,obj.about()) 629 about = MyAboutBox(self,obj.about())
646 about.ShowModal() 630 about.ShowModal()
647 about.Destroy() 631 about.Destroy()
648 632
649 @debugging
650 def on_send_to_map(self, evt): 633 def on_send_to_map(self, evt):
651 item = self.GetSelection() 634 item = self.GetSelection()
652 obj = self.GetPyData(item) 635 obj = self.GetPyData(item)
653 if hasattr(obj,"on_send_to_map"): obj.on_send_to_map(evt) 636 if hasattr(obj,"on_send_to_map"): obj.on_send_to_map(evt)
654 637
655 @debugging
656 def insert_xml(self, txt): 638 def insert_xml(self, txt):
657 #Updated to allow safe merging of gametree files 639 #Updated to allow safe merging of gametree files
658 #without leaving an unusable and undeletable node. 640 #without leaving an unusable and undeletable node.
659 # -- Snowdog 8/03 641 # -- Snowdog 8/03
660 xml_dom = xml.parseXml(txt) 642 if not txt:
661 if xml_dom == None:
662 wx.MessageBox("Import Failed: Invalid or missing node data") 643 wx.MessageBox("Import Failed: Invalid or missing node data")
663 logger.debug("Import Failed: Invalid or missing node data") 644 logger.general("Import Failed: Invalid or missing node data")
664 logger.debug("Exit game_tree->insert_xml(self, txt)")
665 return 645 return
666 xml_temp = xml_dom._get_documentElement() 646 try: new_xml = XML(txt)
667 647 except ExpatError:
668 if not xml_temp:
669 wx.MessageBox("Error Importing Node or Tree") 648 wx.MessageBox("Error Importing Node or Tree")
670 logger.debug("Error Importing Node or Tree") 649 logger.general("Error Importing Node or Tree")
671 logger.debug("Exit game_tree->insert_xml(self, txt)")
672 return 650 return
673 651
674 if xml_temp._get_tagName() == "gametree": 652 if new_xml.tag == "gametree":
675 children = xml_temp._get_childNodes() 653 for xml_child in new_xml:
676 for c in children: self.load_xml(c, self.root) 654 self.load_xml(xml_child, self.root)
677 logger.debug("Exit game_tree->insert_xml(self, txt)")
678 return 655 return
679 656
680 if not xml_dom: 657 if new_xml.tag == "tree":
681 wx.MessageBox("XML Error") 658 self.xml_root.append(new_xml.find('nodehandler'))
682 logger.debug("XML Error") 659 for xml_child in new_xml:
683 logger.debug("Exit game_tree->insert_xml(self, txt)") 660 self.load_xml(xml_child, self.root)
684 return 661 return
685 662
686 xml_dom = xml_dom._get_firstChild() 663 self.xml_root.append(new_xml)
687 child = self.master_dom._get_firstChild() 664 self.load_xml(new_xml, self.root, self.root)
688 xml_dom = self.master_dom.insertBefore(xml_dom,child) 665
689 self.load_xml(xml_dom,self.root,self.root)
690
691 @debugging
692 def build_img_list(self): 666 def build_img_list(self):
693 """make image list""" 667 """make image list"""
694 helper = img_helper() 668 helper = img_helper()
695 self.icons = { } 669 self.icons = { }
696 self._imageList= wx.ImageList(16,16,False) 670 self._imageList= wx.ImageList(16,16,False)
697 man = open(dir_struct["icon"]+"icons.xml","r") 671 icons_xml = parse(orpg.dirpath.dir_struct["icon"]+"icons.xml")
698 xml_dom = xml.parseXml(man.read()) 672 for icon in icons_xml.getroot():
699 man.close() 673 key = icon.get("name")
700 xml_dom = xml_dom._get_documentElement() 674 path = orpg.dirpath.dir_struct["icon"] + icon.get("file")
701 node_list = xml_dom._get_childNodes()
702 for n in node_list:
703 key = n.getAttribute("name")
704 path = dir_struct["icon"] + n.getAttribute("file")
705 img = helper.load_file(path) 675 img = helper.load_file(path)
706 self.icons[key] = self._imageList.Add(img) 676 self.icons[key] = self._imageList.Add(img)
707 self.SetImageList(self._imageList) 677 self.SetImageList(self._imageList)
708 678
709 @debugging 679 def get_tree_map(self, parent):
710 def load_xml(self, xml_dom, parent_node, prev_node=None): 680 ## Could be a little cleaner ##
681 family_tree = []
682 test = parent
683 while test != self.root:
684 parent = self.GetItemText(test)
685 test = self.GetItemParent(test)
686 family_tree.append(parent)
687 return family_tree
688
689 def load_xml(self, xml_element, parent_node, prev_node=None):
690 if parent_node != self.root:
691 ## Loading XML seems to lag on Grids and Images need a cache for load speed ##
692 family_tree = self.get_tree_map(parent_node)
693 family_tree.reverse()
694 map_str = '' #'!@'
695 for member in family_tree:
696 map_str += member +'::'
697 map_str = map_str[:len(map_str)-2] #+'@!'
698 xml_element.set('map', map_str)
699
711 #add the first tree node 700 #add the first tree node
712 i = 0 701 i = 0
713 text = xml_dom.getAttribute("name") 702 name = xml_element.get("name")
714 icon = xml_dom.getAttribute("icon") 703 icon = xml_element.get("icon")
715 if self.icons.has_key(icon): i = self.icons[icon] 704 if self.icons.has_key(icon): i = self.icons[icon]
716 name = xml_dom._get_nodeName() 705
717 logger.debug("Text, icon and name set\n" + text + "\n" + icon + "\n" + name)
718 if prev_node: 706 if prev_node:
719 if prev_node == parent_node: new_tree_node = self.PrependItem(parent_node, text, i, i) 707 if prev_node == parent_node: new_tree_node = self.PrependItem(parent_node, name, i, i)
720 else: new_tree_node = self.InsertItem(parent_node,prev_node, text, i, i) 708 else: new_tree_node = self.InsertItem(parent_node, prev_node, name, i, i)
721 else: new_tree_node = self.AppendItem(parent_node, text, i, i) 709 else: new_tree_node = self.AppendItem(parent_node, name, i, i)
722 710
723 logger.debug("Node Added to tree") 711 logger.debug("Node Added to tree")
724 #create a nodehandler or continue loading xml into tree 712 #create a nodehandler or continue loading xml into tree
725 if name == "nodehandler": 713 if xml_element.tag == "nodehandler":
726 #wx.BeginBusyCursor()
727 logger.debug("We have a Nodehandler")
728 try: 714 try:
729 py_class = xml_dom.getAttribute("class") 715 py_class = xml_element.get("class")
730 logger.debug("nodehandler class: " + py_class) 716 logger.debug("nodehandler class: " + py_class)
731 if not self.nodehandlers.has_key(py_class): 717 if not self.nodehandlers.has_key(py_class):
732 raise Exception, "Unknown Nodehandler for " + py_class 718 raise Exception("Unknown Nodehandler for " + py_class)
733 self.nodes[self.id] = self.nodehandlers[py_class](xml_dom, new_tree_node) 719 self.nodes[self.id] = self.nodehandlers[py_class](xml_element, new_tree_node)
734 self.SetPyData(new_tree_node, self.nodes[self.id]) 720 self.SetPyData(new_tree_node, self.nodes[self.id])
735 logger.debug("Node Data set") 721 logger.debug("Node Data set")
736 bmp = self.nodes[self.id].get_scaled_bitmap(16,16) 722 bmp = self.nodes[self.id].get_scaled_bitmap(16,16)
737 if bmp: self.cached_load_of_image(bmp,new_tree_node,) 723 if bmp: self.cached_load_of_image(bmp,new_tree_node,)
738 logger.debug("Node Icon loaded") 724 logger.debug("Node Icon loaded")
739 self.id = self.id + 1 725 self.id = self.id + 1
740 except Exception, er: 726 except Exception, er:
741 logger.general(traceback.format_exc()) 727 logger.exception(traceback.format_exc())
742 #logger.debug("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), True)?indent? 728 # was deleted -- should we delete non-nodehandler nodes then?
743 self.Delete(new_tree_node) 729 #self.Delete(new_tree_node)
744 parent = xml_dom._get_parentNode() 730 #parent = xml_dom._get_parentNode()
745 parent.removeChild(xml_dom) 731 #parent.removeChild(xml_dom)
746 return new_tree_node 732 return new_tree_node
747 733
748 @debugging
749 def cached_load_of_image(self, bmp_in, new_tree_node): 734 def cached_load_of_image(self, bmp_in, new_tree_node):
750 image_list = self.GetImageList() 735 image_list = self.GetImageList()
751 img = wx.ImageFromBitmap(bmp_in) 736 img = wx.ImageFromBitmap(bmp_in)
752 img_data = img.GetData() 737 img_data = img.GetData()
753 image_index = None 738 image_index = None
754 for key in self.image_cache.keys(): 739 for key in self.image_cache.keys():
755 if self.image_cache[key] == str(img_data): 740 if self.image_cache[key] == str(img_data):
756 image_index = key 741 image_index = key
757 break 742 break
758
759 if image_index is None: 743 if image_index is None:
760 image_index = image_list.Add(bmp_in) 744 image_index = image_list.Add(bmp_in)
761 self.image_cache[image_index] = img_data 745 self.image_cache[image_index] = img_data
762 self.SetItemImage(new_tree_node,image_index) 746 self.SetItemImage(new_tree_node,image_index)
763 self.SetItemImage(new_tree_node,image_index, wx.TreeItemIcon_Selected) 747 self.SetItemImage(new_tree_node,image_index, wx.TreeItemIcon_Selected)
764 return image_index 748 return image_index
765 749
766 @debugging
767 def on_rclick(self, evt): 750 def on_rclick(self, evt):
768 pt = evt.GetPosition() 751 pt = evt.GetPosition()
769 (item, flag) = self.HitTest(pt) 752 (item, flag) = self.HitTest(pt)
770 if item.IsOk(): 753 if item.IsOk():
771 obj = self.GetPyData(item) 754 obj = self.GetPyData(item)
772 self.SelectItem(item) 755 self.SelectItem(item)
773 if(isinstance(obj,core.node_handler)): obj.on_rclick(evt) 756 if(isinstance(obj,core.node_handler)): obj.on_rclick(evt)
774 else: self.PopupMenu(self.top_menu) 757 else: self.PopupMenu(self.top_menu)
775 else: self.PopupMenu(self.top_menu,pt) 758 else: self.PopupMenu(self.top_menu,pt)
776 759
777 @debugging
778 def on_ldclick(self, evt): 760 def on_ldclick(self, evt):
779 self.rename_flag = 0 761 self.rename_flag = 0
780 pt = evt.GetPosition() 762 pt = evt.GetPosition()
781 (item, flag) = self.HitTest(pt) 763 (item, flag) = self.HitTest(pt)
782 if item.IsOk(): 764 if item.IsOk():
787 action = self.settings.get_setting("treedclick") 769 action = self.settings.get_setting("treedclick")
788 if action == "use": obj.on_use(evt) 770 if action == "use": obj.on_use(evt)
789 elif action == "design": obj.on_design(evt) 771 elif action == "design": obj.on_design(evt)
790 elif action == "print": obj.on_html_view(evt) 772 elif action == "print": obj.on_html_view(evt)
791 elif action == "chat": self.on_send_to_chat(evt) 773 elif action == "chat": self.on_send_to_chat(evt)
792 774
793 @debugging
794 def on_left_down(self, evt): 775 def on_left_down(self, evt):
795 pt = evt.GetPosition() 776 pt = evt.GetPosition()
796 (item, flag) = self.HitTest(pt) 777 (item, flag) = self.HitTest(pt)
797 if item.IsOk() and self.was_labeling: 778 if item.IsOk() and self.was_labeling:
798 self.SelectItem(item) 779 self.SelectItem(item)
801 elif (flag & wx.TREE_HITTEST_ONITEMLABEL) == wx.TREE_HITTEST_ONITEMLABEL and self.IsSelected(item): 782 elif (flag & wx.TREE_HITTEST_ONITEMLABEL) == wx.TREE_HITTEST_ONITEMLABEL and self.IsSelected(item):
802 # this next if tests to ensure that the mouse up occurred over a label, and not the icon 783 # this next if tests to ensure that the mouse up occurred over a label, and not the icon
803 self.rename_flag = 1 784 self.rename_flag = 1
804 else: self.SelectItem(item) 785 else: self.SelectItem(item)
805 evt.Skip() 786 evt.Skip()
806 787
807 @debugging
808 def on_left_up(self, evt): 788 def on_left_up(self, evt):
809 if self.dragging: 789 if self.dragging:
810 cur = wx.StockCursor(wx.CURSOR_ARROW) 790 cur = wx.StockCursor(wx.CURSOR_ARROW)
811 self.SetCursor(cur) 791 self.SetCursor(cur)
812 self.dragging = False 792 self.dragging = False
817 self.SelectItem(item) 797 self.SelectItem(item)
818 if(isinstance(obj,core.node_handler)): 798 if(isinstance(obj,core.node_handler)):
819 obj.on_drop(evt) 799 obj.on_drop(evt)
820 self.drag_obj = None 800 self.drag_obj = None
821 801
822 @debugging 802 def traverse(self, root, function, data=None, recurse=True):
803 child, cookie = self.GetFirstChild(root)
804 while child.IsOk():
805 function(child, data)
806 if recurse:
807 self.traverse(child, function, data)
808 child, cookie = self.GetNextChild(root, cookie)
809
823 def on_label_change(self, evt): 810 def on_label_change(self, evt):
824 item = evt.GetItem() 811 item = evt.GetItem()
825 txt = evt.GetLabel() 812 txt = evt.GetLabel()
826 self.was_labeling = 0 813 self.was_labeling = 0
827 self.rename_flag = 0 814 self.rename_flag = 0
828 if txt != "": 815 if txt != "":
829 obj = self.GetPyData(item) 816 obj = self.GetPyData(item)
830 obj.master_dom.setAttribute('name',txt) 817 obj.xml_root.setAttribute('name',txt)
831 else: evt.Veto() 818 else: evt.Veto()
832 819
833 @debugging
834 def on_label_begin(self, evt): 820 def on_label_begin(self, evt):
835 if not self.rename_flag: evt.Veto() 821 if not self.rename_flag: evt.Veto()
836 else: 822 else:
837 self.was_labeling = 1 823 self.was_labeling = 1
838 item = evt.GetItem() 824 item = evt.GetItem()
839 if item == self.GetRootItem(): 825 if item == self.GetRootItem():
840 evt.Veto() 826 evt.Veto()
841 827
842 @debugging
843 def on_drag(self, evt): 828 def on_drag(self, evt):
844 self.rename_flag = 0 829 self.rename_flag = 0
845 item = self.GetSelection() 830 item = self.GetSelection()
846 obj = self.GetPyData(item) 831 obj = self.GetPyData(item)
847 self.SelectItem(item) 832 self.SelectItem(item)
848 if(isinstance(obj,core.node_handler) and obj.drag): 833 if(isinstance(obj,core.node_handler) and obj.drag):
849 self.dragging = True 834 self.dragging = True
850 cur = wx.StockCursor(wx.CURSOR_HAND) 835 cur = wx.StockCursor(wx.CURSOR_HAND)
851 self.SetCursor(cur) 836 self.SetCursor(cur)
852 self.drag_obj = obj 837 self.drag_obj = obj
853 838
854 @debugging
855 def is_parent_node(self, node, compare_node): 839 def is_parent_node(self, node, compare_node):
856 parent_node = self.GetItemParent(node) 840 parent_node = self.GetItemParent(node)
857 if compare_node == parent_node: 841 if compare_node == parent_node:
858 logger.debug("parent node") 842 logger.debug("parent node")
859 return 1 843 return 1
869 CTRL_DESIGN = wx.NewId() 853 CTRL_DESIGN = wx.NewId()
870 CTRL_CHAT = wx.NewId() 854 CTRL_CHAT = wx.NewId()
871 CTRL_PRINT = wx.NewId() 855 CTRL_PRINT = wx.NewId()
872 856
873 class gametree_prop_dlg(wx.Dialog): 857 class gametree_prop_dlg(wx.Dialog):
874 @debugging 858
875 def __init__(self, parent, settings): 859 def __init__(self, parent, settings):
876 wx.Dialog.__init__(self, parent, wx.ID_ANY, "Game Tree Properties") 860 wx.Dialog.__init__(self, parent, wx.ID_ANY, "Game Tree Properties")
877 self.settings = settings 861 self.settings = settings
878 862
879 #sizers 863 #sizers
928 self.SetSizer(sizers['main']) 912 self.SetSizer(sizers['main'])
929 self.SetAutoLayout(True) 913 self.SetAutoLayout(True)
930 self.Fit() 914 self.Fit()
931 self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK) 915 self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK)
932 916
933 @debugging 917
934 def on_ok(self,evt): 918 def on_ok(self,evt):
935 self.settings.set_setting("gametree",self.ctrls[CTRL_TREE_FILE].GetValue()) 919 self.settings.change("gametree",self.ctrls[CTRL_TREE_FILE].GetValue())
936 self.settings.set_setting("SaveGameTreeOnExit",str(self.ctrls[CTRL_YES].GetValue())) 920 self.settings.change("SaveGameTreeOnExit",str(self.ctrls[CTRL_YES].GetValue()))
937 if self.ctrls[CTRL_USE].GetValue(): self.settings.set_setting("treedclick","use") 921 if self.ctrls[CTRL_USE].GetValue(): self.settings.change("treedclick","use")
938 elif self.ctrls[CTRL_DESIGN].GetValue(): self.settings.set_setting("treedclick","design") 922 elif self.ctrls[CTRL_DESIGN].GetValue(): self.settings.change("treedclick","design")
939 elif self.ctrls[CTRL_PRINT].GetValue(): self.settings.set_setting("treedclick","print") 923 elif self.ctrls[CTRL_PRINT].GetValue(): self.settings.change("treedclick","print")
940 elif self.ctrls[CTRL_CHAT].GetValue(): self.settings.set_setting("treedclick","chat") 924 elif self.ctrls[CTRL_CHAT].GetValue(): self.settings.change("treedclick","chat")
941 self.EndModal(wx.ID_OK) 925 self.EndModal(wx.ID_OK)