Mercurial > traipse
changeset 18:97265586402b ornery-orc
Traipse 'OpenRPG' {090827-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:
Update Manager is now in version 0.8. While not every button works, users can now browse the different revisions and their different changesets. The code has been refined some with feature from Core added to it. A Crash report is now created if the users software crashes. Update Manager has been moved to the Traipse Suite menu item, and a Debug Console as been added as well.
line wrap: on
line diff
--- a/orpg/chat/__init__.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/chat/__init__.py Thu Aug 27 01:04:43 2009 -0500 @@ -0,0 +1,1 @@ +
--- a/orpg/chat/chat_msg.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/chat/chat_msg.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,8 +29,10 @@ __version__ = "$Id: chat_msg.py,v 1.15 2006/11/04 21:24:19 digitalxero Exp $" -import orpg.orpg_xml -from chat_version import CHAT_VERSION +from orpg.orpgCore import * +from chat_version import CHAT_VERSION +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging CHAT_MESSAGE = 1 WHISPER_MESSAGE = 2 @@ -39,20 +41,24 @@ SYSTEM_MESSAGE = 5 WHISPER_EMOTE_MESSAGE = 6 -class chat_msg: - def __init__(self,xml_text="<chat type=\"1\" version=\""+CHAT_VERSION+"\" alias=\"\" ></chat>"): +class chat_msg: + @debugging + def __init__(self,xml_text="<chat type=\"1\" version=\""+CHAT_VERSION+"\" alias=\"\" ></chat>"): self.chat_dom = None - self.takexml(xml_text) - + self.takexml(xml_text) + + @debugging def __del__(self): if self.chat_dom: self.chat_dom.unlink() - + + @debugging def toxml(self): - return orpg.orpg_xml.toxml(self.chat_dom) - - def takexml(self,xml_text): - xml_dom = orpg.orpg_xml.parseXml(xml_text) + return component.get('xml').toxml(self.chat_dom) + + @debugging + def takexml(self,xml_text): + xml_dom = component.get('xml').parseXml(xml_text) node_list = xml_dom.getElementsByTagName("chat") if len(node_list) < 1: print "Warning: no <chat/> elements found in DOM." @@ -60,32 +66,40 @@ if len(node_list) > 1: print "Found more than one instance of <" + self.tagname + "/>. Taking first one" self.takedom(node_list[0]) - + + @debugging def takedom(self,xml_dom): if self.chat_dom: self.text_node = None self.chat_dom.unlink() self.chat_dom = xml_dom - self.text_node = orpg.orpg_xml.safe_get_text_node(self.chat_dom) - + self.text_node = component.get('xml').safe_get_text_node(self.chat_dom) + + @debugging def set_text(self,text): - text = orpg.orpg_xml.strip_text(text) + text = component.get('xml').strip_text(text) self.text_node._set_nodeValue(text) - + + @debugging def set_type(self,type): self.chat_dom.setAttribute("type",str(type)) - + + @debugging def get_type(self): return int(self.chat_dom.getAttribute("type")) - + + @debugging def set_alias(self,alias): self.chat_dom.setAttribute("alias",alias) - + + @debugging def get_alias(self): return self.chat_dom.getAttribute("alias") - + + @debugging def get_text(self): return self.text_node._get_nodeValue() - + + @debugging def get_version(self): return self.chat_dom.getAttribute("version")
--- a/orpg/chat/chat_util.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/chat/chat_util.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,7 +1,10 @@ # utility function; see Post() in chatwnd.py import re -import string +import string +from orpg.orpgCore import * +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging #============================================ # simple_html_repair(string) @@ -15,8 +18,9 @@ # to cause issues with the chat display # # Created 04-25-2005 by Snowdog -#============================================= -def simple_html_repair(string): +#============================================= +@debugging +def simple_html_repair(string): "Returns string with extra > symbols to isolate badly formated HTML" #walk though string checking positions of < and > tags. first_instance = string.find('<') @@ -67,24 +71,26 @@ if diff > 0: for d in range(1,diff): string = string+">" + return string - return string - -def strip_unicode(txt): +""" Depricated! Might as well use the already made component.get('xml') +def strip_unicode(txt): for i in xrange(len(txt)): if txt[i] not in string.printable: try: txt = txt.replace(txt[i], '&#' + str(ord(txt[i])) + ';') except: txt = txt.replace(txt[i], '{?}') - return txt + return txt +""" #================================================ # strip_script_tags(string) # # removes all script tags (start and end) # 04-26-2005 Snowdog -#================================================ +#================================================ +@debugging def strip_script_tags(string): #kill the <script> issue p = re.compile( '<(\s*)(/*)[Ss][Cc][Rr][Ii][Pp][Tt](.*?)>') @@ -97,6 +103,7 @@ # removes all li tags (start and end) # 05-13-2005 #================================================ +@debugging def strip_li_tags(string): #kill the <li> issue string = re.sub( r'<(\s*)[Ll][Ii](.*?)>', r'<b><font color="#000000" size=+1>*</font></b> ', string) @@ -111,6 +118,7 @@ # through legitimate means such as the OpenRPG settings. # 07-27-2005 by mDuo13 #================================================ +@debugging def strip_body_tags(string): bodytag_regex = re.compile(r"""<\/?body.*?>""", re.I) string = re.sub(bodytag_regex, "", string) @@ -128,7 +136,8 @@ # algorithm simply closes them, allowing them to be # used legitimately without causing much annoyance. # 07-27-2005 mDuo13 -#================================================ +#================================================ +@debugging def strip_misalignment_tags(string): alignment_regex = re.compile(r"""<p([^>]*?)align\s*=\s*('.*?'|".*?"|[^\s>]*)(.*?)>""", re.I) string = re.sub(alignment_regex, "<p\\1\\3>", string) @@ -148,7 +157,8 @@ # removes all img tags (start and end) # 05-13-2005 # redone 07-11-2005 by mDuo13 -#================================================ +#================================================ +@debugging def strip_img_tags(string): #This is a Settings definable feature, Allowing users to enable or disable image display to fix the client crash due to large img posted to chat. #p = re.sub( r'<(\s*)(/*)[Ii][Mm][Gg][ ][Ss][Rr][Cc][=](.*?)>', r'<!-- img tag removed //--> <a href=\3>\3</a>', string)
--- a/orpg/chat/chatwnd.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/chat/chatwnd.py Thu Aug 27 01:04:43 2009 -0500 @@ -45,11 +45,11 @@ ## from orpg.orpg_windows import * from orpg.player_list import WG_LIST -import orpg.dirpath +from orpg.dirpath import dir_struct import orpg.tools.rgbhex import orpg.tools.inputValidator -from orpg.tools.metamenus import MenuEx -from orpg.orpgCore import open_rpg +#from orpg.tools.metamenus import MenuEx #Needed? + import webbrowser from string import * from orpg.orpg_version import VERSION @@ -65,7 +65,14 @@ import cStringIO # for reading inline imagedata as a stream from HTMLParser import HTMLParser import chat_util -import traceback +import traceback +from wx.lib.expando import EVT_ETC_LAYOUT_NEEDED + +from orpg.tools.validate import validate +from orpg.tools.orpg_settings import settings +from orpg.orpgCore import component +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging NEWCHAT = False try: import wx.webview @@ -76,33 +83,40 @@ # Global parser for stripping HTML tags: # The 'tag stripping' is implicit, because this parser echoes every # type of html data *except* the tags. -class HTMLStripper(HTMLParser): +class HTMLStripper(HTMLParser): + @debugging def __init__(self): self.accum = "" - self.special_tags = ['hr', 'br', 'img'] + self.special_tags = ['hr', 'br', 'img'] + @debugging def handle_data(self, data): # quote cdata literally - self.accum += data + self.accum += data + @debugging def handle_entityref(self, name): # entities must be preserved exactly - self.accum += "&" + name + ";" + self.accum += "&" + name + ";" + @debugging def handle_starttag(self, tag, attrs): if tag in self.special_tags: self.accum += '<' + tag for attrib in attrs: self.accum += ' ' + attrib[0] + '="' + attrib[1] + '"' - self.accum += '>' + self.accum += '>' + @debugging def handle_charref(self, name): # charrefs too self.accum += "&#" + name + ";" htmlstripper = HTMLStripper() -# utility function; see Post(). +# utility function; see Post(). +@debugging def strip_html(string): "Return string tripped of html tags." htmlstripper.reset() htmlstripper.accum = "" htmlstripper.feed(string) htmlstripper.close() - return htmlstripper.accum + return htmlstripper.accum -def log( settings, text ): +@debugging +def log( settings, c, text ): filename = settings.get_setting('GameLogPrefix') if filename > '' and filename[0] != commands.ANTI_LOG_CHAR: filename = filename + time.strftime( '-%Y-%m-%d.html', time.localtime( time.time() ) ) @@ -111,11 +125,11 @@ header = '[%s] : ' % ( timestamp ); if settings.get_setting('TimeStampGameLog') != '1': header = '' try: - f = open( orpg.dirpath.dir_struct["user"] + filename, 'a' ) - f.write( '%s%s<br />\n' % ( header, text ) ) + f = open( dir_struct["user"] + filename, 'a' ) + f.write( '<div class="'+c+'">%s%s</div>\n' % ( header, text ) ) f.close() except: - print "could not open " + orpg.dirpath.dir_struct["user"] + filename + ", ignoring..." + print "could not open " + dir_struct["user"] + filename + ", ignoring..." pass # This class displayes the chat information in html? @@ -133,8 +147,10 @@ # !self : instance of self # !parent : # !id : + @debugging def __init__(self, parent, id): - wx.html.HtmlWindow.__init__(self, parent, id, style=wx.SUNKEN_BORDER | wx.html.HW_SCROLLBAR_AUTO|wx.NO_FULL_REPAINT_ON_RESIZE) + wx.html.HtmlWindow.__init__(self, parent, id, + style=wx.SUNKEN_BORDER|wx.html.HW_SCROLLBAR_AUTO|wx.NO_FULL_REPAINT_ON_RESIZE) self.parent = parent self.build_menu() self.Bind(wx.EVT_LEFT_UP, self.LeftUp) @@ -142,41 +158,50 @@ if "gtk2" in wx.PlatformInfo: self.SetStandardFonts() # def __init__ - end + @debugging def onPopup(self, evt): self.PopupMenu(self.menu) + @debugging def LeftUp(self, event): event.Skip() wx.CallAfter(self.parent.set_chat_text_focus, None) + @debugging def build_menu(self): self.menu = wx.Menu() item = wx.MenuItem(self.menu, wx.ID_ANY, "Copy", "Copy") self.Bind(wx.EVT_MENU, self.OnM_EditCopy, item) self.menu.AppendItem(item) + @debugging def OnM_EditCopy(self, evt): wx.TheClipboard.Open() wx.TheClipboard.Clear() wx.TheClipboard.SetData(wx.TextDataObject(self.SelectionToText())) wx.TheClipboard.Close() + @debugging def scroll_down(self): maxrange = self.GetScrollRange(wx.VERTICAL) pagesize = self.GetScrollPageSize(wx.VERTICAL) self.Scroll(-1, maxrange-pagesize) + @debugging def mouse_wheel(self, event): amt = event.GetWheelRotation() units = amt/(-(event.GetWheelDelta())) self.ScrollLines(units*3) + @debugging def Header(self): return '<html><body bgcolor="' + self.parent.bgcolor + '" text="' + self.parent.textcolor + '">' + @debugging def StripHeader(self): return self.GetPageSource().replace(self.Header(), '') + @debugging def GetPageSource(self): return self.GetParser().GetSource() @@ -184,12 +209,14 @@ # # !self : instance of self # !linkinfo : instance of a class that contains the link information + @debugging def OnLinkClicked(self, linkinfo): href = linkinfo.GetHref() wb = webbrowser.get() wb.open(href) # def OnLinkClicked - end + @debugging def CalculateAllFonts(self, defaultsize): return [int(defaultsize * 0.4), int(defaultsize * 0.7), @@ -199,6 +226,7 @@ int(defaultsize * 2), int(defaultsize * 2.5)] + @debugging def SetDefaultFontAndSize(self, fontname, fontsize): """Set 'fontname' to the default chat font. Returns current font settings in a (fontname, fontsize) tuple.""" @@ -208,72 +236,87 @@ # class chat_html_window - end if NEWCHAT: class ChatHtmlWindow(wx.webview.WebView): + @debugging def __init__(self, parent, id): wx.webview.WebView.__init__(self, parent, id) - self.parent = parent self.__font = wx.Font(10, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, faceName='Ariel') - self.build_menu() self.Bind(wx.EVT_LEFT_UP, self.LeftUp) self.Bind(wx.EVT_RIGHT_DOWN, self.onPopup) self.Bind(wx.webview.EVT_WEBVIEW_BEFORE_LOAD, self.OnLinkClicked) #Wrapers so I dont have to add special Code + @debugging def SetPage(self, htmlstring): self.SetPageSource(htmlstring) + @debugging def AppendToPage(self, htmlstring): self.SetPageSource(self.GetPageSource() + htmlstring) + @debugging def GetFont(self): return self.__font + @debugging def CalculateAllFonts(self, defaultsize): return + @debugging def SetDefaultFontAndSize(self, fontname, fontsize): - self.__font = wx.Font(int(fontsize), wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, faceName=fontname) + self.__font = wx.Font(int(fontsize), + wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, + wx.FONTWEIGHT_NORMAL, faceName=fontname) try: self.SetPageSource(self.Header() + self.StripHeader()) except Exception, e: print e return (self.GetFont().GetFaceName(), self.GetFont().GetPointSize()) #Events + @debugging def OnLinkClicked(self, linkinfo): href = linkinfo.GetHref() wb = webbrowser.get() wb.open(href) + @debugging def onPopup(self, evt): self.PopupMenu(self.menu) + @debugging def LeftUp(self, event): event.Skip() wx.CallAfter(self.parent.set_chat_text_focus, None) + @debugging def OnM_EditCopy(self, evt): self.Copy() #Cutom Methods + @debugging def Header(self): return "<html><head><style>body {font-size: " + str(self.GetFont().GetPointSize()) + "px;font-family: " + self.GetFont().GetFaceName() + ";color: " + self.parent.textcolor + ";background-color: " + self.parent.bgcolor + ";margin: 0;padding: 0 0;height: 100%;}</style></head><body>" + @debugging def StripHeader(self): tmp = self.GetPageSource().split('<BODY>') if tmp[-1].find('<body>') > -1: tmp = tmp[-1].split('<body>') return tmp[-1] + @debugging def build_menu(self): self.menu = wx.Menu() item = wx.MenuItem(self.menu, wx.ID_ANY, "Copy", "Copy") self.Bind(wx.EVT_MENU, self.OnM_EditCopy, item) self.menu.AppendItem(item) + @debugging def scroll_down(self): maxrange = self.GetScrollRange(wx.VERTICAL) pagesize = self.GetScrollPageSize(wx.VERTICAL) self.Scroll(-1, maxrange-pagesize) + @debugging def mouse_wheel(self, event): amt = event.GetWheelRotation() units = amt/(-(event.GetWheelDelta())) @@ -306,19 +349,19 @@ # OnPageChanged(self, event) # set_default_font(self, font, fontsize) -class chat_notebook(orpgTabberWnd): +class chat_notebook(orpgTabberWnd): + @debugging def __init__(self, parent, size): - self.log = open_rpg.get_component("log") - self.log.log("Enter chat_notebook", ORPG_DEBUG) - orpgTabberWnd.__init__(self, parent, True, size=size, style=FNB.FNB_DROPDOWN_TABS_LIST|FNB.FNB_NO_NAV_BUTTONS|FNB.FNB_MOUSE_MIDDLE_CLOSES_TABS) - self.settings = open_rpg.get_component("settings") + orpgTabberWnd.__init__(self, parent, True, size=size, + style=FNB.FNB_DROPDOWN_TABS_LIST|FNB.FNB_NO_NAV_BUTTONS|FNB.FNB_MOUSE_MIDDLE_CLOSES_TABS) + self.settings = component.get("settings") self.whisper_tabs = [] self.group_tabs = [] self.null_tabs = [] self.il = wx.ImageList(16, 16) - bmp = wx.Bitmap(orpg.dirpath.dir_struct["icon"]+'player.gif') + bmp = wx.Bitmap(dir_struct["icon"]+'player.gif') self.il.Add(bmp) - bmp = wx.Bitmap(orpg.dirpath.dir_struct["icon"]+'clear.gif') + bmp = wx.Bitmap(dir_struct["icon"]+'clear.gif') self.il.Add(bmp) self.SetImageList(self.il) # Create "main" chatpanel tab, undeletable, connected to 'public' room. @@ -338,68 +381,62 @@ if self.settings.get_setting("GMWhisperTab") == '1': self.create_gm_tab() self.SetSelection(0) - self.log.log("Exit chat_notebook", ORPG_DEBUG) - + + @debugging def get_tab_index(self, chatpanel): "Return the index of a chatpanel in the wxNotebook." - self.log.log("Enter chat_notebook->get_tab_index(self, chatpanel)", ORPG_DEBUG) for i in xrange(self.GetPageCount()): if (self.GetPage(i) == chatpanel): - self.log.log("Exit chat_notebook->get_tab_index(self, chatpanel)", ORPG_DEBUG) return i - + + @debugging def create_gm_tab(self): - self.log.log("Enter chat_notebook->create_gm_tab(self)", ORPG_DEBUG) if self.GMChatPanel == None: self.GMChatPanel = chat_panel(self, -1, MAIN_TAB, 'gm') self.AddPage(self.GMChatPanel, "GM", False) self.SetPageImage(self.GetPageCount()-1, 1) self.GMChatPanel.chatwnd.SetDefaultFontAndSize(self.font, self.fontsize) - self.log.log("Exit chat_notebook->create_gm_tab(self)", ORPG_DEBUG) - + + @debugging def create_whisper_tab(self, playerid): "Add a new chatpanel directly connected to integer 'playerid' via whispering." - self.log.log("Enter chat_notebook->create_whisper_tab(self," + str(playerid) +")", ORPG_DEBUG) private_tab = chat_panel(self, -1, WHISPER_TAB, playerid) playername = strip_html(self.MainChatPanel.session.get_player_by_player_id(playerid)[0]) self.AddPage(private_tab, playername, False) private_tab.chatwnd.SetDefaultFontAndSize(self.font, self.fontsize) self.whisper_tabs.append(private_tab) self.newMsg(self.GetPageCount()-1) - self.AliasLib = open_rpg.get_component('alias') + self.AliasLib = component.get('alias') wx.CallAfter(self.AliasLib.RefreshAliases) - self.log.log("Exit chat_notebook->create_whisper_tab(self, playerid)", ORPG_DEBUG) return private_tab - + + @debugging def create_group_tab(self, group_name): "Add a new chatpanel directly connected to integer 'playerid' via whispering." - self.log.log("Enter chat_notebook->create_group_tab(self, group_name)", ORPG_DEBUG) private_tab = chat_panel(self, -1, GROUP_TAB, group_name) self.AddPage(private_tab, group_name, False) private_tab.chatwnd.SetDefaultFontAndSize(self.font, self.fontsize) self.group_tabs.append(private_tab) self.newMsg(self.GetPageCount()-1) - self.AliasLib = open_rpg.get_component('alias') + self.AliasLib = component.get('alias') wx.CallAfter(self.AliasLib.RefreshAliases) - self.log.log("Exit chat_notebook->create_group_tab(self, group_name)", ORPG_DEBUG) return private_tab - + + @debugging def create_null_tab(self, tab_name): "Add a new chatpanel directly connected to integer 'playerid' via whispering." - self.log.log("Enter chat_notebook->create_null_tab(self, tab_name)", ORPG_DEBUG) private_tab = chat_panel(self, -1, NULL_TAB, tab_name) self.AddPage(private_tab, tab_name, False) private_tab.chatwnd.SetDefaultFontAndSize(self.font, self.fontsize) self.null_tabs.append(private_tab) self.newMsg(self.GetPageCount()-1) - self.AliasLib = open_rpg.get_component('alias') + self.AliasLib = component.get('alias') wx.CallAfter(self.AliasLib.RefreshAliases) - self.log.log("Exit chat_notebook->create_null_tab(self, tab_name)", ORPG_DEBUG) return private_tab - + + @debugging def onCloseTab(self, evt): - self.log.log("Enter chat_notebook->onCloseTab(self, evt)", ORPG_DEBUG) try: tabid = evt.GetSelection() except: tabid = self.GetSelection() @@ -426,28 +463,24 @@ if panel in self.whisper_tabs: self.whisper_tabs.remove(panel) elif panel in self.group_tabs: self.group_tabs.remove(panel) elif panel in self.null_tabs: self.null_tabs.remove(panel) - self.log.log("Exit chat_notebook->onCloseTab(self, evt)", ORPG_DEBUG) - + + @debugging def newMsg(self, tabid): - self.log.log("Enter chat_notebook->newMsg(self, tabid)", ORPG_DEBUG) if tabid != self.GetSelection(): self.SetPageImage(tabid, 0) - self.log.log("Exit chat_notebook->newMsg(self, tabid)", ORPG_DEBUG) - + + @debugging def onPageChanging(self, event): """When private chattabs are selected, set the bitmap back to 'normal'.""" - self.log.log("Enter chat_notebook->onPageChanging(self, event)", ORPG_DEBUG) event.Skip() - self.log.log("Exit chat_notebook->onPageChanging(self, event)", ORPG_DEBUG) - + + @debugging def onPageChanged(self, event): """When private chattabs are selected, set the bitmap back to 'normal'.""" - self.log.log("Enter chat_notebook->onPageChanged(self, event)", ORPG_DEBUG) selected_idx = event.GetSelection() self.SetPageImage(selected_idx, 1) page = self.GetPage(selected_idx) #wx.CallAfter(page.set_chat_text_focus, 0) event.Skip() - self.log.log("Exit chat_notebook->onPageChanged(self, event)", ORPG_DEBUG) """ This class defines and builds the Chat Frame for OpenRPG @@ -489,21 +522,21 @@ !openrpg : !sendtarget: who gets outbound messages: either 'all' or a playerid """ - + + @debugging def __init__(self, parent, id, tab_type, sendtarget): - self.log = open_rpg.get_component("log") - self.log.log("Enter chat_panel", ORPG_DEBUG) - wx.Panel.__init__(self, parent, id) - self.session = open_rpg.get_component('session') - self.settings = open_rpg.get_component('settings') - self.activeplugins = open_rpg.get_component('plugins') + wx.Panel.__init__(self, parent, id) + logger._set_log_to_console(False) + self.session = component.get('session') + self.settings = component.get('settings') + self.activeplugins = component.get('plugins') self.parent = parent # who receives outbound messages, either "all" or "playerid" string self.sendtarget = sendtarget self.type = tab_type - self.sound_player = open_rpg.get_component('sound') + #self.sound_player = component.get('sound') #Removing! # create die roller manager - self.DiceManager = open_rpg.get_component('DiceManager') + #self.DiceManager = component.get('DiceManager') #Removing! # create rpghex tool self.r_h = orpg.tools.rgbhex.RGBHex() self.h = 0 @@ -525,11 +558,9 @@ self.advancedFilter = False self.lastSend = 0 # this is used to help implement the player typing indicator self.lastPress = 0 # this is used to help implement the player typing indicator - self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(wx.EVT_SIZE, self.OnSize) + self.Bind(EVT_ETC_LAYOUT_NEEDED, self.OnSize) #require to keep text at bottom of chat when text entry expands --SD self.build_ctrls() - #openrpg dir - self.root_dir = orpg.dirpath.dir_struct["home"] - # html font/fontsize is global to all the notebook tabs. StartupFont = self.settings.get_setting("defaultfont") StartupFontSize = self.settings.get_setting("defaultfontsize") if(StartupFont != "") and (StartupFontSize != ""): @@ -537,12 +568,12 @@ except: pass self.font = self.chatwnd.GetFont().GetFaceName() self.fontsize = self.chatwnd.GetFont().GetPointSize() - self.scroll_down() - self.log.log("Exit chat_panel", ORPG_DEBUG) - + self.scroll_down() + + @debugging def set_default_font(self, fontname=None, fontsize=None): - """Set all chatpanels to new default fontname/fontsize. Returns current font settings in a (fontname, fontsize) tuple.""" - self.log.log("Enter chat_panel->set_default_font(self, fontname=None, fontsize=None)", ORPG_DEBUG) + """Set all chatpanels to new default fontname/fontsize. + Returns current font settings in a (fontname, fontsize) tuple.""" if (fontname is not None): newfont = fontname else: newfont = self.font if (fontsize is not None): newfontsize = int(fontsize) @@ -551,12 +582,11 @@ self.InfoPost("Font is now " + newfont + " point size " + `newfontsize`) self.font = newfont self.fontsize = newfontsize - self.log.log("Exit chat_panel->set_default_font(self, fontname=None, fontsize=None)", ORPG_DEBUG) return (self.font, self.fontsize) - + + @debugging def build_menu(self): - self.log.log("Enter chat_panel->build_menu(self)", ORPG_DEBUG) - top_frame = open_rpg.get_component('frame') + top_frame = component.get('frame') menu = wx.Menu() item = wx.MenuItem(menu, wx.ID_ANY, "&Background color", "Background color") top_frame.Bind(wx.EVT_MENU, self.OnMB_BackgroundColor, item) @@ -591,7 +621,8 @@ tabmenu = wx.Menu() toolmenu = wx.Menu() item = wx.MenuItem(wndmenu, wx.ID_ANY, "Show Images", "Show Images", wx.ITEM_CHECK) - top_frame.Bind(wx.EVT_MENU, self.OnMB_ShowImages, item) + top_frame.Bind(wx.EVT_MENU, self.OnMB_ShowImages, item) + wndmenu.AppendItem(item) if self.settings.get_setting("Show_Images_In_Chat") == '1': item.Check(True) item = wx.MenuItem(wndmenu, wx.ID_ANY, "Strip HTML", "Strip HTML", wx.ITEM_CHECK) @@ -641,70 +672,59 @@ toolmenu.AppendItem(item) if self.settings.get_setting("AliasTool_On") == '1': item.Check(True) settingmenu.AppendMenu(wx.ID_ANY, 'Chat Tool Bars', toolmenu) - menu.AppendMenu(wx.ID_ANY, 'Chat Settings', settingmenu) + menu.AppendMenu(wx.ID_ANY, 'Chat Settings', settingmenu) top_frame.mainmenu.Insert(2, menu, '&Chat') - self.log.log("Exit chat_panel->build_menu(self)", ORPG_DEBUG) - ## Settings Menu Events + ## Settings Menu Events + @debugging def OnMB_ShowImages(self, event): - self.log.log("Enter chat_panel->OnMB_ShowImages(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("Show_Images_In_Chat", '1') else: self.settings.set_setting("Show_Images_In_Chat", '0') - self.log.log("Exit chat_panel->OnMB_ShowImages(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_StripHTML(self, event): - self.log.log("Enter chat_panel->OnMB_StripHTML(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("Sstriphtml", '1') else: self.settings.set_setting("striphtml", '0') - self.log.log("Exit chat_panel->OnMB_StripHTML(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_ChatTimeIndex(self, event): - self.log.log("Enter chat_panel->OnMB_ChatTimeIndex(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("Chat_Time_Indexing", '1') else: self.settings.set_setting("Chat_Time_Indexing", '0') - self.log.log("Exit chat_panel->OnMB_ChatTimeIndex(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_ChatAutoComplete(self, event): - self.log.log("Enter chat_panel->OnMB_ChatAutoComplete(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("SuppressChatAutoComplete", '0') else: self.settings.set_setting("SuppressChatAutoComplete", '1') - self.log.log("Exit chat_panel->OnMB_ChatAutoComplete(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_ShowIDinChat(self, event): - self.log.log("Enter chat_panel->OnMB_ShowIDinChat(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("ShowIDInChat", '1') else: self.settings.set_setting("ShowIDInChat", '0') - self.log.log("Exit chat_panel->OnMB_ShowIDinChat(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_LogTimeIndex(self, event): - self.log.log("Enter chat_panel->OnMB_LogTimeIndex(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("TimeStampGameLog", '1') else: self.settings.set_setting("TimeStampGameLog", '0') - self.log.log("Exit chat_panel->OnMB_LogTimeIndex(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_TabbedWhispers(self, event): - self.log.log("Enter chat_panel->OnMB_TabbedWhispers(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("tabbedwhispers", '1') else: self.settings.set_setting("tabbedwhispers", '0') - self.log.log("Exit chat_panel->OnMB_TabbedWhispers(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_GMTab(self, event): - self.log.log("Enter chat_panel->OnMB_GMTab(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("GMWhisperTab", '1') self.parent.create_gm_tab() else: self.settings.set_setting("GMWhisperTab", '0') - self.log.log("Exit chat_panel->OnMB_GMTab(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_GroupWhisperTabs(self, event): - self.log.log("Enter chat_panel->OnMB_GroupWhisperTabs(self, event)", ORPG_DEBUG) if event.IsChecked(): self.settings.set_setting("GroupWhisperTab", '1') else: self.settings.set_setting("GroupWhisperTab", '0') - self.log.log("Exit chat_panel->OnMB_GroupWhisperTabs(self, event)", ORPG_DEBUG) - - + + @debugging def OnMB_DiceBar(self, event): - self.log.log("Enter chat_panel->OnMB_DiceBar(self, event)", ORPG_DEBUG) act = '0' if event.IsChecked(): self.settings.set_setting("DiceButtons_On", '1') @@ -716,10 +736,9 @@ for panel in self.parent.whisper_tabs: panel.toggle_dice(act) for panel in self.parent.group_tabs: panel.toggle_dice(act) for panel in self.parent.null_tabs: panel.toggle_dice(act) - self.log.log("Exit chat_panel->OnMB_DiceBar(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_FormatButtons(self, event): - self.log.log("Enter chat_panel->OnMB_FormatButtons(self, event)", ORPG_DEBUG) act = '0' if event.IsChecked(): self.settings.set_setting("FormattingButtons_On", '1') @@ -732,10 +751,9 @@ for panel in self.parent.whisper_tabs: panel.toggle_formating(act) for panel in self.parent.group_tabs: panel.toggle_formating(act) for panel in self.parent.null_tabs: panel.toggle_formating(act) - self.log.log("Exit chat_panel->OnMB_FormatButtons(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_AliasTool(self, event): - self.log.log("Enter chat_panel->OnMB_AliasTool(self, event)", ORPG_DEBUG) act = '0' if event.IsChecked(): self.settings.set_setting("AliasTool_On", '1') @@ -747,11 +765,10 @@ for panel in self.parent.whisper_tabs: panel.toggle_alias(act) for panel in self.parent.group_tabs: panel.toggle_alias(act) for panel in self.parent.null_tabs:panel.toggle_alias(act) - self.log.log("Exit chat_panel->OnMB_AliasTool(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_BackgroundColor(self, event): - self.log.log("Enter chat_panel->OnMB_BackgroundColor(self, event)", ORPG_DEBUG) - top_frame = open_rpg.get_component('frame') + top_frame = component.get('frame') hexcolor = self.get_color() if hexcolor != None: self.bgcolor = hexcolor @@ -770,11 +787,10 @@ top_frame.players.SetForegroundColour('black') top_frame.players.Refresh() self.chatwnd.scroll_down() - self.log.log("Exit chat_panel->OnMB_BackgroundColor(self, event)", ORPG_DEBUG) - + + @debugging def OnMB_TextColor(self, event): - self.log.log("Enter chat_panel->OnMB_TextColor(self, event)", ORPG_DEBUG) - top_frame = open_rpg.get_component('frame') + top_frame = component.get('frame') hexcolor = self.get_color() if hexcolor != None: self.textcolor = hexcolor @@ -793,41 +809,38 @@ top_frame.players.SetForegroundColour('black') top_frame.players.Refresh() self.chatwnd.scroll_down() - self.log.log("Exit chat_panel->OnMB_TextColor(self, event)", ORPG_DEBUG) - - + + @debugging def get_hot_keys(self): - self.log.log("Enter chat_panel->get_hot_keys(self)", ORPG_DEBUG) # dummy menus for hotkeys self.build_menu() entries = [] entries.append((wx.ACCEL_CTRL, ord('H'), self.setChatFocusMenu.GetId())) #entries.append((wx.ACCEL_CTRL, wx.WXK_TAB, SWAP_TABS)) - self.log.log("Enter chat_panel->get_hot_keys(self)", ORPG_DEBUG) return entries - + + @debugging def forward_tabs(self, evt): - self.log.log("Enter chat_panel->swap_tabs(self, evt)", ORPG_DEBUG) self.parent.AdvanceSelection() - self.log.log("Exit chat_panel->swap_tabs(self, evt)", ORPG_DEBUG) def back_tabs(self, evt): - self.log.log("Enter chat_panel->swap_tabs(self, evt)", ORPG_DEBUG) self.parent.AdvanceSelection(False) - self.log.log("Exit chat_panel->swap_tabs(self, evt)", ORPG_DEBUG) # This subroutine builds the controls for the chat frame # - # !self : instance of self + # !self : instance of self + @debugging def build_ctrls(self): - self.log.log("Enter chat_panel->build_ctrls(self)", ORPG_DEBUG) self.chatwnd = chat_html_window(self,-1) self.set_colors() wx.CallAfter(self.chatwnd.SetPage, self.chatwnd.Header()) if (self.sendtarget == "all"): - wx.CallAfter(self.Post, self.colorize(self.syscolor, "<b>Welcome to <a href='http://www.openrpg.com'>OpenRPG</a> version " + self.version + "... </b>")) + wx.CallAfter(self.Post, self.colorize(self.syscolor, + "<b>Welcome to <a href='http://www.openrpg.com'>OpenRPG</a> version " + self.version + "... </b>")) #self.chat_cmds.on_help() - self.chattxt = orpg.tools.predTextCtrl.predTextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER |wx.TE_PROCESS_TAB|wx.TE_LINEWRAP, keyHook = self.myKeyHook, validator=None ) + self.chattxt = orpg.tools.predTextCtrl.predTextCtrl(self, -1, "", + style=wx.TE_PROCESS_ENTER |wx.TE_PROCESS_TAB|wx.TE_LINEWRAP, + keyHook = self.myKeyHook, validator=None ) self.build_bar() self.basesizer = wx.BoxSizer(wx.VERTICAL) self.basesizer.Add( self.chatwnd, 1, wx.EXPAND ) @@ -862,15 +875,15 @@ self.chattxt.Bind(wx.EVT_MOUSEWHEEL, self.chatwnd.mouse_wheel) self.chattxt.Bind(wx.EVT_CHAR, self.chattxt.OnChar) self.chattxt.Bind(wx.EVT_TEXT_COPY, self.textCopy) - self.log.log("Exit chat_panel->build_ctrls(self)", ORPG_DEBUG) # def build_ctrls - end - + + @debugging def textCopy(self, event): if self.chattxt.GetStringSelection() == '': self.chatwnd.OnM_EditCopy(None) else: self.chatwnd.Copy() - + + @debugging def build_bar(self): - self.log.log("Enter chat_panel->build_bar(self)", ORPG_DEBUG) self.toolbar_sizer = wx.BoxSizer(wx.HORIZONTAL) self.scroll_lock = None self.numDieText = None @@ -884,20 +897,20 @@ self.toolbar_sizer.Add(self.scroll_lock,0,wx.EXPAND) self.build_formating() self.build_colorbutton() - self.log.log("Exit chat_panel->build_bar(self)", ORPG_DEBUG) - + + @debugging def build_scroll(self): - self.log.log("Enter chat_panel->build_scroll(self)", ORPG_DEBUG) self.scroll_lock = wx.Button( self, wx.ID_ANY, "Scroll ON",size= wx.Size(80,25)) - self.log.log("Exit chat_panel->build_scroll(self)", ORPG_DEBUG) - + + @debugging def build_alias(self): - self.log.log("Enter chat_panel->build_alias(self)", ORPG_DEBUG) self.aliasList = wx.Choice(self, wx.ID_ANY, size=(100, 25), choices=[self.defaultAliasName]) - self.aliasButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"] + 'player.gif', 'Refresh list of aliases from Game Tree', wx.ID_ANY, '#bdbdbd' ) + self.aliasButton = createMaskedButton( self, dir_struct["icon"] + 'player.gif', + 'Refresh list of aliases from Game Tree', wx.ID_ANY, '#bdbdbd' ) self.aliasList.SetSelection(0) self.filterList = wx.Choice(self, wx.ID_ANY, size=(100, 25), choices=[self.defaultFilterName]) - self.filterButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"] + 'add_filter.gif', 'Refresh list of filters from Game Tree', wx.ID_ANY, '#bdbdbd' ) + self.filterButton = createMaskedButton( self, dir_struct["icon"] + 'add_filter.gif', + 'Refresh list of filters from Game Tree', wx.ID_ANY, '#bdbdbd' ) self.filterList.SetSelection(0) self.toolbar_sizer.Add( self.aliasButton, 0, wx.EXPAND ) self.toolbar_sizer.Add( self.aliasList,0,wx.EXPAND) @@ -905,10 +918,9 @@ self.toolbar_sizer.Add( self.filterList,0,wx.EXPAND) if self.settings.get_setting('AliasTool_On') == '0': self.toggle_alias('0') else: self.toggle_alias('1') - self.log.log("Exit chat_panel->build_alias(self)", ORPG_DEBUG) - + + @debugging def toggle_alias(self, act): - self.log.log("Enter chat_panel->toggle_alias(self, " + str(act) + ")", ORPG_DEBUG) if act == '0': self.toolbar_sizer.Show(self.aliasList, False) self.toolbar_sizer.Show(self.filterList, False) @@ -921,24 +933,22 @@ self.toolbar_sizer.Show(self.aliasButton, True) self.toolbar_sizer.Show(self.filterButton, True) self.toolbar_sizer.Layout() - self.log.log("Exit chat_panel->toggle_alias(self, act)", ORPG_DEBUG) - + + @debugging def build_text(self): - self.log.log("Enter chat_panel->build_text(self)", ORPG_DEBUG) - self.textpop_lock = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'note.gif', 'Open Text View Of Chat Session', wx.ID_ANY, '#bdbdbd') - self.log.log("Exit chat_panel->build_text(self)", ORPG_DEBUG) - + self.textpop_lock = createMaskedButton(self, dir_struct["icon"]+'note.gif', 'Open Text View Of Chat Session', wx.ID_ANY, '#bdbdbd') + + @debugging def build_dice(self): - self.log.log("Enter chat_panel->build_dice(self)", ORPG_DEBUG) self.numDieText = wx.TextCtrl( self, wx.ID_ANY, "1", size= wx.Size(25, 25), validator=orpg.tools.inputValidator.MathOnlyValidator() ) self.dieModText = wx.TextCtrl( self, wx.ID_ANY, "", size= wx.Size(50, 25), validator=orpg.tools.inputValidator.MathOnlyValidator() ) - self.d4Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d4.gif', 'Roll d4', wx.ID_ANY, '#bdbdbd') - self.d6Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d6.gif', 'Roll d6', wx.ID_ANY, '#bdbdbd') - self.d8Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d8.gif', 'Roll d8', wx.ID_ANY, '#bdbdbd') - self.d10Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d10.gif', 'Roll d10', wx.ID_ANY, '#bdbdbd') - self.d12Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d12.gif', 'Roll d12', wx.ID_ANY, '#bdbdbd') - self.d20Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d20.gif', 'Roll d20', wx.ID_ANY, '#bdbdbd') - self.d100Button = createMaskedButton(self, orpg.dirpath.dir_struct["icon"]+'b_d100.gif', 'Roll d100', wx.ID_ANY, '#bdbdbd') + self.d4Button = createMaskedButton(self, dir_struct["icon"]+'b_d4.gif', 'Roll d4', wx.ID_ANY) + self.d6Button = createMaskedButton(self, dir_struct["icon"]+'b_d6.gif', 'Roll d6', wx.ID_ANY) + self.d8Button = createMaskedButton(self, dir_struct["icon"]+'b_d8.gif', 'Roll d8', wx.ID_ANY) + self.d10Button = createMaskedButton(self, dir_struct["icon"]+'b_d10.gif', 'Roll d10', wx.ID_ANY) + self.d12Button = createMaskedButton(self, dir_struct["icon"]+'b_d12.gif', 'Roll d12', wx.ID_ANY) + self.d20Button = createMaskedButton(self, dir_struct["icon"]+'b_d20.gif', 'Roll d20', wx.ID_ANY) + self.d100Button = createMaskedButton(self, dir_struct["icon"]+'b_d100.gif', 'Roll d100', wx.ID_ANY) self.toolbar_sizer.Add( self.numDieText, 0, wx.ALIGN_CENTER | wx.EXPAND) self.toolbar_sizer.Add( self.d4Button, 0 ,wx.EXPAND) self.toolbar_sizer.Add( self.d6Button, 0 ,wx.EXPAND) @@ -950,10 +960,9 @@ self.toolbar_sizer.Add( self.dieModText, 0, wx.ALIGN_CENTER, 5 ) if self.settings.get_setting('DiceButtons_On') == '0': self.toggle_dice('0') else: self.toggle_dice('1') - self.log.log("Exit chat_panel->build_dice(self)", ORPG_DEBUG) - + + @debugging def toggle_dice(self, act): - self.log.log("Enter chat_panel->toggle_dice(self, "+ str(act) + ")", ORPG_DEBUG) if act == '0': self.toolbar_sizer.Show(self.numDieText, False) self.toolbar_sizer.Show(self.d4Button, False) @@ -976,22 +985,23 @@ self.toolbar_sizer.Show(self.d100Button, True) self.toolbar_sizer.Show(self.dieModText, True) self.toolbar_sizer.Layout() - self.log.log("Exit chat_panel->toggle_dice(self, "+ str(act) + ")", ORPG_DEBUG) - + + @debugging def build_formating(self): - self.log.log("Enter chat_panel->build_formating(self)", ORPG_DEBUG) - self.boldButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'bold.gif', 'Make the selected text Bold', wx.ID_ANY, '#bdbdbd') - self.italicButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'italic.gif', 'Italicize the selected text', wx.ID_ANY, '#bdbdbd' ) - self.underlineButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'underlined.gif', 'Underline the selected text', wx.ID_ANY, '#bdbdbd' ) + self.boldButton = createMaskedButton( self, dir_struct["icon"]+'bold.gif', + 'Make the selected text Bold', wx.ID_ANY, '#bdbdbd') + self.italicButton = createMaskedButton( self, dir_struct["icon"]+'italic.gif', + 'Italicize the selected text', wx.ID_ANY, '#bdbdbd' ) + self.underlineButton = createMaskedButton( self, dir_struct["icon"]+'underlined.gif', + 'Underline the selected text', wx.ID_ANY, '#bdbdbd' ) self.toolbar_sizer.Add( self.boldButton, 0, wx.EXPAND ) self.toolbar_sizer.Add( self.italicButton, 0, wx.EXPAND ) self.toolbar_sizer.Add( self.underlineButton, 0, wx.EXPAND ) if self.settings.get_setting('FormattingButtons_On') == '0': self.toggle_formating('0') else: self.toggle_formating('1') - self.log.log("Exit chat_panel->build_formating(self)", ORPG_DEBUG) - + + @debugging def toggle_formating(self, act): - self.log.log("Enter chat_panel->toggle_formating(self, " + str(act) + ")", ORPG_DEBUG) if act == '0': self.toolbar_sizer.Show(self.boldButton, False) self.toolbar_sizer.Show(self.italicButton, False) @@ -1002,21 +1012,23 @@ self.toolbar_sizer.Show(self.italicButton, True) self.toolbar_sizer.Show(self.underlineButton, True) self.toolbar_sizer.Layout() - self.log.log("Exit chat_panel->toggle_formating(self, " + str(act) + ")", ORPG_DEBUG) - # Heroman - Ideally, we would use static labels... + # Heroman - Ideally, we would use static labels... + @debugging def build_colorbutton(self): - self.log.log("Enter chat_panel->build_colorbutton(self)", ORPG_DEBUG) - self.color_button = wx.Button(self, wx.ID_ANY, "C",wx.Point(0,0), wx.Size(22,0)) - self.saveButton = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'save.bmp', 'Save the chatbuffer', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) - self.color_button.SetBackgroundColour(wx.BLACK) - self.color_button.SetForegroundColour(wx.WHITE) + self.color_button = createMaskedButton(self, dir_struct["icon"]+'textcolor.gif', + 'Text Color', wx.ID_ANY, '#bdbdbd', + wx.BITMAP_TYPE_GIF) + + self.saveButton = createMaskedButton(self, dir_struct["icon"]+'save.bmp', + 'Save the chatbuffer', wx.ID_ANY, + '#c0c0c0', wx.BITMAP_TYPE_BMP ) + self.color_button.SetBackgroundColour(self.settings.get_setting('mytextcolor')) self.toolbar_sizer.Add(self.color_button, 0, wx.EXPAND) - self.toolbar_sizer.Add( self.saveButton, 0, wx.EXPAND ) - self.log.log("Exit chat_panel->build_colorbutton(self)", ORPG_DEBUG) - + self.toolbar_sizer.Add(self.saveButton, 0, wx.EXPAND) + + @debugging def OnMotion(self, evt): - self.log.log("Enter chat_panel->OnMotion(self, evt)", ORPG_DEBUG) contain = self.chatwnd.GetInternalRepresentation() if contain: sx = sy = 0 @@ -1032,18 +1044,17 @@ link = lnk.GetHref() self.session.set_status_url(link) except: pass - else: self.log.log("Error, self.chatwnd.GetInternalRepresentation() return None", ORPG_GENERAL) + else: logger.general("Error, self.chatwnd.GetInternalRepresentation() return None") evt.Skip() - self.log.log("Exit chat_panel->OnMotion(self, evt)", ORPG_DEBUG) # This subroutine is registered with predTextCtrl to be run for every OnChar event # It checks if we need to send a typing message # # self: duh - # event: raw KeyEvent from OnChar() + # event: raw KeyEvent from OnChar() + @debugging def myKeyHook(self, event): - self.log.log("Enter chat_panel->myKeyHook(self, event)", ORPG_DEBUG) if self.session.get_status() == MPLAY_CONNECTED: # only do if we're connected thisPress = time.time() # thisPress is local temp variable if (thisPress - self.lastSend) > 4: # Check to see if it's been 5 seconds since our last notice @@ -1052,16 +1063,17 @@ self.lastPress = thisPress # either way, record the time of this keystroke for use in # self.typingTimerFunc() if self.settings.get_setting('SuppressChatAutoComplete') == '1': - self.log.log("Exit chat_panel->myKeyHook(self, event) return 1", ORPG_DEBUG) + logger.debug("Exit chat_panel->myKeyHook(self, event) return 1") return 1 else: - self.log.log("Exit chat_panel->myKeyHook(self, event) return 0", ORPG_DEBUG) + logger.debug("Exit chat_panel->myKeyHook(self, event) return 0") return 0 # This subroutine gets called once a second by the typing Timer # It checks if we need to send a not_typing message # - # self: duh + # self: duh + @debugging def typingTimerFunc(self, event): #following added by mDuo13 ##############refresh_counter()############## @@ -1070,8 +1082,8 @@ try: plugin.refresh_counter() except Exception, e: if str(e) != "'module' object has no attribute 'refresh_counter'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) #end mDuo13 added code if self.lastSend: # This will be zero when not typing, so equiv to if is_typing thisTime = time.time() # thisTime is a local temp variable @@ -1082,9 +1094,10 @@ # This subroutine actually takes care of sending the messages for typing/not_typing events # # self: duh - # typing: boolean + # typing: boolean + + @debugging def sendTyping(self, typing): - self.log.log("Enter chat_panel->sendTyping(self, typing)", ORPG_DEBUG) if typing: self.lastSend = time.time() # remember our send time for use in myKeyHook() #I think this is cleaner @@ -1097,14 +1110,13 @@ status_text = self.settings.get_setting('IdleStatusAlias') if status_text == "" or status_text == None: status_text = "Idle" self.session.set_text_status(status_text) - self.log.log("Exit chat_panel->sendTyping(self, typing)", ORPG_DEBUG) # This subroutine sets the colors of the chat based on the settings in the # self instance. # - # !self : instance of self + # !self : instance of self + @debugging def set_colors(self): - self.log.log("Enter chat_panel->set_colors(self)", ORPG_DEBUG) # chat window backround color self.bgcolor = self.settings.get_setting('bgcolor') # chat window normal text color @@ -1119,31 +1131,27 @@ self.emotecolor = self.settings.get_setting('emotecolor') # color of whispers self.whispercolor = self.settings.get_setting('whispercolor') - self.log.log("Exit chat_panel->set_colors(self)", ORPG_DEBUG) # def set_colors - end # This subroutine will insert text into the chat window # # !self : instance of self - # !txt : text to be inserted into the chat window + # !txt : text to be inserted into the chat window + @debugging def set_chat_text(self, txt): - self.log.log("Enter chat_panel->set_chat_text(self, txt)", ORPG_DEBUG) self.chattxt.SetValue(txt) self.chattxt.SetFocus() self.chattxt.SetInsertionPointEnd() - self.log.log("Exit chat_panel->set_chat_text(self, txt)", ORPG_DEBUG) # def set_chat_text - end - + + @debugging def get_chat_text(self): - self.log.log("Enter chat_panel->get_chat_text(self)", ORPG_DEBUG) - self.log.log("Enter chat_panel->get_chat_text(self)", ORPG_DEBUG) return self.chattxt.GetValue() - # This subroutine sets the focus to the chat window + # This subroutine sets the focus to the chat window + @debugging def set_chat_text_focus(self, event): - self.log.log("Enter chat_panel->set_chat_text_focus(self, event)", ORPG_DEBUG) wx.CallAfter(self.chattxt.SetFocus) - self.log.log("Exit chat_panel->set_chat_text_focus(self, event)", ORPG_DEBUG) # def set_chat_text_focus - end # This subrtouine grabs the user input and make the special keys and @@ -1153,27 +1161,30 @@ # !event : # # Note: self.chattxt now handles it's own Key events. It does, however still - # call it's parent's (self) OnChar to handle "default" behavior. + # call it's parent's (self) OnChar to handle "default" behavior. + @debugging def OnChar(self, event): - self.log.log("Enter chat_panel->OnChar(self, event)", ORPG_DEBUG) s = self.chattxt.GetValue() #self.histlen = len(self.history) - 1 ## RETURN KEY (no matter if there is text in chattxt) # This section is run even if there is nothing in the chattxt (as opposed to the next wx.WXK_RETURN handler if event.GetKeyCode() == wx.WXK_RETURN: - self.log.log("event.GetKeyCode() == wx.WXK_RETURN", ORPG_DEBUG) + logger.debug("event.GetKeyCode() == wx.WXK_RETURN") self.set_colors() if self.session.get_status() == MPLAY_CONNECTED: # only do if we're connected self.sendTyping(0) # Send a "not_typing" event on enter key press macroText="" + recycle_bin = {wx.WXK_F1: 'event.GetKeyCode() == wx.WXK_F1', wx.WXK_F2: 'event.GetKeyCode() == wx.WXK_F2', + wx.WXK_F3: 'event.GetKeyCode() == wx.WXK_F3', wx.WXK_F4: 'event.GetKeyCode() == wx.WXK_F4', + wx.WXK_F5: 'event.GetKeyCode() == wx.WXK_F5', wx.WXK_F6: 'event.GetKeyCode() == wx.WXK_F6', + wx.WXK_F7: 'event.GetKeyCode() == wx.WXK_F7', wx.WXK_F8: 'event.GetKeyCode() == wx.WXK_F8', + wx.WXK_F9: 'event.GetKeyCode() == wx.WXK_F9', wx.WXK_F10: 'event.GetKeyCode() == wx.WXK_F10', + wx.WXK_F11: 'event.GetKeyCode() == wx.WXK_F11', wx.WXK_F12: 'event.GetKeyCode() == wx.WXK_F12'} - - recycle_bin = {wx.WXK_F1: 'event.GetKeyCode() == wx.WXK_F1', wx.WXK_F2: 'event.GetKeyCode() == wx.WXK_F2', wx.WXK_F3: 'event.GetKeyCode() == wx.WXK_F3', wx.WXK_F4: 'event.GetKeyCode() == wx.WXK_F4', wx.WXK_F5: 'event.GetKeyCode() == wx.WXK_F5', wx.WXK_F6: 'event.GetKeyCode() == wx.WXK_F6', wx.WXK_F7: 'event.GetKeyCode() == wx.WXK_F7', wx.WXK_F8: 'event.GetKeyCode() == wx.WXK_F8', wx.WXK_F9: 'event.GetKeyCode() == wx.WXK_F9', wx.WXK_F10: 'event.GetKeyCode() == wx.WXK_F10', wx.WXK_F11: 'event.GetKeyCode() == wx.WXK_F11', wx.WXK_F12: 'event.GetKeyCode() == wx.WXK_F12'} -# Recycle Bin and Lambda should reduce this whole IF ELIF statement block. bin_event = event.GetKeyCode() if recycle_bin.has_key(bin_event): - self.log.log(lambda bin_event: recycle_bin[bin_event], ORPG_DEBUG) + logger.debug(lambda bin_event: recycle_bin[bin_event]) macroText = self.settings.get_setting(recycle_bin[bin_event][29:]) recycle_bin = {}; del bin_event @@ -1184,21 +1195,21 @@ ## RETURN KEY (and not text in control) if (event.GetKeyCode() == wx.WXK_RETURN and len(s)) or len(macroText): - self.log.log("(event.GetKeyCode() == wx.WXK_RETURN and len(s)) or len(macroText)", ORPG_DEBUG) + logger.debug("(event.GetKeyCode() == wx.WXK_RETURN and len(s)) or len(macroText)") self.histidx = -1 self.temptext = "" self.history = [s] + self.history#prepended instead of appended now, so higher index = greater age if not len(macroText): self.chattxt.SetValue("") # play sound sound_file = self.settings.get_setting("SendSound") - if sound_file != '': self.sound_player.play(sound_file) + if sound_file != '': component.get('sound').play(sound_file) if s[0] != "/": ## it's not a slash command s = self.ParsePost( s, True, True ) else: self.chat_cmds.docmd(s) # emote is in chatutils.py ## UP KEY elif event.GetKeyCode() == wx.WXK_UP: - self.log.log("event.GetKeyCode() == wx.WXK_UP", ORPG_DEBUG) + logger.debug("event.GetKeyCode() == wx.WXK_UP") if self.histidx < len(self.history)-1: #text that's not in history but also hasn't been sent to chat gets stored in self.temptext #this way if someone presses the up key, they don't lose their current message permanently @@ -1214,7 +1225,7 @@ ## DOWN KEY elif event.GetKeyCode() == wx.WXK_DOWN: - self.log.log("event.GetKeyCode() == wx.WXK_DOWN", ORPG_DEBUG) + logger.debug("event.GetKeyCode() == wx.WXK_DOWN") #histidx of -1 indicates currently viewing text that's not in self.history if self.histidx > -1: self.histidx -= 1 @@ -1228,7 +1239,7 @@ ## TAB KEY elif event.GetKeyCode() == wx.WXK_TAB: - self.log.log("event.GetKeyCode() == wx.WXK_TAB", ORPG_DEBUG) + logger.debug("event.GetKeyCode() == wx.WXK_TAB") if s !="": found = 0 nicks = [] @@ -1267,13 +1278,13 @@ ## PAGE UP elif event.GetKeyCode() in (wx.WXK_PRIOR, wx.WXK_PAGEUP): - self.log.log("event.GetKeyCode() in (wx.WXK_PRIOR, wx.WXK_PAGEUP)", ORPG_DEBUG) + logger.debug("event.GetKeyCode() in (wx.WXK_PRIOR, wx.WXK_PAGEUP)") self.chatwnd.ScrollPages(-1) if not self.lockscroll: self.lock_scroll(0) ## PAGE DOWN elif event.GetKeyCode() in (wx.WXK_NEXT, wx.WXK_PAGEDOWN): - self.log.log("event.GetKeyCode() in (wx.WXK_NEXT, wx.WXK_PAGEDOWN)", ORPG_DEBUG) + logger.debug("event.GetKeyCode() in (wx.WXK_NEXT, wx.WXK_PAGEDOWN)") if not self.lockscroll: self.lock_scroll(0) if ((self.chatwnd.GetScrollRange(1)-self.chatwnd.GetScrollPos(1)-self.chatwnd.GetScrollThumb(1) < 30) and self.lockscroll): self.lock_scroll(0) @@ -1281,7 +1292,7 @@ ## END elif event.GetKeyCode() == wx.WXK_END: - self.log.log("event.GetKeyCode() == wx.WXK_END", ORPG_DEBUG) + logger.debug("event.GetKeyCode() == wx.WXK_END") if self.lockscroll: self.lock_scroll(0) self.Post() @@ -1289,12 +1300,12 @@ ## NOTHING else: event.Skip() - self.log.log("Exit chat_panel->OnChar(self, event)", ORPG_DEBUG) + logger.debug("Exit chat_panel->OnChar(self, event)") # def OnChar - end - + + @debugging def onDieRoll(self, evt): """Roll the dice based on the button pressed and the die modifiers entered, if any.""" - self.log.log("Enter chat_panel->onDieRoll(self, evt)", ORPG_DEBUG) # Get any die modifiers if they have been entered numDie = self.numDieText.GetValue() dieMod = self.dieModText.GetValue() @@ -1307,35 +1318,37 @@ dieText = "[" + dieText + "]" self.ParsePost(dieText, 1, 1) self.chattxt.SetFocus() - self.log.log("Exit chat_panel->onDieRoll(self, evt)", ORPG_DEBUG) # This subroutine saves a chat buffer as html to a file chosen via a # FileDialog. # # !self : instance of self - # !evt : + # !evt : + @debugging def on_chat_save(self, evt): - self.log.log("Enter chat_panel->on_chat_save(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Save Chat Buffer",".","","HTM* (*.htm*)|*.htm*|HTML (*.html)|*.html|HTM (*.htm)|*.htm",wx.SAVE) if f.ShowModal() == wx.ID_OK: file = open(f.GetPath(), "w") file.write(self.ResetPage() + "</body></html>") file.close() f.Destroy() - os.chdir(self.root_dir) - self.log.log("Exit chat_panel->on_chat_save(self, evt)", ORPG_DEBUG) + os.chdir(dir_struct["home"]) # def on_chat_save - end - + + @debugging def ResetPage(self): self.set_colors() buffertext = self.chatwnd.Header() + "\n" - buffertext += chat_util.strip_body_tags(self.chatwnd.StripHeader()).replace("<br>", "<br />").replace('</html>', '').replace("<br />", "<br />\n").replace("\n\n", '') + buffertext += chat_util.strip_body_tags(self.chatwnd.StripHeader()).replace("<br>", + "<br />").replace('</html>', + '').replace("<br />", + "<br />\n").replace("\n\n", '') return buffertext # This subroutine sets the color of selected text, or base text color if - # nothing is selected + # nothing is selected + @debugging def on_text_color(self, event): - self.log.log("Enter chat_panel->on_text_color(self, event)", ORPG_DEBUG) hexcolor = self.r_h.do_hex_color_dlg(self) if hexcolor != None: (beg,end) = self.chattxt.GetSelection() @@ -1351,18 +1364,16 @@ self.settings.set_setting('mytextcolor',hexcolor) self.set_colors() self.Post() - self.log.log("Exit chat_panel->on_text_color(self, event)", ORPG_DEBUG) # def on_text_color - end # This subroutine take a color and a text string and formats it into html. # # !self : instance of self # !color : color for the text to be set - # !text : text string to be included in the html. + # !text : text string to be included in the html. + @debugging def colorize(self, color, text): """Puts font tags of 'color' around 'text' value, and returns the string""" - self.log.log("Enter chat_panel->colorize(self, color, text)", ORPG_DEBUG) - self.log.log("Exit chat_panel->colorize(self, color, text)", ORPG_DEBUG) return "<font color='" + color + "'>" + text + "</font>" # def colorize - end @@ -1370,9 +1381,9 @@ # tags included. # # !self : instance of self - # !event : + # !event : + @debugging def on_text_format(self, event): - self.log.log("Enter chat_panel->on_text_format(self, event)", ORPG_DEBUG) id = event.GetId() txt = self.chattxt.GetValue() (beg,end) = self.chattxt.GetSelection() @@ -1386,11 +1397,10 @@ self.chattxt.SetValue(txt) self.chattxt.SetInsertionPointEnd() self.chattxt.SetFocus() - self.log.log("Exit chat_panel->on_text_format(self, event)", ORPG_DEBUG) # def on_text_format - end - + + @debugging def lock_scroll(self, event): - self.log.log("Enter chat_panel->lock_scroll(self, event)", ORPG_DEBUG) if self.lockscroll: self.lockscroll = False self.scroll_lock.SetLabel("Scroll ON") @@ -1401,78 +1411,73 @@ else: self.lockscroll = True self.scroll_lock.SetLabel("Scroll OFF") - self.log.log("Exit chat_panel->lock_scroll(self, event)", ORPG_DEBUG) # This subroutine will popup a text window with the chatbuffer contents # # !self : instance of self - # !event : + # !event : + @debugging def pop_textpop(self, event): """searchable popup text view of chatbuffer""" - self.log.log("Enter chat_panel->pop_textpop(self, event)", ORPG_DEBUG) h_buffertext = self.ResetPage() h_dlg = orpgScrolledMessageFrameEditor(self, h_buffertext, "Text View of Chat Window", None, (500,300)) h_dlg.Show(True) - self.log.log("Exit chat_panel->pop_textpop(self, event)", ORPG_DEBUG) # This subroutine will change the dimension of the window # # !self : instance of self - # !event : + # !event : + @debugging def OnSize(self, event=None): - self.log.log("Enter chat_panel->OnSize(self, event=None)", ORPG_DEBUG) event.Skip() wx.CallAfter(self.scroll_down) - self.log.log("Exit chat_panel->OnSize(self, event=None)", ORPG_DEBUG) # def OnSize - end - + + @debugging def scroll_down(self): self.Freeze() self.chatwnd.scroll_down() self.Thaw() - ###### message helpers ###### + ###### message helpers ###### + @debugging def PurgeChat(self): self.set_colors() self.chatwnd.SetPage(self.chatwnd.Header()) - + + @debugging def system_message(self, text): - self.log.log("Enter chat_panel->system_message(self, text)", ORPG_DEBUG) self.send_chat_message(text,chat_msg.SYSTEM_MESSAGE) self.SystemPost(text) - self.log.log("Exit chat_panel->system_message(self, text)", ORPG_DEBUG) - + + @debugging def info_message(self, text): - self.log.log("Enter chat_panel->info_message(self, text)", ORPG_DEBUG) self.send_chat_message(text,chat_msg.INFO_MESSAGE) self.InfoPost(text) - self.log.log("Exit chat_panel->info_message(self, text)", ORPG_DEBUG) - + + @debugging def get_gms(self): - self.log.log("Enter chat_panel->get_gms(self)", ORPG_DEBUG) the_gms = [] for playerid in self.session.players: if len(self.session.players[playerid])>7: if self.session.players[playerid][7]=="GM" and self.session.group_id != '0': the_gms += [playerid] - self.log.log("Exit chat_panel->get_gms(self)", ORPG_DEBUG) return the_gms - + + @debugging def GetName(self): - self.log.log("Enter chat_panel->GetName(self)", ORPG_DEBUG) - self.AliasLib = open_rpg.get_component('alias') + self.AliasLib = component.get('alias') player = self.session.get_my_info() if self.AliasLib != None: self.AliasLib.alias = self.aliasList.GetStringSelection(); if self.AliasLib.alias[0] != self.defaultAliasName: - self.log.log("Exit chat_panel->GetName(self)", ORPG_DEBUG) + logger.debug("Exit chat_panel->GetName(self)") return [self.chat_display_name([self.AliasLib.alias[0], player[1], player[2]]), self.AliasLib.alias[1]] - self.log.log("Exit chat_panel->GetName(self)", ORPG_DEBUG) return [self.chat_display_name(player), "Default"] - + + @debugging def GetFilteredText(self, text): - self.log.log("Enter chat_panel->GetFilteredText(self, text)", ORPG_DEBUG) advregex = re.compile('\"(.*?)\"', re.I) - self.AliasLib = open_rpg.get_component('alias') + self.AliasLib = component.get('alias') if self.AliasLib != None: self.AliasLib.filter = self.filterList.GetSelection()-1; for rule in self.AliasLib.filterRegEx: @@ -1482,11 +1487,10 @@ match = m.group(0) newmatch = re.sub(rule[0], rule[1], match) text = text.replace(match, newmatch) - self.log.log("Exit chat_panel->GetFilteredText(self, text)", ORPG_DEBUG) return text - + + @debugging def emote_message(self, text): - self.log.log("Enter chat_panel->emote_message(self, text)", ORPG_DEBUG) text = self.NormalizeParse(text) text = self.colorize(self.emotecolor, text) @@ -1503,10 +1507,9 @@ name = self.GetName()[0] text = "** " + name + " " + text + " **" self.EmotePost(text) - self.log.log("Exit chat_panel->emote_message(self, text)", ORPG_DEBUG) - + + @debugging def whisper_to_players(self, text, player_ids): - self.log.log("Enter chat_panel->whisper_to_players(self, text, player_ids)", ORPG_DEBUG) tabbed_whispers_p = self.settings.get_setting("tabbedwhispers") # Heroman - apply any filtering selected text = self.NormalizeParse(text) @@ -1531,10 +1534,9 @@ id = id.strip() if self.session.is_valid_id(id): self.send_chat_message(text,chat_msg.WHISPER_MESSAGE,id) else: self.InfoPost(id + " Unknown!") - self.log.log("Exit chat_panel->whisper_to_players(self, text, player_ids)", ORPG_DEBUG) - + + @debugging def send_chat_message(self, text, type=chat_msg.CHAT_MESSAGE, player_id="all"): - self.log.log("Enter chat_panel->send_chat_message(self, text, type, player_id)", ORPG_DEBUG) #########send_msg()############# send = 1 for plugin_fname in self.activeplugins.keys(): @@ -1542,8 +1544,8 @@ try: text, send = plugin.send_msg(text, send) except Exception, e: if str(e) != "'module' object has no attribute 'send_msg'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) msg = chat_msg.chat_msg() msg.set_text(text) msg.set_type(type) @@ -1557,11 +1559,10 @@ msg.set_alias(playername) if send: self.session.send(msg.toxml(),player_id) del msg - self.log.log("Exit chat_panel->send_chat_message(self, text, type, player_id)", ORPG_DEBUG) - #### incoming chat message handler ##### + #### incoming chat message handler ##### + @debugging def post_incoming_msg(self, msg, player): - self.log.log("Enter chat_panel->post_incoming_msg(self, msg, player)", ORPG_DEBUG) # pull data type = msg.get_type() @@ -1578,8 +1579,8 @@ try: text, type, name = plugin.plugin_incoming_msg(text, type, display_name, player) except Exception, e: if str(e) != "'module' object has no attribute 'receive_msg'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) #end mDuo13 added code #image stripping for players' names strip_img = self.settings.get_setting("Show_Images_In_Chat") @@ -1664,8 +1665,8 @@ else: self.parent.MainChatPanel.EmotePost("**" + msg + "**") self.parent.newMsg(0) except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: 'Error in posting whisper message': " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: 'Error in posting whisper message': " + str(e)) elif (type == chat_msg.EMOTE_MESSAGE): text = "** " + display_name + " " + text + " **" self.EmotePost(text) @@ -1681,28 +1682,24 @@ # playe sound sound_file = self.settings.get_setting(recvSound) if sound_file != '': - self.sound_player.play(sound_file) - self.log.log("Exit chat_panel->post_incoming_msg(self, msg, player)", ORPG_DEBUG) + component.get('sound').play(sound_file) #### Posting helpers ##### - + + @debugging def InfoPost(self, s): - self.log.log("Enter chat_panel->InfoPost(self, s)", ORPG_DEBUG) self.Post(self.colorize(self.infocolor, s), c='info') - self.log.log("Exit chat_panel->InfoPost(self, s)", ORPG_DEBUG) - + + @debugging def SystemPost(self, s): - self.log.log("Enter chat_panel->SystemPost(self, s)", ORPG_DEBUG) self.Post(self.colorize(self.syscolor, s), c='system') - self.log.log("Exit chat_panel->SystemPost(self, s)", ORPG_DEBUG) - + + @debugging def EmotePost(self, s): - self.log.log("Enter chat_panel->EmotePost(self, s)", ORPG_DEBUG) self.Post(self.colorize(self.emotecolor, s), c='emote') - self.log.log("Exit chat_panel->EmotePost(self, s)", ORPG_DEBUG) - #### Standard Post method ##### + #### Standard Post method ##### + @debugging def Post(self, s="", send=False, myself=False, c='post'): - self.log.log("Enter chat_panel->Post(self, s, send, myself)", ORPG_DEBUG) strip_p = self.settings.get_setting("striphtml") strip_img = self.settings.get_setting("Show_Images_In_Chat")#moved back 7-11-05. --mDuo13 if (strip_p == "1"): s = strip_html(s) @@ -1727,8 +1724,8 @@ try: s = plugin.post_msg(s, myself) except Exception, e: if str(e) != "'module' object has no attribute 'post_msg'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) #end mDuo13 added code if myself: name = "<b>" + display_name + "</b>: " @@ -1758,8 +1755,8 @@ s2 = plugin.post_msg(s2, myself) except Exception, e: if str(e) != "'module' object has no attribute 'post_msg'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) if s2 != "": #Italici the messages from tabbed whispers if self.type == WHISPER_TAB or self.type == GROUP_TAB or self.sendtarget == 'gm': @@ -1768,13 +1765,13 @@ if self.type == WHISPER_TAB: name += " (whispering): " elif self.type == GROUP_TAB: name += self.settings.get_setting("gwtext") + ' ' elif self.sendtarget == 'gm': name += " (whispering to GM) " - newline = self.TimeIndexString() + "<div class='"+c+"'> " +name + s2 + "</div>" - log( self.settings, c+' '+name + s2 ) + newline = "<div class='"+c+"'> " + self.TimeIndexString() + name + s2 + "</div>" + log( self.settings, c, name+s2 ) else: - newline = self.TimeIndexString() + "<div class='"+c+"'> " +name + s + "</div>" - log( self.settings, c+' '+name + s ) + newline = "<div class='"+c+"'> " + self.TimeIndexString() + name + s + "</div>" + log( self.settings, c, name+s ) else: send = False - newline = chat_util.strip_unicode(newline) + newline = component.get('xml').strip_unicode(newline) if self.lockscroll == 0: self.chatwnd.AppendToPage(newline) self.scroll_down() @@ -1792,61 +1789,56 @@ elif self.type == NULL_TAB: pass else: self.InfoPost("Failed to send message, unknown send type for this tab") self.parsed=0 - self.log.log("Exit chat_panel->Post(self, s, send, myself)", ORPG_DEBUG) # # TimeIndexString() # # time indexing for chat display only (don't log time indexing) - # added by Snowdog 4/04 + # added by Snowdog 4/04 + @debugging def TimeIndexString(self): - self.log.log("Enter chat_panel->TimeIndexString(self)", ORPG_DEBUG) try: mtime = "" if self.settings.get_setting('Chat_Time_Indexing') == "0": pass elif self.settings.get_setting('Chat_Time_Indexing') == "1": mtime = time.strftime("[%I:%M:%S] ", time.localtime()) - self.log.log("Exit chat_panel->TimeIndexString(self)", ORPG_DEBUG) return mtime except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) return "[ERROR]" - #### Post with parsing dice #### + #### Post with parsing dice #### + @debugging def ParsePost(self, s, send=False, myself=False): - self.log.log("Enter chat_panel->ParsePost(self, s, send, myself)", ORPG_DEBUG) s = self.NormalizeParse(s) self.set_colors() self.Post(s,send,myself) - self.log.log("Exit chat_panel->ParsePost(self, s, send, myself)", ORPG_DEBUG) - - def NormalizeParse(self, s): - self.log.log("Enter chat_panel->NormalizeParse(self, s)", ORPG_DEBUG) + + @debugging + def NormalizeParse(self, s): for plugin_fname in self.activeplugins.keys(): plugin = self.activeplugins[plugin_fname] try: s = plugin.pre_parse(s) except Exception, e: if str(e) != "'module' object has no attribute 'post_msg'": - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: " + str(e), ORPG_GENERAL) + logger.general(traceback.format_exc()) + logger.general("EXCEPTION: " + str(e)) if self.parsed == 0: s = self.ParseNode(s) s = self.ParseDice(s) s = self.ParseFilter(s) self.parsed = 1 - self.log.log("Exit chat_panel->NormalizeParse(self, s)", ORPG_DEBUG) return s - - def ParseFilter(self, s): - self.log.log("Enter chat_panel->ParseFilter(self, s)", ORPG_DEBUG) + + @debugging + def ParseFilter(self, s): s = self.GetFilteredText(s) - self.log.log("Exit chat_panel->ParseFilter(self, s)", ORPG_DEBUG) return s - - def ParseNode(self, s): + + @debugging + def ParseNode(self, s): """Parses player input for embedded nodes rolls""" - self.log.log("Enter chat_panel->ParseNode(self, s)", ORPG_DEBUG) cur_loc = 0 #[a-zA-Z0-9 _\-\.] reg = re.compile("(!@([a-zA-Z0-9 _\-\./]+(::[a-zA-Z0-9 _\-\./]+)*)@!)") @@ -1854,12 +1846,11 @@ for i in xrange(0,len(matches)): newstr = self.ParseNode(self.resolve_nodes(matches[i][1])) s = s.replace(matches[i][0], newstr, 1) - self.log.log("Exit chat_panel->ParseNode(self, s)", ORPG_DEBUG) return s - - def ParseDice(self, s): + + @debugging + def ParseDice(self, s): """Parses player input for embedded dice rolls""" - self.log.log("Enter chat_panel->ParseDice(self, s)", ORPG_DEBUG) reg = re.compile("\[([^]]*?)\]") matches = reg.findall(s) for i in xrange(0,len(matches)): @@ -1869,17 +1860,16 @@ if newstr[0].lower() == 'q': newstr = newstr[1:] qmode = 1 - try: newstr = self.DiceManager.proccessRoll(newstr) + try: newstr = component.get('DiceManager').proccessRoll(newstr) except: pass if qmode == 1: s = s.replace("[" + matches[i] + "]", "<!-- Official Roll [" + newstr1 + "] => " + newstr + "-->" + newstr, 1) else: s = s.replace("[" + matches[i] + "]", "[" + newstr1 + "<!-- Official Roll -->] => " + newstr, 1) - self.log.log("Exit chat_panel->ParseDice(self, s)", ORPG_DEBUG) return s - + + @debugging def PraseUnknowns(self, s): # Uses a tuple. Usage: ?Label}dY. If no Label is assigned then use ?}DY - self.log.log("Enter chat_panel->PraseUnknowns(self, s)", ORPG_DEBUG) newstr = "0" reg = re.compile("(\?\{*)([a-zA-Z ]*)(\}*)") matches = reg.findall(s) @@ -1895,24 +1885,22 @@ if newstr == '': newstr = '0' s = s.replace(matches[i][0], newstr, 1).replace(matches[i][1], '', 1).replace(matches[i][2], '', 1) dlg.Destroy() - self.log.log("Exit chat_panel->PraseUnknowns(self, s)", ORPG_DEBUG) return s # This subroutine builds a chat display name. - # - def chat_display_name(self, player): - self.log.log("Enter chat_panel->chat_display_name(self, player)", ORPG_DEBUG) + # + @debugging + def chat_display_name(self, player): if self.settings.get_setting("ShowIDInChat") == "0": display_name = player[0] else: display_name = "("+player[2]+") " + player[0] - self.log.log("Exit chat_panel->chat_display_name(self, player)", ORPG_DEBUG) return display_name # This subroutine will get a hex color and return it, or return nothing - # - def get_color(self): - self.log.log("Enter chat_panel->get_color(self)", ORPG_DEBUG) + # + @debugging + def get_color(self): data = wx.ColourData() data.SetChooseFull(True) dlg = wx.ColourDialog(self, data) @@ -1921,16 +1909,14 @@ (red,green,blue) = data.GetColour().Get() hexcolor = self.r_h.hexstring(red, green, blue) dlg.Destroy() - self.log.log("Exit chat_panel->get_color(self) return hexcolor", ORPG_DEBUG) return hexcolor else: dlg.Destroy() - self.log.log("Exit chat_panel->get_color(self) return None", ORPG_DEBUG) return None # def get_color - end - + + @debugging def replace_quotes(self, s): - self.log.log("Enter chat_panel->replace_quotes(self, s)", ORPG_DEBUG) in_tag = 0 i = 0 rs = s[:] @@ -1944,11 +1930,10 @@ if in_tag: rs = rs[:i] + "'" + rs[i+1:] i += 1 - self.log.log("Exit chat_panel->replace_quotes(self, s)", ORPG_DEBUG) - return rs + return rs - def resolve_loop(self, dom, nodeName, doLoop = False): - self.log.log("Enter chat_panel->resolve_loop(self, dom, nodeName)", ORPG_DEBUG) + @debugging + def resolve_loop(self, dom, nodeName, doLoop = False): for node in dom: if node._get_tagName() != 'nodehandler': continue @@ -1959,16 +1944,14 @@ if node.getAttribute('name') != nodeName: continue foundNode = node - self.log.log("Exit chat_panel->resolve_loop(self, dom, path) return (True, value)", ORPG_DEBUG) return (True, foundNode) - self.log.log("Exit chat_panel->resolve_loop(self, dom, path) return (False, '')", ORPG_DEBUG) - return (False, '') + return (False, '') - def resolve_nodes(self, s): - self.log.log("Enter chat_panel->resolve_nodes(self, s)", ORPG_DEBUG) + @debugging + def resolve_nodes(self, s): value = "" node_path_list = s.split("::") - gametree = open_rpg.get_component('tree') + gametree = component.get('tree') dom = gametree.master_dom.getChildren() for nodeName in node_path_list: (found, node) = self.resolve_loop(dom, nodeName) @@ -1992,5 +1975,4 @@ value = node._get_nodeValue() else: value = s - self.log.log("Exit chat_panel->resolve_nodes(self, s)", ORPG_DEBUG) return value
--- a/orpg/chat/commands.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/chat/commands.py Thu Aug 27 01:04:43 2009 -0500 @@ -12,7 +12,10 @@ import time import orpg.orpg_version import orpg.orpg_windows -import traceback +import traceback + +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging ##-------------------------------------------------------------- ## dynamically loading module for extended developer commands @@ -35,7 +38,8 @@ # Initialization subroutine. # # !self : instance of self - # !chat : instance of the chat window to write to + # !chat : instance of the chat window to write to + @debugging def __init__(self,chat): self.post = chat.Post self.colorize = chat.colorize @@ -55,18 +59,21 @@ # of implemented emotions. # # !self : instance of self - # !text : string of text matching an implemented emotion + # !text : string of text matching an implemented emotion + @debugging def addcommand(self, cmd, function, helpmsg): if not self.cmdlist.has_key(cmd) and not self.shortcmdlist.has_key(cmd): self.cmdlist[cmd] = {} self.cmdlist[cmd]['function'] = function self.cmdlist[cmd]['help'] = helpmsg #print 'Command Added: ' + cmd - + + @debugging def addshortcmd(self, shortcmd, longcmd): if not self.shortcmdlist.has_key(shortcmd) and not self.cmdlist.has_key(shortcmd): self.shortcmdlist[shortcmd] = longcmd - + + @debugging def removecmd(self, cmd): if self.cmdlist.has_key(cmd): del self.cmdlist[cmd] @@ -75,7 +82,8 @@ #print 'Command Removed: ' + cmd - + + @debugging def defaultcmds(self): self.addcommand('/help', self.on_help, '- Displays this help message') self.addcommand('/version', self.on_version, ' - Displays current version of OpenRPG.') @@ -104,7 +112,8 @@ self.addcommand('/sound', self.on_sound, 'Sound_URL - Plays a sound for all clients in the room.') self.addcommand('/purge', self.on_purge, 'This will clear the entire chat window') self.addcommand('/advfilter', self.on_filter, 'This will toggle the Advanced Filter') - + + @debugging def defaultcmdalias(self): self.addshortcmd('/?', '/help') self.addshortcmd('/he', '/me') @@ -118,8 +127,8 @@ #This is just an example or a differant way the shorcmd can be used self.addshortcmd('/sleep', '/me falls asleep') - - + + @debugging def docmd(self,text): cmdsearch = string.split(text,None,1) cmd = string.lower(cmdsearch[0]) @@ -134,7 +143,8 @@ else: msg = "Sorry I don't know what %s is!" % (cmd) self.chat.InfoPost(msg) - + + @debugging def on_filter(self, cmdargs): #print self.chat.advancedFilter test = not self.chat.advancedFilter @@ -158,11 +168,13 @@ self.chat.InfoPost("Advanced Filtering has been turned On") else: self.chat.InfoPost("Advanced Filtering has been turned Off") - + + @debugging def on_purge(self, cmdargs): self.chat.PurgeChat() self.chat.InfoPost('Chat Buffer has been Purged!') - + + @debugging def on_sound(self, cmdargs): if len(cmdargs) < 8: self.chat.InfoPost("You must provide a URL for the file name, it does not work for just local sound files") @@ -195,10 +207,12 @@ self.chat.InfoPost("You cannot send sound files to the lobby!") else: self.chat.InfoPost("Something dun fuckered up Frank!") - + + @debugging def on_version(self, cmdargs=""): self.chat.InfoPost("Version is OpenRPG " + self.chat.version) - + + @debugging def on_load(self, cmdargs): args = string.split(cmdargs,None,-1) try: @@ -208,13 +222,15 @@ except Exception,e: print e self.chat.InfoPost("ERROR Loading settings") - + + @debugging def on_font(self, cmdargs): try: fontsettings = self.chat.set_default_font(fontname=cmdargs, fontsize=None) except: self.chat.InfoPost("ERROR setting default font") - + + @debugging def on_fontsize(self, cmdargs): args = string.split(cmdargs,None,-1) try: @@ -222,7 +238,8 @@ except Exception, e: print e self.chat.InfoPost("ERROR setting default font size") - + + @debugging def on_close(self, cmdargs): try: chatpanel = self.chat @@ -233,14 +250,16 @@ chatpanel.parent.onCloseTab(0) except: self.chat.InfoPost("Error: cannot close private chat tab.") - + + @debugging def on_time(self, cmdargs): local_time = time.localtime() gmt_time = time.gmtime() format_string = "%A %b %d, %Y %I:%M:%S%p" self.chat.InfoPost("<br />Local: " + time.strftime(format_string)+\ "<br />GMT: "+time.strftime(format_string,gmt_time)) - + + @debugging def on_dieroller(self, cmdargs): args = string.split(cmdargs,None,-1) rm = self.chat.DiceManager @@ -252,12 +271,14 @@ print e self.chat.InfoPost("Available die rollers: " + str(rm.listRollers())) self.chat.InfoPost("You are using the <b>\"" + rm.getRoller() + "\"</b> die roller.") - + + @debugging def on_ping(self, cmdargs): ct = time.clock() msg = "<ping player='"+self.session.id+"' time='"+str(ct)+"' />" self.session.outbox.put(msg) - + + @debugging def on_log(self,cmdargs): args = string.split(cmdargs,None,-1) logfile = self.settings.get_setting( 'GameLogPrefix' ) @@ -288,7 +309,8 @@ self.postLoggingState() else: self.chat.InfoPost("Unknown logging command, use 'on' or 'off'" ) - + + @debugging def postLoggingState( self ): logfile = self.settings.get_setting( 'GameLogPrefix' ) try: @@ -304,7 +326,8 @@ # This subroutine will set the players netork status. # #!self : instance of self - + + @debugging def on_name(self, cmdargs): #only 20 chars no more! :) if cmdargs == "": @@ -318,7 +341,8 @@ # This subroutine will set the players netork status. # - # !self : instance of self + # !self : instance of self + @debugging def on_status(self, cmdargs): if cmdargs == "": self.chat.InfoPost("Incorrect synatx for status.") @@ -327,7 +351,8 @@ txt = cmdargs[:20] self.session.set_text_status(str(txt)) # def on_status - end - + + @debugging def on_set(self, cmdargs): args = string.split(cmdargs,None,-1) keys = self.settings.get_setting_keys() @@ -361,7 +386,8 @@ # This subroutine will display the correct usage of the different emotions. # #!self : instance of self - + + @debugging def on_help(self, cmdargs=""): cmds = self.cmdlist.keys() cmds.sort() @@ -383,7 +409,8 @@ # This subroutine will either show the list of currently ignored users # !self : instance of self # !text : string that is comprised of a list of users to toggle the ignore flag - + + @debugging def on_ignore(self, cmdargs): args = string.split(cmdargs,None,-1) (ignore_list, ignore_name) = self.session.get_ignore_list() @@ -409,7 +436,8 @@ except: self.chat.InfoPost(m + " was ignored because it is an invalid player ID") traceback.print_exc() - + + @debugging def on_role(self, cmdargs): if cmdargs == "": self.session.display_roles() @@ -440,7 +468,8 @@ # !self : instance of self # !text : string that is comprised of a list of users and the message to #whisper. - + + @debugging def on_whisper(self, cmdargs): delim = cmdargs.find("=") @@ -458,7 +487,8 @@ #--------------------------------------------------------- # [START] Digitalxero Multi Whisper Group 1/1/05 -#--------------------------------------------------------- +#--------------------------------------------------------- + @debugging def on_groupwhisper(self, cmdargs): args = string.split(cmdargs,None,-1) delim = cmdargs.find("=") @@ -518,7 +548,8 @@ #--------------------------------------------------------- # [END] Digitalxero Multi Whisper Group 1/1/05 #--------------------------------------------------------- - + + @debugging def on_gmwhisper(self, cmdargs): if cmdargs == "": self.chat.InfoPost("**Incorrect syntax for GM Whisper.") @@ -533,7 +564,8 @@ self.on_whisper(gmstring + "=" + cmdargs) else: self.chat.InfoPost("**No GMs to Whisper to.") - + + @debugging def on_moderate(self, cmdargs): if cmdargs != "": pos = cmdargs.find("=") @@ -570,10 +602,12 @@ msg = "<moderate action='list' from='"+self.session.id+"' />" self.session.outbox.put(msg) self.session.update() - + + @debugging def on_update(self, cmdargs): self.chat.InfoPost("This command is no longer valid") - + + @debugging def on_description(self, cmdargs): if len(cmdargs) <= 0: self.chat.InfoPost("**No description text to display." + str(delim)) @@ -583,7 +617,8 @@ mesg += "</font></td></tr></table>" self.chat.Post(mesg) self.chat.send_chat_message(mesg) - + + @debugging def invoke_tab(self, cmdargs): ######START mDuo13's Tab Initiator######## try: @@ -608,7 +643,8 @@ self.chat.parent.newMsg(nidx) return #######END mDuo13's Tab Initiator######### - + + @debugging def on_remote_admin(self, cmdargs): args = string.split(cmdargs,None,-1) #handles remote administration commands
--- a/orpg/dieroller/d20.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/d20.py Thu Aug 27 01:04:43 2009 -0500 @@ -18,34 +18,40 @@ # # Description: d20 die roller # -from die import * +from die import * __version__ = "$Id: d20.py,v 1.9 2006/11/04 21:24:19 digitalxero Exp $" # d20 stands for "d20 system" not 20 sided die :) class d20(std): + def __init__(self,source=[]): std.__init__(self,source) # these methods return new die objects for specific options + def attack(self,AC,mod,critical): return d20attack(self,AC,mod,critical) + def dc(self,DC,mod): return d20dc(self,DC,mod) class d20dc(std): + def __init__(self,source=[],DC=10,mod=0): std.__init__(self,source) self.DC = DC self.mod = mod self.append(static_di(mod)) + def is_success(self): return ((self.sum() >= self.DC or self.data[0] == 20) and self.data[0] != 1) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -64,6 +70,7 @@ class d20attack(std): + def __init__(self,source=[],AC=10,mod=0,critical=20): std.__init__(self,source) self.mod = mod @@ -72,11 +79,13 @@ self.append(static_di(mod)) self.critical_check() + def attack(AC=10,mod=0,critical=20): self.mod = mod self.critical = critical self.AC = AC + def critical_check(self): self.critical_result = 0 self.critical_roll = 0 @@ -85,12 +94,15 @@ if self.critical_roll.sum() >= self.AC: self.critical_result = 1 + def is_critical(self): return self.critical_result + def is_hit(self): return ((self.sum() >= self.AC or self.data[0] == 20) and self.data[0] != 1) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]:
--- a/orpg/dieroller/die.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/die.py Thu Aug 27 01:04:43 2009 -0500 @@ -37,6 +37,7 @@ class die_base(UserList.UserList): + def __init__(self,source = []): if isinstance(source, (int, float, basestring)): s = [] @@ -46,12 +47,14 @@ UserList.UserList.__init__(self,s) + def sum(self): s = 0 for a in self.data: s += int(a) return s + def __lshift__(self,other): if type(other) == type(3) or type(other) == type(3.0): o = other @@ -66,6 +69,7 @@ result.append(die) return self.__class__(result) + def __rshift__(self,other): if type(other) == type(3) or type(other) == type(3.0): @@ -81,13 +85,16 @@ result.append(die) return self.__class__(result) + def __rlshift__(self,other): return self.__rshift__(other) + def __rrshift__(self,other): return self.__lshift__(other) + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -99,6 +106,7 @@ myStr = "[] = (0)" return myStr + def __lt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() < other) @@ -107,6 +115,7 @@ else: return UserList.UserList.__lt__(self,other) + def __le__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() <= other) @@ -115,6 +124,7 @@ else: return UserList.UserList.__le__(self,other) + def __eq__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() == other) @@ -123,6 +133,7 @@ else: return UserList.UserList.__eq__(self,other) + def __ne__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() != other) @@ -131,6 +142,7 @@ else: return UserList.UserList.__ne__(self,other) + def __gt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() > other) @@ -139,6 +151,7 @@ else: return UserList.UserList.__gt__(self,other) + def __ge__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() >= other) @@ -147,6 +160,7 @@ else: return UserList.UserList.__ge__(self,other) + def __cmp__(self,other): # this function included for backwards compatibility # As of 2.1, lists implement the "rich comparison" @@ -159,9 +173,11 @@ return UserList.UserList.__cmp__(self,other) + def __rcmp__(self,other): return self.__cmp__(other) + def __add__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -177,9 +193,11 @@ #result = UserList.UserList.__add__(mycopy,other) return mycopy + def __iadd__(self,other): return self.__add__(other) + def __radd__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -189,9 +207,11 @@ mycopy.insert(0,other) return mycopy + def __int__(self): return self.sum() + def __sub__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -204,6 +224,7 @@ mycopy.extend(other) return mycopy + def __rsub__(self,other): mycopy = -copy.deepcopy(self) #print type(other) @@ -214,9 +235,11 @@ mycopy.insert(0,other) return mycopy + def __isub__(self,other): return self.__sub__(other) + def __mul__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum() * other @@ -225,9 +248,11 @@ else: return UserList.UserList.__mul__(self,other) + def __rmul__(self,other): return self.__mul__(other) + def __div__(self,other): if type(other) == type(3) or type(other) == type(3.0): return float(self.sum()) / other @@ -236,6 +261,7 @@ else: return UserList.UserList.__div__(self,other) + def __rdiv__(self,other): if type(other) == type(3) or type(other) == type(3.0): return other / float(self.sum()) @@ -244,6 +270,7 @@ else: return UserList.UserList.__rdiv__(self,other) + def __mod__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum()%other @@ -252,6 +279,7 @@ else: return UserList.UserList.__mod__(self,other) + def __rmod__(self,other): if type(other) == type(3) or type(other) == type(3.0): return other % self.sum() @@ -260,22 +288,26 @@ else: return UserList.UserList.__rmod__(self,other) + def __neg__(self): for i in range(len(self.data)): self.data[i] = -self.data[i] return self + def __pos__(self): for i in range(len(self.data)): self.data[i] = +self.data[i] return self + def __abs__(self): for i in range(len(self.data)): self.data[i] = abs(self.data[i]) return self #return abs(self.sum()) + def __pow__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum() ** other @@ -285,6 +317,7 @@ return UserList.UserList.__pow__(self,other) + def __rpow__(self,other): # We're overloading exponentiation of ints to create "other" number of dice @@ -300,6 +333,7 @@ ### di class to handle actual dice class di: + def __init__(self,sides,min=1): self.sides = sides self.history = None @@ -307,40 +341,47 @@ self.target = None self.roll(min) + def __str__(self): if len(self.history) > 1: return str(self.history) else: return str(self.value) + def __neg__(self): self.value = -self.value for i in range(len(self.history)): self.history[i] = -self.history[i] return self + def __pos__(self): self.value = +self.value for i in range(len(self.history)): self.history[i] = +self.history[i] return self + def __abs__(self): self.value = abs(self.value) for i in range(len(self.history)): self.history[i] = abs(self.history[i]) return self + def __repr__(self): if len(self.history) > 1: return str(self.history) else: return str(self.value) + def __int__(self): return self.value + def __lt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value < other @@ -349,6 +390,7 @@ else: return self < other + def __le__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value <= other @@ -357,6 +399,7 @@ else: return self <= other + def __eq__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value == other @@ -365,6 +408,7 @@ else: return self == other + def __ne__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value != other @@ -373,6 +417,7 @@ else: return self != other + def __gt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value > other @@ -381,6 +426,7 @@ else: return self > other + def __ge__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value >= other @@ -389,10 +435,11 @@ else: return self >= other + def __cmp__(self,other): # this function included for backwards compatibility -# As of 2.1, lists implement the "rich comparison" -# methods overloaded above. + # As of 2.1, lists implement the "rich comparison" + # methods overloaded above. if type(other) == type(3) or type(other) == type(3.0): return cmp(self.value, other) elif hasattr(other,"value"): @@ -400,6 +447,7 @@ else: return cmp(self,other) + def roll(self,min=1): if isinstance(self.sides, basestring) and self.sides.lower() == 'f': self.value = random.randint(-1, 1) @@ -409,6 +457,7 @@ self.history = [] self.history.append(self.value) + def extraroll(self): if isinstance(self.sides, basestring) and self.sides.lower() == 'f': result = random.randint(-1, 1) @@ -419,56 +468,68 @@ self.value += result self.history.append(result) + def lastroll(self): return self.history[len(self.history)-1] + def set_value(self,value): self.value = value self.history = [] self.history.append(self.value) + def modify(self,mod): self.value += mod self.history.append(mod) + def gethistory(self): return self.history[:] class static_di(di): + def __init__(self,value): di.__init__(self,value,value) self.set_value(value) class std(die_base): + def __init__(self,source=[]): die_base.__init__(self,source) # Examples of adding member functions through inheritance. + def ascending(self): result = self[:] result.sort() return result + def descending(self): result = self[:] result.sort() result.reverse() return result + def takeHighest(self,num_dice): return self.descending()[:num_dice] + def takeLowest(self,num_dice): return self.ascending()[:num_dice] + def extra(self,num): for i in range(len(self.data)): if self.data[i].lastroll() >= num: self.data[i].extraroll() return self + def open(self,num): if num <= 1: self @@ -482,12 +543,14 @@ else: return self.open(num) + def minroll(self,min): for i in range(len(self.data)): if self.data[i].lastroll() < min: self.data[i].roll(min) return self + def each(self,mod): mod = int(mod) for i in range(len(self.data)): @@ -495,6 +558,7 @@ return self + def vs(self, target): for dn in self.data: dn.target = target @@ -505,6 +569,7 @@ ## greater than or equal to against the target value and ## we only return the number of successful saves. A negative ## value will never be generated. + def sum(self): retValue = 0 for dn in self.data:
--- a/orpg/dieroller/gurps.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/gurps.py Thu Aug 27 01:04:43 2009 -0500 @@ -53,7 +53,6 @@ from time import time, clock import random - __version__ = "$Id: gurps.py,v 1.5 2007/05/06 16:42:55 digitalxero Exp $" # gurps @@ -65,45 +64,58 @@ # these methods return new die objects for specific options # Original msk roll renamed to be easier to understand/remember + def skill(self,skill,mod): return gurpsskill(self,skill,mod) + def defaultskill(self,stat,defaultlevel,mod): return gurpsdefaultskill(self,stat,defaultlevel,mod) + def supernatural(self,skill,resistance,mod): return gurpssupernatural(self,skill,resistance,mod) + def crit_hit(self): return gurpscrit_hit(self) + def crit_headblow(self): return gurpscrit_headblow(self) + def crit_miss(self): return gurpscrit_miss(self) + def crit_unarm(self): return gurpscrit_unarm(self) + def spellfail(self): return gurpsspellfail(self) + def frightcheck(self,level,mod): return gurpsfrightcheck(self,level,mod) + def frightcheckfail(self,mod): return gurpsfrightcheckfail(self,mod) class gurpsskill(std): + def __init__(self,source=[],skill=0,mod=0): std.__init__(self,source) self.skill = skill self.mod = mod + def is_success(self): return (((self.sum()) <= self.skill+self.mod) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -142,12 +154,14 @@ return myStr class gurpsdefaultskill(std): + def __init__(self,source=[],stat=0,defaultlevel=0,mod=0): std.__init__(self,source) self.stat = stat self.defaultlevel = defaultlevel self.mod = mod + def is_success(self): if self.stat < 21: intSkillVal = self.stat + self.defaultlevel + self.mod @@ -155,6 +169,7 @@ intSkillVal = 20 + self.defaultlevel + self.mod return (((self.sum()) <= intSkillVal) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -199,12 +214,14 @@ return myStr class gurpssupernatural(std): + def __init__(self,source=[],skill=0,resistance=0,mod=0): std.__init__(self,source) self.skill = skill self.resistance = resistance self.mod = mod + def is_success(self): if self.skill+self.mod > 16: if self.resistance > 16: @@ -218,6 +235,7 @@ newSkill = self.skill+self.mod return (((self.sum()) <= newSkill) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -269,9 +287,11 @@ return myStr class gurpscrit_hit(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -300,10 +320,11 @@ return myStr class gurpscrit_headblow(std): - def __init__(self,source=[],mod=0): - std.__init__(self,source) + def __init__(self,source=[],mod=0): + std.__init__(self,source) - def __str__(self): + + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. myStr += "," #Adds a comma after each die @@ -337,9 +358,11 @@ return myStr class gurpscrit_miss(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -376,9 +399,11 @@ return myStr class gurpscrit_unarm(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -414,9 +439,11 @@ return myStr class gurpsspellfail(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -455,14 +482,17 @@ return myStr class gurpsfrightcheck(std): + def __init__(self,source=[],skill=0,mod=0): std.__init__(self,source) self.skill = skill self.mod = mod + def is_success(self): return (((self.sum()) <= self.skill+self.mod) and (self.sum() < 14)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -586,10 +616,12 @@ return myStr class gurpsfrightcheckfail(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]:
--- a/orpg/dieroller/hackmaster.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/hackmaster.py Thu Aug 27 01:04:43 2009 -0500 @@ -38,18 +38,23 @@ #hackmaster Class basically passes into functional classes class hackmaster(std): + def __init__(self,source=[]): std.__init__(self,source) + def damage(self, mod, hon): return HMdamage(self, mod, hon) + def attack(self, mod, hon): return HMattack(self, mod, hon) + def help(self): return HMhelp(self) + def severity(self, honor): return HMSeverity(self, honor) @@ -58,6 +63,7 @@ # and this appears to be invisible to the user ( if a 4 on a d4 is rolled a 3 will appear and be followed by another # die. if High honor then a 4 will appear followed by a another die. class HMdamage(std): + def __init__(self,source=[], mod = 0, hon = 0): std.__init__(self,source) self.mod = mod @@ -68,12 +74,14 @@ #here we roll the honor die self.append(static_di(self.hon)) + def damage(mod = 0, hon = 0): self.mod = mod self.hon = hon # This function is called by default to display the die string to the chat window. # Our die string attempts to explain the results + def __str__(self): myStr = "Damage " myStr += "[Damage Roll, Modifiers, Honor]: " + " [" + str(self.data[0]) @@ -85,12 +93,14 @@ return myStr # This function checks to see if we need to reroll for penetration + def check_pen(self): for i in range(len(self.data)): if self.data[i].lastroll() >= self.data[i].sides: self.pen_roll(i) #this function rolls the penetration die, and checks to see if it needs to be re-rolled again. + def pen_roll(self,num): result = int(random.uniform(1,self.data[num].sides+1)) self.data[num].value += (result - 1 + self.hon) @@ -101,6 +111,7 @@ # this function rolls for the HM Attack. the function checks for a 20 and displays critical, and a 1 # and displays fumble class HMattack(std): + def __init__(self, source=[], mod = 0, base_severity = 0, hon = 0, size = 0): std.__init__(self,source) self.size = size @@ -116,6 +127,7 @@ self.append(static_di(self.hon)) + def check_crit(self): if self.data[0] == self.data[0].sides: self.crit = 1 @@ -125,6 +137,7 @@ #this function is the out put to the chat window, it basicaly just displays the roll unless #it's a natural 20, or a natural 1 + def __str__(self): if self.crit > 0: myStr = "Critical Hit!!: " @@ -140,10 +153,12 @@ return myStr class HMhelp(std): + def __init__(self,source=[]): std.__init__(self,source) self.source = source + def __str__(self): myStr = " <br /> .attack(Bonus, Honor): <br />" myStr += " The attack roll rolles the dice and adds your bonus <br />" @@ -171,6 +186,7 @@ # the severity roll is for critical resolution. The die is rerolled and added #on a natural 8 and rerolled and subtracted on a 1 class HMSeverity(std): + def __init__(self, source =[], honor=0): std.__init__(self,source) self.source = source @@ -181,6 +197,7 @@ self.append(static_di(self.hon)) + def __str__(self): myStr = "[Severity Dice, Honor]" + " [" + str(self.data[0]) for a in self.data[1:]: @@ -189,6 +206,7 @@ myStr += "] = (" + str(self.sum()) + ")" return myStr + def CheckReroll(self): if self.data[0] == self.data[0].sides: self.crit_chain(0,1) @@ -196,6 +214,7 @@ self.crit_chain(0,-1) #this function needes moved for severity + def crit_chain(self,num,neg): result = int(random.uniform(1,self.data[num].sides+1)) self.data[num].value += (((result - 1) * neg) + self.hon)
--- a/orpg/dieroller/hero.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/hero.py Thu Aug 27 01:04:43 2009 -0500 @@ -33,42 +33,50 @@ from time import time, clock import random - __version__ = "$Id: hero.py,v 1.15 2006/11/04 21:24:19 digitalxero Exp $" # Hero stands for "Hero system" not 20 sided die :) class hero(std): + def __init__(self,source=[]): std.__init__(self,source) # these methods return new die objects for specific options + def k(self,mod): return herok(self,mod) + def hl(self): return herohl(self) + def hk(self): return herohk(self) + def n(self): return heron(self) + def cv(self,cv,mod): return herocv(self,cv,mod) + def sk(self,sk,mod): return herosk(self,sk,mod) class herocv(std): + def __init__(self,source=[],cv=10,mod=0): std.__init__(self,source) self.cv = cv self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -83,14 +91,17 @@ return myStr class herosk(std): + def __init__(self,source=[],sk=11,mod=0): std.__init__(self,source) self.sk = sk self.mod = mod + def is_success(self): return (((self.sum()-self.mod) <= self.sk)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -117,10 +128,12 @@ return myStr class herok(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -138,10 +151,12 @@ return myStr class herohl(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) side = random.randint(1,6) @@ -182,10 +197,12 @@ return myStr class herohk(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -200,10 +217,12 @@ return myStr class heron(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.bodtot=0 + def __str__(self): myStr = "[" + str(self.data[0]) if self.data[0] == 6:
--- a/orpg/dieroller/runequest.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/runequest.py Thu Aug 27 01:04:43 2009 -0500 @@ -61,40 +61,48 @@ import random from math import floor - __version__ = "$Id: runequest.py,v 1.4 2006/11/15 12:11:22 digitalxero Exp $" # rq stands for "Runequest" class runequest(std): - def __init__(self,source=[]): - std.__init__(self,source) + + def __init__(self,source=[]): + std.__init__(self,source) -# these methods return new die objects for specific options + # these methods return new die objects for specific options - def skill(self,sk,mod,ma): - return rqskill(self,sk,mod,ma) + + def skill(self,sk,mod,ma): + return rqskill(self,sk,mod,ma) - def parry(self,sk,mod,ma,AP): - return rqparry(self,sk,mod,ma,AP) + + def parry(self,sk,mod,ma,AP): + return rqparry(self,sk,mod,ma,AP) - def dodge(self,sk,mod,ma): - return rqdodge(self,sk,mod,ma) + + def dodge(self,sk,mod,ma): + return rqdodge(self,sk,mod,ma) - def attack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd): - return rqattack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd) + + def attack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd): + return rqattack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd) - def sorcery(self,sk,mod,pow,cer,int,acc,mlt): - return rqsorcery(self,sk,mod,pow,cer,int,acc,mlt) + + def sorcery(self,sk,mod,pow,cer,int,acc,mlt): + return rqsorcery(self,sk,mod,pow,cer,int,acc,mlt) - def trainskill(self,initial,final): - return rqtrainskill(self,initial,final) + + def trainskill(self,initial,final): + return rqtrainskill(self,initial,final) - def trainskillcost(self,cost,sk): - return rqtrainskillcost(self,cost,sk) + + def trainskillcost(self,cost,sk): + return rqtrainskillcost(self,cost,sk) - def trainskilltime(self,time,sk): - return rqtrainskilltime(self,time,sk) + + def trainskilltime(self,time,sk): + return rqtrainskilltime(self,time,sk) # RQ Skill Training Cost/Time unlimited # @@ -105,32 +113,34 @@ # # class rqtrainskill(std): - def __init__(self,source=[],initial=11,final=0): - std.__init__(self,source) - self.s = initial - self.f = final + + def __init__(self,source=[],initial=11,final=0): + std.__init__(self,source) + self.s = initial + self.f = final - def __str__(self): - myStr = "Unrestricted Training" + + def __str__(self): + myStr = "Unrestricted Training" - if self.s == 0: - myStr = "Initial training completed for Cost(50) Time(20) Skill(1 + modifier)" - else: - cost = 0 - time = 0 - myStr = "Training: " + if self.s == 0: + myStr = "Initial training completed for Cost(50) Time(20) Skill(1 + modifier)" + else: + cost = 0 + time = 0 + myStr = "Training: " - while self.s < self.f and self.s < 75: - cost += self.s * 5 - time += self.s * 1 - self.s += random.uniform(1,4) + 1 + while self.s < self.f and self.s < 75: + cost += self.s * 5 + time += self.s * 1 + self.s += random.uniform(1,4) + 1 - myStr = "Training completed:\n" - myStr += "\tCost(" + str(int(cost)) + ")\n" - myStr += "\tTime(" + str(int(time)) + ")\n" - myStr += "\tSkill(" + str(int(self.s)) + ")" + myStr = "Training completed:\n" + myStr += "\tCost(" + str(int(cost)) + ")\n" + myStr += "\tTime(" + str(int(time)) + ")\n" + myStr += "\tSkill(" + str(int(self.s)) + ")" - return myStr + return myStr # RQ Skill Training Cost Limited @@ -143,38 +153,40 @@ # # class rqtrainskillcost(std): - def __init__(self,source=[],cost=11,sk=0): - std.__init__(self,source) - self.cost = cost - self.sk = sk + + def __init__(self,source=[],cost=11,sk=0): + std.__init__(self,source) + self.cost = cost + self.sk = sk - def __str__(self): - myStr = "" + + def __str__(self): + myStr = "" - if self.sk == 0 and self.cost >= 50: - myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" - else: - cost = 0 - time = 0 - icost = self.sk * 5 + if self.sk == 0 and self.cost >= 50: + myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" + else: + cost = 0 + time = 0 + icost = self.sk * 5 - myStr = "Training: " + myStr = "Training: " - while (cost + icost) < self.cost: - if self.sk >= 75: - break + while (cost + icost) < self.cost: + if self.sk >= 75: + break - cost += icost - time += self.sk * 1 - self.sk += random.uniform(1,4) + 1 - icost = self.sk * 5 + cost += icost + time += self.sk * 1 + self.sk += random.uniform(1,4) + 1 + icost = self.sk * 5 - myStr = "Training completed: " - myStr += "Cost(" + str(int(cost)) + ") " - myStr += "Time(" + str(int(time)) + ") " - myStr += "Skill(" + str(int(self.sk)) + ")" + myStr = "Training completed: " + myStr += "Cost(" + str(int(cost)) + ") " + myStr += "Time(" + str(int(time)) + ") " + myStr += "Skill(" + str(int(self.sk)) + ")" - return myStr + return myStr # RQ Skill Training Time Limited @@ -187,38 +199,40 @@ # # class rqtrainskilltime(std): - def __init__(self,source=[],time=11,sk=0): - std.__init__(self,source) - self.time = time - self.sk = sk + + def __init__(self,source=[],time=11,sk=0): + std.__init__(self,source) + self.time = time + self.sk = sk - def __str__(self): - myStr = "" + + def __str__(self): + myStr = "" - if self.sk == 0 and self.time >= 20: - myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" - else: - cost = 0 - time = 0 - itime = self.sk * 1 + if self.sk == 0 and self.time >= 20: + myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" + else: + cost = 0 + time = 0 + itime = self.sk * 1 - myStr = "Trainingsss: " + myStr = "Trainingsss: " - while (time + itime) < self.time: - if self.sk >= 75: - break + while (time + itime) < self.time: + if self.sk >= 75: + break - cost += self.sk * 5 - time += itime - self.sk += random.uniform(1,4) + 1 - itime = self.sk * 5 + cost += self.sk * 5 + time += itime + self.sk += random.uniform(1,4) + 1 + itime = self.sk * 5 - myStr = "Training completed: " - myStr += "Cost(" + str(int(cost)) + ") " - myStr += "Time(" + str(int(time)) + ") " - myStr += "Skill(" + str(int(self.sk)) + ")" + myStr = "Training completed: " + myStr += "Cost(" + str(int(cost)) + ") " + myStr += "Time(" + str(int(time)) + ") " + myStr += "Skill(" + str(int(self.sk)) + ")" - return myStr + return myStr # RQ Skill Roll # @@ -245,60 +259,61 @@ # if ( $fum == 100 ) { $fum = '00'; }; # class rqskill(std): - def __init__(self,source=[],sk=11,mod=0,ma=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma + + def __init__(self,source=[],sk=11,mod=0,ma=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - - def is_ma(self): - return (self.sum() <= self.ma) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod)/5))) - - def is_critical(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 20))) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod)/5))) + + + def is_critical(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 20))) - def __str__(self): - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font></b>" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font></b>" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font></i>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font></i>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font>" - else: - myStr += " <font color=red>Failure!</font>" + + def __str__(self): + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - Diff = self.sk - modSum - myStr += " </font>" + if self.is_fumble(): myStr += " <b><font color=red>Fumble!</font></b>" + elif self.is_critical(): myStr += " <b><font color=green>Critical!</font></b>" + elif self.is_special(): myStr += " <i><font color=green>Special!</font></i>" + elif self.is_success() and self.is_ma(): myStr += " <i><font color=green>Special!</font></i>" + elif self.is_success(): myStr += " <font color=blue>Success!</font>" + else: myStr += " <font color=red>Failure!</font>" - return myStr + Diff = self.sk - modSum + myStr += " </font>" + + return myStr # # RQ Parry Roll @@ -310,79 +325,87 @@ # class rqparry(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.AP = AP + + def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.AP = AP - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_riposte(self): - return (self.sum() <= (self.ma / 5)) + + def is_riposte(self): + return (self.sum() <= (self.ma / 5)) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): - - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + + def __str__(self): - # get special AP - spec_AP = int( floor ( self.AP * 1.5 ) ) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) + + # get special AP + spec_AP = int( floor ( self.AP * 1.5 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif self.is_critical() and self.is_riposte(): - myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" - myStr += " Riposte next SR" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" - elif self.is_special and self.is_riposte(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - myStr += " Riposte next SR" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Weapon/Shield AP [" + str(self.AP) + "]" - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif self.is_critical() and self.is_riposte(): + myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" + myStr += " Riposte next SR" + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" + elif self.is_special and self.is_riposte(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + myStr += " Riposte next SR" + elif self.is_special(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + elif self.is_success() and self.is_ma(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Weapon/Shield AP [" + str(self.AP) + "]" + else: + myStr += " <font color=red>Failure!</font>" - Diff = self.sk - modSum - myStr += " </font>" + Diff = self.sk - modSum + myStr += " </font>" - return myStr + return myStr # RQ Dodge Roll # @@ -393,79 +416,87 @@ # class rqdodge(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.AP = AP + + def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.AP = AP - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_riposte(self): - return (self.sum() <= (self.ma / 5)) + + def is_riposte(self): + return (self.sum() <= (self.ma / 5)) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): - - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + + def __str__(self): - # get special AP - spec_AP = int( floor ( self.AP * 1.5 ) ) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) + + # get special AP + spec_AP = int( floor ( self.AP * 1.5 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif self.is_critical() and self.is_riposte(): - myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" - myStr += " Riposte on next SR" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" - elif self.is_special and self.is_riposte(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - myStr += " Riposte on next SR" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Damage dodged</b>" - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif self.is_critical() and self.is_riposte(): + myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" + myStr += " Riposte on next SR" + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" + elif self.is_special and self.is_riposte(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + myStr += " Riposte on next SR" + elif self.is_special(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + elif self.is_success() and self.is_ma(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Damage dodged</b>" + else: + myStr += " <font color=red>Failure!</font>" - Diff = self.sk - modSum - myStr += " </font>" + Diff = self.sk - modSum + myStr += " </font>" - return myStr + return myStr @@ -478,108 +509,116 @@ # skill%, modifer, ma%, min weap dam, max weap dam, dam bonus, truesword_enabled # class rqattack(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,mindam=0,maxdam=0,bondam=0,trueswd=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.mindam = mindam - self.maxdam = maxdam - self.bondam = bondam - self.trueswd = trueswd + + def __init__(self,source=[],sk=11,mod=0,ma=0,mindam=0,maxdam=0,bondam=0,trueswd=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.mindam = mindam + self.maxdam = maxdam + self.bondam = bondam + self.trueswd = trueswd + + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_critical(self): + return ((self.sum() <= int(floor((self.sk + self.mod) / 20)))) - def is_critical(self): - return ((self.sum() <= int(floor((self.sk + self.mod) / 20)))) - - def is_supercritical(self): - return (self.sum() == 1) + + def is_supercritical(self): + return (self.sum() == 1) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): + + def __str__(self): - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) - # get hit location roll result in case needed - location = random.randint(1,20) - myStr = " to the ["+ str(location) + "] " - if location < 5: - myStr += "<B>Right Leg</B>" - elif location < 9: - myStr += "<B>Left Leg</B>" - elif location < 12: - myStr += "<B>Abdomen</B>" - elif location < 13: - myStr += "<B>Chest</B>" - elif location < 16: - myStr += "<B>Right Arm</B>" - elif location < 19: - myStr += "<B>Left Arm</B>" - else: - myStr += "<B>Head</B>" - hit_loc = myStr + # get hit location roll result in case needed + location = random.randint(1,20) + myStr = " to the ["+ str(location) + "] " + if location < 5: + myStr += "<B>Right Leg</B>" + elif location < 9: + myStr += "<B>Left Leg</B>" + elif location < 12: + myStr += "<B>Abdomen</B>" + elif location < 13: + myStr += "<B>Chest</B>" + elif location < 16: + myStr += "<B>Right Arm</B>" + elif location < 19: + myStr += "<B>Left Arm</B>" + else: + myStr += "<B>Head</B>" + hit_loc = myStr - # get normal damage in case needed - norm_damage = random.randint(self.mindam*(self.trueswd+1),self.maxdam*(self.trueswd+1)) + self.bondam - norm_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" - norm_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.bondam) - norm_damage_string += "}[" + str(norm_damage) + "] " + # get normal damage in case needed + norm_damage = random.randint(self.mindam*(self.trueswd+1),self.maxdam*(self.trueswd+1)) + self.bondam + norm_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" + norm_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.bondam) + norm_damage_string += "}[" + str(norm_damage) + "] " - # get special/critical damage in case needed - crit_damage = random.randint( self.mindam*(self.trueswd+2), self.maxdam*(self.trueswd+2) ) + self.bondam - crit_damage_string = "{" + str( self.mindam*(self.trueswd+2) ) + "-" + str(self.maxdam*(self.trueswd+2)) + "+" + str(self.bondam) + "}[" + str(crit_damage) + "] " + # get special/critical damage in case needed + crit_damage = random.randint( self.mindam*(self.trueswd+2), self.maxdam*(self.trueswd+2) ) + self.bondam + crit_damage_string = "{" + str( self.mindam*(self.trueswd+2) ) + "-" + str(self.maxdam*(self.trueswd+2)) + "+" + str(self.bondam) + "}[" + str(crit_damage) + "] " - # get supercritical damage in case needed - super_damage = norm_damage + self.maxdam - super_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" - super_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.maxdam) - super_damage_string += "+" + str(self.bondam) + "}[" + str(super_damage) + "] " + # get supercritical damage in case needed + super_damage = norm_damage + self.maxdam + super_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" + super_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.maxdam) + super_damage_string += "+" + str(self.bondam) + "}[" + str(super_damage) + "] " - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif (self.is_supercritical() and self.is_success()): - myStr += " <b><font color=green>Super Critical!</font></b> Damage: " + str(super_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) - elif (self.is_critical() and self.is_success()): - myStr += " <b><font color=green>Critical!</font></b> Damage: " + str(crit_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) - elif ( self.is_special() and self.is_success() ): - myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) - elif (self.is_success() and self.is_ma()): - myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Damage: " + str(norm_damage_string) + str(hit_loc) - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif (self.is_supercritical() and self.is_success()): + myStr += " <b><font color=green>Super Critical!</font></b> Damage: " + str(super_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) + elif (self.is_critical() and self.is_success()): + myStr += " <b><font color=green>Critical!</font></b> Damage: " + str(crit_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) + elif ( self.is_special() and self.is_success() ): + myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) + elif (self.is_success() and self.is_ma()): + myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Damage: " + str(norm_damage_string) + str(hit_loc) + else: + myStr += " <font color=red>Failure!</font>" - return myStr + return myStr # # @@ -595,102 +634,107 @@ # Hold: (-2% per point in spell Held) # class rqsorcery(std): - def __init__(self,source=[],sk=11,mod=0,pow=0,cer=0,int=0,acc=0,mlt=0): - std.__init__(self,source) - self.sk = sk # sorcery skill - self.mod = mod # additional modifier ( from duration, range, etc ) - self.pow = pow # boost pow and additional pow ( from duration, range, etc ) - self.cer = cer # ceremony d6 - self.int = int # intensity ( -3% ) - self.acc = acc # accelerate ( -5% ) - self.mlt = mlt # multispell ( -10% ) + + def __init__(self,source=[],sk=11,mod=0,pow=0,cer=0,int=0,acc=0,mlt=0): + std.__init__(self,source) + self.sk = sk # sorcery skill + self.mod = mod # additional modifier ( from duration, range, etc ) + self.pow = pow # boost pow and additional pow ( from duration, range, etc ) + self.cer = cer # ceremony d6 + self.int = int # intensity ( -3% ) + self.acc = acc # accelerate ( -5% ) + self.mlt = mlt # multispell ( -10% ) - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/5 ) ) ) ) + + def is_special(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/5 ) ) ) ) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): + + def __str__(self): - # get fumble roll result in case needed - fum_roll = random.randint(2,12) - if fum_roll == 12 : - fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each day to remember.</font>" - if fum_roll == 11 : - fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each hour to remember. </font>" - if fum_roll == 10 : - fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect. </font>" - if fum_roll == 9 : - fum_string = "<br /><font color=purple>Caster is Stunned. Roll INTx3 to recover at SR 10 each round. </font>" - if fum_roll == 8 : - fum_string = "<br /><font color=purple>Caster takes 2D6 Damage to THP </font>" - if fum_roll == 7 : - fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect at 2x Intensity. </font>" - if fum_roll == 6 : - fum_string = "<br /><font color=purple>Spell is cast on companions (if harmful) or on random nearby foes (if beneficial) </font>" - if fum_roll == 5 : - fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to Head </font>" - if fum_roll == 4 : - fum_string = "<br /><font color=purple>Spell is cast on caster (if harmful) or on random nearby foe (if beneficial) </font>" - if fum_roll == 3 : - fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to THP </font>" - if fum_roll == 2 : - fum_string = "<br /><font color=purple>Caster takes 1 point of Damage to Head </font>" + # get fumble roll result in case needed + fum_roll = random.randint(2,12) + if fum_roll == 12 : + fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each day to remember.</font>" + if fum_roll == 11 : + fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each hour to remember. </font>" + if fum_roll == 10 : + fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect. </font>" + if fum_roll == 9 : + fum_string = "<br /><font color=purple>Caster is Stunned. Roll INTx3 to recover at SR 10 each round. </font>" + if fum_roll == 8 : + fum_string = "<br /><font color=purple>Caster takes 2D6 Damage to THP </font>" + if fum_roll == 7 : + fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect at 2x Intensity. </font>" + if fum_roll == 6 : + fum_string = "<br /><font color=purple>Spell is cast on companions (if harmful) or on random nearby foes (if beneficial) </font>" + if fum_roll == 5 : + fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to Head </font>" + if fum_roll == 4 : + fum_string = "<br /><font color=purple>Spell is cast on caster (if harmful) or on random nearby foe (if beneficial) </font>" + if fum_roll == 3 : + fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to THP </font>" + if fum_roll == 2 : + fum_string = "<br /><font color=purple>Caster takes 1 point of Damage to Head </font>" - # roll ceremony - ceremony_roll = random.randint( self.cer, (self.cer*6) ) + # roll ceremony + ceremony_roll = random.randint( self.cer, (self.cer*6) ) - # subtract manipulations - extra_mod = self.mod - self.mod += ceremony_roll - self.int*3 - self.acc*5 - self.mlt*10 + # subtract manipulations + extra_mod = self.mod + self.mod += ceremony_roll - self.int*3 - self.acc*5 - self.mlt*10 - # add up power cost - extra_pow = self.pow - self.pow += self.int + self.mlt + self.acc - special_pow = int( floor( ( self.pow )/2 ) ) + # add up power cost + extra_pow = self.pow + self.pow += self.int + self.mlt + self.acc + special_pow = int( floor( ( self.pow )/2 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> POW Cost: [" + str(self.pow) + "],</b> " + fum_string - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font></b> POW Cost: [1] " - elif self.is_special(): - myStr += " <i><font color=green>Special!</font></i> POW Cost: [" + str(special_pow) + "] " - elif self.is_success(): - myStr += " <font color=blue>Success!</font> POW Cost: [" + str(self.pow) + "] " - else: - myStr += " <font color=red>Failure!</font> POW Cost: [1]" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> POW Cost: [" + str(self.pow) + "],</b> " + fum_string + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font></b> POW Cost: [1] " + elif self.is_special(): + myStr += " <i><font color=green>Special!</font></i> POW Cost: [" + str(special_pow) + "] " + elif self.is_success(): + myStr += " <font color=blue>Success!</font> POW Cost: [" + str(self.pow) + "] " + else: + myStr += " <font color=red>Failure!</font> POW Cost: [1]" - # print spell details - myStr += "<br /> --- Other Modifiers:[" + str( extra_mod ) + "], " - myStr += "Extra POW:[" + str( extra_pow ) + "], " - myStr += "Ceremony:[+" + str( ceremony_roll ) + "%], " - myStr += "Intensity(-3):[" + str( self.int ) + "], " - myStr += "Accelerate(-5):[" + str( self.acc ) + "], " - myStr += "Multispell(-10):[" + str( self.mlt ) + "] ---" + # print spell details + myStr += "<br /> --- Other Modifiers:[" + str( extra_mod ) + "], " + myStr += "Extra POW:[" + str( extra_pow ) + "], " + myStr += "Ceremony:[+" + str( ceremony_roll ) + "%], " + myStr += "Intensity(-3):[" + str( self.int ) + "], " + myStr += "Accelerate(-5):[" + str( self.acc ) + "], " + myStr += "Multispell(-10):[" + str( self.mlt ) + "] ---" - return myStr - + return myStr
--- a/orpg/dieroller/savage.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/savage.py Thu Aug 27 01:04:43 2009 -0500 @@ -20,8 +20,6 @@ # from die import * -#from whrandom import randint -#import random import string from random import * __version__ = "$Id: savage.py,v 1.2 2007/05/06 16:42:55 digitalxero Exp $" @@ -29,32 +27,41 @@ # Savage, as in Savage Worlds class sw(std): #def __init__(self,source=[], wnd=1, loc="rnd", chmod=0): + def __init__(self,source=[],fmod=0): std.__init__(self,source) # these methods return new die objects for specific options + def fright(self,fearmod=0): return fright(self,fearmod=0) + def kob(self,wnd,loc): return kob(self,wnd=1,loc="rnd") + def ooc(self): return ooc(self) + def ract(self,chmod=0): return ract(self,chmod=0) + def vcrit(self): return vcrit(self) + def fortune(self): return fortune(self) + def freak(self): return freak(self) + def swdhelps(self): return swdhelps(self) @@ -67,6 +74,7 @@ # Usage: [fright()] # [fright(6)] - if the fear modifier of the monster was 6 #----------------- + def __init__(self,fmod=0): global fear std.__init__(self) @@ -74,6 +82,7 @@ #def sum(self): + def __str__(self): global fear iroll = randint(1,20) @@ -118,6 +127,7 @@ # [kob(3,"h") - If 3 wounds were received that sent the player to the Knockout Blow Table with a called shot to the head #--------------------- global wound, loca + def __init__(self, wnd, loc="rnd"): global wound, loca std.__init__(self, wnd) @@ -129,6 +139,7 @@ mystr = "You need to supply a number for the wound." return mystr + def __str__(self): global wound, loca itbl = "no" @@ -235,11 +246,13 @@ # [ract(-2)] - A -2 Charisma modifier #---------------------- global charisma + def __init__(self,chmod=0): global charisma std.__init__(self) charisma = chmod + def __str__(self): global charisma r1roll = randint(2,12) @@ -269,9 +282,11 @@ # roll and displays the results of the roll. This will also display altitude information for flying vehicles. # Usage: [ooc()] #-------------------- + def __init__(self): std.__init__(self) + def __str__(self): ooroll = randint(2,12) oodescripton = "Something" @@ -331,9 +346,11 @@ # modifiers to this roll # Usage [vcrit()] #---------------- + def __init__(self): std.__init__(self) + def __str__(self): chitroll = randint(2,12) if chitroll == 2: @@ -373,9 +390,11 @@ class swdhelps(std): #Display help information for this die roller - it will list all the available commands, and how to use them + def __init__(self): std.__init__(self) + def __str__(self): myStr = "<table border='1' valign='top'>\ <tr>\ @@ -421,9 +440,11 @@ return myStr class fortune(std): + def __init___(self): std.__init__(self) + def __str__(self): forroll = randint(2,12) if forroll == 2 or forroll == 12: #Need to roll on Freak Event Table @@ -453,13 +474,16 @@ myStr = "["+fortune+" ("+str(forroll)+")] ==>"+fdescription return myStr + def freak(self): return fortunefreak(self) class freak(std): + def __init__(self): std.__init__(self) + def __str__(self): feroll = randint(1,10) if feroll == 1: @@ -500,8 +524,10 @@ return myStr class rdm(std): #If I get the time and the inspiration - I may try to incorporate a Random Table roller... I need to think about this one. + def __init__(self): std.__init__(self) + def __str__(self): return myStr
--- a/orpg/dieroller/shadowrun.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/shadowrun.py Thu Aug 27 01:04:43 2009 -0500 @@ -43,20 +43,24 @@ # the objective is to find the highest die total out of rolled dice. This is then generally # used as the target in a 'Success Test' (for which .vs functions) from die import * - + __version__ = "1.0" class shadowrun(std): + def __init__(self,source=[],target=2): std.__init__(self,source) + def vs(self,target): return srVs(self, target) + def open(self): return srOpen(self) class srVs(std): + def __init__(self,source=[], target=2): std.__init__(self, source) # In Shadowrun, not target number may be below 2. All defaults are set to two and any @@ -69,6 +73,7 @@ # made the dieroller generic enough to use any die type self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -82,6 +87,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -89,6 +95,7 @@ s += 1 return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -102,10 +109,12 @@ return myStr class srOpen(std): + def __init__(self,source=[]): std.__init__(self,source) self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -119,6 +128,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -126,6 +136,7 @@ s = r return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/sr4.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/sr4.py Thu Aug 27 01:04:43 2009 -0500 @@ -68,25 +68,32 @@ GLITCH_NUMBER = 1 class sr4(std): + def __init__(self,source=[]): std.__init__(self,source) self.threshold = None self.init_attrib = None + def vs(self,threshold=0): return sr4vs(self, threshold) + def edge(self,threshold=0): return sr4vs(self, threshold, 1) + def init(self,init_attrib=0): return sr4init(self, init_attrib) + def initedge(self,init_attrib=0): return sr4init(self, init_attrib, 1) + def edgeinit(self,init_attrib=0): return sr4init(self, init_attrib, 1) + def countEdge(self,num): if num <= 1: self @@ -106,6 +113,7 @@ else: return self.countEdge(num) + def countHits(self,num): for i in range(len(self.data)): if (self.data[i].lastroll() >= MIN_TARGET_NUMBER): @@ -115,6 +123,7 @@ self.ones += 1 self.total += 1 + def __str__(self): if len(self.data) > 0: self.hits = 0 @@ -145,6 +154,7 @@ return myStr class sr4init(sr4): + def __init__(self,source=[],init_attrib=1,edge=0): std.__init__(self,source) if init_attrib < 2: @@ -159,6 +169,7 @@ self.countEdge(self.dicesides) self.countHits(self.dicesides) + def __str__(self): if len(self.data) > 0: firstpass = 0 @@ -182,6 +193,7 @@ return myStr class sr4vs(sr4): + def __init__(self,source=[], threshold=1, edge=0): std.__init__(self, source) if threshold < 0: @@ -196,6 +208,7 @@ self.countEdge(self.dicesides) self.countHits(self.dicesides) + def __str__(self): if len(self.data) > 0: firstpass = 0 @@ -222,6 +235,7 @@ myStr = "[] = (0)" return myStr + def CheckIfGlitch(ones, hits, total_dice): if (ones * 2) >= total_dice: if hits >= 1:
--- a/orpg/dieroller/srex.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/srex.py Thu Aug 27 01:04:43 2009 -0500 @@ -59,19 +59,24 @@ __version__ = "1.1" class srex(std): + def __init__(self,source=[]): std.__init__(self,source) + def vs(self,actualtarget=4,tnrange=3): #reports all tns around specified, max distance of range return srVs(self,actualtarget,(actualtarget-tnrange),(actualtarget+tnrange)) + def vswide(self,actualtarget=4,maxtarget=12): #wide simply means it reports TNs from 2 to a specified max. return srVs(self,actualtarget,2,maxtarget) + def open(self): #unchanged from standard shadowrun open. return srOpen(self) class srVs(std): + def __init__(self,source=[],actualtarget=4,mintn=2,maxtn=12): std.__init__(self, source) if actualtarget > 30: @@ -100,6 +105,7 @@ # made the dieroller generic enough to use any die type self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -116,6 +122,7 @@ return self.openended(num) #count successes, by looping through each die, and checking it against the currently set TN + def __sum__(self): s = 0 for r in self.data: @@ -126,6 +133,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. + def xsum(self,curtarget): s = 0 for r in self.data: @@ -134,6 +142,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -154,10 +163,12 @@ return myStr class srOpen(std): + def __init__(self,source=[]): std.__init__(self,source) self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -171,6 +182,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -178,6 +190,7 @@ s = r return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/trinity.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/trinity.py Thu Aug 27 01:04:43 2009 -0500 @@ -37,47 +37,52 @@ class trinity(std): - def __init__(self,source=[],target=7,targetthr=0): - std.__init__(self,source) - self.target = target - self.targetthr = targetthr + + def __init__(self,source=[],target=7,targetthr=0): + std.__init__(self,source) + self.target = target + self.targetthr = targetthr - def vs(self,target): - self.target = target - return self + + def vs(self,target): + self.target = target + return self - def thr(self,targetthr): - self.targetthr = targetthr - return self + + def thr(self,targetthr): + self.targetthr = targetthr + return self - def sum(self): - rolls = [] - s = 0 - b = 0 - for a in self.data: - rolls.extend(a.gethistory()) - for r in rolls: - if r >= self.target: - s += 1 - elif r == 1: - b -= 1 - if s == 0: - return b - else: - return s + + def sum(self): + rolls = [] + s = 0 + b = 0 + for a in self.data: + rolls.extend(a.gethistory()) + for r in rolls: + if r >= self.target: + s += 1 + elif r == 1: + b -= 1 + if s == 0: + return b + else: + return s - def __str__(self): - if len(self.data) > 0: - myStr = "[" + str(self.data[0]) - for a in self.data[1:]: - myStr += "," - myStr += str(a) - if self.sum() < 0: - myStr += "] result of a (" + str(self.sum()) + ") botch" - elif self.sum() == 0: - myStr += "] result of a failure" - else: - myStr += "] result of (" + str(self.sum()) + ") success" + + def __str__(self): + if len(self.data) > 0: + myStr = "[" + str(self.data[0]) + for a in self.data[1:]: + myStr += "," + myStr += str(a) + if self.sum() < 0: + myStr += "] result of a (" + str(self.sum()) + ") botch" + elif self.sum() == 0: + myStr += "] result of a failure" + else: + myStr += "] result of (" + str(self.sum()) + ") success" - return myStr + return myStr
--- a/orpg/dieroller/utils.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/utils.py Thu Aug 27 01:04:43 2009 -0500 @@ -41,48 +41,46 @@ from gurps import * from runequest import * from savage import * -from trinity import * - +from trinity import * import re rollers = ['std','wod','d20','hero','shadowrun', 'sr4','hackmaster','srex','wodex', 'gurps', 'runequest', 'sw', 'trinity'] class roller_manager: + def __init__(self,roller_class="d20"): - try: - self.setRoller(roller_class) - except: - self.roller_class = "std" + try: self.setRoller(roller_class) + except: self.roller_class = "std" + def setRoller(self,roller_class): try: rollers.index(roller_class) self.roller_class = roller_class - except: - raise Exception, "Invalid die roller!" + except: raise Exception, "Invalid die roller!" + def getRoller(self): return self.roller_class + def listRollers(self): return rollers + def stdDieToDClass(self,match): s = match.group(0) (num,sides) = s.split('d') - if sides.strip().upper() == 'F': - sides = "'f'" - + if sides.strip().upper() == 'F': sides = "'f'" try: if int(num) > 100 or int(sides) > 10000: return None - except: - pass - + except: pass return "(" + num.strip() + "**" + self.roller_class + "(" + sides.strip() + "))" # Use this to convert ndm-style (3d6) dice to d_base format + def convertTheDieString(self,s): reg = re.compile("\d+\s*[a-zA-Z]+\s*[\dFf]+") (result, num_matches) = reg.subn(self.stdDieToDClass, s) @@ -91,10 +89,11 @@ s2 = self.roller_class + "(0)." + s test = eval(s2) return s2 - except: - pass + except: pass return result - + def proccessRoll(self,s): - return str(eval(self.convertTheDieString(s))) + return str(eval(self.convertTheDieString(s))) + +DiceManager = roller_manager
--- a/orpg/dieroller/wod.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/wod.py Thu Aug 27 01:04:43 2009 -0500 @@ -36,19 +36,23 @@ class wod(std): + def __init__(self,source=[],target=0,targetthr=0): std.__init__(self,source) self.target = target self.targetthr = targetthr + def vs(self,target): self.target = target return self + def thr(self,targetthr): self.targetthr = targetthr return self + def sum(self): rolls = [] s = 0 @@ -70,6 +74,7 @@ s = 0 return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/wodex.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dieroller/wodex.py Thu Aug 27 01:04:43 2009 -0500 @@ -36,25 +36,32 @@ __version__ = "$Id: wodex.py,v 1.9 2007/05/06 16:42:55 digitalxero Exp $" class wodex(std): + def __init__(self,source=[]): std.__init__(self,source) + def vs(self,actualtarget=6): return oldwodVs(self,actualtarget,(6)) + def wod(self,actualtarget=8): return newwodVs(self,actualtarget,(8)) + def exalt(self, actualtarget=7): return exaltVs(self, actualtarget) + def exaltDmg(self, actualtarget=7): return exaltDmg(self, actualtarget) + def vswide(self,actualtarget=6,maxtarget=10): #wide simply means it reports TNs from 2 to a specified max. return oldwodVs(self,actualtarget,2,maxtarget) class oldwodVs(std): + def __init__(self,source=[],actualtarget=6,mintn=2,maxtn=10): std.__init__(self, source) if actualtarget > 10: @@ -84,6 +91,7 @@ #count successes, by looping through each die, and checking it against the currently set TN #1's subtract successes. + def __sum__(self): s = 0 for r in self.data: @@ -96,6 +104,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. 1s subtract successes from everything. + def xsum(self,curtarget): s = 0 for r in self.data: @@ -106,6 +115,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -126,6 +136,7 @@ return myStr class newwodVs(std): + def __init__(self,source=[],actualtarget=8,mintn=8,maxtn=8): std.__init__(self, source) if actualtarget > 30: @@ -156,6 +167,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. 1s subtract successes from original but not re-rolls. + def xsum(self,curtarget,subones=1): s = 0 done = 1 @@ -173,6 +185,7 @@ else: return self.xsum(0) + def openended(self,num): if num <= 1: self @@ -187,6 +200,7 @@ return self.openended(num) + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -207,6 +221,7 @@ return myStr class exaltVs(std): + def __init__(self, source=[], actualtarget=7): std.__init__(self, source) @@ -219,6 +234,7 @@ self.target = actualtarget + def xsum(self, target): s = 0 @@ -231,6 +247,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = str(self.data) @@ -249,6 +266,7 @@ return myStr class exaltDmg(std): + def __init__(self, source=[], actualtarget=7): std.__init__(self, source) if actualtarget > 10: @@ -259,6 +277,7 @@ else: self.target = actualtarget + def xsum(self, target): s = 0 @@ -267,6 +286,7 @@ s += 1 return s + def __str__(self): if len(self.data) > 0: myStr = str(self.data)
--- a/orpg/dirpath/dirpath_tools.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/dirpath/dirpath_tools.py Thu Aug 27 01:04:43 2009 -0500 @@ -8,7 +8,6 @@ def OnInit(self): return True - #------------------------------------------------------- # void load_paths( dir_struct_reference ) # moved structure loading from dirpath.py by Snowdog 3-8-05 @@ -27,10 +26,8 @@ dir_struct["nodes"] = dir_struct["template"] + "nodes" + os.sep dir_struct["rollers"] = dir_struct["core"] + "dieroller" + os.sep + "rollers" + os.sep - - _userbase_dir = _userbase_dir = os.environ['OPENRPG_BASE'] - _user_dir = _userbase_dir + os.sep + "myfiles" + os.sep - + _userbase_dir = dir_struct["home"] + _user_dir = dir_struct["home"] + "myfiles" + os.sep try: os.makedirs(_user_dir) @@ -38,15 +35,11 @@ os.makedirs(_user_dir + "logs" + os.sep); os.makedirs(_user_dir + "webfiles" + os.sep); except OSError, e: - if e.errno != errno.EEXIST: - raise + if e.errno != errno.EEXIST: raise dir_struct["user"] = _user_dir - dir_struct["logs"] = dir_struct["user"] + "logs" + os.sep - - #------------------------------------------------------- # int verify_home_path( directory_name ) # added by Snowdog 3-8-05 @@ -55,21 +48,18 @@ def verify_home_path( path ): """checks for key ORPG files in the openrpg tree and askes for user intervention if their is a problem""" - try: #verify that the root dir (as supplied) exists if not verify_file(path): return 0 - + #These checks require that 'path' have a separator at the end. #Check and temporarily add one if needed if (path[(len(path)-len(os.sep)):] != os.sep): path = path + os.sep - # These files should always exist at the root orpg dir check_files = ["orpg","data","images"] for n in range(len(check_files)): if not verify_file(path + check_files[n]): return 0 - except: # an error occured while verifying the directory structure # bail out with error signal @@ -78,8 +68,6 @@ #all files and directories exist. return 1 - - #------------------------------------------------------- # int verify_file( absolute_path ) # added by Snowdog 3-8-05 @@ -98,7 +86,8 @@ # pathname get_user_help() # added by Snowdog 3-8-05 # bug fix (SF #1242456) and updated with bailout code. Snowdog 7-25-05 -#------------------------------------------------------- +#------------------------------------------------------- +## This can be removed in the future. TaS '09 def get_user_located_root(): """Notify the user of directory problems and show directory selection dialog """ @@ -106,16 +95,15 @@ if WXLOADED: app = tmpApp(0) app.MainLoop() - + dir = None - try: msg = "OpenRPG cannot locate critical files.\nPlease locate the /System/ directory in the following window" alert= wx.MessageDialog(None,msg,"Warning",wx.OK|wx.ICON_ERROR) alert.Show() if alert.ShowModal() == wx.OK: alert.Destroy() - dlg = wx.DirDialog(None, "Locate the openrpg1 directory:",style=wx.DD_DEFAULT_STYLE) + dlg = wx.DirDialog(None, "Locate the System directory:",style=wx.DD_DEFAULT_STYLE) if dlg.ShowModal() == wx.ID_OK: dir = dlg.GetPath() dlg.Destroy()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/external/std.py Thu Aug 27 01:04:43 2009 -0500 @@ -0,0 +1,20 @@ + +import sys + +class Std(object): + """ + makes all standard python modules available as a lazily + computed attribute. + """ + + def __init__(self): + self.__dict__ = sys.modules + + def __getattr__(self, name): + try: + m = __import__(name) + except ImportError: + raise AttributeError("py.std: could not import %s" % name) + return m + +std = Std()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/external/terminalwriter.py Thu Aug 27 01:04:43 2009 -0500 @@ -0,0 +1,284 @@ +""" + +Helper functions for writing to terminals and files. + +""" + + +import sys, os +from orpg.external.std import std + +def _getdimensions(): + import termios,fcntl,struct + call = fcntl.ioctl(0,termios.TIOCGWINSZ,"\000"*8) + height,width = struct.unpack( "hhhh", call ) [:2] + return height, width + +if sys.platform == 'win32': + # ctypes access to the Windows console + + STD_OUTPUT_HANDLE = -11 + STD_ERROR_HANDLE = -12 + FOREGROUND_BLUE = 0x0001 # text color contains blue. + FOREGROUND_GREEN = 0x0002 # text color contains green. + FOREGROUND_RED = 0x0004 # text color contains red. + FOREGROUND_WHITE = 0x0007 + FOREGROUND_INTENSITY = 0x0008 # text color is intensified. + BACKGROUND_BLUE = 0x0010 # background color contains blue. + BACKGROUND_GREEN = 0x0020 # background color contains green. + BACKGROUND_RED = 0x0040 # background color contains red. + BACKGROUND_WHITE = 0x0070 + BACKGROUND_INTENSITY = 0x0080 # background color is intensified. + + def GetStdHandle(kind): + import ctypes + return ctypes.windll.kernel32.GetStdHandle(kind) + + def SetConsoleTextAttribute(handle, attr): + import ctypes + ctypes.windll.kernel32.SetConsoleTextAttribute( + handle, attr) + + def _getdimensions(): + import ctypes + from ctypes import wintypes + + SHORT = ctypes.c_short + class COORD(ctypes.Structure): + _fields_ = [('X', SHORT), + ('Y', SHORT)] + class SMALL_RECT(ctypes.Structure): + _fields_ = [('Left', SHORT), + ('Top', SHORT), + ('Right', SHORT), + ('Bottom', SHORT)] + class CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure): + _fields_ = [('dwSize', COORD), + ('dwCursorPosition', COORD), + ('wAttributes', wintypes.WORD), + ('srWindow', SMALL_RECT), + ('dwMaximumWindowSize', COORD)] + STD_OUTPUT_HANDLE = -11 + handle = GetStdHandle(STD_OUTPUT_HANDLE) + info = CONSOLE_SCREEN_BUFFER_INFO() + ctypes.windll.kernel32.GetConsoleScreenBufferInfo( + handle, ctypes.byref(info)) + # Substract one from the width, otherwise the cursor wraps + # and the ending \n causes an empty line to display. + return info.dwSize.Y, info.dwSize.X - 1 + +def get_terminal_width(): + try: + height, width = _getdimensions() + except (SystemExit, KeyboardInterrupt), e: + raise + except: + # FALLBACK + width = int(os.environ.get('COLUMNS', 80))-1 + # XXX the windows getdimensions may be bogus, let's sanify a bit + width = max(width, 40) # we alaways need 40 chars + return width + +terminal_width = get_terminal_width() + +# XXX unify with _escaped func below +def ansi_print(text, esc, file=None, newline=True, flush=False): + if file is None: + file = sys.stderr + text = text.rstrip() + if esc and not isinstance(esc, tuple): + esc = (esc,) + if esc and sys.platform != "win32" and file.isatty(): + text = (''.join(['\x1b[%sm' % cod for cod in esc]) + + text + + '\x1b[0m') # ANSI color code "reset" + if newline: + text += '\n' + + if esc and sys.platform == "win32" and file.isatty(): + if 1 in esc: + bold = True + esc = tuple([x for x in esc if x != 1]) + else: + bold = False + esctable = {() : FOREGROUND_WHITE, # normal + (31,): FOREGROUND_RED, # red + (32,): FOREGROUND_GREEN, # green + (33,): FOREGROUND_GREEN|FOREGROUND_RED, # yellow + (34,): FOREGROUND_BLUE, # blue + (35,): FOREGROUND_BLUE|FOREGROUND_RED, # purple + (36,): FOREGROUND_BLUE|FOREGROUND_GREEN, # cyan + (37,): FOREGROUND_WHITE, # white + (39,): FOREGROUND_WHITE, # reset + } + attr = esctable.get(esc, FOREGROUND_WHITE) + if bold: + attr |= FOREGROUND_INTENSITY + STD_OUTPUT_HANDLE = -11 + STD_ERROR_HANDLE = -12 + if file is sys.stderr: + handle = GetStdHandle(STD_ERROR_HANDLE) + else: + handle = GetStdHandle(STD_OUTPUT_HANDLE) + SetConsoleTextAttribute(handle, attr) + file.write(text) + SetConsoleTextAttribute(handle, FOREGROUND_WHITE) + else: + file.write(text) + + if flush: + file.flush() + +def should_do_markup(file): + return hasattr(file, 'isatty') and file.isatty() \ + and os.environ.get('TERM') != 'dumb' + +class TerminalWriter(object): + _esctable = dict(black=30, red=31, green=32, yellow=33, + blue=34, purple=35, cyan=36, white=37, + Black=40, Red=41, Green=42, Yellow=43, + Blue=44, Purple=45, Cyan=46, White=47, + bold=1, light=2, blink=5, invert=7) + + def __init__(self, file=None, stringio=False): + if file is None: + if stringio: + self.stringio = file = std.cStringIO.StringIO() + else: + file = std.sys.stdout + elif callable(file): + file = WriteFile(file) + self._file = file + self.fullwidth = get_terminal_width() + self.hasmarkup = should_do_markup(file) + + def _escaped(self, text, esc): + if esc and self.hasmarkup: + text = (''.join(['\x1b[%sm' % cod for cod in esc]) + + text +'\x1b[0m') + return text + + def markup(self, text, **kw): + esc = [] + for name in kw: + if name not in self._esctable: + raise ValueError("unknown markup: %r" %(name,)) + if kw[name]: + esc.append(self._esctable[name]) + return self._escaped(text, tuple(esc)) + + def sep(self, sepchar, title=None, fullwidth=None, **kw): + if fullwidth is None: + fullwidth = self.fullwidth + # the goal is to have the line be as long as possible + # under the condition that len(line) <= fullwidth + if title is not None: + # we want 2 + 2*len(fill) + len(title) <= fullwidth + # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth + # 2*len(sepchar)*N <= fullwidth - len(title) - 2 + # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) + N = (fullwidth - len(title) - 2) // (2*len(sepchar)) + fill = sepchar * N + line = "%s %s %s" % (fill, title, fill) + else: + # we want len(sepchar)*N <= fullwidth + # i.e. N <= fullwidth // len(sepchar) + line = sepchar * (fullwidth // len(sepchar)) + # in some situations there is room for an extra sepchar at the right, + # in particular if we consider that with a sepchar like "_ " the + # trailing space is not important at the end of the line + if len(line) + len(sepchar.rstrip()) <= fullwidth: + line += sepchar.rstrip() + + self.line(line, **kw) + + def write(self, s, **kw): + if s: + s = str(s) + if self.hasmarkup and kw: + s = self.markup(s, **kw) + self._file.write(s) + self._file.flush() + + def line(self, s='', **kw): + self.write(s, **kw) + self.write('\n') + +class Win32ConsoleWriter(object): + + def __init__(self, file=None, stringio=False): + if file is None: + if stringio: + self.stringio = file = std.cStringIO.StringIO() + else: + file = std.sys.stdout + elif callable(file): + file = WriteFile(file) + self._file = file + self.fullwidth = get_terminal_width() + self.hasmarkup = should_do_markup(file) + + def sep(self, sepchar, title=None, fullwidth=None, **kw): + if fullwidth is None: + fullwidth = self.fullwidth + # the goal is to have the line be as long as possible + # under the condition that len(line) <= fullwidth + if title is not None: + # we want 2 + 2*len(fill) + len(title) <= fullwidth + # i.e. 2 + 2*len(sepchar)*N + len(title) <= fullwidth + # 2*len(sepchar)*N <= fullwidth - len(title) - 2 + # N <= (fullwidth - len(title) - 2) // (2*len(sepchar)) + N = (fullwidth - len(title) - 2) // (2*len(sepchar)) + fill = sepchar * N + line = "%s %s %s" % (fill, title, fill) + else: + # we want len(sepchar)*N <= fullwidth + # i.e. N <= fullwidth // len(sepchar) + line = sepchar * (fullwidth // len(sepchar)) + # in some situations there is room for an extra sepchar at the right, + # in particular if we consider that with a sepchar like "_ " the + # trailing space is not important at the end of the line + if len(line) + len(sepchar.rstrip()) <= fullwidth: + line += sepchar.rstrip() + + self.line(line, **kw) + + def write(self, s, **kw): + if s: + s = str(s) + if self.hasmarkup: + handle = GetStdHandle(STD_OUTPUT_HANDLE) + + if self.hasmarkup and kw: + attr = 0 + if kw.pop('bold', False): + attr |= FOREGROUND_INTENSITY + + if kw.pop('red', False): + attr |= FOREGROUND_RED + elif kw.pop('blue', False): + attr |= FOREGROUND_BLUE + elif kw.pop('green', False): + attr |= FOREGROUND_GREEN + else: + attr |= FOREGROUND_WHITE + + SetConsoleTextAttribute(handle, attr) + self._file.write(s) + self._file.flush() + if self.hasmarkup: + SetConsoleTextAttribute(handle, FOREGROUND_WHITE) + + def line(self, s='', **kw): + self.write(s + '\n', **kw) + +if sys.platform == 'win32': + TerminalWriter = Win32ConsoleWriter + +class WriteFile(object): + def __init__(self, writemethod): + self.write = writemethod + def flush(self): + return + +
--- a/orpg/gametree/gametree.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/gametree.py Thu Aug 27 01:04:43 2009 -0500 @@ -30,25 +30,23 @@ from orpg.orpg_wx import * from orpg.orpg_windows import * -from orpg.orpgCore import open_rpg -import orpg.dirpath -from nodehandlers import core -import orpg.gametree.nodehandlers.containers -import orpg.gametree.nodehandlers.forms -import orpg.gametree.nodehandlers.dnd3e -import orpg.gametree.nodehandlers.dnd35 -import orpg.gametree.nodehandlers.chatmacro -import orpg.gametree.nodehandlers.map_miniature_nodehandler -import orpg.gametree.nodehandlers.minilib -import orpg.gametree.nodehandlers.rpg_grid -import orpg.gametree.nodehandlers.d20 -import orpg.gametree.nodehandlers.StarWarsd20 -import orpg.gametree.nodehandlers.voxchat -from gametree_version import GAMETREE_VERSION +from orpg.orpgCore import component +from orpg.dirpath import dir_struct +from nodehandlers import core import string import urllib import time -import os +import os + +from orpg.orpg_xml import xml +from orpg.tools.validate import validate +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging +from orpg.gametree.nodehandlers import containers, forms, dnd3e, dnd35, chatmacro +from orpg.gametree.nodehandlers import map_miniature_nodehandler +from orpg.gametree.nodehandlers import minilib, rpg_grid, d20, StarWarsd20, voxchat + +from gametree_version import GAMETREE_VERSION STD_MENU_DELETE = wx.NewId() STD_MENU_DESIGN = wx.NewId() @@ -78,17 +76,16 @@ TOP_TREE_PROP = wx.NewId() TOP_FEATURES = wx.NewId() -class game_tree(wx.TreeCtrl): +class game_tree(wx.TreeCtrl): + @debugging def __init__(self, parent, id): - wx.TreeCtrl.__init__(self,parent,id, wx.DefaultPosition, wx.DefaultSize,style=wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS) - self.log = open_rpg.get_component('log') - self.log.log("Enter game_tree", ORPG_DEBUG) - self.validate = open_rpg.get_component('validate') - self.xml = open_rpg.get_component('xml') - self.settings = open_rpg.get_component('settings') - self.session = open_rpg.get_component('session') - self.chat = open_rpg.get_component('chat') - self.mainframe = open_rpg.get_component('frame') + wx.TreeCtrl.__init__(self,parent,id, wx.DefaultPosition, + wx.DefaultSize,style=wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS) + #self.xml = component.get('xml') # + self.settings = component.get('settings') + self.session = component.get('session') + self.chat = component.get('chat') + self.mainframe = component.get('frame') self.build_img_list() self.build_std_menu() self.nodehandlers = {} @@ -105,65 +102,58 @@ self.Bind(wx.EVT_KEY_UP, self.on_key_up) self.id = 1 self.dragging = False - self.root_dir = orpg.dirpath.dir_struct["home"] - self.last_save_dir = orpg.dirpath.dir_struct["user"] + self.last_save_dir = dir_struct["user"] #Create tree from default if it does not exist - self.validate.config_file("tree.xml","default_tree.xml") - open_rpg.add_component("tree", self) + validate.config_file("tree.xml","default_tree.xml") + component.add("tree", self) #build tree self.root = self.AddRoot("Game Tree",self.icons['gear']) self.was_labeling = 0 self.rename_flag = 0 self.image_cache = {} - self.log.log("Exit game_tree", ORPG_DEBUG) - + logger.debug("Exit game_tree") + + @debugging def add_nodehandler(self, nodehandler, nodeclass): - self.log.log("Enter game_tree->add_nodehandler(self, nodehandler, nodeclass)", ORPG_DEBUG) - if not self.nodehandlers.has_key(nodehandler): - self.nodehandlers[nodehandler] = nodeclass - else: - self.log.log("Nodehandler for " + nodehandler + " already exists!", ORPG_DEBUG, True) - self.log.log("Exit game_tree->add_nodehandler(self, nodehandler, nodeclass)", ORPG_DEBUG) - + if not self.nodehandlers.has_key(nodehandler): self.nodehandlers[nodehandler] = nodeclass + else: logger.debug("Nodehandler for " + nodehandler + " already exists!") + + @debugging def remove_nodehandler(self, nodehandler): - self.log.log("Enter game_tree->remove_nodehandler(self, nodehandler)", ORPG_DEBUG) if self.nodehandlers.has_key(nodehandler): del self.nodehandlers[nodehandler] - else: - self.log.log("No nodehandler for " + nodehandler + " exists!", ORPG_DEBUG, True) - self.log.log("Exit game_tree->remove_nodehandler(self, nodehandler)", ORPG_DEBUG) - + else: logger.debug("No nodehandler for " + nodehandler + " exists!") + + @debugging def init_nodehandlers(self): - self.log.log("Enter game_tree->init_nodehandlers(self)", ORPG_DEBUG) - self.add_nodehandler('group_handler', orpg.gametree.nodehandlers.containers.group_handler) - self.add_nodehandler('tabber_handler', orpg.gametree.nodehandlers.containers.tabber_handler) - self.add_nodehandler('splitter_handler', orpg.gametree.nodehandlers.containers.splitter_handler) - self.add_nodehandler('form_handler', orpg.gametree.nodehandlers.forms.form_handler) - self.add_nodehandler('textctrl_handler', orpg.gametree.nodehandlers.forms.textctrl_handler) - self.add_nodehandler('listbox_handler', orpg.gametree.nodehandlers.forms.listbox_handler) - self.add_nodehandler('link_handler', orpg.gametree.nodehandlers.forms.link_handler) - self.add_nodehandler('webimg_handler', orpg.gametree.nodehandlers.forms.webimg_handler) - self.add_nodehandler('dnd3echar_handler', orpg.gametree.nodehandlers.dnd3e.dnd3echar_handler) - self.add_nodehandler('dnd35char_handler', orpg.gametree.nodehandlers.dnd35.dnd35char_handler) - self.add_nodehandler('macro_handler', orpg.gametree.nodehandlers.chatmacro.macro_handler) - self.add_nodehandler('map_miniature_handler', orpg.gametree.nodehandlers.map_miniature_nodehandler.map_miniature_handler) - self.add_nodehandler('minilib_handler', orpg.gametree.nodehandlers.minilib.minilib_handler) - self.add_nodehandler('mini_handler', orpg.gametree.nodehandlers.minilib.mini_handler) - self.add_nodehandler('rpg_grid_handler', orpg.gametree.nodehandlers.rpg_grid.rpg_grid_handler) - self.add_nodehandler('d20char_handler', orpg.gametree.nodehandlers.d20.d20char_handler) - self.add_nodehandler('SWd20char_handler', orpg.gametree.nodehandlers.StarWarsd20.SWd20char_handler) - self.add_nodehandler('voxchat_handler', orpg.gametree.nodehandlers.voxchat.voxchat_handler) + self.add_nodehandler('group_handler', containers.group_handler) + self.add_nodehandler('tabber_handler', containers.tabber_handler) + self.add_nodehandler('splitter_handler', containers.splitter_handler) + self.add_nodehandler('form_handler', forms.form_handler) + self.add_nodehandler('textctrl_handler', forms.textctrl_handler) + self.add_nodehandler('listbox_handler', forms.listbox_handler) + self.add_nodehandler('link_handler', forms.link_handler) + self.add_nodehandler('webimg_handler', forms.webimg_handler) + self.add_nodehandler('dnd3echar_handler', dnd3e.dnd3echar_handler) + self.add_nodehandler('dnd35char_handler', dnd35.dnd35char_handler) + self.add_nodehandler('macro_handler', chatmacro.macro_handler) + self.add_nodehandler('map_miniature_handler', map_miniature_nodehandler.map_miniature_handler) + self.add_nodehandler('minilib_handler', minilib.minilib_handler) + self.add_nodehandler('mini_handler', minilib.mini_handler) + self.add_nodehandler('rpg_grid_handler', rpg_grid.rpg_grid_handler) + self.add_nodehandler('d20char_handler', d20.d20char_handler) + self.add_nodehandler('SWd20char_handler', StarWarsd20.SWd20char_handler) + self.add_nodehandler('voxchat_handler', voxchat.voxchat_handler) self.add_nodehandler('file_loader', core.file_loader) self.add_nodehandler('node_loader', core.node_loader) self.add_nodehandler('url_loader', core.url_loader) self.add_nodehandler('min_map', core.min_map) - self.log.log("Exit game_tree->init_nodehandlers(self)", ORPG_DEBUG) # event = wxKeyEvent - # set to be called by wxWindows by EVT_CHAR macro in __init__ + # set to be called by wxWindows by EVT_CHAR macro in __init__ + @debugging def on_key_up(self, evt): - self.log.log("Enter game_tree->on_key_up(self, evt)", ORPG_DEBUG) key_code = evt.GetKeyCode() if self.dragging and (key_code == wx.WXK_SHIFT): curSelection = self.GetSelection() @@ -176,10 +166,9 @@ obj.on_drop(evt) self.drag_obj = None evt.Skip() - self.log.log("Exit game_tree->on_key_up(self, evt)", ORPG_DEBUG) - + + @debugging def on_char(self, evt): - self.log.log("Enter game_tree->on_char(self, evt)", ORPG_DEBUG) key_code = evt.GetKeyCode() curSelection = self.GetSelection() # Get the current selection if evt.ShiftDown() and ((key_code == wx.WXK_UP) or (key_code == wx.WXK_DOWN)) and not self.dragging: @@ -191,29 +180,22 @@ cur = wx.StockCursor(wx.CURSOR_HAND) self.SetCursor(cur) self.drag_obj = obj - elif key_code == wx.WXK_LEFT: - self.Collapse(curSelection) - + elif key_code == wx.WXK_LEFT: self.Collapse(curSelection) elif key_code == wx.WXK_DELETE: # Handle the delete key if curSelection: nextSelect = self.GetItemParent(curSelection) self.on_del(evt) try: - if self.GetItemText(nextSelect) != "": - self.SelectItem(nextSelect) - except: - pass + if self.GetItemText(nextSelect) != "": self.SelectItem(nextSelect) + except: pass elif key_code == wx.WXK_F2: self.rename_flag = 1 self.EditLabel(curSelection) evt.Skip() - self.log.log("Exit game_tree->on_char(self, evt)", ORPG_DEBUG) - - ## locate_valid_tree - ## GUI based dialogs to locate/fix missing treefile issues --Snowdog 3/05 - def locate_valid_tree(self, error, msg, dir, filename): + + @debugging + def locate_valid_tree(self, error, msg, dir, filename): ## --Snowdog 3/05 """prompts the user to locate a new tree file or create a new one""" - self.log.log("Enter game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) response = wx.MessageDialog(self, msg, error, wx.YES|wx.NO|wx.ICON_ERROR) if response == wx.YES: file = None @@ -223,39 +205,34 @@ dlg.Destroy() if not file: self.load_tree(error=1) else: self.load_tree(file) - self.log.log("Exit game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) return else: - self.validate.config_file("tree.xml","default_tree.xml") + validate.config_file("tree.xml","default_tree.xml") self.load_tree(error=1) - self.log.log("Exit game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) return - - def load_tree(self, filename=orpg.dirpath.dir_struct["user"]+'tree.xml', error=0): - self.log.log("Enter game_tree->load_tree(self, filename, error)", ORPG_DEBUG) + + @debugging + def load_tree(self, filename=dir_struct["user"]+'tree.xml', error=0): self.settings.set_setting("gametree", filename) tmp = None xml_dom = None xml_doc = None try: - self.log.log("Reading Gametree file: " + filename + "...", ORPG_INFO, True) + logger.info("Reading Gametree file: " + filename + "...", True) tmp = open(filename,"r") - xml_doc = self.xml.parseXml(tmp.read()) + xml_doc = xml.parseXml(tmp.read()) tmp.close() - if xml_doc == None: - pass - else: - xml_dom = xml_doc._get_documentElement() - self.log.log("done.", ORPG_INFO, True) + if xml_doc == None: pass + else: xml_dom = xml_doc._get_documentElement() + logger.info("done.", True) except IOError: emsg = "Gametree Missing!\n"+filename+" cannot be found.\n\n"\ "Would you like to locate it?\n"\ "(Selecting 'No' will cause a new default gametree to be generated)" fn = filename[ ((filename.rfind(os.sep))+len(os.sep)):] - self.locate_valid_tree("Gametree Error", emsg, orpg.dirpath.dir_struct["user"], fn) - self.log.log(emsg, ORPG_GENERAL) - self.log.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) + self.locate_valid_tree("Gametree Error", emsg, dir_struct["user"], fn) + logger.general(emsg) return if not xml_dom: @@ -269,9 +246,8 @@ "lastgood.xml WILL BE OVERWRITTEN NEXT TIME YOU RUN OPENRPG.\n\n"\ "Would you like to select a different gametree file to use?\n"\ "(Selecting 'No' will cause a new default gametree to be generated)" - self.locate_valid_tree("Corrupt Gametree!", emsg, orpg.dirpath.dir_struct["user"], fn) - self.log.log(emsg, ORPG_GENERAL) - self.log.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) + self.locate_valid_tree("Corrupt Gametree!", emsg, dir_struct["user"], fn) + logger.general(emsg) return if xml_dom._get_tagName() != "gametree": @@ -279,59 +255,56 @@ emsg = fn+" does not appear to be a valid gametree file.\n\n"\ "Would you like to select a different gametree file to use?\n"\ "(Selecting 'No' will cause a new default gametree to be generated)" - self.locate_valid_tree("Invalid Gametree!", emsg, orpg.dirpath.dir_struct["user"], fn) - self.log.log(emsg, ORPG_DEBUG) - self.log.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) + self.locate_valid_tree("Invalid Gametree!", emsg, dir_struct["user"], fn) + logger.debug(emsg) return # get gametree version - we could write conversion code here! self.master_dom = xml_dom - self.log.log("Master Dom Set", ORPG_DEBUG) + logger.debug("Master Dom Set") try: version = self.master_dom.getAttribute("version") # see if we should load the gametree loadfeatures = int(self.settings.get_setting("LoadGameTreeFeatures")) if loadfeatures: - xml_dom = self.xml.parseXml(open(orpg.dirpath.dir_struct["template"]+"feature.xml","r").read()) + xml_dom = xml.parseXml(open(dir_struct["template"]+"feature.xml","r").read()) xml_dom = xml_dom._get_documentElement() xml_dom = self.master_dom.appendChild(xml_dom) self.settings.set_setting("LoadGameTreeFeatures","0") ## load tree - self.log.log("Features loaded (if required)", ORPG_DEBUG) + logger.debug("Features loaded (if required)") self.CollapseAndReset(self.root) children = self.master_dom._get_childNodes() - self.log.log("Parsing Gametree Nodes ", ORPG_INFO, True) + logger.info("Parsing Gametree Nodes ", True) for c in children: print '.', self.load_xml(c,self.root) - self.log.log("done", ORPG_INFO, True) + logger.info("done", True) self.Expand(self.root) self.SetPyData(self.root,self.master_dom) if error != 1: infile = open(filename, "rb") - outfile = open(orpg.dirpath.dir_struct["user"]+"lastgood.xml", "wb") + outfile = open(dir_struct["user"]+"lastgood.xml", "wb") outfile.write(infile.read()) - else: - self.log.log("Not overwriting lastgood.xml file.", ORPG_INFO, True) + else: logger.info("Not overwriting lastgood.xml file.", True) except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) + logger.general(traceback.format_exc()) 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.") os.rename(filename,filename+".corrupt") - self.validate.config_file("tree.xml","default_tree.xml") + validate.config_file("tree.xml","default_tree.xml") self.load_tree(error=1) - self.log.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) - + + @debugging def build_std_menu(self, obj=None): - self.log.log("Enter game_tree->build_std_menu(self, obj)", ORPG_DEBUG) - # build useful menu useful_menu = wx.Menu() useful_menu.Append(STD_MENU_NODE_USEFUL,"Use&ful") useful_menu.Append(STD_MENU_NODE_USELESS,"Use&less") - useful_menu.Append(STD_MENU_NODE_INDIFFERENT,"&Indifferent") + useful_menu.Append(STD_MENU_NODE_INDIFFERENT,"&Indifferent") + # build standard menu self.std_menu = wx.Menu() self.std_menu.SetTitle("game tree") @@ -385,82 +358,66 @@ self.Bind(wx.EVT_MENU, self.on_load_new_tree, id=TOP_NEW_TREE) self.Bind(wx.EVT_MENU, self.on_tree_prop, id=TOP_TREE_PROP) self.Bind(wx.EVT_MENU, self.on_insert_features, id=TOP_FEATURES) - self.log.log("Exit game_tree->build_std_menu(self, obj)", ORPG_DEBUG) - + + @debugging def do_std_menu(self, evt, obj): - self.log.log("Enter game_tree->do_std_menu(self, evt, obj)", ORPG_DEBUG) - try: - self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu()) - except: - self.std_menu.Enable(STD_MENU_MAP, obj.map_aware()) + try: self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu()) + except: self.std_menu.Enable(STD_MENU_MAP, obj.map_aware()) self.std_menu.Enable(STD_MENU_CLONE, obj.can_clone()) self.PopupMenu(self.std_menu) - self.log.log("Exit game_tree->do_std_menu(self, evt, obj)", ORPG_DEBUG) - + + @debugging def strip_html(self, player): - self.log.log("Enter game_tree->strip_html(self, player)", ORPG_DEBUG) ret_string = "" x = 0 in_tag = 0 for x in xrange(len(player[0])) : if player[0][x] == "<" or player[0][x] == ">" or in_tag == 1 : - if player[0][x] == "<" : - in_tag = 1 - elif player[0][x] == ">" : - in_tag = 0 - else : - pass - else : - ret_string = ret_string + player[0][x] - self.log.log(ret_string, ORPG_DEBUG) - self.log.log("Exit game_tree->strip_html(self, player)", ORPG_DEBUG) + if player[0][x] == "<" : in_tag = 1 + elif player[0][x] == ">" : in_tag = 0 + else: pass + else: ret_string = ret_string + player[0][x] + logger.debug(ret_string) return ret_string - + + @debugging def on_receive_data(self, data, player): - self.log.log("Enter game_tree->on_receive_data(self, data, player)", ORPG_DEBUG) beg = string.find(data,"<tree>") end = string.rfind(data,"</tree>") data = data[6:end] self.insert_xml(data) - self.log.log("Exit game_tree->on_receive_data(self, data, player)", ORPG_DEBUG) - + + @debugging def on_send_to_chat(self, evt): - self.log.log("Enter game_tree->on_send_to_chat(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.on_send_to_chat(evt) - self.log.log("Exit game_tree->on_send_to_chat(self, evt)", ORPG_DEBUG) - + + @debugging def on_whisper_to(self, evt): - self.log.log("Enter game_tree->on_whisper_to(self, evt)", ORPG_DEBUG) players = self.session.get_players() opts = [] myid = self.session.get_id() me = None for p in players: - if p[2] != myid: - opts.append("("+p[2]+") " + self.strip_html(p)) - else: - me = p - if len(opts): - players.remove(me) + if p[2] != myid: opts.append("("+p[2]+") " + self.strip_html(p)) + else: me = p + if len(opts): players.remove(me) if len(opts): dlg = orpgMultiCheckBoxDlg( self.GetParent(),opts,"Select Players:","Whisper To",[] ) if dlg.ShowModal() == wx.ID_OK: item = self.GetSelection() obj = self.GetPyData(item) selections = dlg.get_selections() - if len(selections) == len(opts): - self.chat.ParsePost(obj.tohtml(),True,True) + if len(selections) == len(opts): self.chat.ParsePost(obj.tohtml(),True,True) else: player_ids = [] for s in selections: player_ids.append(players[s][2]) self.chat.whisper_to_players(obj.tohtml(),player_ids) - self.log.log("Exit game_tree->on_whisper_to(self, evt)", ORPG_DEBUG) - + + @debugging def on_export_html(self, evt): - self.log.log("Enter game_tree->on_export_html(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","HTML (*.html)|*.html",wx.SAVE) if f.ShowModal() == wx.ID_OK: item = self.GetSelection() @@ -475,62 +432,54 @@ file.close() self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.log.log("Exit game_tree->on_export_html(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def indifferent(self, evt): - self.log.log("Enter game_tree->indifferent(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("indifferent") - self.log.log("Exit game_tree->indifferent(self, evt)", ORPG_DEBUG) - + + @debugging def useful(self, evt): - self.log.log("Enter game_tree->useful(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("useful") - self.log.log("Exit game_tree->useful(self, evt)", ORPG_DEBUG) - + + @debugging def useless(self, evt): - self.log.log("Enter game_tree->useless(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("useless") - self.log.log("Exit game_tree->useless(self, evt)", ORPG_DEBUG) - + + @debugging def on_email(self,evt): pass - + + @debugging def on_send_to(self, evt): - self.log.log("Enter game_tree->on_send_to(self, evt)", ORPG_DEBUG) players = self.session.get_players() opts = [] myid = self.session.get_id() me = None for p in players: - if p[2] != myid: - opts.append("("+p[2]+") " + self.strip_html(p)) - else: - me = p + if p[2] != myid: opts.append("("+p[2]+") " + self.strip_html(p)) + else: me = p if len(opts): players.remove(me) dlg = orpgMultiCheckBoxDlg( None, opts, "Select Players:", "Send To", [] ) if dlg.ShowModal() == wx.ID_OK: item = self.GetSelection() obj = self.GetPyData(item) - xmldata = "<tree>" + self.xml.toxml(obj) + "</tree>" + xmldata = "<tree>" + xml.toxml(obj) + "</tree>" selections = dlg.get_selections() - if len(selections) == len(opts): - self.session.send(xmldata) + if len(selections) == len(opts): self.session.send(xmldata) else: - for s in selections: - self.session.send(xmldata,players[s][2]) + for s in selections: self.session.send(xmldata,players[s][2]) dlg.Destroy() - self.log.log("Exit game_tree->on_send_to(self, evt)", ORPG_DEBUG) - + + @debugging def on_icon(self, evt): - self.log.log("Enter game_tree->on_icon(self, evt)", ORPG_DEBUG) icons = self.icons.keys() icons.sort() dlg = wx.SingleChoiceDialog(self,"Choose Icon?","Change Icon",icons) @@ -540,147 +489,124 @@ obj = self.GetPyData(item) obj.change_icon(key) dlg.Destroy() - self.log.log("Exit game_tree->on_icon(self, evt)", ORPG_DEBUG) - + + @debugging def on_wizard(self, evt): - self.log.log("Enter game_tree->on_wizard(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) name = "New " + obj.master_dom.getAttribute("name") icon = obj.master_dom.getAttribute("icon") xml_data = "<nodehandler name=\""+name+"\" icon=\"" + icon + "\" module=\"core\" class=\"node_loader\" >" - xml_data += self.xml.toxml(obj) + xml_data += xml.toxml(obj) xml_data += "</nodehandler>" self.insert_xml(xml_data) - self.log.log(xml_data, ORPG_DEBUG) - self.log.log("Exit game_tree->on_wizard(self, evt)", ORPG_DEBUG) - + logger.debug(xml_data) + + @debugging def on_clone(self, evt): - self.log.log("Enter game_tree->on_clone(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) if obj.can_clone(): parent_node = self.GetItemParent(item) prev_sib = self.GetPrevSibling(item) - if not prev_sib.IsOk(): - prev_sib = parent_node - xml_dom = self.xml.parseXml(self.xml.toxml(obj)) + if not prev_sib.IsOk(): prev_sib = parent_node + xml_dom = xml.parseXml(xml.toxml(obj)) xml_dom = xml_dom._get_firstChild() parent = obj.master_dom._get_parentNode() xml_dom = parent.insertBefore(xml_dom, obj.master_dom) self.load_xml(xml_dom, parent_node, prev_sib) - self.log.log("Exit game_tree->on_clone(self, evt)", ORPG_DEBUG) - + + @debugging def on_save(self, evt): """save node to a xml file""" - self.log.log("Enter game_tree->on_save(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.on_save(evt) - os.chdir(self.root_dir) - self.log.log("Exit game_tree->on_save(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_save_tree_as(self, evt): - self.log.log("Enter game_tree->on_save_tree_as(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.SAVE) if f.ShowModal() == wx.ID_OK: self.save_tree(f.GetPath()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.log.log("Exit game_tree->on_save_tree_as(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_save_tree(self, evt=None): - self.log.log("Enter game_tree->on_save_tree(self, evt)", ORPG_DEBUG) filename = self.settings.get_setting("gametree") self.save_tree(filename) - self.log.log("Exit game_tree->on_save_tree(self, evt)", ORPG_DEBUG) - - def save_tree(self, filename=orpg.dirpath.dir_struct["user"]+'tree.xml'): - self.log.log("Enter game_tree->save_tree(self, filename)", ORPG_DEBUG) + + @debugging + def save_tree(self, filename=dir_struct["user"]+'tree.xml'): self.master_dom.setAttribute("version",GAMETREE_VERSION) self.settings.set_setting("gametree",filename) file = open(filename,"w") - file.write(self.xml.toxml(self.master_dom,1)) + file.write(xml.toxml(self.master_dom,1)) file.close() - self.log.log("Exit game_tree->save_tree(self, filename)", ORPG_DEBUG) - + + @debugging def on_load_new_tree(self, evt): - self.log.log("Enter game_tree->on_load_new_tree(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) if f.ShowModal() == wx.ID_OK: self.load_tree(f.GetPath()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.log.log("Exit game_tree->on_load_new_tree(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_insert_file(self, evt): """loads xml file into the tree""" - self.log.log("Enter game_tree->on_insert_file(self, evt)", ORPG_DEBUG) if self.last_save_dir == ".": - self.last_save_dir = orpg.dirpath.dir_struct["user"] + self.last_save_dir = dir_struct["user"] f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) if f.ShowModal() == wx.ID_OK: self.insert_xml(open(f.GetPath(),"r").read()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.log.log("Exit game_tree->on_insert_file(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_insert_url(self, evt): """loads xml url into the tree""" - self.log.log("Enter game_tree->on_insert_url(self, evt)", ORPG_DEBUG) dlg = wx.TextEntryDialog(self,"URL?","Insert URL", "http://") if dlg.ShowModal() == wx.ID_OK: path = dlg.GetValue() file = urllib.urlopen(path) self.insert_xml(file.read()) dlg.Destroy() - self.log.log("Exit game_tree->on_insert_url(self, evt)", ORPG_DEBUG) - + + @debugging def on_insert_features(self, evt): - self.log.log("Enter game_tree->on_insert_features(self, evt)", ORPG_DEBUG) - self.insert_xml(open(orpg.dirpath.dir_struct["template"]+"feature.xml","r").read()) - self.log.log("Exit game_tree->on_insert_features(self, evt)", ORPG_DEBUG) - + self.insert_xml(open(dir_struct["template"]+"feature.xml","r").read()) + + @debugging def on_tree_prop(self, evt): - self.log.log("Enter game_tree->on_tree_prop(self, evt)", ORPG_DEBUG) dlg = gametree_prop_dlg(self, self.settings) - if dlg.ShowModal() == wx.ID_OK: - pass + if dlg.ShowModal() == wx.ID_OK: pass dlg.Destroy() - self.log.log("Exit game_tree->on_tree_prop(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_design(self, evt): - self.log.log("Enter game_tree->on_node_design(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_design(evt) - - self.log.log("Exit game_tree->on_node_design(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_use(self, evt): - self.log.log("Enter game_tree->on_node_use(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_use(evt) - - self.log.log("Exit game_tree->on_node_use(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_pp(self, evt): - self.log.log("Enter game_tree->on_node_pp(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_html_view(evt) - - self.log.log("Exit game_tree->on_node_pp(self, evt)", ORPG_DEBUG) - + + @debugging def on_del(self, evt): - self.log.log("Enter game_tree->on_del(self, evt)", ORPG_DEBUG) status_value = "none" try: item = self.GetSelection() @@ -690,166 +616,137 @@ try: status_value = parent_obj.master_dom.getAttribute('status') name = parent_obj.master_dom.getAttribute('name') - except: - status_value = "none" + except: status_value = "none" parent_obj = parent_obj.master_dom._get_parentNode() while status_value!="useful" and status_value!="useless": try: status_value = parent_obj.getAttribute('status') name = parent_obj.getAttribute('name') - if status_value == "useless": - break - elif status_value == "useful": - break - except: - status_value = "none" - try: - parent_obj = parent_obj._get_parentNode() - except: - break + if status_value == "useless": break + elif status_value == "useful": break + except: status_value = "none" + try: parent_obj = parent_obj._get_parentNode() + except: break if status_value == "useful": 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) - if dlg.ShowModal() == wx.ID_YES: - obj.delete() - else: - obj.delete() + if dlg.ShowModal() == wx.ID_YES: obj.delete() + else: obj.delete() except: if self.GetSelection() == self.GetRootItem(): msg = wx.MessageDialog(None,"You can't delete the root item.","Delete Error",wx.OK) - else: - msg = wx.MessageDialog(None,"Unknown error deleting node.","Delete Error",wx.OK) + else: msg = wx.MessageDialog(None,"Unknown error deleting node.","Delete Error",wx.OK) msg.ShowModal() msg.Destroy() - - self.log.log("Exit game_tree->on_del(self, evt)", ORPG_DEBUG) - + + @debugging def on_about(self, evt): - self.log.log("Enter game_tree->on_about(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) about = MyAboutBox(self,obj.about()) about.ShowModal() about.Destroy() - - self.log.log("Exit game_tree->on_about(self, evt)", ORPG_DEBUG) - + + @debugging def on_send_to_map(self, evt): - self.log.log("Enter game_tree->on_send_to_map(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) - if hasattr(obj,"on_send_to_map"): - obj.on_send_to_map(evt) - - self.log.log("Exit game_tree->on_send_to_map(self, evt)", ORPG_DEBUG) - + if hasattr(obj,"on_send_to_map"): obj.on_send_to_map(evt) + + @debugging def insert_xml(self, txt): - self.log.log("Enter game_tree->insert_xml(self, txt)", ORPG_DEBUG) #Updated to allow safe merging of gametree files #without leaving an unusable and undeletable node. # -- Snowdog 8/03 - xml_dom = self.xml.parseXml(txt) + xml_dom = xml.parseXml(txt) if xml_dom == None: wx.MessageBox("Import Failed: Invalid or missing node data") - self.log.log("Import Failed: Invalid or missing node data", ORPG_DEBUG) - self.log.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) + logger.debug("Import Failed: Invalid or missing node data") + logger.debug("Exit game_tree->insert_xml(self, txt)") return xml_temp = xml_dom._get_documentElement() if not xml_temp: wx.MessageBox("Error Importing Node or Tree") - self.log.log("Error Importing Node or Tree", ORPG_DEBUG) - self.log.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) + logger.debug("Error Importing Node or Tree") + logger.debug("Exit game_tree->insert_xml(self, txt)") return if xml_temp._get_tagName() == "gametree": children = xml_temp._get_childNodes() - for c in children: - self.load_xml(c, self.root) - self.log.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) + for c in children: self.load_xml(c, self.root) + logger.debug("Exit game_tree->insert_xml(self, txt)") return if not xml_dom: wx.MessageBox("XML Error") - self.log.log("XML Error", ORPG_DEBUG) - self.log.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) + logger.debug("XML Error") + logger.debug("Exit game_tree->insert_xml(self, txt)") return xml_dom = xml_dom._get_firstChild() child = self.master_dom._get_firstChild() xml_dom = self.master_dom.insertBefore(xml_dom,child) self.load_xml(xml_dom,self.root,self.root) - self.log.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) - + + @debugging def build_img_list(self): """make image list""" - self.log.log("Enter game_tree->build_img_list(self)", ORPG_DEBUG) helper = img_helper() self.icons = { } self._imageList= wx.ImageList(16,16,False) - man = open(orpg.dirpath.dir_struct["icon"]+"icons.xml","r") - xml_dom = self.xml.parseXml(man.read()) + man = open(dir_struct["icon"]+"icons.xml","r") + xml_dom = xml.parseXml(man.read()) man.close() xml_dom = xml_dom._get_documentElement() node_list = xml_dom._get_childNodes() for n in node_list: key = n.getAttribute("name") - path = orpg.dirpath.dir_struct["icon"] + n.getAttribute("file") + path = dir_struct["icon"] + n.getAttribute("file") img = helper.load_file(path) self.icons[key] = self._imageList.Add(img) self.SetImageList(self._imageList) - self.log.log("Exit game_tree->build_img_list(self)", ORPG_DEBUG) - + + @debugging def load_xml(self, xml_dom, parent_node, prev_node=None): - self.log.log("Enter game_tree->load_xml(self, xml_dom, parent_node, prev_node)", ORPG_DEBUG) #add the first tree node i = 0 text = xml_dom.getAttribute("name") icon = xml_dom.getAttribute("icon") - if self.icons.has_key(icon): - i = self.icons[icon] + if self.icons.has_key(icon): i = self.icons[icon] name = xml_dom._get_nodeName() - self.log.log("Text, icon and name set\n" + text + "\n" + icon + "\n" + name, ORPG_DEBUG) + logger.debug("Text, icon and name set\n" + text + "\n" + icon + "\n" + name) if prev_node: - if prev_node == parent_node: - new_tree_node = self.PrependItem(parent_node, text, i, i) - else: - new_tree_node = self.InsertItem(parent_node,prev_node, text, i, i) - else: - new_tree_node = self.AppendItem(parent_node, text, i, i) + if prev_node == parent_node: new_tree_node = self.PrependItem(parent_node, text, i, i) + else: new_tree_node = self.InsertItem(parent_node,prev_node, text, i, i) + else: new_tree_node = self.AppendItem(parent_node, text, i, i) - self.log.log("Node Added to tree", ORPG_DEBUG) + logger.debug("Node Added to tree") #create a nodehandler or continue loading xml into tree if name == "nodehandler": #wx.BeginBusyCursor() - self.log.log("We have a Nodehandler", ORPG_DEBUG) + logger.debug("We have a Nodehandler") try: py_class = xml_dom.getAttribute("class") - self.log.log("nodehandler class: " + py_class, ORPG_DEBUG) + logger.debug("nodehandler class: " + py_class) if not self.nodehandlers.has_key(py_class): raise Exception, "Unknown Nodehandler for " + py_class self.nodes[self.id] = self.nodehandlers[py_class](xml_dom, new_tree_node) self.SetPyData(new_tree_node, self.nodes[self.id]) - self.log.log("Node Data set", ORPG_DEBUG) + logger.debug("Node Data set") bmp = self.nodes[self.id].get_scaled_bitmap(16,16) - if bmp: - self.cached_load_of_image(bmp,new_tree_node,) - self.log.log("Node Icon loaded", ORPG_DEBUG) + if bmp: self.cached_load_of_image(bmp,new_tree_node,) + logger.debug("Node Icon loaded") self.id = self.id + 1 except Exception, er: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - #self.log.log("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), "Tree Node Load Error", ORPG_GENERAL, True) # Arbitrary fix! TaS. (gametree should thread in the future.) - self.log.log("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), ORPG_GENERAL, True) + logger.general(traceback.format_exc()) + #logger.debug("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), True)?indent? self.Delete(new_tree_node) parent = xml_dom._get_parentNode() parent.removeChild(xml_dom) - #wx.EndBusyCursor() - self.log.log("Exit game_tree->load_xml(self, xml_dom, parent_node, prev_node)", ORPG_DEBUG) return new_tree_node - + + @debugging def cached_load_of_image(self, bmp_in, new_tree_node): - self.log.log("Enter game_tree->cached_load_of_image(self, bmp_in, new_tree_node)", ORPG_DEBUG) image_list = self.GetImageList() img = wx.ImageFromBitmap(bmp_in) img_data = img.GetData() @@ -864,27 +761,21 @@ self.image_cache[image_index] = img_data self.SetItemImage(new_tree_node,image_index) self.SetItemImage(new_tree_node,image_index, wx.TreeItemIcon_Selected) - self.log.log("Exit game_tree->cached_load_of_image(self, bmp_in, new_tree_node)", ORPG_DEBUG) return image_index - - + + @debugging def on_rclick(self, evt): - self.log.log("Enter game_tree->on_rclick(self, evt)", ORPG_DEBUG) pt = evt.GetPosition() (item, flag) = self.HitTest(pt) if item.IsOk(): obj = self.GetPyData(item) self.SelectItem(item) - if(isinstance(obj,core.node_handler)): - obj.on_rclick(evt) - else: - self.PopupMenu(self.top_menu) - else: - self.PopupMenu(self.top_menu,pt) - self.log.log("Exit game_tree->on_rclick(self, evt)", ORPG_DEBUG) - + if(isinstance(obj,core.node_handler)): obj.on_rclick(evt) + else: self.PopupMenu(self.top_menu) + else: self.PopupMenu(self.top_menu,pt) + + @debugging def on_ldclick(self, evt): - self.log.log("Enter game_tree->on_ldclick(self, evt)", ORPG_DEBUG) self.rename_flag = 0 pt = evt.GetPosition() (item, flag) = self.HitTest(pt) @@ -894,18 +785,13 @@ if(isinstance(obj,core.node_handler)): if not obj.on_ldclick(evt): action = self.settings.get_setting("treedclick") - if action == "use": - obj.on_use(evt) - elif action == "design": - obj.on_design(evt) - elif action == "print": - obj.on_html_view(evt) - elif action == "chat": - self.on_send_to_chat(evt) - self.log.log("Exit game_tree->on_ldclick(self, evt)", ORPG_DEBUG) - + if action == "use": obj.on_use(evt) + elif action == "design": obj.on_design(evt) + elif action == "print": obj.on_html_view(evt) + elif action == "chat": self.on_send_to_chat(evt) + + @debugging def on_left_down(self, evt): - self.log.log("Enter game_tree->on_left_down(self, evt)", ORPG_DEBUG) pt = evt.GetPosition() (item, flag) = self.HitTest(pt) if item.IsOk() and self.was_labeling: @@ -915,13 +801,11 @@ elif (flag & wx.TREE_HITTEST_ONITEMLABEL) == wx.TREE_HITTEST_ONITEMLABEL and self.IsSelected(item): # this next if tests to ensure that the mouse up occurred over a label, and not the icon self.rename_flag = 1 - else: - self.SelectItem(item) + else: self.SelectItem(item) evt.Skip() - self.log.log("Exit game_tree->on_left_down(self, evt)", ORPG_DEBUG) - + + @debugging def on_left_up(self, evt): - self.log.log("Enter game_tree->on_left_up(self, evt)", ORPG_DEBUG) if self.dragging: cur = wx.StockCursor(wx.CURSOR_ARROW) self.SetCursor(cur) @@ -934,10 +818,9 @@ if(isinstance(obj,core.node_handler)): obj.on_drop(evt) self.drag_obj = None - self.log.log("Exit game_tree->on_left_up(self, evt)", ORPG_DEBUG) - + + @debugging def on_label_change(self, evt): - self.log.log("Enter game_tree->on_label_change(self, evt)", ORPG_DEBUG) item = evt.GetItem() txt = evt.GetLabel() self.was_labeling = 0 @@ -945,23 +828,19 @@ if txt != "": obj = self.GetPyData(item) obj.master_dom.setAttribute('name',txt) - else: - evt.Veto() - self.log.log("Exit game_tree->on_label_change(self, evt)", ORPG_DEBUG) - + else: evt.Veto() + + @debugging def on_label_begin(self, evt): - self.log.log("Enter game_tree->on_label_begin(self, evt)", ORPG_DEBUG) - if not self.rename_flag: - evt.Veto() + if not self.rename_flag: evt.Veto() else: self.was_labeling = 1 item = evt.GetItem() if item == self.GetRootItem(): evt.Veto() - self.log.log("Exit game_tree->on_label_begin(self, evt)", ORPG_DEBUG) - + + @debugging def on_drag(self, evt): - self.log.log("Enter game_tree->on_drag(self, evt)", ORPG_DEBUG) self.rename_flag = 0 item = self.GetSelection() obj = self.GetPyData(item) @@ -971,26 +850,17 @@ cur = wx.StockCursor(wx.CURSOR_HAND) self.SetCursor(cur) self.drag_obj = obj - self.log.log("Exit game_tree->on_drag(self, evt)", ORPG_DEBUG) - + + @debugging def is_parent_node(self, node, compare_node): - self.log.log("Enter game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) - parent_node = self.GetItemParent(node) if compare_node == parent_node: - - self.log.log("parent node", ORPG_DEBUG) - self.log.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) + logger.debug("parent node") return 1 elif parent_node == self.root: - - self.log.log("not parent", ORPG_DEBUG) - self.log.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) + logger.debug("not parent") return 0 - else: - - self.log.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) - return self.is_parent_node(parent_node, compare_node) + else: return self.is_parent_node(parent_node, compare_node) CTRL_TREE_FILE = wx.NewId() CTRL_YES = wx.NewId() @@ -1000,7 +870,8 @@ CTRL_CHAT = wx.NewId() CTRL_PRINT = wx.NewId() -class gametree_prop_dlg(wx.Dialog): +class gametree_prop_dlg(wx.Dialog): + @debugging def __init__(self, parent, settings): wx.Dialog.__init__(self, parent, wx.ID_ANY, "Game Tree Properties") self.settings = settings @@ -1058,16 +929,13 @@ self.SetAutoLayout(True) self.Fit() self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK) - + + @debugging def on_ok(self,evt): self.settings.set_setting("gametree",self.ctrls[CTRL_TREE_FILE].GetValue()) self.settings.set_setting("SaveGameTreeOnExit",str(self.ctrls[CTRL_YES].GetValue())) - if self.ctrls[CTRL_USE].GetValue(): - self.settings.set_setting("treedclick","use") - elif self.ctrls[CTRL_DESIGN].GetValue(): - self.settings.set_setting("treedclick","design") - elif self.ctrls[CTRL_PRINT].GetValue(): - self.settings.set_setting("treedclick","print") - elif self.ctrls[CTRL_CHAT].GetValue(): - self.settings.set_setting("treedclick","chat") + if self.ctrls[CTRL_USE].GetValue(): self.settings.set_setting("treedclick","use") + elif self.ctrls[CTRL_DESIGN].GetValue(): self.settings.set_setting("treedclick","design") + elif self.ctrls[CTRL_PRINT].GetValue(): self.settings.set_setting("treedclick","print") + elif self.ctrls[CTRL_CHAT].GetValue(): self.settings.set_setting("treedclick","chat") self.EndModal(wx.ID_OK)
--- a/orpg/gametree/nodehandlers/StarWarsd20.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/StarWarsd20.py Thu Aug 27 01:04:43 2009 -0500 @@ -107,7 +107,7 @@ """ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('howtouse','HowTO use this tool',SWd20howto,'note') self.new_child_handler('general','General Information',SWd20general,'gear') @@ -127,7 +127,7 @@ def on_version(self,old_version): node_handler.on_version(self,old_version) if old_version == "": - tmp = open(orpg.dirpath.dir_struct["nodes"]+"StarWars_d20character.xml","r") + tmp = open(dir_struct["nodes"]+"StarWars_d20character.xml","r") xml_dom = parseXml_with_dlg(self.tree,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -212,7 +212,7 @@ return html_str def about(self): - html_str = "<img src='" + orpg.dirpath.dir_struct["icon"]+'d20_logo.gif' "><br /><b>d20 Character Tool v0.7 beta</b>" + html_str = "<img src='" + dir_struct["icon"]+'d20_logo.gif' "><br /><b>d20 Character Tool v0.7 beta</b>" html_str += "<br />by Chris Davis<br />chris@rpgarchive.com" return html_str @@ -267,7 +267,7 @@ def about(self): - html_str = "<img src='" + orpg.dirpath.dir_struct["icon"]+'d20_logo.gif' "><br /><b>d20 Character Tool v0.7 beta</b>" + html_str = "<img src='" + dir_struct["icon"]+'d20_logo.gif' "><br /><b>d20 Character Tool v0.7 beta</b>" html_str += "<br />by Chris Davis<br />chris@rpgarchive.com" return html_str @@ -291,7 +291,7 @@ node_handler.__init__(self,xml_dom, tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -305,7 +305,7 @@ if self.myeditor == None or self.myeditor.destroyed: title = self.master_dom.getAttribute('name') + " Editor" # Frame created in correctly. - self.myeditor = wx.Frame(self.frame,title,orpg.dirpath.dir_struct["icon"]+'grid.ico') + self.myeditor = wx.Frame(self.frame,title,dir_struct["icon"]+'grid.ico') wnd = self.get_design_panel(self.myeditor) self.myeditor.panel = wnd self.wnd = wnd @@ -558,7 +558,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + ", " html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -569,7 +569,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() @@ -652,7 +652,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + "<br />" html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -663,7 +663,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() class SWd20hp(SWd20_char_child): @@ -1004,7 +1004,7 @@ self.master_dom = handler.master_dom n_list = self.master_dom._get_childNodes() for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) self.sizer.AddMany([ (wx.StaticText(self, -1, t_node._get_nodeValue()), 0, wx.ALIGN_CENTER_VERTICAL), ]) self.sizer.AddGrowableCol(1) @@ -1143,7 +1143,7 @@ if row==0: self.handler.on_name_change(value) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) self.SetCellValue(rowi,1,t_node._get_nodeValue()) @@ -1183,7 +1183,7 @@ if row==0: self.handler.on_name_change(value) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) self.SetCellValue(rowi,1,t_node._get_nodeValue()) @@ -1439,7 +1439,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["SWd20"]+"d20feats.xml","r") + tmp = open(dir_struct["SWd20"]+"d20feats.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -1609,7 +1609,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["SWd20"]+"d20weapons.xml","r") + tmp = open(dir_struct["SWd20"]+"d20weapons.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -1724,7 +1724,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["SWd20"]+"d20armor.xml","r") + tmp = open(dir_struct["SWd20"]+"d20armor.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -1811,7 +1811,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["SWd20"]+"SWd20classes.xml","r") + tmp = open(dir_struct["SWd20"]+"SWd20classes.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close()
--- a/orpg/gametree/nodehandlers/chatmacro.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/chatmacro.py Thu Aug 27 01:04:43 2009 -0500 @@ -42,7 +42,7 @@ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) self.text_elem = self.master_dom.getElementsByTagName('text')[0] - self.text = safe_get_text_node(self.text_elem) + self.text = component.get('xml').safe_get_text_node(self.text_elem) def set_text(self,txt): self.text._set_nodeValue(txt)
--- a/orpg/gametree/nodehandlers/containers.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/containers.py Thu Aug 27 01:04:43 2009 -0500 @@ -28,7 +28,7 @@ from core import * -import wx.lib.splitter +from wx.lib.splitter import MultiSplitterWindow ########################## @@ -295,7 +295,7 @@ self.pane = splitter_panel(parent, self) - self.splitter = wx.lib.splitter.MultiSplitterWindow(self.pane, -1, style=wx.SP_LIVE_UPDATE|wx.SP_3DSASH|wx.SP_NO_XP_THEME) + self.splitter = MultiSplitterWindow(self.pane, -1, style=wx.SP_LIVE_UPDATE|wx.SP_3DSASH|wx.SP_NO_XP_THEME) if self.split == '1': self.splitter.SetOrientation(wx.VERTICAL)
--- a/orpg/gametree/nodehandlers/core.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/core.py Thu Aug 27 01:04:43 2009 -0500 @@ -31,9 +31,8 @@ from nodehandler_version import NODEHANDLER_VERSION try: from orpg.orpg_windows import * - import orpg.dirpath - from orpg.orpg_xml import * - from orpg.orpgCore import open_rpg + from orpg.dirpath import dir_struct + from orpg.orpgCore import component import webbrowser from orpg.mapper import map import os @@ -41,8 +40,6 @@ import wx - - #html defaults TH_BG = "#E9E9E9" ########################## @@ -53,13 +50,13 @@ def __init__(self,xml_dom,tree_node): self.master_dom = xml_dom self.mytree_node = tree_node - self.tree = open_rpg.get_component('tree') - self.frame = open_rpg.get_component('frame') - self.chat = open_rpg.get_component('chat') - self.xml = open_rpg.get_component('xml') + self.tree = component.get('tree') + self.frame = component.get('frame') + self.chat = component.get('chat') + self.xml = component.get('xml') #Not used? self.drag = True self.myeditor = None # designing - self.myviewer = None # prett print + self.myviewer = None # pretty print self.mywindow = None # using # call version hook self.on_version(self.master_dom.getAttribute("version")) @@ -114,8 +111,7 @@ if self.create_designframe(): self.myeditor.Show() self.myeditor.Raise() - else: - return + else: return wx.CallAfter(self.myeditor.Layout) @@ -124,7 +120,7 @@ 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) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myeditor.SetIcon(icon) del icon @@ -163,14 +159,13 @@ return wx.CallAfter(self.mywindow.Layout) - def create_useframe(self): caption = self.master_dom.getAttribute('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) + icon = wx.Icon(dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO) self.mywindow.SetIcon(icon) del icon self.mywindow.panel = self.get_use_panel(self.mywindow) @@ -203,7 +198,7 @@ caption = self.master_dom.getAttribute('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) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myviewer.SetIcon(icon) del icon self.myviewer.panel = self.get_html_panel(self.myviewer) @@ -246,7 +241,7 @@ self.tree.load_xml(xml_dom, parent_node, prev_sib) def toxml(self,pretty=0): - return toxml(self.master_dom,pretty) + return component.get('xml').toxml(self.master_dom,pretty) def tohtml(self): return self.master_dom.getAttribute("name") @@ -270,7 +265,7 @@ 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) + f = wx.FileDialog(self.tree,"Select a file", dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE) if f.ShowModal() == wx.ID_OK: type = f.GetFilterIndex() if f.GetPath()[:len(f.GetPath())-4] != '.xml': file = open(f.GetPath()+'.xml',"w") @@ -392,11 +387,11 @@ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) self.file_node = self.master_dom._get_firstChild() - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') def on_ldclick(self,evt): file_name = self.file_node.getAttribute("name") - self.tree.insert_xml(open(orpg.dirpath.dir_struct["nodes"] + file_name,"r").read()) + self.tree.insert_xml(open(dir_struct["nodes"] + file_name,"r").read()) return 1 def on_design(self,evt): @@ -424,7 +419,7 @@ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) self.file_node = self.master_dom._get_firstChild() - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') def on_ldclick(self,evt): file_name = self.file_node.getAttribute("url") @@ -455,9 +450,9 @@ """ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) - self.map = open_rpg.get_component('map') + self.map = component.get('map') self.mapdata = self.master_dom._get_firstChild() def on_ldclick(self,evt): self.map.new_data(toxml(self.mapdata)) - return 1 + return 1
--- a/orpg/gametree/nodehandlers/d20.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/d20.py Thu Aug 27 01:04:43 2009 -0500 @@ -112,7 +112,7 @@ """ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('howtouse','HowTO use this tool',d20howto,'note') self.new_child_handler('general','General Information',d20general,'gear') @@ -301,7 +301,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -573,7 +573,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + ", " html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -584,7 +584,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() @@ -714,7 +714,7 @@ created by d20char_handler. """ def __init__(self,xml_dom,tree_node,parent): - d20_char_child.__init__(self,xml_dom,tree_node,openrpg,parent) + d20_char_child.__init__(self,xml_dom,tree_node,component,parent) node_list = self.master_dom.getElementsByTagName( 'gift' ) self.spells = {} tree = self.tree @@ -903,7 +903,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + "<br />" html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -914,7 +914,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() class d20hp(d20_char_child): @@ -1302,7 +1302,7 @@ self.master_dom = handler.master_dom n_list = self.master_dom._get_childNodes() for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) self.sizer.AddMany([ (wx.StaticText(self, -1, t_node._get_nodeValue()), 0, wx.ALIGN_CENTER_VERTICAL), ]) self.sizer.AddGrowableCol(1) @@ -1411,7 +1411,7 @@ if row==0: self.handler.on_name_change(value) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) self.SetCellValue(rowi,1,t_node._get_nodeValue()) @@ -1451,7 +1451,7 @@ if row==0: self.handler.on_name_change(value) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) self.SetCellValue(rowi,1,t_node._get_nodeValue())
--- a/orpg/gametree/nodehandlers/dnd35.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/dnd35.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,9 +1,10 @@ -import orpg.tools.orpg_settings -import orpg.minidom +#from orpg.tools.orpg_settings import settings #Settings used? +#import orpg.minidom from core import * from containers import * from string import * #a 1.6003 -from inspect import * #a 1.9001 +from inspect import * #a 1.9001 +from orpg.dirpath import dir_struct dnd35_EXPORT = wx.NewId() ############Global Stuff############## @@ -45,7 +46,7 @@ self.hparent = None #a 1.5002 allow ability to run up tree, this is the - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('general','GeneralInformation',dnd35general,'gear') self.new_child_handler('inventory','MoneyAndInventory',dnd35inventory,'money') @@ -90,7 +91,7 @@ return html_str def about(self): - html_str = "<img src='" + orpg.dirpath.dir_struct["icon"] + html_str = "<img src='" + dir_struct["icon"] html_str += "dnd3e_logo.gif' ><br /><b>dnd35 Character Tool " html_str += self.Version+"</b>" #m 1.6000 was hard coded. html_str += "<br />by Dj Gilcrease<br />digitalxero@gmail.com" @@ -120,7 +121,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -169,7 +170,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + ", " html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -183,7 +184,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() class gen_grid(wx.grid.Grid): @@ -218,7 +219,7 @@ #self.AutoSizeColumn(1) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) @@ -244,7 +245,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>Inventory</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + "<br />" html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -316,12 +317,12 @@ for node in self.n_list: if node._get_tagName() == nodeName: - t_node = safe_get_text_node(node) + t_node = component.get('xml').safe_get_text_node(node) t_node._set_nodeValue(value) def saveMoney(self, row, col): value = self.grid.GetCellValue(row, col) - t_node = safe_get_text_node(self.n_list[row]) + t_node = component.get('xml').safe_get_text_node(self.n_list[row]) t_node._set_nodeValue(value) def on_cell_change(self, evt): @@ -333,7 +334,7 @@ def refresh_row(self, row): - t_node = safe_get_text_node(self.n_list[row]) + t_node = component.get('xml').safe_get_text_node(self.n_list[row]) tagname = self.n_list[row]._get_tagName() value = t_node._get_nodeValue() if tagname == 'Gear': @@ -357,7 +358,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.hparent = parent #a 1.5002 allow ability to run up tree. dnd35_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('abilities','Abilities Scores',dnd35ability,'gear') self.new_child_handler('classes','Classes',dnd35classes,'knight') @@ -389,7 +390,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None def on_drop(self,evt): @@ -680,7 +681,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+"dnd35classes.xml","r") + tmp = open(dir_struct["dnd35"]+"dnd35classes.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -907,7 +908,7 @@ node_handler.__init__(self,xml_dom,tree_node) dnd35_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('skills','Skills',dnd35skill,'book') self.new_child_handler('feats','Feats',dnd35feats,'book') @@ -938,7 +939,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -1314,7 +1315,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+"dnd35feats.xml","r") + tmp = open(dir_struct["dnd35"]+"dnd35feats.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -1329,7 +1330,8 @@ i = dlg.GetSelection() new_node = self.master_dom.appendChild(f_list[i].cloneNode(False)) self.grid.AppendRows(1) - self.refresh_row(self.grid.GetNumberRows()-1) + self.refresh_row(self.grid.GetNumberRows()-1) + f_list=0; opts=0 dlg.Destroy() @@ -1358,7 +1360,7 @@ #mark3 dnd35_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('hp','Hit Points',dnd35hp,'gear') self.new_child_handler('attacks','Attacks',dnd35attacks,'spears') @@ -1392,7 +1394,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -1579,7 +1581,7 @@ def updateFootN(self,n):#a 1.5012 this whole function if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+"dnd35weapons.xml","r") + tmp = open(dir_struct["dnd35"]+"dnd35weapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") #a (debug) 1.5012 self.temp_dom = xml.dom.minidom.parse(tmp) @@ -2048,7 +2050,7 @@ fnFrame = wx.Frame(masterFrame, -1, title) fnFrame.panel = wx.html.HtmlWindow(fnFrame,-1) if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+ + tmp = open(dir_struct["dnd35"]+ "dnd35weapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) @@ -2141,11 +2143,11 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+"dnd35weapons.xml","r") + tmp = open(dir_struct["dnd35"]+"dnd35weapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") #a (debug) 1.5012 xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() - tmp.close() + tmp.close(); print self.temp_dom = xml_dom f_list = self.temp_dom.getElementsByTagName('weapon') opts = [] @@ -2368,7 +2370,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd35"]+"dnd35armor.xml","r") + tmp = open(dir_struct["dnd35"]+"dnd35armor.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close()
--- a/orpg/gametree/nodehandlers/dnd3e.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/dnd3e.py Thu Aug 27 01:04:43 2009 -0500 @@ -143,12 +143,15 @@ # r- resolved # o- open # -import orpg.tools.orpg_settings -import orpg.minidom + +#import orpg.tools.orpg_settings #Not used?? +#import orpg.minidom from core import * from containers import * from string import * #a 1.6003 -from inspect import * #a 1.9001 +from inspect import * #a 1.9001 +from orpg.dirpath import dir_struct + dnd3e_EXPORT = wx.NewId() ############Global Stuff############## @@ -233,7 +236,7 @@ #a 1.5002 top of the handler tree, this is used to flag where to stop #a 1.5002 on the way up. Changing this will break getRoot(self) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('howtouse','HowTo use this tool',dnd3ehowto,'note') self.new_child_handler('general','GeneralInformation',dnd3egeneral,'gear') @@ -300,12 +303,11 @@ html_str += "<P>" + self.pp.tohtml() html_str += "<P>" + self.skills.tohtml() +"</td>" #a block for 1.6009 end - html_str += "</tr></table>" return html_str def about(self): - html_str = "<img src='" + orpg.dirpath.dir_struct["icon"] + html_str = "<img src='" + dir_struct["icon"] html_str += "dnd3e_logo.gif' ><br><b>dnd3e Character Tool " html_str += self.Version+"</b>" #m 1.6000 was hard coded. html_str += "<br>by Dj Gilcrease<br>digitalxero@gmail.com" @@ -335,7 +337,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -387,7 +389,7 @@ self.master_dom = handler.master_dom n_list = self.master_dom._get_childNodes() for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) self.sizer.Add(wx.StaticText(self, -1, t_node._get_nodeValue()), 1, wx.EXPAND) self.SetSizer(self.sizer) self.SetAutoLayout(True) @@ -413,7 +415,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + ", " html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -427,7 +429,7 @@ def get_char_name( self ): node = self.master_dom.getElementsByTagName( 'name' )[0] - t_node = safe_get_text_node( node ) + t_node = component.get('xml').safe_get_text_node( node ) return t_node._get_nodeValue() class gen_grid(wx.grid.Grid): @@ -462,7 +464,7 @@ #self.AutoSizeColumn(1) def refresh_row(self,rowi): - t_node = safe_get_text_node(self.n_list[rowi]) + t_node = component.get('xml').safe_get_text_node(self.n_list[rowi]) self.SetCellValue(rowi,0,self.n_list[rowi]._get_tagName()) self.SetReadOnly(rowi,0) @@ -488,7 +490,7 @@ n_list = self.master_dom._get_childNodes() html_str = "<table width=100% border=1 ><tr BGCOLOR=#E9E9E9 ><th>General Information</th></tr><tr><td>" for n in n_list: - t_node = safe_get_text_node(n) + t_node = component.get('xml').safe_get_text_node(n) html_str += "<B>"+n._get_tagName().capitalize() +":</B> " html_str += t_node._get_nodeValue() + "<br>" html_str = html_str[:len(html_str)-2] + "</td></tr></table>" @@ -560,12 +562,12 @@ for node in self.n_list: if node._get_tagName() == nodeName: - t_node = safe_get_text_node(node) + t_node = component.get('xml').safe_get_text_node(node) t_node._set_nodeValue(value) def saveMoney(self, row, col): value = self.grid.GetCellValue(row, col) - t_node = safe_get_text_node(self.n_list[row]) + t_node = component.get('xml').safe_get_text_node(self.n_list[row]) t_node._set_nodeValue(value) def on_cell_change(self, evt): @@ -577,7 +579,7 @@ def refresh_row(self, row): - t_node = safe_get_text_node(self.n_list[row]) + t_node = component.get('xml').safe_get_text_node(self.n_list[row]) tagname = self.n_list[row]._get_tagName() value = t_node._get_nodeValue() if tagname == 'Gear': @@ -601,7 +603,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.hparent = parent #a 1.5002 allow ability to run up tree. dnd3e_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('abilities','Abilities Scores',dnd3eability,'gear') self.new_child_handler('classes','Classes',dnd3eclasses,'knight') @@ -633,7 +635,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None def on_drop(self,evt): @@ -919,7 +921,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3eclasses.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3eclasses.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -1150,7 +1152,7 @@ node_handler.__init__(self,xml_dom,tree_node) dnd3e_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('skills','Skills',dnd3eskill,'book') self.new_child_handler('feats','Feats',dnd3efeats,'book') @@ -1182,7 +1184,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -1550,12 +1552,12 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3efeats.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3efeats.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() - self.temp_dom = xml_dom - f_list = self.temp_dom.getElementsByTagName('feat') + temp_dom = xml_dom + f_list = temp_dom.getElementsByTagName('feat') opts = [] for f in f_list: opts.append(f.getAttribute('name') + " - [" + @@ -1594,7 +1596,7 @@ #mark3 dnd3e_char_child.__init__(self,xml_dom,tree_node,parent) - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('hp','Hit Points',dnd3ehp,'gear') self.new_child_handler('attacks','Attacks',dnd3eattacks,'spears') @@ -1628,7 +1630,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -1815,7 +1817,7 @@ def updateFootN(self,n):#a 1.5012 this whole function if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3eweapons.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3eweapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") #a (debug) 1.5012 self.temp_dom = xml.dom.minidom.parse(tmp) @@ -2248,7 +2250,7 @@ fnFrame = wx.Frame(masterFrame, -1, title) fnFrame.panel = wx.html.HtmlWindow(fnFrame,-1) if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+ + tmp = open(dir_struct["dnd3e"]+ "dnd3eweapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) @@ -2354,7 +2356,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3eweapons.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3eweapons.xml","r") #tmp = open("c:\clh\codeSamples\sample1.xml","r") #a (debug) 1.5012 xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() @@ -2581,7 +2583,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3earmor.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3earmor.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -2620,7 +2622,7 @@ self.hparent = parent #a 1.5002 allow ability to run up tree. - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.child_handlers = {} self.new_child_handler('spells','Spells',dnd3espells,'book') self.new_child_handler('divine','Divine Spells',dnd3edivine,'book') @@ -2658,7 +2660,7 @@ node_handler.__init__(self,xml_dom,tree_node) self.char_hander = parent self.drag = False - self.frame = open_rpg.get_component('frame') + self.frame = component.get('frame') self.myeditor = None @@ -2844,7 +2846,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3espells.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3espells.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() tmp.close() @@ -3051,7 +3053,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3edivine.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3edivine.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild() @@ -3288,7 +3290,7 @@ def on_add(self,evt): if not self.temp_dom: - tmp = open(orpg.dirpath.dir_struct["dnd3e"]+"dnd3epowers.xml","r") + tmp = open(dir_struct["dnd3e"]+"dnd3epowers.xml","r") xml_dom = parseXml_with_dlg(self,tmp.read()) xml_dom = xml_dom._get_firstChild()
--- a/orpg/gametree/nodehandlers/forms.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/forms.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,7 +29,7 @@ __version__ = "$Id: forms.py,v 1.53 2007/04/21 23:00:51 digitalxero Exp $" from containers import * -import wx.lib.scrolledpanel +from wx.lib.scrolledpanel import ScrolledPanel def bool2int(b): #in wxPython 2.5+, evt.Checked() returns True or False instead of 1.0 or 0. @@ -81,9 +81,9 @@ container_handler.on_drop(self,evt) -class form_panel(wx.lib.scrolledpanel.ScrolledPanel): +class form_panel(ScrolledPanel): def __init__(self, parent, handler): - wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent, wx.ID_ANY, style=wx.NO_BORDER|wx.VSCROLL|wx.HSCROLL) + ScrolledPanel.__init__(self, parent, wx.ID_ANY, style=wx.NO_BORDER|wx.VSCROLL|wx.HSCROLL) self.height = int(handler.atts.getAttribute("height")) self.width = int(handler.atts.getAttribute("width")) @@ -112,7 +112,7 @@ if x < nx: x = nx+10 y += ny+11 - wx.lib.scrolledpanel.ScrolledPanel.SetSize(self, (x, y)) + ScrolledPanel.SetSize(self, (x, y)) def create_child_wnd(self, obj, evt): @@ -209,9 +209,9 @@ </nodehandler> """ def __init__(self,xml_dom,tree_node): - node_handler.__init__(self,xml_dom,tree_node) + node_handler.__init__(self,xml_dom,tree_node) self.text_elem = self.master_dom.getElementsByTagName('text')[0] - self.text = safe_get_text_node(self.text_elem) + self.text = component.get('xml').safe_get_text_node(self.text_elem) if self.text_elem.getAttribute("send_button") == "": self.text_elem.setAttribute("send_button","0") if self.text_elem.getAttribute("raw_mode") == "": @@ -410,7 +410,7 @@ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) self.list = self.master_dom.getElementsByTagName('list')[0] - self.options = self.list.getElementsByTagName('option') + self.options = self.list.getElementsByTagName('option') if self.list.getAttribute("send_button") == "": self.list.setAttribute("send_button","0") if self.list.getAttribute("hide_title") == "": @@ -448,7 +448,7 @@ def get_selected_text(self): node = self.get_selected_node() if node: - return safe_get_text_node(node)._get_nodeValue() + return component.get('xml').safe_get_text_node(node)._get_nodeValue() else: return "" @@ -466,7 +466,7 @@ opts = [] for opt in self.options: if opt.getAttribute("selected") == "1": - opts.append(safe_get_text_node(opt)._get_nodeValue()) + opts.append(component.get('xml').safe_get_text_node(opt)._get_nodeValue()) return opts def get_selections_index(self): @@ -494,11 +494,11 @@ def get_options(self): opts = [] for opt in self.options: - opts.append(safe_get_text_node(opt)._get_nodeValue()) + opts.append(component.get('xml').safe_get_text_node(opt)._get_nodeValue()) return opts def get_option(self,index): - return safe_get_text_node(self.options[index])._get_nodeValue() + return component.get('xml').safe_get_text_node(self.options[index])._get_nodeValue() def add_option(self,opt): elem = minidom.Element('option') @@ -514,7 +514,7 @@ self.options = self.list.getElementsByTagName('option') def edit_option(self,index,value): - safe_get_text_node(self.options[index])._set_nodeValue(value) + component.get('xml').safe_get_text_node(self.options[index])._set_nodeValue(value) def has_send_button(self): if self.list.getAttribute("send_button") == '0':
--- a/orpg/gametree/nodehandlers/map_miniature_nodehandler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/map_miniature_nodehandler.py Thu Aug 27 01:04:43 2009 -0500 @@ -33,7 +33,6 @@ from orpg.mapper.images import ImageHandler import urllib - class map_miniature_handler(node_handler): """ A node handler for miniatures @@ -45,8 +44,8 @@ def __init__(self,xml_dom,tree_node): node_handler.__init__(self,xml_dom,tree_node) - self.mapper = open_rpg.get_component("map") - self.session = open_rpg.get_component("session") + self.mapper = component.get("map") + self.session = component.get("session") self.miniature_dom = self.master_dom.getElementsByTagName("miniature") if self.miniature_dom: self.miniature_dom = self.miniature_dom[0] # convert to scalar @@ -120,7 +119,7 @@ self.miniature_dom.setAttribute("posy", str(pos.y)) new_xml = self.get_to_map_XML() if (self.session.my_role() != self.session.ROLE_GM) and (self.session.my_role() != self.session.ROLE_PLAYER): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use the miniature Layer") + component.get("chat").InfoPost("You must be either a player or GM to use the miniature Layer") return if new_xml:
--- a/orpg/gametree/nodehandlers/minilib.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/minilib.py Thu Aug 27 01:04:43 2009 -0500 @@ -32,10 +32,10 @@ miniatures as sending them to the map singly or in batches. """ from core import * -import orpg.dirpath +from orpg.dirpath import dir_struct import string import map_miniature_nodehandler -import orpg.mapper.map_msg +import orpg.mapper.map_msg # import scriptkit # Constants @@ -189,11 +189,11 @@ if mini.getAttribute( ATTRIBUTE_URL ) == '' or mini.getAttribute( ATTRIBUTE_URL ) == 'http://': self.chat.ParsePost( self.chat.colorize(self.chat.syscolor, '"%s" is not a valid URL, the mini "%s" will not be added to the map' % ( mini.getAttribute( ATTRIBUTE_URL ), mini.getAttribute( ATTRIBUTE_NAME ) )) ) return - session = open_rpg.get_component( COMPONENT_SESSION ) + session = component.get( COMPONENT_SESSION ) if (session.my_role() != session.ROLE_GM) and (session.my_role() != session.ROLE_PLAYER): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use the miniature Layer") + component.get("chat").InfoPost("You must be either a player or GM to use the miniature Layer") return - map = open_rpg.get_component(COMPONENT_MAP) + map = component.get(COMPONENT_MAP) for loop in range( count ): msg = self.get_miniature_XML( mini, addName) msg = str("<map action='update'><miniatures>" + msg + "</miniatures></map>") @@ -202,8 +202,8 @@ def get_miniature_XML( self, mini, addName = True ): msg = orpg.mapper.map_msg.mini_msg() - map = open_rpg.get_component( COMPONENT_MAP ) - session = open_rpg.get_component( COMPONENT_SESSION ) + map = component.get( COMPONENT_MAP ) + session = component.get( COMPONENT_SESSION ) msg.init_prop( ATTRIBUTE_ID, session.get_next_id() ) for k in mini.getAttributeKeys(): # translate our attributes to map attributes @@ -218,7 +218,7 @@ label = mini.getAttribute( ATTRIBUTE_NAME ) else: label = '' - return msg.get_all_xml() + return msg().get_all_xml() def is_unique( self, mini ): unique = mini.getAttribute( ATTRIBUTE_UNIQUE ) @@ -272,7 +272,7 @@ self.handler = handler self.frame = frame - self.map = open_rpg.get_component('map') + self.map = component.get('map') names = self.buildList() # self.keys = self.list.keys() # self.keys.sort()
--- a/orpg/gametree/nodehandlers/rpg_grid.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/rpg_grid.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,7 +29,8 @@ __version__ = "$Id: rpg_grid.py,v 1.20 2006/11/15 12:11:24 digitalxero Exp $" from core import * -from forms import * +from forms import * +from orpg.minidom import Element, Text class rpg_grid_handler(node_handler): """ Node handler for rpg grid tool @@ -196,12 +197,12 @@ self._tc.SetDimensions(rect.x+1, rect.y+1, rect.width+2, rect.height+2) - def Show(self, show, attr): - """ - Show or hide the edit control. You can use the attr (if not None) - to set colours or fonts for the control. - """ - self.base_Show(show, attr) + #def Show(self, show, attr): #deprecated DeprecationWarning: Please use PyGridCellEditor.Show instead. + # """ + # Show or hide the edit control. You can use the attr (if not None) + # to set colours or fonts for the control. + # """ + # self.base_Show(show, attr) # Removed to prevent recursive error type. def BeginEdit(self, row, col, grid): @@ -283,7 +284,6 @@ evt.Skip() - def Destroy(self): """final cleanup""" self.base_Destroy() @@ -341,7 +341,6 @@ value = self.GetCellValue(row,col) cells = self.rows[row].getElementsByTagName('cell') t_node = cells[col]._get_firstChild() - print t_node t_node._set_nodeValue(value) if col == 0: self.handler.refresh_rows() @@ -362,7 +361,7 @@ if t_node == None: #doc = cells[i].ownerDocument #t_node = doc.createTextNode("") - t_node = minidom.Text("") + t_node = Text("") t_node = cells[i].appendChild(t_node) self.SetCellValue(rowi,i,t_node._get_nodeValue()) @@ -370,12 +369,12 @@ cols = self.GetNumberCols() #doc = self.handler.grid.ownerDocument #row = doc.createElement('row') - row = minidom.Element('row') + row = Element('row') for i in range(0,cols): #cell = doc.createElement('cell') - cell = minidom.Element('cell') + cell = Element('cell') #t_node = doc.createTextNode("") - t_node = minidom.Text("") + t_node = Text("") t_node = cell.appendChild(t_node) row.appendChild(cell) self.handler.grid.appendChild(row) @@ -387,9 +386,9 @@ #doc = self.handler.grid.ownerDocument for r in self.rows: #cell = doc.createElement('cell') - cell = minidom.Element('cell') + cell = Element('cell') #t_node = doc.createTextNode("") - t_node = minidom.Text("") + t_node = Text("") t_node = cell.appendChild(t_node) r.appendChild(cell) self.AppendCols(1)
--- a/orpg/gametree/nodehandlers/voxchat.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/gametree/nodehandlers/voxchat.py Thu Aug 27 01:04:43 2009 -0500 @@ -39,10 +39,10 @@ import orpg.tools.rgbhex import orpg.tools.inputValidator -import orpg.dirpath +from orpg.dirpath import dir_struct import orpg.minidom import orpg.networking.mplay_client -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component # # Good things to add: @@ -55,14 +55,14 @@ def __init__(self, xml_dom, tree_node): core.node_handler.__init__( self, xml_dom, tree_node) self.node = xml_dom - self.xml = open_rpg.get_component('xml') + self.xml = component.get('xml') def get_design_panel( self, parent ): - aliasLib = open_rpg.get_component('alias') + aliasLib = component.get('alias') aliasLib.ImportFromTree(self.node) return None def get_use_panel( self, parent ): - aliasLib = open_rpg.get_component('alias') + aliasLib = component.get('alias') aliasLib.ImportFromTree(self.node) return None
--- a/orpg/main.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/main.py Thu Aug 27 01:04:43 2009 -0500 @@ -33,29 +33,38 @@ from orpg.orpgCore import * from orpg_version import * from orpg.orpg_windows import * -import orpg.dirpath -import orpg.orpg_xml + +import wx.py +from orpg import minidom import orpg.player_list import orpg.tools.pluginui as pluginUI -import orpg.tools.orpg_settings -import orpg.tools.orpg_log import orpg.tools.aliaslib -from orpg.tools.metamenus import MenuBarEx import orpg.tools.toolBars -import orpg.tools.passtool import orpg.tools.orpg_sound -import orpg.tools.validate import orpg.tools.rgbhex import orpg.gametree.gametree import orpg.chat.chatwnd -import orpg.dieroller.utils +import orpg.networking.gsclient import orpg.networking.mplay_client -import orpg.networking.gsclient import orpg.mapper.map import orpg.mapper.images + import upmana.updatemana import upmana.manifest as manifest -import wx.py + +from orpg.dirpath import dir_struct +from orpg.dieroller.utils import DiceManager +from orpg.tools.orpg_settings import settings +from orpg.tools.validate import validate +from orpg.tools.passtool import PassTool +from orpg.tools.orpg_log import logger, crash +from orpg.tools.decorators import debugging +from orpg.tools.metamenus import MenuBarEx + +#from xml.etree.ElementTree import ElementTree, Element +#from xml.etree.ElementTree import fromstring, tostring +from orpg.orpg_xml import xml #to be replaced by etree + #################################### ## Main Frame @@ -63,22 +72,18 @@ class orpgFrame(wx.Frame): + @debugging def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.Point(100, 100), wx.Size(600,420), style=wx.DEFAULT_FRAME_STYLE) - self.log = open_rpg.get_component("log") - self.xml = open_rpg.get_component("xml") - self.dir_struct = open_rpg.get_component("dir_struct") - self.validate = open_rpg.get_component("validate") - self.settings = open_rpg.get_component("settings") - self.log.log("Enter orpgFrame", ORPG_DEBUG) - self.rgbcovert = orpg.tools.rgbhex.RGBHex() + self.validate = component.get("validate") + logger.debug("Enter orpgFrame") + self.rgb = orpg.tools.rgbhex.RGBHex() self._mgr = AUI.AuiManager(self) # Determine which icon format to use icon = None - if wx.Platform == '__WXMSW__': icon = wx.Icon(orpg.dirpath.dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) - else: icon = wx.Icon(orpg.dirpath.dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM) - #if icon != None: self.SetIcon( icon ) worth 'less' now since it sets the icon either or. + if wx.Platform == '__WXMSW__': icon = wx.Icon(dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) + else: icon = wx.Icon(dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM) self.SetIcon( icon ) # create session @@ -89,6 +94,7 @@ "on_status_event":self.on_status_event, "on_password_signal":self.on_password_signal, "orpgFrame":self} + self.settings = component.get('settings') #Arbitrary until settings updated with Core. self.session = orpg.networking.mplay_client.mplay_client(self.settings.get_setting("player"), call_backs) self.poll_timer = wx.Timer(self, wx.NewId()) self.Bind(wx.EVT_TIMER, self.session.poll, self.poll_timer) @@ -97,66 +103,73 @@ self.Bind(wx.EVT_TIMER, self.session.update, self.ping_timer) # create roller manager - self.DiceManager = orpg.dieroller.utils.roller_manager(self.settings.get_setting("dieroller")) + self.DiceManager = DiceManager(settings.get_setting("dieroller")) + component.add('DiceManager', self.DiceManager) #create password manager --SD 8/03 - self.password_manager = orpg.tools.passtool.PassTool() - open_rpg.add_component("session", self.session) - open_rpg.add_component('frame', self) - open_rpg.add_component('DiceManager', self.DiceManager) - open_rpg.add_component('password_manager', self.password_manager) + self.password_manager = component.get('password_manager') + component.add("session", self.session) + component.add('frame', self) # build frame windows self.build_menu() self.build_gui() self.build_hotkeys() - self.log.log("GUI Built", ORPG_DEBUG) - open_rpg.add_component("chat",self.chat) - open_rpg.add_component("map",self.map) - open_rpg.add_component("alias", self.aliaslib) - self.log.log("openrpg components all added", ORPG_DEBUG) - self.tree.load_tree(self.settings.get_setting("gametree")) - self.log.log("Tree Loaded", ORPG_DEBUG) + + logger.debug("GUI Built") + component.add("chat",self.chat) + component.add("map",self.map) + component.add("alias", self.aliaslib) + + logger.debug("openrpg components all added") + self.tree.load_tree(settings.get_setting("gametree")) + logger.debug("Tree Loaded") self.players.size_cols() - self.log.log("player window cols sized", ORPG_DEBUG) #Load the Plugins This has to be after the chat component has been added - open_rpg.add_component('pluginmenu', self.pluginMenu) + component.add('pluginmenu', self.pluginMenu) self.pluginsFrame.Start() - self.log.log("plugins reloaded and startup plugins launched", ORPG_DEBUG) + logger.debug("plugins reloaded and startup plugins launched") self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) - self.log.log("Exit orpgFrame", ORPG_DEBUG) + + #Load Update Manager + component.add('updatemana', self.updateMana) + logger.debug("update manager reloaded") + self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) #Load Update Manager - open_rpg.add_component('updatemana', self.updateMana) - self.log.log("update manager reloaded", ORPG_DEBUG) + component.add('debugconsole', self.debugger) + logger.debug("debugger window") self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) - self.log.log("Exit orpgFrame", ORPG_DEBUG) + @debugging def post_show_init(self): """Some Actions need to be done after the main fram is drawn""" - self.log.log("Enter orpgFrame->post_show_init(self)", ORPG_DEBUG) self.players.size_cols() - self.log.log("Exit orpgFrame->post_show_init(self)", ORPG_DEBUG) + @debugging def get_activeplugins(self): - self.log.log("Enter orpgFrame->get_activeplugins(self)", ORPG_DEBUG) try: tmp = self.pluginsFrame.get_activeplugins() except: tmp = {} - self.log.log("Exit orpgFrame->get_activeplugins(self)", ORPG_DEBUG) return tmp + @debugging def get_startplugins(self): - self.log.log("Enter orpgFrame->get_startplugins(self)", ORPG_DEBUG) try: tmp = self.pluginsFrame.get_startplugins() except: tmp = {} - self.log.log("Exit orpgFrame->get_startplugins(self)", ORPG_DEBUG) return tmp + @debugging def on_password_signal(self,signal,type,id,data): - self.log.log("Enter orpgFrame->on_password_signal(self,signal,type,id,data)", ORPG_DEBUG) try: - self.log.log("DEBUG: password response= "+str(signal)+" (T:"+str(type)+" #"+str(id)+")", ORPG_DEBUG) + msg = ["DEBUG: password response= ", + str(signal), + " (T:", + str(type), + " #", + str(id), + ")"] + logger.debug("".join(msg)) id = int(id) type = str(type) data = str(data) @@ -167,10 +180,9 @@ elif type == "room": self.password_manager.ClearPassword("room", int(id)) else: pass except: traceback.print_exc() - self.log.log("Exit orpgFrame->on_password_signal(self,signal,type,id,data)", ORPG_DEBUG) + @debugging def build_menu(self): - self.log.log("Enter orpgFrame->build_menu()", ORPG_DEBUG) menu = \ [[ ['&OpenRPG'], @@ -222,10 +234,10 @@ ]] self.mainmenu = MenuBarEx(self, menu) - if self.settings.get_setting('Heartbeat') == '1': + if settings.get_setting('Heartbeat') == '1': self.mainmenu.SetMenuState("GameServerServerHeartbeat", True) - tabtheme = self.settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -234,7 +246,7 @@ self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", tabtheme == 'customslant') self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", tabtheme == 'customflat') - lvl = int(self.settings.get_setting('LoggingLevel')) + lvl = int(settings.get_setting('LoggingLevel')) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelDebug", True) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelNote", True) if lvl & ORPG_INFO: self.mainmenu.SetMenuState("ToolsLoggingLevelInfo", True) @@ -247,25 +259,28 @@ self.pluginMenu.AppendItem(item) self.pluginMenu.AppendSeparator() self.mainmenu.Insert(2, self.pluginMenu, "&Plugins") - self.log.log("Exit orpgFrame->build_menu()", ORPG_DEBUG) - self.updateMana = wx.Menu() - mana = wx.MenuItem(self.updateMana, wx.ID_ANY, "Update Manager", "Update Manager") + # Traipse Suite of Additions. + self.traipseSuite = wx.Menu() + self.mainmenu.Insert(5, self.traipseSuite, "&Traipse Suite") + + mana = wx.MenuItem(self.traipseSuite, wx.ID_ANY, "Update Manager", "Update Manager") self.Bind(wx.EVT_MENU, self.OnMB_UpdateManagerPanel, mana) + self.traipseSuite.AppendItem(mana) - self.updateMana.AppendItem(mana) - self.mainmenu.Insert(5, self.updateMana, "&Update Manager") - self.log.log("Exit orpgFrame->build_menu()", ORPG_DEBUG) + debugger = wx.MenuItem(self.traipseSuite, -1, "Debug Console", "Debug Console") + self.Bind(wx.EVT_MENU, self.OnMB_DebugConsole, debugger) + self.traipseSuite.AppendItem(debugger) ################################# ## All Menu Events ################################# #Tab Styles Menus + @debugging def SetTabStyles(self, *args, **kwargs): - self.log.log("Enter orpgFrame->SetTabStyles(self, *args, **kwargs)", ORPG_DEBUG) - tabtheme = self.settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -277,11 +292,11 @@ if kwargs.has_key('style'): newstyle = kwargs['style'] else: try: newstyle = args[1] - except: self.log.log('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)', ORPG_GENERAL); return + except: logger.general('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)'); return if kwargs.has_key('menu'): menu = kwargs['menu'] else: try: menu = args[0] - except: self.log.log('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)', ORPG_GENERAL); return + except: logger.general('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)'); return if kwargs.has_key('graidentTo'): graidentTo = kwargs['graidentTo'] else: graidentTo = None @@ -291,19 +306,17 @@ else: textColor = None #Run though the current tabbed window list and remove those that have been closed - tabbedwindows = open_rpg.get_component("tabbedWindows") - rgbc = orpg.tools.rgbhex.RGBHex() + tabbedwindows = component.get("tabbedWindows") new = [] for wnd in tabbedwindows: try: style = wnd.GetWindowStyleFlag(); new.append(wnd) except: pass tabbedwindows = new - open_rpg.add_component("tabbedWindows", tabbedwindows) + component.add("tabbedWindows", tabbedwindows) #Run though the new list and set the proper styles - tabbg = self.settings.get_setting('TabBackgroundGradient') - rgbc = orpg.tools.rgbhex.RGBHex() - (red, green, blue) = rgbc.rgb_tuple(tabbg) + tabbg = settings.get_setting('TabBackgroundGradient') + (red, green, blue) = self.rgb.rgb_tuple(tabbg) for wnd in tabbedwindows: style = wnd.GetWindowStyleFlag() @@ -318,93 +331,86 @@ if textColor != None: wnd.SetNonActiveTabTextColour(textColor) wnd.Refresh() + @debugging def OnMB_OpenRPGNewMap(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGNewMap(self)", ORPG_DEBUG) - self.log.log("Exit orpgFrame->OnMB_OpenRPGNewMap(self)", ORPG_DEBUG) + pass #Not Implemented yet! + @debugging def OnMB_OpenRPGTabStylesSlantedColorful(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesSlantedColorful(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedColorful"): - self.settings.set_setting('TabTheme', 'slanted&colorful') + settings.set_setting('TabTheme', 'slanted&colorful') self.SetTabStyles("OpenRPGTabStylesSlantedColorful", FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedColorful(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesSlantedBlackandWhite(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesSlantedBlackandWhite(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedBlackandWhite"): - self.settings.set_setting('TabTheme', 'slanted&bw') - self.SetTabStyles("OpenRPGTabStylesSlantedBlackandWhite", FNB.FNB_VC8, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) + settings.set_setting('TabTheme', 'slanted&bw') + self.SetTabStyles("OpenRPGTabStylesSlantedBlackandWhite", + FNB.FNB_VC8, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedBlackandWhite(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesSlantedAqua(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesSlantedAqua(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedAqua"): - self.settings.set_setting('TabTheme', 'slanted&aqua') - self.SetTabStyles("OpenRPGTabStylesSlantedAqua", FNB.FNB_VC8, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) + settings.set_setting('TabTheme', 'slanted&aqua') + self.SetTabStyles("OpenRPGTabStylesSlantedAqua", FNB.FNB_VC8, + graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedBlackandWhite(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesSlantedCustom(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesSlantedCustom(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedCustom"): - self.settings.set_setting('TabTheme', 'customslant') - rgbc = orpg.tools.rgbhex.RGBHex() - gfrom = self.settings.get_setting('TabGradientFrom') - (fred, fgreen, fblue) = rgbc.rgb_tuple(gfrom) - gto = self.settings.get_setting('TabGradientTo') - (tored, togreen, toblue) = rgbc.rgb_tuple(gto) - tabtext = self.settings.get_setting('TabTextColor') - (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) - tabbg = self.settings.get_setting('TabBackgroundGradient') - (red, green, blue) = rgbc.rgb_tuple(tabbg) + settings.set_setting('TabTheme', 'customslant') + gfrom = settings.get_setting('TabGradientFrom') + (fred, fgreen, fblue) = self.rgb.rgb_tuple(gfrom) + gto = settings.get_setting('TabGradientTo') + (tored, togreen, toblue) = self.rgb.rgb_tuple(gto) + tabtext = settings.get_setting('TabTextColor') + (tred, tgreen, tblue) = self.rgb.rgb_tuple(tabtext) + tabbg = settings.get_setting('TabBackgroundGradient') + (red, green, blue) = self.rgb.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesSlantedCustom", FNB.FNB_VC8, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), textColor=wx.Color(tred, tgreen, tblue)) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedCustom(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesFlatBlackandWhite(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesFlatBlackandWhite(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatBlackandWhite"): - self.settings.set_setting('TabTheme', 'flat&bw') + settings.set_setting('TabTheme', 'flat&bw') self.SetTabStyles("OpenRPGTabStylesFlatBlackandWhite", FNB.FNB_FANCY_TABS, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesFlatBlackandWhite(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesFlatAqua(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesFlatAqua(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatAqua"): - self.settings.set_setting('TabTheme', 'flat&aqua') + settings.set_setting('TabTheme', 'flat&aqua') self.SetTabStyles("OpenRPGTabStylesFlatAqua", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatAqua", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesFlatAqua(self)", ORPG_DEBUG) + @debugging def OnMB_OpenRPGTabStylesFlatCustom(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGTabStylesFlatCustom(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatCustom"): - self.settings.set_setting('TabTheme', 'customflat') - rgbc = orpg.tools.rgbhex.RGBHex() - gfrom = self.settings.get_setting('TabGradientFrom') - (fred, fgreen, fblue) = rgbc.rgb_tuple(gfrom) - gto = self.settings.get_setting('TabGradientTo') - (tored, togreen, toblue) = rgbc.rgb_tuple(gto) - tabtext = self.settings.get_setting('TabTextColor') - (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) - tabbg = self.settings.get_setting('TabBackgroundGradient') - (red, green, blue) = rgbc.rgb_tuple(tabbg) + settings.set_setting('TabTheme', 'customflat') + gfrom = settings.get_setting('TabGradientFrom') + (fred, fgreen, fblue) = self.rgb.rgb_tuple(gfrom) + gto = settings.get_setting('TabGradientTo') + (tored, togreen, toblue) = self.rgb.rgb_tuple(gto) + tabtext = settings.get_setting('TabTextColor') + (tred, tgreen, tblue) = self.rgb.rgb_tuple(tabtext) + tabbg = settings.get_setting('TabBackgroundGradient') + (red, green, blue) = self.rgb.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesFlatCustom", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), textColor=wx.Color(tred, tgreen, tblue)) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", True) - self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesFlatCustom(self)", ORPG_DEBUG) #Window Menu + @debugging def OnMB_WindowsMenu(self, event): - self.log.log("Enter orpgFrame->OnMB_WindowsMenu(self, event)", ORPG_DEBUG) menuid = event.GetId() name = self.mainwindows[menuid] if name == 'Alias Lib': @@ -414,109 +420,102 @@ if self._mgr.GetPane(name).IsShown(): self._mgr.GetPane(name).Hide() else: self._mgr.GetPane(name).Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_WindowsMenu(self, event)", ORPG_DEBUG) #OpenRPG Menu + @debugging def OnMB_OpenRPGSettings(self): - self.log.log("Enter orpgFrame->OnMB_OpenRPGSettings()", ORPG_DEBUG) dlg = orpg.tools.orpg_settings.orpgSettingsWnd(self) dlg.Centre() dlg.ShowModal() - self.log.log("Exit orpgFrame->OnMB_OpenRPGSettings()", ORPG_DEBUG) def OnMB_OpenRPGExit(self): self.OnCloseWindow(0) #Game Server Menu + @debugging def OnMB_GameServerBrowseServers(self): - self.log.log("Enter orpgFrame->OnMB_GameServerBrowseServers(self)", ORPG_DEBUG) if self._mgr.GetPane("Browse Server Window").IsShown() == True: self._mgr.GetPane("Browse Server Window").Hide() else: self._mgr.GetPane("Browse Server Window").Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_GameServerBrowseServers(self)", ORPG_DEBUG) + @debugging def OnMB_GameServerServerHeartbeat(self): - self.log.log("Enter orpgFrame->OnMB_GameServerServerHeartbeat(self)", ORPG_DEBUG) - if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): self.settings.set_setting('Heartbeat', '1') - else: self.settings.set_setting('Heartbeat', '0') - self.log.log("Exit orpgFrame->OnMB_GameServerServerHeartbeat(self)", ORPG_DEBUG) + if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): settings.set_setting('Heartbeat', '1') + else: settings.set_setting('Heartbeat', '0') + @debugging def OnMB_GameServerStartServer(self): - self.log.log("Enter orpgFrame->OnMB_GameServerStartServer(self)", ORPG_DEBUG) start_dialog = wx.ProgressDialog( "Server Loading", "Server Loading, Please Wait...", 1, self ) # Spawn the new process and close the stdout handle from it start_dialog.Update( 0 ) # Adjusted following code to work with win32, can't test for Unix # as per reported bug 586227 if wx.Platform == "__WXMSW__": - arg = '\"' + os.path.normpath(orpg.dirpath.dir_struct["home"] + 'start_server_gui.py') + '\"' + arg = '\"' + os.path.normpath(dir_struct["home"] + 'start_server_gui.py') + '\"' args = ( sys.executable, arg ) else: - arg = orpg.dirpath.dir_struct["home"] + 'start_server_gui.py' + arg = dir_struct["home"] + 'start_server_gui.py' args = (arg,arg) os.spawnv( os.P_NOWAIT, sys.executable, args ) start_dialog.Update( 1 ) start_dialog.Show(False) start_dialog.Destroy() - self.log.log("Exit orpgFrame->OnMB_GameServerStartServer(self)", ORPG_DEBUG) # Tools Menu + @debugging def OnMB_PluginControlPanel(self, evt): - self.log.log("Enter orpgFrame->OnMB_ToolsPlugins(self)", ORPG_DEBUG) if self.pluginsFrame.IsShown() == True: self.pluginsFrame.Hide() else: self.pluginsFrame.Show() - self.log.log("Exit orpgFrame->OnMB_ToolsPlugins(self)", ORPG_DEBUG) + @debugging def OnMB_UpdateManagerPanel(self, evt): - self.log.log("Enter orpgFrame->OnMB_ToolsPlugins(self)", ORPG_DEBUG) if self.updateMana.IsShown() == True: self.updateMana.Hide() else: self.updateMana.Show() - self.log.log("Exit orpgFrame->OnMB_ToolsPlugins(self)", ORPG_DEBUG) + @debugging + def OnMB_DebugConsole(self, evt): + if self.debugger.IsShown() == True: self.debugger.Hide() + else: self.debugger.Show() + + @debugging def OnMB_ToolsLoggingLevelDebug(self): - self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelDebug(self)", ORPG_DEBUG) - lvl = self.log.getLogLevel() + lvl = logger.log_level if self.mainmenu.GetMenuState("ToolsLoggingLevelDebug"): lvl |= ORPG_DEBUG else: lvl &= ~ORPG_DEBUG - self.log.setLogLevel(lvl) - self.settings.set_setting('LoggingLevel', lvl) - self.log.log("Exit orpgFrame->OnMB_ToolsLoggingLevelDebug(self)", ORPG_DEBUG) + logger.log_level = lvl + settings.set('LoggingLevel', lvl) + @debugging def OnMB_ToolsLoggingLevelNote(self): - self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelNote(self)", ORPG_DEBUG) - lvl = self.log.getLogLevel() + lvl = logger.log_level if self.mainmenu.GetMenuState("ToolsLoggingLevelNote"): lvl |= ORPG_DEBUG else: lvl &= ~ORPG_DEBUG - self.log.setLogLevel(lvl) - self.settings.set_setting('LoggingLevel', lvl) - self.log.log("Exit orpgFrame->OnMB_ToolsLoggingLevelNote(self)", ORPG_DEBUG) + logger.log_level = lvl + settings.set('LoggingLevel', lvl) + @debugging def OnMB_ToolsLoggingLevelInfo(self): - self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelInfo(self)", ORPG_DEBUG) - lvl = self.log.getLogLevel() + lvl = logger.log_level if self.mainmenu.GetMenuState("ToolsLoggingLevelInfo"): lvl |= ORPG_INFO else: lvl &= ~ORPG_INFO - self.log.setLogLevel(lvl) - self.settings.set_setting('LoggingLevel', lvl) - self.log.log("Exit orpgFrame->OnMB_ToolsLoggingLevelInfo(self)", ORPG_DEBUG) + logger.log_level = lvl + settings.set('LoggingLevel', lvl) + @debugging def OnMB_ToolsLoggingLevelGeneral(self): - self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelGeneral(self)", ORPG_DEBUG) - lvl = self.log.getLogLevel() + lvl = logger.log_level if self.mainmenu.GetMenuState("ToolsLoggingLevelGeneral"): lvl |= ORPG_GENERAL else: lvl &= ~ORPG_GENERAL - self.log.setLogLevel(lvl) - self.settings.set_setting('LoggingLevel', lvl) - self.log.log("Exit orpgFrame->OnMB_ToolsLoggingLevelGeneral(self)", ORPG_DEBUG) + logger.log_level = lvl + settings.set('LoggingLevel', lvl) + @debugging def OnMB_ToolsPasswordManager(self): - self.log.log("Enter orpgFrame->OnMB_ToolsPasswordManager(self)", ORPG_DEBUG) if self.mainmenu.GetMenuState("ToolsPasswordManager"): self.password_manager.Enable() else: self.password_manager.Disable() - self.log.log("Exit orpgFrame->OnMB_ToolsPasswordManager(self)", ORPG_DEBUG) + @debugging def OnMB_ToolsStatusBar(self): - self.log.log("Enter orpgFrame->OnMB_ToolsStatusBar(self)", ORPG_DEBUG) if self._mgr.GetPane("Status Window").IsShown() == True: self.mainmenu.SetMenuState("ToolsStatusBar", False) self._mgr.GetPane("Status Window").Hide() @@ -524,10 +523,9 @@ self.mainmenu.SetMenuState("ToolsStatusBar", True) self._mgr.GetPane("Status Window").Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_ToolsStatusBar(self)", ORPG_DEBUG) + @debugging def OnMB_ToolsSoundToolbar(self): - self.log.log("Enter orpgFrame->OnMB_ToolsSoundToolbar(self)", ORPG_DEBUG) if self._mgr.GetPane("Sound Control Toolbar").IsShown() == True: self.mainmenu.SetMenuState("ToolsSoundToolbar", False) self._mgr.GetPane("Sound Control Toolbar").Hide() @@ -535,10 +533,9 @@ self.mainmenu.SetMenuState("ToolsSoundToolbar", True) self._mgr.GetPane("Sound Control Toolbar").Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_ToolsSoundToolbar(self)", ORPG_DEBUG) + @debugging def OnMB_ToolsDiceBar(self): - self.log.log("Enter orpgFrame->OnMB_ToolsDiceBar(self)", ORPG_DEBUG) if self._mgr.GetPane("Dice Tool Bar").IsShown() == True: self.mainmenu.SetMenuState("ToolsDiceBar", False) self._mgr.GetPane("Dice Tool Bar").Hide() @@ -546,10 +543,9 @@ self.mainmenu.SetMenuState("ToolsDiceBar", True) self._mgr.GetPane("Dice Tool Bar").Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_ToolsDiceBar(self)", ORPG_DEBUG) + @debugging def OnMB_ToolsMapBar(self): - self.log.log("Enter orpgFrame->OnMB_ToolsMapBar(self)", ORPG_DEBUG) if self._mgr.GetPane("Map Tool Bar").IsShown() == True: self.mainmenu.SetMenuState("ToolsMapBar", False) self._mgr.GetPane("Map Tool Bar").Hide() @@ -557,29 +553,27 @@ self.mainmenu.SetMenuState("ToolsMapBar", True) self._mgr.GetPane("Map Tool Bar").Show() self._mgr.Update() - self.log.log("Exit orpgFrame->OnMB_ToolsMapBar(self)", ORPG_DEBUG) #Help Menu #Needs a custom Dialog because it is ugly on Windows + @debugging def OnMB_HelpAbout(self): - description = """OpenRPG is a Virtual Game Table that allows users to connect via a network and play table -top games with friends. 'Traipse' is an OpenRPG distro that is easy to setup and provides superb -functionality. OpenRPG is originally designed by Chris Davis.""" - - license = """OpenRPG 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. + description = "OpenRPG is a Virtual Game Table that allows users to connect via a network and play table\n" + description += "top games with friends. 'Traipse' is an OpenRPG distro that is easy to setup and provides superb \n" + description += "functionality. OpenRPG is originally designed by Chris Davis. \n" -OpenRPG and Traipse 'OpenRPG' 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 Traipse 'OpenRPG'; if not, write to -the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -'Traipse' and the 'Traipse' Logo are trademarks of Mad Mathematics Laboratories.""" + license = "OpenRPG is free software; you can redistribute it and/or modify it " + license += "under the terms of the GNU General Public License as published by the Free Software Foundation; \n" + license += "either version 2 of the License, or (at your option) any later version.\n\n" + license += "OpenRPG and Traipse 'OpenRPG' is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n" + license += "without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \n" + license += "See the GNU General Public License for more details. You should have received a copy of \n" + license += "the GNU General Public License along with Traipse 'OpenRPG'; if not, write to \n" + license += "the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n" + license += "'Traipse' and the 'Traipse' Logo are trademarks of Mad Mathematics Laboratories." info = wx.AboutDialogInfo() - info.SetIcon(wx.Icon(orpg.dirpath.dir_struct["icon"]+'splash.gif', wx.BITMAP_TYPE_GIF)) + info.SetIcon(wx.Icon(dir_struct["icon"]+'splash.gif', wx.BITMAP_TYPE_GIF)) info.SetName('Traipse') info.SetVersion('OpenRPG ' + VERSION) info.SetDescription(description) @@ -595,14 +589,17 @@ info.AddDeveloper(dev) wx.AboutBox(info) + @debugging def OnMB_HelpOnlineUserGuide(self): wb = webbrowser.get() wb.open("https://www.assembla.com/wiki/show/traipse/User_Manual") + @debugging def OnMB_HelpChangeLog(self): wb = webbrowser.get() wb.open("http://www.assembla.com/spaces/milestones/index/traipse_dev?spaces_tool_id=Milestones") + @debugging def OnMB_HelpReportaBug(self): wb = webbrowser.get() wb.open("http://www.assembla.com/spaces/tickets/index/traipse_dev?spaces_tool_id=Tickets") @@ -611,47 +608,68 @@ ################################# ## Build the GUI ################################# + @debugging def build_gui(self): - self.log.log("Enter orpgFrame->build_gui()", ORPG_DEBUG) self.Freeze() self.validate.config_file("layout.xml","default_layout.xml") - filename = orpg.dirpath.dir_struct["user"] + "layout.xml" + + filename = dir_struct["user"] + "layout.xml" temp_file = open(filename) txt = temp_file.read() - xml_dom = self.xml.parseXml(txt)._get_documentElement() + xml_dom = xml.parseXml(txt)._get_documentElement() temp_file.close() + + """ Would a component work better? + etree = ElementTree() + with open(dir_struct['user'] + 'layout.xml') as f: + etree.parse(f) + + base = etree.getroot() + """ self.windowsmenu = wx.Menu() self.mainwindows = {} #Plugins Window self.pluginsFrame = pluginUI.PluginFrame(self) - open_rpg.add_component("plugins", self.get_activeplugins()) - open_rpg.add_component("startplugs", self.get_startplugins()) - self.log.log("Menu Created", ORPG_DEBUG) + component.add("plugins", self.get_activeplugins()) + component.add("startplugs", self.get_startplugins()) + logger.debug("Menu Created") h = int(xml_dom.getAttribute("height")) w = int(xml_dom.getAttribute("width")) posx = int(xml_dom.getAttribute("posx")) posy = int(xml_dom.getAttribute("posy")) maximized = int(xml_dom.getAttribute("maximized")) self.SetDimensions(posx, posy, w, h) - self.log.log("Dimensions Set", ORPG_DEBUG) + logger.debug("Dimensions Set") #Update Manager self.manifest = manifest.ManifestChanges() self.updateMana = upmana.updatemana.updaterFrame(self, - "OpenRPG Update Manager Beta 0.7.2", open_rpg, self.manifest, True) - self.log.log("Menu Created", ORPG_DEBUG) + "OpenRPG Update Manager Beta 0.8", component, self.manifest, True) + logger.debug("Menu Created") h = int(xml_dom.getAttribute("height")) w = int(xml_dom.getAttribute("width")) posx = int(xml_dom.getAttribute("posx")) posy = int(xml_dom.getAttribute("posy")) maximized = int(xml_dom.getAttribute("maximized")) self.SetDimensions(posx, posy, w, h) - self.log.log("Dimensions Set", ORPG_DEBUG) + logger.debug("Dimensions Set") + + #Update Manager + self.manifest = manifest.ManifestChanges() + self.debugger = orpg.tools.orpg_log.DebugConsole(self) + logger.debug("Menu Created") + h = int(xml_dom.getAttribute("height")) + w = int(xml_dom.getAttribute("width")) + posx = int(xml_dom.getAttribute("posx")) + posy = int(xml_dom.getAttribute("posy")) + maximized = int(xml_dom.getAttribute("maximized")) + self.SetDimensions(posx, posy, w, h) + logger.debug("Dimensions Set") # Sound Manager self.sound_player = orpg.tools.orpg_sound.orpgSound(self) - open_rpg.add_component("sound", self.sound_player) + component.add("sound", self.sound_player) wndinfo = AUI.AuiPaneInfo() menuid = wx.NewId() self.mainwindows[menuid] = "Sound Control Toolbar" @@ -677,7 +695,7 @@ wndinfo.ToolbarPane() wndinfo.Hide() self._mgr.AddPane(self.status, wndinfo) - self.log.log("Status Window Created", ORPG_DEBUG) + logger.debug("Status Window Created") # Create and show the floating dice toolbar self.dieToolBar = orpg.tools.toolBars.DiceToolBar(self, callBack = self.chat.ParsePost) @@ -691,7 +709,7 @@ wndinfo.ToolbarPane() wndinfo.Hide() self._mgr.AddPane(self.dieToolBar, wndinfo) - self.log.log("Dice Tool Bar Created", ORPG_DEBUG) + logger.debug("Dice Tool Bar Created") #Create the Map tool bar self.mapToolBar = orpg.tools.toolBars.MapToolBar(self, callBack = self.map.MapBar) @@ -705,9 +723,9 @@ wndinfo.ToolbarPane() wndinfo.Hide() self._mgr.AddPane(self.mapToolBar, wndinfo) - self.log.log("Map Tool Bar Created", ORPG_DEBUG) + logger.debug("Map Tool Bar Created") - #Create the Browse Server Window + #Create the Browse Server Window #Turn into frame, as with others. self.gs = orpg.networking.gsclient.game_server_panel(self) wndinfo = AUI.AuiPaneInfo() wndinfo.DestroyOnClose(False) @@ -718,57 +736,62 @@ wndinfo.MinSize(wx.Size(640,480)) wndinfo.Hide() self._mgr.AddPane(self.gs, wndinfo) - self.log.log("Game Server Window Created", ORPG_DEBUG) + logger.debug("Game Server Window Created") #Create the Alias Lib Window self.aliaslib = orpg.tools.aliaslib.AliasLib() self.aliaslib.Hide() - self.log.log("Alias Window Created", ORPG_DEBUG) + logger.debug("Alias Window Created") menuid = wx.NewId() self.windowsmenu.Append(menuid, "Alias Lib", kind=wx.ITEM_CHECK) self.windowsmenu.Check(menuid, False) self.Bind(wx.EVT_MENU, self.OnMB_WindowsMenu, id=menuid) self.mainwindows[menuid] = "Alias Lib" self.mainmenu.Insert(3, self.windowsmenu, 'Windows') - self.log.log("Windows Menu Done", ORPG_DEBUG) + logger.debug("Windows Menu Done") self._mgr.Update() if wx.VERSION_STRING > "2.8": self.Bind(AUI.EVT_AUI_PANE_CLOSE, self.onPaneClose) else: self.Bind(AUI.EVT_AUI_PANECLOSE, self.onPaneClose) - self.log.log("AUI Bindings Done", ORPG_DEBUG) + logger.debug("AUI Bindings Done") #Load the layout if one exists layout = xml_dom.getElementsByTagName("DockLayout") try: - textnode = self.xml.safe_get_text_node(layout[0]) + textnode = xml.safe_get_text_node(layout[0]) self._mgr.LoadPerspective(textnode._get_nodeValue()) except: pass xml_dom.unlink() - self.log.log("Perspective Loaded", ORPG_DEBUG) + logger.debug("Perspective Loaded") self._mgr.GetPane("Browse Server Window").Hide() self._mgr.Update() self.Maximize(maximized) - self.log.log("GUI is all created", ORPG_DEBUG) + logger.debug("GUI is all created") self.Thaw() - self.log.log("Exit orpgFrame->build_gui()", ORPG_DEBUG) + @debugging def do_tab_window(self,xml_dom,parent_wnd): - self.log.log("Enter orpgFrame->do_tab_window(self,xml_dom,parent_wnd)", ORPG_DEBUG) - + #def do_tab_window(self, etreeEl, parent_wnd): # if container window loop through childern and do a recursive call temp_wnd = orpgTabberWnd(parent_wnd, style=FNB.FNB_ALLOW_FOREIGN_DND) + children = xml_dom._get_childNodes() for c in children: wnd = self.build_window(c,temp_wnd) name = c.getAttribute("name") temp_wnd.AddPage(wnd, name, False) - self.log.log("Exit orpgFrame->do_tab_window(self,xml_dom,parent_wnd)", ORPG_DEBUG) + + """ + for c in etreeEl.getchildren(): + wnd = self.build_window(c, temp_wnd) + temp_wnd.AddPage(wnd, c.get('name'), False) + """ return temp_wnd + @debugging def build_window(self, xml_dom, parent_wnd): name = xml_dom._get_nodeName() - self.log.log("Enter orpgFrame->build_window(" + name + ")", ORPG_DEBUG) if name == "DockLayout" or name == "dock": return - dir = xml_dom.getAttribute("direction") + dirc = xml_dom.getAttribute("direction") #should NOT use dir, it is a built in function. pos = xml_dom.getAttribute("pos") height = xml_dom.getAttribute("height") width = xml_dom.getAttribute("width") @@ -786,9 +809,9 @@ elif name == "tree": temp_wnd = orpg.gametree.gametree.game_tree(parent_wnd, -1) self.tree = temp_wnd - if self.settings.get_setting('ColorTree') == '1': - self.tree.SetBackgroundColour(self.settings.get_setting('bgcolor')) - self.tree.SetForegroundColour(self.settings.get_setting('textcolor')) + if settings.get_setting('ColorTree') == '1': + self.tree.SetBackgroundColour(settings.get_setting('bgcolor')) + self.tree.SetForegroundColour(settings.get_setting('textcolor')) else: self.tree.SetBackgroundColour('white') self.tree.SetForegroundColour('black') @@ -801,9 +824,9 @@ elif name == "player": temp_wnd = orpg.player_list.player_list(parent_wnd) self.players = temp_wnd - if self.settings.get_setting('ColorTree') == '1': - self.players.SetBackgroundColour(self.settings.get_setting('bgcolor')) - self.players.SetForegroundColour(self.settings.get_setting('textcolor')) + if settings.get_setting('ColorTree') == '1': + self.players.SetBackgroundColour(settings.get_setting('bgcolor')) + self.players.SetForegroundColour(settings.get_setting('textcolor')) else: self.players.SetBackgroundColour('white') self.players.SetForegroundColour('black') @@ -823,11 +846,11 @@ wndinfo.Caption(cap) # Lambda here should work! (future dev) - if dir.lower() == 'top': wndinfo.Top() - elif dir.lower() == 'bottom': wndinfo.Bottom() - elif dir.lower() == 'left': wndinfo.Left() - elif dir.lower() == 'right': wndinfo.Right() - elif dir.lower() == 'center': wndinfo.Center(); wndinfo.CaptionVisible(False) + if dirc.lower() == 'top': wndinfo.Top() + elif dirc.lower() == 'bottom': wndinfo.Bottom() + elif dirc.lower() == 'left': wndinfo.Left() + elif dirc.lower() == 'right': wndinfo.Right() + elif dirc.lower() == 'center': wndinfo.Center(); wndinfo.CaptionVisible(False) if dockable != 1: wndinfo.Dockable(False) @@ -836,11 +859,10 @@ wndinfo.Position(int(pos)) wndinfo.Show() self._mgr.AddPane(temp_wnd, wndinfo) - self.log.log("Exit orpgFrame->build_window(" + name + ")", ORPG_DEBUG) return temp_wnd + @debugging def onPaneClose(self, evt): - self.log.log("Enter orpgFrame->onPaneClose()", ORPG_DEBUG) pane = evt.GetPane() #Arbitrary If ELIF fix. Items had incorrect ID's set. Finding correct ID will fix it for the iteration. #Adding ID also fixed docking. Go figure. @@ -854,14 +876,13 @@ if pane.name == wname: self.windowsmenu.Check(wndid, False); break evt.Skip() self._mgr.Update() - self.log.log("Exit orpgFrame->onPaneClose()", ORPG_DEBUG) + @debugging def saveLayout(self): - self.log.log("Enter orpgFrame->saveLayout()", ORPG_DEBUG) - filename = orpg.dirpath.dir_struct["user"] + "layout.xml" + filename = dir_struct["user"] + "layout.xml" temp_file = open(filename) txt = temp_file.read() - xml_dom = self.xml.parseXml(txt)._get_documentElement() + xml_dom = xml.parseXml(txt)._get_documentElement() temp_file.close() (x_size,y_size) = self.GetClientSize() (x_pos,y_pos) = self.GetPositionTuple() @@ -874,58 +895,52 @@ xml_dom.setAttribute("maximized", str(max)) layout = xml_dom.getElementsByTagName("DockLayout") try: - textnode = self.xml.safe_get_text_node(layout[0]) + textnode = xml.safe_get_text_node(layout[0]) textnode._set_nodeValue(str(self._mgr.SavePerspective())) except: - elem = self.xml.minidom.Element('DockLayout') + elem = minidom.Element('DockLayout') elem.setAttribute("DO_NO_EDIT","True") - textnode = self.xml.safe_get_text_node(elem) + textnode = xml.safe_get_text_node(elem) textnode._set_nodeValue(str(self._mgr.SavePerspective())) xml_dom.appendChild(elem) temp_file = open(filename, "w") temp_file.write(xml_dom.toxml(1)) temp_file.close() - self.log.log("Exit saveLayout()", ORPG_DEBUG) + @debugging def build_hotkeys(self): - self.log.log("Enter orpgFrame->build_hotkeys(self)", ORPG_DEBUG) self.mainmenu.accel.xaccel.extend(self.chat.get_hot_keys()) self.mainmenu.accel.xaccel.extend(self.map.get_hot_keys()) - self.log.log("Exit orpgFrame->build_hotkeys(self)", ORPG_DEBUG) + @debugging def start_timer(self): - self.log.log("Enter orpgFrame->start_timer(self)", ORPG_DEBUG) self.poll_timer.Start(100) - s = open_rpg.get_component('settings') + s = component.get('settings') if s.get_setting("Heartbeat") == "1": self.ping_timer.Start(1000*60) - self.log.log("starting heartbeat...", ORPG_DEBUG, True) - self.log.log("Exit orpgFrame->start_timer(self)", ORPG_DEBUG) + logger.debug("starting heartbeat...", True) + @debugging def kill_mplay_session(self): - self.log.log("Enter orpgFrame->kill_mplay_session(self)", ORPG_DEBUG) self.game_name = "" self.session.start_disconnect() - self.log.log("Exit orpgFrame->kill_mplay_session(self)", ORPG_DEBUG) + @debugging def quit_game(self, evt): - self.log.log("Enter orpgFrame->quit_game(self, evt)", ORPG_DEBUG) dlg = wx.MessageDialog(self,"Exit gaming session?","Game Session",wx.YES_NO) if dlg.ShowModal() == wx.ID_YES: self.session.exitCondition.notifyAll() dlg.Destroy() self.kill_mplay_session() - self.log.log("Exit orpgFrame->quit_game(self, evt)", ORPG_DEBUG) + @debugging def on_status_event(self, evt): - self.log.log("Enter orpgFrame->on_status_event(self, evt)", ORPG_DEBUG) id = evt.get_id() status = evt.get_data() if id == orpg.networking.mplay_client.STATUS_SET_URL: self.status.set_url(status) - self.log.log("Exit orpgFrame->on_status_event(self, evt)", ORPG_DEBUG) + @debugging def on_player_event(self, evt): - self.log.log("Enter orpgFrame->on_player_event(self, evt)", ORPG_DEBUG) id = evt.get_id() player = evt.get_data() display_name = self.chat.chat_display_name(player) @@ -939,37 +954,32 @@ elif id == orpg.networking.mplay_client.PLAYER_UPDATE: self.players.update_player(player) self.players.Refresh() - self.log.log("Exit orpgFrame->on_player_event(self, evt)", ORPG_DEBUG) + @debugging def on_group_event(self, evt): - self.log.log("Enter orpgFrame->on_group_event(self, evt)", ORPG_DEBUG) id = evt.get_id() data = evt.get_data() - if id == orpg.networking.mplay_client.GROUP_NEW: self.gs.add_room(data) elif id == orpg.networking.mplay_client.GROUP_DEL: self.password_manager.RemoveGroupData(data) self.gs.del_room(data) elif id == orpg.networking.mplay_client.GROUP_UPDATE: self.gs.update_room(data) - self.log.log("Exit orpgFrame->on_group_event(self, evt)", ORPG_DEBUG) + @debugging def on_receive(self, data, player): - self.log.log("Enter orpgFrame->on_receive(self, data, player)", ORPG_DEBUG) - # see if we are ignoring this user (ignore_id,ignore_name) = self.session.get_ignore_list() for m in ignore_id: - if m == player[2]: self.log.log("ignoring message from player:" + player[0], ORPG_INFO, True); return + if m == player[2]: logger.debug("ignoring message from player:" + player[0], True); return # ok we are not ignoring this message - #recvSound = "RecvSound" # this will be the default sound. Whisper will change this below + #recvSound = "RecvSound" # this will be the default sound. Whisper will change this below if player: display_name = self.chat.chat_display_name(player) else: display_name = "Server Administrator" if data[:5] == "<tree": self.tree.on_receive_data(data,player) self.chat.InfoPost(display_name + " has sent you a tree node...") - #self.tree.OnNewData(data) elif data[:4] == "<map": self.map.new_data(data) @@ -977,28 +987,42 @@ msg = orpg.chat.chat_msg.chat_msg(data) self.chat.post_incoming_msg(msg,player) else: - ############################################################################################## - # all this below code is for comptiablity with older clients and can be removed after a bit # - ############################################################################################## + """ + all this below code is for comptiablity with older clients and can + be removed after a bit + """ + import warnings + warnings.warn("Getting here is bad, find out how and fix it", + DeprecationWarning, 2) if data[:3] == "/me": - # This fixes the emote coloring to comply with what has been asked for by the user - # population, not to mention, what I committed to many moons ago. - # In doing so, Woody's scheme has been tossed out. I'm sure Woody won't be - # happy but I'm invoking developer priveledge to satisfy user request, not to mention, - # this scheme actually makes more sense. In Woody's scheme, a user could over-ride another - # users emote color. This doesn't make sense, rather, people dictate their OWN colors...which is as - # it should be in the first place and is as it has been with normal text. In short, this makes - # sense and is consistent. + """ + This fixes the emote coloring to comply with what has been + asked for by the user population, not to mention, what I + committed to many moons ago. In doing so, Woody's scheme has + been tossed out. I'm sure Woody won't be happy but I'm + invoking developer priveledge to satisfy user request, not to + mention, this scheme actually makes more sense. In Woody's + scheme, a user could over-ride another users emote color. This + doesn't make sense, rather, people dictate their OWN colors... + which is as it should be in the first place and is as it has + been with normal text. In short, this makes sense and is + consistent. + """ data = data.replace( "/me", "" ) - - # Check to see if we find the closing ">" for the font within the first 22 values + """ + Check to see if we find the closing '>' for the font within the + first 22 values + """ index = data[:22].find( ">" ) if index == -1: data = "** " + self.chat.colorize( self.chat.infocolor, display_name + data ) + " **" else: - # This means that we found a valid font string, so we can simply plug the name into - # the string between the start and stop font delimiter + """ + This means that we found a valid font string, so we can + simply plug the name into the string between the start and + stop font delimiter + """ print "pre data = " + data data = data[:22] + "** " + display_name + " " + data[22:] + " **" print "post data = " + data @@ -1012,11 +1036,9 @@ if player: data = "<b>" + display_name + "</b>: " + data else: data = "<b><i><u>" + display_name + "</u>-></i></b> " + data self.chat.Post(data) - self.log.log("Exit orpgFrame->on_receive(self, data, player)", ORPG_DEBUG) + @debugging def on_mplay_event(self, evt): - self.log.log("Enter orpgFrame->on_mplay_event(self, evt)", ORPG_DEBUG) - id = evt.get_id() if id == orpg.networking.mplay_client.MPLAY_CONNECTED: self.chat.InfoPost("Game connected!") @@ -1033,7 +1055,7 @@ ####Begin changes for Custom Exit Message by mDuo13###### elif id == orpg.networking.mplay_client.MPLAY_DISCONNECTING: - settings = open_rpg.get_component('settings') + settings = component.get('settings') custom_msg = settings.get_setting("dcmsg") custom_msg=custom_msg[:80] if custom_msg[:3]=="/me": self.chat.send_chat_message(custom_msg[3:], 3) @@ -1047,19 +1069,17 @@ self.players.reset() elif id== orpg.networking.mplay_client.MPLAY_GROUP_CHANGE_F: self.chat.SystemPost("Room access denied!") - self.log.log("Exit orpgFrame->on_mplay_event(self, evt)", ORPG_DEBUG) + @debugging def OnCloseWindow(self, event): - self.log.log("Enter orpgFrame->OnCloseWindow(self, event)", ORPG_DEBUG) dlg = wx.MessageDialog(self, "Quit OpenRPG?", "OpenRPG", wx.YES_NO) if dlg.ShowModal() == wx.ID_YES: dlg.Destroy() self.closed_confirmed() - self.log.log("Exit orpgFrame->OnCloseWindow(self, event)", ORPG_DEBUG) + @debugging def closed_confirmed(self): - self.log.log("Enter orpgFrame->closed_confirmed(self)", ORPG_DEBUG) - self.activeplugins = open_rpg.get_component('plugins') + self.activeplugins = component.get('plugins') self.aliaslib.OnMB_FileSave(None) #following lines added by mDuo13 @@ -1068,22 +1088,23 @@ plugin = self.activeplugins[plugin_fname] try: plugin.plugin_disabled() except Exception, e: - if str(e) != "'module' object has no attribute 'plugin_disabled'": - #print e traceback.print_exc() #end mDuo13 added code self.saveLayout() - try: self.settings.save() - except: self.log.log("[WARNING] Error saving 'settings' component", ORPG_GENERAL, True) + try: settings.save() + except Exception: + logger.general("[WARNING] Error saving 'settings' component", True) try: self.map.pre_exit_cleanup() - except: self.log.log("[WARNING] Map error pre_exit_cleanup()", ORPG_GENERAL, True) + except Exception: + logger.general("[WARNING] Map error pre_exit_cleanup()", True) try: - save_tree = string.upper(self.settings.get_setting("SaveGameTreeOnExit")) + save_tree = string.upper(settings.get_setting("SaveGameTreeOnExit")) if (save_tree != "0") and (save_tree != "False") and (save_tree != "NO"): - self.tree.save_tree(self.settings.get_setting("gametree")) - except: self.log.log("[WARNING] Error saving gametree", ORPG_GENERAL, True) + self.tree.save_tree(settings.get_setting("gametree")) + except Exception: + logger.general("[WARNING] Error saving gametree", True) if self.session.get_status() == orpg.networking.mplay_client.MPLAY_CONNECTED: self.kill_mplay_session() @@ -1091,7 +1112,8 @@ #Kill all the damn timers self.sound_player.timer.Stop() del self.sound_player.timer - except: self.log.log("sound didn't die properly.",ORPG_GENERAL, True) + except Exception: + logger.general("sound didn't die properly.", True) try: self.poll_timer.Stop() @@ -1102,7 +1124,9 @@ self.status.timer.Stop() del self.ping_timer; del self.poll_timer; del self.chat.parent.chat_timer del self.map.canvas.zoom_display_timer; del self.map.canvas.image_timer; del self.status.timer - except: self.log.log("some timer didn't die properly.",ORPG_GENERAL, True) + except Exception: + logger.general("some timer didn't die properly.", True) + self._mgr.UnInit() mainapp = wx.GetApp() mainapp.ExitMainLoop() @@ -1114,22 +1138,23 @@ dlg.Update(2) dlg.Show(True) self.server_pipe.write("\nkill\n") - self.log.log("Killing Server process:", ORPG_GENERAL, True) + logger.general("Killing Server process:", True) time.sleep(5) self.server_stop() self.server_pipe.close() self.std_out.close() self.server_thread.exit() dlg.Destroy() - self.log.log("Server killed:", ORPG_GENERAL, True) - except: pass - self.log.log("Exit orpgFrame->closed_confirmed(self)", ORPG_DEBUG) + logger.general("Server killed:", True) + except Exception: + pass ######################################## ## Application class ######################################## class orpgSplashScreen(wx.SplashScreen): + @debugging def __init__(self, parent, bitmapfile, duration, callback): wx.SplashScreen.__init__(self, wx.Bitmap(bitmapfile), wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, duration, None, -1) @@ -1138,35 +1163,35 @@ self.Bind(wx.EVT_CLOSE, self.callback) class orpgApp(wx.App): + @debugging def OnInit(self): - self.log = orpg.tools.orpg_log.orpgLog(orpg.dirpath.dir_struct["user"] + "runlogs/") - self.log.setLogToConsol(False) - self.log.log("Main Application Start", ORPG_DEBUG) + + component.add('log', logger) + component.add('xml', xml) + component.add('settings', settings) + component.add('validate', validate) + component.add("tabbedWindows", []) + + logger._set_log_level = int(settings.get_setting('LoggingLevel')) + logger._set_log_to_console(False) + self.manifest = manifest.ManifestChanges() - #Add the initial global components of the openrpg class - #Every class should be passed openrpg - open_rpg.add_component("log", self.log) - open_rpg.add_component("xml", orpg.orpg_xml) - open_rpg.add_component("dir_struct", orpg.dirpath.dir_struct) - open_rpg.add_component("tabbedWindows", []) - self.validate = orpg.tools.validate.Validate() - open_rpg.add_component("validate", self.validate) - self.settings = orpg.tools.orpg_settings.orpgSettings() - open_rpg.add_component("settings", self.settings) - self.log.setLogLevel(int(self.settings.get_setting('LoggingLevel'))) + self.called = False wx.InitAllImageHandlers() - self.splash = orpgSplashScreen(None, orpg.dirpath.dir_struct["icon"] + 'splash13.jpg', 3000, self.AfterSplash) + self.splash = orpgSplashScreen(None, dir_struct["icon"] + 'splash13.jpg', 3000, self.AfterSplash) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyPress) self._crust = None wx.Yield() return True + @debugging def OnKeyPress(self, evt): #Event handler if evt.AltDown() and evt.CmdDown() and evt.KeyCode == ord('I'): self.ShowShell() else: evt.Skip() + @debugging def ShowShell(self): #Show the PyCrust window. if not self._crust: @@ -1176,6 +1201,7 @@ self._crust.shell.interp.locals['win'] = win self._crust.Show() + @debugging def AfterSplash(self,evt): if not self.called: self.splash.Hide() @@ -1190,8 +1216,9 @@ wx.CallAfter(self.splash.Close) return True + @debugging def OnExit_CleanUp(self): - self.log.log("Preforming cleanup\n", ORPG_DEBUG) + logger.debug("Preforming cleanup\n") try: del os.environ["OPENRPG_BASE"] except: pass try: os.remove(os.environ["OPENRPG_BASE"] + os.sep + 'orpg' + os.sep + 'dirpath' + os.sep + 'approot.py') @@ -1199,7 +1226,8 @@ try: os.remove(os.environ["OPENRPG_BASE"] + os.sep + 'orpg' + os.sep + 'dirpath' + os.sep + 'approot.pyc') except: pass + @debugging def OnExit(self): self.OnExit_CleanUp() #Exit - self.log.log("Main Application Exit\n\n", ORPG_DEBUG) + logger.debug("Main Application Exit\n\n")
--- a/orpg/mapper/background.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/background.py Thu Aug 27 01:04:43 2009 -0500 @@ -34,6 +34,11 @@ import os.path import time +from orpg.orpgCore import component +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging +from orpg.tools.orpg_settings import settings + ##----------------------------- ## background layer ##----------------------------- @@ -44,27 +49,24 @@ BG_COLOR = 3 class layer_back_ground(layer_base): + @debugging def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter layer_back_ground", ORPG_DEBUG) - self.settings = self.canvas.settings + self.log = component.get('log') layer_base.__init__(self) self.canvas = canvas self.r_h = RGBHex() self.clear() - self.log.log("Exit layer_back_ground", ORPG_DEBUG) + @debugging def error_loading_image(self, image): - self.log.log("Enter layer_back_ground->error_loading_image(self, image)", ORPG_DEBUG) msg = "Unable to load image:" + `image` dlg = wx.MessageDialog(self.canvas,msg,'File not Found',wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() - self.log.log("Exit layer_back_ground->error_loading_image(self, image)", ORPG_DEBUG) + @debugging def clear(self): - self.log.log("Enter layer_back_ground->clear(self)", ORPG_DEBUG) self.type = BG_NONE self.bg_bmp = None self.bg_color = None @@ -73,75 +75,62 @@ self.localPath = '' self.localTime = -1 self.isUpdated = True - self.log.log("Exit layer_back_ground->clear(self)", ORPG_DEBUG) + @debugging def get_type(self): - self.log.log("Enter layer_back_ground->get_type(self)", ORPG_DEBUG) - self.log.log("Exit layer_back_ground->get_type(self)", ORPG_DEBUG) return self.type + @debugging def get_img_path(self): - self.log.log("Enter layer_back_ground->get_type(self)", ORPG_DEBUG) - if self.img_path: - self.log.log("Exit layer_back_ground->get_type(self) return " + self.img_path, ORPG_DEBUG) - return self.img_path - else: - self.log.log("Exit layer_back_ground->get_type(self) return None", ORPG_DEBUG) - return "" + if self.img_path: return self.img_path + else: return "" + @debugging def get_color(self): - self.log.log("Enter layer_back_ground->get_color(self)", ORPG_DEBUG) hexcolor = "#FFFFFF" if self.bg_color: (red,green,blue) = self.bg_color.Get() hexcolor = self.r_h.hexstring(red, green, blue) - self.log.log("Exit layer_back_ground->get_color(self)", ORPG_DEBUG) return hexcolor + @debugging def set_texture(self, path): - self.log.log("Enter layer_back_ground->set_texture(self, path)", ORPG_DEBUG) self.isUpdated = True - self.type = BG_TEXTURE if self.img_path != path: try: self.bg_bmp = ImageHandler.load(path, "texture", 0) if self.bg_bmp == None: - self.log.log("Invalid image type!", ORPG_GENERAL) + logger.general("Invalid image type!") raise Exception, "Invalid image type!" except: self.error_loading_image(path) self.img_path = path - self.log.log("Enter layer_back_ground->set_texture(self, path)", ORPG_DEBUG) + @debugging def set_image(self, path, scale): - self.log.log("Enter layer_back_ground->set_image(self, path, scale)", ORPG_DEBUG) self.isUpdated = True - self.type = BG_IMAGE if self.img_path != path: self.bg_bmp = ImageHandler.load(path, "background", 0) try: if self.bg_bmp == None: - self.log.log("Invalid image type!", ORPG_GENERAL) + logger.general("Invalid image type!") raise Exception, "Invalid image type!" except: self.error_loading_image(path) self.img_path = path - self.log.log("Exit layer_back_ground->set_image(self, path, scale)", ORPG_DEBUG) return (self.bg_bmp.GetWidth(),self.bg_bmp.GetHeight()) + @debugging def set_color(self, color): - self.log.log("Enter layer_back_ground->set_color(self, color)", ORPG_DEBUG) self.isUpdated = True self.type = BG_COLOR (r,g,b) = color.Get() self.bg_color = cmpColour(r,g,b) self.canvas.SetBackgroundColour(self.bg_color) - self.log.log("Exit layer_back_ground->set_color(self, color)", ORPG_DEBUG) + @debugging def layerDraw(self, dc, scale, topleft, size): - self.log.log("Enter layer_back_ground->layerDraw(self, dc, scale, topleft, size)", ORPG_DEBUG) if self.bg_bmp == None or not self.bg_bmp.Ok() or ((self.type != BG_TEXTURE) and (self.type != BG_IMAGE)): - self.log.log("Exit layer_back_ground->layerDraw(self, dc, scale, topleft, size) return False", ORPG_DEBUG) return False dc2 = wx.MemoryDC() dc2.SelectObject(self.bg_bmp) @@ -212,11 +201,10 @@ dc.Blit(posx, posy, newW, newH, dc2, cl, ct) dc2.SelectObject(wx.NullBitmap) del dc2 - self.log.log("Exit layer_back_ground->layerDraw(self, dc, scale, topleft, size)", ORPG_DEBUG) return True + @debugging def layerToXML(self, action="update"): - self.log.log("Enter layer_back_ground->layerToXML(self, " + action + ")", ORPG_DEBUG) xml_str = "<bg" if self.bg_color != None: (red,green,blue) = self.bg_color.Get() @@ -229,21 +217,19 @@ xml_str += ' localPath="' + urllib.quote(self.localPath).replace('%3A', ':') + '"' xml_str += ' localTime="' + str(self.localTime) + '"' xml_str += "/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit layer_back_ground->layerToXML(self, " + action + ")", ORPG_DEBUG) + logger.debug(xml_str) if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str else: return '' + @debugging def layerTakeDOM(self, xml_dom): - self.log.log("Enter layer_back_ground->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) type = BG_COLOR color = xml_dom.getAttribute("color") - self.log.log("color=" + color, ORPG_DEBUG) + logger.debug("color=" + color) path = urllib.unquote(xml_dom.getAttribute("path")) - self.log.log("path=" + path, ORPG_DEBUG) - + logger.debug("path=" + path) # Begin ted's map changes if xml_dom.hasAttribute("color"): r,g,b = self.r_h.rgb_tuple(xml_dom.getAttribute("color")) @@ -251,16 +237,12 @@ # End ted's map changes if xml_dom.hasAttribute("type"): type = int(xml_dom.getAttribute("type")) - self.log.log("type=" + str(type), ORPG_DEBUG) - + logger.debug("type=" + str(type)) if type == BG_TEXTURE: if path != "": self.set_texture(path) - elif type == BG_IMAGE: if path != "": self.set_image(path, 1) - elif type == BG_NONE: self.clear() - if xml_dom.hasAttribute('local') and xml_dom.getAttribute('local') == 'True' and os.path.exists(urllib.unquote(xml_dom.getAttribute('localPath'))): self.localPath = urllib.unquote(xml_dom.getAttribute('localPath')) self.local = True @@ -273,12 +255,12 @@ (imgtype,j) = mimetypes.guess_type(filename[1]) postdata = urllib.urlencode({'filename':filename[1], 'imgdata':imgdata, 'imgtype':imgtype}) thread.start_new_thread(self.upload, (postdata, self.localPath, type)) - self.log.log("Exit layer_back_ground->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) + @debugging def upload(self, postdata, filename, type): self.lock.acquire() if type == 'Image' or type == 'Texture': - url = self.settings.get_setting('ImageServerBaseURL') + url = component.get('settings').get_setting('ImageServerBaseURL') file = urllib.urlopen(url, postdata) recvdata = file.read() file.close()
--- a/orpg/mapper/background_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/background_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -35,10 +35,12 @@ import os from base import * +from orpg.tools.orpg_settings import settings + class background_handler(base_layer_handler): def __init__(self, parent, id, canvas): base_layer_handler.__init__(self, parent, id, canvas) - self.settings = self.canvas.settings + self.settings = settings def build_ctrls(self): base_layer_handler.build_ctrls(self) @@ -86,10 +88,10 @@ thread.start_new_thread(self.canvas.layers['bg'].upload, (postdata, dlg.GetPath(), self.bg_type.GetStringSelection())) else: - try: min_url = open_rpg.get_component("cherrypy") + filename + try: min_url = component.get("cherrypy") + filename except: return min_url = dlg.GetDirectory().replace(orpg.dirpath.dir_struct["user"]+'webfiles' + os.sep, - open_rpg.get_component("cherrypy")) + '/' + filename + component.get("cherrypy")) + '/' + filename if self.bg_type.GetStringSelection() == 'Texture': self.canvas.layers['bg'].set_texture(min_url) elif self.bg_type.GetStringSelection() == 'Image': self.size = self.canvas.layers['bg'].set_image(min_url,1) @@ -138,7 +140,7 @@ def on_apply(self, evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return self.canvas.layers['bg'].set_color(self.color_button.GetBackgroundColour())
--- a/orpg/mapper/base.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/base.py Thu Aug 27 01:04:43 2009 -0500 @@ -30,7 +30,6 @@ from images import ImageHandler from orpg.tools.rgbhex import * from orpg.orpg_windows import * -from orpg.orpg_xml import * from math import * from threading import Lock import time
--- a/orpg/mapper/base_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/base_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -30,7 +30,7 @@ from orpg.orpg_windows import * -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component class base_layer_handler(wx.Panel): @@ -39,7 +39,7 @@ self.canvas = canvas self.map_frame = self.canvas.frame self.top_frame = self.canvas.frame.top_frame - self.chat = open_rpg.get_component("chat") + self.chat = component.get("chat") self.build_ctrls() self.build_menu() #self.Bind(wx.EVT_SIZE, self.on_size) @@ -51,15 +51,15 @@ self.buttonsizer = wx.BoxSizer(wx.HORIZONTAL) self.zoom_in_button = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'zoom_in.gif', "Zoom in from x1.0", wx.ID_ANY ) + dir_struct["icon"]+'zoom_in.gif', "Zoom in from x1.0", wx.ID_ANY ) self.zoom_out_button = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'zoom_out.gif', "Zoom out from x1.0", wx.ID_ANY ) + dir_struct["icon"]+'zoom_out.gif', "Zoom out from x1.0", wx.ID_ANY ) props = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'compass.gif', 'Edit map properties', wx.ID_ANY ) + dir_struct["icon"]+'compass.gif', 'Edit map properties', wx.ID_ANY ) mapopen = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'open.bmp', 'Load a map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) + dir_struct["icon"]+'open.bmp', 'Load a map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) mapsave = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'save.bmp', 'Save the map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) + dir_struct["icon"]+'save.bmp', 'Save the map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) self.buttonsizer.Add(self.zoom_in_button, 0, wx.ALIGN_CENTER ) self.buttonsizer.Add(self.zoom_out_button, 0, wx.ALIGN_CENTER ) self.buttonsizer.Add(props, 0, wx.ALIGN_CENTER ) @@ -98,7 +98,7 @@ self.main_menu = main_menu def on_save_map_jpg(self, evt): - directory = orpg.dirpath.dir_struct["user"] + directory = dir_struct["user"] if directory == None: directory = "" d = wx.FileDialog(self.GetParent(), "Save map as a jpg", directory, "", "*.jpg", wx.SAVE)
--- a/orpg/mapper/fog.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/fog.py Thu Aug 27 01:04:43 2009 -0500 @@ -33,33 +33,25 @@ class FogArea: def __init__(self, outline, log): - self.log = log - self.log.log("Enter FogArea", ORPG_DEBUG) self.outline = outline - self.log.log("Exit FogArea", ORPG_DEBUG) def set_fog_props(self, str): - self.log.log("Enter FogArea->set_fog_props(self, str)", ORPG_DEBUG) self.outline = str - self.log.log("Exit FogArea->set_fog_props(self, str)", ORPG_DEBUG) def points_to_elements(self, points=None): - self.log.log("Enter FogArea->points_to_elements(self, points)", ORPG_DEBUG) result = [] if points == None: - self.log.log("Exit FogArea->points_to_elements(self, points)", ORPG_DEBUG) return result + for pairs in string.split( points, ';' ): pair = string.split( pairs, ',' ) p = Element( "point" ) p.setAttribute( "x", pair[0] ) p.setAttribute( "y", pair[1] ) result.append( p ) - self.log.log("Exit FogArea->points_to_elements(self, points)", ORPG_DEBUG) return result def toxml(self, action="update"): - self.log.log("Enter FogArea->toxml(self, " + action + ")", ORPG_DEBUG) xml_str = "" localOutline = self.outline if localOutline != None and localOutline != "all" and localOutline != "none": @@ -73,8 +65,6 @@ for p in list: elem.appendChild( p ) str = elem.toxml() elem.unlink() - self.log.log(str, ORPG_DEBUG) - self.log.log("Exit FogArea->toxml(self, " + action + ")", ORPG_DEBUG) return str elem.setAttribute( "action", action ) if localOutline != None: @@ -84,15 +74,11 @@ for p in list: elem.appendChild( p ) xml_str = elem.toxml() elem.unlink() - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit FogArea->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str class fog_layer(layer_base): def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter fog_layer", ORPG_DEBUG) layer_base.__init__(self) self.color = wx.Color(128,128,128) if "__WXGTK__" not in wx.PlatformInfo: self.color = wx.Color(128,128,128, 128) @@ -103,51 +89,38 @@ self.height = 0 self.use_fog = False self.last_role = "" - self.log.log("Exit fog_layer", ORPG_DEBUG) def clear(self): - self.log.log("Enter fog_layer->clear(self)", ORPG_DEBUG) self.fogregion.Clear() self.use_fog = True self.del_area("all") self.recompute_fog() - self.log.log("Exit fog_layer->clear(self)", ORPG_DEBUG) def remove_fog(self): - self.log.log("Enter fog_layer->remove_fog(self)", ORPG_DEBUG) self.fogregion.Clear() self.use_fog = False self.del_area("all") self.add_area("none") self.fog_bmp = None - self.log.log("Exit fog_layer->remove_fog(self)", ORPG_DEBUG) def resize(self, size): - self.log.log("Enter fog_layer->resize(self, size)", ORPG_DEBUG) try: if self.width == size[0] and self.height == size[1]: - self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) return self.recompute_fog() except: pass - self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) def recompute_fog(self): - self.log.log("Enter fog_layer->recompute_fog(self)", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->recompute_fog(self)", ORPG_DEBUG) return size = self.canvas.size self.width = size[0]/COURSE+1 self.height = size[1]/COURSE+1 self.fog_bmp = wx.EmptyBitmap(self.width+2,self.height+2) self.fill_fog() - self.log.log("Exit fog_layer->recompute_fog(self)", ORPG_DEBUG) def fill_fog(self): - self.log.log("Enter fog_layer->fill_fog(self)", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->fill_fog(self)", ORPG_DEBUG) return if "__WXGTK__" in wx.PlatformInfo: mdc = wx.MemoryDC() @@ -165,12 +138,9 @@ mdc.DrawRectangle(0, 0, self.width+2, self.height+2) mdc.SelectObject(wx.NullBitmap) del mdc - self.log.log("Exit fog_layer->fill_fog(self)", ORPG_DEBUG) def layerDraw(self, dc, topleft, size): - self.log.log("Enter fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) if self.fog_bmp == None or not self.fog_bmp.Ok() or not self.use_fog: - self.log.log("Exit fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) return if self.last_role != self.canvas.frame.session.role: self.fill_fog() if "__WXGTK__" not in wx.PlatformInfo: @@ -209,10 +179,8 @@ dc.SetUserScale(sc[0],sc[1]) mdc.SelectObject(wx.NullBitmap) del mdc - self.log.log("Exit fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) def createregn2(self, polyline, mode, show): - self.log.log("Enter fog_layer->createregn2(self, polyline, mode, show)", ORPG_DEBUG) regn = self.scanConvert(polyline) area = "" for i in polyline: @@ -231,59 +199,46 @@ self.fogregion = wx.Region(0, 0, self.canvas.size[0]+2, self.canvas.size[1]+2) self.fogregion.SubtractRegion(regn) self.del_area(area, show) - self.log.log("Exit fog_layer->createregn2(self, polyline, mode, show)", ORPG_DEBUG) def createregn(self, polyline, mode, show="Yes"): - self.log.log("Enter fog_layer->createregn(self, polyline, mode, show)", ORPG_DEBUG) if not self.use_fog and mode == 'del': self.clear() self.canvas.Refresh(False) if self.use_fog: self.createregn2(polyline, mode, show) self.fill_fog() - self.log.log("Exit fog_layer->createregn(self, polyline, mode, show)", ORPG_DEBUG) def scanConvert(self, polypt): - self.log.log("Enter fog_layer->scanConvert(self, polypt)", ORPG_DEBUG) regn = wx.Region() regn.Clear() list = IRegion().scan_Convert(polypt) for i in list: if regn.IsEmpty(): - if "__WXGTK__" not in wx.PlatformInfo: - regn = wx.Region(i.left*COURSE, i.y*COURSE, i.right*COURSE+1-i.left*COURSE, 1*COURSE) + if "__WXGTK__" not in wx.PlatformInfo: regn = wx.Region(i.left*COURSE, i.y*COURSE, + i.right*COURSE+1-i.left*COURSE, 1*COURSE) else: regn = wx.Region(i.left, i.y, i.right+1-i.left, 1) else: - if "__WXGTK__" not in wx.PlatformInfo: - regn.Union(i.left*COURSE, i.y*COURSE, i.right*COURSE+1-i.left*COURSE, 1*COURSE) + if "__WXGTK__" not in wx.PlatformInfo: regn.Union(i.left*COURSE, i.y*COURSE, + i.right*COURSE+1-i.left*COURSE, 1*COURSE) else: regn.Union(i.left, i.y, i.right+1-i.left, 1) - self.log.log("Exit fog_layer->scanConvert(self, polypt)", ORPG_DEBUG) return regn def add_area(self, area="", show="Yes"): - self.log.log("Enter fog_layer->add_area(self, area, show)", ORPG_DEBUG) poly = FogArea(area, self.log) xml_str = "<map><fog>" xml_str += poly.toxml("new") xml_str += "</fog></map>" if show == "Yes": self.canvas.frame.session.send(xml_str) - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit fog_layer->add_area(self, area, show)", ORPG_DEBUG) def del_area(self, area="", show="Yes"): - self.log.log("Enter fog_layer->del_area(self, area, show)", ORPG_DEBUG) poly = FogArea(area, self.log) xml_str = "<map><fog>" xml_str += poly.toxml("del") xml_str += "</fog></map>" if show == "Yes": self.canvas.frame.session.send(xml_str) - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit fog_layer->del_area(self, area, show)", ORPG_DEBUG) def layerToXML(self, action="update"): - self.log.log("Enter fog_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG) return "" fog_string = "" ri = wx.RegionIterator(self.fogregion) @@ -310,15 +265,11 @@ s += ">" s += fog_string s += "</fog>" - self.log.log(s, ORPG_DEBUG) - self.log.log("Exit fog_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s else: - self.log.log("Exit fog_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG) return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter fog_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) try: if not self.use_fog: self.use_fog = True @@ -350,5 +301,4 @@ lasty = y if (len(polyline) > 1): self.createregn2(polyline, action, "No") self.fill_fog() - except: self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("Exit fog_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) + except: pass
--- a/orpg/mapper/fog_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/fog_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -71,7 +71,7 @@ def on_remove(self,evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return self.canvas.layers['fog'].remove_fog() self.canvas.Refresh(False) @@ -79,7 +79,7 @@ def on_showall(self,evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return foglayer = self.canvas.layers['fog'] foglayer.showall() @@ -99,7 +99,7 @@ def on_hideall(self,evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return foglayer=self.canvas.layers['fog'] foglayer.clear() @@ -108,7 +108,7 @@ def on_color(self,evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return data = wx.ColourData() data.SetChooseFull(True) @@ -158,7 +158,7 @@ if self.drawing == True: session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") else: # This code sets the mode to either new or del # depending on the action to function with the updated createregen code.
--- a/orpg/mapper/fog_msg.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/fog_msg.py Thu Aug 27 01:04:43 2009 -0500 @@ -71,10 +71,6 @@ return self.toxml(action,output_action) def toxml(self,action,output_action): - #print "fog_msg.toxml called" - #print "use_fog :",self.use_fog - #print "output_action :",output_action - #print "action :",action if not (self.use_fog): return "" fog_string = "" if self.fogregion.isEmpty(): fog_string=self.get_line("all","del",output_action) @@ -116,11 +112,11 @@ list = l._get_childNodes() for node in list: polyline.append( IPoint().make( int(node.getAttribute("x")), int(node.getAttribute("y")) ) ) - # pointarray = outline.split(";") - # for m in range(len(pointarray)): - # pt=pointarray[m].split(",") - # polyline.append(IPoint().make(int(pt[0]),int(pt[1]))) - #print "length of polyline", len(polyline) + # pointarray = outline.split(";") + # for m in range(len(pointarray)): + # pt=pointarray[m].split(",") + # polyline.append(IPoint().make(int(pt[0]),int(pt[1]))) + #print "length of polyline", len(polyline) if (len(polyline)>2): if action=="del": self.fogregion.FromPolygon(polyline,0) else: self.fogregion.FromPolygon(polyline,1)
--- a/orpg/mapper/grid.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/grid.py Thu Aug 27 01:04:43 2009 -0500 @@ -107,7 +107,7 @@ else: x = topLeft.x y = topLeft.y - return cmpPoint(int(x),int(y)) # Set the pos attribute + return cmpPoint(int(x),int(y)) # Set the pos attribute else: return cmpPoint(int(pos.x),int(pos.y)) def set_rect_mode(self): @@ -209,7 +209,6 @@ # and therefore (per transformation above) is at iso co-ord (iso_unit_size, 0) # the bottom corner of the first diamond is grid co-ord (width/2, height) # and therefore (per transformation above) is at iso co-ord (0, iso_unit_size) - # the calculation is now as simple as the rectangle case, but using iso co-ords return cmpPoint(floor(iso_x/iso_unit_size), floor(iso_y/iso_unit_size)) else: return None
--- a/orpg/mapper/grid_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/grid_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -89,7 +89,7 @@ def on_apply(self, evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return self.canvas.layers['grid'].set_grid(int(self.grid_size.GetValue()),self.grid_snap.GetValue(),
--- a/orpg/mapper/grid_msg.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/grid_msg.py Thu Aug 27 01:04:43 2009 -0500 @@ -27,7 +27,8 @@ # __version__ = "$Id: grid_msg.py,v 1.8 2006/11/04 21:24:21 digitalxero Exp $" -from base_msg import * +from base_msg import map_element_msg_base +#from base_msg import * ## ?? import all? Deprecated!? class grid_msg(map_element_msg_base):
--- a/orpg/mapper/images.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/images.py Thu Aug 27 01:04:43 2009 -0500 @@ -32,8 +32,11 @@ import thread from threading import Lock import time + from orpg.orpg_wx import * -from orpg.orpgCore import * +from orpg.orpgCore import component +from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger def singleton(cls): instances = {} @@ -48,50 +51,51 @@ __fetching = {} __queue = Queue.Queue(0) __lock = Lock() + chat = component.get("chat") def load(self, path, image_type, imageId): - # Load an image, with a intermideary fetching image shown while it loads in a background thread + """Load an image, with a intermideary fetching image shown while it loads in a background thread""" if self.__cache.has_key(path): return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() if not self.__fetching.has_key(path): self.__fetching[path] = True - #Start Image Loading Thread + """Start Image Loading Thread""" thread.start_new_thread(self.__loadThread, (path, image_type, imageId)) else: if self.__fetching[path] is True: thread.start_new_thread(self.__loadCacheThread, (path, image_type, imageId)) - return wx.Bitmap(open_rpg.get_component("dir_struct")["icon"] + "fetching.png", wx.BITMAP_TYPE_PNG) + return wx.Bitmap(dir_struct["icon"] + "fetching.png", wx.BITMAP_TYPE_PNG) def directLoad(self, path): - # Directly load an image, no threads + """Directly load an image, no threads""" if self.__cache.has_key(path): return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() uriPath = urllib.unquote(path) try: d = urllib.urlretrieve(uriPath) - # We have to make sure that not only did we fetch something, but that - # it was an image that we got back. + """We have to make sure that not only did we fetch something, but that + it was an image that we got back.""" if d[0] and d[1].getmaintype() == "image": self.__cache[path] = (path, d[0], d[1].gettype(), None) return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() else: - open_rpg.get_component('log').log("Image refused to load or URI did not reference a valid image: " + path, - ORPG_GENERAL, True) + logger.general("Image refused to load or URI did not reference a valid image: " + path) + component.get('chat').InfoPost("<font color='#FF0000'>Image refused to load or URI did not reference a valid image: " + path + "</font>") return None except IOError: - open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, - ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT loaded: " + path) + component.get('chat').InfoPost("<font color='#FF0000'>Unable to resolve/open the specified URI; image was NOT loaded: " + path + "</font>") return None def cleanCache(self): - # Shrinks the Cache down to the proper size - try: cacheSize = int(open_rpg.get_component('settings').get_setting("ImageCacheSize")) + """Shrinks the Cache down to the proper size""" + try: cacheSize = int(component.get('settings').get_setting("ImageCacheSize")) except: cacheSize = 32 cache = self.__cache.keys() cache.sort() for key in cache[cacheSize:]: del self.__cache[key] def flushCache(self): - # This function will flush all images contained within the image cache. + """This function will flush all images contained within the image cache.""" self.__lock.acquire() try: keyList = self.__cache.keys() @@ -99,26 +103,26 @@ finally: self.__lock.release() urllib.urlcleanup() -#Private Methods + """Private Methods""" def __loadThread(self, path, image_type, imageId): uriPath = urllib.unquote(path) self.__lock.acquire() try: d = urllib.urlretrieve(uriPath) - # We have to make sure that not only did we fetch something, but that - # it was an image that we got back. + """We have to make sure that not only did we fetch something, but that + it was an image that we got back.""" if d[0] and d[1].getmaintype() == "image": self.__cache[path] = (path, d[0], d[1].gettype(), imageId) self.__queue.put((self.__cache[path], image_type, imageId)) - if self.__fetching.has_key(path): del self.__fetching[path] + if self.__fetching.has_key(path): self.__fetching[path] = False #Fix for failed multi-load? else: - open_rpg.get_component('log').log("Image refused to load or URI did not reference a valid image: " + path, - ORPG_GENERAL, True) + logger.general("Image refused to load or URI did not reference a valid image: " + path) + component.get('chat').InfoPost("<font color='#FF0000'>Image refused to load or URI did not reference a valid image: " + path +"</font>") del self.__fetching[path] except IOError: del self.__fetching[path] - open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT laoded: " + path, - ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT loaded: " + path) + component.get('chat').InfoPost("<font color='#FF0000'> Unable to resolve/open the specified URI; image was NOT loaded: " + path + "</font>") finally: self.__lock.release() def __loadCacheThread(self, path, image_type, imageId): @@ -128,26 +132,28 @@ while self.__fetching.has_key(path) and self.__fetching[path] is not False: time.sleep(0.025) if (time.time()-st) > 120: - open_rpg.get_component('log').log("Timeout: " + path, ORPG_GENERAL, True) + logger.general("Timeout: " + path) break except: del self.__fetching[path] - open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT loaded: " + path) + component.get('chat').InfoPost("<font color='#FF0000'>Unable to resolve/open the specified URI; image was NOT loaded: " + path + "</font>") return self.__lock.acquire() try: - open_rpg.get_component('log').log("Adding Image to Queue from Cache: " + str(self.__cache[path]), ORPG_DEBUG) + logger.debug("Adding Image to Queue from Cache: " + str(self.__cache[path])) + component.debug('chat').InfoPost("<font color='#FF0000'>Adding Image to Queue from Cache: " + str(self.__cache[path]) + "</font>") self.__queue.put((self.__cache[path], image_type, imageId)) finally: self.__lock.release() -#Property Methods + """Property Methods""" def _getCache(self): return self.__cache def _getQueue(self): return self.__queue -#Properties + """Properties""" Cache = property(_getCache) Queue = property(_getQueue)
--- a/orpg/mapper/map.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/map.py Thu Aug 27 01:04:43 2009 -0500 @@ -31,20 +31,24 @@ from map_msg import * from min_dialogs import * from map_prop_dialog import * -import orpg.dirpath + import random import os import thread -import gc +#import gc #Garbage Collecter Needed? import traceback + from miniatures_handler import * from whiteboard_handler import * from background_handler import * -from fog_handler import * -from images import ImageHandler from grid_handler import * from map_handler import * -from orpg.orpgCore import open_rpg +from fog_handler import * + +from orpg.dirpath import dir_struct +from images import ImageHandler +from orpg.orpgCore import component +from orpg.tools.orpg_settings import settings # Various marker modes for player tools on the map MARKER_MODE_NONE = 0 @@ -55,10 +59,7 @@ class MapCanvas(wx.ScrolledWindow): def __init__(self, parent, ID, isEditor=0): self.parent = parent - self.log = open_rpg.get_component("log") - self.log.log("Enter MapCanvas", ORPG_DEBUG) - self.settings = open_rpg.get_component("settings") - self.session = open_rpg.get_component("session") + self.session = component.get("session") wx.ScrolledWindow.__init__(self, parent, ID, style=wx.HSCROLL | wx.VSCROLL | wx.FULL_REPAINT_ON_RESIZE | wx.SUNKEN_BORDER ) self.frame = parent @@ -106,21 +107,15 @@ self.inside = 0 # miniatures drag self.drag = None - self.log.log("Exit MapCanvas", ORPG_DEBUG) def better_refresh(self, event=None): - self.log.log("Enter MapCanvas->better_refresh(self)", ORPG_DEBUG) self.Refresh(True) - self.log.log("Eexit MapCanvas->better_refresh(self)", ORPG_DEBUG) def pre_destory_cleanup(self): - self.log.log("Enter MapCanvas->pre_destory_cleanup(self)", ORPG_DEBUG) self.layers["miniatures"].del_all_miniatures() - self.log.log("Exit MapCanvas->pre_destory_cleanup(self)", ORPG_DEBUG) def processImages(self, evt=None): - self.log.log("Enter MapCanvas->processImages(self)", ORPG_DEBUG) - self.session = open_rpg.get_component("session") + self.session = component.get("session") if self.session.my_role() == self.session.ROLE_LURKER or (str(self.session.group_id) == '0' and str(self.session.status) == '1'): cidx = self.parent.get_tab_index("Background") self.parent.layer_tabs.EnableTab(cidx, False) @@ -160,11 +155,9 @@ self.parent.layer_tabs.EnableTab(cidx, True) if not self.cacheSizeSet: self.cacheSizeSet = True - cacheSize = self.settings.get_setting("ImageCacheSize") + cacheSize = component.get('settings').get_setting("ImageCacheSize") if len(cacheSize): self.cacheSize = int(cacheSize) - else: self.log.log("Default cache size being used.", ORPG_GENERAL) - self.log.log("Current image cache size is set at " + str(self.cacheSize) + " images, using random purge.", - ORPG_GENERAL) + else: pass if not ImageHandler.Queue.empty(): (path, image_type, imageId) = ImageHandler.Queue.get() img = wx.ImageFromMime(path[1], path[2]).ConvertToBitmap() @@ -180,15 +173,15 @@ # Flag that we now need to refresh! self.requireRefresh += 1 - # Randomly purge an item from the cache, while this is lamo, it does - # keep the cache from growing without bounds, which is pretty important! + """ Randomly purge an item from the cache, while this is lamo, it does + keep the cache from growing without bounds, which is pretty important!""" if len(ImageHandler.Cache) >= self.cacheSize: ImageHandler.cleanCache() else: - # Now, make sure not only that we require a refresh, but that enough time has - # gone by since our last refresh. This keeps back to back refreshing occuring during - # large map loads. Of course, we are now trying to pack as many image refreshes as - # we can into a single cycle. + """ Now, make sure not only that we require a refresh, but that enough time has + gone by since our last refresh. This keeps back to back refreshing occuring during + large map loads. Of course, we are now trying to pack as many image refreshes as + we can into a single cycle.""" if self.requireRefresh and (self.requireRefresh == self.lastRefreshValue): if (self.lastRefreshTime) < time.time(): self.requireRefresh = 0 @@ -196,86 +189,64 @@ self.lastRefreshTime = time.time() self.Refresh(True) else: self.lastRefreshValue = self.requireRefresh - self.log.log("Exit MapCanvas->processImages(self)", ORPG_DEBUG) def on_scroll(self, evt): - self.log.log("Enter MapCanvas->on_scroll(self, evt)", ORPG_DEBUG) if self.drag: self.drag.Hide() - if self.settings.get_setting("AlwaysShowMapScale") == "1": self.printscale() + if component.get('settings').get_setting("AlwaysShowMapScale") == "1": self.printscale() evt.Skip() - self.log.log("Exit MapCanvas->on_scroll(self, evt)", ORPG_DEBUG) def on_char(self, evt): - self.log.log("Enter MapCanvas->on_char(self, evt)", ORPG_DEBUG) - if self.settings.get_setting("AlwaysShowMapScale") == "1": self.printscale() + if component.get('settings').get_setting("AlwaysShowMapScale") == "1": self.printscale() evt.Skip() - self.log.log("Exit MapCanvas->on_char(self, evt)", ORPG_DEBUG) def printscale(self): - self.log.log("Enter MapCanvas->printscale(self)", ORPG_DEBUG) wx.BeginBusyCursor() dc = wx.ClientDC(self) self.PrepareDC(dc) self.showmapscale(dc) self.Refresh(True) wx.EndBusyCursor() - self.log.log("Exit MapCanvas->printscale(self)", ORPG_DEBUG) def send_map_data(self, action="update"): - self.log.log("Enter MapCanvas->send_map_data(self, " + action +")", ORPG_DEBUG) wx.BeginBusyCursor() send_text = self.toxml(action) if send_text: if not self.isEditor: self.frame.session.send(send_text) wx.EndBusyCursor() - self.log.log("Exit MapCanvas->send_map_data(self, " + action +")", ORPG_DEBUG) def get_size(self): - self.log.log("Enter MapCanvas->get_size(self)", ORPG_DEBUG) - self.log.log("Exit MapCanvas->get_size(self) return " + str(self.size), ORPG_DEBUG) return self.size def set_size(self, size): - self.log.log("Enter MapCanvas->set_size(self, size)", ORPG_DEBUG) if size[0] < 300: size = (300, size[1]) if size[1] < 300: size = (size[0], 300) self.size_changed = 1 self.size = size self.fix_scroll() self.layers['fog'].resize(size) - self.log.log("Exit MapCanvas->set_size(self, size)", ORPG_DEBUG) def fix_scroll(self): - self.log.log("Enter MapCanvas->fix_scroll(self)", ORPG_DEBUG) scale = self.layers['grid'].mapscale pos = self.GetViewStart() unit = self.GetScrollPixelsPerUnit() pos = [pos[0]*unit[0],pos[1]*unit[1]] size = self.GetClientSize() unit = [10*scale,10*scale] - if (unit[0] == 0 or unit[1] == 0): - self.log.log("Exit MapCanvas->fix_scroll(self)", ORPG_DEBUG) - return + if (unit[0] == 0 or unit[1] == 0): return pos[0] /= unit[0] pos[1] /= unit[1] mx = [int(self.size[0]*scale/unit[0])+1, int(self.size[1]*scale/unit[1]+1)] self.SetScrollbars(unit[0], unit[1], mx[0], mx[1], pos[0], pos[1]) - self.log.log("Exit MapCanvas->fix_scroll(self)", ORPG_DEBUG) def on_resize(self, evt): - self.log.log("Enter MapCanvas->on_resize(self, evt)", ORPG_DEBUG) self.fix_scroll() wx.CallAfter(self.Refresh, True) evt.Skip() - self.log.log("Exit MapCanvas->on_resize(self, evt)", ORPG_DEBUG) def on_erase_background(self, evt): - self.log.log("Enter MapCanvas->on_erase_background(self, evt)", ORPG_DEBUG) evt.Skip() - self.log.log("Exit MapCanvas->on_erase_background(self, evt)", ORPG_DEBUG) def on_paint(self, evt): - self.log.log("Enter MapCanvas->on_paint(self, evt)", ORPG_DEBUG) scale = self.layers['grid'].mapscale scrollsize = self.GetScrollPixelsPerUnit() clientsize = self.GetClientSize() @@ -303,21 +274,17 @@ del dc wdc = self.preppaint() wdc.DrawBitmap(bmp, topleft[0], topleft[1]) - if self.frame.settings.get_setting("AlwaysShowMapScale") == "1": + if settings.get_setting("AlwaysShowMapScale") == "1": self.showmapscale(wdc) try: evt.Skip() except: pass - self.log.log("Exit MapCanvas->on_paint(self, evt)", ORPG_DEBUG) def preppaint(self): - self.log.log("Enter MapCanvas->preppaint(self)", ORPG_DEBUG) dc = wx.PaintDC(self) self.PrepareDC(dc) - self.log.log("Exit MapCanvas->preppaint(self)", ORPG_DEBUG) return (dc) def showmapscale(self, dc): - self.log.log("Enter MapCanvas->showmapscale(self, dc)", ORPG_DEBUG) scalestring = "Scale x" + `self.layers['grid'].mapscale`[:3] (textWidth, textHeight) = dc.GetTextExtent(scalestring) dc.SetUserScale(1, 1) @@ -330,13 +297,11 @@ dc.DrawText(scalestring, x+1, y+1) dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) - self.log.log("Exit MapCanvas->showmapscale(self, dc)", ORPG_DEBUG) def snapMarker(self, snapPoint): """Based on the position and unit size, figure out where we need to snap to. As is, on a square grid, there are four possible places to snap. On a hex gid, there are 6 or 12 snap points.""" - self.log.log("Enter MapCanvas->snapMarker(self, snapPoint)", ORPG_DEBUG) # If snap to grid is disabled, simply return snapPoint unmodified if self.layers['grid'].snap: @@ -362,48 +327,38 @@ else: quadYPos = offsetY + size # Create our snap snapPoint and return it snapPoint = wx.Point( quadXPos, quadYPos ) - self.log.log("Exit MapCanvas->snapMarker(self, snapPoint)", ORPG_DEBUG) return snapPoint # Bunch of math stuff for marking and measuring def calcSlope(self, start, stop): """Calculates the slop of a line and returns it.""" - self.log.log("Enter MapCanvas->calcSlope(self, start, stop)", ORPG_DEBUG) if start.x == stop.x: s = 0.0001 else: s = float((stop.y - start.y)) / float((stop.x - start.x)) - self.log.log("Exit MapCanvas->calcSlope(self, start, stop)", ORPG_DEBUG) return s def calcSlopeToAngle(self, slope): """Based on the input slope, the angle (in degrees) will be returned.""" - self.log.log("Enter MapCanvas->calcSlopeToAngle(self, slope)", ORPG_DEBUG) # See if the slope is neg or positive if slope == abs(slope): # Slope is positive, so make sure it's not zero if slope == 0: a = 0 else: a = 360 - atan(slope) * (180.0/pi) else: a = atan(abs(slope)) * (180.0/pi) - self.log.log("Exit MapCanvas->calcSlopeToAngle(self, slope)", ORPG_DEBUG) return a def calcLineAngle(self, start, stop): """Based on two points that are on a line, return the angle of that line.""" - self.log.log("Enter MapCanvas->calcLineAngle(self, start, stop)", ORPG_DEBUG) a = self.calcSlopeToAngle( self.calcSlope( start, stop ) ) - self.log.log("Exit MapCanvas->calcLineAngle(self, start, stop)", ORPG_DEBUG) return a def calcPixelDistance(self, start, stop): """Calculate the distance between two pixels and returns it. The calculated distance is the Euclidean Distance, which is: d = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )""" - self.log.log("Enter MapCanvas->calcPixelDistance(self, start, stop)", ORPG_DEBUG) d = sqrt( abs((stop.x - start.x)**2 - (stop.y - start.y)**2) ) - self.log.log("Exit MapCanvas->calcPixelDistance(self, start, stop)", ORPG_DEBUG) return d def calcUnitDistance(self, start, stop, lineAngle): - self.log.log("Enter MapCanvas->calcUnitDistance(self, start, stop, lineAngle)", ORPG_DEBUG) distance = self.calcPixelDistance( start, stop ) ln = "%0.2f" % lineAngle if self.layers['grid'].mode == GRID_HEXAGON: @@ -413,12 +368,10 @@ if ln == "0.00" or ln == "359.99": ud = distance / self.layers['grid'].unit_size else: ud = (sqrt(abs((stop.x - start.x)**2 + (stop.y - start.y)**2))) / self.layers['grid'].unit_size #ud = sqrt( abs((stop.x - start.x)**2 - (stop.y - start.y)**2) ) - self.log.log("Exit MapCanvas->calcUnitDistance(self, start, stop, lineAngle)", ORPG_DEBUG) return ud def on_tape_motion(self, evt): """Track mouse motion so we can update the marker visual every time it's moved""" - self.log.log("Enter MapCanvas->on_tape_motion(self, evt)", ORPG_DEBUG) # Make sure we have a mode to do anything, otherwise, we ignore this if self.markerMode: # Grap the current DC for all of the marker modes @@ -428,7 +381,7 @@ # Grab the current map position pos = self.snapMarker( evt.GetLogicalPosition( dc ) ) # Enable brush optimizations - #dc.SetOptimization( True ) + # dc.SetOptimization( True ) # Set up the pen used for drawing our marker dc.SetPen( wx.Pen(wx.RED, 1, wx.LONG_DASH) ) # Now, based on the marker mode, draw the right thing @@ -449,12 +402,10 @@ # Disable brush optimizations #dc.SetOptimization( False ) del dc - self.log.log("Exit MapCanvas->on_tape_motion(self, evt)", ORPG_DEBUG) def on_tape_down(self, evt): """Greg's experimental tape measure code. Hopefully, when this is done, it will all be modal based on a toolbar.""" - self.log.log("Enter MapCanvas->on_tape_down(self, evt)", ORPG_DEBUG) dc = wx.ClientDC( self ) self.PrepareDC( dc ) dc.SetUserScale(self.layers['grid'].mapscale,self.layers['grid'].mapscale) @@ -484,11 +435,9 @@ self.markerStart = pos self.markerStop = pos del dc - self.log.log("Exit MapCanvas->on_tape_down(self, evt)", ORPG_DEBUG) def on_tape_up(self, evt): """When we release the middle button, disable any marking updates that we have been doing.""" - self.log.log("Enter MapCanvas->on_tape_up(self, evt)", ORPG_DEBUG) # If we are in measure mode, draw the actual UNIT distance if self.markerMode == MARKER_MODE_MEASURE: dc = wx.ClientDC( self ) @@ -521,48 +470,36 @@ del font del dc self.markerMode = MARKER_MODE_NONE - self.log.log("Exit MapCanvas->on_tape_up(self, evt)", ORPG_DEBUG) # MODE 1 = MOVE, MODE 2 = whiteboard, MODE 3 = Tape measure def on_left_down(self, evt): - self.log.log("Enter MapCanvas->on_left_down(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_down (evt) else: self.frame.on_left_down(evt) - self.log.log("Exit MapCanvas->on_left_down(self, evt)", ORPG_DEBUG) def on_right_down(self, evt): - self.log.log("Enter MapCanvas->on_right_down(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): pass else: self.frame.on_right_down(evt) - self.log.log("Exit MapCanvas->on_right_down(self, evt)", ORPG_DEBUG) def on_left_dclick(self, evt): - self.log.log("Enter MapCanvas->on_left_dclick(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): pass else: self.frame.on_left_dclick(evt) - self.log.log("Exit MapCanvas->on_left_dclick(self, evt)", ORPG_DEBUG) def on_left_up(self, evt): - self.log.log("Enter MapCanvas->on_left_up(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_up(evt) - elif open_rpg.get_component("tree").dragging: - tree = open_rpg.get_component("tree") + elif component.get("tree").dragging: + tree = component.get("tree") if tree.drag_obj.map_aware(): tree.drag_obj.on_send_to_map(evt) tree.dragging = False tree.drag_obj = None else: self.frame.on_left_up(evt) - self.log.log("Exit MapCanvas->on_left_up(self, evt)", ORPG_DEBUG) def on_motion(self, evt): - self.log.log("Enter MapCanvas->on_motion(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_motion(evt) - elif evt.LeftIsDown() and open_rpg.get_component("tree").dragging: pass + elif evt.LeftIsDown() and component.get("tree").dragging: pass else: self.frame.on_motion(evt) - self.log.log("Exit MapCanvas->on_motion(self, evt)", ORPG_DEBUG) def on_zoom_out(self, evt): - self.log.log("Enter MapCanvas->on_zoom_out(self, evt)", ORPG_DEBUG) if self.layers['grid'].mapscale > 0.2: # attempt to keep same logical point at center of screen scale = self.layers['grid'].mapscale @@ -592,10 +529,8 @@ dc.EndDrawing() del dc self.zoom_display_timer.Start(500,1) - self.log.log("Exit MapCanvas->on_zoom_out(self, evt)", ORPG_DEBUG) def on_zoom_in(self, evt): - self.log.log("Enter MapCanvas->on_zoom_in(self, evt)", ORPG_DEBUG) # attempt to keep same logical point at center of screen scale = self.layers['grid'].mapscale scrollsize = self.GetScrollPixelsPerUnit() @@ -624,15 +559,12 @@ dc.EndDrawing() del dc self.zoom_display_timer.Start(500, 1) - self.log.log("Exit MapCanvas->on_zoom_in(self, evt)", ORPG_DEBUG) def on_prop(self, evt): - self.log.log("Enter MapCanvas->on_prop(self, evt)", ORPG_DEBUG) - self.session = open_rpg.get_component("session") - self.chat = open_rpg.get_component("chat") + self.session = component.get("session") + self.chat = component.get("chat") if (self.session.my_role() != self.session.ROLE_GM): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit MapCanvas->on_prop(self, evt)", ORPG_DEBUG) return dlg = general_map_prop_dialog(self.frame.GetParent(),self.size,self.layers['bg'],self.layers['grid']) if dlg.ShowModal() == wx.ID_OK: @@ -641,10 +573,8 @@ self.Refresh(False) dlg.Destroy() os.chdir(self.root_dir) - self.log.log("Exit MapCanvas->on_prop(self, evt)", ORPG_DEBUG) def add_miniature(self, min_url, min_label='', min_unique=-1): - self.log.log("Enter MapCanvas->add_miniature(self, min_url, min_label, min_unique)", ORPG_DEBUG) if min_unique == -1: min_unique = not self.use_serial if min_url == "" or min_url == "http://": return if min_url[:7] != "http://" : min_url = "http://" + min_url @@ -659,27 +589,19 @@ try: id = 'mini-' + self.frame.session.get_next_id() self.layers['miniatures'].add_miniature(id, min_url, label=min_label) - except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("Unable to load/resolve URL: " + min_url + " on resource ' + min_label + ' !!!", ORPG_GENERAL) + except: self.layers['miniatures'].rollback_serial() wx.EndBusyCursor() self.send_map_data() self.Refresh(False) - self.log.log("Exit MapCanvas->add_miniature(self, min_url, min_label, min_unique)", ORPG_DEBUG) def get_label_from_url(self, url=''): - self.log.log("Enter MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) - if url == '': - self.log.log("Exit MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) - return '' + if url == '': return '' start = url.rfind("/")+1 label = url[start:len(url)-4] - self.log.log("Exit MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) return label def toxml(self, action="update"): - self.log.log("Enter MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) if action == "new": self.size_changed = 1 xml_str = "<map version='" + self.map_version + "'" @@ -692,36 +614,27 @@ for k in keys: if (k != "fog" or action != "update"): s += self.layers[k].layerToXML(action) self.size_changed = 0 - if s: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return xml_str + " action='" + action + "'>" + s + "</map>" + if s: return xml_str + " action='" + action + "'>" + s + "</map>" else: - if changed: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return xml_str + " action='" + action + "'/>" - else: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return "" + if changed: return xml_str + " action='" + action + "'/>" + else: return "" def takexml(self, xml): - # - # Added Process Dialog to display during long map parsings - # as well as a try block with an exception traceback to try - # and isolate some of the map related problems users have been - # experiencing --Snowdog 5/15/03 - # - # Apparently Process Dialog causes problems with linux.. commenting it out. sheez. - # --Snowdog 5/27/03 - self.log.log("Enter MapCanvas->takexml(self, xml)", ORPG_DEBUG) + """ + Added Process Dialog to display during long map parsings + as well as a try block with an exception traceback to try + and isolate some of the map related problems users have been + experiencing --Snowdog 5/15/03 + + Apparently Process Dialog causes problems with linux.. commenting it out. sheez. + --Snowdog 5/27/03 + """ try: #parse the map DOM xml_dom = parseXml(xml) - if xml_dom == None: - self.log.log("xml_dom == None\n" + xml, ORPG_INFO) - self.log.log("Exit MapCanvas->takexml(self, xml)", ORPG_DEBUG) - return + if xml_dom == None: return node_list = xml_dom.getElementsByTagName("map") - if len(node_list) < 1: self.log.log("Invalid XML format for mapper", ORPG_INFO) + if len(node_list) < 1: pass else: # set map version to incoming data so layers can convert self.map_version = node_list[0].getAttribute("version") @@ -762,18 +675,14 @@ self.map_version = MAP_VERSION self.Refresh(False) xml_dom.unlink() # eliminate circular refs - except: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: Critical Error Loading Map!!!", ORPG_GENERAL) - self.log.log("Exit MapCanvas->takexml(self, xml)", ORPG_DEBUG) + except: pass def re_ids_in_xml(self, xml): - self.log.log("Enter MapCanvas->re_ids_in_xml(self, xml)", ORPG_DEBUG) new_xml = "" tmp_map = map_msg() xml_dom = parseXml(str(xml)) node_list = xml_dom.getElementsByTagName("map") - if len(node_list) < 1: self.log.log("Invalid XML format for mapper", ORPG_INFO) + if len(node_list) < 1: pass else: tmp_map.init_from_dom(node_list[0]) if tmp_map.children.has_key("miniatures"): @@ -801,19 +710,15 @@ l.init_prop("id", id) new_xml = tmp_map.get_all_xml() if xml_dom: xml_dom.unlink() - self.log.log("Exit MapCanvas->re_ids_in_xml(self, xml)", ORPG_DEBUG) return str(new_xml) class map_wnd(wx.Panel): def __init__(self, parent, id): - self.log = open_rpg.get_component('log') - self.log.log("Enter map_wnd", ORPG_DEBUG) wx.Panel.__init__(self, parent, id) self.canvas = MapCanvas(self, -1) - self.session = open_rpg.get_component('session') - self.settings = open_rpg.get_component('settings') - self.chat = open_rpg.get_component('chat') - self.top_frame = open_rpg.get_component('frame') + self.session = component.get('session') + self.chat = component.get('chat') + self.top_frame = component.get('frame') self.root_dir = os.getcwd() self.current_layer = 2 self.layer_tabs = orpgTabberWnd(self, style=FNB.FNB_NO_X_BUTTON|FNB.FNB_BOTTOM|FNB.FNB_NO_NAV_BUTTONS) @@ -839,38 +744,30 @@ #self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) self.load_default() - self.log.log("Exit map_wnd", ORPG_DEBUG) def OnLeave(self, evt): if "__WXGTK__" in wx.PlatformInfo: wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) def load_default(self): - self.log.log("Enter map_wnd->load_default(self)", ORPG_DEBUG) if self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM) and (self.session.use_roles()): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->load_default(self)", ORPG_DEBUG) return - f = open(orpg.dirpath.dir_struct["template"] + "default_map.xml") + f = open(dir_struct["template"] + "default_map.xml") self.new_data(f.read()) f.close() self.canvas.send_map_data("new") if not self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM): self.session.update_role("GM") - self.log.log("Exit map_wnd->load_default(self)", ORPG_DEBUG) def new_data(self, data): - self.log.log("Enter map_wnd->new_data(self, data)", ORPG_DEBUG) self.canvas.takexml(data) self.update_tools() - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) def on_save(self,evt): - self.log.log("Enter map_wnd->new_data(self, data)", ORPG_DEBUG) if (self.session.my_role() != self.session.ROLE_GM): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) return - d = wx.FileDialog(self.GetParent(), "Save map data", orpg.dirpath.dir_struct["user"], "", "*.xml", wx.SAVE) + d = wx.FileDialog(self.GetParent(), "Save map data", dir_struct["user"], "", "*.xml", wx.SAVE) if d.ShowModal() == wx.ID_OK: f = open(d.GetPath(), "w") data = '<nodehandler class="min_map" icon="compass" module="core" name="miniature Map">' @@ -881,15 +778,12 @@ f.close() d.Destroy() os.chdir(self.root_dir) - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) def on_open(self, evt): - self.log.log("Enter map_wnd->on_open(self, evt)", ORPG_DEBUG) if self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM) and (self.session.use_roles()): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->on_open(self, evt)", ORPG_DEBUG) return - d = wx.FileDialog(self.GetParent(), "Select a file", orpg.dirpath.dir_struct["user"], "", "*.xml", wx.OPEN) + d = wx.FileDialog(self.GetParent(), "Select a file", dir_struct["user"], "", "*.xml", wx.OPEN) if d.ShowModal() == wx.ID_OK: f = open(d.GetPath()) map_string = f.read() @@ -902,25 +796,18 @@ self.session.update_role("GM") d.Destroy() os.chdir(self.root_dir) - self.log.log("Exit map_wnd->on_open(self, evt)", ORPG_DEBUG) def get_current_layer_handler(self): - self.log.log("Enter map_wnd->get_current_layer_handler(self)", ORPG_DEBUG) - self.log.log("Exit map_wnd->get_current_layer_handler(self)", ORPG_DEBUG) return self.layer_handlers[self.current_layer] def get_tab_index(self, layer): """Return the index of a chatpanel in the wxNotebook.""" - self.log.log("Enter map_wnd->get_tab_index(self, layer)", ORPG_DEBUG) for i in xrange(self.layer_tabs.GetPageCount()): if (self.layer_tabs.GetPageText(i) == layer): - self.log.log("Exit map_wnd->get_tab_index(self, layer) return " + str(i), ORPG_DEBUG) return i - self.log.log("Exit map_wnd->get_tab_index(self, layer) return 0", ORPG_DEBUG) return 0 def on_layer_change(self, evt): - self.log.log("Enter map_wnd->on_layer_change(self, evt)", ORPG_DEBUG) layer = self.layer_tabs.GetPage(evt.GetSelection()) for i in xrange(0, len(self.layer_handlers)): if layer == self.layer_handlers[i]: self.current_layer = i @@ -930,67 +817,43 @@ else: bg.url_path.Show(True) self.canvas.Refresh(False) evt.Skip() - self.log.log("Exit map_wnd->on_layer_change(self, evt)", ORPG_DEBUG) def on_left_down(self, evt): - self.log.log("Enter map_wnd->on_left_down(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_down(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_down(evt) #double click handler added by Snowdog 5/03 def on_left_dclick(self, evt): - self.log.log("Enter map_wnd->on_left_dclick(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_dclick(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_dclick(evt) def on_right_down(self, evt): - self.log.log("Enter map_wnd->on_right_down(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_right_down(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_right_down(evt) def on_left_up(self, evt): - self.log.log("Enter map_wnd->on_left_up(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_up(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_up(evt) def on_motion(self, evt): - self.log.log("Enter map_wnd->on_motion(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_motion(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_motion(evt) def MapBar(self, id, data): - self.log.log("Enter map_wnd->MapBar(self, id, data)", ORPG_DEBUG) self.canvas.MAP_MODE = data - if id == 1: - self.canvas.MAP_MODE = data - self.log.log("Exit map_wnd->MapBar(self, id, data)", ORPG_DEBUG) + if id == 1: self.canvas.MAP_MODE = data def set_map_focus(self, evt): - self.log.log("Enter map_wnd->set_map_focus(self, evt)", ORPG_DEBUG) self.canvas.SetFocus() - self.log.log("Exit map_wnd->set_map_focus(self, evt)", ORPG_DEBUG) def pre_exit_cleanup(self): - self.log.log("Enter map_wnd->pre_exit_cleanup(self)", ORPG_DEBUG) # do some pre exit clean up for bitmaps or other objects try: ImageHandler.flushCache() self.canvas.pre_destory_cleanup() - except Exception, e: - self.log.log(traceback.format_exc(), ORPG_CRITICAL) - self.log.log("EXCEPTION: " + str(e), ORPG_CRITICAL) - self.log.log("Exit map_wnd->pre_exit_cleanup(self)", ORPG_DEBUG) + except: pass def update_tools(self): - self.log.log("Enter map_wnd->update_tools(self)", ORPG_DEBUG) for h in self.layer_handlers: h.update_info() - self.log.log("Exit map_wnd->update_tools(self)", ORPG_DEBUG) def on_hk_map_layer(self, evt): - self.log.log("Enter map_wnd->on_hk_map_layer(self, evt)", ORPG_DEBUG) id = self.top_frame.mainmenu.GetHelpString(evt.GetId()) - #print evt.GetMenu().GetTitle() if id == "Background Layer": self.current_layer = self.get_tab_index("Background") if id == "Grid Layer": self.current_layer = self.get_tab_index("Grid") if id == "Miniature Layer": self.current_layer = self.get_tab_index("Miniatures") @@ -998,15 +861,11 @@ elif id == "Fog Layer": self.current_layer = self.get_tab_index("Fog") elif id == "General Properties": self.current_layer = self.get_tab_index("General") self.layer_tabs.SetSelection(self.current_layer) - self.log.log("Exit map_wnd->on_hk_map_layer(self, evt)", ORPG_DEBUG) def on_flush_cache(self, evt): - self.log.log("Enter map_wnd->on_flush_cache(self, evt)", ORPG_DEBUG) ImageHandler.flushCache() - self.log.log("Exit map_wnd->on_flush_cache(self, evt)", ORPG_DEBUG) def build_menu(self): - self.log.log("Enter map_wnd->build_menu(self)", ORPG_DEBUG) # temp menu menu = wx.Menu() item = wx.MenuItem(menu, wx.ID_ANY, "&Load Map", "Load Map") @@ -1043,10 +902,7 @@ self.top_frame.Bind(wx.EVT_MENU, self.canvas.on_prop, item) menu.AppendItem(item) self.top_frame.mainmenu.Insert(2, menu, '&Map') - self.log.log("Exit map_wnd->build_menu(self)", ORPG_DEBUG) def get_hot_keys(self): - self.log.log("Enter map_wnd->get_hot_keys(self)", ORPG_DEBUG) self.build_menu() - self.log.log("Exit map_wnd->get_hot_keys(self)", ORPG_DEBUG) return []
--- a/orpg/mapper/map_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/map_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -65,7 +65,7 @@ def on_apply(self, evt): session=self.canvas.frame.session if (session.my_role() != session.ROLE_GM): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return try: size = (int(self.width.GetValue()),int(self.height.GetValue())) except: wx.MessageBox("Invalid Map Size!","Map Properties"); return
--- a/orpg/mapper/map_msg.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/map_msg.py Thu Aug 27 01:04:43 2009 -0500 @@ -66,16 +66,11 @@ for c in xml_dom._get_childNodes(): name = c._get_nodeName() if not self.children.has_key(name): - if name == "miniatures": - self.children[name] = minis_msg(self.p_lock) - elif name == "grid": - self.children[name] = grid_msg(self.p_lock) - elif name == "bg": - self.children[name] = bg_msg(self.p_lock) - elif name == "whiteboard": - self.children[name] = whiteboard_msg(self.p_lock) - elif name == "fog": - self.children[name] = fog_msg(self.p_lock) + if name == "miniatures": self.children[name] = minis_msg(self.p_lock) + elif name == "grid": self.children[name] = grid_msg(self.p_lock) + elif name == "bg": self.children[name] = bg_msg(self.p_lock) + elif name == "whiteboard": self.children[name] = whiteboard_msg(self.p_lock) + elif name == "fog": self.children[name] = fog_msg(self.p_lock) else: print "Unrecognized tag " + name + " found in map_msg.init_from_dom - skipping" continue
--- a/orpg/mapper/map_prop_dialog.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/map_prop_dialog.py Thu Aug 27 01:04:43 2009 -0500 @@ -201,6 +201,7 @@ data = dlg.GetColourData() self.ctrls[CTRL_GRID_COLOR].SetBackgroundColour(data.GetColour()) dlg.Destroy() + def on_ok(self,evt): try: self.size = (int(self.ctrls[CTRL_WIDTH].GetValue()),int(self.ctrls[CTRL_HEIGHT].GetValue())) except: pass
--- a/orpg/mapper/map_utils.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/map_utils.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,36 +1,35 @@ -#------------------------------------------------ -# file: map_utils.py -# -# This file contains generic utility functions -# for use in the openrpg mapping system -# ----------------------------------------------- +""" + file: map_utils.py + + This file contains generic utility functions + for use in the openrpg mapping system +""" import math - -#----------------------------------------------------------------------- -# distance_between() -# Returns the distance between two points -#----------------------------------------------------------------------- +""" + distance_between() + Returns the distance between two points +""" def distance_between( x1, y1, x2, y2 ): "Returns the distance between two points" dx = x2 - x1 dy = y2 - y1 return math.sqrt( dx*dx + dy*dy ) -#----------------------------------------------------------------------- -# proximity_test() -# Tests if 'test_point' (T) is close (within 'threshold' units) to the -# line segment 'start_point' to 'end_point' (PQ). -# -# The closest point (R) to T on the line PQ is given by: -# R = P + u (Q - P) -# TR is perpendicular to PQ so: -# (T - R) dot (Q - P) = 0 -# Solving these two equations gives the equation for u (see below). -# -# If u < 0 or u > 1 then R is not within the line segment and we simply -# test against point P or Q. -#----------------------------------------------------------------------- +""" + proximity_test() + Tests if 'test_point' (T) is close (within 'threshold' units) to the + line segment 'start_point' to 'end_point' (PQ). + + The closest point (R) to T on the line PQ is given by: + R = P + u (Q - P) + TR is perpendicular to PQ so: + (T - R) dot (Q - P) = 0 + Solving these two equations gives the equation for u (see below). + + If u < 0 or u > 1 then R is not within the line segment and we simply + test against point P or Q. +""" def proximity_test( start_point, end_point, test_point, threshold ): "Test if a point is close to a line segment" x1,y1 = start_point
--- a/orpg/mapper/min_dialogs.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/min_dialogs.py Thu Aug 27 01:04:43 2009 -0500 @@ -151,7 +151,7 @@ else: node_begin += "Unnamed Miniature'" node_begin += ">" - gametree = open_rpg.get_component('tree') + gametree = component.get('tree') node_xml = node_begin + min_xml + '</nodehandler>' print "Sending this XML to insert_xml:" + node_xml gametree.insert_xml(node_xml) @@ -417,10 +417,14 @@ sizer.Add(self.label, 0, wx.EXPAND) sizer.Add(wx.Size(10,10)) self.heading = wx.RadioBox(self, MIN_HEADING, "Heading", - choices=["None","N","NE","E","SE","S","SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) + choices=["None","N","NE", + "E","SE","S", + "SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) self.heading.SetSelection(min.heading) self.face = wx.RadioBox(self, MIN_FACE, "Facing", - choices=["None","N","NE","E","SE","S","SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) + choices=["None","N","NE", + "E","SE","S", + "SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) self.face.SetSelection(min.face) self.locked = wx.CheckBox(self, MIN_LOCK, " Lock") self.locked.SetValue(min.locked)
--- a/orpg/mapper/miniatures.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/miniatures.py Thu Aug 27 01:04:43 2009 -0500 @@ -34,6 +34,8 @@ import urllib import os.path +from orpg.tools.orpg_settings import settings + MIN_STICKY_BACK = -0XFFFFFF MIN_STICKY_FRONT = 0xFFFFFF @@ -64,9 +66,10 @@ return value class BmpMiniature: - def __init__(self, id,path, bmp, pos=cmpPoint(0,0), heading=FACE_NONE, face=FACE_NONE, label="", locked=False, hide=False, snap_to_align=SNAPTO_ALIGN_CENTER, zorder=0, width=0, height=0, log=None, local=False, localPath='', localTime=-1): - self.log = log - self.log.log("Enter BmpMiniature", ORPG_DEBUG) + def __init__(self, id,path, bmp, pos=cmpPoint(0,0), + heading=FACE_NONE, face=FACE_NONE, label="", + locked=False, hide=False, snap_to_align=SNAPTO_ALIGN_CENTER, + zorder=0, width=0, height=0, log=None, local=False, localPath='', localTime=-1): self.heading = heading self.face = face self.label = label @@ -92,22 +95,15 @@ self.bottom = bmp.GetHeight() self.isUpdated = False self.gray = False - self.log.log("Exit BmpMiniature", ORPG_DEBUG) def __del__(self): - self.log.log("Enter BmpMiniature->__del__(self)", ORPG_DEBUG) del self.bmp self.bmp = None - self.log.log("Exit BmpMiniature->__del__(self)", ORPG_DEBUG) def set_bmp(self, bmp): - self.log.log("Enter BmpMiniature->set_bmp(self, bmp)", ORPG_DEBUG) self.bmp = bmp - self.log.log("Exit BmpMiniature->set_bmp(self, bmp)", ORPG_DEBUG) def set_min_props(self, heading=FACE_NONE, face=FACE_NONE, label="", locked=False, hide=False, width=0, height=0): - self.log.log("Enter BmpMiniature->set_min_props(self, heading, face, label, locked, hide, width, height)", - ORPG_DEBUG) self.heading = heading self.face = face self.label = label @@ -118,33 +114,24 @@ self.width = int(width) self.height = int(height) self.isUpdated = True - self.log.log("Exit BmpMiniature->set_min_props(self, heading, face, label, locked, hide, width, height)", - ORPG_DEBUG) def hit_test(self, pt): - self.log.log("Enter BmpMiniature->hit_test(self, pt)", ORPG_DEBUG) rect = self.get_rect() result = None result = rect.InsideXY(pt.x, pt.y) - self.log.log("Exit BmpMiniature->hit_test(self, pt)", ORPG_DEBUG) return result def get_rect(self): - self.log.log("Enter BmpMiniature->get_rect(self)", ORPG_DEBUG) ret = wx.Rect(self.pos.x, self.pos.y, self.bmp.GetWidth(), self.bmp.GetHeight()) - self.log.log("Exit BmpMiniature->get_rect(self)", ORPG_DEBUG) return ret def draw(self, dc, mini_layer, op=wx.COPY): - self.log.log("Enter BmpMiniature->draw(self, dc, mini_layer, op)", ORPG_DEBUG) if isinstance(self.bmp, tuple): - self.log.log("bmp is a tuple, it shouldnt be!", ORPG_INFO) self.bmp = wx.ImageFromMime(self.bmp[1], self.bmp[2]).ConvertToBitmap() if self.bmp != None and self.bmp.Ok(): # check if hidden and GM: we outline the mini in grey (little bit smaller than the actual size) # and write the label in the center of the mini if self.hide and mini_layer.canvas.frame.session.my_role() == mini_layer.canvas.frame.session.ROLE_GM: - self.log.log("Enter BmpMiniature->draw->Draw Hidden", ORPG_DEBUG) # set the width and height of the image if self.width and self.height: tmp_image = self.bmp.ConvertToImage() @@ -199,12 +186,10 @@ dc.DrawRectangle(self.pos.x, self.pos.y, self.bmp.GetWidth(), self.bmp.GetHeight()) dc.SetBrush(wx.NullBrush) dc.SetPen(wx.NullPen) - self.log.log("Exit BmpMiniature->draw->Draw Hidden", ORPG_DEBUG) return True - elif self.hide: self.log.log("Enter/Exit BmpMiniature->draw->Skip Hidden", ORPG_DEBUG); return True + elif self.hide: return True else: - self.log.log("Enter BmpMiniature->draw->Not Hidden", ORPG_DEBUG) # set the width and height of the image bmp = self.bmp if self.width and self.height: @@ -362,17 +347,12 @@ self.bottom+=5 self.left-=5 self.right+=5 - self.log.log("Exit BmpMiniature->draw->Not Hidden", ORPG_DEBUG) return True - else: self.log.log("Exit BmpMiniature->draw(self, dc, mini_layer, op) return False", ORPG_DEBUG); return False - self.log.log("Exit BmpMiniature->draw(self, dc, mini_layer, op)", ORPG_DEBUG) + else: return False def toxml(self, action="update"): - self.log.log("Enter BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<miniature action='del' id='" + self.id + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str xml_str = "<miniature" xml_str += " action='" + action + "'" @@ -397,58 +377,41 @@ xml_str += ' localPath="' + str(urllib.quote(self.localPath).replace('%3A', ':')) + '"' xml_str += ' localTime="' + str(self.localTime) + '"' xml_str += " />" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str else: return '' def takedom(self, xml_dom): - self.log.log("Enter BmpMiniature->takedom(self, xml_dom)", ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("posx"): self.pos.x = int(xml_dom.getAttribute("posx")) - self.log.log("self.pos.x=" + str(self.pos.x), ORPG_DEBUG) if xml_dom.hasAttribute("posy"): self.pos.y = int(xml_dom.getAttribute("posy")) - self.log.log("self.pos.y=" + str(self.pos.y), ORPG_DEBUG) if xml_dom.hasAttribute("heading"): self.heading = int(xml_dom.getAttribute("heading")) - self.log.log("self.heading=" + str(self.heading), ORPG_DEBUG) if xml_dom.hasAttribute("face"): self.face = int(xml_dom.getAttribute("face")) - self.log.log("self.face=" + str(self.face), ORPG_DEBUG) if xml_dom.hasAttribute("path"): self.path = urllib.unquote(xml_dom.getAttribute("path")) self.set_bmp(ImageHandler.load(self.path, 'miniature', self.id)) - self.log.log("self.path=" + self.path, ORPG_DEBUG) if xml_dom.hasAttribute("locked"): if xml_dom.getAttribute("locked") == '1' or xml_dom.getAttribute("locked") == 'True': self.locked = True else: self.locked = False - self.log.log("self.locked=" + str(self.locked), ORPG_DEBUG) if xml_dom.hasAttribute("hide"): if xml_dom.getAttribute("hide") == '1' or xml_dom.getAttribute("hide") == 'True': self.hide = True else: self.hide = False - self.log.log("self.hide=" + str(self.hide), ORPG_DEBUG) if xml_dom.hasAttribute("label"): self.label = xml_dom.getAttribute("label") - self.log.log("self.label=" + self.label, ORPG_DEBUG) if xml_dom.hasAttribute("zorder"): self.zorder = int(xml_dom.getAttribute("zorder")) - self.log.log("self.zorder=" + str(self.zorder), ORPG_DEBUG) if xml_dom.hasAttribute("align"): if xml_dom.getAttribute("align") == '1' or xml_dom.getAttribute("align") == 'True': self.snap_to_align = 1 else: self.snap_to_align = 0 - self.log.log("self.snap_to_align=" + str(self.snap_to_align), ORPG_DEBUG) if xml_dom.hasAttribute("width"): self.width = int(xml_dom.getAttribute("width")) - self.log.log("self.width=" + str(self.width), ORPG_DEBUG) if xml_dom.hasAttribute("height"): self.height = int(xml_dom.getAttribute("height")) - self.log.log("self.height=" + str(self.height), ORPG_DEBUG) - self.log.log("Exit BmpMiniature->takedom(self, xml_dom)", ORPG_DEBUG) ##----------------------------- ## miniature layer @@ -456,9 +419,6 @@ class miniature_layer(layer_base): def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter miniature_layer", ORPG_DEBUG) - self.settings = self.canvas.settings layer_base.__init__(self) self.id = -1 #added. self.miniatures = [] @@ -466,26 +426,20 @@ # Set the font of the labels to be the same as the chat window # only smaller. - font_size = int(self.settings.get_setting('defaultfontsize')) + font_size = int(settings.get_setting('defaultfontsize')) if (font_size >= 10): font_size -= 2 self.label_font = wx.Font(font_size, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, - False, self.settings.get_setting('defaultfont')) - self.log.log("Exit miniature_layer", ORPG_DEBUG) + False, settings.get_setting('defaultfont')) def next_serial(self): - self.log.log("Enter miniature_layer->next_serial(self)", ORPG_DEBUG) self.serial_number += 1 - self.log.log("Exit miniature_layer->next_serial(self)", ORPG_DEBUG) return self.serial_number def get_next_highest_z(self): - self.log.log("Enter miniature_layer->get_next_highest_z(self)", ORPG_DEBUG) z = len(self.miniatures)+1 - self.log.log("Exit miniature_layer->get_next_highest_z(self)", ORPG_DEBUG) return z def cleanly_collapse_zorder(self): - self.log.log("Enter miniature_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) # lock the zorder stuff sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -493,11 +447,9 @@ for mini in sorted_miniatures: mini.zorder = i i = i + 1 - self.log.log("Exit miniature_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) # unlock the zorder stuff def collapse_zorder(self): - self.log.log("Enter miniature_layer->collapse_zorder(self)", ORPG_DEBUG) # lock the zorder stuff sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -506,46 +458,31 @@ if (mini.zorder != MIN_STICKY_BACK) and (mini.zorder != MIN_STICKY_FRONT): mini.zorder = i else: pass i = i + 1 - self.log.log("Exit miniature_layer->collapse_zorder(self)", ORPG_DEBUG) # unlock the zorder stuff def rollback_serial(self): - self.log.log("Enter miniature_layer->rollback_serial(self)", ORPG_DEBUG) self.serial_number -= 1 - self.log.log("Exit miniature_layer->rollback_serial(self)", ORPG_DEBUG) def add_miniature(self, id, path, pos=cmpPoint(0,0), label="", heading=FACE_NONE, face=FACE_NONE, width=0, height=0, local=False, localPath='', localTime=-1): - self.log.log("Enter miniature_layer->add_miniature(self, id, path, pos, label, heading, face, width, height)", - ORPG_DEBUG) - self.log.log("Before mini creation: " + str(self.get_next_highest_z()), ORPG_DEBUG) bmp = ImageHandler.load(path, 'miniature', id) if bmp: mini = BmpMiniature(id, path, bmp, pos, heading, face, label, zorder=self. get_next_highest_z(), width=width, - height=height, log=self.log, local=local, localPath=localPath, localTime=localTime) - self.log.log("After mini creation:" + str(self.get_next_highest_z()), ORPG_DEBUG) + height=height, local=local, localPath=localPath, localTime=localTime) self.miniatures.append(mini) - self.log.log("After mini addition:" + str(self.get_next_highest_z()), ORPG_DEBUG) xml_str = "<map><miniatures>" xml_str += mini.toxml("new") xml_str += "</miniatures></map>" self.canvas.frame.session.send(xml_str) - else: self.log.log("Invalid image " + path + " has been ignored!", ORPG_DEBUG) - self.log.log("Exit miniature_layer->add_miniature(self, id, path, pos, label, heading, face, width, height)", - ORPG_DEBUG) def get_miniature_by_id(self, id): - self.log.log("Enter miniature_layer->get_miniature_by_id(self, id)", ORPG_DEBUG) for mini in self.miniatures: if str(mini.id) == str(id): - self.log.log("Exit miniature_layer->get_miniature_by_id(self, id) return miniID: " + str(id), ORPG_DEBUG) return mini - self.log.log("Exit miniature_layer->get_miniature_by_id(self, id) return None", ORPG_DEBUG) return None def del_miniature(self, min): - self.log.log("Enter miniature_layer->del_miniature(self, min)", ORPG_DEBUG) xml_str = "<map><miniatures>" xml_str += min.toxml("del") xml_str += "</miniatures></map>" @@ -553,18 +490,14 @@ self.miniatures.remove(min) del min self.collapse_zorder() - self.log.log("Exit miniature_layer->del_miniature(self, min)", ORPG_DEBUG) def del_all_miniatures(self): - self.log.log("Enter miniature_layer->del_all_miniatures(self)", ORPG_DEBUG) while len(self.miniatures): min = self.miniatures.pop() del min self.collapse_zorder() - self.log.log("Exit miniature_layer->del_all_miniatures(self)", ORPG_DEBUG) def layerDraw(self, dc, topleft, size): - self.log.log("Enter miniature_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) dc.SetFont(self.label_font) sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -574,10 +507,8 @@ m.pos.x<topleft[0]+size[0]-m.left and m.pos.y<topleft[1]+size[1]-m.top): m.draw(dc, self) - self.log.log("Exit miniature_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) def find_miniature(self, pt, only_unlocked=False): - self.log.log("Enter miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG) min_list = [] for m in self.miniatures: if m.hit_test(pt): @@ -586,13 +517,11 @@ elif not only_unlocked and m.locked: min_list.append(m) else: continue if len(min_list) > 0: - self.log.log("Exit miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG) return min_list - else: self.log.log("Exit miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG); return None + else: return None def layerToXML(self, action="update"): """ format """ - self.log.log("Enter miniature_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) minis_string = "" if self.miniatures: for m in self.miniatures: minis_string += m.toxml(action) @@ -602,12 +531,10 @@ s += ">" s += minis_string s += "</miniatures>" - self.log.log("Exit miniature_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s - else: self.log.log("Exit miniature_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG); return "" + else: return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter miniature_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) if xml_dom.hasAttribute('serial'): self.serial_number = int(xml_dom.getAttribute('serial')) children = xml_dom._get_childNodes() @@ -619,7 +546,6 @@ if mini: self.miniatures.remove(mini) del mini - else: self.log.log("Map Synchronization Error :: Update of unknown mini attempted", ORPG_DEBUG) elif action == "new": pos = cmpPoint(int(c.getAttribute('posx')),int(c.getAttribute('posy'))) path = urllib.unquote(c.getAttribute('path')) @@ -635,7 +561,7 @@ if c.hasAttribute('align'): snap_to_align = int(c.getAttribute('align')) if c.getAttribute('zorder'): zorder = int(c.getAttribute('zorder')) min = BmpMiniature(id, path, ImageHandler.load(path, 'miniature', id), pos, heading, - face, label, locked, hide, snap_to_align, zorder, width, height, self.log) + face, label, locked, hide, snap_to_align, zorder, width, height) self.miniatures.append(min) if c.hasAttribute('local') and c.getAttribute('local') == 'True' and os.path.exists(urllib.unquote(c.getAttribute('localPath'))): localPath = urllib.unquote(c.getAttribute('localPath')) @@ -655,12 +581,10 @@ else: mini = self.get_miniature_by_id(id) if mini: mini.takedom(c) - else: self.log.log("Map Synchronization Error :: Update of unknown mini attempted", ORPG_DEBUG) - self.log.log("Exit miniature_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) def upload(self, postdata, filename, modify=False, pos=cmpPoint(0,0)): self.lock.acquire() - url = self.settings.get_setting('ImageServerBaseURL') + url = settings.get_setting('ImageServerBaseURL') file = urllib.urlopen(url, postdata) recvdata = file.read() file.close()
--- a/orpg/mapper/miniatures_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/miniatures_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -40,6 +40,8 @@ from grid import GRID_ISOMETRIC import os +from orpg.tools.orpg_settings import settings + LABEL_TOOL = wx.NewId() LAYER_TOOL = wx.NewId() MIN_LIST_TOOL = wx.NewId() @@ -103,7 +105,7 @@ self.use_serial = 1 self.auto_label_cb = None self.canvas = canvas - self.settings = self.canvas.settings + self.settings = settings self.mini_rclick_menu_extra_items = {} self.background_rclick_menu_extra_items = {} base_layer_handler.__init__(self, parent, id, canvas) @@ -117,7 +119,7 @@ self.tooltip_timer.Stop() dt = myFileDropTarget(self) self.canvas.SetDropTarget(dt) - # wxInitAllImageHandlers() + #wxInitAllImageHandlers() def build_ctrls(self): base_layer_handler.build_ctrls(self) @@ -126,7 +128,7 @@ self.auto_label_cb.SetValue(self.auto_label) self.min_url = wx.ComboBox(self, wx.ID_ANY, "http://", style=wx.CB_DROPDOWN | wx.CB_SORT) self.localBrowse = wx.Button(self, wx.ID_ANY, 'Browse', style=wx.BU_EXACTFIT) - minilist = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'questionhead.gif', 'Edit miniature properties', wx.ID_ANY) + minilist = createMaskedButton( self, dir_struct["icon"]+'questionhead.gif', 'Edit miniature properties', wx.ID_ANY) miniadd = wx.Button(self, wx.ID_OK, "Add Miniature", style=wx.BU_EXACTFIT) self.sizer.Add(self.auto_label_cb,0,wx.ALIGN_CENTER) self.sizer.Add((6, 0)) @@ -144,7 +146,7 @@ def on_browse(self, evt): if not self.role_is_gm_or_player(): return - dlg = wx.FileDialog(None, "Select a Miniature to load", orpg.dirpath.dir_struct["user"]+'webfiles/', + dlg = wx.FileDialog(None, "Select a Miniature to load", dir_struct["user"]+'webfiles/', wildcard="Image files (*.bmp, *.gif, *.jpg, *.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) if not dlg.ShowModal() == wx.ID_OK: dlg.Destroy() @@ -162,12 +164,13 @@ dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(0) y = dc.DeviceToLogicalY(0) - thread.start_new_thread(self.canvas.layers['miniatures'].upload, (postdata, dlg.GetPath()), {'pos':cmpPoint(x,y)}) + thread.start_new_thread(self.canvas.layers['miniatures'].upload, + (postdata, dlg.GetPath()), {'pos':cmpPoint(x,y)}) else: - try: min_url = open_rpg.get_component("cherrypy") + filename - except: return - min_url = dlg.GetDirectory().replace(orpg.dirpath.dir_struct["user"]+'webfiles' + os.sep, - open_rpg.get_component("cherrypy")) + '/' + filename + try: min_url = component.get("cherrypy") + filename + except: return #chat.InfoPost('CherryPy is not started!') + min_url = dlg.GetDirectory().replace(dir_struct["user"]+'webfiles' + os.sep, + component.get("cherrypy")) + '/' + filename # build url if min_url == "" or min_url == "http://": return if min_url[:7] != "http://": min_url = "http://" + min_url @@ -190,7 +193,6 @@ except: # When there is an exception here, we should be decrementing the serial_number for reuse!! unablemsg= "Unable to load/resolve URL: " + min_url + " on resource \"" + min_label + "\"!!!\n\n" - #print unablemsg dlg = wx.MessageDialog(self,unablemsg, 'Url not found',wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() @@ -355,7 +357,7 @@ if self.sel_rmin.label: node_begin += self.sel_rmin.label + "'" else: node_begin += "Unnamed Miniature'" node_begin += ">" - gametree = open_rpg.get_component('tree') + gametree = component.get('tree') node_xml = node_begin + min_xml + '</nodehandler>' #print "Sending this XML to insert_xml:" + node_xml gametree.insert_xml(str(node_xml)) @@ -746,7 +748,7 @@ ## helper functions def infoPost(self, message): - open_rpg.get_component("chat").InfoPost(message) + component.get("chat").InfoPost(message) def role_is_gm_or_player(self): session = self.canvas.frame.session
--- a/orpg/mapper/region.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/region.py Thu Aug 27 01:04:43 2009 -0500 @@ -156,10 +156,14 @@ return IRect().make(self.left+pt.X,self.top+pt.Y,self.right+pt.X,self.bottom+pt.Y) def intersect(self,rect): - return IRect().make(max(self.left,rect.left),max(self.top,rect.top),min(self.right,rect.right),min(self.bottom,rect.bottom)) + return IRect().make(max(self.left,rect.left), + max(self.top,rect.top),min(self.right,rect.right), + min(self.bottom,rect.bottom)) def union(self,rect): - return IRect().make(min(self.left,rect.left),min(self.top,rect.top),max(self.right,rect.right),max(self.bottom,rect.bottom)) + return IRect().make(min(self.left,rect.left), + min(self.top,rect.top),max(self.right,rect.right), + max(self.bottom,rect.bottom)) def equals(self,rect): if (self.top==rect.top and self.bottom==rect.bottom and self.left==rect.left and self.right==rect.right): return 1 @@ -206,7 +210,7 @@ x+="]" return x -#remove all rectangles from list + #remove all rectangles from list def Clear(self): while(self.first): rect=self.first @@ -215,7 +219,7 @@ self.last=None self.count=0 -#add a new clipping rectangle to list + #add a new clipping rectangle to list def AddRect(self,rect): rect.prev=None rect.next=self.first @@ -224,7 +228,7 @@ if self.last is None: self.last=rect self.count += 1 -#removes the passed clipping rectangle from the list + #removes the passed clipping rectangle from the list def RemoveRect(self,rect): if not (rect.prev is None): rect.prev.next=rect.next else: self.first=rect.next @@ -232,8 +236,8 @@ else: self.last=rect.prev self.count -= 1 -# find the clipping rectangle at the the beginning of the list, remove it, -# and return it + # find the clipping rectangle at the the beginning of the list, remove it, + # and return it def RemoveHead(self): if self.count==0: return None rect=self.first @@ -242,8 +246,8 @@ self.count -= 1 return rect -# stealrects -- appends the list of clipping rectangles in pclist to the current -# list. removes the entries from pclist + # stealrects -- appends the list of clipping rectangles in pclist to the current + # list. removes the entries from pclist def StealRects(self,pclist): if pclist.first is None: return if self.first is None: @@ -258,7 +262,7 @@ pclist.last = None pclist.count = 0 -# utilitarian procedure to return all clipping rectangles as a Python list + # utilitarian procedure to return all clipping rectangles as a Python list def GetList(self): result=[] f = self.first
--- a/orpg/mapper/whiteboard.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/whiteboard.py Thu Aug 27 01:04:43 2009 -0500 @@ -43,8 +43,6 @@ class WhiteboardText: def __init__(self, id, text_string, pos, style, pointsize, weight, color="#000000", log=None): - self.log = log - self.log.log("Enter WhiteboardText", ORPG_DEBUG) self.scale = 1 self.r_h = RGBHex() self.selected = False @@ -61,15 +59,11 @@ r,g,b = self.r_h.rgb_tuple(self.textcolor) self.highlight_color = self.r_h.hexstring(r^255, g^255, b^255) self.isUpdated = False - self.log.log("Exit WhiteboardText", ORPG_DEBUG) def highlight(self, highlight=True): - self.log.log("Enter WhiteboardText->highlight(self, highlight)", ORPG_DEBUG) self.highlighted = highlight - self.log.log("Exit WhiteboardText->highlight(self, highlight)", ORPG_DEBUG) def set_text_props(self, text_string, style, point, weight, color="#000000"): - self.log.log("Enter WhiteboardText->set_text_props(self, text_string, style, point, weight, color)", ORPG_DEBUG) self.text_string = text_string self.textcolor = color self.style = int(style) @@ -79,24 +73,18 @@ self.weight = int(weight) self.font.SetWeight(self.weight) self.isUpdated = True - self.log.log("Exit WhiteboardText->set_text_props(self, text_string, style, point, weight, color)", ORPG_DEBUG) def hit_test(self, pt, dc): - self.log.log("Enter WhiteboardText->hit_test(self, pt, dc)", ORPG_DEBUG) rect = self.get_rect(dc) result = rect.InsideXY(pt.x, pt.y) - self.log.log("Exit WhiteboardText->hit_test(self, pt, dc)", ORPG_DEBUG) return result def get_rect(self, dc): - self.log.log("Enter WhiteboardText->get_rect(self, dc)", ORPG_DEBUG) dc.SetFont(self.font) (w,x,y,z) = dc.GetFullTextExtent(self.text_string) - self.log.log("Exit WhiteboardText->get_rect(self, dc)", ORPG_DEBUG) return wx.Rect(self.posx,self.posy,w,(x+y+z)) def draw(self, parent, dc, op=wx.COPY): - self.log.log("Enter WhiteboardText->draw(self, parent, dc, op)", ORPG_DEBUG) self.scale = parent.canvas.layers['grid'].mapscale if self.highlighted: textcolor = self.highlight_color else: textcolor = self.textcolor @@ -109,14 +97,10 @@ dc.SetFont(self.font) dc.DrawText(self.text_string, self.posx, self.posy) dc.SetTextForeground(wx.Colour(0,0,0)) - self.log.log("Exit WhiteboardText->draw(self, parent, dc, op)", ORPG_DEBUG) def toxml(self, action="update"): - self.log.log("Enter WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<text action='del' id='" + str(self.id) + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str xml_str = "<text" xml_str += " action='" + action + "'" @@ -129,47 +113,33 @@ if self.text_string != None: xml_str+= " text_string='" + self.text_string + "'" if self.textcolor != None: xml_str += " color='" + self.textcolor + "'" xml_str += "/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str else: return '' def takedom(self, xml_dom): - self.log.log("Enter WhiteboardText->takedom(self, xml_dom)", ORPG_DEBUG) self.text_string = xml_dom.getAttribute("text_string") - self.log.log("self.text_string=" + self.text_string, ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("posy"): self.posy = int(xml_dom.getAttribute("posy")) - self.log.log("self.posy=" + str(self.posy), ORPG_DEBUG) if xml_dom.hasAttribute("posx"): self.posx = int(xml_dom.getAttribute("posx")) - self.log.log("self.posx=" + str(self.posx), ORPG_DEBUG) if xml_dom.hasAttribute("weight"): self.weight = int(xml_dom.getAttribute("weight")) self.font.SetWeight(self.weight) - self.log.log("self.weight=" + str(self.weight), ORPG_DEBUG) if xml_dom.hasAttribute("style"): self.style = int(xml_dom.getAttribute("style")) self.font.SetStyle(self.style) - self.log.log("self.style=" + str(self.style), ORPG_DEBUG) if xml_dom.hasAttribute("pointsize"): self.pointsize = int(xml_dom.getAttribute("pointsize")) self.font.SetPointSize(self.pointsize) - self.log.log("self.pointsize=" + str(self.pointsize), ORPG_DEBUG) if xml_dom.hasAttribute("color") and xml_dom.getAttribute("color") != '': self.textcolor = xml_dom.getAttribute("color") if self.textcolor == '#0000000': self.textcolor = '#000000' - self.log.log("self.textcolor=" + self.textcolor, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->takedom(self, xml_dom)", ORPG_DEBUG) class WhiteboardLine: def __init__(self, id, line_string, upperleft, lowerright, color="#000000", width=1, log=None): - self.log = log - self.log.log("Enter WhiteboardLine", ORPG_DEBUG) self.scale = 1 self.r_h = RGBHex() if color == '': color = "#000000" @@ -183,16 +153,14 @@ self.highlighted = False r,g,b = self.r_h.rgb_tuple(self.linecolor) self.highlight_color = self.r_h.hexstring(r^255, g^255, b^255) - self.log.log("Exit WhiteboardLine", ORPG_DEBUG) def highlight(self, highlight=True): - self.log.log("Enter WhiteboardLine->highlight(self, highlight)", ORPG_DEBUG) self.highlighted = highlight - self.log.log("Enter WhiteboardLine->highlight(self, highlight)", ORPG_DEBUG) - def set_line_props(self, line_string="", upperleftx=0, upperlefty=0, - lowerrightx=0, lowerrighty=0, color="#000000", width=1): - self.log.log("Enter WhiteboardLine->set_line_props(self, line_string, upperleftx, upperlefty, lowerrightx, lowerrighty, color, width)", ORPG_DEBUG) + def set_line_props(self, line_string="", + upperleftx=0, upperlefty=0, + lowerrightx=0, lowerrighty=0, + color="#000000", width=1): self.line_string = line_string self.upperleft.x = upperleftx self.upperleft.y = upperlefty @@ -200,28 +168,22 @@ self.lowerright.y = lowerrighty self.linecolor = color self.linewidth = width - self.log.log("Exit WhiteboardLine->set_line_props(self, line_string, upperleftx, upperlefty, lowerrightx, lowerrighty, color, width)", ORPG_DEBUG) def hit_test(self, pt): - self.log.log("Enter WhiteboardLine->hit_test(self, pt)", ORPG_DEBUG) coords = self.line_string.split(";") stcords = coords[0].split(",") oldicords = (int(stcords[0]),int(stcords[1])) for coordinate_string_counter in range(1, len(coords)): stcords = coords[coordinate_string_counter].split(",") if stcords[0] == "": - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return False", ORPG_DEBUG) return False icords = (int(stcords[0]),int(stcords[1])) if orpg.mapper.map_utils.proximity_test(oldicords,icords,pt,12): - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return True", ORPG_DEBUG) return True oldicords = icords - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return False", ORPG_DEBUG) return False def draw(self, parent, dc, op=wx.COPY): - self.log.log("Enter WhiteboardLine->draw(self, parent, dc, op=wx.COPY)", ORPG_DEBUG) self.scale = parent.canvas.layers['grid'].mapscale if self.highlighted: linecolor = self.highlight_color else: linecolor = self.linecolor @@ -248,14 +210,10 @@ dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) #selected outline - self.log.log("Exit WhiteboardLine->draw(self, parent, dc, op=wx.COPY)", ORPG_DEBUG) def toxml(self, action="update"): - self.log.log("Enter WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<line action='del' id='" + str(self.id) + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str # if there are any changes, make sure id is one of them xml_str = "<line" @@ -273,38 +231,26 @@ if self.linewidth != None: xml_str += " width='" + str(self.linewidth) + "'" xml_str += "/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) if action == "new": return xml_str return '' def takedom(self, xml_dom): - self.log.log("Enter WhiteboardLine->takedom(self, xml_dom)", ORPG_DEBUG) self.line_string = xml_dom.getAttribute("line_string") - self.log.log("self.line_string=" + self.line_string, ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("upperleftx"): self.upperleft.x = int(xml_dom.getAttribute("upperleftx")) - self.log.log("self.upperleft.x=" + str(self.upperleft.x), ORPG_DEBUG) if xml_dom.hasAttribute("upperlefty"): self.upperleft.y = int(xml_dom.getAttribute("upperlefty")) - self.log.log("self.upperleft.y=" + str(self.upperleft.y), ORPG_DEBUG) if xml_dom.hasAttribute("lowerrightx"): self.lowerright.x = int(xml_dom.getAttribute("lowerrightx")) - self.log.log("self.lowerright.x=" + str(self.lowerright.x), ORPG_DEBUG) if xml_dom.hasAttribute("lowerrighty"): self.lowerright.y = int(xml_dom.getAttribute("lowerrighty")) - self.log.log("self.lowerright.y=" + str(self.lowerright.y), ORPG_DEBUG) if xml_dom.hasAttribute("color") and xml_dom.getAttribute("color") != '': self.linecolor = xml_dom.getAttribute("color") if self.linecolor == '#0000000': self.linecolor = '#000000' - self.log.log("self.linecolor=" + self.linecolor, ORPG_DEBUG) if xml_dom.hasAttribute("width"): self.linewidth = int(xml_dom.getAttribute("width")) - self.log.log("self.linewidth=" + str(self.linewidth), ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->takedom(self, xml_dom)", ORPG_DEBUG) ##----------------------------- ## whiteboard layer @@ -313,8 +259,6 @@ def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter whiteboard_layer", ORPG_DEBUG) layer_base.__init__(self) self.r_h = RGBHex() self.id = -1 @@ -324,64 +268,48 @@ self.color = "#000000" self.width = 1 self.removedLines = [] - self.log.log("Exit whiteboard_layer", ORPG_DEBUG) def next_serial(self): - self.log.log("Enter whiteboard_layer->next_serial(self)", ORPG_DEBUG) self.serial_number += 1 - self.log.log("Exit whiteboard_layer->next_serial(self)", ORPG_DEBUG) return self.serial_number def get_next_highest_z(self): - self.log.log("Enter whiteboard_layer->get_next_highest_z(self)", ORPG_DEBUG) z = len(self.lines)+1 - self.log.log("Exit whiteboard_layer->get_next_highest_z(self)", ORPG_DEBUG) return z def cleanly_collapse_zorder(self): - self.log.log("Enter/Exit whiteboard_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) + pass def collapse_zorder(self): - self.log.log("Enter/Exit whiteboard_layer->collapse_zorder(self)", ORPG_DEBUG) + pass def rollback_serial(self): - self.log.log("Enter whiteboard_layer->rollback_serial(self)", ORPG_DEBUG) self.serial_number -= 1 - self.log.log("Exit whiteboard_layer->rollback_serial(self)", ORPG_DEBUG) def add_line(self, line_string="", upperleft=cmpPoint(0,0), lowerright=cmpPoint(0,0), color="#000000", width=1): - self.log.log("Enter whiteboard_layer->add_line(self, line_string, upperleft, lowerright, color, width)", ORPG_DEBUG) id = 'line-' + str(self.next_serial()) - line = WhiteboardLine(id, line_string, upperleft, lowerright, color=self.color, width=self.width, log=self.log) + line = WhiteboardLine(id, line_string, upperleft, lowerright, color=self.color, width=self.width) self.lines.append(line) xml_str = "<map><whiteboard>" xml_str += line.toxml("new") xml_str += "</whiteboard></map>" self.canvas.frame.session.send(xml_str) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->add_line(self, line_string, upperleft, lowerright, color, width)", ORPG_DEBUG) return line def get_line_by_id(self, id): - self.log.log("Enter whiteboard_layer->get_line_by_id(self, id)", ORPG_DEBUG) for line in self.lines: if str(line.id) == str(id): - self.log.log("Exit whiteboard_layer->get_line_by_id(self, id) return LineID: " + str(id), ORPG_DEBUG) return line - self.log.log("Exit whiteboard_layer->get_line_by_id(self, id) return None", ORPG_DEBUG) return None def get_text_by_id(self, id): - self.log.log("Enter whiteboard_layer->get_text_by_id(self, id)", ORPG_DEBUG) for text in self.texts: if str(text.id) == str(id): - self.log.log("Exit whiteboard_layer->get_text_by_id(self, id) return textID: " + str(id), ORPG_DEBUG) return text - self.log.log("Enter whiteboard_layer->get_text_by_id(self, id) return None", ORPG_DEBUG) return None def del_line(self, line): - self.log.log("Enter whiteboard_layer->del_line(self, line)", ORPG_DEBUG) xml_str = "<map><whiteboard>" xml_str += line.toxml("del") xml_str += "</whiteboard></map>" @@ -390,7 +318,6 @@ self.lines.remove(line) self.removedLines.append(line) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->del_line(self, line)", ORPG_DEBUG) def undo_line(self): if len(self.removedLines)>0: @@ -400,14 +327,11 @@ self.canvas.Refresh(True) def del_all_lines(self): - self.log.log("Enter whiteboard_layer->del_all_lines(self)", ORPG_DEBUG) for i in xrange(len(self.lines)): self.del_line(self.lines[0]) print self.lines - self.log.log("Exit whiteboard_layer->del_all_lines(self)", ORPG_DEBUG) def del_text(self, text): - self.log.log("Enter whiteboard_layer->del_text(self, text)", ORPG_DEBUG) xml_str = "<map><whiteboard>" xml_str += text.toxml("del") xml_str += "</whiteboard></map>" @@ -415,87 +339,64 @@ if text: self.texts.remove(text) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->del_text(self, text)", ORPG_DEBUG) def layerDraw(self, dc): - self.log.log("Enter whiteboard_layer->layerDraw(self, dc)", ORPG_DEBUG) for m in self.lines: m.draw(self, dc) for m in self.texts: m.draw(self,dc) - self.log.log("Exit whiteboard_layer->layerDraw(self, dc)", ORPG_DEBUG) def hit_test_text(self, pos, dc): - self.log.log("Enter whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) list_of_texts_matching = [] if self.canvas.layers['fog'].use_fog == 1: if self.canvas.frame.session.role != "GM": - self.log.log("Exit whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) return list_of_texts_matching for m in self.texts: if m.hit_test(pos,dc): list_of_texts_matching.append(m) - self.log.log("Exit whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) return list_of_texts_matching def hit_test_lines(self, pos, dc): - self.log.log("Enter whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) list_of_lines_matching = [] if self.canvas.layers['fog'].use_fog == 1: if self.canvas.frame.session.role != "GM": - self.log.log("Exit whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) return list_of_lines_matching for m in self.lines: if m.hit_test(pos): list_of_lines_matching.append(m) - self.log.log("Exit whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) return list_of_lines_matching def find_line(self, pt): - self.log.log("Enter whiteboard_layer->find_line(self, pt)", ORPG_DEBUG) scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc ) dc.SetUserScale(scale,scale) line_list = self.hit_test_lines(pt,dc) if line_list: - self.log.log("Exit whiteboard_layer->find_line(self, pt)", ORPG_DEBUG) return line_list[0] else: - self.log.log("Exit whiteboard_layer->find_line(self, pt) return None", ORPG_DEBUG) return None def setcolor(self, color): - self.log.log("Enter whiteboard_layer->setcolor(self, color)", ORPG_DEBUG) r,g,b = color.Get() self.color = self.r_h.hexstring(r,g,b) - self.log.log("Exit whiteboard_layer->setcolor(self, color)", ORPG_DEBUG) def sethexcolor(self, hexcolor): - self.log.log("Enter whiteboard_layer->sethexcolor(self, hexcolor)", ORPG_DEBUG) self.color = hexcolor - self.log.log("Exit whiteboard_layer->sethexcolor(self, hexcolor)", ORPG_DEBUG) def setwidth(self, width): - self.log.log("Enter whiteboard_layer->setwidth(self, width)", ORPG_DEBUG) self.width = int(width) - self.log.log("Exit whiteboard_layer->setwidth(self, width)", ORPG_DEBUG) def set_font(self, font): - self.log.log("Enter whiteboard_layer->set_font(self, font)", ORPG_DEBUG) self.font = font - self.log.log("Exit whiteboard_layer->set_font(self, font)", ORPG_DEBUG) def add_text(self, text_string, pos, style, pointsize, weight, color="#000000"): - self.log.log("Enter whiteboard_layer->add_text(self, text_string, pos, style, pointsize, weight, color)", ORPG_DEBUG) id = 'text-' + str(self.next_serial()) - text = WhiteboardText(id,text_string, pos, style, pointsize, weight, color, self.log) + text = WhiteboardText(id,text_string, pos, style, pointsize, weight, color) self.texts.append(text) xml_str = "<map><whiteboard>" xml_str += text.toxml("new") xml_str += "</whiteboard></map>" self.canvas.frame.session.send(xml_str) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->add_text(self, text_string, pos, style, pointsize, weight, color)", ORPG_DEBUG) def draw_working_line(self, dc, line_string): - self.log.log("Enter whiteboard_layer->draw_working_line(self, dc, line_string)", ORPG_DEBUG) scale = self.canvas.layers['grid'].mapscale dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) @@ -517,11 +418,9 @@ y2 = y1 dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) - self.log.log("Exit whiteboard_layer->draw_working_line(self, dc, line_string)", ORPG_DEBUG) def layerToXML(self, action="update"): """ format """ - self.log.log("Enter whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) white_string = "" if self.lines: for l in self.lines: white_string += l.toxml(action) @@ -533,15 +432,11 @@ s += ">" s += white_string s += "</whiteboard>" - self.log.log(s, ORPG_DEBUG) - self.log.log("Exit whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s else: - self.log.log("Exit whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter whiteboard_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) serial_number = xml_dom.getAttribute('serial') if serial_number != "": self.serial_number = int(serial_number) children = xml_dom._get_childNodes() @@ -553,12 +448,9 @@ if nodename == 'line': line = self.get_line_by_id(id) if line != None: self.lines.remove(line) - else: self.log.log("Whiteboard error: Deletion of unknown line object attempted.", ORPG_GENERAL) elif nodename == 'text': text = self.get_text_by_id(id) if text != None: self.texts.remove(text) - else: self.log.log("Whiteboard error: Deletion of unknown text object attempted.", ORPG_GENERAL) - else: self.log.log("Whiteboard error: Deletion of unknown whiteboard object attempted.", ORPG_GENERAL) elif action == "new": if nodename == "line": try: @@ -575,10 +467,8 @@ width = int(l.getAttribute('width')) except: line_string = upperleftx = upperlefty = lowerrightx = lowerrighty = color = 0 - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("invalid line", ORPG_GENERAL) continue - line = WhiteboardLine(id, line_string, upperleft, lowerright, color, width, self.log) + line = WhiteboardLine(id, line_string, upperleft, lowerright, color, width) self.lines.append(line) elif nodename == "text": try: @@ -595,26 +485,21 @@ pos.x = int(posx) pos.y = int(posy) except: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("invalid line", ORPG_GENERAL) continue - text = WhiteboardText(id, text_string, pos, style, pointsize, weight, color, self.log) + text = WhiteboardText(id, text_string, pos, style, pointsize, weight, color) self.texts.append(text) else: if nodename == "line": line = self.get_line_by_id(id) if line: line.takedom(l) - else: self.log.log("Whiteboard error: Update of unknown line attempted.", ORPG_GENERAL) if nodename == "text": text = self.get_text_by_id(id) if text: text.takedom(l) - else: self.log.log("Whiteboard error: Update of unknown text attempted.", ORPG_GENERAL) - self.log.log("Enter whiteboard_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) #self.canvas.send_map_data() def add_temp_line(self, line_string): line = WhiteboardLine(0, line_string, wx.Point(0,0), wx.Point(0,0), - color=self.color, width=self.width, log=self.log) + color=self.color, width=self.width) self.lines.append(line) return line
--- a/orpg/mapper/whiteboard_handler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/mapper/whiteboard_handler.py Thu Aug 27 01:04:43 2009 -0500 @@ -68,8 +68,8 @@ self.live_refresh = wx.CheckBox(self, wx.ID_ANY, " Live Refresh") self.live_refresh.SetValue(True) self.widthList= wx.Choice(self, wx.ID_ANY, size= wx.Size(40, 20), - choices=['1','2','3','4','5','6','7','8','9','10']) - self.widthList.SetSelection(0) #always start showing "1" + choices=['1','2','3','4','5','6','7','8','9','10']) + self.widthList.SetSelection(0) self.sizer.Add(wx.StaticText(self, wx.ID_ANY, "Line Width: "),0,wx.ALIGN_CENTER) self.sizer.Add(self.widthList, 0, wx.EXPAND) self.sizer.Add(wx.Size(10,25)) @@ -104,8 +104,10 @@ self.txt_boxer.Add(self.text_control,1,wx.EXPAND) self.point_boxer = wx.BoxSizer(wx.HORIZONTAL) self.point_static = wx.StaticText(self.text_properties_dialog, -1, "Text Size: ") - self.point_control = wx.SpinCtrl(self.text_properties_dialog, wx.ID_ANY, value = "12", - min = 1, initial = 12, name = "Font Size: ") + self.point_control = wx.SpinCtrl(self.text_properties_dialog, + wx.ID_ANY, value = "12", + min = 1, initial = 12, + name = "Font Size: ") self.point_boxer.Add(self.point_static,1,wx.EXPAND) self.point_boxer.Add(wx.Size(10,10)) self.point_boxer.Add(self.point_control,0,wx.EXPAND) @@ -261,7 +263,7 @@ def undo_line(self,evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.use_roles()): - self.top_frame.openrpg.get_component("chat").InfoPost("You must be a GM to use this feature") + self.top_frame.openrpg.get("chat").InfoPost("You must be a GM to use this feature") return self.canvas.layers['whiteboard'].undo_line() dc = self.create_dc() @@ -272,9 +274,11 @@ def delete_all_lines(self,evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be a GM to use this feature") + component.get("chat").InfoPost("You must be a GM to use this feature") return - dlg = wx.MessageDialog(self, "Are you sure you want to delete all lines?","Delete All Lines",wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) + dlg = wx.MessageDialog(self, + "Are you sure you want to delete all lines?","Delete All Lines", + wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() != wx.ID_YES: return self.canvas.layers['whiteboard'].del_all_lines() dc = self.create_dc() @@ -436,7 +440,7 @@ #check to role to make sure user can draw at all.... session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) else: line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) #resetting variables for next line @@ -472,7 +476,7 @@ #check to role to make sure user can draw at all.... session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) else: line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) #resetting variables for next line @@ -534,8 +538,8 @@ # to allow alternate drawing method to be used # 05-09-2003 Snowdog def freeform_motion(self, evt): -# if not self.drawing: -# return + #if not self.drawing: + # return scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc ) @@ -566,7 +570,7 @@ self.drawing = False session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) return #self.id +=1 @@ -584,7 +588,7 @@ def on_text_left_down(self, evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) return scale = self.canvas.layers['grid'].mapscale @@ -618,7 +622,7 @@ def on_text_right_down(self, evt, dc): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) return pos = evt.GetLogicalPosition(dc) @@ -632,7 +636,7 @@ def on_start_cone(self, evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) return self.cone_start = self.get_snapped_to_logical_pos(evt) @@ -748,7 +752,7 @@ def draw_temporary_circle(self, evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM) and (session.my_role()!=session.ROLE_PLAYER) and (session.use_roles()): - open_rpg.get_component("chat").InfoPost("You must be either a player or GM to use this feature") + component.get("chat").InfoPost("You must be either a player or GM to use this feature") self.canvas.Refresh(False) return pos = self.get_snapped_to_logical_pos(evt)
--- a/orpg/networking/gsclient.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/gsclient.py Thu Aug 27 01:04:43 2009 -0500 @@ -28,13 +28,13 @@ __version__ = "$Id: gsclient.py,v 1.53 2007/10/25 21:49:34 digitalxero Exp $" -import orpg.dirpath +from orpg.dirpath import dir_struct from orpg.orpg_windows import * -from orpg.orpg_xml import * import meta_server_lib import orpg.tools.orpg_settings +from orpg.tools.orpg_settings import settings import orpg.tools.rgbhex -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component import traceback gs_host = 1 @@ -99,13 +99,10 @@ def __init__(self,parent): wx.Panel.__init__(self, parent, -1) self.parent = parent - self.log = open_rpg.get_component('log') - self.log.log("Enter game_server_panel", ORPG_DEBUG) - self.password_manager = open_rpg.get_component('password_manager') # passtool --SD 8/03 - self.frame = open_rpg.get_component('frame') - self.session = open_rpg.get_component('session') - self.settings = open_rpg.get_component('settings') - self.xml = open_rpg.get_component('xml') + self.password_manager = component.get('password_manager') # passtool --SD 8/03 + self.frame = component.get('frame') + self.session = component.get('session') + self.xml = component.get('xml') #Not used?? self.serverNameSet = 0 self.last_motd = "" self.buttons = {} @@ -114,14 +111,11 @@ self.build_ctrls() self.refresh_server_list() self.refresh_room_list() - self.log.log("Exit game_server_panel", ORPG_DEBUG) #--------------------------------------------------------- # [START] Snowdog: Updated Game Server Window 12/02 #--------------------------------------------------------- def build_ctrls(self): - self.log.log("Enter game_server_panel->build_ctrls(self)", ORPG_DEBUG) - ## Section Sizers (with frame edges and text captions) self.box_sizers = {} self.box_sizers["server"] = wx.StaticBox(self, -1, "Server") @@ -237,7 +231,6 @@ self.cur_room_index = -1 self.cur_server_index = -1 self.rmList = {} - self.log.log("Exit game_server_panel->build_ctrls(self)", ORPG_DEBUG) #--------------------------------------------------------- # [END] Snowdog: Updated Game Server Window 12/02 @@ -249,8 +242,6 @@ # 5/16/05 -- Snowdog #----------------------------------------------------- def on_server_dbclick(self, evt=None): - self.log.log("Enter game_server_panel->on_server_dbclick(self, evt)", ORPG_DEBUG) - #make sure address is updated just in case list select wasn't done try: self.on_select(evt) @@ -265,7 +256,6 @@ #address differs, disconnect. self.frame.kill_mplay_session() self.do_connect(address) - self.log.log("Exit game_server_panel->on_server_dbclick(self, evt)", ORPG_DEBUG) #----------------------------------------------------- @@ -275,8 +265,6 @@ #----------------------------------------------------- def on_room_dbclick(self, evt=None): - self.log.log("Enter game_server_panel->on_room_dbclick(self, evt)", ORPG_DEBUG) - #make sure address is updated just in case list select wasn't done try: self.on_select(evt) @@ -302,11 +290,9 @@ else: pwd = "" self.session.send_join_group(group_id, pwd) - self.log.log("Exit game_server_panel->on_room_dbclick(self, evt)", ORPG_DEBUG) def on_select(self,evt): - self.log.log("Enter game_server_panel->on_select(self,evt)", ORPG_DEBUG) id = evt.GetId() if id == LIST_ROOM: self.cur_room_index = evt.m_itemIndex @@ -317,19 +303,15 @@ port = self.svrList[self.cur_server_index].port self.texts["address"].SetValue(address+":"+str(port)) self.refresh_room_list() - self.log.log("Exit game_server_panel->on_select(self,evt)", ORPG_DEBUG) def on_text(self,evt): - self.log.log("Enter game_server_panel->on_text(self,evt)", ORPG_DEBUG) id = evt.GetId() if (id == ADDRESS) and (self.cur_server_index >= 0): #print "ADDRESS id = ", id, "index = ", self.cur_server_index self.cur_server_index = -1 evt.Skip() - self.log.log("Exit game_server_panel->on_text(self,evt)", ORPG_DEBUG) def add_room(self,data): - self.log.log("Enter game_server_panel->add_room(self,data)", ORPG_DEBUG) i = self.room_list.GetItemCount() if (data[2]=="1") or (data[2]=="True"): pwd="yes" else: pwd="no" @@ -338,21 +320,17 @@ self.room_list.SetStringItem(i,2,pwd) self.room_list.SetItemData(i,int(data[0])) self.refresh_room_list() - self.log.log("Exit game_server_panel->add_room(self,data)", ORPG_DEBUG) def del_room(self, data): - self.log.log("Enter game_server_panel->del_room(self, data)", ORPG_DEBUG) i = self.room_list.FindItemData(-1, int(data[0])) self.room_list.DeleteItem(i) self.refresh_room_list() - self.log.log("Exit game_server_panel->del_room(self, data)", ORPG_DEBUG) #--------------------------------------------------------- # [START] Snowdog Password/Room Name altering code 12/02 #--------------------------------------------------------- def update_room(self,data): - self.log.log("Enter game_server_panel->update_room(self,data)", ORPG_DEBUG) #------------------------------------------------------- # Udated 12/02 by Snowdog @@ -365,7 +343,6 @@ self.room_list.SetStringItem(i,1,data[3]) self.room_list.SetStringItem(i,2,pwd) self.refresh_room_list() - self.log.log("Exit game_server_panel->update_room(self,data)", ORPG_DEBUG) #--------------------------------------------------------- # [END] Snowdog Password/Room Name altering code 12/02 @@ -377,12 +354,9 @@ #self.sizers["room"].Layout() def set_lobbybutton(self,allow): - self.log.log("Enter game_server_panel->set_lobbybutton(self,allow)", ORPG_DEBUG) self.buttons[GS_JOINLOBBY].Enable(allow) - self.log.log("Exit game_server_panel->set_lobbybutton(self,allow)", ORPG_DEBUG) def set_connected(self,connected): - self.log.log("Enter game_server_panel->set_connected(self,connected)", ORPG_DEBUG) self.buttons[GS_CONNECT].Enable(not connected) self.buttons[GS_DISCONNECT].Enable(connected) self.buttons[GS_JOIN].Enable(connected) @@ -397,10 +371,8 @@ #data = self.session.get_my_group() self.frame.status.set_connect_status(self.name) self.set_cur_room_text("Lobby") - self.log.log("Exit game_server_panel->set_connected(self,connected)", ORPG_DEBUG) def on_button(self,evt): - self.log.log("Enter game_server_panel->son_button(self,evt)", ORPG_DEBUG) id = evt.GetId() if id == GS_CONNECT: address = self.texts["address"].GetValue() @@ -410,18 +382,12 @@ except: self.name = `address` self.do_connect(address) - elif id == GS_DISCONNECT: - self.frame.kill_mplay_session() - elif id == GS_CREATE_ROOM: - self.do_create_group() - elif id == GS_JOIN: - self.do_join_group() - elif id == GS_JOINLOBBY: - self.do_join_lobby() - elif id == GS_SERVER_REFRESH: - self.refresh_server_list() - elif id == GS_PWD: - self.texts["room_pwd"].Enable(evt.Checked()) + elif id == GS_DISCONNECT: self.frame.kill_mplay_session() + elif id == GS_CREATE_ROOM: self.do_create_group() + elif id == GS_JOIN: self.do_join_group() + elif id == GS_JOINLOBBY: self.do_join_lobby() + elif id == GS_SERVER_REFRESH: self.refresh_server_list() + elif id == GS_PWD: self.texts["room_pwd"].Enable(evt.Checked()) elif id == OR_CLOSE: dlg = wx.MessageDialog(self,"Quit OpenRPG?","OpenRPG",wx.YES_NO) if dlg.ShowModal() == wx.ID_YES: @@ -430,10 +396,8 @@ self.frame.closed_confirmed() elif id == GS_CLOSE: self.parent.OnMB_GameServerBrowseServers() - self.log.log("Exit game_server_panel->son_button(self,evt)", ORPG_DEBUG) def refresh_room_list(self): - self.log.log("Enter game_server_panel->refresh_room_list(self)", ORPG_DEBUG) self.room_list.DeleteAllItems() address = self.texts["address"].GetValue() try: @@ -458,31 +422,24 @@ self.colorize_group_list(groups) self.room_list.SortItems(roomCmp) wx.CallAfter(self.autosizeRooms) - self.log.log("Exit game_server_panel->refresh_room_list(self)", ORPG_DEBUG) def autosizeRooms(self): - self.log.log("Enter game_server_panel->autosizeRooms(self)", ORPG_DEBUG) self.room_list.SetColumnWidth(0, wx.LIST_AUTOSIZE) - #self.room_list.SetColumnWidth(1, wx.LIST_AUTOSIZE) - #self.room_list.SetColumnWidth(2, wx.LIST_AUTOSIZE) if self.room_list.GetColumnWidth(0) < 70: self.room_list.SetColumnWidth(0, 70) if self.room_list.GetColumnWidth(1) < 70: self.room_list.SetColumnWidth(1, 70) if self.room_list.GetColumnWidth(2) < 50: self.room_list.SetColumnWidth(2, 50) - self.log.log("Exit game_server_panel->autosizeRooms(self)", ORPG_DEBUG) def refresh_server_list(self): - self.log.log("Enter game_server_panel->refresh_server_list(self)", ORPG_DEBUG) - try: self.svrList = [] self.server_list.DeleteAllItems() xml_dom = meta_server_lib.get_server_list(["2"]); node_list = xml_dom.getElementsByTagName('server') hex = orpg.tools.rgbhex.RGBHex() - color1 = self.settings.get_setting("RoomColor_Active") - color2 = self.settings.get_setting("RoomColor_Locked") - color3 = self.settings.get_setting("RoomColor_Empty") - color4 = self.settings.get_setting("RoomColor_Lobby") + color1 = settings.get_setting("RoomColor_Active") + color2 = settings.get_setting("RoomColor_Locked") + color3 = settings.get_setting("RoomColor_Empty") + color4 = settings.get_setting("RoomColor_Lobby") if len(node_list): length = len(node_list) @@ -490,7 +447,9 @@ partLength = 1.0/length for n in node_list: if n.hasAttribute('id') and n.hasAttribute('name') and n.hasAttribute('num_users') and n.hasAttribute('address') and n.hasAttribute('port'): - self.svrList.append( server_instance(n.getAttribute('id'),n.getAttribute('name'), n.getAttribute('num_users'), n.getAttribute('address'),n.getAttribute('port'))) + self.svrList.append(server_instance(n.getAttribute('id'), n.getAttribute('name'), + n.getAttribute('num_users'), n.getAttribute('address'), + n.getAttribute('port'))) address = n.getAttribute('address') + ':' + n.getAttribute('port') self.rmList[address] = [] rooms = n.getElementsByTagName('room') @@ -553,10 +512,8 @@ except Exception, e: print "Server List not available." traceback.print_exc() - self.log.log("Exit game_server_panel->refresh_server_list(self)", ORPG_DEBUG) def failed_connection(self): - self.log.log("Enter game_server_panel->failed_connection(self)", ORPG_DEBUG) if(self.cur_server_index >= 0): id = self.servers[self.cur_server_index].getAttribute('id') meta = self.servers[self.cur_server_index].getAttribute('meta') @@ -566,28 +523,22 @@ # was removed. If it was, refresh the display if(meta_server_lib.post_failed_connection(id,meta=meta,address=address,port=port)): self.refresh_server_list() - self.log.log("Exit game_server_panel->failed_connection(self)", ORPG_DEBUG) def do_connect(self, address): - self.log.log("Enter game_server_panel->do_connect(self, address)", ORPG_DEBUG) - chat = open_rpg.get_component('chat') + chat = component.get('chat') chat.InfoPost("Locating server at " + address + "...") if self.session.connect(address): self.frame.start_timer() else: chat.SystemPost("Failed to connect to game server...") self.failed_connection() - self.log.log("Exit game_server_panel->do_connect(self, address)", ORPG_DEBUG) def do_join_lobby(self): - self.log.log("Enter game_server_panel->do_join_lobby(self)", ORPG_DEBUG) self.cur_room_index = 0 self.session.send_join_group("0","") self.set_lobbybutton(0); - self.log.log("Exit game_server_panel->do_join_lobby(self)", ORPG_DEBUG) def do_join_group(self): - self.log.log("Enter game_server_panel->do_join_group(self)", ORPG_DEBUG) if self.cur_room_index >= 0: if self.cur_room_index != 0: self.set_lobbybutton(1); @@ -606,10 +557,8 @@ pwd = "" if pwd != None: #pwd==None means the user clicked "Cancel" self.session.send_join_group(group_id,pwd) - self.log.log("Exit game_server_panel->do_join_group(self)", ORPG_DEBUG) def do_create_group(self): - self.log.log("Enter game_server_panel->do_create_group(self)", ORPG_DEBUG) name = self.texts["room_name"].GetValue() boot_pwd = self.texts["room_boot_pwd"].GetValue() minversion = self.texts["room_min_version"].GetValue() @@ -654,7 +603,6 @@ self.session.send( msg ) self.session.send_create_group(name,pwd,boot_pwd,minversion) self.set_lobbybutton(1); #enable the Lobby quickbutton - self.log.log("Exit game_server_panel->do_create_group(self)", ORPG_DEBUG) #--------------------------------------------------------- @@ -676,39 +624,31 @@ def colorize_group_list(self, groups): - self.log.log("Enter game_server_panel->colorize_group_list(self, groups)", ORPG_DEBUG) - try: hex = orpg.tools.rgbhex.RGBHex() -# activ = self.settings.get_setting("RoomColor_Active") -# lockt = self.settings.get_setting("RoomColor_Locked") -# empty = self.settings.get_setting("RoomColor_Empty") -# lobby = self.settings.get_setting("RoomColor_Lobby") -#renamed colors - TaS sirebral for gr in groups: item_list_location = self.room_list.FindItemData(-1,int(gr[0])) if item_list_location != -1: item = self.room_list.GetItem(item_list_location) if gr[0] == "0": -# active_state = lobby - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Lobby")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Lobby")) elif gr[3] <> "0": -# active_state = activ + if gr[2] == "True" or gr[2] == "1": -# active_state = lockt - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Locked")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Locked")) else: -# active_state = activ - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Active")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Active")) else: -# active_state = empty - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Empty")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Empty")) -# r,g,b = hex.rgb_tuple(active_state) + color = wx.Colour(red=r,green=g,blue=b) item.SetTextColour(color) self.room_list.SetItem(item) except: traceback.print_exc() - self.log.log("Exit game_server_panel->colorize_group_list(self, groups)", ORPG_DEBUG)
--- a/orpg/networking/meta_server_lib.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/meta_server_lib.py Thu Aug 27 01:04:43 2009 -0500 @@ -34,9 +34,9 @@ __version__ = "$Id: meta_server_lib.py,v 1.40 2007/04/04 01:18:42 digitalxero Exp $" from orpg.orpg_version import PROTOCOL_VERSION -from orpg.orpg_xml import * -import orpg.dirpath -import orpg.tools.validate +from orpg.orpgCore import component +from orpg.tools.validate import validate +from orpg.dirpath import dir_struct import urllib import orpg.minidom from threading import * @@ -69,8 +69,7 @@ # Remove any leading or trailing data. This can happen on some satellite connections p = re.compile('(<servers>.*?</servers>)',re.DOTALL|re.IGNORECASE) mo = p.search(data) - if mo: - data = mo.group(0) + if mo: data = mo.group(0) if META_DEBUG: print @@ -79,16 +78,12 @@ print data print # build dom - xml_dom = parseXml(data) + xml = component.get('xml') + xml_dom = xml.parseXml(data) xml_dom = xml_dom._get_documentElement() return xml_dom def post_server_data( name, realHostName=None): - # build POST data -## data = urllib.urlencode( {"server_data[name]":name, -## "server_data[version]":PROTOCOL_VERSION, -## "act":"new"} ) -## if realHostName: data = urllib.urlencode( {"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, @@ -101,7 +96,9 @@ "server_data[version]":PROTOCOL_VERSION, "act":"new"} ) - xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php") + #xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php")#Sourceforge still? + path = component.get('settings').get_setting('MetaServerBaseURL') #getMetaServerBaseURL() + xml_dom = get_server_dom(data, path) ret_val = int( xml_dom.getAttribute( "id" ) ) return ret_val @@ -109,10 +106,10 @@ # For now, turning this off. This needs to be re-vamped for # handling multiple Metas. return 0 -# data = urllib.urlencode({"id":id,"act":"failed"}); -# xml_dom = get_server_dom(data) -# ret_val = int(xml_dom.getAttribute("return")) -# return ret_val + #data = urllib.urlencode({"id":id,"act":"failed"}); + #xml_dom = get_server_dom(data) + #ret_val = int(xml_dom.getAttribute("return")) + #return ret_val def remove_server(id): data = urllib.urlencode({"id":id,"act":"del"}); @@ -125,15 +122,11 @@ # This function is used to easily sort a list of nodes # by their start time - if first.hasAttribute("start"): - first_start = int(first.getAttribute("start")) - else: - first_start = 0 + if first.hasAttribute("start"): first_start = int(first.getAttribute("start")) + else: first_start = 0 - if second.hasAttribute("start"): - second_start = int(second.getAttribute("start")) - else: - second_start = 0 + if second.hasAttribute("start"): second_start = int(second.getAttribute("start")) + else: second_start = 0 # Return the result of the cmp function on the two strings return cmp(first_start,second_start) @@ -144,18 +137,13 @@ # Ensure there is something to sort with for each - if first.hasAttribute("name"): - first_name = str(first.getAttribute("name")).lower() - else: - first_name = "" + if first.hasAttribute("name"): first_name = str(first.getAttribute("name")).lower() + else: first_name = "" - if second.hasAttribute("name"): - second_name = str(second.getAttribute("name")).lower() - else: - second_name = "" + if second.hasAttribute("name"): second_name = str(second.getAttribute("name")).lower() + else: second_name = "" # Return the result of the cmp function on the two strings - return cmp(first_name,second_name) @@ -171,11 +159,10 @@ for meta in all_metas: # check all of the metas - # get the server's xml from the current meta + #get the server's xml from the current meta bad_meta = 0 #print "Getting server list from " + meta + "..." - try: - xml_dom = get_server_dom(data=data,path=meta) + try: xml_dom = get_server_dom(data=data,path=meta) except: #print "Trouble getting servers from " + meta + "..." bad_meta = 1 @@ -198,17 +185,13 @@ # set them from current node - if not n.hasAttribute('name'): - n.setAttribute('name','NO_NAME_GIVEN') + if not n.hasAttribute('name'): n.setAttribute('name','NO_NAME_GIVEN') name = n.getAttribute('name') - if not n.hasAttribute('num_users'): - n.setAttribute('num_users','N/A') + if not n.hasAttribute('num_users'): n.setAttribute('num_users','N/A') num_users = n.getAttribute('num_users') - if not n.hasAttribute('address'): - n.setAttribute('address','NO_ADDRESS_GIVEN') + if not n.hasAttribute('address'): n.setAttribute('address','NO_ADDRESS_GIVEN') address = n.getAttribute('address') - if not n.hasAttribute('port'): - n.setAttribute('port','6774') + if not n.hasAttribute('port'): n.setAttribute('port','6774') port = n.getAttribute('port') n.setAttribute('meta',meta) end_point = str(address) + ":" + str(port) @@ -228,14 +211,11 @@ # sort them by their name attribute. Uses byNameAttribute() # defined above as a comparison function - if sort_by == "start": - return_list.sort(byStartAttribute) - elif sort_by == "name": - return_list.sort(byNameAttribute) + if sort_by == "start": return_list.sort(byStartAttribute) + elif sort_by == "name": return_list.sort(byNameAttribute) # Add each node to the DOM - for n in return_list: - return_dom.appendChild(n) + for n in return_list: return_dom.appendChild(n) return return_dom ## List Format: @@ -257,7 +237,7 @@ if META_DEBUG: print " Meta List ("+str(len(metas))+" servers)" try: metacache_lock.acquire() - ini = open(orpg.dirpath.dir_struct["user"]+"metaservers.cache","w") + ini = open(dir_struct["user"]+"metaservers.cache","w") for meta in metas: if META_DEBUG: print " Writing: "+str(meta.getAttribute('path')) ini.write(str(meta.getAttribute('path')) + " " + str(meta.getAttribute('versions')) + "\n") @@ -273,8 +253,8 @@ try: metacache_lock.acquire() # Read in the metas - orpg.tools.validate.Validate().config_file("metaservers.cache","metaservers.cache") - ini = open(orpg.dirpath.dir_struct["user"]+"metaservers.cache","r") + validate.config_file("metaservers.cache","metaservers.cache") + ini = open(dir_struct["user"]+"metaservers.cache","r") metas = ini.readlines() ini.close() return metas @@ -286,23 +266,27 @@ return [] def getMetaServers(versions = None, pick_random=0): - # get meta server URLs as a list + """ + get meta server URLs as a list - # versions is a list of acceptable version numbers. - # A False truth value will use getMetaServerBaseURL() + versions is a list of acceptable version numbers. + A False truth value will use getMetaServerBaseURL() - # set a default if we have weird reading problems - # default_url = "http://www.openrpg.com/openrpg_servers.php" + set a default if we have weird reading problems + default_url = "http://www.openrpg.com/openrpg_servers.php" + """ meta_names = [] if(versions): # If versions are supplied, then look in metaservers.conf try: - # read in the metas from file - # format of file is one meta entry per line - # each entry will be the meta url, followed by one or more version numbers that it - # handle. Generally, this will be either a 1 for the original Meta format, or - # 2 for the new one. + """ + read in the metas from file + format of file is one meta entry per line + each entry will be the meta url, followed by one or more version numbers that it + handle. Generally, this will be either a 1 for the original Meta format, or + 2 for the new one. + """ # Read in the metas metas = getRawMetaList() @@ -315,13 +299,10 @@ # split the line on whitespace # obviously, your meta servers urls shouldn't contain whitespace. duh. words = meta.split() - success = 0 # init success flag for version check - for version in versions: # run through each allowed version from caller if version in words[1:]: # if the allowed version token was found success += 1 # then increment the success indicator - if success: # if the meta entry is acceptable to the caller meta_names.append(words[0]) # add the entry if META_DEBUG: print "adding metaserver " + meta @@ -330,8 +311,8 @@ if not meta_names: default_meta = getMetaServerBaseURL() # grab the meta from ini.xml meta_names.append(default_meta) # add it to the return list -# print "Warning!!\nNo valid metaservers cached." -# print "Using meta from MetaServerBaseURL: " + default_meta + "\n" + # print "Warning!!\nNo valid metaservers cached." + # print "Using meta from MetaServerBaseURL: " + default_meta + "\n" # if we have more than one and want a random one elif pick_random: if META_DEBUG: print "choosing random meta from: " + str(meta_names) @@ -357,57 +338,58 @@ # get meta server URL url = "http://www.openrpg.com/openrpg_servers.php" try: - orpg.tools.validate.Validate().config_file("settings.xml","default_settings.xml") - ini = open(orpg.dirpath.dir_struct["user"]+"settings.xml","r") + component.get('validate').config_file("settings.xml","default_settings.xml") + ini = open(dir_struct["user"]+"settings.xml","r") txt = ini.read() - tree = parseXml(txt)._get_documentElement() + xml = component.get('xml') + tree = xml.parseXml(txt)._get_documentElement() ini.close() node_list = tree.getElementsByTagName("MetaServerBaseURL") if node_list: url = node_list[0].getAttribute("value") # allow tree to be collected - try: - tree.unlink() - except: - pass + try: tree.unlink() + except: pass except Exception,e: print e -# print "using meta server URI: " + url + #print "using meta server URI: " + url return url -####################################################################################### -# Beginning of Class registerThread -# -# A Class to Manage Registration with the Meta2 -# Create an instance and call it's start() method -# if you want to be (and stay) registered. This class -# will take care of registering and re-registering as -# often as necessary to stay in the Meta list. -# -# You may call register() yourself if you wish to change your -# server's name. It will immediately update the Meta. There -# is no need to unregister first. -# -# Call unregister() when you no longer want to be registered. -# This will result in the registerThread dying after -# attempting to immediately remove itself from the Meta. -# -# If you need to become registered again after that, you -# must create a new instance of class registerThread. Don't -# just try to call register() on the old, dead thread class. +""" + Beginning of Class registerThread + + A Class to Manage Registration with the Meta2 + Create an instance and call it's start() method + if you want to be (and stay) registered. This class + will take care of registering and re-registering as + often as necessary to stay in the Meta list. + You may call register() yourself if you wish to change your + server's name. It will immediately update the Meta. There + is no need to unregister first. + + Call unregister() when you no longer want to be registered. + This will result in the registerThread dying after + attempting to immediately remove itself from the Meta. + + If you need to become registered again after that, you + must create a new instance of class registerThread. Don't + just try to call register() on the old, dead thread class. +""" class registerThread(Thread): -# Originally, I wrote this as a sub-class of wxThread, but -# A) I couldn't get it to import right -# B) I realized that I want this to be used in a server, -# which I don't want needing wxWindows to run! -# -# Because of this fact, there are some methods from wxThread -# that I implemented to minimize changes to the code I had -# just written, i.e. TestDeleteStatus() and Delete() + """ + Originally, I wrote this as a sub-class of wxThread, but + A) I couldn't get it to import right + B) I realized that I want this to be used in a server, + which I don't want needing wxWindows to run! + + Because of this fact, there are some methods from wxThread + that I implemented to minimize changes to the code I had + just written, i.e. TestDeleteStatus() and Delete() + """ def __init__(self,name=None,realHostName=None,num_users = "Hmmm",MetaPath=None,port=6774,register_callback=None): @@ -429,15 +411,17 @@ # re-register, in minutes. self.destroy = 0 # Used to flag that this thread should die self.port = str(port) - self.register_callback = register_callback # set a method to call to report result of register - # This thread will communicate with one and only one - # Meta. If the Meta in ini.xml is changed after - # instantiation, then this instance must be - # unregistered and a new instance instantiated. - # - # Also, if MetaPath is specified, then use that. Makes - # it easier to have multiple registerThreads going to keep the server registered - # on multiple (compatible) Metas. + self.register_callback = register_callback # set a method to call to report result of register + """ + This thread will communicate with one and only one + Meta. If the Meta in ini.xml is changed after + instantiation, then this instance must be + unregistered and a new instance instantiated. + + Also, if MetaPath is specified, then use that. Makes + it easier to have multiple registerThreads going to keep the server registered + on multiple (compatible) Metas. + """ if MetaPath == None: self.path = getMetaServerBaseURL() # Do this if no Meta specified @@ -462,18 +446,19 @@ self.rlock.release() def run(self): - # This method gets called by Thread implementation - # when self.start() is called to begin the thread's - # execution - # - # We will basically enter a loop that continually - # re-registers this server and sleeps Interval - # minutes until the thread is ordered to die in place + """ + This method gets called by Thread implementation + when self.start() is called to begin the thread's + execution + + We will basically enter a loop that continually + re-registers this server and sleeps Interval + minutes until the thread is ordered to die in place + """ while(not self.TestDeleteStatus()): # Loop while until told to die # Otherwise, call thread safe register(). self.register(self.name, self.realHostName, self.num_users) if META_DEBUG: print "Sent Registration Data" - # register() will end up setting the state variables # for us, including self.interval. try: @@ -496,19 +481,21 @@ # calls to Thread.isAlive() return False. def unregister(self): - # This method can (I hope) be called from both within the thread - # and from other threads. It will attempt to unregister this - # server from the Meta database - # When this is either accomplished or has been tried hard enough - # (after which it just makes sense to let the Meta remove the - # entry itself when we don't re-register using this id), - # this method will either cause the thread to immediately die - # (if called from this thread's context) or set the Destroy flag - # (if called from the main thread), a positive test for which will cause - # the code in Entry() to exit() when the thread wakes up and - # checks TestDeleteStatus(). - # lock the critical section. The unlock will - # automatically occur at the end of the function in the finally clause + """ + This method can (I hope) be called from both within the thread + and from other threads. It will attempt to unregister this + server from the Meta database + When this is either accomplished or has been tried hard enough + (after which it just makes sense to let the Meta remove the + entry itself when we don't re-register using this id), + this method will either cause the thread to immediately die + (if called from this thread's context) or set the Destroy flag + (if called from the main thread), a positive test for which will cause + the code in Entry() to exit() when the thread wakes up and + checks TestDeleteStatus(). + lock the critical section. The unlock will + automatically occur at the end of the function in the finally clause + """ try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead @@ -531,35 +518,31 @@ # way, we can't do anything else, so die. self.Delete() # This will cause the registerThread to die in register() # prep xml_dom for garbage collection - try: - xml_dom.unlink() - except: - pass + try: xml_dom.unlink() + except: pass return 0 - finally: - self.rlock.release() + finally: self.rlock.release() def register(self, name=None, realHostName=None, num_users=None): - # Designed to handle the registration, both new and - # repeated. - # - # It is intended to be called once every interval - # (or interval - delta) minutes. + """ + Designed to handle the registration, both new and + repeated. + + It is intended to be called once every interval + (or interval - delta) minutes. - # lock the critical section. The unlock will - # automatically occur at the end of the function in the finally clause + lock the critical section. The unlock will + automatically occur at the end of the function in the finally clause + """ try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead return 1 # If so, return an error result # Set the server's attibutes, if specified. - if name: - self.name = name - if num_users != None: - self.num_users = num_users - if realHostName: - self.realHostName = realHostName + if name: self.name = name + if num_users != None: self.num_users = num_users + if realHostName: self.realHostName = realHostName # build POST data if self.realHostName: data = urllib.urlencode( {"server_data[id]":self.id, @@ -586,17 +569,20 @@ if META_DEBUG: print data if META_DEBUG: print self.interval = 0 - # If we are in the registerThread thread, then setting interval to 0 - # will end up causing a retry in about 6 seconds (see self.run()) - # If we are in the main thread, then setting interval to 0 will do one - # of two things: - # 1) Do the same as if we were in the registerThread - # 2) Cause the next, normally scheduled register() call to use the values - # provided in this call. - # - # Which case occurs depends on where the registerThread thread is when - # the main thread calls register(). + """ + If we are in the registerThread thread, then setting interval to 0 + will end up causing a retry in about 6 seconds (see self.run()) + If we are in the main thread, then setting interval to 0 will do one + of two things: + 1) Do the same as if we were in the registerThread + 2) Cause the next, normally scheduled register() call to use the values + provided in this call. + + Which case occurs depends on where the registerThread thread is when + the main thread calls register(). + """ return 0 # indicates that it was okay to call, not that no errors occurred + # If there is a DOM returned .... if xml_dom: # If there's an error, echo it to the console @@ -604,22 +590,24 @@ print "Error durring registration: " + xml_dom.getAttribute("errmsg") if META_DEBUG: print data if META_DEBUG: print - # No special handling is required. If the registration worked, id, cookie, and interval - # can be stored and used for the next time. - # If an error occurred, then the Meta will delete us and we need to re-register as - # a new server. The way to indicate this is with a "0" id and "0" cookie sent to - # the server during the next registration. Since that's what the server returns to - # us on an error anyway, we just store them and the next registration will - # automatically be set up as a new one. - # - # Unless the server calls register() itself in the meantime. Of course, that's okay - # too, because a success on THAT register() call will set up the next one to use - # the issued id and cookie. - # - # The interval is stored unconditionally for similar reasons. If there's an error, - # the interval will be less than 1, and the main thread's while loop will reset it - # to 6 seconds for the next retry. - # Is it wrong to have a method where there's more comments than code? :) + """ + No special handling is required. If the registration worked, id, cookie, and interval + can be stored and used for the next time. + If an error occurred, then the Meta will delete us and we need to re-register as + a new server. The way to indicate this is with a "0" id and "0" cookie sent to + the server during the next registration. Since that's what the server returns to + us on an error anyway, we just store them and the next registration will + automatically be set up as a new one. + + Unless the server calls register() itself in the meantime. Of course, that's okay + too, because a success on THAT register() call will set up the next one to use + the issued id and cookie. + + The interval is stored unconditionally for similar reasons. If there's an error, + the interval will be less than 1, and the main thread's while loop will reset it + to 6 seconds for the next retry. + Is it wrong to have a method where there's more comments than code? :) + """ try: self.interval = int(xml_dom.getAttribute("interval")) self.id = xml_dom.getAttribute("id")
--- a/orpg/networking/mplay_client.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/mplay_client.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,7 +29,7 @@ __version__ = "$Id: mplay_client.py,v 1.71 2007/05/12 20:41:54 digitalxero Exp $" -import orpg.minidom +#import orpg.minidom import socket import Queue import thread @@ -38,22 +38,22 @@ from xml.sax.saxutils import escape from struct import pack, unpack, calcsize from string import * -from orpg.orpg_version import * +from orpg.orpg_version import CLIENT_STRING, PROTOCOL_VERSION, VERSION import errno import os import time +from orpg.orpgCore import component +from orpg.orpg_xml import xml try: import bz2 cmpBZ2 = True -except: - cmpBZ2 = False +except: cmpBZ2 = False try: import zlib cmpZLIB = True -except: - cmpZLIB = False +except: cmpZLIB = False # This should be configurable @@ -83,7 +83,7 @@ def parseXml(data): "parse and return doc" #print data - doc = orpg.minidom.parseString(data) + doc = xml.parseXml(data) doc.normalize() return doc @@ -117,9 +117,11 @@ self.group_id = "0" self.name = "" self.role = "GM" + ## Soon to be removed self.ROLE_GM = "GM" self.ROLE_PLAYER = "Player" self.ROLE_LURKER = "Lurker" + ## --TaS self.ip = socket.gethostbyname(socket.gethostname()) self.remote_ip = None self.version = VERSION @@ -133,9 +135,6 @@ self.text_status = "Idle" self.statLock = Lock() self.useroles = 0 - self.ROLE_GM = "GM" - self.ROLE_PLAYER = "Player" - self.ROLE_LURKER = "Lurker" self.lastmessagetime = time.time() self.connecttime = time.time() @@ -147,8 +146,7 @@ # Loop as long as we have a connection while( self.get_status() == MPLAY_CONNECTED ): - try: - readMsg = self.outbox.get( block=1 ) + try: readMsg = self.outbox.get( block=1 ) except Exception, text: self.log_msg( ("outbox.get() got an exception: ", text) ) @@ -176,15 +174,13 @@ try: if self.useCompression and self.compressionType != None: readMsg = self.compressionType.decompress(readMsg) - except: - pass + except: pass # Check the length of the message bytes = len( readMsg ) # Make sure we are still connected - if bytes == 0: - break + if bytes == 0: break else: # Pass along the message so it can be processed self.inbox.put( readMsg ) @@ -223,12 +219,9 @@ # Now, send the message the the length was describing sentm = sock.send( msg ) - if self.isServer(): - self.log_msg(("data_sent", sentl+sentm)) - except socket.error, e: - self.log_msg( e ) - except Exception, e: - self.log_msg( e ) + if self.isServer(): self.log_msg(("data_sent", sentl+sentm)) + except socket.error, e: self.log_msg( e ) + except Exception, e: self.log_msg( e ) return sentm def recvData( self, sock, readSize ): @@ -276,10 +269,8 @@ # Make the peer IP address available for reference later if self.remote_ip is None: self.remote_ip = self.sock.getpeername() - except IOError, e: - self.log_msg( e ) - except Exception, e: - self.log_msg( e ) + except IOError, e: self.log_msg( e ) + except Exception, e: self.log_msg( e ) return msgData def initialize_threads(self): @@ -295,8 +286,7 @@ self.set_status(MPLAY_DISCONNECTING) self.log_msg("client stub " + self.ip +" disconnecting...") self.log_msg("closing sockets...") - try: - self.sock.shutdown( 2 ) + try: self.sock.shutdown( 2 ) except Exception, e: print "Caught exception: " + str(e) print @@ -318,13 +308,15 @@ else: return 0 def update_self_from_player(self, player): - try: - (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player + try: (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, role) = player except Exception, e: print e - -# The IP field should really be deprecated as too many systems are NAT'd and/or behind firewalls for a -# client provided IP address to have much value. As such, we now label it as deprecated. + """ + The IP field should really be deprecated as too many systems are NAT'd and/or behind firewalls for a + client provided IP address to have much value. As such, we now label it as deprecated. + """ def toxml(self,action): xml_data = '<player name="' + myescape(self.name) + '"' xml_data += ' action="' + action + '" id="' + self.id + '"' @@ -338,16 +330,13 @@ xml_data += ' cmpType="bz2"' elif cmpZLIB and (self.compressionType == 'Undefined' or self.compressionType == zlib): xml_data += ' cmpType="zlib"' - else: - xml_data += ' cmpType="None"' + else: xml_data += ' cmpType="None"' xml_data += ' />' return xml_data def log_msg(self,msg): if self.log_console: self.log_console(msg) -# else: -# print "message", msg def get_status(self): self.statLock.acquire() @@ -356,7 +345,9 @@ return status def my_role(self): -#Why create the three different objects? Why not just assign a value to self.role and use that? Prof_Ebral ponders. + #Leaving this for testing. + return self.role + """ if self.role == "GM": return self.ROLE_GM elif self.role == "Player": @@ -364,6 +355,7 @@ elif self.role == "Lurker": return self.ROLE_LURKER return -1 + """ def set_status(self,status): self.statLock.acquire() @@ -391,12 +383,9 @@ idletime = self.idle_time() idlemins = idletime / 60 status = "Unknown" - if idlemins < 3: - status = "Active" - elif idlemins < 10: - status = "Idle ("+str(int(idlemins))+" mins)" - else: - status = "Inactive ("+str(int(idlemins))+" mins)" + if idlemins < 3: status = "Active" + elif idlemins < 10: status = "Idle ("+str(int(idlemins))+" mins)" + else: status = "Inactive ("+str(int(idlemins))+" mins)" return status def connected_time(self): @@ -425,6 +414,8 @@ "mplay client" def __init__(self,name,callbacks): client_base.__init__(self) + component.add('mp_client', self) + self.xml = component.get('xml') self.set_name(name) self.on_receive = callbacks['on_receive'] self.on_mplay_event = callbacks['on_mplay_event'] @@ -437,9 +428,6 @@ # Should really find a better solution. -- SD 8/03 self.orpgFrame_callback = callbacks['orpgFrame'] self.settings = self.orpgFrame_callback.settings - #self.version = VERSION - #self.protocol_version = PROTOCOL_VERSION - #self.client_string = CLIENT_STRING self.ignore_id = [] self.ignore_name = [] self.players = {} @@ -507,15 +495,17 @@ players = self.get_players() if self.players.has_key(player): for m in players: - if player == m[2]: - return m + if player == m[2]: return m return -1 def get_id(self): return self.id def get_my_info(self): - return (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string, self.role) + return (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, + self.role) def is_valid_id(self,id): self.statLock.acquire() @@ -526,25 +516,21 @@ def clear_players(self,save_self=0): self.statLock.acquire() keys = self.players.keys() - for k in keys: - del self.players[k] + for k in keys: del self.players[k] self.statLock.release() def clear_groups(self): self.statLock.acquire() keys = self.groups.keys() - for k in keys: - del self.groups[k] + for k in keys: del self.groups[k] self.statLock.release() def find_role(self,id): return self.players[id].role def get_ignore_list(self): - try: - return (self.ignore_id, self.ignore_name) - except: - return (None, None) + try: return (self.ignore_id, self.ignore_name) + except: return (None, None) def toggle_ignore(self, id): for m in self.ignore_id: @@ -567,7 +553,10 @@ #--------------------------------------------------------- def set_room_pass(self,npwd,pwd=""): - self.outbox.put("<alter key=\"pwd\" val=\"" +npwd+ "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") + recycle_bin = "<alter key=\"pwd\" " + recycle_bin += "val=\"" +npwd+ "\" bpw=\"" + pwd + "\" " + recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS self.update() def set_room_name(self,name,pwd=""): @@ -598,7 +587,10 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - self.outbox.put("<alter key=\"name\" val=\"" + name + "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") + recycle_bin = "<alter key=\"name\" " + recycle_bin += "val=\"" + name + "\" bpw=\"" + pwd + "\" " + recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS self.update() #--------------------------------------------------------- @@ -612,7 +604,9 @@ self.outbox.put("<role action=\"get\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") def set_role(self,player,role,pwd=""): - self.outbox.put("<role action=\"set\" player=\"" + player + "\" role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />") + recycle_bin = "<role action=\"set\" player=\"" + player + "\" " + recycle_bin += "role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easer to read. --TaS self.update() def send(self,msg,player="all"): @@ -626,12 +620,13 @@ self.check_my_status() def send_create_group(self,name,pwd,boot_pwd,minversion): - self.outbox.put("<create_group from=\""+self.id+"\" pwd=\""+pwd+"\" name=\""+ - name+"\" boot_pwd=\""+boot_pwd+"\" min_version=\"" + minversion +"\" />") + recycle_bin = "<create_group from=\""+self.id+"\" " + recycle_bin += "pwd=\""+pwd+"\" name=\""+ name+"\" boot_pwd=\""+boot_pwd+"\" " + recycle_bin += "min_version=\"" + minversion +"\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS def send_join_group(self,group_id,pwd): - if (group_id != 0): - self.update_role("Lurker") + if (group_id != 0): self.update_role("Lurker") self.outbox.put("<join_group from=\""+self.id+"\" pwd=\""+pwd+"\" group_id=\""+str(group_id)+"\" />") def poll(self, evt=None): @@ -641,8 +636,7 @@ if self.get_status() != MPLAY_CONNECTED: self.check_my_status() else: - try: - self.pretranslate(msg) + try: self.pretranslate(msg) except Exception, e: print "The following message: " + str(msg) print "created the following exception: " @@ -651,16 +645,13 @@ def add_msg_handler(self, tag, function, core=False): if not self.msg_handlers.has_key(tag): self.msg_handlers[tag] = function - if core: - self.core_msg_handlers.append(tag) - else: - print 'XML Messages ' + tag + ' already has a handler' + if core: self.core_msg_handlers.append(tag) + else: print 'XML Messages ' + tag + ' already has a handler' def remove_msg_handler(self, tag): if self.msg_handlers.has_key(tag) and not tag in self.core_msg_handlers: del self.msg_handlers[tag] - else: - print 'XML Messages ' + tag + ' already deleted' + else: print 'XML Messages ' + tag + ' already deleted' def load_core_msg_handlers(self): self.add_msg_handler('msg', self.on_msg, True) @@ -674,19 +665,16 @@ def pretranslate(self,data): # Pre-qualify our data. If we don't have atleast 5-bytes, then there is # no way we even have a valid message! - if len(data) < 5: - return + if len(data) < 5: return end = data.find(">") head = data[:end+1] msg = data[end+1:] - xml_dom = parseXml(head) + xml_dom = self.xml.parseXml(head) xml_dom = xml_dom._get_documentElement() tag_name = xml_dom._get_tagName() id = xml_dom.getAttribute("from") - if id == '': - id = xml_dom.getAttribute("id") - if self.msg_handlers.has_key(tag_name): - self.msg_handlers[tag_name](id, data, xml_dom) + if id == '': id = xml_dom.getAttribute("id") + if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](id, data, xml_dom) else: #Unknown messages recived ignoring #using pass insted or printing an error message @@ -694,8 +682,7 @@ #if someone is using a plugin to send messages and this user does not #have the plugin they would be getting errors pass - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_sound(self, id, data, xml_dom): (ignore_id,ignore_name) = self.get_ignore_list() @@ -717,10 +704,8 @@ self.on_receive(msg,None) # None get's interpreted in on_receive as the sys admin. # Doing it this way makes it harder to impersonate the admin else: - if self.is_valid_id(id): - self.on_receive(msg,self.players[id]) - if xml_dom: - xml_dom.unlink() + if self.is_valid_id(id): self.on_receive(msg,self.players[id]) + if xml_dom: xml_dom.unlink() def on_ping(self, id, msg, xml_dom): #a REAL ping time implementation by Snowdog 8/03 @@ -735,8 +720,7 @@ latency = float( latency) / 10.0 ping_msg = "Ping Results: " + str(latency) + " ms (parsed message, round trip)" self.on_receive(ping_msg,None) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_group(self, id, msg, xml_dom): name = xml_dom.getAttribute("name") @@ -754,8 +738,7 @@ elif act == 'update': self.groups[id] = group_data self.on_group_event(mplay_event(GROUP_UPDATE, group_data)) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_role(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") @@ -766,13 +749,10 @@ if id == self.id: self.players[id] = (a,b,c,d,e,f,g,role) self.update_role(role) - else: - self.players[id] = (a,b,c,d,e,f,g,role) + else: self.players[id] = (a,b,c,d,e,f,g,role) self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) - except: - pass - if xml_dom: - xml_dom.unlink() + except: pass + if xml_dom: xml_dom.unlink() def on_player(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") @@ -782,42 +762,39 @@ version = xml_dom.getAttribute("version") protocol_version = xml_dom.getAttribute("protocol_version") client_string = xml_dom.getAttribute("client_string") - try: - player = (name,ip,id,status,version,protocol_version,client_string,self.players[id][7]) + try: player = (name, ip, id, status, + version, protocol_version, + client_string, self.players[id][7]) except Exception, e: - player = (name,ip,id,status,version,protocol_version,client_string,"Player") + player = (name, ip, id, status, + version, protocol_version, + client_string, "Player") if act == "new": self.players[id] = player - self.on_player_event(mplay_event(PLAYER_NEW,self.players[id])) + self.on_player_event(mplay_event(PLAYER_NEW, self.players[id])) elif act == "group": self.group_id = xml_dom.getAttribute("group_id") self.clear_players() - self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE,self.groups[self.group_id])) + self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE, self.groups[self.group_id])) self.players[self.id] = self.get_my_info() #(self.name,self.ip,self.id,self.text_status) - self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) + self.on_player_event(mplay_event(PLAYER_NEW, self.players[self.id])) elif act == "failed": self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE_F)) elif act == "del": self.on_player_event(mplay_event(PLAYER_DEL,self.players[id])) - if self.players.has_key(id): - del self.players[id] - if id == self.id: - self.do_disconnect() + if self.players.has_key(id): del self.players[id] + if id == self.id: self.do_disconnect() # the next two cases handle the events that are used to let you know when others are typing elif act == "update": if id == self.id: self.players[id] = player self.update_self_from_player(player) - else: - self.players[id] = player + else: self.players[id] = player dont_send = 0 for m in self.ignore_id: - if m == id: - dont_send=1 - if dont_send != 1: - self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) - if xml_dom: - xml_dom.unlink() + if m == id: dont_send=1 + if dont_send != 1: self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) + if xml_dom: xml_dom.unlink() def on_password(self, id, msg, xml_dom): signal = type = id = data = None @@ -831,8 +808,7 @@ def check_my_status(self): status = self.get_status() - if status == MPLAY_DISCONNECTING: - self.do_disconnect() + if status == MPLAY_DISCONNECTING: self.do_disconnect() def connect(self, addressport): """Establish a connection to a server while still using sendThread & recvThread for its @@ -858,7 +834,7 @@ self.sendMsg( self.sock, self.toxml("new") ) data = self.recvMsg( self.sock ) # get new id and group_id - xml_dom = parseXml(data) + xml_dom = self.xml.parseXml(data) xml_dom = xml_dom._get_documentElement() self.id = xml_dom.getAttribute("id") self.group_id = xml_dom.getAttribute("group_id") @@ -869,31 +845,29 @@ self.compressionType = bz2 elif cmpZLIB and xml_dom.getAttribute('cmpType') == 'zlib': self.compressionType = zlib - else: - self.compressionType = None - else: - self.compressionType = bz2 + else: self.compressionType = None + else: self.compressionType = bz2 #send confirmation self.sendMsg( self.sock, self.toxml("new") ) except Exception, e: self.log_msg(e) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return 0 # Start things rollings along self.initialize_threads() self.on_mplay_event(mplay_event(MPLAY_CONNECTED)) - self.players[self.id] = (self.name,self.ip,self.id,self.text_status,self.version,self.protocol_version,self.client_string,self.role) + self.players[self.id] = (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, self.role) self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return 1 def start_disconnect(self): self.on_mplay_event(mplay_event(MPLAY_DISCONNECTING)) self.outbox.put( self.toxml("del") ) - ## Client Side Disconect Forced -- Snowdog 10-09-2003 + ## Client Side Disconect Forced -- Snowdog 10-09-2003 #pause to allow GUI events time to sync. time.sleep(1) self.do_disconnect()
--- a/orpg/networking/mplay_groups.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/mplay_groups.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,7 +1,9 @@ from orpg.mapper.map_msg import * class game_group: - def __init__( self, id, name, pwd, desc="", boot_pwd="", minVersion="", mapFile=None, messageFile=None, persist =0 ): + def __init__( self, id, name, pwd, desc="", + boot_pwd="", minVersion="", + mapFile=None, messageFile=None, persist=0 ): self.id = id self.name = name self.desc = desc @@ -33,8 +35,7 @@ self.players.append(id) def remove_player(self,id): - if self.voice.has_key(id): - del self.voice[id] + if self.voice.has_key(id): del self.voice[id] self.players.remove(id) def get_num_players(self): @@ -45,7 +46,6 @@ tmp = self.players return tmp - def check_pwd(self,pwd): return (pwd==self.pwd) @@ -61,13 +61,10 @@ w=max(len(minVersion[i]),len(version[i])) v1=minVersion[i].rjust(w); v2=version[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 + if v1<v2: return 1 + if v1>v2: return 0 - if len(minVersion)>len(version): - return 0 + if len(minVersion)>len(version): return 0 return 1 #depreciated - see send_group_list()
--- a/orpg/networking/mplay_messaging.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/mplay_messaging.py Thu Aug 27 01:04:43 2009 -0500 @@ -36,22 +36,22 @@ from xml.sax.saxutils import escape from struct import pack, unpack, calcsize from string import * -from orpg.orpg_version import * +from orpg.orpg_version import VERSION, PROTOCOL_VERSION, CLIENT_STRING, SERVER_MIN_CLIENT_VERSION import os import time -from orpg.orpgCore import * +from orpg.tools.orpg_log import logger +from orpg.orpgCore import component def myescape(data): return escape(data,{"\"":""}) class messenger: def __init__(self, *args, **kwargs): - self.log = open_rpg.get_component("log") - self.xml = open_rpg.get_component("xml") - self.dir_struct = open_rpg.get_component("dir_struct") - self.validate = open_rpg.get_component("validate") - self.settings = open_rpg.get_component("settings") + #self.xml = component.get("xml") used once, no need for the object. + self.dir_struct = component.get("dir_struct") #used? + self.validate = component.get("validate") #used?? + #self.settings = component.get("settings") ## used once, no need for the object. if kwargs.has_key('isServer'): self.isServer = kwargs['isServer'] else: @@ -64,7 +64,7 @@ self.exitEvent = Event() self.sendThreadExitEvent = Event() self.recvThreadExitEvent = Event() - self.port = int(self.settings.get_setting("port")) + self.port = int(component.get("settings").get_setting("port")) ##used even? self.ip = socket.gethostbyname(socket.gethostname()) self.lensize = calcsize('i') self.mplay_type = ('disconnected', 'connected', 'disconnecting', 'group change', 'group change failed') @@ -137,12 +137,12 @@ def disconnect(self): self.set_status(2) - self.log.log("client stub " + self.ip +" disconnecting...", ORPG_DEBUG) - self.log.log("closing sockets...", ORPG_DEBUG) + logger.debug("client stub " + self.ip +" disconnecting...") + logger.debug("closing sockets...") try: self.sock.shutdown( 2 ) except: - self.log.log("Caught exception:\n" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Caught exception:\n" + traceback.format_exc()) self.set_status(0) def reset(self, sock): @@ -161,10 +161,10 @@ try: (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player except: - self.log.log("Exception: messenger->update_self_from_player():\n" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Exception: messenger->update_self_from_player():\n" + traceback.format_exc()) def toxml(self, act): - self.log.log("DEPRECIATED! messenger->toxml()", ORPG_CRITICAL) + logger.exception("DEPRECIATED! messenger->toxml()") xml_data = self.build_message('player', name=myescape(self.name), action=act, @@ -290,7 +290,7 @@ #Message Handaling def message_handler(self, arg): xml_dom = None - self.log.log("message handler thread running...", ORPG_NOTE) + logger.note("message handler thread running...", ORPG_NOTE) while self.alive or self.status == 'connected': data = None try: @@ -308,24 +308,24 @@ del data data = None except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) + logger.general(traceback.format_exc()) if xml_dom: xml_dom.unlink() if xml_dom: xml_dom.unlink() - self.log.log("message handler thread exiting...", ORPG_NOTE) + logger.note("message handler thread exiting...") self.inbox_event.set() def parse_incoming_dom(self, data): #print data xml_dom = None try: - xml_dom = self.xml.parseXml(data) + xml_dom = component.get("xml").parseXml(data) xml_dom = xml_dom._get_documentElement() self.message_action(xml_dom, data) except Exception, e: - self.log.log("Error in parse of inbound message. Ignoring message.", ORPG_GENERAL) - self.log.log("\tOffending data(" + str(len(data)) + "bytes)=" + data, ORPG_GENERAL) - self.log.log("Exception=" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Error in parse of inbound message. Ignoring message.") + logger.general("\tOffending data(" + str(len(data)) + "bytes)=" + data) + logger.general("Exception=" + traceback.format_exc()) if xml_dom: xml_dom.unlink() def message_action(self, xml_dom, data): @@ -333,8 +333,8 @@ if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](xml_dom, data) else: - self.log.log("Unknown Message Type", ORPG_GENERAL) - self.log.log(data, ORPG_GENERAL) + logger.general("Unknown Message Type") + logger.general(data) #Message Action thread expires and closes here. return @@ -350,7 +350,7 @@ readMsg = self.outbox.get( block=1 ) except Exception, text: - self.log.log("Exception: messenger->sendThread(): " + str(text), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendThread(): " + str(text) # If we are here, it's because we have data to send, no doubt! if self.status == 'connected': @@ -358,12 +358,12 @@ # Send the entire message, properly formated/encoded sent = self.sendMsg( self.sock, readMsg ) except: - self.log.log("Exception: messenger->sendThread():\n" + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendThread():\n" + traceback.format_exc() else: # If we are not connected, purge the data queue - self.log.log("Data queued without a connection, purging data from queue...", ORPG_NOTE) + logger.note("Data queued without a connection, purging data from queue...") self.sendThreadExitEvent.set() - self.log.log( "sendThread has terminated...", ORPG_NOTE) + logger.note( "sendThread has terminated...") def sendMsg( self, sock, msg ): """Very simple function that will properly encode and send a message to te @@ -382,12 +382,12 @@ # Now, send the message the the length was describing sentm = sock.send( msg ) if self.isServer: - self.log.log("('data_sent', " + str(sentl+sentm) + ")", ORPG_DEBUG) + logger.debug("('data_sent', " + str(sentl+sentm) + ")") return sentm except socket.error, e: - self.log.log("Socket Error: messenger->sendMsg(): " + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Socket Error: messenger->sendMsg(): " + traceback.format_exc()) except: - self.log.log("Exception: messenger->sendMsg(): " + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendMsg(): " + traceback.format_exc()) def recvThread( self, arg ): "Receiving thread. This thread reads from the socket and writes to the data queue." @@ -413,11 +413,11 @@ self.inbox.put( readMsg ) self.update_idle_time() #update the last message time if bytes == 0: - self.log.log("Remote has disconnected!", ORPG_NOTE) + logger.note("Remote has disconnected!") self.set_status(2) self.outbox.put( "" ) # Make sure the other thread is woken up! self.sendThreadExitEvent.set() - self.log.log("messenger->recvThread() has terminated...", ORPG_NOTE) + logger.note("messenger->recvThread() has terminated...") def recvData( self, sock, readSize ): """Simple socket receive method. This method will only return when the exact @@ -439,7 +439,7 @@ offset += rs data += frag except socket.error, e: - self.log.log("Socket Error: messenger->recvData(): " + str(e), ORPG_CRITICAL) + logger.exception("Socket Error: messenger->recvData(): " + str(e)) data = "" return data @@ -465,9 +465,9 @@ msgData = self.recvData( sock, length ) if self.isServer: - self.log.log("('data_recv', " + str(length+4) + ")", ORPG_DEBUG) + logger.debug("('data_recv', " + str(length+4) + ")") except: - self.log.log("Exception: messenger->recvMsg():\n" + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->recvMsg():\n" + traceback.format_exc()) return msgData if __name__ == "__main__":
--- a/orpg/networking/mplay_server.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/mplay_server.py Thu Aug 27 01:04:43 2009 -0500 @@ -43,28 +43,30 @@ <role action='set,get,display' player='' group_id='' boot_pwd='' role=''/> """ -from mplay_client import * -from mplay_client import MPLAY_LENSIZE -import orpg.dirpath -import orpg.tools.validate +import re import gc import cgi import sys import string import time import urllib +import traceback + +from mplay_client import * +from mplay_client import MPLAY_LENSIZE +from orpg.dirpath import dir_struct +import orpg.tools.validate + from orpg.mapper.map_msg import * from threading import Lock, RLock from struct import pack, unpack, calcsize from meta_server_lib import * -import traceback -import re # Import the minidom XML module from xml.dom import minidom # Snag the version number -from orpg.orpg_version import * +from orpg.orpg_version import VERSION, PROTOCOL_VERSION, CLIENT_STRING, SERVER_MIN_CLIENT_VERSION #Plugins from server_plugins import ServerPlugins @@ -98,7 +100,7 @@ f.close() else: - f = open(orpg.dirpath.dir_struct["template"] + "default_map.xml") + f = open(dir_struct["template"] + "default_map.xml") tree = f.read() f.close() @@ -110,7 +112,6 @@ f.write(self.game_map.get_all_xml()) f.close() - def add_player(self,id): self.players.append(id) @@ -127,7 +128,6 @@ tmp = self.players return tmp - def check_pwd(self,pwd): return (pwd==self.pwd) @@ -135,19 +135,15 @@ return (pwd==self.boot_pwd) def check_version(self,ver): - if (self.minVersion == ""): - return 1 + if (self.minVersion == ""): return 1 minVersion=self.minVersion.split('.') version=ver.split('.') for i in xrange(min(len(minVersion),len(version))): w=max(len(minVersion[i]),len(version[i])) v1=minVersion[i].rjust(w); v2=version[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 - + if v1<v2: return 1 + if v1>v2: return 0 if len(minVersion)>len(version): return 0 return 1 @@ -163,7 +159,6 @@ return xml_data - class client_stub(client_base): def __init__(self,inbox,sock,props,log): client_base.__init__(self) @@ -189,14 +184,11 @@ self.timeout_time = None def check_time_out(self): - if self.timeout_time==None: - self.timeout_time = time.time() + if self.timeout_time==None: self.timeout_time = time.time() curtime = time.time() diff = curtime - self.timeout_time - if diff > 1800: - return 1 - else: - return 0 + if diff > 1800: return 1 + else: return 0 def send(self,msg,player,group): if self.get_status() == MPLAY_CONNECTED: @@ -219,7 +211,7 @@ self.name = xml_dom.getAttribute("name") self.text_status = xml_dom.getAttribute("status") - +""" ###################################################################### ###################################################################### ## @@ -229,6 +221,7 @@ ## ###################################################################### ###################################################################### +""" class mplay_server: def __init__(self, log_console=None, name=None): @@ -249,7 +242,7 @@ self.boot_pwd = "" self.server_address = None # IP or Name of server to post to the meta. None means the meta will auto-detect it. self.defaultMessageFile = None - self.userPath = orpg.dirpath.dir_struct["user"] + self.userPath = dir_struct["user"] self.lobbyMapFile = "Lobby_map.xml" self.lobbyMessageFile = "LobbyMessage.html" self.banFile = "ban_list.xml" @@ -264,19 +257,19 @@ self.allowRemoteKill = False self.allowRemoteAdmin = True self.sendLobbySound = False - self.lobbySound = 'http://www.digitalxero.net/music/mus_tavern1.bmu' + self.lobbySound = 'http://www.digitalxero.net/music/mus_tavern1.bmu' ##used? def initServer(self, **kwargs): - for atter, value in kwargs.iteritems(): - setattr(self, atter, value) - self.validate = orpg.tools.validate.Validate(self.userPath) - self.validate.config_file( self.lobbyMapFile, "default_Lobby_map.xml" ) - self.validate.config_file( self.lobbyMessageFile, "default_LobbyMessage.html" ) + for atter, value in kwargs.iteritems(): setattr(self, atter, value) + validate.config_file( self.lobbyMapFile, "default_Lobby_map.xml" ) + validate.config_file( self.lobbyMessageFile, "default_LobbyMessage.html" ) self.server_start_time = time.time() # Since the server is just starting here, we read in the XML configuration # file. Notice the lobby is still created here by default. - self.groups = { '0': game_group('0','Lobby','','The game lobby', '', '', self.userPath + self.lobbyMapFile, self.userPath + self.lobbyMessageFile, 1)} + self.groups = { '0': game_group('0','Lobby','', + 'The game lobby', '', '', self.userPath + self.lobbyMapFile, + self.userPath + self.lobbyMessageFile, 1)} # Make sure the server's name gets set, in case we are being started from # elsewhere. Basically, if it's passed in, we'll over ride what we were # prompted for. This should never really happen at any rate. @@ -314,13 +307,12 @@ self.addsvrcmd('plugin', self.plugin_msg_handler) self.addsvrcmd('sound', self.sound_msg_handler) - # This method reads in the server's ban list added by Darren def initBanList( self ): self.log_msg("Processing Ban List File...") # make sure the server_ini.xml exists! - self.validate.config_file(self.banFile, "default_ban_list.xml" ) + validate.config_file(self.banFile, "default_ban_list.xml" ) # try to use it. try: @@ -361,7 +353,7 @@ def initServerConfig(self): self.log_msg("Processing Server Configuration File... " + self.userPath) # make sure the server_ini.xml exists! - self.validate.config_file( "server_ini.xml", "default_server_ini.xml" ) + validate.config_file( "server_ini.xml", "default_server_ini.xml" ) # try to use it. try: self.configDom = minidom.parse(self.userPath + 'server_ini.xml') @@ -383,6 +375,7 @@ if len(opt) and (opt[0].upper() == 'Y'): self.reg = 'Y' else: self.reg = 'N' LobbyName = 'Lobby' + if self.configDoc.hasAttribute("lobbyname"): LobbyName = self.configDoc.getAttribute("lobbyname") map_node = service_node = self.configDoc.getElementsByTagName("map")[0] msg_node = service_node = self.configDoc.getElementsByTagName("message")[0] @@ -391,6 +384,7 @@ if mapFile == '': mapFile = 'Lobby_map.xml' if msgFile == '': msgFile = 'LobbyMessage.html' # Update the lobby with the passwords if they've been specified + if len(self.boot_pwd): self.groups = {'0': game_group( '0', LobbyName, "", 'The game lobby', self.boot_pwd, "", self.userPath + mapFile.replace("myfiles/", ""), @@ -411,12 +405,14 @@ if self.reg[0].upper() == "Y": if self.name == None: self.name = raw_input("Server Name? ") self.register() - + """ # Get the minimum openrpg version from config if available # if it isn't set min version to internal default. # # server_ini.xml entry for version tag... # <version min="x.x.x"> + """ + try: mver = self.configDoc.getElementsByTagName("version")[0] self.minClientVersion = mver.getAttribute("min") @@ -425,13 +421,14 @@ # This try/except bit is to allow older versions of python to continue without a list error. - + """ #------------------------[ START <AUTOKICK> TAG PROCESSING ]-------------- # Auto-kick option defaults for silent booting and # setting the default zombie-client delay time --Snowdog 9/05 # # server_ini.xml entry for autikick tag... # <autokick silent=["no","yes"] delay="(# of seconds)"> + """ try: ak = self.configDoc.getElementsByTagName("autokick")[0] @@ -455,10 +452,10 @@ alk = "" if (self.silent_auto_kick == 1): alk = "(Silent Mode)" self.log_msg("Auto Kick: Delay="+str(self.zombie_time) + " " + alk) - #------------------------[ END <AUTOKICK> TAG PROCESSING ]-------------- + """------------------------[ END <AUTOKICK> TAG PROCESSING ]--------------""" - + """ #-------------------------------[ START <ROOM_DEFAULT> TAG PROCESSING ]-------------------- # # New room_defaults configuration option used to set various defaults @@ -467,6 +464,7 @@ # # option syntax # <room_defaults passwords="yes" map="myfiles/LobbyMap.xml" message="myfiles/LobbyMessage.html" /> + """ #default settings for tag options... roomdefault_msg = str(self.defaultMessageFile) #no message is the default @@ -493,8 +491,7 @@ if map != "": roomdefault_map = self.userPath + map.replace("myfiles/", "") self.log_msg("Room Defaults: Using " + str(map) + " for room map") - except: - self.log_msg("Room Defaults: [Warning] Using Default Map") + except: self.log_msg("Room Defaults: [Warning] Using Default Map") try: setting = roomdefaults.getElementsByTagName('message')[0] @@ -508,12 +505,10 @@ traceback.print_exc() self.log_msg("**WARNING** Error loading default room settings from configuration file. Using internal defaults.") - #set the defaults if roomdefault_msg != "" or roomdefault_msg != None: self.defaultMessageFile = roomdefault_msg #<room_defaults> tag superceeds older <newrooms> tag else: self.defaultMessageFile = None - if roomdefault_map != "" or roomdefault_map != None: self.defaultMapFile = roomdefault_map #<room_defaults> tag superceeds older <newrooms> tag else: self.defaultMapFile = None @@ -521,9 +516,7 @@ ##### room default map not handled yet. SETTING IGNORED if roomdefault_pass == 0: self.allow_room_passwords = 0 else: self.allow_room_passwords = 1 - - #-------------------------------[ END <ROOM_DEFAULT> TAG PROCESSING ]-------------------- - + """-------------------------------[ END <ROOM_DEFAULT> TAG PROCESSING ]--------------------""" ###Server Cheat message try: @@ -533,27 +526,19 @@ self.cheat_msg = "**FAKE ROLL**" self.log_msg("**WARNING** <cheat txt=\"\"> tag missing from server configuration file. Using empty string.") - - # should validate protocal validate_protocol_node = self.configDom.getElementsByTagName("validate_protocol ") - self.validate_protocol = 1 - if(validate_protocol_node): self.validate_protocol = (validate_protocol_node[0].getAttribute("value") == "True") if(self.validate_protocol != 1): self.log_msg("Protocol Validation: OFF") self.makePersistentRooms() - self.log_msg("Server Configuration File: Processing Completed.") - except Exception, e: traceback.print_exc() self.log_msg("Exception in initServerConfig() " + str(e)) - def makePersistentRooms(self): 'Creates rooms on the server as defined in the server config file.' - for element in self.configDom.getElementsByTagName('room'): roomName = element.getAttribute('name') roomPassword = element.getAttribute('password') @@ -567,31 +552,28 @@ # we only care about the first map element found -- others are ignored mapElement = element.getElementsByTagName('map')[0] mapFile = self.userPath + mapElement.getAttribute('file').replace("myfiles/", "") - messageElement = element.getElementsByTagName('message')[0] messageFile = messageElement.getAttribute('file') - if messageFile[:4] != 'http': messageFile = self.userPath + messageFile.replace("myfiles/", "") # Make sure we have a message to even mess with if(len(messageFile) == 0): messageFile = self.defaultMessageFile - if(len(mapFile) == 0): mapFile = self.defaultMapFile - moderated = 0 if element.hasAttribute('moderated') and element.getAttribute('moderated').lower() == "true": moderated = 1 #create the new persistant group - self.new_group(roomName, roomPassword, bootPassword, minVersion, mapFile, messageFile, persist = 1, moderated=moderated) - - + self.new_group(roomName, roomPassword, + bootPassword, minVersion, mapFile, + messageFile, persist = 1, moderated=moderated) def isPersistentRoom(self, id): 'Returns True if the id is a persistent room (other than the lobby), otherwise, False.' - + """ # altered persistance tracking from simple room id based to per-group setting # allows arbitrary rooms to be marked as persistant without needing the self.persistRoomThreshold # -- Snowdog 4/04 + """ try: id = str(id) #just in case someone sends an int instead of a str into the function if id not in self.groups: return 0 #invalid room, can't be persistant @@ -601,8 +583,6 @@ self.log_msg("Exception occured in isPersistentRoom(self,id)") return 0 - - #----------------------------------------------------- # Toggle Meta Logging -- Added by Snowdog 4/03 #----------------------------------------------------- @@ -633,15 +613,13 @@ for n in self.players: try: self.players[n].EnableMessageLogging = mode except: self.log_msg("Error changing Message Logging Mode for client #" + str(self.players[n].id)) + def NetworkLoggingStatus(self): if self.log_network_messages == 0: return "Network Traffic Log: Off" elif self.log_network_messages == 1: return "Network Traffic Log: Logging (composite file)" elif self.log_network_messages == 2: return "Network Traffic Log: Logging (inbound/outbound files)" else: self.log_msg("Network Traffic Log: [Unknown]") - - - def register_callback(instance, xml_dom = None,source=None): if xml_dom: # if we get something if source == getMetaServerBaseURL(): # if the source of this DOM is the authoritative meta @@ -655,17 +633,19 @@ if newlist != curlist: # If the two lists aren't identical # then something has changed. - instance.register() # Call self.register() + instance.register() # Call self.register() # which will force a re-read of the meta cache and # redo the registerThreads else: instance.register() - # Eventually, reset the MetaServerBaseURL here + # Eventually, reset the MetaServerBaseURL here + """ ## Added to help clean up parser errors in the XML on clients ## due to characters that break welformedness of the XML from ## the meta server. ## NOTE: this is a stopgap measure -SD + """ def clean_published_servername(self, name): #clean name of all apostrophes and quotes badchars = "\"\\`><" @@ -679,11 +659,8 @@ for rnum in self.groups.keys(): rooms += urllib.urlencode( {"room_data[rooms][" + str(rnum) + "][name]":self.groups[rnum].name, "room_data[rooms][" + str(rnum) + "][pwd]":str(self.groups[rnum].pwd != "")})+'&' - for pid in self.groups[rnum].players: rooms += urllib.urlencode( {"room_data[rooms][" + str(rnum) + "][players]["+str(pid)+"]":self.players[pid].name,})+'&' - - for meta in self.metas.keys(): while id == '0': id, cookie = self.metas[meta].getIdAndCookie() @@ -691,11 +668,9 @@ "act":'registerrooms'}) get_server_dom(data+'&'+rooms, self.metas[meta].path) - def register(self,name_given=None): if name_given == None: name = self.name else: self.name = name = name_given - name = self.clean_published_servername(name) # Set up the value for num_users @@ -708,14 +683,16 @@ self.log_msg("Found these valid metas:") for meta in metalist: self.log_msg("Meta:" + meta) + """ # Go through the list and see if there is already a running register # thread for the meta. # If so, call it's register() method # If not, start one, implicitly calling the new thread's register() method - # iterate through the currently running metas and prune any # not currently listed in the Meta Server list. + """ + if self.show_meta_messages != 0: self.log_msg( "Checking running register threads for outdated metas.") for meta in self.metas.keys(): if self.show_meta_messages != 0: self.log_msg("meta:" + meta + ": ") @@ -729,39 +706,43 @@ # Now call register() for alive metas or start one if we need one for meta in metalist: if self.metas.has_key(meta) and self.metas[meta] and self.metas[meta].isAlive(): - self.metas[meta].register(name=name, realHostName=self.server_address, num_users=num_players) + self.metas[meta].register(name=name, + realHostName=self.server_address, + num_users=num_players) else: - self.metas[meta] = registerThread(name=name, realHostName=self.server_address, num_users=num_players, MetaPath=meta, port=self.server_port,register_callback=self.register_callback) + self.metas[meta] = registerThread(name=name, realHostName=self.server_address, + num_users=num_players, MetaPath=meta, port=self.server_port, + register_callback=self.register_callback) self.metas[meta].start() #The register Rooms thread - self.be_registered = 1 thread.start_new_thread(self.registerRooms,(0,)) - - def unregister(self): + """ # loop through all existing meta entries # Don't rely on getMetaServers(), as a server may have been # removed since it was started. In that case, then the meta # would never get unregistered. # # Instead, loop through all existing meta threads and unregister them + """ for meta in self.metas.values(): if meta and meta.isAlive(): meta.unregister() self.be_registered = 0 + """ # This method runs as it's own thread and does the group_member_check every # sixty seconds. This should eliminate zombies that linger when no one is # around to spook them. GC: Frequency has been reduced as I question how valid # the implementation is as it will only catch a very small segment of lingering # connections. + """ def player_reaper_thread_func(self,arg): while self.alive: time.sleep(60) - self.p_lock.acquire() for group in self.groups.keys(): self.check_group_members(group) self.p_lock.release() @@ -771,7 +752,6 @@ while self.alive: self.p_lock.acquire() players = ServerPlugins.getPlayer() - for player in players: if player is not None: pass #Do something here so they can show up in the chat room for non web users' data = ServerPlugins.preParseOutgoing() @@ -779,28 +759,22 @@ try: xml_dom = parseXml(msg) xml_dom = xml_dom._get_documentElement() - if xml_dom.hasAttribute('from') and int(xml_dom.getAttribute('from')) > -1: xml_dom.setAttribute('from', '-1') - xml_dom.setAttribute('to', 'all') self.incoming_msg_handler(xml_dom, msg) xml_dom.unlink() except: pass - self.p_lock.release() time.sleep(0.250) - def sendMsg( self, sock, msg, useCompression=False, cmpType=None): """Very simple function that will properly encode and send a message to te remote on the specified socket.""" - if useCompression and cmpType != None: mpacket = cmpType.compress(msg) lpacket = pack('!i', len(mpacket)) sock.send(lpacket) - offset = 0 while offset < len(mpacket): slice = buffer(mpacket, offset, len(mpacket)-offset) @@ -821,7 +795,6 @@ """Simple socket receive method. This method will only return when the exact byte count has been read from the connection, if remote terminates our connection or we get some other socket exception.""" - data = "" offset = 0 try: @@ -834,7 +807,6 @@ else: # Continue to build complete message offset += rs data += frag - except socket.error, e: self.log_msg("Socket Error: recvData(): " + e ) data = "" @@ -853,18 +825,14 @@ msgData = "" try: lenData = self.recvData( sock, MPLAY_LENSIZE ) - # Now, convert to a usable form - (length,) = unpack('!i', lenData) - # Read exactly the remaining amount of data - msgData = self.recvData( sock, length ) + (length,) = unpack('!i', lenData) # Now, convert to a usable form + msgData = self.recvData( sock, length ) # Read exactly the remaining amount of data try: if useCompression and cmpType != None: msgData = cmpType.decompress(msgData) except: traceback.print_exc() - except Exception, e: self.log_msg( "Exception: recvMsg(): " + str(e) ) return msgData - def kill_server(self): self.alive = 0 self.log_msg("Server stopping...") @@ -872,10 +840,8 @@ for p in self.players.itervalues(): p.disconnect() self.incoming.put("<system/>") - for g in self.groups.itervalues(): g.save_map() - try: ip = socket.gethostbyname(socket.gethostname()) kill = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -892,15 +858,10 @@ self.incoming_event.wait(10) self.log_msg("Server stopped!") - - def log_msg(self,msg): if self.log_to_console: - if self.log_console: - self.log_console(msg) - else: - print str(msg) - + if self.log_console: self.log_console(msg) + else: print str(msg) def print_help(self): print @@ -937,11 +898,9 @@ print "'help' or '?' or 'h' - for this help message" print - def broadcast(self,msg): self.send_to_all("0","<msg to='all' from='0' group_id='1'><font color='#FF0000'>" + msg + "</font>") - def console_log(self): if self.log_to_console == 1: print "console logging now off" @@ -950,7 +909,6 @@ print "console logging now on" self.log_to_console = 1 - def groups_list(self): self.p_lock.acquire() try: @@ -958,26 +916,23 @@ for k in keys: pw = "-" pr = " -" - if self.groups[k].pwd != "": - pw = "P" - if self.isPersistentRoom( k ): - pr = " S" #using S for static (P for persistant conflicts with password) + if self.groups[k].pwd != "": pw = "P" + if self.isPersistentRoom( k ): pr = " S" #using S for static (P for persistant conflicts with password) print "Group: " + k + pr + pw + ' Name: ' + self.groups[k].name print - except Exception, e: self.log_msg(str(e)) - self.p_lock.release() -#---------------------------------------------------------------- -# Monitor Function -- Added by snowdog 2/05 -#---------------------------------------------------------------- + """ + #---------------------------------------------------------------- + # Monitor Function -- Added by snowdog 2/05 + #---------------------------------------------------------------- + """ def monitor(self, pid, mode=1 ): "allows monitoring of a specific user(s) network i/o" #if mode is not set to 1 then monitor adds toggles the state #of monitoring on the given user - if (mode == 1): for p in self.players: try: p.monitor("off") @@ -989,44 +944,29 @@ self.log_msg("Monitor: Invalid Player ID") traceback.print_exc() - def search(self,patern): keys = self.groups.keys() print "Search results:" for k in keys: ids = self.groups[k].get_player_ids() for id in ids: - if self.players[id].id.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].name.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].ip.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].group_id.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].role.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].version.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].protocol_version.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].client_string.find(patern)>-1: - self.print_player_info(self.players[id]) - + if self.players[id].id.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].name.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].ip.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].group_id.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].role.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].version.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].protocol_version.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].client_string.find(patern)>-1: self.print_player_info(self.players[id]) def print_player_info(self,player): - print player.id,player.name,player.ip,player.group_id, player.role,player.version,player.protocol_version,player.client_string + print player.id, player.name, player.ip, player.group_id, player.role, player.version, player.protocol_version, player.client_string + """ #---------------------------------------------------------------- # Uptime Function -- Added by snowdog 4/03 #---------------------------------------------------------------- + """ def uptime(self , mode = 0): "returns string containing how long server has been in operation" ut = time.time() - self.server_start_time @@ -1038,9 +978,11 @@ if mode == 0: print uts else: return uts + """ #----------------------------------------------------- # Toggle Room Password Allow -- Added by Snowdog 11/03 #----------------------------------------------------- + """ def RoomPasswords(self): if self.allow_room_passwords != 0: self.allow_room_passwords = 0 @@ -1049,7 +991,6 @@ self.allow_room_passwords = 1 return "Client Created Room Passwords: Allowed" - def group_dump(self,k): self.p_lock.acquire() try: @@ -1065,9 +1006,11 @@ self.log_msg(str(e)) self.p_lock.release() + """ #---------------------------------------------------------------- # Player List -- Added by snowdog 4/03 #---------------------------------------------------------------- + """ def player_list(self): "display a condensed list of players on the server" self.p_lock.acquire() @@ -1102,56 +1045,46 @@ keys = self.groups.keys() for k in keys: print "Group: %s %s (pass: \"%s\")" % (str(k),self.groups[k].name, self.groups[k].pwd) - ids = self.groups[k].get_player_ids() for id in ids: - if self.players.has_key(id): - print str(self.players[id]) + if self.players.has_key(id): print str(self.players[id]) else: self.groups[k].remove_player(id) print "Bad Player Ref (#" + id + ") in group" except Exception, e: self.log_msg(str(e)) - self.p_lock.release() - def update_request(self,newsock,xml_dom): # handle reconnects - self.log_msg( "update_request() has been called." ) # get player id id = xml_dom.getAttribute("id") group_id = xml_dom.getAttribute("group_id") - self.p_lock.acquire() if self.players.has_key(id): - self.sendMsg( newsock, self.players[id].toxml("update"), self.players[id].useCompression, self.players[id].compressionType ) + self.sendMsg(newsock, self.players[id].toxml("update"), + self.players[id].useCompression, + self.players[id].compressionType ) self.players[id].reset(newsock) self.players[id].clear_timeout() need_new = 0 - else: - need_new = 1 + else: need_new = 1 self.p_lock.release() - - if need_new: - self.new_request(newsock,xml_dom) + if need_new: self.new_request(newsock,xml_dom) else: msg = self.groups[group_id].game_map.get_all_xml() self.send(msg,id,group_id) - def new_request(self,newsock,xml_dom,LOBBY_ID='0'): #build client stub props = {} # Don't trust what the client tells us...trust what they connected as! props['ip'] = socket.gethostbyname( newsock.getpeername()[0] ) - try: - props['role'] = xml_dom.getAttribute("role") - except: - props['role'] = "GM" + try: props['role'] = xml_dom.getAttribute("role") + except: props['role'] = "GM" props['name'] = xml_dom.getAttribute("name") props['group_id'] = LOBBY_ID @@ -1159,28 +1092,21 @@ props['version'] = xml_dom.getAttribute("version") props['protocol_version'] = xml_dom.getAttribute("protocol_version") props['client_string'] = xml_dom.getAttribute("client_string") + self.next_player_id += 1 new_stub = client_stub(self.incoming,newsock,props,self.log_console) if xml_dom.hasAttribute('useCompression'): new_stub.useCompression = True - if xml_dom.hasAttribute('cmpType'): cmpType = xml_dom.getAttribute('cmpType') - if cmpBZ2 and cmpType == 'bz2': - new_stub.compressionType = bz2 - elif cmpZLIB and cmpType == 'zlib': - new_stub.compressionType = zlib - else: - new_stub.compressionType = None - else: - new_stub.compressionType = bz2 - - else: - new_stub.useCompression = False + if cmpBZ2 and cmpType == 'bz2': new_stub.compressionType = bz2 + elif cmpZLIB and cmpType == 'zlib': new_stub.compressionType = zlib + else: new_stub.compressionType = None + else: new_stub.compressionType = bz2 + else: new_stub.useCompression = False #update newly create client stub with network logging state new_stub.EnableMessageLogging = self.log_network_messages - self.sendMsg(newsock, new_stub.toxml("new"), False, None) # try to remove circular refs @@ -1206,13 +1132,10 @@ print "Error in parse found from " + str(remote_host) + ". Disconnected." print " Offending data(" + str(len(data)) + "bytes)=" + data print "Exception=" + str(e) - - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return #start threads and store player - allowed = 1 version_string = "" @@ -1222,12 +1145,16 @@ if not self.checkClientVersion(props['version']): version_string = "Sorry, your client is out of date. <br />" - version_string += "This server requires your client be version " + self.minClientVersion + " or higher to connect.<br />" + version_string += "This server requires your client be version " + version_string += "" + self.minClientVersion + " or higher to connect.<br />" allowed = 0 if not allowed: - version_string += ' Please go to <a href="http://openrpg.digitalxero.net">http://openrpg.digitalxero.net</a> to find a compatible client.<br />' - version_string += "If you can't find a compatible client on the website, chances are that the server is running an unreleased development version for testing purposes.<br />" + version_string += " Please go to <a href='http://www.assembla.com/traipse'>" + version_string += "http://www.assembla.com/traipse</a> to find a compatible client.<br />" + version_string += "If you can't find a compatible client on the website, " + version_string += "chances are that the server is running an unreleased development " + version_string += "version for testing purposes.<br />" self.sendMsg( newsock, "<msg to='" + props['id'] + "' from='0' group_id='0' />" + version_string, new_stub.useCompression, new_stub.compressionType) # Give messages time to flow @@ -1244,7 +1171,6 @@ cmsg = "Banned Client: (" + str(props['id']) + ") " + str(props['name']) + " [" + str(props['ip']) + "]" self.log_msg(cmsg) allowed = 0 - self.sendMsg( newsock, "<msg to='" + props['id'] + "' from='0' group_id='0' />" + banmsg, new_stub.useCompression, new_stub.compressionType) # Give messages time to flow time.sleep(1) @@ -1253,6 +1179,7 @@ xml_dom.unlink() return None + """ #---- Connection order changed by Snowdog 1/05 #---- Attempt to register player and send group data #---- before displaying lobby message @@ -1264,6 +1191,7 @@ #---- to clients. Not sure why the group messages were being sent to the #---- incomming message queue, when they should be sent directly to user #---- Does not solve the black hole bug totally -SD + """ try: if xml_dom.getAttribute("id") == props['id']: @@ -1274,7 +1202,6 @@ self.send_group_list(props['id']) self.send_player_list(props['id'],LOBBY_ID) self.p_lock.release() - msg = self.groups[LOBBY_ID].game_map.get_all_xml() self.send(msg,props['id'],LOBBY_ID) self.send_to_group(props['id'],LOBBY_ID,self.players[props['id']].toxml('new')) @@ -1282,7 +1209,6 @@ # Re-initialize the role for this player incase they came from a different server self.handle_role("set",props['id'], "GM",self.groups[LOBBY_ID].boot_pwd, LOBBY_ID) - cmsg = "Client Connect: (" + str(props['id']) + ") " + str(props['name']) + " [" + str(props['ip']) + "]" self.log_msg(cmsg) cmsg = ("connect", props) ################################################# @@ -1305,14 +1231,11 @@ time.sleep(2) newsock.close() - # Display the lobby message self.SendLobbyMessage(newsock,props['id']) - if xml_dom: xml_dom.unlink() - def checkClientVersion(self, clientversion): minv = self.minClientVersion.split('.') cver = clientversion.split('.') @@ -1320,53 +1243,47 @@ w=max(len(minv[i]),len(cver[i])) v1=minv[i].rjust(w); v2=cver[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 - - if len(minv)>len(cver): - return 0 + if v1<v2: return 1 + if v1>v2: return 0 + if len(minv)>len(cver): return 0 return 1 - - def SendLobbyMessage(self, socket, player_id): - ####################################################################### + """ # Display the lobby message # prepend this server's version string to the the lobby message + """ try: - lobbyMsg = "You have connected to an <a href=\"http://www.openrpg.com\">OpenRPG</a> server, version '" + VERSION + "'" + lobbyMsg = "You have connected to an <a href=\"http://www.openrpg.com\">OpenRPG</a> " + lobbyMsg += "server, version '" + VERSION + "'" # See if we have a server name to report! - if len(self.serverName): lobbyMsg += ", named '" + self.serverName + "'." - else: lobbyMsg += "." # Add extra line spacing lobbyMsg += "\n\n" - try: - self.validate.config_file("LobbyMessage.html","default_LobbyMessage.html") - except: - pass + try: validate.config_file("LobbyMessage.html","default_LobbyMessage.html") + except: pass else: open_msg = open( self.userPath + "LobbyMessage.html", "r" ) lobbyMsg += open_msg.read() open_msg.close() # Send the server's lobby message to the client no matter what - self.sendMsg(socket, "<msg to='" + player_id + "' from='0' group_id='0' />" + lobbyMsg, self.players[player_id].useCompression, self.players[player_id].compressionType) + self.sendMsg(socket, "<msg to='" + player_id + "' from='0' group_id='0' />" + lobbyMsg, + self.players[player_id].useCompression, self.players[player_id].compressionType) if self.sendLobbySound: - self.sendMsg(socket, '<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />', self.players[player_id].useCompression, self.players[player_id].compressionType) + self.sendMsg(socket, '<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />', + self.players[player_id].useCompression, self.players[player_id].compressionType) return - except: - traceback.print_exc() + except: traceback.print_exc() + """ # End of lobby message code - ####################################################################### + """ def listenAcceptThread(self,arg): @@ -1374,8 +1291,7 @@ try: self.log_msg("\nlisten thread running...") adder = "" - if self.server_address is not None: - adder = self.server_address + if self.server_address is not None: adder = self.server_address self.listen_sock.bind(('', self.server_port)) self.listen_sock.listen(5) @@ -1383,18 +1299,18 @@ self.log_msg(("Error binding request socket!", e)) self.alive = 0 - while self.alive: - # Block on the socket waiting for a new connection try: (newsock, addr) = self.listen_sock.accept() + """ ## self.log_msg("New connection from " + str(addr)+ ". Interfacing with server...") # Now that we've accepted a new connection, we must immediately spawn a new # thread to handle it...otherwise we run the risk of having a DoS shoved into # our face! :O After words, this thread is dead ready for another connection # accept to come in. + """ thread.start_new_thread(self.acceptedNewConnectionThread, ( newsock, addr )) except: @@ -1405,11 +1321,8 @@ self.log_msg("server socket listening thread exiting...") self.listen_event.set() - - def acceptedNewConnectionThread( self, newsock, addr ): """Once a new connection comes in and is accepted, this thread starts up to handle it.""" - # Initialize xml_dom xml_dom = None data = None @@ -1417,51 +1330,36 @@ # get client info and send othe client info # If this receive fails, this thread should exit without even attempting to process it self.log_msg("Connection from " + str(addr) + " has been accepted. Waiting for data...") - data = self.recvMsg( newsock ) - if data=="" or data == None: self.log_msg("Connection from " + str(addr) + " failed. Closing connection.") - try: - newsock.close() + try: newsock.close() except Exception, e: self.log_msg( str(e) ) print str(e) return #returning causes connection thread instance to terminate - - if data == "<system/>": - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass return #returning causes connection thread instance to terminate - # Clear out the xml_dom in preparation for new stuff, if necessary try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except: self.log_msg( "The following exception caught unlinking xml_dom:") self.log_msg("Continuing") - - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass return #returning causes connection thread instance to terminate - # Parse the XML received from the connecting client try: xml_dom = parseXml(data) xml_dom = xml_dom._get_documentElement() except: - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass self.log_msg( "Error in parse found from " + str(addr) + ". Disconnected.") self.log_msg(" Offending data(" + str(len(data)) + "bytes)=" + data) self.log_msg( "Exception:") @@ -1474,14 +1372,9 @@ action = xml_dom.getAttribute("action") # Figure out what type of connection we have going on now - if action == "new": - self.new_request(newsock,xml_dom) - - elif action == "update": - self.update_request(newsock,xml_dom) - - else: - self.log_msg("Unknown Join Request!") + if action == "new": self.new_request(newsock,xml_dom) + elif action == "update": self.update_request(newsock,xml_dom) + else: self.log_msg("Unknown Join Request!") except Exception, e: print "The following message: " + str(data) @@ -1491,15 +1384,13 @@ # Again attempt to clean out DOM stuff try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except: print "The following exception caught unlinking xml_dom:" traceback.print_exc() return #returning causes connection thread instance to terminate - - + """ #======================================================== # # Message_handler @@ -1509,21 +1400,20 @@ # Changed thread organization from one continuous parsing/handling thread # to multiple expiring parsing/handling threads to improve server performance # and player load capacity -- Snowdog 3/04 + """ def message_handler(self,arg): xml_dom = None self.log_msg( "message handler thread running..." ) while self.alive: data = None - try: - data=self.incoming.get(0) + try: data=self.incoming.get(0) except Queue.Empty: time.sleep(0.5) #sleep 1/2 second continue bytes = len(data) - if bytes <= 0: - continue + if bytes <= 0: continue try: thread.start_new_thread(self.parse_incoming_dom,(str(data),)) #data has been passed... unlink from the variable references @@ -1551,20 +1441,15 @@ print "Error in parse of inbound message. Ignoring message." print " Offending data(" + str(len(data)) + "bytes)=" + data print "Exception=" + str(e) - if xml_dom: xml_dom.unlink() - def message_action(self, xml_dom, data): tag_name = xml_dom._get_tagName() - if self.svrcmds.has_key(tag_name): - self.svrcmds[tag_name]['function'](xml_dom,data) - else: - raise Exception, "Not a valid header!" + if self.svrcmds.has_key(tag_name): self.svrcmds[tag_name]['function'](xml_dom,data) + else: raise Exception, "Not a valid header!" #Message Action thread expires and closes here. return - def do_alter(self, xml_dom, data): target = xml_dom.getAttribute("key") value = xml_dom.getAttribute("val") @@ -1574,14 +1459,15 @@ actual_boot_pwd = self.groups[group_id].boot_pwd if self.allow_room_passwords == 0: - msg ="<msg to='" + player + "' from='0' group_id='0' /> Room passwords have been disabled by the server administrator." + msg ="<msg to='" + player + "' from='0' group_id='0' /> " + msg += "Room passwords have been disabled by the server administrator." self.players[player].outbox.put(msg) return elif boot_pwd == actual_boot_pwd: if target == "pwd": - lmessage = "Room password changed to from \"" + self.groups[group_id].pwd + "\" to \"" + value + "\" by " + player + lmessage = "Room password changed to from " + self.groups[group_id].pwd + " to " + value + " by " + player self.groups[group_id].pwd = value - msg ="<msg to='" + player + "' from='0' group_id='0' /> Room password changed to \"" + value + "\"." + msg ="<msg to='" + player + "' from='0' group_id='0' /> Room password changed to " + value + "." self.players[player].outbox.put(msg) self.log_msg(lmessage) self.send_to_all('0',self.groups[group_id].toxml('update')) @@ -1595,7 +1481,6 @@ msg ="<msg to='" + player + "' from='0' group_id='0'>Invalid Administrator Password." self.players[player].outbox.put(msg) - def do_role(self, xml_dom, data): role = "" boot_pwd = "" @@ -1615,17 +1500,12 @@ group_id = xml_dom.getAttribute("group_id") sent_time = "" msg = "" - try: - sent_time = xml_dom.getAttribute("time") - except: - pass - - if sent_time != "": - #because a time was sent return a ping response - msg ="<ping time='" + str(sent_time) + "' />" + try: sent_time = xml_dom.getAttribute("time") + except: pass + if sent_time != "": msg ="<ping time='" + str(sent_time) + "' />" #because a time was sent return a ping response else: - msg ="<msg to='" + player + "' from='" + player + "' group_id='" + group_id + "'><font color='#FF0000'>PONG!?!</font>" - + msg ="<msg to='" + player + "' from='" + player + "' group_id='" + group_id + "'>" + msg += "<font color='#FF0000'>PONG!?!</font>" self.players[player].outbox.put(msg) xml_dom.unlink() @@ -1636,65 +1516,43 @@ try: action = xml_dom.getAttribute("action") from_id = xml_dom.getAttribute("from") - if xml_dom.hasAttribute("pwd"): - pwd=xml_dom.getAttribute("pwd") - else: - pwd="" + if xml_dom.hasAttribute("pwd"): pwd=xml_dom.getAttribute("pwd") + else: pwd="" group_id=self.players[from_id].group_id - if action == "list": if (self.groups[group_id].moderated): msg = "" for i in self.groups[group_id].voice.keys(): - if msg != "": - msg +=", " - if self.players.has_key(i): - msg += '('+i+') '+self.players[i].name - else: - del self.groups[group_id].voice[i] - if (msg != ""): - msg = "The following users may speak in this room: " + msg - else: - msg = "No people are currently in this room with the ability to chat" + if msg != "": msg +=", " + if self.players.has_key(i): msg += '('+i+') '+self.players[i].name + else: del self.groups[group_id].voice[i] + if (msg != ""): msg = "The following users may speak in this room: " + msg + else: msg = "No people are currently in this room with the ability to chat" self.players[from_id].self_message(msg) - else: - self.players[from_id].self_message("This room is currently unmoderated") - elif action == "enable": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - self.groups[group_id].moderated = 1 - self.players[from_id].self_message("This channel is now moderated") - elif action == "disable": + else: self.players[from_id].self_message("This room is currently unmoderated") + elif action == 'enable' or 'disable' or 'addvoice' or 'delvoice': + #condenses password check --TaS 2009 if not self.groups[group_id].check_boot_pwd(pwd): self.players[from_id].self_message("Failed - incorrect admin password") return - self.groups[group_id].moderated = 0 - self.players[from_id].self_message("This channel is now unmoderated") - elif action == "addvoice": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - users = xml_dom.getAttribute("users").split(',') - for i in users: - self.groups[group_id].voice[i.strip()]=1 - elif action == "delvoice": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - users = xml_dom.getAttribute("users").split(',') - for i in users: - if self.groups[group_id].voice.has_key(i.strip()): - del self.groups[group_id].voice[i.strip()] + if action == 'enable': + self.groups[group_id].moderated = 1 + self.players[from_id].self_message("This channel is now moderated") + if action == 'disable': + self.groups[group_id].moderated = 0 + self.players[from_id].self_message("This channel is now unmoderated") + if action == 'addvoice': + users = xml_dom.getAttribute("users").split(',') + for i in users: self.groups[group_id].voice[i.strip()]=1 + if action == 'delvoice': + users = xml_dom.getAttribute("users").split(',') + for i in users: + if self.groups[group_id].voice.has_key(i.strip()): del self.groups[group_id].voice[i.strip()] else: print "Bad input: " + data - except Exception,e: self.log_msg(str(e)) - - - def join_group(self,xml_dom,data): try: from_id = xml_dom.getAttribute("from") @@ -1713,7 +1571,6 @@ #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"room\" id=\"" + group_id + "\" data=\"\"/>" self.players[from_id].outbox.put(pm) - msg = 'failed - incorrect room password' if not allowed: @@ -1727,19 +1584,16 @@ #move the player into their new group. self.move_player(from_id, group_id) - except Exception, e: self.log_msg(str(e)) - - - - #---------------------------------------------------------------------------- + """ # move_player function -- added by Snowdog 4/03 # # Split join_group function in half. separating the player validation checks # from the actual group changing code. Done primarily to impliment # boot-from-room-to-lobby behavior in the server. + """ def move_player(self, from_id, group_id ): "move a player from one group to another" @@ -1758,19 +1612,20 @@ self.send_to_group(from_id,group_id,self.players[from_id].toxml('new')) self.check_group(from_id, old_group_id) + """ # Here, if we have a group specific lobby message to send, push it on # out the door! Make it put the message then announce the player...just # like in the lobby during a new connection. # -- only do this check if the room id is within range of known persistent id thresholds #also goes ahead if there is a defaultRoomMessage --akoman + """ if self.isPersistentRoom(group_id) or self.defaultMessageFile != None: try: if self.groups[group_id].messageFile[:4] == 'http': data = urllib.urlretrieve(self.groups[group_id].messageFile) roomMsgFile = open(data[0]) - else: - roomMsgFile = open(self.groups[group_id].messageFile, "r") + else: roomMsgFile = open(self.groups[group_id].messageFile, "r") roomMsg = roomMsgFile.read() roomMsgFile.close() urllib.urlcleanup() @@ -1781,24 +1636,18 @@ # Spit that darn message out now! self.players[from_id].outbox.put("<msg to='" + from_id + "' from='0' group_id='" + group_id + "' />" + roomMsg) - if self.sendLobbySound and group_id == '0': self.players[from_id].outbox.put('<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />') - # Now, tell everyone that we've arrived self.send_to_all('0', self.groups[group_id].toxml('update')) - # this line sends a handle role message to change the players role self.send_player_list(from_id,group_id) - #notify user about others in the room self.return_room_roles(from_id,group_id) self.log_msg(("join_group", (self.groups[group_id].name, group_id, from_id))) self.handle_role("set", from_id, self.players[from_id].role, self.groups[group_id].boot_pwd, group_id) - except Exception, e: self.log_msg(str(e)) - thread.start_new_thread(self.registerRooms,(0,)) def return_room_roles(self,from_id,group_id): @@ -1807,12 +1656,13 @@ msg = "<role action=\"update\" id=\"" + self.players[m].id + "\" role=\"" + self.players[m].role + "\" />" self.players[from_id].outbox.put(msg) - + """ # This is pretty much the same thing as the create_group method, however, # it's much more generic whereas the create_group method is tied to a specific # xml message. Ack! This version simply creates the groups, it does not # send them to players. Also note, both these methods have race # conditions written all over them. Ack! Ack! + """ def new_group( self, name, pwd, boot, minVersion, mapFile, messageFile, persist = 0, moderated=0 ): group_id = str( self.next_group_id ) self.next_group_id += 1 @@ -1824,7 +1674,6 @@ self.log_msg( lmsg ) self.log_msg(("create_group", (str(name), int(group_id), 0) )) ##-99 works, could be better. - def change_group_name(self,gid,name,pid): "Change the name of a group" # Check for & in name. We want to allow this because of its common @@ -1839,7 +1688,6 @@ e = name[loc+1:] value = b + "&" + e oldloc = loc+1 - loc = name.find("'") oldloc = 0 while loc > -1: @@ -1849,7 +1697,6 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - loc = name.find('"') oldloc = 0 while loc > -1: @@ -1859,20 +1706,15 @@ e = name[loc+1:] name = b + """ + e oldloc = loc+1 - oldroomname = self.groups[gid].name self.groups[gid].name = str(name) lmessage = "Room name changed to from \"" + oldroomname + "\" to \"" + name + "\"" self.log_msg(lmessage + " by " + str(pid) ) self.send_to_all('0',self.groups[gid].toxml('update')) return lmessage - except: - return "An error occured during rename of room!" - + except: return "An error occured during rename of room!" thread.start_new_thread(self.registerRooms,(0,)) - - def create_group(self,xml_dom,data): try: from_id = xml_dom.getAttribute("from") @@ -1886,8 +1728,6 @@ # see if passwords are allowed on this server and null password if not if self.allow_room_passwords != 1: pwd = "" - - # # Check for & in name. We want to allow this because of its common # use in d&d games. @@ -1900,7 +1740,6 @@ e = name[loc+1:] name = b + "&" + e oldloc = loc+1 - loc = name.find("'") oldloc = 0 while loc > -1: @@ -1910,7 +1749,6 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - loc = name.find('"') oldloc = 0 while loc > -1: @@ -1920,8 +1758,6 @@ e = name[loc+1:] name = b + """ + e oldloc = loc+1 - - group_id = str(self.next_group_id) self.next_group_id += 1 self.groups[group_id] = game_group(group_id,name,pwd,"",boot_pwd, minVersion, None, messageFile ) @@ -1945,20 +1781,14 @@ data = urllib.urlretrieve(self.defaultMessageFile) open_msg = open(data[0]) urllib.urlcleanup() - else: - open_msg = open( self.defaultMessageFile, "r" ) - + else: open_msg = open( self.defaultMessageFile, "r" ) roomMsg = open_msg.read() open_msg.close() # Send the rooms message to the client no matter what self.players[from_id].outbox.put( "<msg to='" + from_id + "' from='0' group_id='" + group_id + "' />" + roomMsg ) - - except Exception, e: - self.log_msg( "Exception: create_group(): " + str(e)) - + except Exception, e: self.log_msg( "Exception: create_group(): " + str(e)) thread.start_new_thread(self.registerRooms,(0,)) - def check_group(self, from_id, group_id): try: if group_id not in self.groups: return @@ -1969,15 +1799,12 @@ self.send_to_all("0",self.groups[group_id].toxml('del')) del self.groups[group_id] self.log_msg(("delete_group", (group_id, from_id))) - - else: - self.send_to_all("0",self.groups[group_id].toxml('update')) + else: self.send_to_all("0",self.groups[group_id].toxml('update')) #The register Rooms thread thread.start_new_thread(self.registerRooms,(0,)) - except Exception, e: - self.log_msg(str(e)) + except Exception, e: self.log_msg(str(e)) def del_player(self,id,group_id): try: @@ -1987,23 +1814,17 @@ del self.players[id] self.log_msg(dmsg) self.log_msg(("disconnect",id)) - - + """ # If already registered then re-register, thereby updating the Meta # on the number of players # Note: Upon server shutdown, the server is first unregistered, so # this code won't be repeated for each player being deleted. + """ if self.be_registered: self.register() - - - except Exception, e: - self.log_msg(str(e)) - + except Exception, e: self.log_msg(str(e)) self.log_msg("Explicit garbage collection shows %s undeletable items." % str(gc.collect())) - - def incoming_player_handler(self,xml_dom,data): id = xml_dom.getAttribute("id") act = xml_dom.getAttribute("action") @@ -2011,16 +1832,13 @@ group_id = self.players[id].group_id ip = self.players[id].ip self.log_msg("Player with IP: " + str(ip) + " joined.") - ServerPlugins.setPlayer(self.players[id]) - self.send_to_group(id,group_id,data) if act=="new": try: self.send_player_list(id,group_id) self.send_group_list(id) - except Exception, e: - traceback.print_exc() + except Exception, e: traceback.print_exc() elif act=="del": #print "del player" self.del_player(id,group_id) @@ -2039,31 +1857,26 @@ "ping": xml_dom.getAttribute("time") \ })) - def strip_cheat_roll(self, string): try: cheat_regex = re.compile('&#91;(.*?)&#93;') string = cheat_regex.sub( r'[ ' + self.cheat_msg + " \\1 " + self.cheat_msg + ' ]', string) - except: - pass + except: pass return string def strip_body_tags(self, string): try: bodytag_regex = re.compile('<\/?body(.*?)>') string = bodytag_regex.sub('', string) - except: - pass + except: pass return string def msgTooLong(self, length): - if length > self.maxSendSize and not self.maxSendSize == 0: - return True + if length > self.maxSendSize and not self.maxSendSize == 0: return True return False def incoming_msg_handler(self,xml_dom,data): xml_dom, data = ServerPlugins.preParseIncoming(xml_dom, data) - to_id = xml_dom.getAttribute("to") from_id = xml_dom.getAttribute("from") group_id = xml_dom.getAttribute("group_id") @@ -2074,15 +1887,10 @@ print "WARNING!! Message received with an invalid from_id. Message dropped." return None - # - # check for < body to prevent someone from changing the background - # - + """ check for < body to prevent someone from changing the background""" data = self.strip_body_tags(data) - # - # check for [ and ] codes which are often used to cheat with dice. - # + """check for [ and ] codes which are often used to cheat with dice.""" if self.players[from_id].role != "GM": data = self.strip_cheat_roll(data) @@ -2110,19 +1918,15 @@ if to_id == 'all': if self.groups[group_id].moderated and not self.groups[group_id].voice.has_key(from_id): self.players[from_id].self_message('This room is moderated - message not sent to others') - else: - self.send_to_group(from_id,group_id,data) - else: - self.players[to_id].outbox.put(data) - + else: self.send_to_group(from_id,group_id,data) + else: self.players[to_id].outbox.put(data) self.check_group_members(group_id) return def sound_msg_handler(self, xml_dom, data): from_id = xml_dom.getAttribute("from") group_id = xml_dom.getAttribute("group_id") - if group_id != 0: - self.send_to_group(from_id, group_id, data) + if group_id != 0: self.send_to_group(from_id, group_id, data) def plugin_msg_handler(self,xml_dom,data): to_id = xml_dom.getAttribute("to") @@ -2134,16 +1938,11 @@ if from_id == "0" or len(from_id) == 0: print "WARNING!! Message received with an invalid from_id. Message dropped." return None - - if to_id == 'all': if self.groups[group_id].moderated and not self.groups[group_id].voice.has_key(from_id): self.players[from_id].self_message('This room is moderated - message not sent to others') - else: - self.send_to_group(from_id, group_id, msg) - else: - self.players[to_id].outbox.put(msg) - + else: self.send_to_group(from_id, group_id, msg) + else: self.players[to_id].outbox.put(msg) self.check_group_members(group_id) return @@ -2153,8 +1952,7 @@ msg += "Displaying Roles<br /><br /><u>Role</u>   <u>Player</u><br />" keys = self.players.keys() for m in keys: - if self.players[m].group_id == group_id: - msg += self.players[m].role + " " + self.players[m].name + "<br />" + if self.players[m].group_id == group_id: msg += self.players[m].role + " " + self.players[m].name + "<br />" self.send(msg,player,group_id) elif act == "set": try: @@ -2167,8 +1965,7 @@ msg = "<role action=\"update\" id=\"" + player + "\" role=\"" + role + "\" />" self.send_to_group("0", group_id, msg) self.players[player].role = role - if (role.lower() == "gm" or role.lower() == "player"): - self.groups[group_id].voice[player]=1 + if (role.lower() == "gm" or role.lower() == "player"): self.groups[group_id].voice[player]=1 else: #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"admin\" id=\"" + group_id + "\" data=\"\"/>" @@ -2198,25 +1995,22 @@ try: actual_boot_pwd = self.groups[group_id].boot_pwd server_admin_pwd = self.groups["0"].boot_pwd - self.log_msg("Actual boot pwd = " + actual_boot_pwd) self.log_msg("Given boot pwd = " + given_boot_pwd) if self.players[to_id].group_id == group_id: - + """ ### ---CHANGES BY SNOWDOG 4/03 --- ### added boot to lobby code. ### if boot comes from lobby dump player from the server ### any user in-room boot will dump to lobby instead + """ if given_boot_pwd == server_admin_pwd: # Send a message to everyone in the room, letting them know someone has been booted boot_msg = "<msg to='all' from='%s' group_id='%s'/><font color='#FF0000'>Booting '(%s) %s' from server...</font>" % (from_id, group_id, to_id, self.players[to_id].name) - self.log_msg("boot_msg:" + boot_msg) - self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) - self.log_msg("Booting player " + str(to_id) + " from server.") # Send delete player event to all @@ -2231,9 +2025,7 @@ elif actual_boot_pwd == given_boot_pwd: # Send a message to everyone in the room, letting them know someone has been booted boot_msg = "<msg to='all' from='%s' group_id='%s'/><font color='#FF0000'>Booting '(%s) %s' from room...</font>" % (from_id, group_id, to_id, self.players[to_id].name) - self.log_msg("boot_msg:" + boot_msg) - self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) @@ -2254,17 +2046,15 @@ finally: try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except Exception, e: traceback.print_exc() self.log_msg('Exception in xml_dom.unlink() ' + str(e)) - - #--------------------------------------------------------------- + """ # admin_kick function -- by Snowdog 4/03 # 9/17/05 updated to allow stealth boots (no client chat announce) -SD - #--------------------------------------------------------------- + """ def admin_kick(self, id, message="", silent = 0 ): "Kick a player from a server from the console" @@ -2273,8 +2063,7 @@ # Send a message to everyone in the victim's room, letting them know someone has been booted boot_msg = "<msg to='all' from='0' group_id='%s'/><font color='#FF0000'>Kicking '(%s) %s' from server... %s</font>" % ( group_id, id, self.players[id].name, str(message)) self.log_msg("boot_msg:" + boot_msg) - if (silent == 0): - self.send_to_group( "0", group_id, boot_msg ) + if (silent == 0): self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) self.log_msg("kicking player " + str(id) + " from server.") @@ -2291,7 +2080,6 @@ traceback.print_exc() self.log_msg('Exception in admin_kick() ' + str(e)) - def admin_banip(self, ip, name="", silent = 0): "Ban a player from a server from the console" try: @@ -2338,9 +2126,7 @@ def admin_unban(self, ip): try: - if self.ban_list.has_key(ip): - del self.ban_list[ip] - + if self.ban_list.has_key(ip): del self.ban_list[ip] self.saveBanList() except Exception, e: @@ -2357,15 +2143,11 @@ msg.append(self.ban_list[ip]['ip']) msg.append("</td></tr>") msg.append("</table>") - return "".join(msg) def admin_toggleSound(self): - if self.sendLobbySound: - self.sendLobbySound = False - else: - self.sendLobbySound = True - + if self.sendLobbySound: self.sendLobbySound = False + else: self.sendLobbySound = True return self.sendLobbySound def admin_soundFile(self, file): @@ -2384,16 +2166,13 @@ self.groups[group].persistant = 0 try: keys = self.groups[group].get_player_ids() - for k in keys: - self.del_player(k, str(group)) + for k in keys: self.del_player(k, str(group)) self.check_group("0", str(group)) - except: - pass + except: pass def send(self,msg,player,group): self.players[player].send(msg,player,group) - def send_to_all(self,from_id,data): try: print data @@ -2401,8 +2180,7 @@ keys = self.players.keys() self.p_lock.release() for k in keys: - if k != from_id: - self.players[k].outbox.put(data) + if k != from_id: self.players[k].outbox.put(data) except Exception, e: traceback.print_exc() self.log_msg("Exception: send_to_all(): " + str(e)) @@ -2415,8 +2193,7 @@ keys = self.groups[group_id].get_player_ids() self.p_lock.release() for k in keys: - if k != from_id: - self.players[k].outbox.put(data) + if k != from_id: self.players[k].outbox.put(data) except Exception, e: traceback.print_exc() self.log_msg("Exception: send_to_group(): " + str(e)) @@ -2441,24 +2218,24 @@ self.log_msg("Exception: send_group_list(): (client #"+to_id+") : " + str(e)) traceback.print_exc() - #-------------------------------------------------------------------------- + """ # KICK_ALL_CLIENTS() # # Convience method for booting all clients off the server at once. # used while troubleshooting mysterious "black hole" server bug # Added by Snowdog 11-19-04 + """ def kick_all_clients(self): try: keys = self.groups.keys() for k in keys: pl = self.groups[k].get_player_ids() - for p in pl: - self.admin_kick(p,"Purged from server") + for p in pl: self.admin_kick(p,"Purged from server") except Exception, e: traceback.print_exc() self.log_msg("Exception: kick_all_clients(): " + str(e)) - + """ # This really has little value as it will only catch people that are hung # on a disconnect which didn't complete. Other idle connections which are # really dead go undeterred. @@ -2466,6 +2243,7 @@ # UPDATED 11-29-04: Changed remove XML send to forced admin_kick for 'dead clients' # Dead clients now removed more effeciently as soon as they are detected # --Snowdog + """ def check_group_members(self, group_id): try: keys = self.groups[group_id].get_player_ids() @@ -2474,8 +2252,7 @@ #as these are likely dead clients idlemins = self.players[k].idle_time() idlemins = idlemins/60 - if (idlemins > self.zombie_time): - self.admin_kick(k,"Removing zombie client", self.silent_auto_kick) + if (idlemins > self.zombie_time): self.admin_kick(k,"Removing zombie client", self.silent_auto_kick) elif self.players[k].get_status() != MPLAY_CONNECTED: if self.players[k].check_time_out(): self.log_msg("Player #" + k + " Lost connection!") @@ -2485,13 +2262,12 @@ def remote_admin_handler(self,xml_dom,data): + """ # handle incoming remove server admin messages # (allows basic administration of server from a remote client) # base message format: <admin id="" pwd="" cmd="" [data for command]> - - if not self.allowRemoteAdmin: - return - + """ + if not self.allowRemoteAdmin: return try: pid = xml_dom.getAttribute("id") gid = "" @@ -2502,7 +2278,6 @@ p_name= "" p_ip = "" - #verify that the message came from the proper ID/Socket and get IP address for logging if self.players.has_key(pid): p_name=(self.players[pid]).name @@ -2524,44 +2299,40 @@ #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"server\" id=\"" + str(self.players[pid].group_id) + "\" data=\"\"/>" self.players[pid].outbox.put(pm) - m = "Invalid Remote Server Control Message (bad password) from #" + str(pid) + " (" + str(p_name) + ") " + str(p_ip) + m = "Invalid Remote Server Control Message (bad password) from " + m += "#" + str(pid) + " (" + str(p_name) + ") " + str(p_ip) self.log_msg( m ) return #message now deemed 'authentic' #determine action to take based on command (cmd) - if cmd == "list": #return player list to this user. msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.player_list_remote() self.players[pid].outbox.put(msg) - elif cmd == "banip": ip = xml_dom.getAttribute("bip") name = xml_dom.getAttribute("bname") msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'> Banned: " + str(ip) self.admin_banip(ip, name) - elif cmd == "ban": id = xml_dom.getAttribute("bid") msg = "<msg to='" + id + "' from='0' group_id='" + gid + "'> Banned!" self.players[pid].outbox.put(msg) self.admin_ban(id, "") - elif cmd == "unban": ip = xml_dom.getAttribute("ip") self.admin_unban(ip) msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'> Unbaned: " + str(ip) self.players[pid].outbox.put(msg) - elif cmd == "banlist": msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.admin_banlist() self.players[pid].outbox.put(msg) - elif cmd == "killgroup": ugid = xml_dom.getAttribute("gid") if ugid == "0": - m = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>Cannot Remove Lobby! Remote administrator request denied!" + m = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + m += "Cannot Remove Lobby! Remote administrator request denied!" self.players[pid].outbox.put(m) else: result = self.prune_room(ugid) @@ -2576,30 +2347,24 @@ except: msg = "<msg to='" + pid + "' from='0' group_id='" + gid + ">Unknown Player ID: No message sent." self.players[pid].outbox.put(msg) - elif cmd == "broadcast": bmsg = xml_dom.getAttribute("msg") self.broadcast(bmsg) - elif cmd == "killserver" and self.allowRemoteKill: #dangerous command..once server stopped it must be restarted manually self.kill_server() - elif cmd == "uptime": msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.uptime(1) self.players[pid].outbox.put(msg) - elif cmd == "help": msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" msg += self.AdminHelpMessage() self.players[pid].outbox.put( msg) - elif cmd == "roompasswords": # Toggle if room passwords are allowed on this server msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" msg += self.RoomPasswords() self.players[pid].outbox.put( msg) - elif cmd == "createroom": rm_name = xml_dom.getAttribute("name") rm_pass = xml_dom.getAttribute("pass") @@ -2607,19 +2372,18 @@ result = self.create_temporary_persistant_room(rm_name, rm_boot, rm_pass) msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + result self.players[pid].outbox.put(msg) - elif cmd == "nameroom": rm_id = xml_dom.getAttribute("rmid") rm_name = xml_dom.getAttribute("name") result = self.change_group_name(rm_id,rm_name,pid) msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'/>" + result self.players[pid].outbox.put(msg) - elif cmd == "passwd": tgid = xml_dom.getAttribute("gid") npwd = xml_dom.getAttribute("pass") if tgid == "0": - msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Server password may not be changed remotely!" + msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + msg += "Server password may not be changed remotely!" self.players[pid].outbox.put(msg) else: try: @@ -2627,81 +2391,72 @@ msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Password changed for room " + tgid self.players[pid].outbox.put(msg) except: pass - elif cmd == "savemaps": for g in self.groups.itervalues(): g.save_map() - msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Persistent room maps saved" self.players[pid].outbox.put(msg) - - else: msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'><i>[Unknown Remote Administration Command]</i>" self.players[pid].outbox.put(msg) - - except Exception, e: self.log_msg("Exception: Remote Admin Handler Error: " + str(e)) traceback.print_exc() - def toggleRemoteKill(self): - if self.allowRemoteKill: - self.allowRemoteKill = False - else: - self.allowRemoteKill = True - + if self.allowRemoteKill: self.allowRemoteKill = False + else: self.allowRemoteKill = True return self.allowRemoteKill def toggleRemoteAdmin(self): - if self.allowRemoteAdmin: - self.allowRemoteAdmin = False - else: - self.allowRemoteAdmin = True - + if self.allowRemoteAdmin: self.allowRemoteAdmin = False + else: self.allowRemoteAdmin = True return self.allowRemoteAdmin -#----------------------------------------------------------------- -# Remote Administrator Help (returns from server not client) -#----------------------------------------------------------------- + """ + # Remote Administrator Help (returns from server not client) + """ def AdminHelpMessage(self): "returns a string to be sent as a message to a remote admin" - #define the help command list information info = [] info.append( ['list', '/admin list', 'Displays information about rooms and players on the server'] ) info.append( ['uptime', '/admin uptime', 'Information on how long server has been running'] ) info.append( ['help', '/admin help', 'This help message']) - info.append( ['passwd', '/admin passwd <group id> <new password>', 'Changes a rooms bootpassword. Server(lobby) password may not be changed']) + info.append( ['passwd', '/admin passwd <group id> <new password>', + 'Changes a rooms bootpassword. Server(lobby) password may not be changed']) info.append( ['roompasswords', '/admin roompasswords', 'Allow/Disallow Room Passwords on the server (toggles)']) - info.append( ['message', '/admin message <user id> <message>', 'Send a message to a specific user on the server']) + info.append( ['message', '/admin message <user id> <message>', + 'Send a message to a specific user on the server']) info.append( ['broadcast', '/admin broadcast <message>', 'Broadcast message to all players on server']) - info.append( ['createroom', '/admin createroom <room name> <boot password> [password]', 'Creates a temporary persistant room if possible.<i>Rooms created this way are lost on server restarts']) + info.append( ['createroom', '/admin createroom <room name> <boot password> [password]', + 'Creates a temporary persistant room if possible.<i>Rooms created this way are lost on server restarts']) info.append( ['nameroom', '/admin nameroom <group id> <new name>', 'Rename a room']) - info.append( ['killgroup', '/admin killgroup <room id>', 'Remove a room from the server and kick everyone in it.']) + info.append( ['killgroup', '/admin killgroup <room id>', + 'Remove a room from the server and kick everyone in it.']) if self.allowRemoteKill: - info.append( ['killserver', '/admin killserver', 'Shuts down the server. <b>WARNING: Server cannot be restarted remotely via OpenRPG</b>']) + info.append( ['killserver', '/admin killserver', + 'Shuts down the server. <b>WARNING: Server cannot be restarted remotely via OpenRPG</b>']) info.append( ['ban', '/admin ban {playerId}', 'Ban a player from the server.']) info.append( ['unban', '/admin unban {bannedIP}', 'UnBan a player from the server.']) info.append( ['banlist', '/admin banlist', 'List Banned IPs and the Names associated with them']) - info.append( ['savemaps', '/admin savemaps', 'Save all persistent room maps that are not using the default map file.']) - + info.append( ['savemaps', '/admin savemaps', + 'Save all persistent room maps that are not using the default map file.']) #define the HTML for the help display FS = "<font size='-1'>" FE = "<font>" - help = "<hr><B>REMOTE ADMINISTRATOR COMMANDS SUPPORTED</b><br /><br />" help += "<table border='1' cellpadding='2'>" - help += "<tr><td width='15%'><b>Command</b></td><td width='25%'><b>Format</b></td><td width='60%'><b>Description</b></td></tr>" + help += "<tr><td width='15%'><b>Command</b></td><td width='25%'><b>Format</b>" + help += "</td><td width='60%'><b>Description</b></td></tr>" for n in info: - help += "<tr><td>" + FS + n[0] + FE + "</td><td><nobr>" + FS + n[1] + FE + "</nobr></td><td>" + FS + n[2] + FE + "</td></tr>" + help += "<tr><td>" + FS + n[0] + FE + "</td><td><nobr>" + FS + n[1] + FE + "</nobr>" + help += "</td><td>" + FS + n[2] + FE + "</td></tr>" help += "</table>" return help - - #---------------------------------------------------------------- + """ # Create Persistant Group -- Added by Snowdog 6/03 # # Allows persistant groups to be created on the fly. @@ -2710,11 +2465,11 @@ # # Updated function code to use per-group based persistance and # removed references to outdated persistRoomIdThreshold - #---------------------------------------------------------------- + """ def create_temporary_persistant_room(self, roomname, bootpass, password=""): # if the room id just above the persistant room limit is available (not in use) - # then it will be assigned as a persistant room on the server + # then it will be assigned as a persistant room on the server "create a temporary persistant room" group_id = str(self.next_group_id) @@ -2726,7 +2481,7 @@ self.send_to_all('0',self.groups[group_id].toxml('update')) return str("Persistant room created (group " + group_id + ").") - #---------------------------------------------------------------- + """ # Prune Room -- Added by Snowdog 6/03 # # similar to remove_room() except rooms are removed regardless @@ -2734,39 +2489,34 @@ # # Added some error checking and updated room removal for per-room # based persistance -- Snowdog 4/04 - #---------------------------------------------------------------- + """ def prune_room(self,group): #don't allow lobby to be removed if group == '0': return "Lobby is required to exist and cannot be removed." #check that group id exists - if group not in self.groups: - return "Invalid Room Id. Ignoring remove request." + if group not in self.groups: return "Invalid Room Id. Ignoring remove request." try: keys = self.groups[group].get_player_ids() - for k in keys: - self.move_player(k,'0') - + for k in keys: self.move_player(k,'0') ins = "Room" if self.isPersistentRoom(group) : ins="Persistant room" self.send_to_all("0",self.groups[group].toxml('del')) del self.groups[group] self.log_msg(("delete_group", ('0',group))) return ins + " removed." - except: traceback.print_exc() return "An Error occured on the server during room removal!" - -#---------------------------------------------------------------- -# Remote Player List -- Added by snowdog 6/03 -# -# Similar to console listing except formated for web display -# in chat window on remote client -#---------------------------------------------------------------- + """ + # Remote Player List -- Added by snowdog 6/03 + # + # Similar to console listing except formated for web display + # in chat window on remote client + """ def player_list_remote(self): COLOR1 = "\"#004080\"" #header/footer background color COLOR2 = "\"#DDDDDD\"" #group line background color @@ -2778,18 +2528,19 @@ SIZE = "size=\"-1\"" #player info text size FG = PCOLOR - "display a condensed list of players on the server" self.p_lock.acquire() pl = "<br /><table border=\"0\" cellpadding=\"1\" cellspacing=\"2\">" - pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + "><b>GROUP & PLAYER LIST</b></font></td></tr>" + pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + ">" + pl += "<b>GROUP & PLAYER LIST</b></font></td></tr>" try: - keys = self.groups.keys() keys.sort(id_compare) for k in keys: - groupstring = "<tr><td bgcolor=" + COLOR2 + " colspan='2'><b>Group " + str(k) + ": " + self.groups[k].name + "</b>" - groupstring += "</td><td bgcolor=" + COLOR2 + " > <i>Password: \"" + self.groups[k].pwd + "\"</td><td bgcolor=" + COLOR2 + " > Boot: \"" + self.groups[k].boot_pwd + "\"</i></td></tr>" + groupstring = "<tr><td bgcolor=" + COLOR2 + " colspan='2'>" + groutstring += "<b>Group " + str(k) + ": " + self.groups[k].name + "</b>" + groupstring += "</td><td bgcolor=" + COLOR2 + " > <i>Password: \"" + self.groups[k].pwd + "\"</td>" + groupstring += "<td bgcolor=" + COLOR2 + " > Boot: \"" + self.groups[k].boot_pwd + "\"</i></td></tr>" pl += groupstring ids = self.groups[k].get_player_ids() ids.sort(id_compare) @@ -2803,18 +2554,20 @@ pl += "<tr><td bgcolor=" + COLOR3 + ">" pl += "<font color=" + FG + " " + SIZE + "> (" + (self.players[id]).id + ") " pl += (self.players[id]).name - pl += "</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + ">[IP: " + (self.players[id]).ip + "]</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + "> " + pl += "</font></td><td bgcolor=" + COLOR3 + " >" + pl += "<font color=" + FG + " " + SIZE + ">[IP: " + (self.players[id]).ip + "]</font>" + pl += "</td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + "> " pl += (self.players[id]).idle_status() pl += "</font></td><td><font color=" + FG + " " + SIZE + ">" pl += (self.players[id]).connected_time_string() pl += "</font>" - else: self.groups[k].remove_player(id) pl +="<tr><td colspan='4' bgcolor=" + COLOR3 + " >Bad Player Ref (#" + id + ") in group" pl+="</td></tr>" - pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + "><b><i>Statistics: groups: " + str(len(self.groups)) + " players: " + str(len(self.players)) + "</i></b></font></td></tr></table>" - except Exception, e: - self.log_msg(str(e)) + pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + ">" + pl += "<font color=" + COLOR4 + "><b><i>Statistics: groups: " + str(len(self.groups)) + " " + pl += "players: " + str(len(self.players)) + "</i></b></font></td></tr></table>" + except Exception, e: self.log_msg(str(e)) self.p_lock.release() return pl
--- a/orpg/networking/mplay_server_gui.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/mplay_server_gui.py Thu Aug 27 01:04:43 2009 -0500 @@ -13,8 +13,9 @@ import sys import time import types -import orpg.dirpath -import orpg.systempath +from orpg.dirpath import dir_struct +#import orpg.systempath looks old +from orpg.tools.validate import Validate from orpg.orpg_wx import * import webbrowser from threading import Thread @@ -57,10 +58,8 @@ f = ['b', 'Kb', 'Mb', 'Gb'] i = 0 while i < 3: - if b < 1024: - return str(b) + f[i] - else: - b = b/1024 + if b < 1024: return str(b) + f[i] + else: b = b/1024 i += 1 return str(b) + f[3] @@ -89,10 +88,8 @@ def __init__(self, owner ): """ Loads default configuration settings.""" - userPath = orpg.dirpath.dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file("server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') port = configDom.childNodes[0].childNodes[1].getAttribute('port') OPENRPG_PORT = 6774 if port == '' else int(port) #Pretty ugly, but I couldn't find the tag any other way. self.owner = owner @@ -146,13 +143,14 @@ # Main = GUI class Connections(wx.ListCtrl): def __init__( self, parent, main ): - wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) + wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, + wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) self.main = main self.roomList = { 0 : "Lobby" } self._imageList = wx.ImageList( 16, 16, False ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + img = wx.Image(dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() self._imageList.Add( img ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + img = wx.Image(dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() self._imageList.Add( img ) self.SetImageList( self._imageList, wx.IMAGE_LIST_SMALL ) @@ -276,13 +274,11 @@ print "Send message to room..." msg = self.GetMessageInput( "Send message to room of this player") if len(msg): self.main.server.server.send_to_group('0', str(groupID), msg ) - elif menuItem == MENU_PLAYER_SEND_SERVER_MESSAGE: print "broadcast a message..." msg = self.GetMessageInput( "Broadcast Server Message" ) # If we got a message back, send it - if len(msg): - self.main.server.server.broadcast( msg ) + if len(msg): self.main.server.server.broadcast( msg ) def GetMessageInput( self, title ): prompt = "Please enter the message you wish to send:" @@ -293,11 +289,10 @@ class ServerGUI(wx.Frame): STATUS = SERVER_STOPPED - def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size = (760, 560) ) - if wx.Platform == '__WXMSW__': icon = wx.Icon( orpg.dirpath.dir_struct["icon"]+'WAmisc9.ico', wx.BITMAP_TYPE_ICO ) - else: icon = wx.Icon( orpg.dirpath.dir_struct["icon"]+'connect.gif', wx.BITMAP_TYPE_GIF ) + if wx.Platform == '__WXMSW__': icon = wx.Icon( dir_struct["icon"]+'WAmisc9.ico', wx.BITMAP_TYPE_ICO ) + else: icon = wx.Icon( dir_struct["icon"]+'connect.gif', wx.BITMAP_TYPE_GIF ) self.SetIcon(icon) self.serverName = "Server Name" self.bootPwd = "" @@ -333,52 +328,47 @@ self.total_messages_sent = 0 self.total_data_sent = 0 - ### Build GUI ############################################ + """ Build GUI """ def build_menu(self): """ Build the GUI menu. """ self.mainMenu = wx.MenuBar() + # File Menu menu = wx.Menu() - # Start menu.Append( MENU_START_SERVER, 'Start', 'Start server.') self.Bind(wx.EVT_MENU, self.OnStart, id=MENU_START_SERVER) - # Stop menu.Append( MENU_STOP_SERVER, 'Stop', 'Shutdown server.') self.Bind(wx.EVT_MENU, self.OnStop, id=MENU_STOP_SERVER) - # Exit menu.AppendSeparator() menu.Append( MENU_EXIT, 'E&xit', 'Exit application.') self.Bind(wx.EVT_MENU, self.OnExit, id=MENU_EXIT) self.mainMenu.Append(menu, '&Server') + # Registration Menu menu = wx.Menu() - # Register menu.Append( MENU_REGISTER_SERVER, 'Register', 'Register with OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnRegister, id=MENU_REGISTER_SERVER) - # Unregister menu.Append( MENU_UNREGISTER_SERVER, 'Unregister', 'Unregister from OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnUnregister, id=MENU_UNREGISTER_SERVER) - # Add the registration menu self.mainMenu.Append( menu, '&Registration' ) + # Server Configuration Menu menu = wx.Menu() - # Ping Connected Players menu.Append( MENU_START_PING_PLAYERS, 'Start Ping', 'Ping players to validate remote connection.' ) self.Bind(wx.EVT_MENU, self.PingPlayers, id=MENU_START_PING_PLAYERS) - # Stop Pinging Connected Players menu.Append( MENU_STOP_PING_PLAYERS, 'Stop Ping', 'Stop validating player connections.' ) self.Bind(wx.EVT_MENU, self.StopPingPlayers, id=MENU_STOP_PING_PLAYERS) - # Set Ping Interval menu.Append( MENU_PING_INTERVAL, 'Ping Interval', 'Change the ping interval.' ) self.Bind(wx.EVT_MENU, self.ConfigPingInterval, id=MENU_PING_INTERVAL) self.mainMenu.Append( menu, '&Configuration' ) - # Add the menus to the main menu bar + self.SetMenuBar( self.mainMenu ) - # Disable register, unregister & stop server by default + self.mainMenu.Enable( MENU_STOP_SERVER, False ) self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) + # Disable the ping menu items self.mainMenu.Enable( MENU_START_PING_PLAYERS, False ) self.mainMenu.Enable( MENU_STOP_PING_PLAYERS, False ) @@ -480,10 +470,8 @@ if self.STATUS == SERVER_STOPPED: # see if we already have name specified try: - userPath = orpg.dirpath.dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file( "server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') configDom.normalize() configDoc = configDom.documentElement if configDoc.hasAttribute("name"): self.serverName = configDoc.getAttribute("name") @@ -494,19 +482,18 @@ if serverNameEntry.ShowModal() == wx.ID_OK: self.serverName = serverNameEntry.GetValue() # see if we already have password specified try: - userPath = orpg.dirpath.dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file( "server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') configDom.normalize() configDoc = configDom.documentElement if configDoc.hasAttribute("admin"): self.bootPwd = configDoc.getAttribute("admin") elif configDoc.hasAttribute("boot"): self.bootPwd = configDoc.getAttribute("boot") except: pass if self.bootPwd == '': - serverPasswordEntry = wx.TextEntryDialog(self, "Please Enter The Server Admin Password:", "Server's Password", self.bootPwd, wx.OK|wx.CANCEL|wx.CENTRE) + serverPasswordEntry = wx.TextEntryDialog(self, + "Please Enter The Server Admin Password:", "Server's Password", + self.bootPwd, wx.OK|wx.CANCEL|wx.CENTRE) if serverPasswordEntry.ShowModal() == wx.ID_OK: self.bootPwd = serverPasswordEntry.GetValue() - if len(self.serverName): wx.BeginBusyCursor() self.server = ServerMonitor(self.callbacks, self.conf, self.serverName, self.bootPwd) @@ -532,7 +519,6 @@ self.mainMenu.Enable( MENU_START_SERVER, True ) self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) - # Delete any items that are still in the player list self.conns.DeleteAllItems() def OnRegister(self, event = None): @@ -586,7 +572,7 @@ def OnInit(self): # Make sure our image handlers are loaded before we try to display anything wx.InitAllImageHandlers() - self.splash = wx.SplashScreen(wx.Bitmap(orpg.dirpath.dir_struct["icon"]+'splash.gif'), + self.splash = wx.SplashScreen(wx.Bitmap(dir_struct["icon"]+'splash.gif'), wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT, 2000, None) @@ -604,7 +590,6 @@ class HTMLMessageWindow(wx.html.HtmlWindow): "Widget used to present user to admin messages, in HTML format, to the server administrator" - # Init using the derived from class def __init__( self, parent ): wx.html.HtmlWindow.__init__( self, parent )
--- a/orpg/networking/server_plugins.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/networking/server_plugins.py Thu Aug 27 01:04:43 2009 -0500 @@ -25,7 +25,6 @@ def initBase(self): self._startPlugins() - #Methods def _startPlugins(self): autoload = [] @@ -60,7 +59,6 @@ self._load(pluginData) #Write to the autoload file for this plugin - self.__plugins[pluginName].Activated = True self.__plugins[pluginName].start() @@ -68,13 +66,12 @@ if not self.__plugins.has_key(pluginName): #Print some error about invalid plugin return + pluginData = self.__plugins[pluginName] - self.__plugins[pluginName].stop() #Unload it self._unload(pluginData) - #Remove this plugin from the autoload file #Private Methods @@ -84,7 +81,10 @@ return ('plugins.' + self.__ptype + '.' + s2[0], s2[0]) def _unload(self, pluginData): - self.__plugins[pluginData.Name] = PluginData(pluginData.Name, pluginData.File, pluginData.Author, pluginData.Help) + self.__plugins[pluginData.Name] = PluginData(pluginData.Name, + pluginData.File, + pluginData.Author, + pluginData.Help) unload = [] mod = self._findModule(pluginData.File)[0] for key, module in sys.modules.iteritems(): @@ -115,8 +115,6 @@ def _getType(self): return self.__ptype - - #Properties Plugins = property(_getPlugins, None) Type = property(_getType, None) @@ -132,18 +130,15 @@ def preParseIncoming(self, xml_dom, data): sent = True errmsg = "" - for pluginName, pluginData in self.Plugins.iteritems(): if pluginData.Activated: xml_dom, data = pluginData.preParseIncoming(xml_dom, data) - return xml_dom, data def postParseIncoming(self, data): for pluginName, pluginData in self.Plugins.iteritems(): if pluginData.Activated: data = pluginData.postParseIncoming(data) - return data def getPlayer(self): @@ -152,7 +147,6 @@ if pluginData.Activated: playerName = pluginData.addPlayer(data) players.append(playerName) - return players def setPlayer(self, playerData): @@ -161,7 +155,6 @@ if pluginData.Activated: playerName = pluginData.addPlayer(data) players.append(playerName) - return def preParseOutgoing(self): @@ -171,7 +164,6 @@ xml = pluginData.preParseOutgoing() for msg in xml: data.append(msg) - return data def postParseOutgoing(self): @@ -181,7 +173,6 @@ xml = pluginData.postParseOutgoing() for msg in xml: data.append(msg) - return data __key = _SingletonKey()
--- a/orpg/orpgCore.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/orpgCore.py Thu Aug 27 01:04:43 2009 -0500 @@ -60,20 +60,16 @@ class ORPGStorage(object): __components = {} - def add_component(self, key, com): + def add(self, key, com): self.__components[key] = com - def get_component(self, key): - if self.__components.has_key(key): - return self.__components[key] - else: - return None + def get(self, key): + if self.__components.has_key(key): return self.__components[key] + else: return None - def del_component(self, key): - if self.__components.has_key(key): - del self.__components[key] - else: - return + def delete(self, key): + if self.__components.has_key(key): del self.__components[key] + else: return def singleton(cls): instances = {} @@ -84,4 +80,4 @@ return getinstance ORPGStorage = singleton(ORPGStorage) -open_rpg = ORPGStorage() +component = ORPGStorage()
--- a/orpg/orpg_version.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/orpg_version.py Thu Aug 27 01:04:43 2009 -0500 @@ -2,9 +2,9 @@ SERVER_MIN_CLIENT_VERSION = "1.7.1" #BUILD NUMBER FORMAT: "YYMMDD-##" where ## is the incremental daily build index (if needed) -DISTRO = "Traipse Dev" +DISTRO = "Traipse" DIS_VER = "Ornery Orc" -BUILD = "090812-00" +BUILD = "090813-00" # This version is for network capability. PROTOCOL_VERSION = "1.2"
--- a/orpg/orpg_windows.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/orpg_windows.py Thu Aug 27 01:04:43 2009 -0500 @@ -31,8 +31,7 @@ from orpg.orpg_wx import * from orpg.orpgCore import * import orpg.tools.rgbhex -import orpg.orpg_xml -import orpg.dirpath +from orpg.dirpath import dir_struct from orpg.tools.metamenus import MenuEx class img_helper: @@ -71,15 +70,15 @@ nbstyle = FNB.FNB_HIDE_ON_SINGLE_TAB|FNB.FNB_BACKGROUND_GRADIENT FNB.FlatNotebook.__init__(self, parent, -1, size=size, style=nbstyle) rgbcovert = orpg.tools.rgbhex.RGBHex() - self.log = open_rpg.get_component("log") + self.log = component.get("log") self.log.log("Enter orpgTabberWnd", ORPG_DEBUG) - self.settings = open_rpg.get_component("settings") + self.settings = component.get("settings") tabtheme = self.settings.get_setting('TabTheme') tabtext = self.settings.get_setting('TabTextColor') (tred, tgreen, tblue) = rgbcovert.rgb_tuple(tabtext) - tabbedwindows = open_rpg.get_component("tabbedWindows") + tabbedwindows = component.get("tabbedWindows") tabbedwindows.append(self) - open_rpg.add_component("tabbedWindows", tabbedwindows) + component.add("tabbedWindows", tabbedwindows) theme_dict = {'slanted&aqua': FNB.FNB_VC8, 'slanted&bw': FNB.FNB_VC8, 'flat&aqua': FNB.FNB_FANCY_TABS, 'flat&bw': FNB.FNB_FANCY_TABS, 'customflat': FNB.FNB_FANCY_TABS, 'customslant': FNB.FNB_VC8, @@ -149,15 +148,16 @@ "Open an external browser to resolve our About box links!!!" href = ref.GetHref() webbrowser.open( href ) - -# This class extends wxSplitterWindow to add an auto expand behavior. The idea is that the sash -# determines the ratio of the two windows, while the mouse position determines which -# side will get the larger share of the screen real estate. It is used instead of regular -# wxSplitterWindows if the EnableSplittersAutoExpand setting doesn't evaluate as False. -# -# Note: To be truly functional, some way of passing EVT_MOTION events to this class, even when the -# event takes place over child windows needs to be accomplished. Once this is accomplished, -# however, the class should work as written. + """ + This class extends wxSplitterWindow to add an auto expand behavior. The idea is that the sash + determines the ratio of the two windows, while the mouse position determines which + side will get the larger share of the screen real estate. It is used instead of regular + wxSplitterWindows if the EnableSplittersAutoExpand setting doesn't evaluate as False. + + Note: To be truly functional, some way of passing EVT_MOTION events to this class, even when the + event takes place over child windows needs to be accomplished. Once this is accomplished, + however, the class should work as written. + """ class orpgFocusSplitterWindow(wx.SplitterWindow): def __init__(self,parent,id = -1,AutoExpand = 1,point = wx.DefaultPosition,size = wx.DefaultSize,style=wx.SP_3D,name="splitterWindow"): @@ -255,11 +255,11 @@ self.DIE2 = wx.NewId() self.DIE = wx.NewId() self.sizer = wx.BoxSizer(wx.HORIZONTAL) - gif = wx.Image(orpg.dirpath.dir_struct["icon"]+"bold.gif", wx.BITMAP_TYPE_GIF) + gif = wx.Image(dir_struct["icon"]+"bold.gif", wx.BITMAP_TYPE_GIF) self.sizer.Add(wx.BitmapButton(self, self.BOLD, gif.ConvertToBitmap()), 0, wx.EXPAND) - gif = wx.Image(orpg.dirpath.dir_struct["icon"]+"italic.gif", wx.BITMAP_TYPE_GIF) + gif = wx.Image(dir_struct["icon"]+"italic.gif", wx.BITMAP_TYPE_GIF) self.sizer.Add(wx.BitmapButton(self, self.ITALIC, gif.ConvertToBitmap()), 0, wx.EXPAND) - gif = wx.Image(orpg.dirpath.dir_struct["icon"]+"underlined.gif", wx.BITMAP_TYPE_GIF) + gif = wx.Image(dir_struct["icon"]+"underlined.gif", wx.BITMAP_TYPE_GIF) self.sizer.Add(wx.BitmapButton(self, self.UNDER, gif.ConvertToBitmap()), 0, wx.EXPAND) self.color_button = wx.Button(self, self.COLOR, "C",wx.Point(0,0),wx.Size(22,0)) self.color_button.SetBackgroundColour(wx.BLACK) @@ -619,7 +619,7 @@ "Parse xml with progress dialog" dlg = do_progress_dlg(parent,"XML Parser","Reading Configuration Files...",2) #dlg.Update(1) - doc = orpg.orpg_xml.parseXml(s) + doc = component.get('xml').parseXml(s) dlg.Update(1,"Done.") dlg.Destroy() return doc
--- a/orpg/orpg_xml.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/orpg_xml.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,41 +29,57 @@ from orpg import minidom import string -def toxml(root,pretty=0): - return root.toxml(pretty) - -def parseXml(s): - "parse and return doc" - try: - doc = minidom.parseString(s) - doc.normalize() - return doc - except Exception, e: - print e - return None +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging -def safe_get_text_node(xml_dom): - """ returns the child text node or creates one if doesnt exist """ - t_node = xml_dom._get_firstChild() - if t_node == None: - t_node = minidom.Text("") - t_node = xml_dom.appendChild(t_node) - return t_node +class xml: + @debugging + def __init__(self): + pass + + @debugging + def toxml(self, root, pretty=0): + return root.toxml(pretty) + + @debugging + def parseXml(self, s): + "parse and return doc" + try: + doc = minidom.parseString(s) + doc.normalize() + return doc + except Exception, e: + print e + return None + + @debugging + def safe_get_text_node(self, xml_dom): + """ returns the child text node or creates one if doesnt exist """ + t_node = xml_dom._get_firstChild() + if t_node == None: + t_node = minidom.Text("") + t_node = xml_dom.appendChild(t_node) + return t_node + + @debugging + def strip_unicode(self, txt): + for i in xrange(len(txt)): + if txt[i] not in string.printable: + try: txt = txt.replace(txt[i], '&#' + str(ord(txt[i])) + ';') + except: txt = txt.replace(txt[i], '{?}') + return txt + + @debugging + def strip_text(self, txt): + # The following block strips out 8-bit characters + u_txt = "" + bad_txt_found = 0 + txt = self.strip_unicode(txt) + for c in txt: + if ord(c) < 128: u_txt += c + else: bad_txt_found = 1 + if bad_txt_found: print "Some non 7-bit ASCII characters found and stripped" + return u_txt -def strip_unicode(txt): - for i in xrange(len(txt)): - if txt[i] not in string.printable: - try: txt = txt.replace(txt[i], '&#' + str(ord(txt[i])) + ';') - except: txt = txt.replace(txt[i], '{?}') - return txt -def strip_text(txt): - # The following block strips out 8-bit characters - u_txt = "" - bad_txt_found = 0 - txt = strip_unicode(txt) - for c in txt: - if ord(c) < 128: u_txt += c - else: bad_txt_found = 1 - if bad_txt_found: print "Some non 7-bit ASCII characters found and stripped" - return u_txt +xml = xml()
--- a/orpg/player_list.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/player_list.py Thu Aug 27 01:04:43 2009 -0500 @@ -30,7 +30,7 @@ __version__ = "$Id: player_list.py,v 1.29 2007/03/30 19:12:06 digitalxero Exp $" from orpg.orpg_windows import * -import orpg.dirpath +from orpg.dirpath import dir_struct # global definitions global ROLE_GM; ROLE_GM = "GM" @@ -78,19 +78,18 @@ class player_list(wx.ListCtrl): def __init__( self, parent): - ##wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND ) wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) - self.session = open_rpg.get_component("session") - self.settings = open_rpg.get_component('settings') - self.chat = open_rpg.get_component('chat') - self.password_manager = open_rpg.get_component("password_manager") + self.session = component.get("session") + self.settings = component.get('settings') + self.chat = component.get('chat') + self.password_manager = component.get("password_manager") # Create in image list -- for whatever reason...guess it will be nice when we can tell which is a bot self.whisperCount = 0 self._imageList = wx.ImageList( 16, 16, False ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + img = wx.Image(dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() self._imageList.Add( img ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + img = wx.Image(dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() self._imageList.Add( img ) self.SetImageList( self._imageList, wx.IMAGE_LIST_SMALL ) # Create our column headers @@ -201,9 +200,9 @@ def on_menu_password( self, evt ): id = evt.GetId() - self.session = open_rpg.get_component("session") - self.password_manager = open_rpg.get_component("password_manager") - self.chat = open_rpg.get_component("chat") + self.session = component.get("session") + self.password_manager = component.get("password_manager") + self.chat = component.get("chat") boot_pwd = self.password_manager.GetPassword("admin",int(self.session.group_id)) if boot_pwd != None: alter_pwd_dialog = wx.TextEntryDialog(self, @@ -215,9 +214,9 @@ def on_menu_room_rename( self, evt ): id = evt.GetId() - self.session = open_rpg.get_component("session") - self.password_manager = open_rpg.get_component("password_manager") - self.chat = open_rpg.get_component("chat") + self.session = component.get("session") + self.password_manager = component.get("password_manager") + self.chat = component.get("chat") boot_pwd = self.password_manager.GetPassword("admin",int(self.session.group_id)) if boot_pwd != None: alter_name_dialog = wx.TextEntryDialog(self,"Enter new room name: ","Change Room Name") @@ -269,9 +268,9 @@ return def on_menu_whispergroup( self, evt ): - self.session = open_rpg.get_component("session") - self.settings = open_rpg.get_component('settings') - self.chat = open_rpg.get_component('chat') + self.session = component.get("session") + self.settings = component.get('settings') + self.chat = component.get('chat') "Add/Remove players from Whisper Groups" id = evt.GetId() item = self.GetItem( self.selected_item ) @@ -298,8 +297,8 @@ def on_menu_moderate( self, evt ): "Change the moderated status of a room or player." id = evt.GetId() - self.chat = open_rpg.get_component( "chat" ) - self.session = open_rpg.get_component("session") + self.chat = component.get( "chat" ) + self.session = component.get("session") playerID = self.GetItemData( self.selected_item ) moderationString = None moderateRoomBase = "/moderate %s" @@ -327,10 +326,10 @@ self.chat.InfoPost( infoString ) def on_menu_role_change( self, evt ): - self.session = open_rpg.get_component("session") + self.session = component.get("session") "Change the role of the selected id." id = evt.GetId() - self.chat = open_rpg.get_component( "chat" ) + self.chat = component.get( "chat" ) playerID = self.GetItemData( self.selected_item ) roleString = None roleBase = "/role %d=%s" @@ -355,13 +354,13 @@ pos = wx.Point(evt.GetX(),evt.GetY()) (item, flag) = self.HitTest(pos) id = self.GetItemText(item) - self.chat = open_rpg.get_component("chat") + self.chat = component.get("chat") self.chat.set_chat_text("/w " + id + "=") def on_menu_item(self,evt): id = evt.GetId() - self.session = open_rpg.get_component("session") - self.password_manager = open_rpg.get_component("password_manager") + self.session = component.get("session") + self.password_manager = component.get("password_manager") if id == PLAYER_BOOT: id = str(self.GetItemData(self.selected_item)) @@ -369,11 +368,11 @@ if boot_pwd != None: self.session.boot_player(id,boot_pwd) elif id == PLAYER_WHISPER: id = self.GetItemText(self.selected_item) - self.chat = open_rpg.get_component("chat") + self.chat = component.get("chat") self.chat.set_chat_text("/w " + id + "=") elif id == PLAYER_IGNORE: id = str(self.GetItemData(self.selected_item)) - self.chat = open_rpg.get_component("chat") + self.chat = component.get("chat") (result,id,name) = self.session.toggle_ignore(id) if result == 0: self.chat.Post(self.chat.colorize(self.chat.syscolor, "Player " + name + " with ID:" + id +" no longer ignored")) @@ -392,7 +391,7 @@ self.selected_item = item # This if-else block makes the menu item to boot players active or inactive, as appropriate # This block is enabled for 1.7.8. Ver. 1.7.9 will boast Admin features. - #if open_rpg.get_component("session").group_id == "0": + #if component.get("session").group_id == "0": # self.menu.Enable(PLAYER_BOOT,0) # self.menu.SetLabel(PLAYER_BOOT,"Can't boot from Lobby") #else: @@ -452,10 +451,10 @@ self.colorize_player_list() self.Refresh() # play sound - setobj = open_rpg.get_component('settings') + setobj = component.get('settings') sound_file = setobj.get_setting("AddSound") if sound_file != '': - sound_player = open_rpg.get_component('sound') + sound_player = component.get('sound') sound_player.play(sound_file) self.AutoAdjust() @@ -473,10 +472,10 @@ #--------------------------------------------------------- # play sound - setobj = open_rpg.get_component('settings') + setobj = component.get('settings') sound_file = setobj.get_setting("DelSound") if sound_file != '': - sound_player = open_rpg.get_component('sound') + sound_player = component.get('sound') sound_player.play(sound_file) ic = self.GetItemCount() self.whisperCount = 0 @@ -504,8 +503,8 @@ self.AutoAdjust() def colorize_player_list(self): - session = open_rpg.get_component("session") - settings = open_rpg.get_component('settings') + session = component.get("session") + settings = component.get('settings') mode = settings.get_setting("ColorizeRoles") if mode.lower() == "0": return players = session.players
--- a/orpg/plugindb.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/plugindb.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,12 +1,13 @@ import xmltramp -import orpg.dirpath -import orpg.tools.validate +from orpg.dirpath import dir_struct +#import orpg.tools.validate from types import * +from orpg.orpgCore import component class PluginDB: def __init__(self, filename="plugindb.xml"): - self.filename = orpg.dirpath.dir_struct["user"] + filename - orpg.tools.validate.Validate().config_file(filename,"default_plugindb.xml") + self.filename = dir_struct["user"] + filename + component.get('validate').config_file(filename,"default_plugindb.xml") self.xml_dom = self.LoadDoc() def GetString(self, plugname, strname, defaultval, verbose=0):
--- a/orpg/pluginhandler.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/pluginhandler.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,5 +1,5 @@ from orpg.orpg_wx import * -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component class PluginHandler: # Initialization subroutine. @@ -7,14 +7,14 @@ # !self : instance of self # !chat : instance of the chat window to write to def __init__(self, plugindb, parent): - self.session = open_rpg.get_component("session") - self.chat = open_rpg.get_component("chat") - self.settings = open_rpg.get_component("settings") - self.gametree = open_rpg.get_component("tree") - self.startplugs = open_rpg.get_component("startplugs") - self.xml = open_rpg.get_component("xml") - self.validate = open_rpg.get_component("validate") - self.topframe = open_rpg.get_component("frame") + self.session = component.get("session") + self.chat = component.get("chat") + self.settings = component.get("settings") + self.gametree = component.get("tree") + self.startplugs = component.get("startplugs") + self.xml = component.get("xml") + self.validate = component.get("validate") + self.topframe = component.get("frame") self.plugindb = plugindb self.parent = parent self.shortcmdlist = self.chat.chat_cmds.shortcmdlist @@ -27,7 +27,7 @@ pass def menu_start(self): - rootMenu = open_rpg.get_component("pluginmenu") + rootMenu = component.get("pluginmenu") try: self.plugin_menu() rootMenu.AppendMenu(wx.ID_ANY, self.name, self.menu) @@ -39,7 +39,7 @@ def menu_cleanup(self): self.settings.save() - rootMenu = open_rpg.get_component("pluginmenu") + rootMenu = component.get("pluginmenu") menus = rootMenu.MenuItems for mi in menus: if mi.GetText() == self.name:
--- a/orpg/tools/FlatNotebook.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/FlatNotebook.py Thu Aug 27 01:04:43 2009 -0500 @@ -642,29 +642,23 @@ def GetMondrianBitmap(): return wx.BitmapFromImage(GetMondrianImage().Scale(16, 16)) - def GetMondrianImage(): import cStringIO stream = cStringIO.StringIO(GetMondrianData()) return wx.ImageFromStream(stream) - def GetMondrianIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(GetMondrianBitmap()) return icon #---------------------------------------------------------------------- - def LightColour(color, percent): """ Brighten input colour by percent. """ - end_color = wx.WHITE - rd = end_color.Red() - color.Red() gd = end_color.Green() - color.Green() bd = end_color.Blue() - color.Blue() - high = 100 # We take the percent way of the color from color -. white @@ -674,66 +668,43 @@ b = color.Blue() + ((i*bd*100)/high)/100 return wx.Colour(r, g, b) - def RandomColour(): """ Creates a random colour. """ - r = random.randint(0, 255) # Random value betweem 0-255 g = random.randint(0, 255) # Random value betweem 0-255 b = random.randint(0, 255) # Random value betweem 0-255 - return wx.Colour(r, g, b) - def PaintStraightGradientBox(dc, rect, startColor, endColor, vertical=True): """ Draws a gradient colored box from startColor to endColor. """ - rd = endColor.Red() - startColor.Red() gd = endColor.Green() - startColor.Green() bd = endColor.Blue() - startColor.Blue() - # Save the current pen and brush savedPen = dc.GetPen() savedBrush = dc.GetBrush() - - if vertical: - high = rect.GetHeight()-1 - else: - high = rect.GetWidth()-1 - - if high < 1: - return - + if vertical: high = rect.GetHeight()-1 + else: high = rect.GetWidth()-1 + if high < 1: return for i in xrange(high+1): - r = startColor.Red() + ((i*rd*100)/high)/100 g = startColor.Green() + ((i*gd*100)/high)/100 b = startColor.Blue() + ((i*bd*100)/high)/100 - p = wx.Pen(wx.Colour(r, g, b)) dc.SetPen(p) - - if vertical: - dc.DrawLine(rect.x, rect.y+i, rect.x+rect.width, rect.y+i) - else: - dc.DrawLine(rect.x+i, rect.y, rect.x+i, rect.y+rect.height) - + if vertical: dc.DrawLine(rect.x, rect.y+i, rect.x+rect.width, rect.y+i) + else: dc.DrawLine(rect.x+i, rect.y, rect.x+i, rect.y+rect.height) # Restore the pen and brush dc.SetPen(savedPen) dc.SetBrush(savedBrush) - - -# ----------------------------------------------------------------------------- +""" # Util functions -# ----------------------------------------------------------------------------- - +""" def DrawButton(dc, rect, focus, upperTabs): - # Define the rounded rectangle base on the given rect # we need an array of 9 points for it regPts = [wx.Point() for indx in xrange(9)] - if focus: if upperTabs: leftPt = wx.Point(rect.x, rect.y + (rect.height / 10)*8) @@ -744,16 +715,11 @@ else: leftPt = wx.Point(rect.x, rect.y + (rect.height / 2)) rightPt = wx.Point(rect.x + rect.width - 2, rect.y + (rect.height / 2)) - # Define the top region top = wx.RectPP(rect.GetTopLeft(), rightPt) bottom = wx.RectPP(leftPt, rect.GetBottomRight()) - topStartColor = wx.WHITE - - if not focus: - topStartColor = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 50) - + if not focus: topStartColor = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 50) topEndColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE) bottomStartColor = topEndColor bottomEndColor = topEndColor @@ -766,7 +732,6 @@ else: PaintStraightGradientBox(dc, top, topEndColor , topStartColor) PaintStraightGradientBox(dc, bottom, bottomStartColor, bottomEndColor) - else: if focus: PaintStraightGradientBox(dc, bottom, topEndColor, bottomEndColor) @@ -774,107 +739,83 @@ else: PaintStraightGradientBox(dc, bottom, bottomStartColor, bottomEndColor) PaintStraightGradientBox(dc, top, topEndColor, topStartColor) - dc.SetBrush(wx.TRANSPARENT_BRUSH) -# ---------------------------------------------------------------------------- # +""" # Class FNBDropSource # Gives Some Custom UI Feedback during the DnD Operations -# ---------------------------------------------------------------------------- # - +""" class FNBDropSource(wx.DropSource): """ Give some custom UI feedback during the drag and drop operation in this function. It is called on each mouse move, so your implementation must not be too slow. """ - def __init__(self, win): """ Default class constructor. Used internally. """ - wx.DropSource.__init__(self, win) self._win = win - def GiveFeedback(self, effect): """ Provides user with a nice feedback when tab is being dragged. """ - self._win.DrawDragHint() return False -# ---------------------------------------------------------------------------- # +""" # Class FNBDragInfo # Stores All The Information To Allow Drag And Drop Between Different # FlatNotebooks. -# ---------------------------------------------------------------------------- # - +""" class FNBDragInfo: - _map = weakref.WeakValueDictionary() - def __init__(self, container, pageindex): """ Default class constructor. """ - self._id = id(container) FNBDragInfo._map[self._id] = container self._pageindex = pageindex - def GetContainer(self): """ Returns the L{FlatNotebook} page (usually a panel). """ - return FNBDragInfo._map.get(self._id, None) - def GetPageIndex(self): """ Returns the page index associated with a page. """ - return self._pageindex -# ---------------------------------------------------------------------------- # +""" # Class FNBDropTarget # Simply Used To Handle The OnDrop() Method When Dragging And Dropping Between # Different FlatNotebooks. -# ---------------------------------------------------------------------------- # - +""" class FNBDropTarget(wx.DropTarget): - def __init__(self, parent): """ Default class constructor. """ - wx.DropTarget.__init__(self) - self._parent = parent self._dataobject = wx.CustomDataObject(wx.CustomDataFormat("FlatNotebook")) self.SetDataObject(self._dataobject) - def OnData(self, x, y, dragres): """ Handles the OnData() method to call the real DnD routine. """ - if not self.GetData(): return wx.DragNone - draginfo = self._dataobject.GetData() drginfo = cPickle.loads(draginfo) - return self._parent.OnDropTarget(x, y, drginfo.GetPageIndex(), drginfo.GetContainer()) -# ---------------------------------------------------------------------------- # +""" # Class PageInfo # Contains parameters for every FlatNotebook page -# ---------------------------------------------------------------------------- # - +""" class PageInfo: """ This class holds all the information (caption, image, etc...) belonging to a single tab in L{FlatNotebook}. """ - def __init__(self, caption="", imageindex=-1, tabangle=0, enabled=True): """ Default Class Constructor. @@ -885,7 +826,6 @@ @param tabangle: the tab angle (only on standard tabs, from 0 to 15 degrees); @param enabled: sets enabled or disabled the tab. """ - self._strCaption = caption self._TabAngle = tabangle self._ImageIndex = imageindex @@ -897,119 +837,82 @@ self._color = None self._hasFocus = False - def SetCaption(self, value): """ Sets the tab caption. """ - self._strCaption = value - def GetCaption(self): """ Returns the tab caption. """ - return self._strCaption - def SetPosition(self, value): """ Sets the tab position. """ - self._pos = value - def GetPosition(self): """ Returns the tab position. """ - return self._pos - def SetSize(self, value): """ Sets the tab size. """ - self._size = value - def GetSize(self): """ Returns the tab size. """ - return self._size - def SetTabAngle(self, value): """ Sets the tab header angle (0 <= tab <= 15 degrees). """ - self._TabAngle = min(45, value) - def GetTabAngle(self): """ Returns the tab angle. """ - return self._TabAngle - def SetImageIndex(self, value): """ Sets the tab image index. """ - self._ImageIndex = value - def GetImageIndex(self): """ Returns the tab umage index. """ - return self._ImageIndex - def GetEnabled(self): """ Returns whether the tab is enabled or not. """ - return self._bEnabled - def EnableTab(self, enabled): """ Sets the tab enabled or disabled. """ - self._bEnabled = enabled - def SetRegion(self, points=[]): """ Sets the tab region. """ - self._region = wx.RegionFromPoints(points) - def GetRegion(self): """ Returns the tab region. """ - return self._region - def SetXRect(self, xrect): """ Sets the button 'X' area rect. """ - self._xRect = xrect - def GetXRect(self): """ Returns the button 'X' area rect. """ - return self._xRect - def GetColour(self): """ Returns the tab colour. """ - return self._color - def SetColour(self, color): """ Sets the tab colour. """ - self._color = color -# ---------------------------------------------------------------------------- # +""" # Class FlatNotebookEvent -# ---------------------------------------------------------------------------- # - +""" class FlatNotebookEvent(wx.PyCommandEvent): """ This events will be sent when a EVT_FLATNOTEBOOK_PAGE_CHANGED, @@ -1017,68 +920,48 @@ EVT_FLATNOTEBOOK_PAGE_CLOSED and EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU is mapped in the parent. """ - def __init__(self, eventType, id=1, nSel=-1, nOldSel=-1): """ Default class constructor. """ - wx.PyCommandEvent.__init__(self, eventType, id) self._eventType = eventType - self.notify = wx.NotifyEvent(eventType, id) - def GetNotifyEvent(self): """Returns the actual wx.NotifyEvent.""" - return self.notify - def IsAllowed(self): """Returns whether the event is allowed or not.""" - return self.notify.IsAllowed() - def Veto(self): """Vetos the event.""" - self.notify.Veto() - def Allow(self): """The event is allowed.""" - self.notify.Allow() - def SetSelection(self, nSel): """ Sets event selection. """ - self._selection = nSel - def SetOldSelection(self, nOldSel): """ Sets old event selection. """ - self._oldselection = nOldSel - def GetSelection(self): """ Returns event selection. """ - return self._selection - def GetOldSelection(self): """ Returns old event selection """ - return self._oldselection -# ---------------------------------------------------------------------------- # +""" # Class TabNavigatorWindow -# ---------------------------------------------------------------------------- # - +""" class TabNavigatorWindow(wx.Dialog): """ This class is used to create a modal dialog that enables "Smart Tabbing", @@ -1087,39 +970,26 @@ def __init__(self, parent=None, icon=None): """ Default class constructor. Used internally.""" - wx.Dialog.__init__(self, parent, wx.ID_ANY, "", style=0) - self._selectedItem = -1 self._indexMap = [] - - if icon is None: - self._bmp = GetMondrianBitmap() - else: - self._bmp = icon - + if icon is None: self._bmp = GetMondrianBitmap() + else: self._bmp = icon sz = wx.BoxSizer(wx.VERTICAL) - self._listBox = wx.ListBox(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, 150), [], wx.LB_SINGLE | wx.NO_BORDER) - mem_dc = wx.MemoryDC() mem_dc.SelectObject(wx.EmptyBitmap(1,1)) font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) font.SetWeight(wx.BOLD) mem_dc.SetFont(font) - panelHeight = mem_dc.GetCharHeight() panelHeight += 4 # Place a spacer of 2 pixels # Out signpost bitmap is 24 pixels - if panelHeight < 24: - panelHeight = 24 - + if panelHeight < 24: panelHeight = 24 self._panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(200, panelHeight)) - sz.Add(self._panel) sz.Add(self._listBox, 1, wx.EXPAND) - self.SetSizer(sz) # Connect events to the list box @@ -1130,114 +1000,76 @@ # Connect paint event to the panel self._panel.Bind(wx.EVT_PAINT, self.OnPanelPaint) self._panel.Bind(wx.EVT_ERASE_BACKGROUND, self.OnPanelEraseBg) - self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)) self._listBox.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)) self.PopulateListControl(parent) - self.GetSizer().Fit(self) self.GetSizer().SetSizeHints(self) self.GetSizer().Layout() self.Centre() - def OnKeyUp(self, event): """Handles the wx.EVT_KEY_UP for the L{TabNavigatorWindow}.""" - - if event.GetKeyCode() == wx.WXK_CONTROL: - self.CloseDialog() - + if event.GetKeyCode() == wx.WXK_CONTROL: self.CloseDialog() def OnNavigationKey(self, event): """Handles the wx.EVT_NAVIGATION_KEY for the L{TabNavigatorWindow}. """ - selected = self._listBox.GetSelection() bk = self.GetParent() maxItems = bk.GetPageCount() - if event.GetDirection(): - # Select next page - if selected == maxItems - 1: - itemToSelect = 0 - else: - itemToSelect = selected + 1 - + if selected == maxItems - 1: itemToSelect = 0 + else: itemToSelect = selected + 1 else: - # Previous page - if selected == 0: - itemToSelect = maxItems - 1 - else: - itemToSelect = selected - 1 - + if selected == 0: itemToSelect = maxItems - 1 + else: itemToSelect = selected - 1 self._listBox.SetSelection(itemToSelect) - def PopulateListControl(self, book): """Populates the L{TabNavigatorWindow} listbox with a list of tabs.""" - selection = book.GetSelection() count = book.GetPageCount() - self._listBox.Append(book.GetPageText(selection)) self._indexMap.append(selection) - prevSel = book.GetPreviousSelection() - if prevSel != wx.NOT_FOUND: - # Insert the previous selection as second entry self._listBox.Append(book.GetPageText(prevSel)) self._indexMap.append(prevSel) - for c in xrange(count): - # Skip selected page - if c == selection: - continue - + if c == selection: continue # Skip previous selected page as well - if c == prevSel: - continue - + if c == prevSel: continue self._listBox.Append(book.GetPageText(c)) self._indexMap.append(c) - # Select the next entry after the current selection self._listBox.SetSelection(0) dummy = wx.NavigationKeyEvent() dummy.SetDirection(True) self.OnNavigationKey(dummy) - def OnItemSelected(self, event): """Handles the wx.EVT_LISTBOX_DCLICK event for the wx.ListBox inside L{TabNavigatorWindow}. """ - self.CloseDialog() - def CloseDialog(self): """Closes the L{TabNavigatorWindow} dialog, setting selection in L{FlatNotebook}.""" - bk = self.GetParent() self._selectedItem = self._listBox.GetSelection() iter = self._indexMap[self._selectedItem] bk._pages.FireEvent(iter) self.EndModal(wx.ID_OK) - def OnPanelPaint(self, event): """Handles the wx.EVT_PAINT event for L{TabNavigatorWindow} top panel. """ - dc = wx.PaintDC(self._panel) rect = self._panel.GetClientRect() - bmp = wx.EmptyBitmap(rect.width, rect.height) - mem_dc = wx.MemoryDC() mem_dc.SelectObject(bmp) - endColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW) startColour = LightColour(endColour, 50) PaintStraightGradientBox(mem_dc, rect, startColour, endColour) @@ -1254,41 +1086,34 @@ font.SetWeight(wx.BOLD) mem_dc.SetFont(font) fontHeight = mem_dc.GetCharHeight() - txtPt.x = bmpPt.x + self._bmp.GetWidth() + 4 txtPt.y = (rect.height - fontHeight)/2 mem_dc.SetTextForeground(wx.WHITE) mem_dc.DrawText("Opened tabs:", txtPt.x, txtPt.y) mem_dc.SelectObject(wx.NullBitmap) - dc.DrawBitmap(bmp, 0, 0) - def OnPanelEraseBg(self, event): """Handles the wx.EVT_ERASE_BACKGROUND event for L{TabNavigatorWindow} top panel. """ - pass - -# ---------------------------------------------------------------------------- # +""" # Class FNBRenderer -# ---------------------------------------------------------------------------- # - +""" class FNBRenderer: """ Parent class for the 4 renderers defined: I{Standard}, I{VC71}, I{Fancy} and I{VC8}. This class implements the common methods of all 4 renderers. """ - def __init__(self): """Default class constructor. """ - self._tabHeight = None - if wx.Platform == "__WXMAC__": + """ # Hack to get proper highlight color for focus rectangle from # current theme by creating a theme brush and getting its color. # kThemeBrushFocusHighlight is available on Mac OS 8.5 and higher + """ brush = wx.BLACK_BRUSH brush.MacSetTheme(Carbon.Appearance.kThemeBrushFocusHighlight) self._focusPen = wx.Pen(brush.GetColour(), 2, wx.SOLID) @@ -1297,417 +1122,266 @@ self._focusPen.SetDashes([1, 1]) self._focusPen.SetCap(wx.CAP_BUTT) - def GetLeftButtonPos(self, pageContainer): """ Returns the left button position in the navigation area. """ - pc = pageContainer style = pc.GetParent().GetWindowStyleFlag() rect = pc.GetClientRect() clientWidth = rect.width - - if style & FNB_NO_X_BUTTON: - return clientWidth - 38 - else: - return clientWidth - 54 - + if style & FNB_NO_X_BUTTON: return clientWidth - 38 + else: return clientWidth - 54 def GetRightButtonPos(self, pageContainer): """ Returns the right button position in the navigation area. """ - pc = pageContainer style = pc.GetParent().GetWindowStyleFlag() rect = pc.GetClientRect() clientWidth = rect.width - - if style & FNB_NO_X_BUTTON: - return clientWidth - 22 - else: - return clientWidth - 38 - + if style & FNB_NO_X_BUTTON: return clientWidth - 22 + else: return clientWidth - 38 def GetDropArrowButtonPos(self, pageContainer): """ Returns the drop down button position in the navigation area. """ - return self.GetRightButtonPos(pageContainer) - def GetXPos(self, pageContainer): """ Returns the 'X' button position in the navigation area. """ - pc = pageContainer style = pc.GetParent().GetWindowStyleFlag() rect = pc.GetClientRect() clientWidth = rect.width - - if style & FNB_NO_X_BUTTON: - return clientWidth - else: - return clientWidth - 22 - + if style & FNB_NO_X_BUTTON: return clientWidth + else: return clientWidth - 22 def GetButtonsAreaLength(self, pageContainer): """ Returns the navigation area width. """ - pc = pageContainer style = pc.GetParent().GetWindowStyleFlag() - # '' - if style & FNB_NO_NAV_BUTTONS and style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: - return 0 - + if style & FNB_NO_NAV_BUTTONS and style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: return 0 # 'x' - elif style & FNB_NO_NAV_BUTTONS and not style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: - return 22 - + elif style & FNB_NO_NAV_BUTTONS and not style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: return 22 # '<>' - if not style & FNB_NO_NAV_BUTTONS and style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: - return 53 - 16 - + if not style & FNB_NO_NAV_BUTTONS and style & FNB_NO_X_BUTTON and not style & FNB_DROPDOWN_TABS_LIST: return 53 - 16 # 'vx' - if style & FNB_DROPDOWN_TABS_LIST and not style & FNB_NO_X_BUTTON: - return 22 + 16 - + if style & FNB_DROPDOWN_TABS_LIST and not style & FNB_NO_X_BUTTON: return 22 + 16 # 'v' - if style & FNB_DROPDOWN_TABS_LIST and style & FNB_NO_X_BUTTON: - return 22 - + if style & FNB_DROPDOWN_TABS_LIST and style & FNB_NO_X_BUTTON: return 22 # '<>x' return 53 - def DrawArrowAccordingToState(self, dc, pc, rect): - lightFactor = (pc.HasFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0] PaintStraightGradientBox(dc, rect, pc._tabAreaColor, LightColour(pc._tabAreaColor, lightFactor)) - def DrawLeftArrow(self, pageContainer, dc): """ Draw the left navigation arrow. """ - pc = pageContainer - style = pc.GetParent().GetWindowStyleFlag() - if style & FNB_NO_NAV_BUTTONS: - return - + if style & FNB_NO_NAV_BUTTONS: return # Make sure that there are pages in the container - if not pc._pagesInfoVec: - return - + if not pc._pagesInfoVec: return # Set the bitmap according to the button status - if pc._nLeftButtonStatus == FNB_BTN_HOVER: - arrowBmp = wx.BitmapFromXPMData(left_arrow_hilite_xpm) - elif pc._nLeftButtonStatus == FNB_BTN_PRESSED: - arrowBmp = wx.BitmapFromXPMData(left_arrow_pressed_xpm) - else: - arrowBmp = wx.BitmapFromXPMData(left_arrow_xpm) - + if pc._nLeftButtonStatus == FNB_BTN_HOVER: arrowBmp = wx.BitmapFromXPMData(left_arrow_hilite_xpm) + elif pc._nLeftButtonStatus == FNB_BTN_PRESSED: arrowBmp = wx.BitmapFromXPMData(left_arrow_pressed_xpm) + else: arrowBmp = wx.BitmapFromXPMData(left_arrow_xpm) if pc._nFrom == 0: # Handle disabled arrow arrowBmp = wx.BitmapFromXPMData(left_arrow_disabled_xpm) - arrowBmp.SetMask(wx.Mask(arrowBmp, MASK_COLOR)) - # Erase old bitmap posx = self.GetLeftButtonPos(pc) self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14)) - # Draw the new bitmap dc.DrawBitmap(arrowBmp, posx, 6, True) - def DrawRightArrow(self, pageContainer, dc): """ Draw the right navigation arrow. """ - pc = pageContainer - style = pc.GetParent().GetWindowStyleFlag() - if style & FNB_NO_NAV_BUTTONS: - return - + if style & FNB_NO_NAV_BUTTONS: return # Make sure that there are pages in the container - if not pc._pagesInfoVec: - return + if not pc._pagesInfoVec: return # Set the bitmap according to the button status - if pc._nRightButtonStatus == FNB_BTN_HOVER: - arrowBmp = wx.BitmapFromXPMData(right_arrow_hilite_xpm) - elif pc._nRightButtonStatus == FNB_BTN_PRESSED: - arrowBmp = wx.BitmapFromXPMData(right_arrow_pressed_xpm) - else: - arrowBmp = wx.BitmapFromXPMData(right_arrow_xpm) + if pc._nRightButtonStatus == FNB_BTN_HOVER: arrowBmp = wx.BitmapFromXPMData(right_arrow_hilite_xpm) + elif pc._nRightButtonStatus == FNB_BTN_PRESSED: arrowBmp = wx.BitmapFromXPMData(right_arrow_pressed_xpm) + else: arrowBmp = wx.BitmapFromXPMData(right_arrow_xpm) # Check if the right most tab is visible, if it is # don't rotate right anymore if pc._pagesInfoVec[-1].GetPosition() != wx.Point(-1, -1): arrowBmp = wx.BitmapFromXPMData(right_arrow_disabled_xpm) - arrowBmp.SetMask(wx.Mask(arrowBmp, MASK_COLOR)) - # erase old bitmap posx = self.GetRightButtonPos(pc) self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14)) - # Draw the new bitmap dc.DrawBitmap(arrowBmp, posx, 6, True) - def DrawDropDownArrow(self, pageContainer, dc): """ Draws the drop-down arrow in the navigation area. """ - pc = pageContainer - # Check if this style is enabled style = pc.GetParent().GetWindowStyleFlag() - if not style & FNB_DROPDOWN_TABS_LIST: - return - + if not style & FNB_DROPDOWN_TABS_LIST: return # Make sure that there are pages in the container - if not pc._pagesInfoVec: - return - - if pc._nArrowDownButtonStatus == FNB_BTN_HOVER: - downBmp = wx.BitmapFromXPMData(down_arrow_hilite_xpm) - elif pc._nArrowDownButtonStatus == FNB_BTN_PRESSED: - downBmp = wx.BitmapFromXPMData(down_arrow_pressed_xpm) - else: - downBmp = wx.BitmapFromXPMData(down_arrow_xpm) - + if not pc._pagesInfoVec: return + if pc._nArrowDownButtonStatus == FNB_BTN_HOVER: downBmp = wx.BitmapFromXPMData(down_arrow_hilite_xpm) + elif pc._nArrowDownButtonStatus == FNB_BTN_PRESSED: downBmp = wx.BitmapFromXPMData(down_arrow_pressed_xpm) + else: downBmp = wx.BitmapFromXPMData(down_arrow_xpm) downBmp.SetMask(wx.Mask(downBmp, MASK_COLOR)) - # erase old bitmap posx = self.GetDropArrowButtonPos(pc) self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14)) - # Draw the new bitmap dc.DrawBitmap(downBmp, posx, 6, True) - def DrawX(self, pageContainer, dc): """ Draw the 'X' navigation button in the navigation area. """ - pc = pageContainer - # Check if this style is enabled style = pc.GetParent().GetWindowStyleFlag() - if style & FNB_NO_X_BUTTON: - return - + if style & FNB_NO_X_BUTTON: return # Make sure that there are pages in the container - if not pc._pagesInfoVec: - return - + if not pc._pagesInfoVec: return # Set the bitmap according to the button status - if pc._nXButtonStatus == FNB_BTN_HOVER: - xbmp = wx.BitmapFromXPMData(x_button_hilite_xpm) - elif pc._nXButtonStatus == FNB_BTN_PRESSED: - xbmp = wx.BitmapFromXPMData(x_button_pressed_xpm) - else: - xbmp = wx.BitmapFromXPMData(x_button_xpm) - + if pc._nXButtonStatus == FNB_BTN_HOVER: xbmp = wx.BitmapFromXPMData(x_button_hilite_xpm) + elif pc._nXButtonStatus == FNB_BTN_PRESSED: xbmp = wx.BitmapFromXPMData(x_button_pressed_xpm) + else: xbmp = wx.BitmapFromXPMData(x_button_xpm) xbmp.SetMask(wx.Mask(xbmp, MASK_COLOR)) - # erase old bitmap posx = self.GetXPos(pc) self.DrawArrowAccordingToState(dc, pc, wx.Rect(posx, 6, 16, 14)) - # Draw the new bitmap dc.DrawBitmap(xbmp, posx, 6, True) - def DrawTabX(self, pageContainer, dc, rect, tabIdx, btnStatus): """ Draws the 'X' in the selected tab. """ - pc = pageContainer - if not pc.HasFlag(FNB_X_ON_TAB): - return - + if not pc.HasFlag(FNB_X_ON_TAB): return # We draw the 'x' on the active tab only - if tabIdx != pc.GetSelection() or tabIdx < 0: - return - + if tabIdx != pc.GetSelection() or tabIdx < 0: return # Set the bitmap according to the button status - - if btnStatus == FNB_BTN_HOVER: - xBmp = wx.BitmapFromXPMData(x_button_hilite_xpm) - elif btnStatus == FNB_BTN_PRESSED: - xBmp = wx.BitmapFromXPMData(x_button_pressed_xpm) - else: - xBmp = wx.BitmapFromXPMData(x_button_xpm) - + if btnStatus == FNB_BTN_HOVER: xBmp = wx.BitmapFromXPMData(x_button_hilite_xpm) + elif btnStatus == FNB_BTN_PRESSED: xBmp = wx.BitmapFromXPMData(x_button_pressed_xpm) + else: xBmp = wx.BitmapFromXPMData(x_button_xpm) # Set the masking xBmp.SetMask(wx.Mask(xBmp, MASK_COLOR)) - # Draw the new bitmap dc.DrawBitmap(xBmp, rect.x, rect.y, True) - # Update the vector rr = wx.Rect(rect.x, rect.y, 14, 13) pc._pagesInfoVec[tabIdx].SetXRect(rr) - def DrawTabsLine(self, pageContainer, dc, selTabX1=-1, selTabX2=-1): """ Draws a line over the tabs. """ - pc = pageContainer - clntRect = pc.GetClientRect() clientRect3 = wx.Rect(0, 0, clntRect.width, clntRect.height) - if pc.HasFlag(FNB_FF2): - if not pc.HasFlag(FNB_BOTTOM): - fillColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE) - else: - fillColor = wx.WHITE - + if not pc.HasFlag(FNB_BOTTOM): fillColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE) + else: fillColor = wx.WHITE dc.SetPen(wx.Pen(fillColor)) - if pc.HasFlag(FNB_BOTTOM): - dc.DrawLine(1, 0, clntRect.width-1, 0) dc.DrawLine(1, 1, clntRect.width-1, 1) - dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))) dc.DrawLine(1, 2, clntRect.width-1, 2) - dc.SetPen(wx.Pen(fillColor)) dc.DrawLine(selTabX1 + 2, 2, selTabX2 - 1, 2) - else: - dc.DrawLine(1, clntRect.height, clntRect.width-1, clntRect.height) dc.DrawLine(1, clntRect.height-1, clntRect.width-1, clntRect.height-1) - dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))) dc.DrawLine(1, clntRect.height-2, clntRect.width-1, clntRect.height-2) - dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))) dc.DrawLine(selTabX1 + 2, clntRect.height-2, selTabX2-1, clntRect.height-2) - else: if pc.HasFlag(FNB_BOTTOM): - clientRect = wx.Rect(0, 2, clntRect.width, clntRect.height - 2) clientRect2 = wx.Rect(0, 1, clntRect.width, clntRect.height - 1) - else: - clientRect = wx.Rect(0, 0, clntRect.width, clntRect.height - 2) clientRect2 = wx.Rect(0, 0, clntRect.width, clntRect.height - 1) - dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(wx.Pen(pc.GetSingleLineBorderColour())) dc.DrawRectangleRect(clientRect2) dc.DrawRectangleRect(clientRect3) - dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW))) dc.DrawRectangleRect(clientRect) - if not pc.HasFlag(FNB_TABS_BORDER_SIMPLE): - dc.SetPen(wx.Pen((pc.HasFlag(FNB_VC71) and [wx.Colour(247, 243, 233)] or [pc._tabAreaColor])[0])) dc.DrawLine(0, 0, 0, clientRect.height+1) - if pc.HasFlag(FNB_BOTTOM): - dc.DrawLine(0, clientRect.height+1, clientRect.width, clientRect.height+1) - else: - dc.DrawLine(0, 0, clientRect.width, 0) - dc.DrawLine(clientRect.width - 1, 0, clientRect.width - 1, clientRect.height+1) - def CalcTabWidth(self, pageContainer, tabIdx, tabHeight): """ Calculates the width of the input tab. """ - pc = pageContainer dc = wx.MemoryDC() dc.SelectObject(wx.EmptyBitmap(1,1)) - boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.FONTWEIGHT_BOLD) - if pc.IsDefaultTabs(): shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi)) - # Calculate the text length using the bold font, so when selecting a tab # its width will not change dc.SetFont(boldFont) width, pom = dc.GetTextExtent(pc.GetPageText(tabIdx)) - # Set a minimum size to a tab - if width < 20: - width = 20 - + if width < 20: width = 20 tabWidth = 2*pc._pParent.GetPadding() + width - # Style to add a small 'x' button on the top right # of the tab if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): # The xpm image that contains the 'x' button is 9 pixels spacer = 9 - if pc.HasFlag(FNB_VC8): - spacer = 4 - + if pc.HasFlag(FNB_VC8): spacer = 4 tabWidth += pc._pParent.GetPadding() + spacer - if pc.IsDefaultTabs(): # Default style tabWidth += 2*shapePoints - hasImage = pc._ImageList != None and pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 # For VC71 style, we only add the icon size (16 pixels) if hasImage: - if not pc.IsDefaultTabs(): tabWidth += 16 + pc._pParent.GetPadding() else: # Default style tabWidth += 16 + pc._pParent.GetPadding() + shapePoints/2 - return tabWidth - def CalcTabHeight(self, pageContainer): """ Calculates the height of the input tab. """ - if self._tabHeight: return self._tabHeight - pc = pageContainer dc = wx.MemoryDC() dc.SelectObject(wx.EmptyBitmap(1,1)) - # For GTK it seems that we must do this steps in order # for the tabs will get the proper height on initialization # on MSW, preforming these steps yields wierd results normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont = normalFont - if "__WXGTK__" in wx.PlatformInfo: boldFont.SetWeight(wx.FONTWEIGHT_BOLD) dc.SetFont(boldFont) - height = dc.GetCharHeight() - tabHeight = height + FNB_HEIGHT_SPACER # We use 8 pixels as padding if "__WXGTK__" in wx.PlatformInfo: # On GTK the tabs are should be larger tabHeight += 6 - self._tabHeight = tabHeight - return tabHeight - def DrawTabs(self, pageContainer, dc): """ Actually draws the tabs in L{FlatNotebook}.""" - pc = pageContainer if "__WXMAC__" in wx.PlatformInfo: # Works well on MSW & GTK, however this lines should be skipped on MAC @@ -1718,23 +1392,16 @@ # Get the text hight tabHeight = self.CalcTabHeight(pageContainer) style = pc.GetParent().GetWindowStyleFlag() - # Calculate the number of rows required for drawing the tabs rect = pc.GetClientRect() clientWidth = rect.width - # Set the maximum client size pc.SetSizeHints(self.GetButtonsAreaLength(pc), tabHeight) borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) - - if style & FNB_VC71: - backBrush = wx.Brush(wx.Colour(247, 243, 233)) - else: - backBrush = wx.Brush(pc._tabAreaColor) - + if style & FNB_VC71: backBrush = wx.Brush(wx.Colour(247, 243, 233)) + else: backBrush = wx.Brush(pc._tabAreaColor) noselBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE)) selBrush = wx.Brush(pc._activeTabColor) - size = pc.GetSize() # Background @@ -1748,29 +1415,23 @@ else: colr = (pc.HasFlag(FNB_VC71) and [wx.Colour(247, 243, 233)] or [pc.GetBackgroundColour()])[0] dc.SetPen(wx.Pen(colr)) - if pc.HasFlag(FNB_FF2): lightFactor = (pc.HasFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0] PaintStraightGradientBox(dc, pc.GetClientRect(), pc._tabAreaColor, LightColour(pc._tabAreaColor, lightFactor)) dc.SetBrush(wx.TRANSPARENT_BRUSH) - dc.DrawRectangle(0, 0, size.x, size.y) # We always draw the bottom/upper line of the tabs # regradless the style dc.SetPen(borderPen) - if not pc.HasFlag(FNB_FF2): self.DrawTabsLine(pc, dc) # Restore the pen dc.SetPen(borderPen) - if pc.HasFlag(FNB_VC71): - greyLineYVal = (pc.HasFlag(FNB_BOTTOM) and [0] or [size.y - 2])[0] whiteLineYVal = (pc.HasFlag(FNB_BOTTOM) and [3] or [size.y - 3])[0] - pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE)) dc.SetPen(pen) @@ -1778,7 +1439,6 @@ # the tab area for num in xrange(3): dc.DrawLine(0, greyLineYVal + num, size.x, greyLineYVal + num) - wbPen = (pc.HasFlag(FNB_BOTTOM) and [wx.BLACK_PEN] or [wx.WHITE_PEN])[0] dc.SetPen(wbPen) dc.DrawLine(1, whiteLineYVal, size.x - 1, whiteLineYVal) @@ -1791,69 +1451,55 @@ boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.FONTWEIGHT_BOLD) dc.SetFont(boldFont) - posx = pc._pParent.GetPadding() # Update all the tabs from 0 to 'pc._nFrom' to be non visible for i in xrange(pc._nFrom): - pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1)) pc._pagesInfoVec[i].GetRegion().Clear() - count = pc._nFrom - #---------------------------------------------------------- + """ # Go over and draw the visible tabs - #---------------------------------------------------------- + """ x1 = x2 = -1 for i in xrange(pc._nFrom, len(pc._pagesInfoVec)): - dc.SetPen(borderPen) - if not pc.HasFlag(FNB_FF2): dc.SetBrush((i==pc.GetSelection() and [selBrush] or [noselBrush])[0]) # Now set the font to the correct font dc.SetFont((i==pc.GetSelection() and [boldFont] or [normalFont])[0]) - + """ # Add the padding to the tab width # Tab width: # +-----------------------------------------------------------+ # | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING | # +-----------------------------------------------------------+ + """ tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight) - # Check if we can draw more - if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth: - break - + if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth: break count = count + 1 - # By default we clean the tab region pc._pagesInfoVec[i].GetRegion().Clear() - # Clean the 'x' buttn on the tab. # A 'Clean' rectangle, is a rectangle with width or height # with values lower than or equal to 0 pc._pagesInfoVec[i].GetXRect().SetSize(wx.Size(-1, -1)) - # Draw the tab (border, text, image & 'x' on tab) self.DrawTab(pc, dc, posx, i, tabWidth, tabHeight, pc._nTabXButtonStatus) - if pc.GetSelection() == i: x1 = posx x2 = posx + tabWidth + 2 # Restore the text forground dc.SetTextForeground(pc._activeTextColor) - # Update the tab position & size posy = (pc.HasFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0] - pc._pagesInfoVec[i].SetPosition(wx.Point(posx, posy)) pc._pagesInfoVec[i].SetSize(wx.Size(tabWidth, tabHeight)) self.DrawFocusRectangle(dc, pc, pc._pagesInfoVec[i]) - posx += tabWidth # Update all tabs that can not fit into the screen as non-visible @@ -1867,92 +1513,66 @@ self.DrawRightArrow(pc, dc) self.DrawX(pc, dc) self.DrawDropDownArrow(pc, dc) - - if pc.HasFlag(FNB_FF2): - self.DrawTabsLine(pc, dc, x1, x2) - + if pc.HasFlag(FNB_FF2): self.DrawTabsLine(pc, dc, x1, x2) def DrawFocusRectangle(self, dc, pageContainer, page): """ Draws a focus rectangle like the native Notebooks. """ - if not page._hasFocus: return - tabPos = wx.Point(*page.GetPosition()) if pageContainer.GetParent().GetWindowStyleFlag() & FNB_VC8: vc8ShapeLen = self.CalcTabHeight(pageContainer) - VERTICAL_BORDER_PADDING - 2 tabPos.x += vc8ShapeLen - rect = wx.RectPS(tabPos, page.GetSize()) rect = wx.Rect(rect.x+2, rect.y+2, rect.width-4, rect.height-8) - if wx.Platform == '__WXMAC__': rect.SetWidth(rect.GetWidth() + 1) - dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(self._focusPen) dc.DrawRoundedRectangleRect(rect, 2) - def DrawDragHint(self, pc, tabIdx): """ Draws tab drag hint, the default implementation is to do nothing. You can override this function to provide a nice feedback to user. """ - pass def NumberTabsCanFit(self, pageContainer, fr=-1): - pc = pageContainer - rect = pc.GetClientRect() clientWidth = rect.width - vTabInfo = [] - tabHeight = self.CalcTabHeight(pageContainer) - # The drawing starts from posx posx = pc._pParent.GetPadding() - - if fr < 0: - fr = pc._nFrom - + if fr < 0: fr = pc._nFrom for i in xrange(fr, len(pc._pagesInfoVec)): - tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight) if posx + tabWidth + self.GetButtonsAreaLength(pc) >= clientWidth: break; - # Add a result to the returned vector tabRect = wx.Rect(posx, VERTICAL_BORDER_PADDING, tabWidth , tabHeight) vTabInfo.append(tabRect) - # Advance posx posx += tabWidth + FNB_HEIGHT_SPACER - return vTabInfo -# ---------------------------------------------------------------------------- # +""" # Class FNBRendererMgr # A manager that handles all the renderers defined below and calls the # appropriate one when drawing is needed -# ---------------------------------------------------------------------------- # - +""" class FNBRendererMgr: """ This class represents a manager that handles all the 4 renderers defined and calls the appropriate one when drawing is needed. """ - def __init__(self): """ Default class constructor. """ - # register renderers - self._renderers = {} self._renderers.update({-1: FNBRendererDefault()}) self._renderers.update({FNB_VC71: FNBRendererVC71()}) @@ -1960,99 +1580,69 @@ self._renderers.update({FNB_VC8: FNBRendererVC8()}) self._renderers.update({FNB_FF2: FNBRendererFirefox2()}) - def GetRenderer(self, style): """ Returns the current renderer based on the style selected. """ - - if style & FNB_VC71: - return self._renderers[FNB_VC71] - - if style & FNB_FANCY_TABS: - return self._renderers[FNB_FANCY_TABS] - - if style & FNB_VC8: - return self._renderers[FNB_VC8] - - if style & FNB_FF2: - return self._renderers[FNB_FF2] - + if style & FNB_VC71: return self._renderers[FNB_VC71] + if style & FNB_FANCY_TABS: return self._renderers[FNB_FANCY_TABS] + if style & FNB_VC8: return self._renderers[FNB_VC8] + if style & FNB_FF2: return self._renderers[FNB_FF2] # the default is to return the default renderer return self._renderers[-1] -#------------------------------------------ +""" # Default renderer -#------------------------------------------ - +""" class FNBRendererDefault(FNBRenderer): """ This class handles the drawing of tabs using the I{Standard} renderer. """ - def __init__(self): """ Default class constructor. """ - FNBRenderer.__init__(self) - def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using the I{Standard} style. """ - # Default style borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) pc = pageContainer - tabPoints = [wx.Point() for ii in xrange(7)] tabPoints[0].x = posx tabPoints[0].y = (pc.HasFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0] - tabPoints[1].x = int(posx+(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi)) tabPoints[1].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0] - tabPoints[2].x = tabPoints[1].x+2 tabPoints[2].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[3].x = int(posx+tabWidth-(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi))-2 tabPoints[3].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[4].x = tabPoints[3].x+2 tabPoints[4].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0] - tabPoints[5].x = int(tabPoints[4].x+(tabHeight-2)*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi)) tabPoints[5].y = (pc.HasFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0] - tabPoints[6].x = tabPoints[0].x tabPoints[6].y = tabPoints[0].y - if tabIdx == pc.GetSelection(): - # Draw the tab as rounded rectangle dc.DrawPolygon(tabPoints) - else: - if tabIdx != pc.GetSelection() - 1: - # Draw a vertical line to the right of the text pt1x = tabPoints[5].x pt1y = (pc.HasFlag(FNB_BOTTOM) and [4] or [tabHeight - 6])[0] pt2x = tabPoints[5].x pt2y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - 4] or [4])[0] dc.DrawLine(pt1x, pt1y, pt2x, pt2y) - if tabIdx == pc.GetSelection(): - savePen = dc.GetPen() whitePen = wx.Pen(wx.WHITE) whitePen.SetWidth(1) dc.SetPen(whitePen) - secPt = wx.Point(tabPoints[5].x + 1, tabPoints[5].y) dc.DrawLine(tabPoints[0].x, tabPoints[0].y, secPt.x, secPt.y) - # Restore the pen dc.SetPen(savePen) + """ # ----------------------------------- # Text and image drawing # ----------------------------------- @@ -2061,211 +1651,236 @@ # rectangle # The width of the images are 16 pixels + """ padding = pc.GetParent().GetPadding() shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi)) hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [6] or [8])[0] - if hasImage: - textOffset = 2*pc._pParent._nPadding + 16 + shapePoints/2 - else: - textOffset = pc._pParent._nPadding + shapePoints/2 - + if hasImage: textOffset = 2*pc._pParent._nPadding + 16 + shapePoints/2 + else: textOffset = pc._pParent._nPadding + shapePoints/2 textOffset += 2 - if tabIdx != pc.GetSelection(): - # Set the text background to be like the vertical lines dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) - if hasImage: - imageXOffset = textOffset - 16 - padding pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) - dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) - # draw 'x' on tab (if enabled) if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): - textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 - # take a bitmap from the position of the 'x' button (the x on tab button) # this bitmap will be used later to delete old buttons tabCloseButtonYCoord = imageYCoord x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) - # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) -#------------------------------------------ +""" # Firefox2 renderer -#------------------------------------------ +""" class FNBRendererFirefox2(FNBRenderer): """ This class handles the drawing of tabs using the I{Firefox 2} renderer. """ - def __init__(self): """ Default class constructor. """ - FNBRenderer.__init__(self) - def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using the I{Firefox 2} style. """ - borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) pc = pageContainer - tabPoints = [wx.Point() for indx in xrange(7)] tabPoints[0].x = posx + 2 tabPoints[0].y = (pc.HasFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0] - tabPoints[1].x = tabPoints[0].x tabPoints[1].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0] - tabPoints[2].x = tabPoints[1].x+2 tabPoints[2].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[3].x = posx + tabWidth - 2 tabPoints[3].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[4].x = tabPoints[3].x + 2 tabPoints[4].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0] - tabPoints[5].x = tabPoints[4].x tabPoints[5].y = (pc.HasFlag(FNB_BOTTOM) and [2] or [tabHeight - 2])[0] - tabPoints[6].x = tabPoints[0].x tabPoints[6].y = tabPoints[0].y - #------------------------------------ + """ # Paint the tab with gradient - #------------------------------------ + """ rr = wx.RectPP(tabPoints[2], tabPoints[5]) DrawButton(dc, rr, pc.GetSelection() == tabIdx , not pc.HasFlag(FNB_BOTTOM)) - dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetPen(borderPen) - # Draw the tab as rounded rectangle dc.DrawPolygon(tabPoints) - - # ----------------------------------- + """ # Text and image drawing - # ----------------------------------- - + """ # The width of the images are 16 pixels padding = pc.GetParent().GetPadding() shapePoints = int(tabHeight*math.tan(float(pc._pagesInfoVec[tabIdx].GetTabAngle())/180.0*math.pi)) hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [6] or [8])[0] - - if hasImage: - textOffset = 2*padding + 16 + shapePoints/2 - else: - textOffset = padding + shapePoints/2 - + if hasImage: textOffset = 2*padding + 16 + shapePoints/2 + else: textOffset = padding + shapePoints/2 textOffset += 2 - if tabIdx != pc.GetSelection(): - # Set the text background to be like the vertical lines dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) - if hasImage: imageXOffset = textOffset - 16 - padding pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) - dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) - # draw 'x' on tab (if enabled) if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): - textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 - # take a bitmap from the position of the 'x' button (the x on tab button) # this bitmap will be used later to delete old buttons tabCloseButtonYCoord = imageYCoord x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) - # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) -#------------------------------------------------------------------ +""" # Visual studio 7.1 -#------------------------------------------------------------------ - +""" class FNBRendererVC71(FNBRenderer): """ This class handles the drawing of tabs using the I{VC71} renderer. """ - def __init__(self): """ Default class constructor. """ - FNBRenderer.__init__(self) - def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using the I{VC71} style. """ - # Visual studio 7.1 style borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) pc = pageContainer dc.SetPen((tabIdx == pc.GetSelection() and [wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))] or [borderPen])[0]) dc.SetBrush((tabIdx == pc.GetSelection() and [wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))] or [wx.Brush(wx.Colour(247, 243, 233))])[0]) - if tabIdx == pc.GetSelection(): - posy = (pc.HasFlag(FNB_BOTTOM) and [0] or [VERTICAL_BORDER_PADDING])[0] tabH = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - 5] or [tabHeight - 3])[0] dc.DrawRectangle(posx, posy, tabWidth, tabH) - # Draw a black line on the left side of the # rectangle dc.SetPen(wx.BLACK_PEN) - blackLineY1 = VERTICAL_BORDER_PADDING blackLineY2 = tabH dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2) - + """ # To give the tab more 3D look we do the following # Incase the tab is on top, # Draw a thik white line on topof the rectangle # Otherwise, draw a thin (1 pixel) black line at the bottom - + """ pen = wx.Pen((pc.HasFlag(FNB_BOTTOM) and [wx.BLACK] or [wx.WHITE])[0]) dc.SetPen(pen) whiteLinePosY = (pc.HasFlag(FNB_BOTTOM) and [blackLineY2] or [VERTICAL_BORDER_PADDING ])[0] dc.DrawLine(posx , whiteLinePosY, posx + tabWidth + 1, whiteLinePosY) - # Draw a white vertical line to the left of the tab dc.SetPen(wx.WHITE_PEN) if not pc.HasFlag(FNB_BOTTOM): blackLineY2 += 1 - dc.DrawLine(posx, blackLineY1, posx, blackLineY2) - else: # We dont draw a rectangle for non selected tabs, but only # vertical line on the left - blackLineY1 = (pc.HasFlag(FNB_BOTTOM) and [VERTICAL_BORDER_PADDING + 2] or [VERTICAL_BORDER_PADDING + 1])[0] blackLineY2 = pc.GetSize().y - 5 dc.DrawLine(posx + tabWidth, blackLineY1, posx + tabWidth, blackLineY2) - + """ + # ----------------------------------- + # Text and image drawing + # ----------------------------------- + """ + # Text drawing offset from the left border of the + # rectangle + + # The width of the images are 16 pixels + padding = pc.GetParent().GetPadding() + hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 + imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [5] or [8])[0] + + if hasImage: textOffset = 2*pc._pParent._nPadding + 16 + else: textOffset = pc._pParent._nPadding + if tabIdx != pc.GetSelection(): + # Set the text background to be like the vertical lines + dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) + if hasImage: + imageXOffset = textOffset - 16 - padding + pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, + posx + imageXOffset, imageYCoord, + wx.IMAGELIST_DRAW_TRANSPARENT, True) + dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) + + # draw 'x' on tab (if enabled) + if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): + textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) + tabCloseButtonXCoord = posx + textOffset + textWidth + 1 + # take a bitmap from the position of the 'x' button (the x on tab button) + # this bitmap will be used later to delete old buttons + tabCloseButtonYCoord = imageYCoord + x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) + # Draw the tab + self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) + + +""" +# Fancy style +""" +class FNBRendererFancy(FNBRenderer): + """ + This class handles the drawing of tabs using the I{Fancy} renderer. + """ + def __init__(self): + """ Default class constructor. """ + FNBRenderer.__init__(self) + + def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): + """ Draws a tab using the I{Fancy} style, similar to VC71 but with gradients. """ + # Fancy tabs - like with VC71 but with the following differences: + # - The Selected tab is colored with gradient color + borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) + pc = pageContainer + pen = (tabIdx == pc.GetSelection() and [wx.Pen(pc._pParent.GetBorderColour())] or [wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))])[0] + + if tabIdx == pc.GetSelection(): + posy = (pc.HasFlag(FNB_BOTTOM) and [2] or [VERTICAL_BORDER_PADDING])[0] + th = tabHeight - 5 + rect = wx.Rect(posx, posy, tabWidth, th) + col2 = (pc.HasFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourTo()] or [pc._pParent.GetGradientColourFrom()])[0] + col1 = (pc.HasFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourFrom()] or [pc._pParent.GetGradientColourTo()])[0] + PaintStraightGradientBox(dc, rect, col1, col2) + dc.SetBrush(wx.TRANSPARENT_BRUSH) + dc.SetPen(pen) + dc.DrawRectangleRect(rect) + + # erase the bottom/top line of the rectangle + dc.SetPen(wx.Pen(pc._pParent.GetGradientColourFrom())) + if pc.HasFlag(FNB_BOTTOM): dc.DrawLine(rect.x, 2, rect.x + rect.width, 2) + else: dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1) + else: + # We dont draw a rectangle for non selected tabs, but only + # vertical line on the left + dc.SetPen(borderPen) + dc.DrawLine(posx + tabWidth, VERTICAL_BORDER_PADDING + 3, posx + tabWidth, tabHeight - 4) + """ # ----------------------------------- # Text and image drawing # ----------------------------------- @@ -2274,303 +1889,157 @@ # rectangle # The width of the images are 16 pixels + """ padding = pc.GetParent().GetPadding() hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 - imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [5] or [8])[0] - - if hasImage: - textOffset = 2*pc._pParent._nPadding + 16 - else: - textOffset = pc._pParent._nPadding - + imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [6] or [8])[0] + + if hasImage: textOffset = 2*pc._pParent._nPadding + 16 + else: textOffset = pc._pParent._nPadding + textOffset += 2 if tabIdx != pc.GetSelection(): - # Set the text background to be like the vertical lines dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) - if hasImage: - imageXOffset = textOffset - 16 - padding pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) - dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) - # draw 'x' on tab (if enabled) if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): - textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 - # take a bitmap from the position of the 'x' button (the x on tab button) # this bitmap will be used later to delete old buttons tabCloseButtonYCoord = imageYCoord x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) - # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) -#------------------------------------------------------------------ -# Fancy style -#------------------------------------------------------------------ - -class FNBRendererFancy(FNBRenderer): - """ - This class handles the drawing of tabs using the I{Fancy} renderer. - """ - - def __init__(self): - """ Default class constructor. """ - - FNBRenderer.__init__(self) - - - def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): - """ Draws a tab using the I{Fancy} style, similar to VC71 but with gradients. """ - - # Fancy tabs - like with VC71 but with the following differences: - # - The Selected tab is colored with gradient color - borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) - pc = pageContainer - - pen = (tabIdx == pc.GetSelection() and [wx.Pen(pc._pParent.GetBorderColour())] or [wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))])[0] - - if tabIdx == pc.GetSelection(): - - posy = (pc.HasFlag(FNB_BOTTOM) and [2] or [VERTICAL_BORDER_PADDING])[0] - th = tabHeight - 5 - - rect = wx.Rect(posx, posy, tabWidth, th) - - col2 = (pc.HasFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourTo()] or [pc._pParent.GetGradientColourFrom()])[0] - col1 = (pc.HasFlag(FNB_BOTTOM) and [pc._pParent.GetGradientColourFrom()] or [pc._pParent.GetGradientColourTo()])[0] - - PaintStraightGradientBox(dc, rect, col1, col2) - dc.SetBrush(wx.TRANSPARENT_BRUSH) - dc.SetPen(pen) - dc.DrawRectangleRect(rect) - - # erase the bottom/top line of the rectangle - dc.SetPen(wx.Pen(pc._pParent.GetGradientColourFrom())) - if pc.HasFlag(FNB_BOTTOM): - dc.DrawLine(rect.x, 2, rect.x + rect.width, 2) - else: - dc.DrawLine(rect.x, rect.y + rect.height - 1, rect.x + rect.width, rect.y + rect.height - 1) - - else: - - # We dont draw a rectangle for non selected tabs, but only - # vertical line on the left - dc.SetPen(borderPen) - dc.DrawLine(posx + tabWidth, VERTICAL_BORDER_PADDING + 3, posx + tabWidth, tabHeight - 4) - - - # ----------------------------------- - # Text and image drawing - # ----------------------------------- - - # Text drawing offset from the left border of the - # rectangle - - # The width of the images are 16 pixels - padding = pc.GetParent().GetPadding() - hasImage = pc._pagesInfoVec[tabIdx].GetImageIndex() != -1 - imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [6] or [8])[0] - - if hasImage: - textOffset = 2*pc._pParent._nPadding + 16 - else: - textOffset = pc._pParent._nPadding - - textOffset += 2 - - if tabIdx != pc.GetSelection(): - - # Set the text background to be like the vertical lines - dc.SetTextForeground(pc._pParent.GetNonActiveTabTextColour()) - - if hasImage: - - imageXOffset = textOffset - 16 - padding - pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, - posx + imageXOffset, imageYCoord, - wx.IMAGELIST_DRAW_TRANSPARENT, True) - - dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) - - # draw 'x' on tab (if enabled) - if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): - - textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) - tabCloseButtonXCoord = posx + textOffset + textWidth + 1 - - # take a bitmap from the position of the 'x' button (the x on tab button) - # this bitmap will be used later to delete old buttons - tabCloseButtonYCoord = imageYCoord - x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) - - # Draw the tab - self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) - - -#------------------------------------------------------------------ +""" # Visual studio 2005 (VS8) -#------------------------------------------------------------------ +""" class FNBRendererVC8(FNBRenderer): """ This class handles the drawing of tabs using the I{VC8} renderer. """ - def __init__(self): """ Default class constructor. """ - FNBRenderer.__init__(self) self._first = True self._factor = 1 - def DrawTabs(self, pageContainer, dc): """ Draws all the tabs using VC8 style. Overloads The DrawTabs method in parent class. """ - pc = pageContainer - if "__WXMAC__" in wx.PlatformInfo: # Works well on MSW & GTK, however this lines should be skipped on MAC if not pc._pagesInfoVec or pc._nFrom >= len(pc._pagesInfoVec): pc.Hide() return - # Get the text hight tabHeight = self.CalcTabHeight(pageContainer) - # Set the font for measuring the tab height normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.FONTWEIGHT_BOLD) - # Calculate the number of rows required for drawing the tabs rect = pc.GetClientRect() - # Set the maximum client size pc.SetSizeHints(self.GetButtonsAreaLength(pc), tabHeight) borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) - # Create brushes backBrush = wx.Brush(pc._tabAreaColor) noselBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE)) selBrush = wx.Brush(pc._activeTabColor) size = pc.GetSize() - # Background dc.SetTextBackground(pc.GetBackgroundColour()) dc.SetTextForeground(pc._activeTextColor) - # If border style is set, set the pen to be border pen - if pc.HasFlag(FNB_TABS_BORDER_SIMPLE): - dc.SetPen(borderPen) - else: - dc.SetPen(wx.TRANSPARENT_PEN) - + if pc.HasFlag(FNB_TABS_BORDER_SIMPLE): dc.SetPen(borderPen) + else: dc.SetPen(wx.TRANSPARENT_PEN) lightFactor = (pc.HasFlag(FNB_BACKGROUND_GRADIENT) and [70] or [0])[0] - # For VC8 style, we color the tab area in gradient coloring lightcolour = LightColour(pc._tabAreaColor, lightFactor) PaintStraightGradientBox(dc, pc.GetClientRect(), pc._tabAreaColor, lightcolour) - dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawRectangle(0, 0, size.x, size.y) - # We always draw the bottom/upper line of the tabs # regradless the style dc.SetPen(borderPen) self.DrawTabsLine(pc, dc) - # Restore the pen dc.SetPen(borderPen) - # Draw labels dc.SetFont(boldFont) - # Update all the tabs from 0 to 'pc.self._nFrom' to be non visible for i in xrange(pc._nFrom): - pc._pagesInfoVec[i].SetPosition(wx.Point(-1, -1)) pc._pagesInfoVec[i].GetRegion().Clear() - # Draw the visible tabs, in VC8 style, we draw them from right to left vTabsInfo = self.NumberTabsCanFit(pc) - activeTabPosx = 0 activeTabWidth = 0 activeTabHeight = 0 - for cur in xrange(len(vTabsInfo)-1, -1, -1): - # 'i' points to the index of the currently drawn tab # in pc.GetPageInfoVector() vector i = pc._nFrom + cur dc.SetPen(borderPen) dc.SetBrush((i==pc.GetSelection() and [selBrush] or [noselBrush])[0]) - # Now set the font to the correct font dc.SetFont((i==pc.GetSelection() and [boldFont] or [normalFont])[0]) - + """ # Add the padding to the tab width # Tab width: # +-----------------------------------------------------------+ # | PADDING | IMG | IMG_PADDING | TEXT | PADDING | x |PADDING | # +-----------------------------------------------------------+ - + """ tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight) posx = vTabsInfo[cur].x - + """ # By default we clean the tab region # incase we use the VC8 style which requires # the region, it will be filled by the function # drawVc8Tab + """ pc._pagesInfoVec[i].GetRegion().Clear() - + """ # Clean the 'x' buttn on the tab # 'Clean' rectanlge is a rectangle with width or height # with values lower than or equal to 0 + """ pc._pagesInfoVec[i].GetXRect().SetSize(wx.Size(-1, -1)) - + """ # Draw the tab # Incase we are drawing the active tab # we need to redraw so it will appear on top # of all other tabs - + """ # when using the vc8 style, we keep the position of the active tab so we will draw it again later if i == pc.GetSelection() and pc.HasFlag(FNB_VC8): - activeTabPosx = posx activeTabWidth = tabWidth activeTabHeight = tabHeight - else: - self.DrawTab(pc, dc, posx, i, tabWidth, tabHeight, pc._nTabXButtonStatus) - # Restore the text forground dc.SetTextForeground(pc._activeTextColor) - # Update the tab position & size pc._pagesInfoVec[i].SetPosition(wx.Point(posx, VERTICAL_BORDER_PADDING)) pc._pagesInfoVec[i].SetSize(wx.Size(tabWidth, tabHeight)) # Incase we are in VC8 style, redraw the active tab (incase it is visible) if pc.GetSelection() >= pc._nFrom and pc.GetSelection() < pc._nFrom + len(vTabsInfo): - self.DrawTab(pc, dc, activeTabPosx, pc.GetSelection(), activeTabWidth, activeTabHeight, pc._nTabXButtonStatus) - # Update all tabs that can not fit into the screen as non-visible for xx in xrange(pc._nFrom + len(vTabsInfo), len(pc._pagesInfoVec)): - pc._pagesInfoVec[xx].SetPosition(wx.Point(-1, -1)) pc._pagesInfoVec[xx].GetRegion().Clear() - # Draw the left/right/close buttons # Left arrow self.DrawLeftArrow(pc, dc) @@ -2578,14 +2047,12 @@ self.DrawX(pc, dc) self.DrawDropDownArrow(pc, dc) - def DrawTab(self, pageContainer, dc, posx, tabIdx, tabWidth, tabHeight, btnStatus): """ Draws a tab using VC8 style. """ - pc = pageContainer borderPen = wx.Pen(pc._pParent.GetBorderColour()) tabPoints = [wx.Point() for ii in xrange(8)] - + """ # If we draw the first tab or the active tab, # we draw a full tab, else we draw a truncated tab # @@ -2597,31 +2064,23 @@ # X(0),(7) X(6) # # - + """ tabPoints[0].x = (pc.HasFlag(FNB_BOTTOM) and [posx] or [posx+self._factor])[0] tabPoints[0].y = (pc.HasFlag(FNB_BOTTOM) and [2] or [tabHeight - 3])[0] - tabPoints[1].x = tabPoints[0].x + tabHeight - VERTICAL_BORDER_PADDING - 3 - self._factor tabPoints[1].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - (VERTICAL_BORDER_PADDING+2)] or [(VERTICAL_BORDER_PADDING+2)])[0] - tabPoints[2].x = tabPoints[1].x + 4 tabPoints[2].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[3].x = tabPoints[2].x + tabWidth - 2 tabPoints[3].y = (pc.HasFlag(FNB_BOTTOM) and [tabHeight - VERTICAL_BORDER_PADDING] or [VERTICAL_BORDER_PADDING])[0] - tabPoints[4].x = tabPoints[3].x + 1 tabPoints[4].y = (pc.HasFlag(FNB_BOTTOM) and [tabPoints[3].y - 1] or [tabPoints[3].y + 1])[0] - tabPoints[5].x = tabPoints[4].x + 1 tabPoints[5].y = (pc.HasFlag(FNB_BOTTOM) and [(tabPoints[4].y - 1)] or [tabPoints[4].y + 1])[0] - tabPoints[6].x = tabPoints[2].x + tabWidth tabPoints[6].y = tabPoints[0].y - tabPoints[7].x = tabPoints[0].x tabPoints[7].y = tabPoints[0].y - pc._pagesInfoVec[tabIdx].SetRegion(tabPoints) # Draw the polygon @@ -2633,9 +2092,7 @@ # Restore the brush dc.SetBrush(br) rect = pc.GetClientRect() - if tabIdx != pc.GetSelection() and not pc.HasFlag(FNB_BOTTOM): - # Top default tabs dc.SetPen(wx.Pen(pc._pParent.GetBorderColour())) lineY = rect.height @@ -2647,57 +2104,46 @@ # Incase we are drawing the selected tab, we draw the border of it as well # but without the bottom (upper line incase of wxBOTTOM) if tabIdx == pc.GetSelection(): - borderPen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)) dc.SetPen(borderPen) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawPolygon(tabPoints) - # Delete the bottom line (or the upper one, incase we use wxBOTTOM) dc.SetPen(wx.WHITE_PEN) dc.DrawLine(tabPoints[0].x, tabPoints[0].y, tabPoints[6].x, tabPoints[6].y) - self.FillVC8GradientColour(pc, dc, tabPoints, tabIdx == pc.GetSelection(), tabIdx) - # Draw a thin line to the right of the non-selected tab if tabIdx != pc.GetSelection(): - dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE))) dc.DrawLine(tabPoints[4].x-1, tabPoints[4].y, tabPoints[5].x-1, tabPoints[5].y) dc.DrawLine(tabPoints[5].x-1, tabPoints[5].y, tabPoints[6].x-1, tabPoints[6].y) - + """ # Text drawing offset from the left border of the # rectangle # The width of the images are 16 pixels + """ vc8ShapeLen = tabHeight - VERTICAL_BORDER_PADDING - 2 - if pc.TabHasImage(tabIdx): - textOffset = 2*pc._pParent.GetPadding() + 16 + vc8ShapeLen - else: - textOffset = pc._pParent.GetPadding() + vc8ShapeLen + if pc.TabHasImage(tabIdx): textOffset = 2*pc._pParent.GetPadding() + 16 + vc8ShapeLen + else: textOffset = pc._pParent.GetPadding() + vc8ShapeLen # Draw the image for the tab if any imageYCoord = (pc.HasFlag(FNB_BOTTOM) and [6] or [8])[0] - if pc.TabHasImage(tabIdx): - imageXOffset = textOffset - 16 - pc._pParent.GetPadding() pc._ImageList.Draw(pc._pagesInfoVec[tabIdx].GetImageIndex(), dc, posx + imageXOffset, imageYCoord, wx.IMAGELIST_DRAW_TRANSPARENT, True) - boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) # if selected tab, draw text in bold if tabIdx == pc.GetSelection(): boldFont.SetWeight(wx.FONTWEIGHT_BOLD) - dc.SetFont(boldFont) dc.DrawText(pc.GetPageText(tabIdx), posx + textOffset, imageYCoord) # draw 'x' on tab (if enabled) if pc.HasFlag(FNB_X_ON_TAB) and tabIdx == pc.GetSelection(): - textWidth, textHeight = dc.GetTextExtent(pc.GetPageText(tabIdx)) tabCloseButtonXCoord = posx + textOffset + textWidth + 1 @@ -2707,81 +2153,57 @@ x_rect = wx.Rect(tabCloseButtonXCoord, tabCloseButtonYCoord, 16, 16) # Draw the tab self.DrawTabX(pc, dc, x_rect, tabIdx, btnStatus) - self.DrawFocusRectangle(dc, pc, pc._pagesInfoVec[tabIdx]) - def FillVC8GradientColour(self, pageContainer, dc, tabPoints, bSelectedTab, tabIdx): """ Fills a tab with a gradient shading. """ - # calculate gradient coefficients pc = pageContainer - if self._first: self._first = False pc._colorTo = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 0) pc._colorFrom = LightColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE), 60) - col2 = pc._pParent.GetGradientColourTo() col1 = pc._pParent.GetGradientColourFrom() # If colorful tabs style is set, override the tab color if pc.HasFlag(FNB_COLORFUL_TABS): - if not pc._pagesInfoVec[tabIdx].GetColour(): - # First time, generate color, and keep it in the vector tabColor = RandomColour() pc._pagesInfoVec[tabIdx].SetColour(tabColor) - if pc.HasFlag(FNB_BOTTOM): - col2 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 50) col1 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 80) - else: - col1 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 50) col2 = LightColour(pc._pagesInfoVec[tabIdx].GetColour(), 80) - size = abs(tabPoints[2].y - tabPoints[0].y) - 1 - rf, gf, bf = 0, 0, 0 rstep = float(col2.Red() - col1.Red())/float(size) gstep = float(col2.Green() - col1.Green())/float(size) bstep = float(col2.Blue() - col1.Blue())/float(size) - y = tabPoints[0].y - + """ # If we are drawing the selected tab, we need also to draw a line # from 0.tabPoints[0].x and tabPoints[6].x . end, we achieve this # by drawing the rectangle with transparent brush # the line under the selected tab will be deleted by the drwaing loop + """ if bSelectedTab: self.DrawTabsLine(pc, dc) - while 1: - if pc.HasFlag(FNB_BOTTOM): - - if y > tabPoints[0].y + size: - break - + if y > tabPoints[0].y + size: break else: - - if y < tabPoints[0].y - size: - break - + if y < tabPoints[0].y - size: break currCol = wx.Colour(col1.Red() + rf, col1.Green() + gf, col1.Blue() + bf) - dc.SetPen((bSelectedTab and [wx.Pen(pc._activeTabColor)] or [wx.Pen(currCol)])[0]) startX = self.GetStartX(tabPoints, y, pc.GetParent().GetWindowStyleFlag()) endX = self.GetEndX(tabPoints, y, pc.GetParent().GetWindowStyleFlag()) dc.DrawLine(startX, y, endX, y) - # Draw the border using the 'edge' point dc.SetPen(wx.Pen((bSelectedTab and [wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)] or [pc._colorBorder])[0])) - dc.DrawPoint(startX, y) dc.DrawPoint(endX, y) @@ -2789,166 +2211,111 @@ rf += rstep gf += gstep bf += bstep - - if pc.HasFlag(FNB_BOTTOM): - y = y + 1 - else: - y = y - 1 - + if pc.HasFlag(FNB_BOTTOM): y = y + 1 + else: y = y - 1 def GetStartX(self, tabPoints, y, style): """ Returns the x start position of a tab. """ - x1, x2, y1, y2 = 0.0, 0.0, 0.0, 0.0 # We check the 3 points to the left - bBottomStyle = (style & FNB_BOTTOM and [True] or [False])[0] match = False - if bBottomStyle: - for i in xrange(3): - if y >= tabPoints[i].y and y < tabPoints[i+1].y: - x1 = tabPoints[i].x x2 = tabPoints[i+1].x y1 = tabPoints[i].y y2 = tabPoints[i+1].y match = True break - else: - for i in xrange(3): - if y <= tabPoints[i].y and y > tabPoints[i+1].y: - x1 = tabPoints[i].x x2 = tabPoints[i+1].x y1 = tabPoints[i].y y2 = tabPoints[i+1].y match = True break - - if not match: - return tabPoints[2].x - + if not match: return tabPoints[2].x + """ # According to the equation y = ax + b => x = (y-b)/a # We know the first 2 points - - if x2 == x1: - return x2 - else: - a = (y2 - y1)/(x2 - x1) - + """ + if x2 == x1: return x2 + else: a = (y2 - y1)/(x2 - x1) b = y1 - ((y2 - y1)/(x2 - x1))*x1 - - if a == 0: - return int(x1) - + if a == 0: return int(x1) x = (y - b)/a - return int(x) - def GetEndX(self, tabPoints, y, style): """ Returns the x end position of a tab. """ - x1, x2, y1, y2 = 0.0, 0.0, 0.0, 0.0 - # We check the 3 points to the left bBottomStyle = (style & FNB_BOTTOM and [True] or [False])[0] match = False - if bBottomStyle: - for i in xrange(7, 3, -1): - if y >= tabPoints[i].y and y < tabPoints[i-1].y: - x1 = tabPoints[i].x x2 = tabPoints[i-1].x y1 = tabPoints[i].y y2 = tabPoints[i-1].y match = True break - else: - for i in xrange(7, 3, -1): - if y <= tabPoints[i].y and y > tabPoints[i-1].y: - x1 = tabPoints[i].x x2 = tabPoints[i-1].x y1 = tabPoints[i].y y2 = tabPoints[i-1].y match = True break - if not match: return tabPoints[3].x - + """ # According to the equation y = ax + b => x = (y-b)/a # We know the first 2 points # Vertical line - if x1 == x2: - return int(x1) - + """ + if x1 == x2: return int(x1) a = (y2 - y1)/(x2 - x1) b = y1 - ((y2 - y1)/(x2 - x1))*x1 - - if a == 0: - return int(x1) - + if a == 0: return int(x1) x = (y - b)/a - return int(x) - def NumberTabsCanFit(self, pageContainer, fr=-1): """ Returns the number of tabs that can fit in the visible area. """ - pc = pageContainer - rect = pc.GetClientRect() clientWidth = rect.width - # Empty results vTabInfo = [] tabHeight = self.CalcTabHeight(pageContainer) - # The drawing starts from posx posx = pc._pParent.GetPadding() - - if fr < 0: - fr = pc._nFrom - + if fr < 0: fr = pc._nFrom for i in xrange(fr, len(pc._pagesInfoVec)): - vc8glitch = tabHeight + FNB_HEIGHT_SPACER tabWidth = self.CalcTabWidth(pageContainer, i, tabHeight) - - if posx + tabWidth + vc8glitch + self.GetButtonsAreaLength(pc) >= clientWidth: - break - + if posx + tabWidth + vc8glitch + self.GetButtonsAreaLength(pc) >= clientWidth: break # Add a result to the returned vector tabRect = wx.Rect(posx, VERTICAL_BORDER_PADDING, tabWidth, tabHeight) vTabInfo.append(tabRect) - # Advance posx posx += tabWidth + FNB_HEIGHT_SPACER - return vTabInfo -# ---------------------------------------------------------------------------- # +""" # Class FlatNotebook -# ---------------------------------------------------------------------------- # - +""" class FlatNotebook(wx.PyPanel): """ Display one or more windows in a notebook. @@ -2976,7 +2343,6 @@ 'style': this can be assigned to whatever combination of FNB_* styles. """ - self._bForceSelection = False self._nPadding = 6 self._nFrom = 0 @@ -2985,91 +2351,69 @@ self._windows = [] self._popupWin = None self._naviIcon = None - wx.PyPanel.__init__(self, parent, id, pos, size, style) - self._pages = PageContainer(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, style) - self.Bind(wx.EVT_NAVIGATION_KEY, self.OnNavigationKey) - self.Init() def Init(self): """ Initializes all the class attributes. """ - self._pages._colorBorder = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW) - self._mainSizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._mainSizer) - + """ # The child panels will inherit this bg color, so leave it at the default value #self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_APPWORKSPACE)) # Set default page height + """ dc = wx.ClientDC(self) - if "__WXGTK__" in wx.PlatformInfo: + """ # For GTK it seems that we must do this steps in order # for the tabs will get the proper height on initialization # on MSW, preforming these steps yields wierd results + """ boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.FONTWEIGHT_BOLD) dc.SetFont(boldFont) - height = dc.GetCharHeight() - tabHeight = height + FNB_HEIGHT_SPACER # We use 8 pixels as padding - - if "__WXGTK__" in wx.PlatformInfo: - tabHeight += 6 - + if "__WXGTK__" in wx.PlatformInfo: tabHeight += 6 self._pages.SetSizeHints(-1, tabHeight) # Add the tab container to the sizer self._mainSizer.Insert(0, self._pages, 0, wx.EXPAND) self._mainSizer.Layout() - self._pages._nFrom = self._nFrom self._pDropTarget = FNBDropTarget(self) self.SetDropTarget(self._pDropTarget) - def DoGetBestSize(self): """ Overrides DoGetBestSize to handle sizers nicely. """ - if not self._windows: # Something is better than nothing... no pages! return wx.Size(20, 20) - maxWidth = maxHeight = 0 tabHeight = self.GetPageBestSize().height - for win in self._windows: # Loop over all the windows to get their best size width, height = win.GetBestSize() maxWidth, maxHeight = max(maxWidth, width), max(maxHeight, height) - return wx.Size(maxWidth, maxHeight+tabHeight) - def SetActiveTabTextColour(self, textColour): """ Sets the text colour for the active tab. """ - self._pages._activeTextColor = textColour - def OnDropTarget(self, x, y, nTabPage, wnd_oldContainer): """ Handles the drop action from a DND operation. """ - return self._pages.OnDropTarget(x, y, nTabPage, wnd_oldContainer) - def GetPreviousSelection(self): """ Returns the previous selection. """ - return self._pages._iPreviousActivePage - def AddPage(self, page, text, select=True, imageId=-1): """ Add a page to the L{FlatNotebook}. @@ -3082,96 +2426,65 @@ Return value: True if successful, False otherwise. """ - # sanity check - if not page: - return False - + if not page: return False # reparent the window to us page.Reparent(self) - # Add tab bSelected = select or len(self._windows) == 0 - if bSelected: - bSelected = False - # Check for selection and send events oldSelection = self._pages._iActivePage tabIdx = len(self._windows) - event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetId()) event.SetSelection(tabIdx) event.SetOldSelection(oldSelection) event.SetEventObject(self) - if not self.GetEventHandler().ProcessEvent(event) or event.IsAllowed() or len(self._windows) == 0: bSelected = True - curSel = self._pages.GetSelection() - if not self._pages.IsShown(): self._pages.Show() - self._pages.AddPage(text, bSelected, imageId) self._windows.append(page) - self.Freeze() # Check if a new selection was made if bSelected: - if curSel >= 0: - # Remove the window from the main sizer self._mainSizer.Detach(self._windows[curSel]) self._windows[curSel].Hide() - if self.GetWindowStyleFlag() & FNB_BOTTOM: - self._mainSizer.Insert(0, page, 1, wx.EXPAND) - else: - # We leave a space of 1 pixel around the window self._mainSizer.Add(page, 1, wx.EXPAND) - # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED) event.SetOldSelection(oldSelection) self.GetEventHandler().ProcessEvent(event) - else: - # Hide the page page.Hide() - self.Thaw() self._mainSizer.Layout() self.Refresh() - return True - def SetImageList(self, imageList): """ Sets the image list for the page control. """ - self._pages.SetImageList(imageList) - def AssignImageList(self, imageList): """ Assigns the image list for the page control. """ - self._pages.AssignImageList(imageList) - def GetImageList(self): """ Returns the associated image list. """ - return self._pages.GetImageList() - def InsertPage(self, indx, page, text, select=True, imageId=-1): """ Inserts a new page at the specified position. @@ -3185,137 +2498,92 @@ Return value: True if successful, False otherwise. """ - # sanity check - if not page: - return False - + if not page: return False # reparent the window to us page.Reparent(self) - if not self._windows: - self.AddPage(page, text, select, imageId) return True - # Insert tab bSelected = select or not self._windows curSel = self._pages.GetSelection() - indx = max(0, min(indx, len(self._windows))) - - if indx <= len(self._windows): - - self._windows.insert(indx, page) - - else: - - self._windows.append(page) - + if indx <= len(self._windows): self._windows.insert(indx, page) + else: self._windows.append(page) if bSelected: - bSelected = False # Check for selection and send events oldSelection = self._pages._iActivePage - event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetId()) event.SetSelection(indx) event.SetOldSelection(oldSelection) event.SetEventObject(self) - if not self.GetEventHandler().ProcessEvent(event) or event.IsAllowed() or len(self._windows) == 0: bSelected = True - self._pages.InsertPage(indx, text, bSelected, imageId) - - if indx <= curSel: - curSel = curSel + 1 - + if indx <= curSel: curSel = curSel + 1 self.Freeze() # Check if a new selection was made if bSelected: - if curSel >= 0: # Remove the window from the main sizer self._mainSizer.Detach(self._windows[curSel]) self._windows[curSel].Hide() - self._pages.SetSelection(indx) # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED) event.SetOldSelection(oldSelection) self.GetEventHandler().ProcessEvent(event) - else: - # Hide the page page.Hide() - self.Thaw() self._mainSizer.Layout() self.Refresh() - return True - def SetSelection(self, page): """ Sets the selection for the given page. The call to this function generates the page changing events """ - - if page >= len(self._windows) or not self._windows: - return - + if page >= len(self._windows) or not self._windows: return # Support for disabed tabs if not self._pages.GetEnabled(page) and len(self._windows) > 1 and not self._bForceSelection: return - curSel = self._pages.GetSelection() - # program allows the page change self.Freeze() if curSel >= 0: - # Remove the window from the main sizer self._mainSizer.Detach(self._windows[curSel]) self._windows[curSel].Hide() - if self.GetWindowStyleFlag() & FNB_BOTTOM: - self._mainSizer.Insert(0, self._windows[page], 1, wx.EXPAND) - else: - # We leave a space of 1 pixel around the window self._mainSizer.Add(self._windows[page], 1, wx.EXPAND) - self._windows[page].Show() self.Thaw() - self._mainSizer.Layout() - if page != self._pages._iActivePage: # there is a real page changing self._pages._iPreviousActivePage = self._pages._iActivePage - self._pages._iActivePage = page self._pages.DoSetSelection(page) - def DeletePage(self, page): """ Deletes the specified page, and the associated window. The call to this function generates the page changing events. """ - if page >= len(self._windows) or page < 0: return - # Fire a closing event event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, self.GetId()) event.SetSelection(page) @@ -3325,7 +2593,6 @@ # The event handler allows it? if not event.IsAllowed(): return - self.Freeze() # Delete the requested page @@ -3333,17 +2600,14 @@ # If the page is the current window, remove it from the sizer # as well - if page == self._pages.GetSelection(): - self._mainSizer.Detach(pageRemoved) + if page == self._pages.GetSelection(): self._mainSizer.Detach(pageRemoved) # Remove it from the array as well self._windows.pop(page) # Now we can destroy it in wxWidgets use Destroy instead of delete pageRemoved.Destroy() - self.Thaw() - self._pages.DoDeletePage(page) self.Refresh() self.Update() @@ -3354,72 +2618,46 @@ closedEvent.SetEventObject(self) self.GetEventHandler().ProcessEvent(closedEvent) - def DeleteAllPages(self): """ Deletes all the pages. """ - - if not self._windows: - return False - + if not self._windows: return False self.Freeze() - - for page in self._windows: - page.Destroy() - + for page in self._windows: page.Destroy() self._windows = [] self.Thaw() - # Clear the container of the tabs as well self._pages.DeleteAllPages() return True - def GetCurrentPage(self): """ Returns the currently selected notebook page or None. """ - sel = self._pages.GetSelection() - if sel < 0: - return None - + if sel < 0: return None return self._windows[sel] - def GetPage(self, page): """ Returns the window at the given page position, or None. """ - - if page >= len(self._windows): - return None - + if page >= len(self._windows): return None return self._windows[page] - def GetPageIndex(self, win): """ Returns the index at which the window is found. """ - - try: - return self._windows.index(win) - except: - return -1 - + try: return self._windows.index(win) + except: return -1 def GetSelection(self): """ Returns the currently selected page, or -1 if none was selected. """ - return self._pages.GetSelection() - def AdvanceSelection(self, forward=True): """ Cycles through the tabs. The call to this function generates the page changing events. """ - self._pages.AdvanceSelection(forward) - def GetPageCount(self): """ Returns the number of pages in the L{FlatNotebook} control. """ - return self._pages.GetPageCount() def SetNavigatorIcon(self, bmp): @@ -3431,15 +2669,12 @@ img.Rescale(16, 16, wx.IMAGE_QUALITY_HIGH) bmp = wx.BitmapFromImage(img) self._naviIcon = bmp - else: - raise TypeError, "SetNavigatorIcon requires a valid bitmap" + else: raise TypeError, "SetNavigatorIcon requires a valid bitmap" def OnNavigationKey(self, event): """ Handles the wx.EVT_NAVIGATION_KEY event for L{FlatNotebook}. """ - if event.IsWindowChange(): - if len(self._windows) == 0: - return + if len(self._windows) == 0: return # change pages if self.HasFlag(FNB_SMART_TABS): if not self._popupWin: @@ -3455,292 +2690,198 @@ else: # change pages self.AdvanceSelection(event.GetDirection()) - - else: - event.Skip() - + else: event.Skip() def GetPageShapeAngle(self, page_index): """ Returns the angle associated to a tab. """ - - if page_index < 0 or page_index >= len(self._pages._pagesInfoVec): - return None, False - + if page_index < 0 or page_index >= len(self._pages._pagesInfoVec): return None, False result = self._pages._pagesInfoVec[page_index].GetTabAngle() return result, True - def SetPageShapeAngle(self, page_index, angle): """ Sets the angle associated to a tab. """ - - if page_index < 0 or page_index >= len(self._pages._pagesInfoVec): - return - - if angle > 15: - return - + if page_index < 0 or page_index >= len(self._pages._pagesInfoVec): return + if angle > 15: return self._pages._pagesInfoVec[page_index].SetTabAngle(angle) - def SetAllPagesShapeAngle(self, angle): """ Sets the angle associated to all the tab. """ - - if angle > 15: - return - - for ii in xrange(len(self._pages._pagesInfoVec)): - self._pages._pagesInfoVec[ii].SetTabAngle(angle) - + if angle > 15: return + for ii in xrange(len(self._pages._pagesInfoVec)): self._pages._pagesInfoVec[ii].SetTabAngle(angle) self.Refresh() - def GetPageBestSize(self): """ Return the page best size. """ - return self._pages.GetClientSize() - def SetPageText(self, page, text): """ Sets the text for the given page. """ - bVal = self._pages.SetPageText(page, text) self._pages.Refresh() - return bVal - def SetPadding(self, padding): """ Sets the amount of space around each page's icon and label, in pixels. NB: only the horizontal padding is considered. """ - self._nPadding = padding.GetWidth() - def GetTabArea(self): """ Returns the associated page. """ - return self._pages - def GetPadding(self): """ Returns the amount of space around each page's icon and label, in pixels. """ - return self._nPadding - def SetWindowStyleFlag(self, style): """ Sets the L{FlatNotebook} window style flags. """ - wx.PyPanel.SetWindowStyleFlag(self, style) renderer = self._pages._mgr.GetRenderer(self.GetWindowStyleFlag()) renderer._tabHeight = None - if self._pages: - # For changing the tab position (i.e. placing them top/bottom) # refreshing the tab container is not enough self.SetSelection(self._pages._iActivePage) - if not self._pages.HasFlag(FNB_HIDE_ON_SINGLE_TAB): #For Redrawing the Tabs once you remove the Hide tyle self._pages._ReShow() - def RemovePage(self, page): """ Deletes the specified page, without deleting the associated window. """ - - if page >= len(self._windows): - return False - + if page >= len(self._windows): return False # Fire a closing event event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CLOSING, self.GetId()) event.SetSelection(page) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) - # The event handler allows it? - if not event.IsAllowed(): - return False - + if not event.IsAllowed(): return False self.Freeze() # Remove the requested page pageRemoved = self._windows[page] - # If the page is the current window, remove it from the sizer # as well - if page == self._pages.GetSelection(): - self._mainSizer.Detach(pageRemoved) - + if page == self._pages.GetSelection(): self._mainSizer.Detach(pageRemoved) # Remove it from the array as well self._windows.pop(page) self.Thaw() - self._pages.DoDeletePage(page) - return True - def SetRightClickMenu(self, menu): """ Sets the popup menu associated to a right click on a tab. """ - self._pages._pRightClickMenu = menu - def GetPageText(self, nPage): """ Returns the tab caption. """ - return self._pages.GetPageText(nPage) - def SetGradientColours(self, fr, to, border): """ Sets the gradient colours for the tab. """ - self._pages._colorFrom = fr self._pages._colorTo = to self._pages._colorBorder = border - def SetGradientColourFrom(self, fr): """ Sets the starting colour for the gradient. """ - self._pages._colorFrom = fr - def SetGradientColourTo(self, to): """ Sets the ending colour for the gradient. """ - self._pages._colorTo = to - def SetGradientColourBorder(self, border): """ Sets the tab border colour. """ - self._pages._colorBorder = border - def GetGradientColourFrom(self): """ Gets first gradient colour. """ - return self._pages._colorFrom - def GetGradientColourTo(self): """ Gets second gradient colour. """ - return self._pages._colorTo - def GetGradientColourBorder(self): """ Gets the tab border colour. """ - return self._pages._colorBorder - def GetBorderColour(self): """ Returns the border colour. """ - return self._pages._colorBorder - def GetActiveTabTextColour(self): """ Get the active tab text colour. """ - return self._pages._activeTextColor - def SetPageImage(self, page, image): """ Sets the image index for the given page. Image is an index into the image list which was set with SetImageList. """ - self._pages.SetPageImage(page, image) - def GetPageImage(self, nPage): """ Returns the image index for the given page. Image is an index into the image list which was set with SetImageList. """ - return self._pages.GetPageImage(nPage) - def GetEnabled(self, page): """ Returns whether a tab is enabled or not. """ - return self._pages.GetEnabled(page) - def EnableTab(self, page, enabled=True): """ Enables or disables a tab. """ - - if page >= len(self._windows): - return - + if page >= len(self._windows): return self._windows[page].Enable(enabled) self._pages.EnableTab(page, enabled) - def GetNonActiveTabTextColour(self): """ Returns the non active tabs text colour. """ - return self._pages._nonActiveTextColor - def SetNonActiveTabTextColour(self, color): """ Sets the non active tabs text colour. """ - self._pages._nonActiveTextColor = color - def SetTabAreaColour(self, color): """ Sets the area behind the tabs colour. """ - self._pages._tabAreaColor = color - def GetTabAreaColour(self): """ Returns the area behind the tabs colour. """ - return self._pages._tabAreaColor - def SetActiveTabColour(self, color): """ Sets the active tab colour. """ - self._pages._activeTabColor = color - def GetActiveTabColour(self): """ Returns the active tab colour. """ - return self._pages._activeTabColor -# ---------------------------------------------------------------------------- # +""" # Class PageContainer # Acts as a container for the pages you add to FlatNotebook -# ---------------------------------------------------------------------------- # - +""" class PageContainer(wx.Panel): """ This class acts as a container for the pages you add to L{FlatNotebook}. """ - def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0): """ Default class constructor. """ - self._ImageList = None self._iActivePage = -1 self._pDropTarget = None self._nLeftClickZone = FNB_NOWHERE self._iPreviousActivePage = -1 - self._pRightClickMenu = None self._nXButtonStatus = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE @@ -3748,38 +2889,30 @@ self._nRightButtonStatus = FNB_BTN_NONE self._nLeftButtonStatus = FNB_BTN_NONE self._nTabXButtonStatus = FNB_BTN_NONE - self._pagesInfoVec = [] - self._colorTo = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION) self._colorFrom = wx.WHITE self._activeTabColor = wx.WHITE self._activeTextColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT) self._nonActiveTextColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNTEXT) self._tabAreaColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE) - self._nFrom = 0 self._isdragging = False # Set default page height, this is done according to the system font memDc = wx.MemoryDC() memDc.SelectObject(wx.EmptyBitmap(1,1)) - if "__WXGTK__" in wx.PlatformInfo: boldFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) boldFont.SetWeight(wx.BOLD) memDc.SetFont(boldFont) - height = memDc.GetCharHeight() tabHeight = height + FNB_HEIGHT_SPACER # We use 10 pixels as padding - wx.Panel.__init__(self, parent, id, pos, wx.Size(size.x, tabHeight), style|wx.NO_BORDER|wx.NO_FULL_REPAINT_ON_RESIZE|wx.WANTS_CHARS) - self._pDropTarget = FNBDropTarget(self) self.SetDropTarget(self._pDropTarget) self._mgr = FNBRendererMgr() - self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) @@ -3795,33 +2928,26 @@ self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) - def OnEraseBackground(self, event): """ Handles the wx.EVT_ERASE_BACKGROUND event for L{PageContainer} (does nothing).""" - pass - def _ReShow(self): """ Handles the Redraw of the tabs when the FNB_HIDE_ON_SINGLE_TAB has been removed """ self.Show() self.GetParent()._mainSizer.Layout() self.Refresh() - def OnPaint(self, event): """ Handles the wx.EVT_PAINT event for L{PageContainer}.""" - dc = wx.BufferedPaintDC(self) renderer = self._mgr.GetRenderer(self.GetParent().GetWindowStyleFlag()) renderer.DrawTabs(self, dc) - if self.HasFlag(FNB_HIDE_ON_SINGLE_TAB) and len(self._pagesInfoVec) <= 1: self.Hide() self.GetParent()._mainSizer.Layout() self.Refresh() - def AddPage(self, caption, selected=True, imgindex=-1): """ Add a page to the L{FlatNotebook}. @@ -3834,18 +2960,14 @@ Return value: True if successful, False otherwise. """ - if selected: - self._iPreviousActivePage = self._iActivePage self._iActivePage = len(self._pagesInfoVec) - # Create page info and add it to the vector pageInfo = PageInfo(caption, imgindex) self._pagesInfoVec.append(pageInfo) self.Refresh() - def InsertPage(self, indx, text, selected=True, imgindex=-1): """ Inserts a new page at the specified position. @@ -3859,93 +2981,62 @@ Return value: True if successful, False otherwise. """ - if selected: - self._iPreviousActivePage = self._iActivePage self._iActivePage = len(self._pagesInfoVec) - self._pagesInfoVec.insert(indx, PageInfo(text, imgindex)) - self.Refresh() return True - def OnSize(self, event): """ Handles the wx.EVT_SIZE events for L{PageContainer}. """ - # When resizing the control, try to fit to screen as many tabs as we can style = self.GetParent().GetWindowStyleFlag() renderer = self._mgr.GetRenderer(style) - fr = 0 page = self.GetSelection() - for fr in xrange(self._nFrom): vTabInfo = renderer.NumberTabsCanFit(self, fr) - if page - fr >= len(vTabInfo): - continue + if page - fr >= len(vTabInfo): continue break - self._nFrom = fr - self.Refresh() # Call on paint event.Skip() - def OnMiddleDown(self, event): """ Handles the wx.EVT_MIDDLE_DOWN events for L{PageContainer}. """ - # Test if this style is enabled style = self.GetParent().GetWindowStyleFlag() - - if not style & FNB_MOUSE_MIDDLE_CLOSES_TABS: - return - + if not style & FNB_MOUSE_MIDDLE_CLOSES_TABS: return where, tabIdx = self.HitTest(event.GetPosition()) - - if where == FNB_TAB: - self.DeletePage(tabIdx) - + if where == FNB_TAB: self.DeletePage(tabIdx) event.Skip() - def OnRightDown(self, event): """ Handles the wx.EVT_RIGHT_DOWN events for L{PageContainer}. """ - where, tabIdx = self.HitTest(event.GetPosition()) - if where in [FNB_TAB, FNB_TAB_X]: - if self._pagesInfoVec[tabIdx].GetEnabled(): # Fire events and eventually (if allowed) change selection self.FireEvent(tabIdx) - # send a message to popup a custom menu event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU, self.GetParent().GetId()) event.SetSelection(tabIdx) event.SetOldSelection(self._iActivePage) event.SetEventObject(self.GetParent()) self.GetParent().GetEventHandler().ProcessEvent(event) - - if self._pRightClickMenu: - self.PopupMenu(self._pRightClickMenu) - + if self._pRightClickMenu: self.PopupMenu(self._pRightClickMenu) event.Skip() - def OnLeftDown(self, event): """ Handles the wx.EVT_LEFT_DOWN events for L{PageContainer}. """ - # Reset buttons status self._nXButtonStatus = FNB_BTN_NONE self._nLeftButtonStatus = FNB_BTN_NONE self._nRightButtonStatus = FNB_BTN_NONE self._nTabXButtonStatus = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE - self._nLeftClickZone, tabIdx = self.HitTest(event.GetPosition()) - if self._nLeftClickZone == FNB_DROP_DOWN_ARROW: self._nArrowDownButtonStatus = FNB_BTN_PRESSED self.Refresh() @@ -3961,387 +3052,244 @@ elif self._nLeftClickZone == FNB_TAB_X: self._nTabXButtonStatus = FNB_BTN_PRESSED self.Refresh() - elif self._nLeftClickZone == FNB_TAB: - if self._iActivePage != tabIdx: - # In case the tab is disabled, we dont allow to choose it - if self._pagesInfoVec[tabIdx].GetEnabled(): - self.FireEvent(tabIdx) - + if self._pagesInfoVec[tabIdx].GetEnabled(): self.FireEvent(tabIdx) def RotateLeft(self): - if self._nFrom == 0: return - # Make sure that the button was pressed before - if self._nLeftButtonStatus != FNB_BTN_PRESSED: - return - + if self._nLeftButtonStatus != FNB_BTN_PRESSED: return self._nLeftButtonStatus = FNB_BTN_HOVER - # We scroll left with bulks of 5 scrollLeft = self.GetNumTabsCanScrollLeft() - self._nFrom -= scrollLeft - if self._nFrom < 0: - self._nFrom = 0 - + if self._nFrom < 0: self._nFrom = 0 self.Refresh() - def RotateRight(self): - - if self._nFrom >= len(self._pagesInfoVec) - 1: - return - + if self._nFrom >= len(self._pagesInfoVec) - 1: return # Make sure that the button was pressed before - if self._nRightButtonStatus != FNB_BTN_PRESSED: - return - + if self._nRightButtonStatus != FNB_BTN_PRESSED: return self._nRightButtonStatus = FNB_BTN_HOVER - # Check if the right most tab is visible, if it is # don't rotate right anymore - if self._pagesInfoVec[len(self._pagesInfoVec)-1].GetPosition() != wx.Point(-1, -1): - return - + if self._pagesInfoVec[len(self._pagesInfoVec)-1].GetPosition() != wx.Point(-1, -1): return self._nFrom += 1 self.Refresh() - def OnLeftUp(self, event): """ Handles the wx.EVT_LEFT_UP events for L{PageContainer}. """ - # forget the zone that was initially clicked self._nLeftClickZone = FNB_NOWHERE - where, tabIdx = self.HitTest(event.GetPosition()) - # Make sure selected tab has focus self.SetFocus() - - if where == FNB_LEFT_ARROW: - self.RotateLeft() - - elif where == FNB_RIGHT_ARROW: - self.RotateRight() - + if where == FNB_LEFT_ARROW: self.RotateLeft() + elif where == FNB_RIGHT_ARROW: self.RotateRight() elif where == FNB_X: - # Make sure that the button was pressed before - if self._nXButtonStatus != FNB_BTN_PRESSED: - return - + if self._nXButtonStatus != FNB_BTN_PRESSED: return self._nXButtonStatus = FNB_BTN_HOVER - self.DeletePage(self._iActivePage) - elif where == FNB_TAB_X: - # Make sure that the button was pressed before - if self._nTabXButtonStatus != FNB_BTN_PRESSED: - return - + if self._nTabXButtonStatus != FNB_BTN_PRESSED: return self._nTabXButtonStatus = FNB_BTN_HOVER - self.DeletePage(self._iActivePage) - elif where == FNB_DROP_DOWN_ARROW: - # Make sure that the button was pressed before - if self._nArrowDownButtonStatus != FNB_BTN_PRESSED: - return - + if self._nArrowDownButtonStatus != FNB_BTN_PRESSED: return self._nArrowDownButtonStatus = FNB_BTN_NONE - # Refresh the button status renderer = self._mgr.GetRenderer(self.GetParent().GetWindowStyleFlag()) dc = wx.ClientDC(self) renderer.DrawDropDownArrow(self, dc) - self.PopupTabsMenu() - event.Skip() - def HitTest(self, pt): """ HitTest method for L{PageContainer}. Returns the flag (if any) and the hit page (if any). """ - style = self.GetParent().GetWindowStyleFlag() render = self._mgr.GetRenderer(style) - fullrect = self.GetClientRect() btnLeftPos = render.GetLeftButtonPos(self) btnRightPos = render.GetRightButtonPos(self) btnXPos = render.GetXPos(self) - tabIdx = -1 - - if len(self._pagesInfoVec) == 0: - return FNB_NOWHERE, tabIdx - + if len(self._pagesInfoVec) == 0: return FNB_NOWHERE, tabIdx rect = wx.Rect(btnXPos, 8, 16, 16) - if rect.Contains(pt): - return (style & FNB_NO_X_BUTTON and [FNB_NOWHERE] or [FNB_X])[0], tabIdx - + if rect.Contains(pt): return (style & FNB_NO_X_BUTTON and [FNB_NOWHERE] or [FNB_X])[0], tabIdx rect = wx.Rect(btnRightPos, 8, 16, 16) if style & FNB_DROPDOWN_TABS_LIST: rect = wx.Rect(render.GetDropArrowButtonPos(self), 8, 16, 16) - if rect.Contains(pt): - return FNB_DROP_DOWN_ARROW, tabIdx - + if rect.Contains(pt): return FNB_DROP_DOWN_ARROW, tabIdx if rect.Contains(pt): return (style & FNB_NO_NAV_BUTTONS and [FNB_NOWHERE] or [FNB_RIGHT_ARROW])[0], tabIdx - rect = wx.Rect(btnLeftPos, 8, 16, 16) if rect.Contains(pt): return (style & FNB_NO_NAV_BUTTONS and [FNB_NOWHERE] or [FNB_LEFT_ARROW])[0], tabIdx - # Test whether a left click was made on a tab bFoundMatch = False - for cur in xrange(self._nFrom, len(self._pagesInfoVec)): - pgInfo = self._pagesInfoVec[cur] - if pgInfo.GetPosition() == wx.Point(-1, -1): continue - if style & FNB_X_ON_TAB and cur == self.GetSelection(): # 'x' button exists on a tab if self._pagesInfoVec[cur].GetXRect().Contains(pt): return FNB_TAB_X, cur - if style & FNB_VC8: - if self._pagesInfoVec[cur].GetRegion().Contains(pt.x, pt.y): - if bFoundMatch or cur == self.GetSelection(): - return FNB_TAB, cur - + if bFoundMatch or cur == self.GetSelection(): return FNB_TAB, cur tabIdx = cur bFoundMatch = True - else: - tabRect = wx.Rect(pgInfo.GetPosition().x, pgInfo.GetPosition().y, pgInfo.GetSize().x, pgInfo.GetSize().y) - if tabRect.Contains(pt): # We have a match return FNB_TAB, cur - - if bFoundMatch: - return FNB_TAB, tabIdx - + if bFoundMatch: return FNB_TAB, tabIdx if self._isdragging: # We are doing DND, so check also the region outside the tabs # try before the first tab pgInfo = self._pagesInfoVec[0] tabRect = wx.Rect(0, pgInfo.GetPosition().y, pgInfo.GetPosition().x, self.GetParent().GetSize().y) - if tabRect.Contains(pt): - return FNB_TAB, 0 - + if tabRect.Contains(pt): return FNB_TAB, 0 # try after the last tab pgInfo = self._pagesInfoVec[-1] startpos = pgInfo.GetPosition().x+pgInfo.GetSize().x tabRect = wx.Rect(startpos, pgInfo.GetPosition().y, fullrect.width-startpos, self.GetParent().GetSize().y) - - if tabRect.Contains(pt): - return FNB_TAB, len(self._pagesInfoVec) - + if tabRect.Contains(pt): return FNB_TAB, len(self._pagesInfoVec) # Default return FNB_NOWHERE, -1 - def SetSelection(self, page): """ Sets the selected page. """ - book = self.GetParent() book.SetSelection(page) self.DoSetSelection(page) - def DoSetSelection(self, page): """ Does the actual selection of a page. """ - if page < len(self._pagesInfoVec): #! fix for tabfocus da_page = self._pParent.GetPage(page) - - if da_page != None: - da_page.SetFocus() - + if da_page != None: da_page.SetFocus() if not self.IsTabVisible(page): # Try to remove one tab from start and try again - if not self.CanFitToScreen(page): - - if self._nFrom > page: - self._nFrom = page + if self._nFrom > page: self._nFrom = page else: while self._nFrom < page: self._nFrom += 1 - if self.CanFitToScreen(page): - break - + if self.CanFitToScreen(page): break self.Refresh() - def DeletePage(self, page): """ Delete the specified page from L{FlatNotebook}. """ - book = self.GetParent() book.DeletePage(page) book.Refresh() - def IsTabVisible(self, page): """ Returns whether a tab is visible or not. """ - iLastVisiblePage = self.GetLastVisibleTab() return page <= iLastVisiblePage and page >= self._nFrom - def DoDeletePage(self, page): """ Does the actual page deletion. """ - # Remove the page from the vector book = self.GetParent() self._pagesInfoVec.pop(page) - # Thanks to Yiaanis AKA Mandrav if self._iActivePage >= page: self._iActivePage = self._iActivePage - 1 self._iPreviousActivePage = -1 - # The delete page was the last first on the array, # but the book still has more pages, so we set the # active page to be the first one (0) if self._iActivePage < 0 and len(self._pagesInfoVec) > 0: self._iActivePage = 0 self._iPreviousActivePage = -1 - # Refresh the tabs if self._iActivePage >= 0: - book._bForceSelection = True - # Check for selection and send event event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetParent().GetId()) event.SetSelection(self._iActivePage) event.SetOldSelection(self._iPreviousActivePage) event.SetEventObject(self.GetParent()) - book.SetSelection(self._iActivePage) book._bForceSelection = False - # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED) event.SetOldSelection(self._iPreviousActivePage) self.GetParent().GetEventHandler().ProcessEvent(event) - if not self._pagesInfoVec: # Erase the page container drawings dc = wx.ClientDC(self) dc.Clear() - def DeleteAllPages(self): """ Deletes all the pages. """ - self._iActivePage = -1 self._iPreviousActivePage = -1 self._nFrom = 0 self._pagesInfoVec = [] - # Erase the page container drawings dc = wx.ClientDC(self) dc.Clear() - def OnMouseMove(self, event): """ Handles the wx.EVT_MOTION for L{PageContainer}. """ - if self._pagesInfoVec and self.IsShown(): - xButtonStatus = self._nXButtonStatus xTabButtonStatus = self._nTabXButtonStatus rightButtonStatus = self._nRightButtonStatus leftButtonStatus = self._nLeftButtonStatus dropDownButtonStatus = self._nArrowDownButtonStatus - style = self.GetParent().GetWindowStyleFlag() - self._nXButtonStatus = FNB_BTN_NONE self._nRightButtonStatus = FNB_BTN_NONE self._nLeftButtonStatus = FNB_BTN_NONE self._nTabXButtonStatus = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE - where, tabIdx = self.HitTest(event.GetPosition()) - if where == FNB_X: if event.LeftIsDown(): - self._nXButtonStatus = (self._nLeftClickZone==FNB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] - - else: - - self._nXButtonStatus = FNB_BTN_HOVER - + else: self._nXButtonStatus = FNB_BTN_HOVER elif where == FNB_DROP_DOWN_ARROW: if event.LeftIsDown(): - self._nArrowDownButtonStatus = (self._nLeftClickZone==FNB_DROP_DOWN_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] - - else: - - self._nArrowDownButtonStatus = FNB_BTN_HOVER - + else: self._nArrowDownButtonStatus = FNB_BTN_HOVER elif where == FNB_TAB_X: if event.LeftIsDown(): - self._nTabXButtonStatus = (self._nLeftClickZone==FNB_TAB_X and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] - - else: - - self._nTabXButtonStatus = FNB_BTN_HOVER - + else: self._nTabXButtonStatus = FNB_BTN_HOVER elif where == FNB_RIGHT_ARROW: if event.LeftIsDown(): - self._nRightButtonStatus = (self._nLeftClickZone==FNB_RIGHT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] - - else: - - self._nRightButtonStatus = FNB_BTN_HOVER - + else: self._nRightButtonStatus = FNB_BTN_HOVER elif where == FNB_LEFT_ARROW: if event.LeftIsDown(): - self._nLeftButtonStatus = (self._nLeftClickZone==FNB_LEFT_ARROW and [FNB_BTN_PRESSED] or [FNB_BTN_NONE])[0] - - else: - - self._nLeftButtonStatus = FNB_BTN_HOVER - + else: self._nLeftButtonStatus = FNB_BTN_HOVER elif where == FNB_TAB: # Call virtual method for showing tooltip self.ShowTabTooltip(tabIdx) - if not self.GetEnabled(tabIdx): # Set the cursor to be 'No-entry' wx.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY)) - # Support for drag and drop if event.Dragging() and not (style & FNB_NODRAG): - self._isdragging = True draginfo = FNBDragInfo(self, tabIdx) drginfo = cPickle.dumps(draginfo) @@ -4350,123 +3298,70 @@ dragSource = FNBDropSource(self) dragSource.SetData(dataobject) dragSource.DoDragDrop(wx.Drag_DefaultMove) - bRedrawX = self._nXButtonStatus != xButtonStatus bRedrawRight = self._nRightButtonStatus != rightButtonStatus bRedrawLeft = self._nLeftButtonStatus != leftButtonStatus bRedrawTabX = self._nTabXButtonStatus != xTabButtonStatus bRedrawDropArrow = self._nArrowDownButtonStatus != dropDownButtonStatus - render = self._mgr.GetRenderer(style) - if (bRedrawX or bRedrawRight or bRedrawLeft or bRedrawTabX or bRedrawDropArrow): - dc = wx.ClientDC(self) - - if bRedrawX: - - render.DrawX(self, dc) - - if bRedrawLeft: - - render.DrawLeftArrow(self, dc) - - if bRedrawRight: - - render.DrawRightArrow(self, dc) - - if bRedrawTabX: - - self.Refresh() - - if bRedrawDropArrow: - - render.DrawDropDownArrow(self, dc) - + if bRedrawX: render.DrawX(self, dc) + if bRedrawLeft: render.DrawLeftArrow(self, dc) + if bRedrawRight: render.DrawRightArrow(self, dc) + if bRedrawTabX: self.Refresh() + if bRedrawDropArrow: render.DrawDropDownArrow(self, dc) event.Skip() - def GetLastVisibleTab(self): """ Returns the last visible tab. """ - - if self._nFrom < 0: - return -1 - + if self._nFrom < 0: return -1 ii = 0 - for ii in xrange(self._nFrom, len(self._pagesInfoVec)): - - if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1): - break - + if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1): break return ii-1 - def GetNumTabsCanScrollLeft(self): """ Returns the number of tabs than can be scrolled left. """ - - if self._nFrom - 1 >= 0: - return 1 - + if self._nFrom - 1 >= 0: return 1 return 0 - def IsDefaultTabs(self): """ Returns whether a tab has a default style. """ - style = self.GetParent().GetWindowStyleFlag() res = (style & FNB_VC71) or (style & FNB_FANCY_TABS) or (style & FNB_VC8) return not res - def AdvanceSelection(self, bForward=True): """ Cycles through the tabs. The call to this function generates the page changing events. """ - nSel = self.GetSelection() - - if nSel < 0: - return - + if nSel < 0: return nMax = self.GetPageCount() - 1 - - if bForward: - newSelection = (nSel == nMax and [0] or [nSel + 1])[0] - else: - newSelection = (nSel == 0 and [nMax] or [nSel - 1])[0] - - if not self._pagesInfoVec[newSelection].GetEnabled(): - return - + if bForward: newSelection = (nSel == nMax and [0] or [nSel + 1])[0] + else: newSelection = (nSel == 0 and [nMax] or [nSel - 1])[0] + if not self._pagesInfoVec[newSelection].GetEnabled(): return self.FireEvent(newSelection) - def OnMouseLeave(self, event): """ Handles the wx.EVT_LEAVE_WINDOW event for L{PageContainer}. """ - self._nLeftButtonStatus = FNB_BTN_NONE self._nXButtonStatus = FNB_BTN_NONE self._nRightButtonStatus = FNB_BTN_NONE self._nTabXButtonStatus = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE - style = self.GetParent().GetWindowStyleFlag() render = self._mgr.GetRenderer(style) - dc = wx.ClientDC(self) - render.DrawX(self, dc) render.DrawLeftArrow(self, dc) render.DrawRightArrow(self, dc) - selection = self.GetSelection() - if selection == -1: event.Skip() return - if not self.IsTabVisible(selection): if selection == len(self._pagesInfoVec) - 1: if not self.CanFitToScreen(selection): @@ -4478,151 +3373,96 @@ render.DrawTabX(self, dc, self._pagesInfoVec[selection].GetXRect(), selection, self._nTabXButtonStatus) render.DrawFocusRectangle(dc, self, self._pagesInfoVec[selection]) - event.Skip() - def OnMouseEnterWindow(self, event): """ Handles the wx.EVT_ENTER_WINDOW event for L{PageContainer}. """ - self._nLeftButtonStatus = FNB_BTN_NONE self._nXButtonStatus = FNB_BTN_NONE self._nRightButtonStatus = FNB_BTN_NONE self._nLeftClickZone = FNB_BTN_NONE self._nArrowDownButtonStatus = FNB_BTN_NONE - event.Skip() - def ShowTabTooltip(self, tabIdx): """ Shows a tab tooltip. """ - pWindow = self._pParent.GetPage(tabIdx) - if pWindow: pToolTip = pWindow.GetToolTip() if pToolTip and pToolTip.GetWindow() == pWindow: self.SetToolTipString(pToolTip.GetTip()) - def SetPageImage(self, page, imgindex): """ Sets the image index associated to a page. """ - if page < len(self._pagesInfoVec): - self._pagesInfoVec[page].SetImageIndex(imgindex) self.Refresh() - def GetPageImage(self, page): """ Returns the image index associated to a page. """ - - if page < len(self._pagesInfoVec): - - return self._pagesInfoVec[page].GetImageIndex() - + if page < len(self._pagesInfoVec): return self._pagesInfoVec[page].GetImageIndex() return -1 - def OnDropTarget(self, x, y, nTabPage, wnd_oldContainer): """ Handles the drop action from a DND operation. """ - # Disable drag'n'drop for disabled tab - if not wnd_oldContainer._pagesInfoVec[nTabPage].GetEnabled(): - return wx.DragCancel - + if not wnd_oldContainer._pagesInfoVec[nTabPage].GetEnabled(): return wx.DragCancel self._isdragging = True oldContainer = wnd_oldContainer nIndex = -1 - where, nIndex = self.HitTest(wx.Point(x, y)) - oldNotebook = oldContainer.GetParent() newNotebook = self.GetParent() - if oldNotebook == newNotebook: - if nTabPage >= 0: - - if where == FNB_TAB: - self.MoveTabPage(nTabPage, nIndex) - + if where == FNB_TAB: self.MoveTabPage(nTabPage, nIndex) elif self.GetParent().GetWindowStyleFlag() & FNB_ALLOW_FOREIGN_DND: - if wx.Platform in ["__WXMSW__", "__WXGTK__", "__WXMAC__"]: if nTabPage >= 0: - window = oldNotebook.GetPage(nTabPage) - if window: where, nIndex = newNotebook._pages.HitTest(wx.Point(x, y)) caption = oldContainer.GetPageText(nTabPage) imageindex = oldContainer.GetPageImage(nTabPage) oldNotebook.RemovePage(nTabPage) window.Reparent(newNotebook) - if imageindex >= 0: - bmp = oldNotebook.GetImageList().GetBitmap(imageindex) newImageList = newNotebook.GetImageList() - if not newImageList: xbmp, ybmp = bmp.GetWidth(), bmp.GetHeight() newImageList = wx.ImageList(xbmp, ybmp) imageindex = 0 - else: - imageindex = newImageList.GetImageCount() - + else: imageindex = newImageList.GetImageCount() newImageList.Add(bmp) newNotebook.SetImageList(newImageList) - newNotebook.InsertPage(nIndex, window, caption, True, imageindex) - self._isdragging = False - return wx.DragMove - def MoveTabPage(self, nMove, nMoveTo): """ Moves a tab inside the same L{FlatNotebook}. """ - - if nMove == nMoveTo: - return - - elif nMoveTo < len(self._pParent._windows): - nMoveTo = nMoveTo + 1 - + if nMove == nMoveTo: return + elif nMoveTo < len(self._pParent._windows): nMoveTo = nMoveTo + 1 self._pParent.Freeze() - # Remove the window from the main sizer nCurSel = self._pParent._pages.GetSelection() self._pParent._mainSizer.Detach(self._pParent._windows[nCurSel]) self._pParent._windows[nCurSel].Hide() - pWindow = self._pParent._windows[nMove] self._pParent._windows.pop(nMove) self._pParent._windows.insert(nMoveTo-1, pWindow) - pgInfo = self._pagesInfoVec[nMove] - self._pagesInfoVec.pop(nMove) self._pagesInfoVec.insert(nMoveTo - 1, pgInfo) - # Add the page according to the style pSizer = self._pParent._mainSizer style = self.GetParent().GetWindowStyleFlag() - - if style & FNB_BOTTOM: - - pSizer.Insert(0, pWindow, 1, wx.EXPAND) - + if style & FNB_BOTTOM: pSizer.Insert(0, pWindow, 1, wx.EXPAND) else: - # We leave a space of 1 pixel around the window pSizer.Add(pWindow, 1, wx.EXPAND) - pWindow.Show() - pSizer.Layout() self._iActivePage = nMoveTo - 1 self._iPreviousActivePage = -1 @@ -4630,128 +3470,79 @@ self.Refresh() self._pParent.Thaw() - def CanFitToScreen(self, page): """ Returns wheter a tab can fit in the left space in the screen or not. """ - # Incase the from is greater than page, # we need to reset the self._nFrom, so in order # to force the caller to do so, we return false - if self._nFrom > page: - return False - + if self._nFrom > page: return False style = self.GetParent().GetWindowStyleFlag() render = self._mgr.GetRenderer(style) - vTabInfo = render.NumberTabsCanFit(self) - - if page - self._nFrom >= len(vTabInfo): - return False - + if page - self._nFrom >= len(vTabInfo): return False return True - def GetNumOfVisibleTabs(self): """ Returns the number of visible tabs. """ - count = 0 for ii in xrange(self._nFrom, len(self._pagesInfoVec)): - if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1): - break + if self._pagesInfoVec[ii].GetPosition() == wx.Point(-1, -1): break count = count + 1 - return count - def GetEnabled(self, page): """ Returns whether a tab is enabled or not. """ - - if page >= len(self._pagesInfoVec): - return True # Seems strange, but this is the default - + if page >= len(self._pagesInfoVec): return True # Seems strange, but this is the default return self._pagesInfoVec[page].GetEnabled() - def EnableTab(self, page, enabled=True): """ Enables or disables a tab. """ - - if page >= len(self._pagesInfoVec): - return - + if page >= len(self._pagesInfoVec): return self._pagesInfoVec[page].EnableTab(enabled) - def GetSingleLineBorderColour(self): """ Returns the colour for the single line border. """ - - if self.HasFlag(FNB_FANCY_TABS): - return self._colorFrom - + if self.HasFlag(FNB_FANCY_TABS): return self._colorFrom return wx.WHITE - def HasFlag(self, flag): """ Returns whether a flag is present in the L{FlatNotebook} style. """ - style = self.GetParent().GetWindowStyleFlag() res = (style & flag and [True] or [False])[0] return res - def ClearFlag(self, flag): """ Deletes a flag from the L{FlatNotebook} style. """ - style = self.GetParent().GetWindowStyleFlag() style &= ~flag self.SetWindowStyleFlag(style) - def TabHasImage(self, tabIdx): """ Returns whether a tab has an associated image index or not. """ - if self._ImageList: return self._pagesInfoVec[tabIdx].GetImageIndex() != -1 - return False - def OnLeftDClick(self, event): """ Handles the wx.EVT_LEFT_DCLICK event for L{PageContainer}. """ - where, tabIdx = self.HitTest(event.GetPosition()) - - if where == FNB_RIGHT_ARROW: - self.RotateRight() - - elif where == FNB_LEFT_ARROW: - self.RotateLeft() - + if where == FNB_RIGHT_ARROW: self.RotateRight() + elif where == FNB_LEFT_ARROW: self.RotateLeft() elif self.HasFlag(FNB_DCLICK_CLOSES_TABS): - - if where == FNB_TAB: - self.DeletePage(tabIdx) - - else: - - event.Skip() - + if where == FNB_TAB: self.DeletePage(tabIdx) + else: event.Skip() def OnSetFocus(self, event): """ Handles the wx.EVT_SET_FOCUS event for L{PageContainer}. """ - if self._iActivePage < 0: event.Skip() return - self.SetFocusedPage(self._iActivePage) - def OnKillFocus(self, event): """ Handles the wx.EVT_KILL_FOCUS event for L{PageContainer}. """ - self.SetFocusedPage() - def OnKeyDown(self, event): """ When the PageContainer has the focus tabs can be changed with @@ -4770,125 +3561,92 @@ else: event.Skip() - def SetFocusedPage(self, pageIndex=-1): """ Sets/Unsets the focus on the appropriate page. If pageIndex is defaulted, we have lost focus and no focus indicator is drawn. """ - for indx, page in enumerate(self._pagesInfoVec): if indx == pageIndex: page._hasFocus = True else: page._hasFocus = False - self.Refresh() - def PopupTabsMenu(self): """ Pops up the menu activated with the drop down arrow in the navigation area. """ - popupMenu = wx.Menu() - for i in xrange(len(self._pagesInfoVec)): pi = self._pagesInfoVec[i] item = wx.MenuItem(popupMenu, i+1, pi.GetCaption(), pi.GetCaption(), wx.ITEM_NORMAL) self.Bind(wx.EVT_MENU, self.OnTabMenuSelection, item) - # There is an alignment problem with wx2.6.3 & Menus so only use # images for versions above 2.6.3 if wx.VERSION > (2, 6, 3, 0) and self.TabHasImage(i): item.SetBitmap(self.GetImageList().GetBitmap(pi.GetImageIndex())) - popupMenu.AppendItem(item) item.Enable(pi.GetEnabled()) - self.PopupMenu(popupMenu) - def OnTabMenuSelection(self, event): """ Handles the wx.EVT_MENU event for L{PageContainer}. """ - selection = event.GetId() - 1 self.FireEvent(selection) - def FireEvent(self, selection): """ Fires the wxEVT_FLATNOTEBOOK_PAGE_CHANGING and wxEVT_FLATNOTEBOOK_PAGE_CHANGED events called from other methods (from menu selection or Smart Tabbing). Utility function. """ - if selection == self._iActivePage: # No events for the same selection return - oldSelection = self._iActivePage - event = FlatNotebookEvent(wxEVT_FLATNOTEBOOK_PAGE_CHANGING, self.GetParent().GetId()) event.SetSelection(selection) event.SetOldSelection(oldSelection) event.SetEventObject(self.GetParent()) - if not self.GetParent().GetEventHandler().ProcessEvent(event) or event.IsAllowed(): - self.SetSelection(selection) - # Fire a wxEVT_FLATNOTEBOOK_PAGE_CHANGED event event.SetEventType(wxEVT_FLATNOTEBOOK_PAGE_CHANGED) event.SetOldSelection(oldSelection) self.GetParent().GetEventHandler().ProcessEvent(event) self.SetFocus() - def SetImageList(self, imglist): """ Sets the image list for the page control. """ - self._ImageList = imglist - def AssignImageList(self, imglist): """ Assigns the image list for the page control. """ - self._ImageList = imglist - def GetImageList(self): """ Returns the image list for the page control. """ - return self._ImageList - def GetSelection(self): """ Returns the current selected page. """ return self._iActivePage - def GetPageCount(self): """ Returns the number of tabs in the L{FlatNotebook} control. """ - return len(self._pagesInfoVec) - def GetPageText(self, page): """ Returns the tab caption of the page. """ - return self._pagesInfoVec[page].GetCaption() - def SetPageText(self, page, text): """ Sets the tab caption of the page. """ - self._pagesInfoVec[page].SetCaption(text) return True - def DrawDragHint(self): """ Draws small arrow at the place that the tab will be placed. """ - # get the index of tab that will be replaced with the dragged tab pt = wx.GetMousePosition() client_pt = self.ScreenToClient(pt)
--- a/orpg/tools/aliaslib.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/aliaslib.py Thu Aug 27 01:04:43 2009 -0500 @@ -29,30 +29,23 @@ __version__ = "$Id: aliaslib.py,v 1.20 2007/08/09 05:23:21 digitalxero Exp $" from orpg.orpg_wx import * -from orpg.orpgCore import * +from orpg.orpgCore import component from orpg.orpg_windows import createMaskedButton, orpgMultiCheckBoxDlg from orpg.tools.rgbhex import RGBHex -import orpg.tools.orpg_log -import orpg.dirpath -import orpg.orpg_xml -import orpg.tools.validate -import orpg.tools.orpg_settings +from orpg.dirpath import dir_struct +from orpg.tools.validate import validate +from orpg.tools.orpg_settings import settings +import re class AliasLib(wx.Frame): def __init__(self): - self.orpgframe = open_rpg.get_component('frame') - self.log = open_rpg.get_component('log') - self.log.log("Enter AliasLib", ORPG_DEBUG) + self.orpgframe = component.get('frame') wx.Frame.__init__(self, None, wx.ID_ANY, title="Alias Lib") self.orpgframe.Freeze() self.Freeze() self.SetOwnBackgroundColour('#EFEFEF') - self.dir_struct = open_rpg.get_component('dir_struct') - self.settings = open_rpg.get_component('settings') - self.xml = open_rpg.get_component('xml') - self.validate = open_rpg.get_component('validate') - self.filename = self.settings.get_setting('aliasfile') + '.alias' - self.validate.config_file(self.filename, "default_alias.alias") + self.filename = settings.get_setting('aliasfile') + '.alias' + validate.config_file(self.filename, "default_alias.alias") self.buildMenu() self.buildButtons() self.buildGUI() @@ -61,16 +54,14 @@ self.Thaw() self.orpgframe.Thaw() self.Bind(wx.EVT_CLOSE, self.OnMB_FileExit) - self.log.log("Exit AliasLib", ORPG_DEBUG) def InitSetup(self): - self.chat = open_rpg.get_component('chat') - self.gametree = open_rpg.get_component('tree') - self.map = open_rpg.get_component('map') - self.session = open_rpg.get_component('session') + self.chat = component.get('chat') + self.gametree = component.get('tree') + self.map = component.get('map') + self.session = component.get('session') def buildMenu(self): - self.log.log("Enter AliasLib->buildMenu(self)", ORPG_DEBUG) filemenu = wx.Menu() item = wx.MenuItem(filemenu, wx.ID_ANY, "&New\tCtrl+N", "New ALias Lib") self.Bind(wx.EVT_MENU, self.OnMB_FileNew, item) @@ -129,10 +120,8 @@ menu.Append(filtermenu, "&Filter") menu.Append(transmitmenu, "&Transmit") self.SetMenuBar(menu) - self.log.log("Exit AliasLib->buildMenu(self)", ORPG_DEBUG) def OnMB_FileNew(self, event): - self.log.log("Enter AliasLib->OnMB_FileNew(self, event)", ORPG_DEBUG) oldfilename = self.filename dlg = wx.TextEntryDialog(self, "Please Name This Alias Lib", "New Alias Lib") if dlg.ShowModal() == wx.ID_OK: @@ -143,24 +132,22 @@ self.aliasList = [] self.filterList = [] self.OnMB_FileSave(None) - self.settings.set_setting('aliasfile', self.filename[:-6]) - self.log.log("Exit AliasLib->OnMB_FileNew(self, event)", ORPG_DEBUG) + settings.set_setting('aliasfile', self.filename[:-6]) def OnMB_FileOpen(self, event): - self.log.log("Enter AliasLib->OnMB_FileOpen(self, event)", ORPG_DEBUG) oldfilename = self.filename - dlg = wx.FileDialog(self, "Select an Alias Lib to Open", self.dir_struct["user"], wildcard="*.alias", style=wx.HIDE_READONLY|wx.OPEN) + dlg = wx.FileDialog(self, "Select an Alias Lib to Open", + dir_struct["user"], wildcard="*.alias", + style=wx.HIDE_READONLY|wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() dlg.Destroy() if oldfilename != self.filename: self.OnMB_FileSave(None, oldfilename) self.loadFile() - self.settings.set_setting('aliasfile', self.filename[:-6]) - self.log.log("Exit AliasLib->OnMB_FileOpen(self, event)", ORPG_DEBUG) + settings.set_setting('aliasfile', self.filename[:-6]) def OnMB_FileSave(self, event, file=None): - self.log.log("Enter AliasLib->OnMB_FileSave(self, event)", ORPG_DEBUG) idx = self.aliasIdx if file == None: file = self.filename @@ -182,15 +169,18 @@ xml += "\t</filter>\n" xml += "</aliaslib>" self.alias = idx - f = open(self.dir_struct["user"] + file, "w") + f = open(dir_struct["user"] + file, "w") f.write(xml) f.close() - self.log.log("Exit AliasLib->OnMB_FileSave(self, event)", ORPG_DEBUG) def OnMB_FileExportToTree(self, event): - self.log.log("Enter AliasLib->OnMB_FileExportToTree(self, event)", ORPG_DEBUG) - #tree = open_rpg.get_component("tree") - xml = '<nodehandler class="voxchat_handler" icon="player" module="voxchat" name="' + self.filename[:-6] + '" use.filter="0" version="1.0">' + "\n" + #tree = component.get("tree") + xml = '<nodehandler class="voxchat_handler" ' + xml += 'icon="player" ' + xml += 'module="voxchat" ' + xml += 'name="' + self.filename[:-6] + '" ' + xml += 'use.filter="0" ' + xml += 'version="1.0">' + '\n' idx = self.aliasIdx for n in xrange(self.selectAliasWnd.GetItemCount()): self.alias = n @@ -210,23 +200,16 @@ xml += "\t</voxchat.filter>\n" xml += "</nodehandler>" self.gametree.insert_xml(xml) - self.log.log("Exit AliasLib->OnMB_FileExportToTree(self, event)", ORPG_DEBUG) def OnMB_FileExit(self, event): - self.log.log("Enter AliasLib->OnMB_FileExit(self, event)", ORPG_DEBUG) self.OnMB_FileSave(0) self.Hide() - top_frame = open_rpg.get_component('frame') - top_frame.mainmenu.Check(top_frame.mainmenu.FindMenuItem("Windows", "Alias Lib"), False) - self.log.log("Exit AliasLib->OnMB_FileExit(self, event)", ORPG_DEBUG) + self.orpgframe.mainmenu.Check(self.orpgframe.mainmenu.FindMenuItem("Windows", "Alias Lib"), False) def OnMB_AliasNew(self, event): - self.log.log("Enter AliasLib->OnMB_AliasNew(self, event)", ORPG_DEBUG) self.NewEditAliasDialog("New") - self.log.log("Exit AliasLib->OnMB_AliasNew(self, event)", ORPG_DEBUG) def OnMB_AliasAddTemporary(self, event): - self.log.log("Enter AliasLib->OnMB_AliasAddTemporary(self, event)", ORPG_DEBUG) minis = self.map.canvas.layers['miniatures'].miniatures for min in minis: name = min.label @@ -235,16 +218,12 @@ self.selectAliasWnd.SetStringItem(i, 1, "Default") self.selectAliasWnd.RefreshItem(i) self.RefreshAliases() - self.log.log("Exit AliasLib->OnMB_AliasAddTemporary(self, event)", ORPG_DEBUG) def OnMB_AliasEdit(self, event): - self.log.log("Enter AliasLib->OnMB_AliasEdit(self, event)", ORPG_DEBUG) if self.aliasIdx != -1: self.NewEditAliasDialog("Edit") - self.log.log("Exit AliasLib->OnMB_AliasEdit(self, event)", ORPG_DEBUG) def NewEditAliasDialog(self, type): - self.log.log("Enter AliasLib->NewEditAliasDialog(self, type)", ORPG_DEBUG) dlg = wx.Dialog(self, wx.ID_ANY, type + " Alias", style=wx.DEFAULT_DIALOG_STYLE|wx.STAY_ON_TOP) txt = wx.TextCtrl(dlg, wx.ID_ANY) if type == 'Edit': @@ -279,24 +258,18 @@ self.selectAliasWnd.SetItemTextColour(i, RGBHex().hexstring(r, g, b)) self.selectAliasWnd.RefreshItem(i) self.RefreshAliases() - self.log.log("Exit AliasLib->NewEditAliasDialog(self, type)", ORPG_DEBUG) def ChangeAliasColor(self, event): - self.log.log("Enter AliasLib->ChangeAliasColor(self, event)", ORPG_DEBUG) color = RGBHex().do_hex_color_dlg(self) self.colorbtn.SetLabel("Chat Color") self.colorbtn.SetForegroundColour(color) - self.log.log("Exit AliasLib->ChangeAliasColor(self, event)", ORPG_DEBUG) def OnMB_AliasDelete(self, event): - self.log.log("Enter AliasLib->OnMB_AliasDelete(self, event)", ORPG_DEBUG) if self.aliasIdx != -1: self.selectAliasWnd.DeleteItem(self.aliasIdx) self.RefreshAliases() - self.log.log("Exit AliasLib->OnMB_AliasDelete(self, event)", ORPG_DEBUG) def OnMB_FilterNew(self, event): - self.log.log("Enter AliasLib->OnMB_FilterNew(self, event)", ORPG_DEBUG) dlg = wx.TextEntryDialog(self, 'Filter Name: ', 'Please name this filter') if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() @@ -306,141 +279,121 @@ self.filter = i self.regExList.append([]) self.OnMB_FilterEdit(None) - self.log.log("Exit AliasLib->OnMB_FilterNew(self, event)", ORPG_DEBUG) def OnMB_FilterEdit(self, event): - self.log.log("Enter AliasLib->OnMB_FilterEdit(self, event)", ORPG_DEBUG) wnd = FilterEditWnd(self, self.filter, self.filterRegEx) wnd.MakeModal(True) wnd.Show() - self.log.log("Exit AliasLib->OnMB_FilterEdit(self, event)", ORPG_DEBUG) def OnMB_FilterDelete(self, event): - self.log.log("Enter AliasLib->OnMB_FilterDelete(self, event)", ORPG_DEBUG) if self.filterIdx != -1: self.selectFilterWnd.DeleteItem(self.filterIdx) - self.log.log("Exit AliasLib->OnMB_FilterDelete(self, event)", ORPG_DEBUG) def OnMB_TransmitSend(self, event): - self.log.log("Enter AliasLib->OnMB_TransmitSend(self, event)", ORPG_DEBUG) self.orpgframe.Freeze() if self.alias[1] != 'Default': - defaultcolor = self.settings.get_setting("mytextcolor") - self.settings.set_setting("mytextcolor", self.alias[1]) + defaultcolor = settings.get_setting("mytextcolor") + settings.set_setting("mytextcolor", self.alias[1]) self.chat.set_colors() line = self.textWnd.GetValue().replace("\n", "<br />") if self.checkFilterText.IsChecked() and self.filter != self.chat.defaultFilterName: - for rule in self.filterRegEx: - line = re.sub(rule[0], rule[1], line) + for rule in self.filterRegEx: line = re.sub(rule[0], rule[1], line) if len(line) > 1: - if len(line) > 1 and line[0] != "/": - self.chat.ParsePost(line, True, True) - else: - self.chat.chat_cmds.docmd(line) + if len(line) > 1 and line[0] != "/": self.chat.ParsePost(line, True, True) + else: self.chat.chat_cmds.docmd(line) if self.alias[1] != 'Default': - self.settings.set_setting("mytextcolor", defaultcolor) + settings.set_setting("mytextcolor", defaultcolor) self.chat.set_colors() if self.checkClearText.IsChecked(): self.textWnd.SetValue("") - top_frame.Thaw() - self.log.log("Exit AliasLib->OnMB_TransmitSend(self, event)", ORPG_DEBUG) + self.orpgframe.Thaw() def OnMB_TransmitEmote(self, event): - self.log.log("Enter AliasLib->OnMB_TransmitEmote(self, event)", ORPG_DEBUG) self.orpgframe.Freeze() line = self.textWnd.GetValue().replace("\n", "<br />") if self.checkFilterText.IsChecked() and self.filter != self.chat.defaultFilterName: - for rule in self.filterRegEx: - line = re.sub(rule[0], rule[1], line) + for rule in self.filterRegEx: line = re.sub(rule[0], rule[1], line) self.chat.emote_message(line) if self.checkClearText.IsChecked(): self.textWnd.SetValue("") - top_frame.Thaw() - self.log.log("Exit AliasLib->OnMB_TransmitEmote(self, event)", ORPG_DEBUG) + self.orpgframe.Thaw() def OnMB_TransmitWhisper(self, event): - self.log.log("Enter AliasLib->OnMB_TransmitWhisper(self, event)", ORPG_DEBUG) self.orpgframe.Freeze() players = self.session.get_players() if self.alias[1] != 'Default': - defaultcolor = self.settings.get_setting("mytextcolor") - self.settings.set_setting("mytextcolor", self.alias[1]) + defaultcolor = settings.get_setting("mytextcolor") + settings.set_setting("mytextcolor", self.alias[1]) self.chat.set_colors() opts = [] - myid = session.get_id() + myid = self.session.get_id() for p in players: - if p[2] != myid: - opts.append("(" + p[2] + ") " + self.chat.html_strip(p[0])) + if p[2] != myid: opts.append("(" + p[2] + ") " + self.chat.html_strip(p[0])) dlg = orpgMultiCheckBoxDlg(self, opts, "Select Players:", "Whisper To", []) sendto = [] if dlg.ShowModal() == wx.ID_OK: selections = dlg.get_selections() - for s in selections: - sendto.append(players[s][2]) + for s in selections: sendto.append(players[s][2]) line = self.textWnd.GetValue().replace("\n", "<br />") if self.checkFilterText.IsChecked() and self.filter != self.chat.defaultFilterName: - for rule in self.filterRegEx: - line = re.sub(rule[0], rule[1], line) - if len(sendto): - self.chat.whisper_to_players(line, sendto) + for rule in self.filterRegEx: line = re.sub(rule[0], rule[1], line) + if len(sendto): self.chat.whisper_to_players(line, sendto) if self.alias[1] != 'Default': - self.settings.set_setting("mytextcolor", defaultcolor) + settings.set_setting("mytextcolor", defaultcolor) self.chat.set_colors() - if self.checkClearText.IsChecked(): - self.textWnd.SetValue("") - top_frame.Thaw() - self.log.log("Exit AliasLib->OnMB_TransmitWhisper(self, event)", ORPG_DEBUG) + if self.checkClearText.IsChecked(): self.textWnd.SetValue("") + self.orpgframe.Thaw() def OnMB_TransmitMacro(self, event): - self.log.log("Enter AliasLib->OnMB_TransmitMacro(self, event)", ORPG_DEBUG) self.orpgframe.Freeze() if self.alias[1] != 'Default': - defaultcolor = self.settings.get_setting("mytextcolor") - self.settings.set_setting("mytextcolor", self.alias[1]) + defaultcolor = settings.get_setting("mytextcolor") + settings.set_setting("mytextcolor", self.alias[1]) self.chat.set_colors() lines = self.textWnd.GetValue().split("\n") if self.checkFilterText.IsChecked() and self.filter != self.chat.defaultFilterName: + line = self.textWnd.GetValue().replace("\n", "<br />") for rule in self.filterRegEx: line = re.sub(rule[0], rule[1], line) for line in lines: if len(line) > 1: - if line[0] != "/": - self.chat.ParsePost(line, True, True) - else: - self.chat.chat_cmds.docmd(line) + if line[0] != "/": self.chat.ParsePost(line, True, True) + else: self.chat.chat_cmds.docmd(line) if self.alias[1] != 'Default': - self.settings.set_setting("mytextcolor", defaultcolor) + settings.set_setting("mytextcolor", defaultcolor) self.chat.set_colors() - if self.checkClearText.IsChecked(): - self.textWnd.SetValue("") - top_frame.Thaw() - self.log.log("Exit AliasLib->OnMB_TransmitMacro(self, event)", ORPG_DEBUG) + if self.checkClearText.IsChecked(): self.textWnd.SetValue("") + self.orpgframe.Thaw() def buildButtons(self): - self.log.log("Enter AliasLib->buildButtons(self)", ORPG_DEBUG) self.topBtnSizer = wx.BoxSizer(wx.HORIZONTAL) self.middleBtnSizer = wx.BoxSizer(wx.HORIZONTAL) self.bottomBtnSizer = wx.BoxSizer(wx.HORIZONTAL) - self.addFromMapBtn = createMaskedButton(self, self.dir_struct["icon"] + 'install.gif', 'Add temporary aliases from map', wx.ID_ANY, "#C0C0C0") - self.newAliasBtn = createMaskedButton(self, self.dir_struct["icon"] + 'player.gif', 'Add a new Alias', wx.ID_ANY) - self.delAliasBtn = createMaskedButton(self, self.dir_struct["icon"] + 'noplayer.gif', 'Delete selected Alias', wx.ID_ANY) - self.editAliasBtn = createMaskedButton(self, self.dir_struct["icon"] + 'note.gif', 'Edit selected Alias', wx.ID_ANY) + self.addFromMapBtn = createMaskedButton(self, dir_struct["icon"] + 'install.gif', + 'Add temporary aliases from map', wx.ID_ANY, "#C0C0C0") + self.newAliasBtn = createMaskedButton(self, dir_struct["icon"] + 'player.gif', 'Add a new Alias', wx.ID_ANY) + self.delAliasBtn = createMaskedButton(self, dir_struct["icon"] + 'noplayer.gif', 'Delete selected Alias', wx.ID_ANY) + self.editAliasBtn = createMaskedButton(self, dir_struct["icon"] + 'note.gif', 'Edit selected Alias', wx.ID_ANY) self.Bind(wx.EVT_BUTTON, self.OnMB_AliasNew, self.newAliasBtn) self.Bind(wx.EVT_BUTTON, self.OnMB_AliasAddTemporary, self.addFromMapBtn) self.Bind(wx.EVT_BUTTON, self.OnMB_AliasEdit, self.editAliasBtn) self.Bind(wx.EVT_BUTTON, self.OnMB_AliasDelete, self.delAliasBtn) - self.newFilterBtn = createMaskedButton(self, self.dir_struct["icon"] + 'add_filter.gif', 'Add a new Filter', wx.ID_ANY, "#0000FF") - self.editFilterBtn = createMaskedButton(self, self.dir_struct["icon"] + 'edit_filter.gif', 'Edit selected Filter', wx.ID_ANY, "#FF0000") - self.delFilterBtn = createMaskedButton(self, self.dir_struct["icon"] + 'delete_filter.gif', 'Delete selected Filter', wx.ID_ANY, "#0000FF") + self.newFilterBtn = createMaskedButton(self, dir_struct["icon"] + 'add_filter.gif', + 'Add a new Filter', wx.ID_ANY, "#0000FF") + self.editFilterBtn = createMaskedButton(self, dir_struct["icon"] + 'edit_filter.gif', + 'Edit selected Filter', wx.ID_ANY, "#FF0000") + self.delFilterBtn = createMaskedButton(self, dir_struct["icon"] + 'delete_filter.gif', + 'Delete selected Filter', wx.ID_ANY, "#0000FF") self.Bind(wx.EVT_BUTTON, self.OnMB_FilterNew, self.newFilterBtn) self.Bind(wx.EVT_BUTTON, self.OnMB_FilterEdit, self.editFilterBtn) self.Bind(wx.EVT_BUTTON, self.OnMB_FilterDelete, self.delFilterBtn) - self.textBoldBtn = createMaskedButton(self, self.dir_struct["icon"] + 'bold.gif', 'Bold', wx.ID_ANY, "#BDBDBD") - self.textItalicBtn = createMaskedButton(self, self.dir_struct["icon"] + 'italic.gif', 'Italic', wx.ID_ANY, "#BDBDBD") - self.textUnderlineBtn = createMaskedButton(self, self.dir_struct["icon"] + 'underlined.gif', 'Underline', wx.ID_ANY, "#BDBDBD") + self.textBoldBtn = createMaskedButton(self, dir_struct["icon"] + 'bold.gif', 'Bold', wx.ID_ANY, "#BDBDBD") + self.textItalicBtn = createMaskedButton(self, dir_struct["icon"] + 'italic.gif', 'Italic', wx.ID_ANY, "#BDBDBD") + self.textUnderlineBtn = createMaskedButton(self, dir_struct["icon"] + 'underlined.gif', + 'Underline', wx.ID_ANY, "#BDBDBD") self.textColorBtn = wx.Button(self, wx.ID_ANY, "Color") self.textColorBtn.SetForegroundColour(wx.BLACK) - self.exportBtn = createMaskedButton(self, self.dir_struct["icon"] + 'grid.gif', 'Export to Tree', wx.ID_ANY) + self.exportBtn = createMaskedButton(self, dir_struct["icon"] + 'grid.gif', 'Export to Tree', wx.ID_ANY) self.Bind(wx.EVT_BUTTON, self.FormatText, self.textBoldBtn) self.Bind(wx.EVT_BUTTON, self.FormatText, self.textItalicBtn) self.Bind(wx.EVT_BUTTON, self.FormatText, self.textUnderlineBtn) @@ -478,10 +431,8 @@ self.bottomBtnSizer.Add(self.whisperBtn, 0, wx.EXPAND) self.bottomBtnSizer.Add(self.macroBtn, 0, wx.EXPAND) self.bottomBtnSizer.Add(self.doneBtn, 0, wx.EXPAND|wx.ALIGN_RIGHT) - self.log.log("Exit AliasLib->buildButtons(self)", ORPG_DEBUG) def buildGUI(self): - self.log.log("Enter AliasLib->buildGUI(self)", ORPG_DEBUG) self.sizer = wx.BoxSizer(wx.VERTICAL) rightwnd = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_LIVE_UPDATE|wx.SP_NO_XP_THEME|wx.SP_3DSASH) leftwnd = wx.SplitterWindow(rightwnd, wx.ID_ANY, style=wx.SP_LIVE_UPDATE|wx.SP_NO_XP_THEME|wx.SP_3DSASH) @@ -495,7 +446,9 @@ self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnMB_FilterEdit, self.selectFilterWnd) self.textWnd = wx.TextCtrl(rightwnd, wx.ID_ANY, style=wx.TE_MULTILINE|wx.TE_BESTWRAP) leftwnd.SplitHorizontally(self.selectAliasWnd, self.selectFilterWnd) + leftwnd.SetMinimumPaneSize(75) rightwnd.SplitVertically(leftwnd, self.textWnd) + rightwnd.SetMinimumPaneSize(200) self.sizer.Add(self.topBtnSizer, 0, wx.EXPAND) self.sizer.Add(rightwnd, 1, wx.EXPAND) self.sizer.Add(self.middleBtnSizer, 0, wx.EXPAND) @@ -503,24 +456,20 @@ self.SetSizer(self.sizer) self.SetAutoLayout(True) self.Fit() - self.log.log("Exit AliasLib->buildGUI(self)", ORPG_DEBUG) def loadFile(self): - self.log.log("Enter AliasLib->loadFile(self)", ORPG_DEBUG) - f = open(self.dir_struct["user"] + self.filename, "r") + f = open(dir_struct["user"] + self.filename, "r") data = f.read() f.close() self.alias = -1 self.filter = -1 - xml_dom = self.xml.parseXml(data) + xml_dom = component.get('xml').parseXml(data) del data aliases = xml_dom.getElementsByTagName("alias") alist = [] for alias in aliases: - if alias.hasAttribute("color"): - color = alias.getAttribute("color") - else: - color = 'Default' + if alias.hasAttribute("color"): color = alias.getAttribute("color") + else: color = 'Default' aname = self.MakeSafeHTML(alias.getAttribute("name")) alist.append([aname, color]) alist.sort() @@ -532,21 +481,19 @@ flist.append(filter.getAttribute("name")) rules = filter.getElementsByTagName("rule") sub = [] - for rule in rules: - sub.append([self.MakeSafeHTML(rule.getAttribute("match")), self.MakeSafeHTML(rule.getAttribute("sub"))]) + for rule in rules: sub.append([self.MakeSafeHTML(rule.getAttribute("match")), + self.MakeSafeHTML(rule.getAttribute("sub"))]) self.regExList.append(sub) self.filterList = flist xml_dom.unlink() self.alias = -1 self.filter = -1 - self.log.log("Exit AliasLib->loadFile(self)", ORPG_DEBUG) def MakeSafeHTML(self, str): return str.replace("&", "&").replace("<", "<").replace(""", '"').replace(">", ">").replace("'", "'") def MakeHTMLSafe(self, str): return str.replace("&", "&").replace("<", "<").replace('"', """).replace(">", ">").replace("'", "'") def ImportFromTree(self, xml_dom): - self.log.log("Enter AliasLib->ImportFromTree(self, xml_dom)", ORPG_DEBUG) oldfilename = self.filename if xml_dom.getAttribute('name') == 'Alias Library': dlg = wx.TextEntryDialog(self, "Please Name This Alias Lib", "New Alias Lib") @@ -556,40 +503,30 @@ else: dlg.Destroy() return - else: - self.filename = xml_dom.getAttribute('name') + '.alias' - self.settings.set_setting('aliasfile', self.filename[:-6]) - if oldfilename != self.filename: - self.OnMB_FileSave(None, oldfilename) - f = open(self.dir_struct["user"] + self.filename, "w") + else: self.filename = xml_dom.getAttribute('name') + '.alias' + settings.set_setting('aliasfile', self.filename[:-6]) + if oldfilename != self.filename: self.OnMB_FileSave(None, oldfilename) + f = open(dir_struct["user"] + self.filename, "w") f.write(xml_dom.toxml().replace('nodehandler', 'aliaslib').replace('voxchat.', '')) f.close() wx.CallAfter(self.loadFile) - self.log.log("Exit AliasLib->ImportFromTree(self, xml_dom)", ORPG_DEBUG) def NewAliasSelection(self, event): - self.log.log("Enter AliasLib->NewAliasSelection(self, event)", ORPG_DEBUG) self.alias = event.GetIndex() wx.CallAfter(self.chat.aliasList.SetStringSelection, self.alias[0]) - self.log.log("Exit AliasLib->NewAliasSelection(self, event)", ORPG_DEBUG) def NoAliasSelection(self, event): - self.log.log("Enter AliasLib->NoAliasSelection(self, event)", ORPG_DEBUG) self.aliasIdx = -1 wx.CallAfter(self.chat.aliasList.SetStringSelection, self.alias[0]) - self.log.log("Exit AliasLib->NoAliasSelection(self, event)", ORPG_DEBUG) def GetSelectedAlias(self): - self.log.log("Enter AliasLib->GetSelectedAlias(self)", ORPG_DEBUG) self.InitSetup() if self.aliasIdx != -1: - self.log.log("Exit AliasLib->GetSelectedAlias(self) return " + str(self.aliasIdx), ORPG_DEBUG) - return [self.selectAliasWnd.GetItem(self.aliasIdx, 0).GetText(), self.selectAliasWnd.GetItem(self.aliasIdx, 1).GetText()] - self.log.log("Exit AliasLib->GetSelectedAlias(self) return " + str(self.aliasIdx), ORPG_DEBUG) + return [self.selectAliasWnd.GetItem(self.aliasIdx, 0).GetText(), + self.selectAliasWnd.GetItem(self.aliasIdx, 1).GetText()] return [self.chat.defaultAliasName, "Default"] def SetSelectedAlias(self, alias): - self.log.log("Enter AliasLib->SetSelectedAlias(self, aliasIdx)", ORPG_DEBUG) found = False if isinstance(alias, (int, long)): self.aliasIdx = alias @@ -601,36 +538,29 @@ found = True if not found: self.aliasIdx = -1 - self.log.log("Exit AliasLib->SetSelectedAlias(self, aliasIdx)", ORPG_DEBUG) def GetAliasList(self): - self.log.log("Enter AliasLib->GetAliasList(self)", ORPG_DEBUG) alist = [] for n in xrange(0, self.selectAliasWnd.GetItemCount()): self.alias = n alist.append(self.alias[0]) - self.log.log("Exit AliasLib->GetAliasList(self)", ORPG_DEBUG) alist.sort() alist.insert(0, self.chat.defaultAliasName) return alist def SetAliasList(self, alist): - self.log.log("Enter AliasLib->SetAliasList(self, list)", ORPG_DEBUG) self.selectAliasWnd.ClearAll() self.selectAliasWnd.InsertColumn(0, "Alias") self.selectAliasWnd.InsertColumn(1, "Chat Color") for item in alist: i = self.selectAliasWnd.InsertStringItem(self.selectAliasWnd.GetItemCount(), item[0]) self.selectAliasWnd.SetStringItem(i, 1, item[1]) - if item[1] != 'Default': - self.selectAliasWnd.SetItemTextColour(i, item[1]) + if item[1] != 'Default': self.selectAliasWnd.SetItemTextColour(i, item[1]) self.selectAliasWnd.RefreshItem(i) self.aliasIdx = -1 self.RefreshAliases() - self.log.log("Exit AliasLib->SetAliasList(self, list)", ORPG_DEBUG) def GetAliasColor(self): - self.log.log("Enter/Exit AliasLib->GetAliasColor(self) return " + self.alias[1], ORPG_DEBUG) return self.alias[1] def RefreshAliases(self): @@ -643,23 +573,19 @@ tmp = self.chat.aliasList.GetStringSelection() self.alias = tmp aidx = self.aliasIdx+1 - if len(self.aliasList) <= aidx: - aidx = 0 + if len(self.aliasList) <= aidx: aidx = 0 self.chat.aliasList.Clear() - for n in xrange(l1): - self.chat.aliasList.Insert(self.aliasList[n], n) + for n in xrange(l1): self.chat.aliasList.Insert(self.aliasList[n], n) self.chat.aliasList.SetStringSelection(self.aliasList[aidx]) fidx = self.chat.filterList.GetSelection() - if len(self.filterList) <= fidx: - fidx = 0 + if len(self.filterList) <= fidx: fidx = 0 self.chat.filterList.Clear() for n in xrange(l2): self.chat.filterList.Insert(self.filterList[n], n) self.chat.filterList.SetStringSelection(self.filterList[fidx]) if self.chat.parent.GMChatPanel != None: aidx = self.chat.parent.GMChatPanel.aliasList.GetSelection() - if len(self.aliasList) <- aidx: - aidx = 0 + if len(self.aliasList) <- aidx: aidx = 0 self.chat.parent.GMChatPanel.aliasList.Clear() for n in xrange(l1): self.chat.parent.GMChatPanel.aliasList.Insert(self.aliasList[n], n) @@ -699,8 +625,7 @@ for tab in self.chat.parent.null_tabs: aidx = tab.aliasList.GetSelection() - if len(self.aliasList) <= aidx: - aidx = 0 + if len(self.aliasList) <= aidx: aidx = 0 tab.aliasList.Clear() for n in xrange(l1): tab.aliasList.Insert(self.aliasList[n], n) @@ -714,55 +639,38 @@ wx.CallAfter(self.orpgframe.Thaw) def SetAliasColor(self, color): - self.log.log("Enter AliasLib->SetAliasColor(self, color)", ORPG_DEBUG) if self.aliasIdx != -1: self.selectAliasWnd.SetStringItem(self.aliasIdx, 1, color) self.selectAliasWnd.SetItemTextColour(self.aliasIdx, color) - self.log.log("Exit AliasLib->SetAliasColor(self, color)", ORPG_DEBUG) def FilterTextChecked(self, event): if self.checkFilterText.IsChecked(): self.chat.filterList.SetStringSelection(self.filter) - else: - self.chat.filterList.SetStringSelection(self.chat.defaultFilterName) + else: self.chat.filterList.SetStringSelection(self.chat.defaultFilterName) def NewFilterSelection(self, event): - self.log.log("Enter AliasLib->NewFilterSelection(self, event)", ORPG_DEBUG) self.filter = event.GetIndex() - if self.checkFilterText.IsChecked(): - wx.CallAfter(self.chat.filterList.SetStringSelection, self.filter) - self.log.log("Exit AliasLib->NewFilterSelection(self, event)", ORPG_DEBUG) + if self.checkFilterText.IsChecked(): wx.CallAfter(self.chat.filterList.SetStringSelection, self.filter) def NoFilterSelection(self, event): - self.log.log("Enter AliasLib->NoFilterSelection(self, event)", ORPG_DEBUG) self.filter = -1 wx.CallAfter(self.chat.filterList.SetStringSelection, self.filter) - self.log.log("Exit AliasLib->NoFilterSelection(self, event)", ORPG_DEBUG) def GetSelectedFilter(self): - self.log.log("Enter AliasLib->GetSelectedFilter(self)", ORPG_DEBUG) - if self.filterIdx != -1: - self.log.log("Exit AliasLib->GetSelectedFilter(self) return " + str(self.filterIdx), ORPG_DEBUG) - return self.selectFilterWnd.GetItem(self.filterIdx, 0).GetText() - self.log.log("Exit AliasLib->GetSelectedFilter(self) return " + str(self.filterIdx), ORPG_DEBUG) + if self.filterIdx != -1: return self.selectFilterWnd.GetItem(self.filterIdx, 0).GetText() return self.chat.defaultFilterName def SetSelectedFilter(self, idx): - self.log.log("Enter AliasLib->SetSelectedFilter(self, filter)", ORPG_DEBUG) self.filterIdx = idx - self.log.log("Exit AliasLib->SetSelectedFilter(self, filter)", ORPG_DEBUG) def GetFilterList(self): - self.log.log("Enter AliasLib->GetFilterList(self)", ORPG_DEBUG) list = [] for n in xrange(-1, self.selectFilterWnd.GetItemCount()): self.filter = n list.append(self.filter) - self.log.log("Exit AliasLib->GetFilterList(self)", ORPG_DEBUG) return list def SetFilterList(self, list): - self.log.log("Enter AliasLib->SetFilterList(self, list)", ORPG_DEBUG) self.selectFilterWnd.ClearAll() self.selectFilterWnd.InsertColumn(0, "Filter Name") for item in list: @@ -771,11 +679,9 @@ self.selectFilterWnd.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.filter = -1 self.RefreshAliases() - self.log.log("Exit AliasLib->SetFilterList(self, list)", ORPG_DEBUG) def GetFilterRegEx(self): - if self.filterIdx == -1: - return [] + if self.filterIdx == -1: return [] return self.regExList[self.filterIdx] def SetFilterRegEx(self, list): @@ -787,16 +693,11 @@ id = event.GetId() txt = self.textWnd.GetValue() (beg, end) = self.textWnd.GetSelection() - if beg != end: - sel_txt = txt[beg:end] - else: - sel_txt = txt - if id == self.textBoldBtn.GetId(): - sel_txt = "<b>" + sel_txt + "</b>" - elif id == self.textItalicBtn.GetId(): - sel_txt = "<i>" + sel_txt + "</i>" - elif id == self.textUnderlineBtn.GetId(): - sel_txt = "<u>" + sel_txt + "</u>" + if beg != end: sel_txt = txt[beg:end] + else: sel_txt = txt + if id == self.textBoldBtn.GetId(): sel_txt = "<b>" + sel_txt + "</b>" + elif id == self.textItalicBtn.GetId(): sel_txt = "<i>" + sel_txt + "</i>" + elif id == self.textUnderlineBtn.GetId(): sel_txt = "<u>" + sel_txt + "</u>" elif id == self.textColorBtn.GetId(): dlg = wx.ColourDialog(self) if not dlg.ShowModal() == wx.ID_OK: @@ -806,10 +707,8 @@ color = RGBHex().hexstring(color[0], color[1], color[2]) dlg.Destroy() sel_txt = '<font color="' + color + '">' + sel_txt + '</font>' - if beg != end: - txt = txt[:beg] + sel_txt + txt[end:] - else: - txt = sel_txt + if beg != end: txt = txt[:beg] + sel_txt + txt[end:] + else: txt = sel_txt self.textWnd.SetValue(txt) self.textWnd.SetInsertionPointEnd() self.textWnd.SetFocus() @@ -818,27 +717,22 @@ alias = property(GetSelectedAlias, SetSelectedAlias) aliasList = property(GetAliasList, SetAliasList) aliasColor = property(GetAliasColor, SetAliasColor) - filter = property(GetSelectedFilter, SetSelectedFilter) filterList = property(GetFilterList, SetFilterList) filterRegEx = property(GetFilterRegEx, SetFilterRegEx) - class FilterEditWnd(wx.Frame): def __init__(self, parent, filterName, filterList): wx.Frame.__init__(self, parent, wx.ID_ANY, "Edit Filter: " + filterName) - self.filterList = filterList self.parent = parent - self.Freeze() self.buildGUI() self.fillList() self.Layout() self.grid.Select(0) self.Thaw() - self.Bind(wx.EVT_CLOSE, self.OnExit) def buildGUI(self): @@ -847,38 +741,30 @@ bsizer.Add(self.panel, 1, wx.EXPAND) self.SetSizer(bsizer) self.SetAutoLayout(True) - self.grid = wx.ListCtrl(self.panel, wx.ID_ANY, style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES) self.grid.InsertColumn(0, "Replace") self.grid.InsertColumn(1, "With") self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.selectRule, self.grid) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.RuleEdit, self.grid) - self.addBtn = wx.Button(self.panel, wx.ID_ANY, 'Add') self.editBtn = wx.Button(self.panel, wx.ID_ANY, 'Edit') self.deleteBtn = wx.Button(self.panel, wx.ID_ANY, 'Delete') self.okBtn = wx.Button(self.panel, wx.ID_OK, 'Done') - self.Bind(wx.EVT_BUTTON, self.RuleAdd, self.addBtn) self.Bind(wx.EVT_BUTTON, self.RuleEdit, self.editBtn) self.Bind(wx.EVT_BUTTON, self.RuleDelete, self.deleteBtn) self.Bind(wx.EVT_BUTTON, self.OnDone, self.okBtn) - btsizer = wx.BoxSizer(wx.VERTICAL) btsizer.Add(self.addBtn, 0, wx.EXPAND) btsizer.Add(self.editBtn, 0, wx.EXPAND) btsizer.Add(self.deleteBtn, 0, wx.EXPAND) btsizer.Add(self.okBtn, 0, wx.EXPAND) - sizer = wx.GridBagSizer(5,5) - sizer.Add(self.grid, (0,0), flag=wx.EXPAND) sizer.Add(btsizer, (0,1), flag=wx.EXPAND) - sizer.AddGrowableCol(0) sizer.AddGrowableRow(0) sizer.SetEmptyCellSize((0,0)) - self.panel.SetSizer(sizer) self.panel.SetAutoLayout(True) @@ -886,7 +772,6 @@ for rule in self.filterList: i = self.grid.InsertStringItem(self.grid.GetItemCount(), rule[0]) self.grid.SetStringItem(i, 1, rule[1]) - self.grid.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.grid.SetColumnWidth(1, wx.LIST_AUTOSIZE) @@ -895,7 +780,6 @@ self.Freeze() for i in xrange(0, self.grid.GetItemCount()): self.grid.SetItemBackgroundColour(i, (255,255,255)) - self.grid.SetItemBackgroundColour(self.currentIdx, (0,255,0)) self.grid.SetItemState(self.currentIdx, 0, wx.LIST_STATE_SELECTED) self.grid.EnsureVisible(self.currentIdx) @@ -912,24 +796,19 @@ sizer.Add(withtxt, 0, wx.EXPAND) sizer.Add(wx.Button(dlg, wx.ID_OK, 'Ok'), 0, wx.EXPAND) sizer.Add(wx.Button(dlg, wx.ID_CANCEL, 'Cancel'), 0, wx.EXPAND) - dlg.SetSizer(sizer) dlg.SetAutoLayout(True) dlg.Fit() - rpltxt.SetValue(self.grid.GetItem(self.currentIdx, 0).GetText()) withtxt.SetValue(self.grid.GetItem(self.currentIdx, 1).GetText()) - if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return - self.grid.SetStringItem(self.currentIdx, 0, rpltxt.GetValue()) self.grid.SetStringItem(self.currentIdx, 1, withtxt.GetValue()) self.grid.RefreshItem(self.currentIdx) self.grid.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.grid.SetColumnWidth(1, wx.LIST_AUTOSIZE) - dlg.Destroy() def RuleAdd(self, event): @@ -944,11 +823,9 @@ def OnExit(self, event): self.MakeModal(False) - list = [] for i in xrange(0, self.grid.GetItemCount()): list.append([self.grid.GetItem(i, 0).GetText(), self.grid.GetItem(i, 1).GetText()]) - self.parent.filterRegEx = list event.Skip()
--- a/orpg/tools/orpg_log.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/orpg_log.py Thu Aug 27 01:04:43 2009 -0500 @@ -26,38 +26,168 @@ # Description: classes for orpg log messages # -from orpg.orpgCore import * +from __future__ import with_statement +import sys, os, os.path, wx, time, traceback + +from orpg.orpgCore import component +from orpg.external.terminalwriter import TerminalWriter +from orpg.tools.decorators import pending_deprecation +from orpg.dirpath import dir_struct -class orpgLog: - def __init__(self, home_dir, filename='orpgRunLog '): - self.logToConsol = True - self.logLevel = 7 - self.logName = home_dir + filename + time.strftime( '%m-%d-%Y.txt', time.localtime( time.time() ) ) +######################### +## Error Types +######################### +ORPG_CRITICAL = 1 +ORPG_GENERAL = 2 +ORPG_INFO = 4 +ORPG_NOTE = 8 +ORPG_DEBUG = 16 + +def Crash(type, value, crash): + crash_report = open(dir_struct["home"] + 'crash-report.txt', "w") + traceback.print_exception(type, value, crash, file=crash_report) + crash_report.close() + msg = '' + crash_report = open(dir_struct["home"] + 'crash-report.txt', "r") + for line in crash_report: msg += line + logger.exception(msg) + crash_report.close() + logger.exception("Crash Report Created!!") + logger.info("Printed out crash-report.txt in your System folder", True) + wx.MessageBox('Crash Report Created!', 'System Failure') - def log(self, msg, type, to_consol=False): - if self.logToConsol or to_consol or type == ORPG_CRITICAL: - print msg +class DebugConsole(wx.Frame): + def __init__(self, parent): + super(DebugConsole, self).__init__(parent, -1, "Debug Window") + icon = None + icon = wx.Icon(dir_struct["icon"]+'note.ico', wx.BITMAP_TYPE_ICO) + self.SetIcon( icon ) + self.console = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE | wx.TE_READONLY) + sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(self.console, 1, wx.EXPAND) + self.SetSizer(sizer) + self.SetAutoLayout(True) + self.SetSize((300, 175)) + self.Bind(wx.EVT_CLOSE, self.Min) + self.Min(None) + component.add('debugger', self.console) + + def Min(self, evt): + self.Hide() - if type & self.logLevel or to_consol: - logMsg = time.strftime( '[%x %X] ', time.localtime( time.time() ) ) + msg + "\n" - logFile = open(self.logName, "a") - logFile.write(logMsg) - logFile.close() +class orpgLog(object): + _log_level = 7 + _log_name = None + _log_to_console = False + _io = TerminalWriter(sys.stderr) + _lvl_args = None + + def __new__(cls, *args, **kwargs): + it = cls.__dict__.get("__it__") + if it is not None: + return it + cls.__it__ = it = object.__new__(cls) + return it + + def __init__(self, home_dir, filename='orpgRunLog '): + self._lvl_args = {16: {'colorizer': {'green': True}, + 'log_string': 'DEBUG'}, + 8: {'colorizer': {'bold': True, 'green':True}, + 'log_string':'NOTE'}, + 4: {'colorizer': {'blue': True}, + 'log_string': 'INFO'}, + 2: {'colorizer': {'red': True}, + 'log_string': 'ERROR'}, + 1: {'colorizer': {'bold': True, 'red': True}, + 'log_string': 'EXCEPTION'}} + if not self.log_name: + self.log_name = home_dir + filename + time.strftime('%m-%d-%Y.txt', + time.localtime(time.time())) + + def debug(self, msg, to_console=False): + self.log(msg, ORPG_DEBUG, to_console) + def note(self, msg, to_console=False): + self.log(msg, ORPG_NOTE, to_console) + + def info(self, msg, to_console=False): + self.log(msg, ORPG_INFO, to_console) + + def general(self, msg, to_console=False): + self.log(msg, ORPG_GENERAL, to_console) + + def exception(self, msg, to_console=True): + self.log(msg, ORPG_CRITICAL, to_console) + + def log(self, msg, log_type, to_console=False): + if self.log_to_console or to_console or log_type == ORPG_CRITICAL: + try: self._io.line(str(msg), **self._lvl_args[log_type]['colorizer']) + except: pass #Fails without the Debug Console + try: component.get('debugger').AppendText(".. " + str(msg) +'\n') + except: pass + + if log_type & self.log_level or to_console: + atr = {'msg': msg, 'level': self._lvl_args[log_type]['log_string']} + atr['time'] = time.strftime('[%x %X]', time.localtime(time.time())) + logMsg = '%(time)s (%(level)s) - %(msg)s\n' % (atr) + + with open(self.log_name, 'a') as f: + f.write(logMsg) + + @pending_deprecation("use logger.log_level = #") def setLogLevel(self, log_level): - self.logLevel = log_level + self.log_level = log_level + @pending_deprecation("use logger.log_level") def getLogLevel(self): - return self.logLevel + return self.log_level + @pending_deprecation("use logger.log_name = bla") def setLogName(self, log_name): - self.logName = log_name + self.log_name = log_name + @pending_deprecation("use logger.log_name") def getLogName(self): - return self.logName + return self.log_name + + @pending_deprecation("use logger.log_to_console = True/False") + def setLogToConsol(self, true_or_false): + self.log_to_consol = true_or_false + + @pending_deprecation("use logger.log_to_console") + def getLogToConsol(self): + return self.log_to_consol + + """ + Property Methods + """ + def _get_log_level(self): + return self._log_level + def _set_log_level(self, log_level): + if not isinstance(log_level, int) or log_level < 1 or log_level > 31: + raise TypeError("The loggers level must be an int between 1 and 31") + + self._log_level = log_level - def setLogToConsol(self, bool): - self.logToConsol = bool + def _get_log_name(self): + return self._log_name + def _set_log_name(self, name): + if not os.access(os.path.abspath(os.path.dirname(name)), os.W_OK): + raise IOError("Could not write to the specified location") + + self._log_name = name - def getLogToConsol(self): - return self.logToConsol + def _get_log_to_console(self): + return self._log_to_console + def _set_log_to_console(self, true_or_false): + if not isinstance(true_or_false, bool): + raise TypeError("log_to_console must be a boolean value") + + self._log_to_console = true_or_false + + log_level = property(_get_log_level, _set_log_level) + log_name = property(_get_log_name, _set_log_name) + log_to_console = property(_get_log_to_console, _set_log_to_console) + +logger = orpgLog(dir_struct.get("user") + "runlogs/") +crash = sys.excepthook = Crash
--- a/orpg/tools/orpg_settings.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/orpg_settings.py Thu Aug 27 01:04:43 2009 -0500 @@ -27,29 +27,33 @@ # from orpg.orpg_windows import * -import orpg.dirpath +from orpg.orpgCore import component +from orpg.dirpath import dir_struct from rgbhex import * import sys import os +from orpg.orpg_xml import xml class orpgSettings: def __init__(self): - self.validate = open_rpg.get_component("validate") - self.xml = open_rpg.get_component("xml") - self.log = open_rpg.get_component("log") + self.validate = component.get("validate") + component.add('xml', xml) + self.xml = component.get("xml") + self.orpgLog = component.get("log") self.changes = [] self.validate.config_file("settings.xml","default_settings.xml") - self.filename = orpg.dirpath.dir_struct["user"] + "settings.xml" + self.filename = dir_struct["user"] + "settings.xml" temp_file = open(self.filename) txt = temp_file.read() temp_file.close() + self.xml_dom = self.xml.parseXml(txt) if self.xml_dom is None: self.rebuildSettings() self.xml_dom = self.xml_dom._get_documentElement() def rebuildSettings(self): - self.log.log("Settings file has be corrupted, rebuilding settings.", ORPG_INFO, True) + self.orpgLog.log("Settings file has be corrupted, rebuilding settings.", ORPG_INFO, True) try: os.remove(self.filename) except: pass @@ -78,7 +82,8 @@ def add_setting(self, tab, setting, value, options, help): if len(self.xml_dom.getElementsByTagName(setting)) > 0: return False tabs = self.xml_dom.getElementsByTagName("tab") - newsetting = self.xml.parseXml('<' + setting + ' value="' + value + '" options="' + options + '" help="' + help + '" />')._get_documentElement() + newsetting = self.xml.parseXml('<' + setting + ' value="' + value + '" options="' + + options + '" help="' + help + '" />')._get_documentElement() for i in xrange(0, len(tabs)): if tabs[i].getAttribute("name") == tab and tabs[i].getAttribute("type") == 'grid': tabs[i].appendChild(newsetting) @@ -125,7 +130,9 @@ if child._get_tagName() == 'tab' and child.hasChildNodes(): self.proccessChildren(child, dom.getAttribute("name")) else: - self.add_setting(dom.getAttribute("name"), child._get_tagName(), child.getAttribute("value"), child.getAttribute("options"), child.getAttribute("help")) + self.add_setting(dom.getAttribute("name"), child._get_tagName(), + child.getAttribute("value"), child.getAttribute("options"), + child.getAttribute("help")) def save(self): temp_file = open(self.filename, "w") @@ -134,11 +141,13 @@ class orpgSettingsWnd(wx.Dialog): def __init__(self, parent): - wx.Dialog.__init__(self,parent,-1,"OpenRPG Preferences",wx.DefaultPosition,size = wx.Size(-1,-1), style=wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION) + wx.Dialog.__init__(self,parent,-1,"OpenRPG Preferences", + wx.DefaultPosition,size = wx.Size(-1,-1), + style=wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION) self.Freeze() - self.validate = open_rpg.get_component("validate") - self.settings = open_rpg.get_component("settings") - self.chat = open_rpg.get_component("chat") + self.validate = component.get("validate") + self.settings = component.get("settings") + self.chat = component.get("chat") self.changes = [] self.SetMinSize((545,500)) self.tabber = orpgTabberWnd(self, style=FNB.FNB_NO_X_BUTTON) @@ -164,7 +173,7 @@ def build_gui(self): self.validate.config_file("settings.xml","default_settings.xml") - filename = open_rpg.get_component("dir_struct")["user"] + "settings.xml" + filename = dir_struct["user"] + "settings.xml" temp_file = open(filename) temp_file.close() children = self.settings.xml_dom._get_childNodes() @@ -210,8 +219,8 @@ def onOk(self, evt): #This will write the settings back to the XML - self.session = open_rpg.get_component("session") - tabbedwindows = open_rpg.get_component("tabbedWindows") + self.session = component.get("session") + tabbedwindows = component.get("tabbedWindows") new = [] for wnd in tabbedwindows: try: @@ -219,12 +228,20 @@ new.append(wnd) except: pass tabbedwindows = new - open_rpg.add_component("tabbedWindows", tabbedwindows) + component.add("tabbedWindows", tabbedwindows) rgbconvert = RGBHex() for i in xrange(0,len(self.changes)): self.settings.set_setting(self.changes[i][0], self.changes[i][1]) - top_frame = open_rpg.get_component('frame') + top_frame = component.get('frame') + + if self.changes[i][0] == 'defaultfontsize' or self.changes[i][0] == 'defaultfont': + self.chat.chatwnd.SetDefaultFontAndSize(self.settings.get_setting('defaultfont'), + self.settings.get_setting('defaultfontsize')) + self.chat.InfoPost("Font is now " + + self.settings.get_setting('defaultfont') + " point size " + + self.settings.get_setting('defaultfontsize')) + self.chat.chatwnd.scroll_down() if self.changes[i][0] == 'bgcolor' or self.changes[i][0] == 'textcolor': self.chat.chatwnd.SetPage(self.chat.ResetPage()) @@ -372,3 +389,6 @@ col_w = w/(cols) for i in range(0,cols): self.SetColSize(i,col_w) self.Refresh() + +settings = orpgSettings() +component.add('settings', settings)
--- a/orpg/tools/orpg_sound.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/orpg_sound.py Thu Aug 27 01:04:43 2009 -0500 @@ -7,8 +7,8 @@ wx.Panel.__init__(self, parent, -1) self.parent = parent - self.log = open_rpg.get_component("log") - self.settings = open_rpg.get_component('settings') + self.log = component.get("log") + self.settings = component.get('settings') self.log.log("Enter orpgSound", ORPG_DEBUG)
--- a/orpg/tools/passtool.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/passtool.py Thu Aug 27 01:04:43 2009 -0500 @@ -27,8 +27,9 @@ # doesn't have to type passwords over and over import orpg.orpg_windows -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component import traceback +#from orpg.tools.settings import settings ##################### ## Password Assistant @@ -42,19 +43,15 @@ #room password self.room = None - - class PassTool: "Password Management System" def __init__(self): - self.settings = open_rpg.get_component("settings") + self.settings = component.get("settings") #server admin password self.server = None self.groups = {} - if self.settings.get_setting('PWMannager') == 'On': - self.enabled = 1 - else: - self.enabled = 0 + if self.settings.get_setting('PWMannager') == 'On': self.enabled = 1 + else: self.enabled = 0 def DumpPasswords(self): @@ -179,3 +176,6 @@ elif type == "server": self.ClearPassword( type, groupid ) return self.ServerPass() + +#PassTool = PassTool() +component.add('password_manager', PassTool())
--- a/orpg/tools/pluginui.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/pluginui.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,9 +1,9 @@ from orpg.orpg_wx import * from orpg.orpgCore import * import orpg.plugindb as plugindb -import orpg.dirpath +from orpg.dirpath import dir_struct -sys.path.append(orpg.dirpath.dir_struct["plugins"]) +sys.path.append(dir_struct["plugins"]) class PluginFrame(wx.Frame): def __init__(self, parent): @@ -278,7 +278,7 @@ self.pluginList.DeleteAllItems() self.pluginNames = [] - list_of_plugin_dir = os.listdir(orpg.dirpath.dir_struct["plugins"]) + list_of_plugin_dir = os.listdir(dir_struct["plugins"]) for p in list_of_plugin_dir: #print p[:2]; print p[-4:] if p[:2].lower()=="xx" and p[-3:]==".py":
--- a/orpg/tools/scriptkit.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/scriptkit.py Thu Aug 27 01:04:43 2009 -0500 @@ -41,11 +41,11 @@ <li>openrpg - a reference to the application openrpg object. </ul> """ - self.chat = open_rpg.get_component( 'chat' ) - self.map = open_rpg.get_component( 'map' ) - self.settings = open_rpg.get_component( 'settings' ) - self.session = open_rpg.get_component('session') - self.xml = open_rpg.get_component('xml') + self.chat = component.get( 'chat' ) + self.map = component.get( 'map' ) + self.settings = component.get( 'settings' ) + self.session = component.get('session') + self.xml = component.get('xml') def addMiniatureToMap( self, min_label, min_url, unique=0 ): """Adds a new miniature icon to the map. Miniature <em>will</em> be labeled unless autolabel is
--- a/orpg/tools/toolBars.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/toolBars.py Thu Aug 27 01:04:43 2009 -0500 @@ -33,7 +33,7 @@ ## from inputValidator import * import string -import orpg.dirpath +from orpg.dirpath import dir_struct # DICE stuff TB_IDC_D4 = wx.NewId() @@ -56,12 +56,12 @@ wx.Panel.__init__(self, parent, id, size=size) self.callback = callBack self.mapmode = 1 - self.modeicons = [orpg.dirpath.dir_struct["icon"]+"move.gif", - orpg.dirpath.dir_struct["icon"]+"draw.gif", - orpg.dirpath.dir_struct["icon"]+"tape.gif"] + self.modeicons = [dir_struct["icon"]+"move.gif", + dir_struct["icon"]+"draw.gif", + dir_struct["icon"]+"tape.gif"] # Make a sizer for everything to belong to self.sizer = wx.BoxSizer( wx.HORIZONTAL ) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"move.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"move.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() self.butt = wx.BitmapButton( self, TB_MAP_MODE, bm ) self.sizer.Add( self.butt,0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_MAP_MODE) @@ -98,31 +98,31 @@ self.numDieText = wx.TextCtrl( self, TB_IDC_NUMDICE, "1", size= wx.Size(50, 25), validator=MathOnlyValidator() ) self.sizer.Add( self.numDieText, 1, wx.EXPAND | wx.ALIGN_LEFT ) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d4.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d4.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D4, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D4) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d6.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d6.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D6, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D6) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d8.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d8.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D8, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D8) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d10.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d10.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D10, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D10) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d12.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d12.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D12, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D12) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d20.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d20.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D20, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D20) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d100.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + bm = wx.Image(dir_struct["icon"]+"b_d100.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() butt = wx.BitmapButton( self, TB_IDC_D100, bm, size=(bm.GetWidth(), bm.GetHeight()) ) self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D100)
--- a/orpg/tools/validate.py Thu Aug 13 13:14:10 2009 -0500 +++ b/orpg/tools/validate.py Thu Aug 27 01:04:43 2009 -0500 @@ -6,23 +6,24 @@ # Misc. config file service methods # -import orpg.dirpath +from orpg.dirpath import dir_struct import os +from orpg.orpgCore import component class Validate: def __init__(self, userpath=None): if userpath is None: - userpath = orpg.dirpath.dir_struct["user"] + userpath = dir_struct["user"] self.__loadUserPath = userpath def config_file(self, user_file, template_file): #STEP 1: verify the template exists - if (not os.path.exists(orpg.dirpath.dir_struct["template"] + template_file)): + if (not os.path.exists(dir_struct["template"] + template_file)): return 0 #STEP 2: verify the user file exists. If it doesn't then create it from template if (not os.path.exists(self.__loadUserPath + user_file)): - default = open(orpg.dirpath.dir_struct["template"] + template_file,"r") + default = open(dir_struct["template"] + template_file,"r") file = default.read() newfile = open(self.__loadUserPath + user_file,"w") newfile.write(file) @@ -35,3 +36,6 @@ def ini_entry(self, entry_name, ini_file): pass + +validate = Validate() +component.add('validate', Validate())
--- a/plugins/xxchatnotify.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxchatnotify.py Thu Aug 27 01:04:43 2009 -0500 @@ -34,10 +34,10 @@ self.topframe.Bind(wx.EVT_MENU, self.on_settings, self.notifyAll) self.topframe.Bind(wx.EVT_MENU, self.on_settings, self.notifyWhisper) - def on_settings(self, evt): if self.notifyToggle.IsChecked() == False: self.notify = 'Off' + self.plugindb.SetString('xxchatnotify', 'notify', self.notify) return if self.notifyBeep.IsChecked() == True: self.notify ='beep' @@ -49,14 +49,16 @@ self.type = 'all' elif self.notifyWhisper.IsChecked() == True: self.type = 'whisper' + self.plugindb.SetString('xxchatnotify', 'notify', self.notify) + self.plugindb.SetString('xxchatnotify', 'type', self.type) def plugin_enabled(self): self.plugin_addcommand('/notify', self.on_notify, 'beep | flash | both | off | type all|whisper | clearsound | lsound soundfile [Local Sound Files only] | rsound http://to.sound.file [Remote Sound Files only] - This command turns on the chat notification. You can use sound files and flash by issuing /notify both') - self.notify = self.plugindb.GetString('xxchatnotify', 'notify', 'off') - self.type = self.plugindb.GetString('xxchatnotify', 'type', 'all') - self.mainframe = open_rpg.get_component('frame') - self.sound_player = open_rpg.get_component('sound') + self.notify = self.plugindb.GetString('xxchatnotify', 'notify', string) or 'off' + self.type = self.plugindb.GetString('xxchatnotify', 'type', string) or 'beep' + self.mainframe = component.get('frame') + self.sound_player = component.get('sound') self.soundloc = self.plugindb.GetString('xxchatnotify', 'soundloc', 'local') self.soundfile = self.plugindb.GetString('xxchatnotify', 'soundfile', 'None') self.chat_settings()
--- a/plugins/xxcherrypy.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxcherrypy.py Thu Aug 27 01:04:43 2009 -0500 @@ -55,7 +55,7 @@ del cherry_start self.cherryhost = 'http://' + self.host + ':' + str(self.port) + '/webfiles/' - open_rpg.add_component("cherrypy", self.cherryhost) + component.add("cherrypy", self.cherryhost) def plugin_disabled(self): #Here you need to remove any commands you added, and anything else you want to happen when you disable the plugin @@ -66,7 +66,7 @@ self.isServerRunning = 'off' else: pass - open_rpg.del_component("cherrypy") + component.delete("cherrypy") def on_cherrypy(self, cmdargs): args = cmdargs.split(None,-1) @@ -96,7 +96,7 @@ self.plugindb.SetString("xxcherrypy", "port", str(self.port)) # TAS self.chat.InfoPost("CherryPy Web Server is currently: " + self.isServerRunning) self.cherryhost = 'http://' + self.host + ':' + str(self.port) + '/webfiles/' - open_rpg.del_component("cherrypy"); open_rpg.add_component("cherrypy", self.cherryhost) + component.delete("cherrypy"); component.add("cherrypy", self.cherryhost) self.chat.InfoPost('CherryPy Web Server address is: ' + self.cherryhost) def startServer(self, port):
--- a/plugins/xxgvm.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxgvm.py Thu Aug 27 01:04:43 2009 -0500 @@ -192,4 +192,4 @@ if len(keychain)==0: return "No variables!" else: - return lister \ No newline at end of file + return lister
--- a/plugins/xxheroinit.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxheroinit.py Thu Aug 27 01:04:43 2009 -0500 @@ -519,4 +519,4 @@ msg += " Example: heroinit (hact 1 full) : Make character index 1 perform a full action.<br>" msg += " Example: heroinit (hact full) : Have your first owned character perform a full action<br>" - self.chat.whisper_to_players(msg, [player[2]]) \ No newline at end of file + self.chat.whisper_to_players(msg, [player[2]])
--- a/plugins/xxhiddendice.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxhiddendice.py Thu Aug 27 01:04:43 2009 -0500 @@ -42,7 +42,6 @@ return text def post_msg(self, text, myself): - print "post_msg:\n\t" + text c = 0 a = text.find("(hidden roll)")
--- a/plugins/xxinit.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxinit.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,7 +1,7 @@ import os import orpg.pluginhandler from string import find, replace -import orpg.dirpath +from orpg.dirpath import dir_struct class Plugin(orpg.pluginhandler.PluginHandler): # Initialization subroutine. @@ -52,7 +52,7 @@ self.post_my_msg("<font color='#ff0000'>Init recording on</font>") self.toggle = 1 elif args[0] == 'help': - f = open(orpg.dirpath.dir_struct["plugins"]+ "inittool.xml","r") + f = open(dir_struct["plugins"]+ "inittool.xml","r") self.gametree.insert_xml(f.read()) f.close() elif args[0] == 'type':
--- a/plugins/xxinit2.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxinit2.py Thu Aug 27 01:04:43 2009 -0500 @@ -22,7 +22,7 @@ import wx import os -import orpg.dirpath +from orpg.dirpath import dir_struct import orpg.orpg_version import orpg.plugindb import orpg.pluginhandler @@ -300,8 +300,8 @@ ############################################################### def CMD_inittool2(self, cmdargs): - f = open(orpg.dirpath.dir_struct["plugins"]+ "inittool2.xml","r") - f2 = open(orpg.dirpath.dir_struct["plugins"]+ "inittool2_player.xml","r") + f = open(dir_struct["plugins"]+ "inittool2.xml","r") + f2 = open(dir_struct["plugins"]+ "inittool2_player.xml","r") self.gametree.insert_xml(f.read()) self.gametree.insert_xml(f2.read()) f.close()
--- a/plugins/xxnamesound.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxnamesound.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,9 +1,9 @@ import os import orpg.pluginhandler -import orpg.dirpath +from orpg.dirpath import dir_struct import re import string -from orpg.orpgCore import open_rpg +from orpg.orpgCore import component class Plugin(orpg.pluginhandler.PluginHandler): # Initialization subroutine. @@ -39,13 +39,13 @@ self.names = self.plugindb.GetList("xxnamesound", "names", []) - self.soundplayer = self.sound_player = open_rpg.get_component('sound') + self.soundplayer = self.sound_player = component.get('sound') tmp = self.plugindb.GetString('xxnamesound', 'wnotify', str(self.notify)) if tmp == 'True': self.on_wnotify(None) - self.soundfile = self.plugindb.GetString('xxnamesound', 'soundfile', orpg.dirpath.dir_struct['plugins'] + 'heya.wav') + self.soundfile = self.plugindb.GetString('xxnamesound', 'soundfile', dir_struct['plugins'] + 'heya.wav') reg = []
--- a/plugins/xxnote.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxnote.py Thu Aug 27 01:04:43 2009 -0500 @@ -177,4 +177,4 @@ self.chat.InfoPost('/listnotes ' + self.cmdlist['/listnotes']['help']) self.chat.InfoPost('/clearnotes ' + self.cmdlist['/clearnotes']['help']) self.chat.InfoPost('/notetonode ' + self.cmdlist['/notetonode']['help']) - self.chat.InfoPost('/viewnote ' + self.cmdlist['/viewnote']['help']) \ No newline at end of file + self.chat.InfoPost('/viewnote ' + self.cmdlist['/viewnote']['help'])
--- a/plugins/xxquotebox.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxquotebox.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,5 +1,5 @@ import os -import orpg.dirpath +from orpg.dirpath import dir_struct import orpg.plugindb import orpg.pluginhandler from orpg.tools.rgbhex import RGBHex @@ -236,7 +236,7 @@ # loads up quotebox.xml as a node in the gametree def on_quotebox(self, cmdargs): - f = open(orpg.dirpath.dir_struct["plugins"]+ "quotebox.xml","r") + f = open(dir_struct["plugins"]+ "quotebox.xml","r") self.gametree.insert_xml(f.read()) f.close() return 1
--- a/plugins/xxsimpleinit.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxsimpleinit.py Thu Aug 27 01:04:43 2009 -0500 @@ -10,12 +10,12 @@ # !openrpg : instance of the the base openrpg control def __init__(self, plugindb, parent): orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) - self.orpgframe = open_rpg.get_component('frame') + self.orpgframe = component.get('frame') # The Following code should be edited to contain the proper information self.name = 'Simple Init' - self.author = 'Dj Gilcrease' - self.help = 'This is a simplistic Init tool that does not relie on Chat message parsing' + self.author = 'Dj Gilcrease + Tyler Starke' + self.help = 'This is a simplistic Init tool that does not rely on Chat message parsing' #You can set variables below here. Always set them to a blank value in this section. Use plugin_enabled #to set their proper values. @@ -45,7 +45,6 @@ self.frame.Bind(wx.EVT_TIMER, self.buttonCheck, self.buttonTimer) self.buttonTimer.Start(250) self.autoAdvancePaused = False - #self.PluginMenu() def plugin_disabled(self): self.plugin_removecmd('/inittoggle') @@ -61,10 +60,8 @@ self.buttonTimer.Stop() del self.buttonTimer - try: - self.frame.Destroy() - except: - pass + try: self.frame.Destroy() + except: pass def on_init(self, cmdargs): if self.frame.IsShown(): @@ -73,7 +70,6 @@ else: self.toggle.Check(True) self.frame.Show() - print self.toggle.IsChecked() def startInit(self, evt=None): if self.frame.initList.GetItemCount() == 0: @@ -103,7 +99,7 @@ self.frame.currentInit = -1 self.round = 0 - self.chat.Post('<font color="#00ff00" size="4"><b>============ START COMBAT ============</b></font>', True, True) + self.chat.Post('<center><font color="#00ff00"><b>== START COMBAT ==</b></font></center>', True, True, c='simpleinit-combat') self.advanceInit() self.frame.Thaw() @@ -152,7 +148,7 @@ self.frame.Thaw() self.advanceTimer.Stop() - self.chat.Post('<font color="#ff0000" size="4"><b>============ END COMBAT ============</b></font>', True, True) + self.chat.Post('<center><font color="#ff0000" ><b>== END COMBAT ==</b></font></center>', True, True, c='simpleinit-combat') def advanceInit(self, evt=None): if not self.frame.nextButton.IsEnabled(): @@ -163,16 +159,16 @@ if self.frame.currentInit.type == 'Effect': newDur = str(int(self.frame.currentInit.duration)-1) self.frame.initList.SetStringItem(self.frame.initIdx, 2, newDur) - msg = '<br><table width="100%" border="1"><tr><td align="center"><center><u><b><font color="#ff0000" size="4">EFFECT NOTICE</font></b></u></center></td></tr>' - msg += '<tr><td align="center"><font color="#000000">' + self.frame.currentInit.name + ' has ' + newDur + ' rounds remaining</font></td></tr></table>' - self.chat.Post(msg, True, True) + msg = '<br><table width="100%" border="1"><tr><td align="center"><center><u><b><font color="#ff0000" >EFFECT NOTICE</font></b></u></center></td></tr>' + msg += '<tr><td align="center"><font color="#000000">' + self.frame.currentInit.name + ' has ' + newDur + ' rounds remaining</font></td></tr></table><br />' + self.chat.Post(msg, True, True, c='simpleinit-effect') wx.CallAfter(self.advanceInit) else: - msg = '<br><table width="100%" border="1"><tr><td align="center"><center><u><font color="#ff0000" size="4"><b>' + self.frame.nextMessage.GetValue() + '</b></font></u></center></td></tr>' - msg += '<tr><td align="center"><b><font size="3"><font color="#ff0000">' + str(self.frame.initIdx+1) + ':</font> ' + msg = '<table width="100%" border="1"><tr><td align="center"><u><font color="#ff0000" ><b>' + self.frame.nextMessage.GetValue() + '</b></font></u></td></tr>' + msg += '<tr><td align="center"><b><font color="#ff0000">' + str(self.frame.initIdx+1) + ':</font> ' msg += '<font color="#0000ff">(' + self.frame.currentInit.init + ')</font> ' - msg += '<font color="#000000">' + self.frame.currentInit.name + '</b></font></font></td></tr></table>' - self.chat.Post(msg, True, True) + msg += '<font color="#000000">' + self.frame.currentInit.name + '</b></font></td></tr></table><br />' + self.chat.Post(msg, True, True, c='simpleinit-pc') if self.frame.currentInit.type == 'Effect' and int(self.frame.currentInit.duration) <= 0: self.frame.Freeze() @@ -205,7 +201,7 @@ def newRound(self): self.round += 1 - msg = '<br><hr><font color="#ff0000" size="4"><b>End of Round #' + str(self.round-1) + ', Starting Round #' + str(self.round) + '</b></font><hr>' + msg = '<br><hr><font color="#ff0000" ><b>End of Round #' + str(self.round-1) + ', Starting Round #' + str(self.round) + '</b></font><hr>' self.chat.Post(msg, True, True) def rollD20Init(self): @@ -214,7 +210,7 @@ return self.orpgframe.Freeze() self.frame.Freeze() - msg = '<br><font color="#0000ff" size="4"><b>============ START INIT LIST ============</b></font><br>' + msg = '<br><center><font color="#0000ff" ><b>== START INIT LIST ==</b></font></center><br>' msg += '<font color="#000000"><b>' for i in xrange(0, self.frame.initList.GetItemCount()): self.frame.currentInit = i @@ -234,8 +230,8 @@ msg += '</b></font><br>' self.frame.initList.SortItems(self.frame.initSort) - msg += '<font color="#0000ff" size="4"><b>============ END INIT LIST ============</b></font>' - self.chat.Post(msg, True, True) + msg += '<center><font color="#0000ff" ><b>== END INIT LIST ==</b></center></font>' + self.chat.Post(msg, True, True, c='simpleinit-lst') self.frame.Thaw() if self.frame.IsShown(): @@ -248,8 +244,6 @@ self.rollD20Init() def buttonCheck(self, evt): - if self.autoAdvancePaused: - return if self.frame.initList.GetItemCount() == 0: self.frame.Freeze() self.advanceTimer.Stop() @@ -269,6 +263,8 @@ self.frame.deleteButton.Enable() self.frame.saveButton.Enable() self.frame.clearButton.Enable() + if self.autoAdvancePaused: + return if not self.frame.autoAdvanceCheck.IsChecked(): self.frame.autoAdvanceToggle.Disable() @@ -280,16 +276,16 @@ def __init__(self, plugin): self.plugin = plugin self.toggle = plugin.toggle - self.log = open_rpg.get_component('log') + self.log = component.get('log') self.log.log("Enter InitFrame", ORPG_DEBUG) wx.Frame.__init__(self, None, wx.ID_ANY, title="Simple Init", style=wx.DEFAULT_FRAME_STYLE) self.SetOwnBackgroundColour('#EFEFEF') - self.dir_struct = open_rpg.get_component('dir_struct') - self.settings = open_rpg.get_component('settings') - self.xml = open_rpg.get_component('xml') - self.validate = open_rpg.get_component('validate') + self.dir_struct = component.get('dir_struct') + self.settings = component.get('settings') + self.xml = component.get('xml') + self.validate = component.get('validate') self.Freeze() self.buildMenu() @@ -302,10 +298,10 @@ self.log.log("Exit InitFrame", ORPG_DEBUG) def InitSetup(self): - self.chat = open_rpg.get_component('chat') - self.gametree = open_rpg.get_component('tree') - self.map = open_rpg.get_component('map') - self.session = open_rpg.get_component('session') + self.chat = component.get('chat') + self.gametree = component.get('tree') + self.map = component.get('map') + self.session = component.get('session') self.initIdx = -1 self.Thaw()
--- a/plugins/xxsmiley.py Thu Aug 13 13:14:10 2009 -0500 +++ b/plugins/xxsmiley.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,6 +1,6 @@ import os import orpg.pluginhandler -import orpg.dirpath +from orpg.dirpath import dir_struct class Plugin(orpg.pluginhandler.PluginHandler): # Initialization subroutine. @@ -25,86 +25,86 @@ self.plugin_addcommand('/smiley', self.on_smiley, '- [add|remove|help] The Smiley command') smlist = { - '>:-(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley7.gif" /> ', - ':/' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley5.gif" /> ', - ':|' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley6.gif" /> ', - ':(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley9.gif" /> ', - ' />:(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley7.gif" /> ', - ' />=(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley7.gif" /> ', - '=)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley0.gif" /> ', - '=D' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley1.gif" /> ', - ';)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley3.gif" /> ', - '=/' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley5.gif" /> ', - '=|' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley6.gif" /> ', - '=(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley9.gif" /> ', - ':)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley0.gif" /> ', - ':D' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley1.gif" /> ', - 'B)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley2.gif" /> ', - ':p' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley4.gif" /> ', - '=\\' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley5.gif" /> ', - ':P' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley4.gif" /> ', - '=P' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley4.gif" /> ', - '^_^' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - '^-^' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - '^.^' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - 'n_n' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - 'n.n' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - 'n,n' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley12.gif" /> ', - 'I-)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley13.gif" /> ', - 'n.n;' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley14.gif" /> ', - 'n.n;;' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley14.gif" /> ', - 'n_n;' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley14.gif" /> ', - ':-)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley0.gif" /> ', - ':-D' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley1.gif" /> ', - ':-P' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley2.gif" /> ', - ':-p' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley4.gif" /> ', - ':-/' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley5.gif" /> ', - ':-|' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley6.gif" /> ', - ':-(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley9.gif" /> ', - ':-\\' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/smiley5.gif" /> ', - '-)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_smile.gif" /> ', - ';-)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_wink.gif" /> ', - ':->' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_smile2.gif" /> ', - ':-D' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_biggrin.gif" /> ', - ':-P' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_razz.gif" /> ', - ':-o' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_surprised.gif" /> ', - ':mrgreen:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_mrgreen.gif" /> ', - ':lol:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_lol.gif" /> ', - ':-(' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_sad.gif" /> ', - ':-|' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_neutral.gif" /> ', - ':-?' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_confused.gif" /> ', - ':-x' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_mad.gif" /> ', - ':shock:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_eek.gif" /> ', - ':cry:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_cry.gif" /> ', - ';_;' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_cry.gif" /> ', - ':oops:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_redface.gif" /> ', - '8-)' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_cool.gif" /> ', - ':evil:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_evil.gif" /> ', - ':twisted:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_twisted.gif" /> ', - ':roll:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_rolleyes.gif" /> ', - ':!:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_exclaim.gif" /> ', - ':?:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_question.gif" /> ', - ':idea:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_idea.gif" /> ', - ':arrow:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_arrow.gif" /> ', - ':ubergeek:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_e_ugeek.gif" /> ', - ':geek:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/icon_e_geek.gif" /> ', - ':fairy:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/fairy.gif" /> ', - ':hood:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/hood.gif" /> ', - ':gnome:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/gnome.gif" /> ', - ':link:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/link.gif" /> ', - ':mummy:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/mummy.gif" /> ', - ':ogre:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/ogre.gif" /> ', - ':medusa:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/medusa.gif" /> ', - ':mimic:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/mimic.gif" /> ', - ':skull:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/skull.gif" /> ', - ':zombie:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/zombie.gif" /> ', - ':chocobo:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/chocobo.gif" /> ', - ':darkside:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/darkside.gif" /> ', - ':flyingspaghetti:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/flyingspaghetti.gif" /> ', - ':rupee:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/rupee.gif" /> ', - ':ros:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/ros.gif" /> ', - ':skeleton:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/skeleton.gif" /> ', - ':samurai:' : ' <img src="' + orpg.dirpath.dir_struct['plugins'] + 'images/samurai.gif" /> '} + '>:-(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley7.gif" /> ', + ':/' : ' <img src="' + dir_struct['plugins'] + 'images/smiley5.gif" /> ', + ':|' : ' <img src="' + dir_struct['plugins'] + 'images/smiley6.gif" /> ', + ':(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley9.gif" /> ', + ' />:(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley7.gif" /> ', + ' />=(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley7.gif" /> ', + '=)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley0.gif" /> ', + '=D' : ' <img src="' + dir_struct['plugins'] + 'images/smiley1.gif" /> ', + ';)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley3.gif" /> ', + '=/' : ' <img src="' + dir_struct['plugins'] + 'images/smiley5.gif" /> ', + '=|' : ' <img src="' + dir_struct['plugins'] + 'images/smiley6.gif" /> ', + '=(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley9.gif" /> ', + ':)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley0.gif" /> ', + ':D' : ' <img src="' + dir_struct['plugins'] + 'images/smiley1.gif" /> ', + 'B)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley2.gif" /> ', + ':p' : ' <img src="' + dir_struct['plugins'] + 'images/smiley4.gif" /> ', + '=\\' : ' <img src="' + dir_struct['plugins'] + 'images/smiley5.gif" /> ', + ':P' : ' <img src="' + dir_struct['plugins'] + 'images/smiley4.gif" /> ', + '=P' : ' <img src="' + dir_struct['plugins'] + 'images/smiley4.gif" /> ', + '^_^' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + '^-^' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + '^.^' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + 'n_n' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + 'n.n' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + 'n,n' : ' <img src="' + dir_struct['plugins'] + 'images/smiley12.gif" /> ', + 'I-)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley13.gif" /> ', + 'n.n;' : ' <img src="' + dir_struct['plugins'] + 'images/smiley14.gif" /> ', + 'n.n;;' : ' <img src="' + dir_struct['plugins'] + 'images/smiley14.gif" /> ', + 'n_n;' : ' <img src="' + dir_struct['plugins'] + 'images/smiley14.gif" /> ', + ':-)' : ' <img src="' + dir_struct['plugins'] + 'images/smiley0.gif" /> ', + ':-D' : ' <img src="' + dir_struct['plugins'] + 'images/smiley1.gif" /> ', + ':-P' : ' <img src="' + dir_struct['plugins'] + 'images/smiley2.gif" /> ', + ':-p' : ' <img src="' + dir_struct['plugins'] + 'images/smiley4.gif" /> ', + ':-/' : ' <img src="' + dir_struct['plugins'] + 'images/smiley5.gif" /> ', + ':-|' : ' <img src="' + dir_struct['plugins'] + 'images/smiley6.gif" /> ', + ':-(' : ' <img src="' + dir_struct['plugins'] + 'images/smiley9.gif" /> ', + ':-\\' : ' <img src="' + dir_struct['plugins'] + 'images/smiley5.gif" /> ', + '-)' : ' <img src="' + dir_struct['plugins'] + 'images/icon_smile.gif" /> ', + ';-)' : ' <img src="' + dir_struct['plugins'] + 'images/icon_wink.gif" /> ', + ':->' : ' <img src="' + dir_struct['plugins'] + 'images/icon_smile2.gif" /> ', + ':-D' : ' <img src="' + dir_struct['plugins'] + 'images/icon_biggrin.gif" /> ', + ':-P' : ' <img src="' + dir_struct['plugins'] + 'images/icon_razz.gif" /> ', + ':-o' : ' <img src="' + dir_struct['plugins'] + 'images/icon_surprised.gif" /> ', + ':mrgreen:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_mrgreen.gif" /> ', + ':lol:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_lol.gif" /> ', + ':-(' : ' <img src="' + dir_struct['plugins'] + 'images/icon_sad.gif" /> ', + ':-|' : ' <img src="' + dir_struct['plugins'] + 'images/icon_neutral.gif" /> ', + ':-?' : ' <img src="' + dir_struct['plugins'] + 'images/icon_confused.gif" /> ', + ':-x' : ' <img src="' + dir_struct['plugins'] + 'images/icon_mad.gif" /> ', + ':shock:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_eek.gif" /> ', + ':cry:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_cry.gif" /> ', + ';_;' : ' <img src="' + dir_struct['plugins'] + 'images/icon_cry.gif" /> ', + ':oops:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_redface.gif" /> ', + '8-)' : ' <img src="' + dir_struct['plugins'] + 'images/icon_cool.gif" /> ', + ':evil:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_evil.gif" /> ', + ':twisted:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_twisted.gif" /> ', + ':roll:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_rolleyes.gif" /> ', + ':!:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_exclaim.gif" /> ', + ':?:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_question.gif" /> ', + ':idea:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_idea.gif" /> ', + ':arrow:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_arrow.gif" /> ', + ':ubergeek:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_e_ugeek.gif" /> ', + ':geek:' : ' <img src="' + dir_struct['plugins'] + 'images/icon_e_geek.gif" /> ', + ':fairy:' : ' <img src="' + dir_struct['plugins'] + 'images/fairy.gif" /> ', + ':hood:' : ' <img src="' + dir_struct['plugins'] + 'images/hood.gif" /> ', + ':gnome:' : ' <img src="' + dir_struct['plugins'] + 'images/gnome.gif" /> ', + ':link:' : ' <img src="' + dir_struct['plugins'] + 'images/link.gif" /> ', + ':mummy:' : ' <img src="' + dir_struct['plugins'] + 'images/mummy.gif" /> ', + ':ogre:' : ' <img src="' + dir_struct['plugins'] + 'images/ogre.gif" /> ', + ':medusa:' : ' <img src="' + dir_struct['plugins'] + 'images/medusa.gif" /> ', + ':mimic:' : ' <img src="' + dir_struct['plugins'] + 'images/mimic.gif" /> ', + ':skull:' : ' <img src="' + dir_struct['plugins'] + 'images/skull.gif" /> ', + ':zombie:' : ' <img src="' + dir_struct['plugins'] + 'images/zombie.gif" /> ', + ':chocobo:' : ' <img src="' + dir_struct['plugins'] + 'images/chocobo.gif" /> ', + ':darkside:' : ' <img src="' + dir_struct['plugins'] + 'images/darkside.gif" /> ', + ':flyingspaghetti:' : ' <img src="' + dir_struct['plugins'] + 'images/flyingspaghetti.gif" /> ', + ':rupee:' : ' <img src="' + dir_struct['plugins'] + 'images/rupee.gif" /> ', + ':ros:' : ' <img src="' + dir_struct['plugins'] + 'images/ros.gif" /> ', + ':skeleton:' : ' <img src="' + dir_struct['plugins'] + 'images/skeleton.gif" /> ', + ':samurai:' : ' <img src="' + dir_struct['plugins'] + 'images/samurai.gif" /> '} self.smileylist = self.plugindb.GetDict("xxsmiley", "smileylist", smlist) @@ -132,7 +132,7 @@ if args[2].find('http') > -1: self.smileylist[args[1]] = ' <img src="' + args[2] + '" alt="' + args[1] + '" />' else: - self.smileylist[args[1]] = ' <img src="' + orpg.dirpath.dir_struct["plugins"] + 'images/' + args[2] + '" />' + "\n" + self.smileylist[args[1]] = ' <img src="' + dir_struct["plugins"] + 'images/' + args[2] + '" />' + "\n" self.chat.InfoPost('Added ' + args[1] + '    :    ' + self.smileylist[args[1]]) @@ -165,4 +165,4 @@ if myself: text = self.doSmiley(text) - return text \ No newline at end of file + return text
--- a/upmana/manifest.py Thu Aug 13 13:14:10 2009 -0500 +++ b/upmana/manifest.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,13 +1,13 @@ import xmltramp -import orpg.dirpath +from orpg.dirpath import dir_struct import upmana.validate from os import sep from types import * class ManifestChanges: def __init__(self, filename="updatemana.xml"): - self.filename = orpg.dirpath.dir_struct["home"] + 'upmana' + sep + filename - upmana.validate.Validate(orpg.dirpath.dir_struct["home"] + 'upmana' + sep).config_file(filename,"default_manifest.xml") + self.filename = dir_struct["home"] + 'upmana' + sep + filename + upmana.validate.Validate(dir_struct["home"] + 'upmana' + sep).config_file(filename,"default_manifest.xml") self.xml_dom = self.LoadDoc() def GetString(self, plugname, strname, defaultval, verbose=0):
--- a/upmana/updatemana.py Thu Aug 13 13:14:10 2009 -0500 +++ b/upmana/updatemana.py Thu Aug 27 01:04:43 2009 -0500 @@ -1,19 +1,21 @@ -import wx +import wx +import sys +import os #just .sep maybe import manifest -import orpg.dirpath -from orpg.orpgCore import * -import orpg.orpg_version -import orpg.tools.orpg_log -import orpg.orpg_xml -import orpg.dirpath -import upmana.validate -import tempfile import shutil + +from orpg.orpgCore import component +from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger, crash +from orpg.tools.decorators import debugging +from upmana.validate import validate +from orpg.dirpath import dir_struct from mercurial import ui, hg, commands, repo, revlog, cmdutil, util class Updater(wx.Panel): - def __init__(self, parent, open_rpg, manifest): + @debugging + def __init__(self, parent, component, manifest): wx.Panel.__init__(self, parent) ### Update Manager @@ -21,11 +23,7 @@ self.repo = hg.repository(self.ui, ".") self.c = self.repo.changectx('tip') self.manifest = manifest - self.xml = open_rpg.get_component('xml') - self.dir_struct = open_rpg.get_component("dir_struct") - self.parent = parent - self.log = open_rpg.get_component("log") - self.log.log("Enter updaterFrame", ORPG_DEBUG) + self.parent = parent self.SetBackgroundColour(wx.WHITE) self.sizer = wx.GridBagSizer(hgap=1, vgap=1) self.changelog = wx.TextCtrl(self, wx.ID_ANY, size=(325, -1), style=wx.TE_MULTILINE | wx.TE_READONLY) @@ -93,17 +91,17 @@ self.ui = ui.ui() self.repo = hg.repository(self.ui, ".") self.c = self.repo.changectx('tip') - filename = 'ignorelist.txt' - self.filename = orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + filename - upmana.validate.Validate(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep).config_file(filename, "default_ignorelist.txt") + self.filename = dir_struct["home"] + 'upmana' + os.sep + filename + component.get('validate').config_file(filename, "default_ignorelist.txt") self.mana = self.LoadDoc() + temp = dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep for ignore in self.ignorelist: - shutil.copy(ignore, orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep +ignore.split('/')[len(ignore.split('/')) - 1]) + shutil.copy(ignore, temp + ignore.split('/')[len(ignore.split('/')) - 1]) hg.clean(self.repo, self.current) for ignore in self.ignorelist: - shutil.copyfile(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep + ignore.split('/')[len(ignore.split('/')) - 1], ignore) - os.remove(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep + ignore.split('/')[len(ignore.split('/')) - 1]) + shutil.copyfile(temp + ignore.split('/')[len(ignore.split('/')) - 1], ignore) + os.remove(temp + ignore.split('/')[len(ignore.split('/')) - 1]) def LoadDoc(self): ignore = open(self.filename) @@ -119,8 +117,8 @@ def ChooseBranch(self, evt=None): dlg = wx.Dialog(self, wx.ID_ANY, "Package Selector", style=wx.DEFAULT_DIALOG_STYLE) - if wx.Platform == '__WXMSW__': icon = wx.Icon(self.dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) - else: icon = wx.Icon(self.dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM ) + if wx.Platform == '__WXMSW__': icon = wx.Icon(dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) + else: icon = wx.Icon(dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM ) dlg.SetIcon(icon) self.ui = ui.ui() @@ -176,12 +174,12 @@ def BranchInfo(self, branch): cs = self.repo.changectx( self.current ).changeset() - rev = self.repo.changelog.rev(self.repo.branchtags()[self.current]) #Current revision number. Use in Controls self.changelog.SetValue('') changelog = cs[4] self.changelog.AppendText(changelog + '\n') self.filelist.SetValue('') - self.filelist.AppendText("Currently selected branch: " + branch + "\n\nAuthor: "+cs[1]+"\n\nFiles Modified (in update): \n") + self.filelist.AppendText("Currently selected branch: " + branch + "\n\nAuthor: "+cs[1]+"\n\n") + self.filelist.AppendText("Files Modified (in update): \n") for f in cs[3]: self.filelist.AppendText(f+"\n") def get_packages(self, type=None): @@ -370,11 +368,11 @@ self.manifestlist.sort() self.SetBackgroundColour(wx.WHITE) self.sizer = wx.GridBagSizer(hgap=1, vgap=1) - self.manifestlog = wx.CheckListBox( self, -1, wx.DefaultPosition, wx.DefaultSize, self.manifestlist, - wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES) + self.manifestlog = wx.CheckListBox( self, -1, wx.DefaultPosition, wx.DefaultSize, + self.manifestlist, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES) filename = 'ignorelist.txt' - self.filename = orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + filename - upmana.validate.Validate(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep).config_file(filename, "default_ignorelist.txt") + self.filename = dir_struct["home"] + 'upmana' + os.sep + filename + component.get('validate').config_file(filename, "default_ignorelist.txt") self.mana = self.LoadDoc() self.manifestlog.Bind(wx.EVT_CHECKLISTBOX, self.GetChecked) self.sizer.Add(self.manifestlog, (0,0), flag=wx.EXPAND) @@ -409,17 +407,182 @@ class Control(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) + + ### Control Panel + self.ui = ui.ui() + self.repo = hg.repository(self.ui, ".") + self.c = self.repo.changectx('tip') + self.manifest = manifest + self.parent = parent + #logger.debug("Enter updaterFrame") #Need to set logging level + + self.get_packages() + self.SetBackgroundColour(wx.WHITE) + self.sizer = wx.GridBagSizer(hgap=1, vgap=1) + self.buttons = {} + ## Changelog / File List + changelogcp = wx.Panel(self) + self.changelogcp = wx.GridBagSizer(hgap=1, vgap=1) + self.changelog = wx.TextCtrl(changelogcp, wx.ID_ANY, size=wx.DefaultSize, style=wx.TE_MULTILINE | wx.TE_READONLY) + self.filelist = wx.TextCtrl(changelogcp, wx.ID_ANY, size=wx.DefaultSize, style=wx.TE_MULTILINE | wx.TE_READONLY) + self.changelogcp.Add(self.changelog, (0,0), flag=wx.EXPAND) + self.changelogcp.Add(self.filelist, (1,0), flag=wx.EXPAND) + changelogcp.SetSizer(self.changelogcp) + self.changelogcp.AddGrowableCol(0) + self.changelogcp.AddGrowableRow(0) + self.changelogcp.AddGrowableRow(1) + changelogcp.SetAutoLayout(True) + + ## Branches / Revisions + branchcp = wx.Panel(self) + self.branchcp = wx.GridBagSizer(hgap=1, vgap=1) + self.branches = wx.Choice(branchcp, wx.ID_ANY, choices=self.package_list) + self.branch_txt = wx.StaticText(branchcp, wx.ID_ANY, "Branches") + self.branchcp.Add(self.branches, (0,0)) + self.branchcp.Add(self.branch_txt, (0,1), flag=wx.ALIGN_CENTER_VERTICAL) + branchcp.SetSizer(self.branchcp) + branchcp.SetAutoLayout(True) + + revlistcp = wx.Panel(self) + self.revlistcp = wx.GridBagSizer(hgap=2, vgap=2) + self.revlist = wx.ListCtrl(revlistcp, -1, wx.DefaultPosition, size=wx.DefaultSize, + style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_HRULES) + self.revlist.InsertColumn(0, 'Revs') + self.revlist.InsertColumn(1, 'Changeset') + self.revlist.SetColumnWidth(0, -1) + self.revlist.SetColumnWidth(1, -1) + self.revlist.Refresh() + self.revlistcp.Add(self.revlist, (0,0), flag=wx.EXPAND) + revlistcp.SetSizer(self.revlistcp) + self.revlistcp.AddGrowableCol(0) + self.revlistcp.AddGrowableRow(0) + self.revlistcp.AddGrowableRow(1) + revlistcp.SetAutoLayout(True) + + ## Control Panel + cp = wx.Panel(self) + self.cp = wx.GridBagSizer(hgap=1, vgap=1) + self.buttons['update'] = wx.Button(cp, wx.ID_ANY, "Revision Update") + self.buttons['delete'] = wx.Button(cp, wx.ID_ANY, "Delete Branch") + self.cp.Add(self.buttons['update'], (0,0)) + self.cp.Add(self.buttons['delete'], (0,1)) + cp.SetSizer(self.cp) + cp.SetAutoLayout(True) + + self.sizer.Add(changelogcp, (0,0), span=(3,1), flag=wx.EXPAND) + self.sizer.Add(branchcp, (0,1), span=(1,1)) + self.sizer.Add(revlistcp, (2,1), span=(1,1), flag=wx.EXPAND) + self.sizer.Add(cp, (1,1), span=(1,1)) + + self.buttons['delete'].Disable() + self.sizer.AddGrowableCol(0) + self.sizer.AddGrowableCol(1) + self.sizer.AddGrowableRow(2) + self.SetSizer(self.sizer) + self.SetAutoLayout(True) + + self.current = self.repo.dirstate.branch() + self.currev = self.repo.changelog.rev(self.repo.branchtags()[self.current]) + self.RevInfo(self.currev) + self.revlist.Select(self.revlist.FindItem(0, str(self.currev), 1)) + self.BranchInfo(self.current) + self.Bind(wx.EVT_CHOICE, self.PackageSet) + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.RevSet) + self.Bind(wx.EVT_BUTTON, self.RevUpdate, self.buttons['update']) + + + def PackageSet(self, event): + self.current = self.branches.GetStringSelection() + branches = self.repo.branchtags() + heads = dict.fromkeys(self.repo.heads(), 1) + l = [((n in heads), self.repo.changelog.rev(n), n, t) for t, n in branches.items()] + if self.current != type: + heads = dict.fromkeys(self.repo.heads(), self.repo.branchtags()) + branches = dict.copy(self.repo.branchtags()) + self.BranchInfo(self.current) + self.RevInfo(self.current) + + def RevSet(self, event): + self.currev = self.revlist.GetItemText( self.revlist.GetFirstSelected() ) + i = event.GetIndex() + self.revlist.Select(i, True) + self.revlist.Focus(i) + if self.currev != self.revlist.GetItemText( self.revlist.GetFirstSelected() ): + self.RevInfo(self.currev) + + def RevInfo(self, rev): + self.revlist.DeleteAllItems() + self.revlist_a = []; self.revlist_b = {} + for heads in self.repo.changelog.reachable(self.repo.branchtags()[self.current]): + self.revlist_a.append(str(self.repo.changelog.rev(heads))) + self.revlist_b[str(self.repo.changelog.rev(heads))] = str(self.repo.changectx(heads)) + self.revlist_a.sort() + for i in self.revlist_a: + self.revlist.InsertStringItem(0, str(i), 0 ) + self.revlist.SetStringItem(0, 1, self.revlist_b[i]) + self.revlist.SetColumnWidth(0, -1) + self.revlist.SetColumnWidth(1, -1) + self.revlist.Refresh() + self.BranchInfo(self.current) + + def BranchInfo(self, branch): + rs = self.repo.changectx( self.currev ).changeset() + self.changelog.SetValue('') + changelog = rs[4] + self.changelog.AppendText(changelog + '\n') + self.filelist.SetValue('') + self.filelist.AppendText("Currently selected branch: " + branch + "\n\nAuthor: "+rs[1]+"\n\n") + self.filelist.AppendText("Files Modified (in update): \n") + for f in rs[3]: self.filelist.AppendText(f+"\n") + + def DelBranch(self, event): + pass + + def RevUpdate(self, event): + filename = 'ignorelist.txt' + self.filename = dir_struct["home"] + 'upmana' + os.sep + filename + component.get('validate').config_file(filename, "default_ignorelist.txt") + self.mana = self.LoadDoc() + temp = dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep + for ignore in self.ignorelist: + shutil.copy(ignore, temp + ignore.split('/')[len(ignore.split('/')) - 1]) + hg.clean(self.repo, self.currev) + for ignore in self.ignorelist: + shutil.copyfile(temp + ignore.split('/')[len(ignore.split('/')) - 1], ignore) + os.remove(temp + ignore.split('/')[len(ignore.split('/')) - 1]) + pass + + def LoadDoc(self): + ignore = open(self.filename) + self.ignorelist = [] + for i in ignore: self.ignorelist.append(str(i [:len(i)-1])) + manifest = ignore.readlines() + ignore.close() + + def get_packages(self, type=None): + #Fixed and ready for Test. Can be cleaner + self.package_list = [] + b = self.repo.branchtags() + heads = dict.fromkeys(self.repo.heads(), 1) #The code below looks superfluous but there is good info inside + l = [((n in heads), self.repo.changelog.rev(n), n, t) for t, n in b.items()] + l.sort() + l.reverse() + for ishead, r, n, t in l: self.package_list.append(t) + + def get_package(self): + self.get_packages() + if self.package_list == None: return None + return None class updaterFrame(wx.Frame): def __init__(self, parent, title, openrpg, manifest, main): - self.dir_struct = open_rpg.get_component("dir_struct") wx.Frame.__init__(self, None, wx.ID_ANY, title, size=(600,480), style=wx.DEFAULT_FRAME_STYLE) - if wx.Platform == '__WXMSW__': icon = wx.Icon(self.dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) - else: icon = wx.Icon(self.dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM ) + if wx.Platform == '__WXMSW__': icon = wx.Icon(dir_struct["icon"]+'d20.ico', wx.BITMAP_TYPE_ICO) + else: icon = wx.Icon(dir_struct["icon"]+"d20.xpm", wx.BITMAP_TYPE_XPM ) + self.SetIcon(icon) - self.CenterOnScreen() self.main = main ####### Panel Stuff ###### @@ -451,18 +614,13 @@ class updateApp(wx.App): def OnInit(self): - self.open_rpg = open_rpg self.main = False - self.log = orpg.tools.orpg_log.orpgLog(orpg.dirpath.dir_struct["user"] + "runlogs/") - self.log.setLogToConsol(False) - self.log.log("Updater Start", ORPG_NOTE) + logger._set_log_to_console(False) + logger.note("Updater Start") self.manifest = manifest.ManifestChanges() - self.open_rpg.add_component("log", self.log) - self.open_rpg.add_component("xml", orpg.orpg_xml) - self.open_rpg.add_component("dir_struct", orpg.dirpath.dir_struct) - self.validate = upmana.validate.Validate() - self.open_rpg.add_component("validate", self.validate) - self.updater = updaterFrame(self, "OpenRPG Update Manager 0.7.2 (open beta)", self.open_rpg, self.manifest, self.main) + component.add('validate', validate) + self.updater = updaterFrame(self, "OpenRPG Update Manager 0.8 (open beta)", + component, self.manifest, self.main) if self.manifest.GetString("updatemana", "auto_update", "") == 'on' and self.main == False: self.AutoUpdate(); self.OnExit() else: pass @@ -485,17 +643,17 @@ if capture != '': commands.pull(self.ui, self.repo, capture, rev='', update=False, force=True) filename = 'ignorelist.txt' - self.filename = orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + filename - upmana.validate.Validate(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep).config_file(filename, "default_ignorelist.txt") + self.filename = dir_struct["home"] + 'upmana' + os.sep + filename + component.get('validate').config_file(filename, "default_ignorelist.txt") self.mana = self.LoadDoc() + temp = dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep for ignore in self.ignorelist: - shutil.copy(ignore, orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep +ignore.split('/')[len(ignore.split('/')) - 1]) + shutil.copy(ignore, temp + ignore.split('/')[len(ignore.split('/')) - 1]) hg.clean(self.repo, self.current) for ignore in self.ignorelist: - print ignore.split('/')[len(ignore.split('/')) - 1] - shutil.copyfile(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep + ignore.split('/')[len(ignore.split('/')) - 1], ignore) - os.remove(orpg.dirpath.dir_struct["home"] + 'upmana' + os.sep + 'tmp' + os.sep + ignore.split('/')[len(ignore.split('/')) - 1]) - else: print 'No default repository set, skipping Auto Update!' + shutil.copyfile(temp + ignore.split('/')[len(ignore.split('/')) - 1], ignore) + os.remove(temp + ignore.split('/')[len(ignore.split('/')) - 1]) + else: wx.MessageBox('No default Rpository set. Skipping Auto Update!', 'Info') def LoadDoc(self): ignore = open(self.filename) @@ -505,7 +663,10 @@ ignore.close() def OnExit(self): - imported = ['manifest', 'orpg.dirpath', 'orpg.orpgCore', 'orpg.orpg_version', 'orpg.tools.orpg_log', 'orpg.tools.orpg_log', 'orpg.orpg_xml', 'orpg.dirpath', 'orpg.dirpath', 'upmana.validate', 'mercurial.ui', 'mercurial.hg', 'mercurial.commands', 'mercurial.repo', 'mercurial.revlog', 'mercurial.cmdutil', 'shutil'] + imported = ['manifest', 'orpg.dirpath', 'orpg.orpgCore', 'orpg.orpg_version', + 'orpg.tools.orpg_log', 'orpg.tools.orpg_log', 'orpg.orpg_xml', 'orpg.dirpath', + 'orpg.dirpath', 'upmana.validate', 'mercurial.ui', 'mercurial.hg', + 'mercurial.commands', 'mercurial.repo', 'mercurial.revlog', 'mercurial.cmdutil', 'shutil'] for name in imported: if name in sys.modules: del sys.modules[name]
--- a/upmana/validate.py Thu Aug 13 13:14:10 2009 -0500 +++ b/upmana/validate.py Thu Aug 27 01:04:43 2009 -0500 @@ -6,23 +6,23 @@ # Misc. config file service methods # -import orpg.dirpath +from orpg.dirpath import dir_struct import os class Validate: def __init__(self, userpath=None): if userpath is None: - userpath = orpg.dirpath.dir_struct["user"] + userpath = dir_struct["home"] + os.sep + 'upmana' +os.sep self.__loadUserPath = userpath def config_file(self, user_file, template_file): #STEP 1: verify the template exists - if (not os.path.exists(orpg.dirpath.dir_struct["template"] + template_file)): + if (not os.path.exists(dir_struct["template"] + template_file)): return 0 #STEP 2: verify the user file exists. If it doesn't then create it from template if (not os.path.exists(self.__loadUserPath + user_file)): - default = open(orpg.dirpath.dir_struct["template"] + template_file,"r") + default = open(dir_struct["template"] + template_file,"r") file = default.read() newfile = open(self.__loadUserPath + user_file,"w") newfile.write(file) @@ -35,3 +35,5 @@ def ini_entry(self, entry_name, ini_file): pass + +validate = Validate()