Mercurial > traipse
changeset 13:211ac836b6a0 grumpy-goblin
{090731-00} Fixes problem with Name & Settings window, cleans code.
line wrap: on
line diff
--- a/orpg/main.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/main.py Fri Jul 31 15:22:11 2009 -0500 @@ -74,14 +74,10 @@ # 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) # create the object, then determine if it needs to be replaced. It calculates 2 less calculations. - - # Set it if we have it - if icon != None: - self.SetIcon( icon ) + 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. + self.SetIcon( icon ) # create session call_backs = {"on_receive":self.on_receive, @@ -137,25 +133,20 @@ def get_activeplugins(self): self.log.log("Enter orpgFrame->get_activeplugins(self)", ORPG_DEBUG) - try: - tmp = self.pluginsFrame.get_activeplugins() - except: - tmp = {} + try: tmp = self.pluginsFrame.get_activeplugins() + except: tmp = {} self.log.log("Exit orpgFrame->get_activeplugins(self)", ORPG_DEBUG) return tmp def get_startplugins(self): self.log.log("Enter orpgFrame->get_startplugins(self)", ORPG_DEBUG) - try: - tmp = self.pluginsFrame.get_startplugins() - except: - tmp = {} + try: tmp = self.pluginsFrame.get_startplugins() + except: tmp = {} self.log.log("Exit orpgFrame->get_startplugins(self)", ORPG_DEBUG) return tmp 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) id = int(id) @@ -163,16 +154,11 @@ data = str(data) signal = str(signal) if signal == "fail": - if type == "server": - self.password_manager.ClearPassword("server", 0) - elif type == "admin": - self.password_manager.ClearPassword("admin", int(id)) - elif type == "room": - self.password_manager.ClearPassword("room", int(id)) - else: - pass - except: - traceback.print_exc() + if type == "server": self.password_manager.ClearPassword("server", 0) + elif type == "admin": self.password_manager.ClearPassword("admin", int(id)) + 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) def build_menu(self): @@ -230,9 +216,8 @@ self.mainmenu = MenuBarEx(self, menu) if self.settings.get_setting('Heartbeat') == '1': self.mainmenu.SetMenuState("GameServerServerHeartbeat", True) - tabtheme = self.settings.get_setting('TabTheme') - #This change is stable. TaS. + tabtheme = self.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') @@ -242,21 +227,18 @@ self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", tabtheme == 'customflat') lvl = int(self.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) - if lvl & ORPG_GENERAL: - self.mainmenu.SetMenuState("ToolsLoggingLevelGeneral", True) + 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) + if lvl & ORPG_GENERAL: self.mainmenu.SetMenuState("ToolsLoggingLevelGeneral", True) + self.pluginMenu = wx.Menu() item = wx.MenuItem(self.pluginMenu, wx.ID_ANY, "Control Panel", "Control Panel") self.Bind(wx.EVT_MENU, self.OnMB_PluginControlPanel, item) self.pluginMenu.AppendItem(item) self.pluginMenu.AppendSeparator() self.mainmenu.Insert(2, self.pluginMenu, "&Plugins") - self.log.log("Exit orpgFrame->build_menu()", ORPG_DEBUG) + self.log.log("Exit orpgFrame->build_menu()", ORPG_DEBUG) ################################# ## All Menu Events @@ -264,57 +246,39 @@ #Tab Styles Menus def SetTabStyles(self, *args, **kwargs): self.log.log("Enter orpgFrame->SetTabStyles(self, *args, **kwargs)", ORPG_DEBUG) - 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 - 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 - if kwargs.has_key('graidentTo'): - graidentTo = kwargs['graidentTo'] + + tabtheme = self.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') + self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", tabtheme == 'flat&bw') + self.mainmenu.SetMenuState("OpenRPGTabStylesFlatAqua", tabtheme == 'flat&aqua') + self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", tabtheme == 'customslant') + self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", tabtheme == 'customflat') + + if kwargs.has_key('style'): newstyle = kwargs['style'] else: - graidentTo = None - if kwargs.has_key('graidentFrom'): - graidentFrom = kwargs['graidentFrom'] + try: newstyle = args[1] + except: self.log.log('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)', ORPG_GENERAL); return + if kwargs.has_key('menu'): menu = kwargs['menu'] else: - graidentFrom = None - if kwargs.has_key('textColor'): - textColor = kwargs['textColor'] - else: - textColor = None + try: menu = args[0] + except: self.log.log('Invalid Syntax for orpgFrame->SetTabStyles(self, *args, **kwargs)', ORPG_GENERAL); return - #Set all menu's to unchecked - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesFlatAqua", False) - self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", False) - - #check the proper menu - self.mainmenu.SetMenuState(menu, True) + if kwargs.has_key('graidentTo'): graidentTo = kwargs['graidentTo'] + else: graidentTo = None + if kwargs.has_key('graidentFrom'): graidentFrom = kwargs['graidentFrom'] + else: graidentFrom = None + if kwargs.has_key('textColor'): textColor = kwargs['textColor'] + 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() new = [] for wnd in tabbedwindows: - try: - style = wnd.GetWindowStyleFlag() - new.append(wnd) - except: - pass + try: style = wnd.GetWindowStyleFlag(); new.append(wnd) + except: pass tabbedwindows = new open_rpg.add_component("tabbedWindows", tabbedwindows) @@ -331,12 +295,9 @@ style |= newstyle wnd.SetWindowStyleFlag(style) wnd.SetTabAreaColour(wx.Color(red, green, blue)) - if graidentTo != None: - wnd.SetGradientColourTo(graidentTo) - if graidentFrom != None: - wnd.SetGradientColourFrom(graidentFrom) - if textColor != None: - wnd.SetNonActiveTabTextColour(textColor) + if graidentTo != None: wnd.SetGradientColourTo(graidentTo) + if graidentFrom != None: wnd.SetGradientColourFrom(graidentFrom) + if textColor != None: wnd.SetNonActiveTabTextColour(textColor) wnd.Refresh() def OnMB_OpenRPGNewMap(self): @@ -348,8 +309,7 @@ if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedColorful"): self.settings.set_setting('TabTheme', 'slanted&colorful') self.SetTabStyles("OpenRPGTabStylesSlantedColorful", FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS) - else: - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", True) + else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", True) self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedColorful(self)", ORPG_DEBUG) def OnMB_OpenRPGTabStylesSlantedBlackandWhite(self): @@ -357,8 +317,7 @@ 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) - else: - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", True) + else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", True) self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedBlackandWhite(self)", ORPG_DEBUG) def OnMB_OpenRPGTabStylesSlantedAqua(self): @@ -366,13 +325,11 @@ 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) - else: - self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", True) + else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", True) self.log.log("Exit orpgFrame->OnMB_OpenRPGTabStylesSlantedBlackandWhite(self)", ORPG_DEBUG) 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() @@ -384,27 +341,28 @@ (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) tabbg = self.settings.get_setting('TabBackgroundGradient') (red, green, blue) = rgbc.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.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) 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') - self.SetTabStyles("OpenRPGTabStylesFlatBlackandWhite", FNB.FNB_FANCY_TABS, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) - else: - self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", True) + 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) 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') - 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.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) def OnMB_OpenRPGTabStylesFlatCustom(self): @@ -420,9 +378,10 @@ (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) tabbg = self.settings.get_setting('TabBackgroundGradient') (red, green, blue) = rgbc.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.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 @@ -431,15 +390,11 @@ menuid = event.GetId() name = self.mainwindows[menuid] if name == 'Alias Lib': - if self.aliaslib.IsShown() == True: - self.aliaslib.Hide() - else: - self.aliaslib.Show() + if self.aliaslib.IsShown() == True: self.aliaslib.Hide() + else: self.aliaslib.Show() else: - if self._mgr.GetPane(name).IsShown() == True: - self._mgr.GetPane(name).Hide() - else: - self._mgr.GetPane(name).Show() + if self._mgr.GetPane(name).IsShown() == True: 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) @@ -457,19 +412,15 @@ #Game Server Menu 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() + 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) 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') + 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) def OnMB_GameServerStartServer(self): @@ -494,19 +445,15 @@ # Tools Menu 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() + if self.pluginsFrame.IsShown() == True: self.pluginsFrame.Hide() + else: self.pluginsFrame.Show() self.log.log("Exit orpgFrame->OnMB_ToolsPlugins(self)", ORPG_DEBUG) def OnMB_ToolsLoggingLevelDebug(self): self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelDebug(self)", ORPG_DEBUG) lvl = self.log.getLogLevel() - if self.mainmenu.GetMenuState("ToolsLoggingLevelDebug"): - lvl |= ORPG_DEBUG - else: - lvl &= ~ORPG_DEBUG + 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) @@ -514,10 +461,8 @@ def OnMB_ToolsLoggingLevelNote(self): self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelNote(self)", ORPG_DEBUG) lvl = self.log.getLogLevel() - if self.mainmenu.GetMenuState("ToolsLoggingLevelNote"): - lvl |= ORPG_DEBUG - else: - lvl &= ~ORPG_DEBUG + 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) @@ -525,10 +470,8 @@ def OnMB_ToolsLoggingLevelInfo(self): self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelInfo(self)", ORPG_DEBUG) lvl = self.log.getLogLevel() - if self.mainmenu.GetMenuState("ToolsLoggingLevelInfo"): - lvl |= ORPG_INFO - else: - lvl &= ~ORPG_INFO + 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) @@ -536,20 +479,16 @@ def OnMB_ToolsLoggingLevelGeneral(self): self.log.log("Enter orpgFrame->OnMB_ToolsLoggingLevelGeneral(self)", ORPG_DEBUG) lvl = self.log.getLogLevel() - if self.mainmenu.GetMenuState("ToolsLoggingLevelGeneral"): - lvl |= ORPG_GENERAL - else: - lvl &= ~ORPG_GENERAL + 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) 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() + if self.mainmenu.GetMenuState("ToolsPasswordManager"): self.password_manager.Enable() + else: self.password_manager.Disable() self.log.log("Exit orpgFrame->OnMB_ToolsPasswordManager(self)", ORPG_DEBUG) def OnMB_ToolsStatusBar(self): @@ -760,8 +699,7 @@ try: textnode = self.xml.safe_get_text_node(layout[0]) self._mgr.LoadPerspective(textnode._get_nodeValue()) - except: - pass + except: pass xml_dom.unlink() self.log.log("Perspective Loaded", ORPG_DEBUG) self._mgr.GetPane("Browse Server Window").Hide() @@ -787,8 +725,7 @@ 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 + if name == "DockLayout" or name == "dock": return dir = xml_dom.getAttribute("direction") pos = xml_dom.getAttribute("pos") height = xml_dom.getAttribute("height") @@ -797,15 +734,10 @@ dockable = xml_dom.getAttribute("dockable") layer = xml_dom.getAttribute("layer") - try: - layer = int(layer) - dockable = int(dockable) - except: - layer = 0 - dockable = 1 + try: layer = int(layer); dockable = int(dockable) + except: layer = 0; dockable = 1 - if name == "tab": - temp_wnd = self.do_tab_window(xml_dom, parent_wnd) + if name == "tab": temp_wnd = self.do_tab_window(xml_dom, parent_wnd) elif name == "map": temp_wnd = orpg.mapper.map.map_wnd(parent_wnd, -1) self.map = temp_wnd @@ -833,9 +765,8 @@ else: self.players.SetBackgroundColour('white') self.players.SetForegroundColour('black') - if parent_wnd != self: - #We dont need this if the window are beeing tabed - return temp_wnd + + if parent_wnd != self: return temp_wnd menuid = wx.NewId() self.windowsmenu.Append(menuid, cap, kind=wx.ITEM_CHECK) self.windowsmenu.Check(menuid, True) @@ -850,17 +781,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 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 dockable != 1: wndinfo.Dockable(False) @@ -876,9 +801,7 @@ self.log.log("Enter orpgFrame->onPaneClose()", ORPG_DEBUG) pane = evt.GetPane() for wndid, wname in self.mainwindows.iteritems(): - if pane.name == wname: - self.windowsmenu.Check(wndid, False) - break + if pane.name == wname: self.windowsmenu.Check(wndid, False); break evt.Skip() self._mgr.Update() self.log.log("Exit orpgFrame->onPaneClose()", ORPG_DEBUG) @@ -892,10 +815,8 @@ temp_file.close() (x_size,y_size) = self.GetClientSize() (x_pos,y_pos) = self.GetPositionTuple() - if self.IsMaximized(): - max = 1 - else: - max = 0 + if self.IsMaximized(): max = 1 + else: max = 0 xml_dom.setAttribute("height", str(y_size)) xml_dom.setAttribute("width", str(x_size)) xml_dom.setAttribute("posx", str(x_pos)) @@ -950,8 +871,7 @@ 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) + 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) def on_player_event(self, evt): @@ -976,13 +896,11 @@ id = evt.get_id() data = evt.get_data() - if id == orpg.networking.mplay_client.GROUP_NEW: - self.gs.add_room(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) + 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) def on_receive(self, data, player): @@ -991,25 +909,19 @@ # 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]: - # yes we are - self.log.log("ignoring message from player:" + player[0], ORPG_INFO, True) - return + if m == player[2]: self.log.log("ignoring message from player:" + player[0], ORPG_INFO, True); return # ok we are not ignoring this message #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 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) + elif data[:4] == "<map": self.map.new_data(data) elif data[:5] == "<chat": msg = orpg.chat.chat_msg.chat_msg(data) @@ -1047,10 +959,8 @@ else: # Normal text - if player: - data = "<b>" + display_name + "</b>: " + data - else: - data = "<b><i><u>" + display_name + "</u>-></i></b> " + data + 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) @@ -1076,10 +986,8 @@ settings = open_rpg.get_component('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) - else: - self.chat.system_message(custom_msg) + if custom_msg[:3]=="/me": self.chat.send_chat_message(custom_msg[3:], 3) + else: self.chat.system_message(custom_msg) #####End Changes for Custom Exit Message by mDuo13 elif id== orpg.networking.mplay_client.MPLAY_GROUP_CHANGE: @@ -1108,40 +1016,32 @@ #########plugin_disabled()######### for plugin_fname in self.activeplugins.keys(): plugin = self.activeplugins[plugin_fname] - try: - plugin.plugin_disabled() + 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: self.settings.save() + except: self.log.log("[WARNING] Error saving 'settings' component", ORPG_GENERAL, True) - try: - self.map.pre_exit_cleanup() - except: - self.log.log("[WARNING] Map error pre_exit_cleanup()", ORPG_GENERAL, True) + try: self.map.pre_exit_cleanup() + except: self.log.log("[WARNING] Map error pre_exit_cleanup()", ORPG_GENERAL, True) try: save_tree = string.upper(self.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) + except: self.log.log("[WARNING] Error saving gametree", ORPG_GENERAL, True) - if self.session.get_status() == orpg.networking.mplay_client.MPLAY_CONNECTED: - self.kill_mplay_session() + if self.session.get_status() == orpg.networking.mplay_client.MPLAY_CONNECTED: self.kill_mplay_session() try: #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: self.log.log("sound didn't die properly.",ORPG_GENERAL, True) try: self.poll_timer.Stop() @@ -1152,8 +1052,7 @@ 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: self.log.log("some timer didn't die properly.",ORPG_GENERAL, True) self._mgr.UnInit() mainapp = wx.GetApp() mainapp.ExitMainLoop() @@ -1173,8 +1072,7 @@ self.server_thread.exit() dlg.Destroy() self.log.log("Server killed:", ORPG_GENERAL, True) - except: - pass + except: pass self.log.log("Exit orpgFrame->closed_confirmed(self)", ORPG_DEBUG) @@ -1183,7 +1081,8 @@ ######################################## class orpgSplashScreen(wx.SplashScreen): 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) + wx.SplashScreen.__init__(self, wx.Bitmap(bitmapfile), + wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, duration, None, -1) self.callback = callback self.closing = False self.Bind(wx.EVT_CLOSE, self.callback) @@ -1214,10 +1113,8 @@ def OnKeyPress(self, evt): #Event handler - if evt.AltDown() and evt.CmdDown() and evt.KeyCode == ord('I'): - self.ShowShell() - else: - evt.Skip() + if evt.AltDown() and evt.CmdDown() and evt.KeyCode == ord('I'): self.ShowShell() + else: evt.Skip() def ShowShell(self): #Show the PyCrust window. @@ -1244,18 +1141,12 @@ def OnExit_CleanUp(self): self.log.log("Preforming cleanup\n", ORPG_DEBUG) - 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') - except: - pass - try: - os.remove(os.environ["OPENRPG_BASE"] + os.sep + 'orpg' + os.sep + 'dirpath' + os.sep + 'approot.pyc') - except: - pass + 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') + except: pass + try: os.remove(os.environ["OPENRPG_BASE"] + os.sep + 'orpg' + os.sep + 'dirpath' + os.sep + 'approot.pyc') + except: pass def OnExit(self): self.OnExit_CleanUp()
--- a/orpg/mapper/background.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/background.py Fri Jul 31 15:22:11 2009 -0500 @@ -109,8 +109,7 @@ if self.bg_bmp == None: self.log.log("Invalid image type!", ORPG_GENERAL) raise Exception, "Invalid image type!" - except: - self.error_loading_image(path) + except: self.error_loading_image(path) self.img_path = path self.log.log("Enter layer_back_ground->set_texture(self, path)", ORPG_DEBUG) @@ -125,8 +124,7 @@ if self.bg_bmp == None: self.log.log("Invalid image type!", ORPG_GENERAL) raise Exception, "Invalid image type!" - except: - self.error_loading_image(path) + 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()) @@ -149,10 +147,8 @@ dc2.SelectObject(self.bg_bmp) topLeft = [int(topleft[0]/scale), int(topleft[1]/scale)] topRight = [int((topleft[0]+size[0]+1)/scale)+1, int((topleft[1]+size[1]+1)/scale)+1] - if (topRight[0] > self.canvas.size[0]): - topRight[0] = self.canvas.size[0] - if (topRight[1] > self.canvas.size[1]): - topRight[1] = self.canvas.size[1] + if (topRight[0] > self.canvas.size[0]): topRight[0] = self.canvas.size[0] + if (topRight[1] > self.canvas.size[1]): topRight[1] = self.canvas.size[1] bmpW = self.bg_bmp.GetWidth() bmpH = self.bg_bmp.GetHeight() if self.type == BG_TEXTURE: @@ -165,10 +161,8 @@ cl = 0 posx = x while x < topRight[0]: - if x+bmpW > topRight[0]: - cr = x+bmpW-topRight[0] - else: - cr = 0 + if x+bmpW > topRight[0]: cr = x+bmpW-topRight[0] + else: cr = 0 y = int(topLeft[1]/bmpH)*bmpH if y < topLeft[1]: posy = topLeft[1] @@ -177,16 +171,12 @@ ct = 0 posy = y while y < topRight[1]: - if y+bmpH > topRight[1]: - cb = y+bmpH-topRight[1] - else: - cb = 0 + if y+bmpH > topRight[1]: cb = y+bmpH-topRight[1] + else: cb = 0 newW = bmpW-cr-cl newH = bmpH-cb-ct - if newW < 0: - newW = 0 - if newH < 0: - newH = 0 + if newW < 0: newW = 0 + if newH < 0: newH = 0 dc.DrawBitmap(self.bg_bmp, posx, posy) dc.Blit(posx, posy, newW, newH, dc2, cl, ct) ct = 0 @@ -204,27 +194,20 @@ else: cl = 0 posx = x - if y < topLeft[1]: posy = topLeft[1] ct = topLeft[1]-y else: ct = 0 posy = y - if x+bmpW > topRight[0]: - cr = x+bmpW-topRight[0] - else: - cr = 0 - if y+bmpH > topRight[1]: - cb = y+bmpH-topRight[1] - else: - cb = 0 + if x+bmpW > topRight[0]: cr = x+bmpW-topRight[0] + else: cr = 0 + if y+bmpH > topRight[1]: cb = y+bmpH-topRight[1] + else: cb = 0 newW = bmpW-cr-cl newH = bmpH-cb-ct - if newW < 0: - newW = 0 - if newH < 0: - newH = 0 + if newW < 0: newW = 0 + if newH < 0: newH = 0 dc.DrawBitmap(self.bg_bmp, posx, posy) dc.Blit(posx, posy, newW, newH, dc2, cl, ct) dc2.SelectObject(wx.NullBitmap) @@ -239,10 +222,8 @@ (red,green,blue) = self.bg_color.Get() hexcolor = self.r_h.hexstring(red, green, blue) xml_str += ' color="' + hexcolor + '"' - if self.img_path != None: - xml_str += ' path="' + urllib.quote(self.img_path).replace('%3A', ':') + '"' - if self.type != None: - xml_str += ' type="' + str(self.type) + '"' + if self.img_path != None: xml_str += ' path="' + urllib.quote(self.img_path).replace('%3A', ':') + '"' + if self.type != None: xml_str += ' type="' + str(self.type) + '"' if self.local and self.img_path != None: xml_str += ' local="True"' xml_str += ' localPath="' + urllib.quote(self.localPath).replace('%3A', ':') + '"' @@ -253,8 +234,7 @@ if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str - else: - return '' + else: return '' def layerTakeDOM(self, xml_dom): self.log.log("Enter layer_back_ground->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) @@ -274,15 +254,12 @@ self.log.log("type=" + str(type), ORPG_DEBUG) if type == BG_TEXTURE: - if path != "": - self.set_texture(path) + if path != "": self.set_texture(path) elif type == BG_IMAGE: - if path != "": - self.set_image(path, 1) + if path != "": self.set_image(path, 1) - elif type == BG_NONE: - self.clear() + 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')) @@ -310,12 +287,8 @@ if xml_dom.nodeName == 'path': path = xml_dom.getAttribute('url') path = urllib.unquote(path) - - if type == 'Image': - self.set_image(path, 1) - else: - self.set_texture(path) - + if type == 'Image': self.set_image(path, 1) + else: self.set_texture(path) self.localPath = filename self.local = True self.localTime = time.time()
--- a/orpg/mapper/background_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/background_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -69,7 +69,9 @@ def on_browse(self, evt): if self.bg_type.GetStringSelection() == 'Texture' or self.bg_type.GetStringSelection() == 'Image': - dlg = wx.FileDialog(None, "Select a Miniature to load", orpg.dirpath.dir_struct["user"]+'webfiles/', wildcard="Image files (*.bmp, *.gif, *.jpg, *.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) + dlg = wx.FileDialog(None, "Select a Miniature to load", + orpg.dirpath.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() return @@ -81,18 +83,16 @@ postdata = urllib.urlencode({'filename':filename, 'imgdata':imgdata, 'imgtype':imgtype}) if self.settings.get_setting('LocalorRemote') == 'Remote': - thread.start_new_thread(self.canvas.layers['bg'].upload, (postdata, dlg.GetPath(), self.bg_type.GetStringSelection())) + 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 - except: - return - min_url = dlg.GetDirectory().replace(orpg.dirpath.dir_struct["user"]+'webfiles' + os.sep, open_rpg.get_component("cherrypy")) + '/' + filename + 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 - 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) + 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) self.update_info() self.canvas.send_map_data() self.canvas.Refresh(False) @@ -100,8 +100,7 @@ def update_info(self): bg_type = self.canvas.layers['bg'].get_type() session=self.canvas.frame.session - if (session.my_role() != session.ROLE_GM): - self.url_path.Hide() + if (session.my_role() != session.ROLE_GM): self.url_path.Hide() else: self.url_path.Show() self.url_path.Enable(BG_COLOR!=bg_type) @@ -143,9 +142,8 @@ return self.canvas.layers['bg'].set_color(self.color_button.GetBackgroundColour()) - if self.bg_type.GetStringSelection() == 'Texture': - self.canvas.layers['bg'].set_texture(self.url_path.GetValue()) - elif self.bg_type.GetStringSelection() == 'Image': + if self.bg_type.GetStringSelection() == 'Texture': self.canvas.layers['bg'].set_texture(self.url_path.GetValue()) + elif self.bg_type.GetStringSelection() == 'Image': self.size = self.canvas.layers['bg'].set_image(self.url_path.GetValue(),1) self.update_info()
--- a/orpg/mapper/base.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/base.py Fri Jul 31 15:22:11 2009 -0500 @@ -41,18 +41,12 @@ def __cmp__(self,other): try: - if self.x < other.x: - return -1 - elif self.x > other.x: - return 1 - elif self.y < other.y: - return -1 - elif self.y > other.y: - return 1 - else: - return 0 - except: - return -2 + if self.x < other.x: return -1 + elif self.x > other.x: return 1 + elif self.y < other.y: return -1 + elif self.y > other.y: return 1 + else: return 0 + except: return -2 class cmpColour(wx.Colour): def __init__(self,*_args,**_kwargs): @@ -64,14 +58,10 @@ my_value = b*256*256 + g*256 + r (r,g,b) = other.Get() other_value = b*256*256 + g*256 + r - if my_value < other_value: - return -1 - elif my_value > other_value: - return 1 - else: # they're equal - return 0 - except: - return -2 + if my_value < other_value: return -1 + elif my_value > other_value: return 1 + else: return 0 + except: return -2 class protectable_attributes: @@ -86,19 +76,15 @@ full_name = "_protect_" + name if hasattr(self,full_name): (p,c) = getattr(self,full_name) - if p != value: - self._set(full_name,(value,1)) - else: - self._set(full_name,(value,1)) - else: - self._set(name,value) + if p != value: self._set(full_name,(value,1)) + else: self._set(full_name,(value,1)) + else: self._set(name,value) def __getattr__(self,name): if name in self._protected_attr: (p,c) = self.__dict__["_protect_" + name] return p - else: - raise AttributeError + else: raise AttributeError def _clean_attr(self,name): if name in self._protected_attr: @@ -114,8 +100,7 @@ changed = {} for name in self._protected_attr: (p,c) = self.__dict__["_protect_" + name] - if c: - changed[name] = p + if c: changed[name] = p return changed def _clean_all_attr(self):
--- a/orpg/mapper/base_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/base_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -50,11 +50,16 @@ self.sizer = wx.BoxSizer(wx.HORIZONTAL) 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 ) - self.zoom_out_button = createMaskedButton( self, orpg.dirpath.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 ) - mapopen = createMaskedButton( self, orpg.dirpath.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 ) + self.zoom_in_button = createMaskedButton( self, + orpg.dirpath.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 ) + props = createMaskedButton( self, + orpg.dirpath.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 ) + mapsave = createMaskedButton( self, + orpg.dirpath.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 ) @@ -75,7 +80,7 @@ def build_menu(self,label = "Map"): "Menu is built based on the type of grid (rectangle or hex) we have in use." # do main menu - main_menu = wx.Menu(label) # create a menu resource + main_menu = wx.Menu(label) #create a menu resource main_menu.SetTitle(label) item = wx.MenuItem(main_menu, wx.ID_ANY, "&Load Map", "Load Map") self.canvas.Bind(wx.EVT_MENU, self.map_frame.on_open, item)
--- a/orpg/mapper/base_msg.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/base_msg.py Fri Jul 31 15:22:11 2009 -0500 @@ -50,10 +50,8 @@ # Using a passed in object is useful to protect an entire <map/> element from # being changed by another thread when any part of it is being change by another # thread. Just pass the map_msg's p_lock object in to it's descendents. - if reentrant_lock_object: - self.p_lock = reentrant_lock_object - else: - self.p_lock = RLock() + if reentrant_lock_object: self.p_lock = reentrant_lock_object + else: self.p_lock = RLock() def clear(self): self.p_lock.acquire() @@ -63,12 +61,10 @@ self.children[child] = None del self.children[child] - for p in self._props.keys(): - self._props[p] = None + for p in self._props.keys(): self._props[p] = None self.p_lock.release() - ######################################### # Accessor functions begin @@ -90,9 +86,7 @@ (p,c) = self._props[prop] self.p_lock.release() return p - else: - self.p_lock.release() - return None + else: self.p_lock.release(); return None def is_prop_changed(self,prop): # returns None if prop not found self.p_lock_acquire() @@ -100,9 +94,7 @@ (p,c) = self._props[prop] self.p_lock.release() return c - else: - self.p_lock.release() - return None + else: self.p_lock.release(); return None def get_child(self,key): # returns None if key not found in children list self.p_lock_acquire() @@ -117,14 +109,12 @@ def init_props(self,props): # same as init_prop(), but takes dictionary of props self.p_lock.acquire() - for k in props.keys(): - self._props[k] = (props[k],0) + for k in props.keys(): self._props[k] = (props[k],0) self.p_lock.release() def set_props(self,props): # same as set_prop(), but takes dictionary of props self.p_lock.acquire() - for k in props.keys(): - self._props[k] = (props[k],1) + for k in props.keys(): self._props[k] = (props[k],1) self.p_lock.release() def get_all_props(self): # returns dictionary of all properties, regardless of change @@ -143,15 +133,13 @@ result = {} for k in self._props.keys(): (p,c) = self._props[k] - if c: - result[k] = p + if c: result[k] = p self.p_lock.release() return result def get_children(self): # returns dictionary of children return self.children - # Accessor functions end ######################################### @@ -160,19 +148,15 @@ def get_all_xml(self,action="new",output_action = 0): # outputs a tag with all attributes it contains self.p_lock.acquire() xml_str = "<" + self.tagname - if action and output_action: - xml_str += " action='" + action + "'" + if action and output_action: xml_str += " action='" + action + "'" for k in self._props.keys(): (p,c) = self._props[k] - if k != "action" or not action: - xml_str += " " + k + "='" + p + "'" + if k != "action" or not action: xml_str += " " + k + "='" + p + "'" if self.children: xml_str += ">" - for child in self.children.keys(): - xml_str += self.children[child].get_all_xml(action) + for child in self.children.keys(): xml_str += self.children[child].get_all_xml(action) xml_str += "</" + self.tagname + ">" - else: - xml_str += "/>" + else: xml_str += "/>" self.p_lock.release() return xml_str @@ -188,15 +172,12 @@ xml_str += " id='" + p + "'" for k in self._props.keys(): (p,c) = self._props[k] - if (k != "id" or k != "action") and c == 1: # don't duplicate the id attribute - xml_str += " " + k + "='" + p + "'" + if (k != "id" or k != "action") and c == 1: xml_str += " " + k + "='" + p + "'" if self.children: xml_str += ">" - for child in self.children.keys(): - xml_str += self.children[child].get_changed_xml(action) + for child in self.children.keys(): xml_str += self.children[child].get_changed_xml(action) xml_str += "</" + self.tagname + ">" - else: - xml_str += "/>" + else: xml_str += "/>" self.p_lock.release() return xml_str @@ -236,24 +217,18 @@ def init_from_xml(self,xml): xml_dom = parseXml(xml) node_list = xml_dom.getElementsByTagName(self.tagname) - if len(node_list) < 1: - print "Warning: no <" + self.tagname + "/> elements found in DOM." + if len(node_list) < 1: print "Warning: no <" + self.tagname + "/> elements found in DOM." else: - while len(node_list): - self.init_from_dom(node_list.pop()) - if xml_dom: - xml_dom.unlink() + while len(node_list): self.init_from_dom(node_list.pop()) + if xml_dom: xml_dom.unlink() def set_from_xml(self,xml): xml_dom = parseXml(xml) node_list = xml_dom.getElementsByTagName(self.tagname) - if len(node_list) < 1: - print "Warning: no <" + self.tagname + "/> elements found in DOM." + if len(node_list) < 1: print "Warning: no <" + self.tagname + "/> elements found in DOM." else: - while len(node_list): - self.set_from_dom(node_list.pop()) - if xml_dom: - xml_dom.unlink() + while len(node_list): self.set_from_dom(node_list.pop()) + if xml_dom: xml_dom.unlink() # XML importers end #########################################
--- a/orpg/mapper/fog.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/fog.py Fri Jul 31 15:22:11 2009 -0500 @@ -70,8 +70,7 @@ elem.setAttribute( "outline", localOutline ) if localOutline == 'points': list = self.points_to_elements( self.outline ) - for p in list: - elem.appendChild( p ) + for p in list: elem.appendChild( p ) str = elem.toxml() elem.unlink() self.log.log(str, ORPG_DEBUG) @@ -82,8 +81,7 @@ elem.setAttribute( "outline", localOutline ) if localOutline == 'points': list = self.points_to_elements( self.outline ) - for p in list: - elem.appendChild( p ) + for p in list: elem.appendChild( p ) xml_str = elem.toxml() elem.unlink() self.log.log(xml_str, ORPG_DEBUG) @@ -97,8 +95,7 @@ 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) + if "__WXGTK__" not in wx.PlatformInfo: self.color = wx.Color(128,128,128, 128) self.fogregion = wx.Region() self.fogregion.Clear() self.fog_bmp = None @@ -132,8 +129,7 @@ self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) return self.recompute_fog() - except: - pass + except: pass self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) def recompute_fog(self): @@ -157,10 +153,8 @@ mdc = wx.MemoryDC() mdc.SelectObject(self.fog_bmp) mdc.SetPen(wx.TRANSPARENT_PEN) - if (self.canvas.frame.session.role == "GM"): - color = self.color - else: - color = wx.BLACK + if (self.canvas.frame.session.role == "GM"): color = self.color + else: color = wx.BLACK self.last_role = self.canvas.frame.session.role mdc.SetBrush(wx.Brush(color,wx.SOLID)) mdc.DestroyClippingRegion() @@ -178,16 +172,14 @@ 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 self.last_role != self.canvas.frame.session.role: self.fill_fog() if "__WXGTK__" not in wx.PlatformInfo: gc = wx.GraphicsContext.Create(dc) gc.SetBrush(wx.Brush(wx.BLACK)) if (self.canvas.frame.session.role == "GM"): gc.SetBrush(wx.Brush(self.color)) rgn = wx.Region(0, 0, self.canvas.size[0]+2, self.canvas.size[1]+2) - if not self.fogregion.IsEmpty(): - rgn.SubtractRegion(self.fogregion) + if not self.fogregion.IsEmpty(): rgn.SubtractRegion(self.fogregion) gc.ClipRegion(rgn) gc.DrawRectangle(0, 0, self.canvas.size[0]+2, self.canvas.size[1]+2) else: @@ -200,11 +192,10 @@ mdc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID)) mdc.DrawRectangle(0,0,size[0],size[1]) srct = [int(topleft[0]/(sc[0]*COURSE)), int(topleft[1]/(sc[1]*COURSE))] - srcsz = [int((int(size[0]/COURSE+1)*COURSE)/(sc[0]*COURSE))+2, int((int(size[1]/COURSE+1)*COURSE)/(sc[1]*COURSE))+2] - if (srct[0]+srcsz[0] > self.width): - srcsz[0] = self.width-srct[0] - if (srct[1]+srcsz[1] > self.height): - srcsz[1] = self.height-srct[1] + srcsz = [int((int(size[0]/COURSE+1)*COURSE)/(sc[0]*COURSE))+2, + int((int(size[1]/COURSE+1)*COURSE)/(sc[1]*COURSE))+2] + if (srct[0]+srcsz[0] > self.width): srcsz[0] = self.width-srct[0] + if (srct[1]+srcsz[1] > self.height): srcsz[1] = self.height-srct[1] img = wx.ImageFromBitmap(self.fog_bmp).GetSubImage(wx.Rect(srct[0], srct[1], srcsz[0], srcsz[1])) img.Rescale(srcsz[0]*COURSE*sc[0], srcsz[1]*COURSE*sc[1]) fog = wx.BitmapFromImage(img) @@ -231,8 +222,7 @@ if mode == 'new': if self.fogregion.IsEmpty(): self.fogregion = regn - else: - self.fogregion.UnionRegion(regn) + else: self.fogregion.UnionRegion(regn) self.add_area(area, show) else: if not self.fogregion.IsEmpty(): @@ -262,13 +252,11 @@ 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) - else: - regn = wx.Region(i.left, i.y, i.right+1-i.left, 1) + 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) - else: - regn.Union(i.left, i.y, i.right+1-i.left, 1) + 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 @@ -278,8 +266,7 @@ xml_str = "<map><fog>" xml_str += poly.toxml("new") xml_str += "</fog></map>" - if show == "Yes": - self.canvas.frame.session.send(xml_str) + 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) @@ -289,8 +276,7 @@ xml_str = "<map><fog>" xml_str += poly.toxml("del") xml_str += "</fog></map>" - if show == "Yes": - self.canvas.frame.session.send(xml_str) + 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) @@ -301,8 +287,7 @@ return "" fog_string = "" ri = wx.RegionIterator(self.fogregion) - if not (ri.HaveRects()): - fog_string = FogArea("all", self.log).toxml("del") + if not (ri.HaveRects()): fog_string = FogArea("all", self.log).toxml("del") while ri.HaveRects(): if "__WXGTK__" not in wx.PlatformInfo: x1 = ri.GetX()/COURSE @@ -338,8 +323,7 @@ if not self.use_fog: self.use_fog = True self.recompute_fog() - if xml_dom.hasAttribute('serial'): - self.serial_number = int(xml_dom.getAttribute('serial')) + if xml_dom.hasAttribute('serial'): self.serial_number = int(xml_dom.getAttribute('serial')) children = xml_dom._get_childNodes() for l in children: action = l.getAttribute("action") @@ -364,9 +348,7 @@ polyline.append(IPoint().make(int(x), int(y))) lastx = x lasty = y - if (len(polyline) > 1): - self.createregn2(polyline, action, "No") + if (len(polyline) > 1): self.createregn2(polyline, action, "No") self.fill_fog() - except: - self.log.log(traceback.format_exc(), ORPG_GENERAL) + except: self.log.log(traceback.format_exc(), ORPG_GENERAL) self.log.log("Exit fog_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG)
--- a/orpg/mapper/fog_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/fog_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -55,19 +55,15 @@ def build_menu(self,label = "fog"): base_layer_handler.build_menu(self,label) self.main_menu.AppendSeparator() - item = wx.MenuItem(self.main_menu, wx.ID_ANY, "&Hide All", "Hide All") self.canvas.Bind(wx.EVT_MENU, self.on_hideall, item) self.main_menu.AppendItem(item) - item = wx.MenuItem(self.main_menu, wx.ID_ANY, "&Fog Mask", "Fog Mask") self.canvas.Bind(wx.EVT_MENU, self.on_color, item) self.main_menu.AppendItem(item) - item = wx.MenuItem(self.main_menu, wx.ID_ANY, "&Remove Fog Layer", "Remove Fog Layer") self.canvas.Bind(wx.EVT_MENU, self.on_remove, item) self.main_menu.AppendItem(item) - item = wx.MenuItem(self.main_menu, wx.ID_ANY, "&Pen Color", "Pen Color") self.canvas.Bind(wx.EVT_MENU, self.on_pen_color, item) self.main_menu.AppendItem(item) @@ -121,8 +117,7 @@ if dlg.ShowModal() == wx.ID_OK: data = dlg.GetColourData() color = data.GetColour() - if "__WXGTK__" not in wx.PlatformInfo: - color = wx.Color(color.Red(), color.Green(), color.Blue(), 128) + if "__WXGTK__" not in wx.PlatformInfo: color = wx.Color(color.Red(), color.Green(), color.Blue(), 128) self.canvas.layers['fog'].color = color dlg.Destroy() self.canvas.layers['fog'].fill_fog() @@ -132,7 +127,6 @@ foglayer = self.canvas.layers['fog'] pass - def on_motion(self, evt): scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC(self.canvas) @@ -166,7 +160,8 @@ if (session.my_role() != session.ROLE_GM): open_rpg.get_component("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. + # This code sets the mode to either new or del + # depending on the action to function with the updated createregen code. if (self.fogshow.GetValue() == 1): showmode = 'new' else: @@ -178,15 +173,14 @@ pen= wx.Pen(self.pencolor) pen.SetWidth(COURSE/2+1) dc.SetPen(pen) - dc.DrawLine(self.last.x*scale*COURSE,self.last.y*scale*COURSE,self.line[0].X*scale*COURSE,self.line[0].Y*scale*COURSE) + dc.DrawLine(self.last.x*scale*COURSE,self.last.y*scale*COURSE, + self.line[0].X*scale*COURSE,self.line[0].Y*scale*COURSE) dc.SetPen(wx.NullPen) wx.BeginBusyCursor() - # This prevents the divide by zero error by not even sending the line to be proccessed if it contains less then 3 points - if (len(self.line)>1): - self.canvas.layers['fog'].createregn(self.line, showmode) - else: - #print "Error Divide by zero, ignoring this section" - pass + # This prevents the divide by zero error by not even + # sending the line to be proccessed if it contains less then 3 points + if (len(self.line)>1): self.canvas.layers['fog'].createregn(self.line, showmode) + else: pass wx.EndBusyCursor() del dc self.canvas.Refresh(False)
--- a/orpg/mapper/fog_msg.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/fog_msg.py Fri Jul 31 15:22:11 2009 -0500 @@ -41,10 +41,8 @@ def get_line(self,outline,action,output_act): elem = Element( "poly" ) - if ( output_act ): - elem.setAttribute( "action", action ) - if ( outline == 'all' ) or ( outline == 'none' ): - elem.setAttribute( "outline", outline ) + if ( output_act ): elem.setAttribute( "action", action ) + if ( outline == 'all' ) or ( outline == 'none' ): elem.setAttribute( "outline", outline ) else: elem.setAttribute( "outline", "points" ) for pair in string.split( outline, ";" ): @@ -77,11 +75,9 @@ #print "use_fog :",self.use_fog #print "output_action :",output_action #print "action :",action - if not (self.use_fog): - return "" + if not (self.use_fog): return "" fog_string = "" - if self.fogregion.isEmpty(): - fog_string=self.get_line("all","del",output_action) + if self.fogregion.isEmpty(): fog_string=self.get_line("all","del",output_action) for ri in self.fogregion.GetRectList(): x1=ri.GetX() x2=x1+ri.GetW()-1 @@ -96,8 +92,7 @@ s += ">" s += fog_string s += "</fog>" - else: - s+="/>" + else: s+="/>" return s def interpret_dom(self,xml_dom): @@ -127,10 +122,8 @@ # 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) + if action=="del": self.fogregion.FromPolygon(polyline,0) + else: self.fogregion.FromPolygon(polyline,1) def init_from_dom(self,xml_dom): self.interpret_dom(xml_dom)
--- a/orpg/mapper/grid.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/grid.py Fri Jul 31 15:22:11 2009 -0500 @@ -54,7 +54,8 @@ self.mapscale = 1.0 self.unit_size = 100 self.unit_size_y = 100 - #unit_widest and unit_offset are for the Hex Grid only. these are mathmatics to figure out the exact center of the hex + #unit_widest and unit_offset are for the Hex Grid only. + #These are mathematics to figure out the exact center of the hex self.unit_widest = 100 self.unit_offset = 100 #size_ratio is the size ajustment for Hex and ISO to make them more accurate @@ -107,8 +108,7 @@ x = topLeft.x y = topLeft.y return cmpPoint(int(x),int(y)) # Set the pos attribute - else: - return cmpPoint(int(pos.x),int(pos.y)) + else: return cmpPoint(int(pos.x),int(pos.y)) def set_rect_mode(self): "switch grid to rectangular mode" @@ -150,10 +150,8 @@ def grid_hit_test_rect(self,pos): "return grid pos (w,h) on rect map from pos" - if self.unit_size and self.snap: - return cmpPoint(int(pos.x/self.unit_size), int(pos.y/self.unit_size)) - else: - return None + if self.unit_size and self.snap: return cmpPoint(int(pos.x/self.unit_size), int(pos.y/self.unit_size)) + else: return None def grid_hit_test_hex(self,pos): "return grid pos (w,h) on hex map from pos" @@ -175,21 +173,17 @@ if py < half_height: row = row - 1 py = py + half_height - else: - py = py - half_height + else: py = py - half_height # adjust for top right corner if (px * height - py * hex_side) > height * hex_side: - if col % 2 == 0: - row = row - 1 + if col % 2 == 0: row = row - 1 col = col + 1 # adjust for bottom right corner elif (px * height + py * hex_side) > 2 * height * hex_side: - if col%2==1: - row = row + 1 + if col%2==1: row = row + 1 col = col + 1 return cmpPoint(col, row) - else: - return None + else: return None def grid_hit_test_iso(self,pos): "return grid pos (w,h) on isometric map from pos" @@ -218,8 +212,7 @@ # 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 + else: return None def get_top_corner_iso(self, iso_pos): "return upper left of a iso grid pos" @@ -231,15 +224,12 @@ grid_x = (iso_pos.y*half_width) + (iso_pos.x*half_width) + half_width grid_y = (iso_pos.y*half_height) - (iso_pos.x*half_height) + half_height return cmpPoint(int(grid_x), int(grid_y)) - else: - return None + else: return None def get_top_corner_rect(self,grid_pos): "return upper left of a rect grid pos" - if self.unit_size: - return cmpPoint(grid_pos[0]*self.unit_size,grid_pos[1]*self.unit_size) - else: - return None + if self.unit_size: return cmpPoint(grid_pos[0]*self.unit_size,grid_pos[1]*self.unit_size) + else: return None def get_top_corner_hex(self,grid_pos): "return upper left of a hex grid pos" @@ -251,33 +241,25 @@ if grid_pos[0] % 2: temp_y += self.unit_size/2 return cmpPoint(temp_x,temp_y) - else: - return None + else: return None def set_grid(self, unit_size, snap, color, mode, line, ratio=None): self.unit_size = unit_size - if ratio != None: - self.iso_ratio = ratio + if ratio != None: self.iso_ratio = ratio self.snap = snap self.set_color(color) self.SetMode(mode) self.SetLine(line) def SetLine(self,line): - if line == LINE_NONE: - self.set_line_none() - elif line == LINE_DOTTED: - self.set_line_dotted() - elif line == LINE_SOLID: - self.set_line_solid() + if line == LINE_NONE: self.set_line_none() + elif line == LINE_DOTTED: self.set_line_dotted() + elif line == LINE_SOLID: self.set_line_solid() def SetMode(self, mode): - if mode == GRID_RECTANGLE: - self.set_rect_mode() - elif mode == GRID_HEXAGON: - self.set_hex_mode() - elif mode == GRID_ISOMETRIC: - self.set_iso_mode() + if mode == GRID_RECTANGLE: self.set_rect_mode() + elif mode == GRID_HEXAGON: self.set_hex_mode() + elif mode == GRID_ISOMETRIC: self.set_iso_mode() def return_grid(self): return self.canvas.size @@ -289,10 +271,8 @@ def draw_iso(self,dc,topleft,clientsize): if not self.unit_size: return if self.line == LINE_NONE: return - if self.line == LINE_SOLID: - dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) - else: - dc.SetPen(wx.Pen(self.color,1,wx.DOT)) + if self.line == LINE_SOLID: dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) + else: dc.SetPen(wx.Pen(self.color,1,wx.DOT)) sz = self.canvas.size # Enable DC optimizations if available on a platform @@ -327,12 +307,9 @@ if self.unit_size: draw = 1 # Enable pen/brush optimizations if available on a platform - if self.line == LINE_NONE: - draw = 0 - elif self.line == LINE_SOLID: - dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) - else: - dc.SetPen(wx.Pen(self.color,1,wx.DOT)) + if self.line == LINE_NONE: draw = 0 + elif self.line == LINE_SOLID: dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) + else: dc.SetPen(wx.Pen(self.color,1,wx.DOT)) if draw: sz = self.canvas.size # Enable DC optimizations if available on a platform @@ -360,12 +337,9 @@ if self.unit_size: draw = 1 # Enable pen/brush optimizations if available on a platform - if self.line == LINE_NONE: - draw = 0 - elif self.line == LINE_SOLID: - dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) - else: - dc.SetPen(wx.Pen(self.color,1,wx.DOT)) + if self.line == LINE_NONE: draw = 0 + elif self.line == LINE_SOLID: dc.SetPen(wx.Pen(self.color,1,wx.SOLID)) + else: dc.SetPen(wx.Pen(self.color,1,wx.DOT)) if draw: sz = self.canvas.size x = 0 @@ -419,25 +393,18 @@ (red,green,blue) = self.color.Get() hexcolor = self.r_h.hexstring(red, green, blue) xml_str += " color='" + hexcolor + "'" - if self.unit_size != None: - xml_str += " size='" + str(self.unit_size) + "'" - if self.iso_ratio != None: - xml_str += " ratio='" + str(self.iso_ratio) + "'" + if self.unit_size != None: xml_str += " size='" + str(self.unit_size) + "'" + if self.iso_ratio != None: xml_str += " ratio='" + str(self.iso_ratio) + "'" if self.snap != None: - if self.snap: - xml_str += " snap='1'" - else: - xml_str += " snap='0'" - if self.mode != None: - xml_str+= " mode='" + str(self.mode) + "'" - if self.line != None: - xml_str+= " line='" + str(self.line) + "'" + if self.snap: xml_str += " snap='1'" + else: xml_str += " snap='0'" + if self.mode != None: xml_str+= " mode='" + str(self.mode) + "'" + if self.line != None: xml_str+= " line='" + str(self.line) + "'" xml_str += "/>" if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str - else: - return '' + else: return '' def layerTakeDOM(self, xml_dom): if xml_dom.hasAttribute("color"): @@ -445,17 +412,14 @@ self.set_color(cmpColour(r,g,b)) #backwards compatible with non-isometric map formated clients ratio = RATIO_DEFAULT - if xml_dom.hasAttribute("ratio"): - ratio = xml_dom.getAttribute("ratio") + if xml_dom.hasAttribute("ratio"): ratio = xml_dom.getAttribute("ratio") if xml_dom.hasAttribute("mode"): self.SetMode(int(xml_dom.getAttribute("mode"))) if xml_dom.hasAttribute("size"): self.unit_size = int(xml_dom.getAttribute("size")) self.unit_size_y = self.unit_size if xml_dom.hasAttribute("snap"): - if (xml_dom.getAttribute("snap") == 'True') or (xml_dom.getAttribute("snap") == "1"): - self.snap = True - else: - self.snap = False + if (xml_dom.getAttribute("snap") == 'True') or (xml_dom.getAttribute("snap") == "1"): self.snap = True + else: self.snap = False if xml_dom.hasAttribute("line"): self.SetLine(int(xml_dom.getAttribute("line")))
--- a/orpg/mapper/grid_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/grid_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -93,7 +93,8 @@ return self.canvas.layers['grid'].set_grid(int(self.grid_size.GetValue()),self.grid_snap.GetValue(), - self.color_button.GetBackgroundColour(),self.grid_mode.GetSelection(),self.line_type.GetSelection(),float(self.grid_ratio.GetValue())) + self.color_button.GetBackgroundColour(),self.grid_mode.GetSelection(), + self.line_type.GetSelection(),float(self.grid_ratio.GetValue())) self.update_info() self.canvas.send_map_data() self.canvas.Refresh()
--- a/orpg/mapper/images.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/images.py Fri Jul 31 15:22:11 2009 -0500 @@ -51,21 +51,20 @@ def load(self, path, image_type, imageId): # 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 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 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)) + 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) def directLoad(self, path): # Directly load an image, no threads - if self.__cache.has_key(path): - return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() + 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) @@ -75,32 +74,29 @@ 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) + open_rpg.get_component('log').log("Image refused to load or URI did not reference a valid image: " + path, + ORPG_GENERAL, True) 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) + open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, + ORPG_GENERAL, True) return None def cleanCache(self): # Shrinks the Cache down to the proper size - try: - cacheSize = int(open_rpg.get_component('settings').get_setting("ImageCacheSize")) - except: - cacheSize = 32 + try: cacheSize = int(open_rpg.get_component('settings').get_setting("ImageCacheSize")) + except: cacheSize = 32 cache = self.__cache.keys() cache.sort() - for key in cache[cacheSize:]: - del self.__cache[key] + for key in cache[cacheSize:]: del self.__cache[key] def flushCache(self): # This function will flush all images contained within the image cache. self.__lock.acquire() try: keyList = self.__cache.keys() - for key in keyList: - del self.__cache[key] - finally: - self.__lock.release() + for key in keyList: del self.__cache[key] + finally: self.__lock.release() urllib.urlcleanup() #Private Methods @@ -114,35 +110,35 @@ 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): del self.__fetching[path] else: - open_rpg.get_component('log').log("Image refused to load or URI did not reference a valid image: " + path, ORPG_GENERAL, True) + open_rpg.get_component('log').log("Image refused to load or URI did not reference a valid image: " + path, + ORPG_GENERAL, True) 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) - finally: - self.__lock.release() + open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT laoded: " + path, + ORPG_GENERAL, True) + finally: self.__lock.release() def __loadCacheThread(self, path, image_type, imageId): - try: - st = time.time() - 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) - break - except: - self.__fetching[path] = False - open_rpg.get_component('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, ORPG_GENERAL, True) - return - self.__lock.acquire() - try: - open_rpg.get_component('log').log("Adding Image to Queue from Cache: " + str(self.__cache[path]), ORPG_DEBUG) - self.__queue.put((self.__cache[path], image_type, imageId)) - finally: - self.__lock.release() + if self.__cache.has_key(path): + try: + st = time.time() + 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) + 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) + return + self.__lock.acquire() + try: + open_rpg.get_component('log').log("Adding Image to Queue from Cache: " + str(self.__cache[path]), ORPG_DEBUG) + self.__queue.put((self.__cache[path], image_type, imageId)) + finally: self.__lock.release() #Property Methods def _getCache(self):
--- a/orpg/mapper/map.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/map.py Fri Jul 31 15:22:11 2009 -0500 @@ -59,7 +59,8 @@ self.log.log("Enter MapCanvas", ORPG_DEBUG) self.settings = open_rpg.get_component("settings") self.session = open_rpg.get_component("session") - wx.ScrolledWindow.__init__(self, parent, ID, style=wx.HSCROLL | wx.VSCROLL | wx.FULL_REPAINT_ON_RESIZE | wx.SUNKEN_BORDER ) + wx.ScrolledWindow.__init__(self, parent, ID, + style=wx.HSCROLL | wx.VSCROLL | wx.FULL_REPAINT_ON_RESIZE | wx.SUNKEN_BORDER ) self.frame = parent self.MAP_MODE = 1 #Mode 1 = MINI, 2 = DRAW, 3 = TAPE MEASURE self.layers = {} @@ -160,11 +161,10 @@ if not self.cacheSizeSet: self.cacheSizeSet = True cacheSize = self.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) + 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) if not ImageHandler.Queue.empty(): (path, image_type, imageId) = ImageHandler.Queue.get() img = wx.ImageFromMime(path[1], path[2]).ConvertToBitmap() @@ -175,10 +175,8 @@ min.set_bmp(img) elif image_type == "background" or image_type == "texture": self.layers['bg'].bg_bmp = img - if image_type == "background": - self.set_size([img.GetWidth(), img.GetHeight()]) - except: - pass + if image_type == "background": self.set_size([img.GetWidth(), img.GetHeight()]) + except: pass # Flag that we now need to refresh! self.requireRefresh += 1 @@ -197,23 +195,19 @@ self.lastRefreshValue = 0 self.lastRefreshTime = time.time() self.Refresh(True) - else: - self.lastRefreshValue = self.requireRefresh + 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 self.drag: self.drag.Hide() + if self.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 self.settings.get_setting("AlwaysShowMapScale") == "1": self.printscale() evt.Skip() self.log.log("Exit MapCanvas->on_char(self, evt)", ORPG_DEBUG) @@ -232,8 +226,7 @@ wx.BeginBusyCursor() send_text = self.toxml(action) if send_text: - if not self.isEditor: - self.frame.session.send(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) @@ -244,10 +237,8 @@ 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) + 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() @@ -300,8 +291,10 @@ dc.SetDeviceOrigin(-topleft[0], -topleft[1]) dc.SetUserScale(scale, scale) self.layers['bg'].layerDraw(dc, scale, topleft, clientsize) - self.layers['grid'].layerDraw(dc, [topleft[0]/scale, topleft[1]/scale], [clientsize[0]/scale, clientsize[1]/scale]) - self.layers['miniatures'].layerDraw(dc, [topleft[0]/scale, topleft[1]/scale], [clientsize[0]/scale, clientsize[1]/scale]) + self.layers['grid'].layerDraw(dc, [topleft[0]/scale, topleft[1]/scale], + [clientsize[0]/scale, clientsize[1]/scale]) + self.layers['miniatures'].layerDraw(dc, [topleft[0]/scale, topleft[1]/scale], + [clientsize[0]/scale, clientsize[1]/scale]) self.layers['whiteboard'].layerDraw(dc) self.layers['fog'].layerDraw(dc, topleft, clientsize) dc.SetPen(wx.NullPen) @@ -312,10 +305,8 @@ wdc.DrawBitmap(bmp, topleft[0], topleft[1]) if self.frame.settings.get_setting("AlwaysShowMapScale") == "1": self.showmapscale(wdc) - try: - evt.Skip() - except: - pass + try: evt.Skip() + except: pass self.log.log("Exit MapCanvas->on_paint(self, evt)", ORPG_DEBUG) def preppaint(self): @@ -352,8 +343,7 @@ # This means we need to determine where to snap our line. We will support # snapping to four different snapPoints per square for now. # TODO!!! - if self.layers['grid'].mode == GRID_HEXAGON: - size = self.layers['grid'].unit_size_y + if self.layers['grid'].mode == GRID_HEXAGON: size = self.layers['grid'].unit_size_y else: size = int(self.layers['grid'].unit_size) # Find the uppper left hand corner of the grid we are to snap to @@ -365,15 +355,11 @@ # Now, figure our what quadrant (x, y) we need to snap to snapSize = size / 2 # Figure out the X snap placement - if deltaX <= snapSize: - quadXPos = offsetX - else: - quadXPos = offsetX + size + if deltaX <= snapSize: quadXPos = offsetX + else: quadXPos = offsetX + size # Now, figure out the Y snap placement - if deltaY <= snapSize: - quadYPos = offsetY - else: - quadYPos = offsetY + size + if deltaY <= snapSize: quadYPos = offsetY + 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) @@ -383,10 +369,8 @@ 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)) + 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 @@ -396,14 +380,9 @@ # 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: - # We are positive and NOT zero - a = 360 - atan(slope) * (180.0/pi) - else: - # Slope is negative so work on the abs of it - a = atan(abs(slope)) * (180.0/pi) + 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 @@ -428,15 +407,11 @@ distance = self.calcPixelDistance( start, stop ) ln = "%0.2f" % lineAngle if self.layers['grid'].mode == GRID_HEXAGON: - if ln == "0.00" or ln == "359.99": - ud = distance / self.layers['grid'].unit_size_y - else: - ud = (sqrt(abs((stop.x - start.x)**2 + (stop.y - start.y)**2))) / self.layers['grid'].unit_size_y + if ln == "0.00" or ln == "359.99": ud = distance / self.layers['grid'].unit_size_y + else: ud = (sqrt(abs((stop.x - start.x)**2 + (stop.y - start.y)**2))) / self.layers['grid'].unit_size_y else: - 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 + 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 @@ -551,50 +526,39 @@ # 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) + 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) + 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) + 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) + if evt.ShiftDown(): self.on_tape_up(evt) elif open_rpg.get_component("tree").dragging: tree = open_rpg.get_component("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) + 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 - else: - self.frame.on_motion(evt) + if evt.ShiftDown(): self.on_tape_motion(evt) + elif evt.LeftIsDown() and open_rpg.get_component("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): @@ -681,23 +645,17 @@ 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 + 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 # make label wx.BeginBusyCursor() if self.auto_label: - if min_label == '': - min_label = self.get_label_from_url( min_url ) + if min_label == '': min_label = self.get_label_from_url( min_url ) if not min_unique and self.use_serial: min_label = '%s %d' % ( min_label, self.layers['miniatures'].next_serial() ) - else: - min_label = "" - if self.frame.min_url.FindString(min_url) == -1: - self.frame.min_url.Append(min_url) + else: min_label = "" + if self.frame.min_url.FindString(min_url) == -1: self.frame.min_url.Append(min_url) try: id = 'mini-' + self.frame.session.get_next_id() self.layers['miniatures'].add_miniature(id, min_url, label=min_label) @@ -732,8 +690,7 @@ s = "" keys = self.layers.keys() for k in keys: - if (k != "fog" or action != "update"): - s += self.layers[k].layerToXML(action) + 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) @@ -764,34 +721,23 @@ self.log.log("Exit MapCanvas->takexml(self, xml)", ORPG_DEBUG) 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: self.log.log("Invalid XML format for mapper", ORPG_INFO) else: # set map version to incoming data so layers can convert self.map_version = node_list[0].getAttribute("version") action = node_list[0].getAttribute("action") if action == "new": self.layers = {} - try: - self.layers['bg'] = layer_back_ground(self) - except: - pass - try: - self.layers['grid'] = grid_layer(self) - except: - pass - try: - self.layers['miniatures'] = miniature_layer(self) - except: - pass - try: - self.layers['whiteboard'] = whiteboard_layer(self) - except: - pass - try: - self.layers['fog'] = fog_layer(self) - except: - pass + try: self.layers['bg'] = layer_back_ground(self) + except: pass + try: self.layers['grid'] = grid_layer(self) + except: pass + try: self.layers['miniatures'] = miniature_layer(self) + except: pass + try: self.layers['whiteboard'] = whiteboard_layer(self) + except: pass + try: self.layers['fog'] = fog_layer(self) + except: pass sizex = node_list[0].getAttribute("sizex") if sizex != "": sizex = int(float(sizex)) @@ -808,12 +754,10 @@ #fog layer must be computed first, so that no data is inadvertently revealed for c in children: name = c._get_nodeName() - if name == "fog": - self.layers[name].layerTakeDOM(c) + if name == "fog": self.layers[name].layerTakeDOM(c) for c in children: name = c._get_nodeName() - if name != "fog": - self.layers[name].layerTakeDOM(c) + if name != "fog": self.layers[name].layerTakeDOM(c) # all map data should be converted, set map version to current version self.map_version = MAP_VERSION self.Refresh(False) @@ -829,8 +773,7 @@ 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: self.log.log("Invalid XML format for mapper", ORPG_INFO) else: tmp_map.init_from_dom(node_list[0]) if tmp_map.children.has_key("miniatures"): @@ -852,16 +795,12 @@ if lines: for line in lines: l = whiteboard_layer.children[line] - if l.tagname == 'line': - id = 'line-' + self.frame.session.get_next_id() - elif l.tagname == 'text': - id = 'text-' + self.frame.session.get_next_id() - elif l.tagname == 'circle': - id = 'circle-' + self.frame.session.get_next_id() + if l.tagname == 'line': id = 'line-' + self.frame.session.get_next_id() + elif l.tagname == 'text': id = 'text-' + self.frame.session.get_next_id() + elif l.tagname == 'circle': id = 'circle-' + self.frame.session.get_next_id() l.init_prop("id", id) new_xml = tmp_map.get_all_xml() - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() self.log.log("Exit MapCanvas->re_ids_in_xml(self, xml)", ORPG_DEBUG) return str(new_xml) @@ -892,12 +831,10 @@ self.layer_handlers.append(map_handler(self.layer_tabs,-1,self.canvas)) self.layer_tabs.AddPage(self.layer_handlers[5],"General") self.layer_tabs.SetSelection(2) - self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.EXPAND) self.sizer.Add(self.layer_tabs, 0, wx.EXPAND) self.SetSizer(self.sizer) - self.Bind(FNB.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.on_layer_change) #self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) @@ -905,8 +842,7 @@ self.log.log("Exit map_wnd", ORPG_DEBUG) def OnLeave(self, evt): - if "__WXGTK__" in wx.PlatformInfo: - wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) + 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) @@ -987,14 +923,11 @@ 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 + if layer == self.layer_handlers[i]: self.current_layer = i if self.current_layer == 0: bg = self.layer_handlers[0] - if (self.session.my_role() != self.session.ROLE_GM): - bg.url_path.Show(False) - else: - bg.url_path.Show(True) + if (self.session.my_role() != self.session.ROLE_GM): bg.url_path.Show(False) + 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) @@ -1058,18 +991,12 @@ 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") - elif id == "Whiteboard Layer": - self.current_layer = self.get_tab_index("Whiteboard") - elif id == "Fog Layer": - self.current_layer = self.get_tab_index("Fog") - elif id == "General Properties": - self.current_layer = self.get_tab_index("General") + 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") + elif id == "Whiteboard Layer": self.current_layer = self.get_tab_index("Whiteboard") + 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)
--- a/orpg/mapper/map_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/map_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -67,11 +67,8 @@ if (session.my_role() != session.ROLE_GM): open_rpg.get_component("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("Invalide Map Size!","Map Properties") - return + try: size = (int(self.width.GetValue()),int(self.height.GetValue())) + except: wx.MessageBox("Invalid Map Size!","Map Properties"); return self.canvas.set_size(size) self.update_info() self.canvas.send_map_data()
--- a/orpg/mapper/map_msg.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/map_msg.py Fri Jul 31 15:22:11 2009 -0500 @@ -79,8 +79,7 @@ else: print "Unrecognized tag " + name + " found in map_msg.init_from_dom - skipping" continue - try: - self.children[name].init_from_dom(c) + try: self.children[name].init_from_dom(c) except Exception, e: print "map_msg.init_from_dom() exception: "+str(e) continue @@ -103,21 +102,15 @@ 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 - try: - self.children[name].set_from_dom(c) + try: self.children[name].set_from_dom(c) except Exception, e: print "map_msg.set_from_dom() exception: "+str(e) continue
--- a/orpg/mapper/map_prop_dialog.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/map_prop_dialog.py Fri Jul 31 15:22:11 2009 -0500 @@ -84,19 +84,14 @@ self.ctrls[CTRL_IMAGE].SetValue(False) # Begin ted's changes for map bg persistency. - if bg_layer.bg_color != None: - self.ctrls[CTRL_BG_COLOR_VALUE].SetBackgroundColour(bg_layer.bg_color) + if bg_layer.bg_color != None: self.ctrls[CTRL_BG_COLOR_VALUE].SetBackgroundColour(bg_layer.bg_color) if bg_layer.img_path != None: self.ctrls[CTRL_TEXTURE_PATH].SetValue(bg_layer.img_path) self.ctrls[CTRL_IMAGE_PATH].SetValue(bg_layer.img_path) # End ted's changes - if bg_layer.type == BG_COLOR: - self.ctrls[CTRL_BG_COLOR].SetValue(True) - # self.ctrls[CTRL_BG_COLOR_VALUE].SetBackgroundColour(bg_layer.bg_color) - elif bg_layer.type == BG_TEXTURE: - self.ctrls[CTRL_TEXTURE].SetValue(True) - # self.ctrls[CTRL_TEXTURE_PATH].SetValue(bg_layer.img_path) + if bg_layer.type == BG_COLOR: self.ctrls[CTRL_BG_COLOR].SetValue(True) + elif bg_layer.type == BG_TEXTURE: self.ctrls[CTRL_TEXTURE].SetValue(True) elif bg_layer.type == BG_IMAGE: self.ctrls[CTRL_WIDTH].Enable(False) self.ctrls[CTRL_HEIGHT].Enable(False) @@ -207,31 +202,20 @@ 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 -# dlg = wx.MessageDialog(frame, 'Invalid Size',"Error") -# dlg.ShowModal() -# dlg.Destroy() + try: self.size = (int(self.ctrls[CTRL_WIDTH].GetValue()),int(self.ctrls[CTRL_HEIGHT].GetValue())) + except: pass if self.ctrls[CTRL_BG_COLOR].GetValue() == True: self.bg_layer.set_color(self.ctrls[CTRL_BG_COLOR_VALUE].GetBackgroundColour()) elif self.ctrls[CTRL_TEXTURE].GetValue() == True: self.bg_layer.set_texture(self.ctrls[CTRL_TEXTURE_PATH].GetValue()) elif self.ctrls[CTRL_IMAGE].GetValue() == True: self.size = self.bg_layer.set_image(self.ctrls[CTRL_IMAGE_PATH].GetValue(),self.grid_layer.mapscale) - else: - self.bg_layer.clear() - if self.ctrls[CTRL_GRID_MODE_RECT].GetValue() == True: - grid_mode = GRID_RECTANGLE - else: - grid_mode = GRID_HEXAGON - if self.ctrls[CTRL_GRID_LINE_NONE].GetValue() == True: - grid_line = LINE_NONE - elif self.ctrls[CTRL_GRID_LINE_DOTTED].GetValue() == True: - grid_line = LINE_DOTTED - else: - grid_line = LINE_SOLID + else: self.bg_layer.clear() + if self.ctrls[CTRL_GRID_MODE_RECT].GetValue() == True: grid_mode = GRID_RECTANGLE + else: grid_mode = GRID_HEXAGON + if self.ctrls[CTRL_GRID_LINE_NONE].GetValue() == True: grid_line = LINE_NONE + elif self.ctrls[CTRL_GRID_LINE_DOTTED].GetValue() == True: grid_line = LINE_DOTTED + else: grid_line = LINE_SOLID self.grid_layer.set_grid(int(self.ctrls[CTRL_GRID].GetValue()), self.ctrls[CTRL_GRID_SNAP].GetValue(), self.ctrls[CTRL_GRID_COLOR].GetBackgroundColour(),
--- a/orpg/mapper/map_utils.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/map_utils.py Fri Jul 31 15:22:11 2009 -0500 @@ -44,16 +44,13 @@ yt = float(yt) # Coincident points? - if x1 == x2 and y1 == y2: - d = distance_between(xt, yt, x1, y1) + if x1 == x2 and y1 == y2: d = distance_between(xt, yt, x1, y1) else: dx = x2 - x1 dy = y2 - y1 u = ((xt - x1) * dx + (yt - y1) * dy) / (dx*dx + dy*dy) - if u < 0: - d = distance_between(xt, yt, x1, y1) - elif u > 1: - d = distance_between(xt, yt, x2, y2) + if u < 0: d = distance_between(xt, yt, x1, y1) + elif u > 1: d = distance_between(xt, yt, x2, y2) else: xr = x1 + u * dx yr = y1 + u * dy
--- a/orpg/mapper/min_dialogs.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/min_dialogs.py Fri Jul 31 15:22:11 2009 -0500 @@ -97,10 +97,8 @@ self.listctrl.SetStringItem(self.min.index(m),5,`self.min[self.min.index(m)].pos`) oldcolumnwidth = self.listctrl.GetColumnWidth(0) self.listctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE) - if oldcolumnwidth < self.listctrl.GetColumnWidth(0): - self.listctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE) - else: - self.listctrl.SetColumnWidth(0, oldcolumnwidth) + if oldcolumnwidth < self.listctrl.GetColumnWidth(0): self.listctrl.SetColumnWidth(0, wx.LIST_AUTOSIZE) + else: self.listctrl.SetColumnWidth(0, oldcolumnwidth) self.list_sizer=self.list_sizer def onEdit(self,event): @@ -111,14 +109,11 @@ while True: loop_count += 1 item = self.listctrl.GetNextItem(item,wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) - if item == -1: - break + if item == -1: break min_list.append(self.min[item]) min_index.append(item-loop_count+1) - if len(min_list) > 0: - dlg = min_list_edit_dialog(self.parent,min_index, min_list,self.layers) - if dlg.ShowModal() == wx.ID_OK: - pass + if len(min_list) > 0: dlg = min_list_edit_dialog(self.parent,min_index, min_list,self.layers) + if dlg.ShowModal() == wx.ID_OK: pass self.listctrl.DeleteAllItems() self.refresh() event.Skip() @@ -129,9 +124,7 @@ while True: loop_count += 1 item = self.listctrl.GetNextItem(item,wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) - if item == -1: - break - #self.min.remove(self.min[item-loop_count+1]) + if item == -1: break self.layers["miniatures"].del_miniature(self.min[item-loop_count+1]) self.listctrl.DeleteAllItems() self.refresh() @@ -145,27 +138,24 @@ while True: loop_count += 1 item = self.listctrl.GetNextItem(item,wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) - if item == -1: - break + if item == -1: break min_list.append(self.min[item]) min_index.append(item-loop_count+1) if len(min_list) > 0: for sel_rmin in min_list: -############# + ############# min_xml = sel_rmin.toxml(action="new") node_begin = "<nodehandler module='map_miniature_nodehandler' class='map_miniature_handler' name='" - if sel_rmin.label: - node_begin += sel_rmin.label + "'" - else: - node_begin += "Unnamed Miniature'" + if sel_rmin.label: node_begin += sel_rmin.label + "'" + else: node_begin += "Unnamed Miniature'" node_begin += ">" gametree = open_rpg.get_component('tree') node_xml = node_begin + min_xml + '</nodehandler>' print "Sending this XML to insert_xml:" + node_xml gametree.insert_xml(node_xml) -########## + ############# self.listctrl.DeleteAllItems() self.refresh() event.Skip() @@ -244,22 +234,27 @@ listsizer.Add(wx.StaticText(self, -1, "Path:"), 0, wx.EXPAND) listsizer.Add(self.pathcombo, 0, wx.EXPAND) listsizer.Add(wx.Size(10,10)) - self.heading = wx.RadioBox(self, MIN_HEADING, "Heading", choices=["None","N","NE","E","SE","S","SW","W","NW","no change"], majorDimension=5, style=wx.RA_SPECIFY_COLS) + self.heading = wx.RadioBox(self, MIN_HEADING, "Heading", + choices=["None","N","NE","E","SE","S","SW","W","NW","no change"], majorDimension=5, style=wx.RA_SPECIFY_COLS) self.heading.SetSelection( 9 ) listsizer.Add( self.heading, 0, wx.EXPAND ) listsizer.Add(wx.Size(10,10)) - self.face = wx.RadioBox(self, MIN_FACE, "Facing", choices=["None","N","NE","E","SE","S","SW","W","NW","no change"], majorDimension=5, style=wx.RA_SPECIFY_COLS) + self.face = wx.RadioBox(self, MIN_FACE, "Facing", + choices=["None","N","NE","E","SE","S","SW","W","NW","no change"], majorDimension=5, style=wx.RA_SPECIFY_COLS) self.face.SetSelection(9) listsizer.Add(self.face, 0, wx.EXPAND) -### -### Group together locked, Hide, and snap radioboxes in group2 box -### + ### + ###Group together locked, Hide, and snap radioboxes in group2 box + ### group2 = wx.BoxSizer(wx.HORIZONTAL) - self.locked = wx.RadioBox(self, MIN_LOCK, "Lock", choices=["Don't lock","Lock","no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) + self.locked = wx.RadioBox(self, MIN_LOCK, "Lock", + choices=["Don't lock","Lock","no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) self.locked.SetSelection(2) - self.hide = wx.RadioBox(self, MIN_HIDE, "Hide", choices=["Don't hide", "Hide", "no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) + self.hide = wx.RadioBox(self, MIN_HIDE, "Hide", + choices=["Don't hide", "Hide", "no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) self.hide.SetSelection(2) - self.snap = wx.RadioBox(self,MIN_ALIGN,"Snap",choices=["Center","Top left","no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) + self.snap = wx.RadioBox(self,MIN_ALIGN,"Snap", + choices=["Center","Top left","no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) self.snap.SetSelection(2) group2.Add(self.locked, 0, wx.EXPAND) group2.Add(wx.Size(10,0)) @@ -268,9 +263,9 @@ group2.Add(self.snap, 0, wx.EXPAND) group2.Add(wx.Size(10,0)) listsizer.Add(group2,0,0) -### -### group together the postion radiobox and the and its selection elements -### + ### + ###Group together the postion radiobox and the and its selection elements + ### xpos = int(min_list[0].pos[0]) #xpos = int(`min_list[0].pos`[1:`min_list[0].pos`.index(',')]) ypos = int(min_list[0].pos[1]) @@ -283,7 +278,8 @@ self.scy.SetValue(1) self.scy.SetValue(ypos) positionbox = wx.BoxSizer(wx.HORIZONTAL) - self.poschoice = wx.RadioBox(self,MIN_POS,"Position",choices=["Manual", "Existing", "no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) + self.poschoice = wx.RadioBox(self,MIN_POS,"Position", + choices=["Manual", "Existing", "no change"],majorDimension=1,style=wx.RA_SPECIFY_COLS) self.poschoice.SetSelection(2) positionbox.Add(self.poschoice,0,0) ### @@ -303,9 +299,9 @@ spinbox.Add(self.scy, 0, 0) poschoicebox.Add(wx.Size(0,15)) poschoicebox.Add(spinbox,0,0) - ### - ### kludge is just a way to horizontaly position text. .Add doesn't seem to work. - ### + ### + ### kludge is just a way to horizontaly position text. .Add doesn't seem to work. + ### kluge = wx.BoxSizer(wx.HORIZONTAL) klugetext = wx.StaticText(self, -1, " ") kluge.Add(klugetext,0,0) @@ -330,22 +326,14 @@ def on_ok(self,min): self.min = min for m in self.min_list: - if self.hide.GetSelection() !=2: - m.hide = self.hide.GetSelection() - if self.heading.GetSelection() !=9: - m.heading = self.heading.GetSelection() - if self.face.GetSelection() !=9: - m.face = self.face.GetSelection() - if self.locked.GetSelection() !=2: - m.locked = self.locked.GetSelection() - if self.snap.GetSelection() !=2: - m.snap_to_align = self.snap.GetSelection() + if self.hide.GetSelection() !=2: m.hide = self.hide.GetSelection() + if self.heading.GetSelection() !=9: m.heading = self.heading.GetSelection() + if self.face.GetSelection() !=9: m.face = self.face.GetSelection() + if self.locked.GetSelection() !=2: m.locked = self.locked.GetSelection() + if self.snap.GetSelection() !=2: m.snap_to_align = self.snap.GetSelection() if self.labelcombo.GetValue() != "no change": m.label = self.labelcombo.GetValue() - if self.labelcheck.GetValue(): - m.label += " " + `self.layers['miniatures'].next_serial()` - # self.layers['miniatures'].serial_number +=1 - # m.label += " " + `self.layers['miniatures'].serial_number` + if self.labelcheck.GetValue(): m.label += " " + `self.layers['miniatures'].next_serial()` if self.pathcombo.GetValue() != "no change": path = self.pathcombo.GetValue() image = self.evaluate(path) @@ -356,7 +344,8 @@ image[-1] = -1 while image[1] == -1: image = 0 - self.dlg = wx.TextEntryDialog(self, 'You entered an invalid URL for the image path. Please Enter a valid URL or cancel to leave the old url unchanged') + self.dlg = wx.TextEntryDialog(self, + 'You entered an invalid URL for the image path. Please Enter a valid URL or cancel to leave the old url unchanged') if self.dlg.ShowModal() == wx.ID_OK: path = self.dlg.GetValue() image = self.evaluate(path) @@ -364,11 +353,9 @@ m.path = image[0] m.bmp = image[1] self.dlg.Destroy() - else: - break + else: break if self.poschoice.GetSelection() !=2: - if self.poschoice.GetSelection() == 0: - m.pos = cmpPoint(self.scx.GetValue(),self.scy.GetValue()) + if self.poschoice.GetSelection() == 0: m.pos = cmpPoint(self.scx.GetValue(),self.scy.GetValue()) else: pos = self.positioncombo.GetValue() m.pos = cmpPoint(int(`pos`[2:`pos`.index(",")]),int(`pos`[`pos`.rfind(',')+1:len(`pos`)-2])) @@ -376,17 +363,14 @@ def evaluate(self, ckpath): path = [] - if ckpath[:7] != "http://": - ckpath = "http://" + ckpath + if ckpath[:7] != "http://": ckpath = "http://" + ckpath path = self.check_path(ckpath) return [ckpath, path] def check_path(self, path): - if ImageHandler.Cache.has_key(path): - return ImageHandler.Cache[path] + if ImageHandler.Cache.has_key(path): return ImageHandler.Cache[path] img = ImageHandler.directLoad(path) - if img is None: - return -1 + if img is None: return -1 return img def on_text(self,evt): @@ -432,9 +416,11 @@ sizer.Add(wx.StaticText(self, -1, "Label:"), 0, wx.EXPAND) 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) + 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) 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) + 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) self.face.SetSelection(min.face) self.locked = wx.CheckBox(self, MIN_LOCK, " Lock") self.locked.SetValue(min.locked) @@ -484,12 +470,11 @@ self.Bind(wx.EVT_RADIOBOX, self.on_radio_box, id=MIN_FACE) def on_scaling(self, evt): - if self.min_scaling.GetValue() == False: - return + if self.min_scaling.GetValue() == False: return elif self.min_width.GetValue() and wxID_MIN_WIDTH == evt.GetId() and self.min_width.GetInsertionPoint(): - self.min_height.SetValue ( str(int((float(self.min_width.GetValue()) / float(self.min_width_old_value)) * float(self.min_height_old_value))) ) + self.min_height.SetValue(str(int((float(self.min_width.GetValue()) / float(self.min_width_old_value)) * float(self.min_height_old_value))) ) elif self.min_height.GetValue() and wxID_MIN_HEIGHT == evt.GetId() and self.min_height.GetInsertionPoint(): - self.min_width.SetValue ( str(int((float(self.min_height.GetValue()) / float(self.min_height_old_value)) * float(self.min_width_old_value))) ) + self.min_width.SetValue(str(int((float(self.min_height.GetValue()) / float(self.min_height_old_value)) * float(self.min_width_old_value))) ) def update_min(self): self.min.set_min_props(self.heading.GetSelection(), @@ -514,7 +499,7 @@ class min_edit_dialog(wx.Dialog): def __init__(self,parent,min): -#520,265 + #520,265 wx.Dialog.__init__(self,parent,-1,"Miniature",wx.DefaultPosition,wx.Size(520,350)) (w,h) = self.GetClientSizeTuple() mastersizer = wx.BoxSizer(wx.VERTICAL)
--- a/orpg/mapper/miniatures.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/miniatures.py Fri Jul 31 15:22:11 2009 -0500 @@ -56,16 +56,11 @@ def cmp_zorder(first,second): f = first.zorder s = second.zorder - if f == None: - f = 0 - if s == None: - s = 0 - if f == s: - value = 0 - elif f < s: - value = -1 - else: - value = 1 + if f == None: f = 0 + if s == None: s = 0 + if f == s: value = 0 + elif f < s: value = -1 + else: value = 1 return value class BmpMiniature: @@ -88,14 +83,10 @@ self.local = local self.localPath = localPath self.localTime = localTime - if not width: - self.width = 0 - else: - self.width = width - if not height: - self.height = 0 - else: - self.height = height + if not width: self.width = 0 + else: self.width = width + if not height: self.height = 0 + else: self.height = height self.right = bmp.GetWidth() self.top = 0 self.bottom = bmp.GetHeight() @@ -115,22 +106,20 @@ 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.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 - if locked: - self.locked = True - else: - self.locked = False - if hide: - self.hide = True - else: - self.hide = False + if locked: self.locked = True + else: self.locked = False + if hide: self.hide = True + else: self.hide = False 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) + 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) @@ -162,7 +151,8 @@ tmp_image.Rescale(int(self.width), int(self.height)) tmp_image.ConvertAlphaToMask() self.bmp = tmp_image.ConvertToBitmap() - mask = wx.Mask(self.bmp, wx.Colour(tmp_image.GetMaskRed(), tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) + mask = wx.Mask(self.bmp, wx.Colour(tmp_image.GetMaskRed(), + tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) self.bmp.SetMask(mask) del tmp_image del mask @@ -175,15 +165,13 @@ dc.SetPen(graypen) dc.SetBrush(wx.TRANSPARENT_BRUSH) #if width or height < 20 then offset = 1 - if self.bmp.GetWidth() <= 20: - xoffset = 1 - else: - xoffset = 5 - if self.bmp.GetHeight() <= 20: - yoffset = 1 - else: - yoffset = 5 - dc.DrawRectangle(self.pos.x + xoffset, self.pos.y + yoffset, self.bmp.GetWidth() - (xoffset * 2), self.bmp.GetHeight() - (yoffset * 2)) + if self.bmp.GetWidth() <= 20: xoffset = 1 + else: xoffset = 5 + if self.bmp.GetHeight() <= 20: yoffset = 1 + else: yoffset = 5 + dc.DrawRectangle(self.pos.x + xoffset, + self.pos.y + yoffset, self.bmp.GetWidth() - (xoffset * 2), + self.bmp.GetHeight() - (yoffset * 2)) dc.SetBrush(wx.NullBrush) dc.SetPen(wx.NullPen) ## draw label in the center of the mini @@ -213,9 +201,7 @@ 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: self.log.log("Enter/Exit BmpMiniature->draw->Skip Hidden", ORPG_DEBUG); return True else: self.log.log("Enter BmpMiniature->draw->Not Hidden", ORPG_DEBUG) @@ -226,13 +212,13 @@ tmp_image.Rescale(int(self.width), int(self.height)) tmp_image.ConvertAlphaToMask() self.bmp = tmp_image.ConvertToBitmap() - mask = wx.Mask(self.bmp, wx.Colour(tmp_image.GetMaskRed(), tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) + mask = wx.Mask(self.bmp, wx.Colour(tmp_image.GetMaskRed(), + tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) self.bmp.SetMask(mask) if self.gray: tmp_image = tmp_image.ConvertToGreyscale() bmp = tmp_image.ConvertToBitmap() - else: - bmp = self.bmp + else: bmp = self.bmp dc.DrawBitmap(bmp, self.pos.x, self.pos.y, True) self.left = 0 self.right = self.bmp.GetWidth() @@ -378,9 +364,7 @@ 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 + 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) def toxml(self, action="update"): @@ -397,28 +381,17 @@ if self.pos != None: xml_str += " posx='" + str(self.pos.x) + "'" xml_str += " posy='" + str(self.pos.y) + "'" - if self.heading != None: - xml_str += " heading='" + str(self.heading) + "'" - if self.face != None: - xml_str += " face='" + str(self.face) + "'" - if self.path != None: - xml_str += " path='" + urllib.quote(self.path).replace('%3A', ':') + "'" - if self.locked: - xml_str += " locked='1'" - else: - xml_str += " locked='0'" - if self.hide: - xml_str += " hide='1'" - else: - xml_str += " hide='0'" - if self.snap_to_align != None: - xml_str += " align='" + str(self.snap_to_align) + "'" - if self.id != None: - xml_str += " zorder='" + str(self.zorder) + "'" - if self.width != None: - xml_str += " width='" + str(self.width) + "'" - if self.height != None: - xml_str += " height='" + str(self.height) + "'" + if self.heading != None: xml_str += " heading='" + str(self.heading) + "'" + if self.face != None: xml_str += " face='" + str(self.face) + "'" + if self.path != None: xml_str += " path='" + urllib.quote(self.path).replace('%3A', ':') + "'" + if self.locked: xml_str += " locked='1'" + else: xml_str += " locked='0'" + if self.hide: xml_str += " hide='1'" + else: xml_str += " hide='0'" + if self.snap_to_align != None: xml_str += " align='" + str(self.snap_to_align) + "'" + if self.id != None: xml_str += " zorder='" + str(self.zorder) + "'" + if self.width != None: xml_str += " width='" + str(self.width) + "'" + if self.height != None: xml_str += " height='" + str(self.height) + "'" if self.local: xml_str += ' local="' + str(self.local) + '"' xml_str += ' localPath="' + str(urllib.quote(self.localPath).replace('%3A', ':')) + '"' @@ -429,8 +402,7 @@ if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str - else: - return '' + else: return '' def takedom(self, xml_dom): self.log.log("Enter BmpMiniature->takedom(self, xml_dom)", ORPG_DEBUG) @@ -453,16 +425,12 @@ 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 + 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 + 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") @@ -471,10 +439,8 @@ 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 + 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")) @@ -494,20 +460,16 @@ self.log.log("Enter miniature_layer", ORPG_DEBUG) self.settings = self.canvas.settings layer_base.__init__(self) - self.id = -1 #added. - self.miniatures = [] self.serial_number = 0 # Set the font of the labels to be the same as the chat window # only smaller. font_size = int(self.settings.get_setting('defaultfontsize')) - if (font_size >= 10): - font_size -= 2 + 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) def next_serial(self): @@ -541,10 +503,8 @@ sorted_miniatures.sort(cmp_zorder) i = 0 for mini in sorted_miniatures: - if (mini.zorder != MIN_STICKY_BACK) and (mini.zorder != MIN_STICKY_FRONT): - mini.zorder = i - else: - pass + 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 @@ -554,12 +514,16 @@ 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) + 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) + 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) self.miniatures.append(mini) self.log.log("After mini addition:" + str(self.get_next_highest_z()), ORPG_DEBUG) @@ -567,9 +531,9 @@ 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) + 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) @@ -601,9 +565,7 @@ 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) for m in sorted_miniatures: @@ -619,28 +581,21 @@ min_list = [] for m in self.miniatures: if m.hit_test(pt): - if m.hide and self.canvas.frame.session.my_role() != self.canvas.frame.session.ROLE_GM: - continue - if only_unlocked and not m.locked: - min_list.append(m) - elif not only_unlocked and m.locked: - min_list.append(m) - else: - continue + if m.hide and self.canvas.frame.session.my_role() != self.canvas.frame.session.ROLE_GM: continue + if only_unlocked and not m.locked: min_list.append(m) + 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: self.log.log("Exit miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG); 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) + for m in self.miniatures: minis_string += m.toxml(action) if minis_string != '': s = "<miniatures" s += " serial='" + str(self.serial_number) + "'" @@ -649,9 +604,7 @@ 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: self.log.log("Exit miniature_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG); return "" def layerTakeDOM(self, xml_dom): self.log.log("Enter miniature_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) @@ -661,37 +614,28 @@ for c in children: action = c.getAttribute("action") id = c.getAttribute('id') - if action == "del": + if action == "del": mini = self.get_miniature_by_id(id) if mini: self.miniatures.remove(mini) del mini - else: - self.log.log("Map Synchronization Error :: Update of unknown mini attempted", ORPG_DEBUG) - #wx.MessageBox("Deletion of unknown mini attempted","Map Synchronization Error") + 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')) label = c.getAttribute('label') height = width = heading = face = snap_to_align = zorder = 0 locked = hide = False - if c.hasAttribute('height'): - height = int(c.getAttribute('height')) - if c.hasAttribute('width'): - width = int(c.getAttribute('width')) - if c.getAttribute('locked') == 'True' or c.getAttribute('locked') == '1': - locked = True - if c.getAttribute('hide') == 'True' or c.getAttribute('hide') == '1': - hide = True - if c.getAttribute('heading'): - heading = int(c.getAttribute('heading')) - if c.hasAttribute('face'): - face = int(c.getAttribute('face')) - 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) + if c.hasAttribute('height'): height = int(c.getAttribute('height')) + if c.hasAttribute('width'): width = int(c.getAttribute('width')) + if c.getAttribute('locked') == 'True' or c.getAttribute('locked') == '1': locked = True + if c.getAttribute('hide') == 'True' or c.getAttribute('hide') == '1': hide = True + if c.getAttribute('heading'): heading = int(c.getAttribute('heading')) + if c.hasAttribute('face'): face = int(c.getAttribute('face')) + 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) 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')) @@ -710,11 +654,8 @@ self.collapse_zorder() 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) - #wx.MessageBox("Update of unknown mini attempted","Map Synchronization Error") + 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)): @@ -730,12 +671,11 @@ path = urllib.unquote(path) if not modify: start = path.rfind("/") + 1 - if self.canvas.parent.layer_handlers[2].auto_label: - min_label = path[start:len(path)-4] - else: - min_label = "" + if self.canvas.parent.layer_handlers[2].auto_label: min_label = path[start:len(path)-4] + else: min_label = "" id = 'mini-' + self.canvas.frame.session.get_next_id() - self.add_miniature(id, path, pos=pos, label=min_label, local=True, localPath=filename, localTime=time.time()) + self.add_miniature(id, path, pos=pos, label=min_label, local=True, + localPath=filename, localTime=time.time()) else: self.miniatures[len(self.miniatures)-1].local = True self.miniatures[len(self.miniatures)-1].localPath = filename
--- a/orpg/mapper/miniatures_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/miniatures_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -143,9 +143,9 @@ self.Bind(wx.EVT_CHECKBOX, self.on_label, self.auto_label_cb) 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/', wildcard="Image files (*.bmp, *.gif, *.jpg, *.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) + if not self.role_is_gm_or_player(): return + dlg = wx.FileDialog(None, "Select a Miniature to load", orpg.dirpath.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() return @@ -164,26 +164,20 @@ y = dc.DeviceToLogicalY(0) 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 = 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 # build url - if min_url == "" or min_url == "http://": - return - if min_url[:7] != "http://" : - min_url = "http://" + min_url + if min_url == "" or min_url == "http://": return + if min_url[:7] != "http://": min_url = "http://" + min_url # make label if self.auto_label and min_url[-4:-3] == '.': start = min_url.rfind("/") + 1 min_label = min_url[start:len(min_url)-4] - if self.use_serial: - min_label = '%s %d' % ( min_label, self.canvas.layers['miniatures'].next_serial() ) - else: - min_label = "" - if self.min_url.FindString(min_url) == -1: - self.min_url.Append(min_url) + if self.use_serial: min_label = '%s %d' % ( min_label, self.canvas.layers['miniatures'].next_serial() ) + else: min_label = "" + if self.min_url.FindString(min_url) == -1: self.min_url.Append(min_url) try: id = 'mini-' + self.canvas.frame.session.get_next_id() # make the new mini appear in top left of current viewable map @@ -246,8 +240,7 @@ align_menu.Append(MIN_ALIGN_GRID_CENTER,"&Center") align_menu.Append(MIN_ALIGN_GRID_TL,"&Top-Left") # This is a hack to simulate a menu title, due to problem in Linux - if wx.Platform == '__WXMSW__': - self.min_menu.SetTitle(label) + if wx.Platform == '__WXMSW__': self.min_menu.SetTitle(label) else: self.min_menu.Append(MIN_TITLE_HACK,label) self.min_menu.AppendSeparator() @@ -311,8 +304,7 @@ ######### add plugin added menu items ######### if len(self.mini_rclick_menu_extra_items)>0: self.min_menu.AppendSeparator() - for item in self.mini_rclick_menu_extra_items.items(): - self.min_menu.Append(item[1], item[0]) + for item in self.mini_rclick_menu_extra_items.items(): self.min_menu.Append(item[1], item[0]) if len(self.background_rclick_menu_extra_items)>0: self.main_menu.AppendSeparator() for item in self.background_rclick_menu_extra_items.items(): @@ -330,8 +322,7 @@ try: for m in min_list: # Either use the miniatures label for the selection list - if m.label: - self.min_select_menu.Append(loop_count, m.label) + if m.label: self.min_select_menu.Append(loop_count, m.label) # Or use part of the images filename as an identifier else: string_split = string.split(m.path,"/",) @@ -340,8 +331,7 @@ self.canvas.Bind(wx.EVT_MENU, self.min_selected, id=loop_count) loop_count += 1 self.canvas.PopupMenu(self.min_select_menu,pos) - except: - pass + except: pass def min_selected(self,evt): # this is the callback function for the menu that is used to choose @@ -358,48 +348,45 @@ self.moveSelectedMini(self.last_rclick_pos) self.deselectAndRefresh() return - elif id == MIN_REMOVE: - self.canvas.layers['miniatures'].del_miniature(self.sel_rmin) + elif id == MIN_REMOVE: self.canvas.layers['miniatures'].del_miniature(self.sel_rmin) elif id == MIN_TO_GAMETREE: min_xml = self.sel_rmin.toxml(action="new") node_begin = "<nodehandler module='map_miniature_nodehandler' class='map_miniature_handler' name='" - if self.sel_rmin.label: - node_begin += self.sel_rmin.label + "'" - else: - node_begin += "Unnamed Miniature'" + if self.sel_rmin.label: node_begin += self.sel_rmin.label + "'" + else: node_begin += "Unnamed Miniature'" node_begin += ">" gametree = open_rpg.get_component('tree') node_xml = node_begin + min_xml + '</nodehandler>' #print "Sending this XML to insert_xml:" + node_xml gametree.insert_xml(node_xml) elif id == MIN_SHOW_HIDE: - if self.sel_rmin.hide: - self.sel_rmin.hide = 0 - else: - self.sel_rmin.hide = 1 + if self.sel_rmin.hide: self.sel_rmin.hide = 0 + else: self.sel_rmin.hide = 1 elif id == MIN_LOCK_UNLOCK: - if self.sel_rmin.locked: - self.sel_rmin.locked = False - else: - self.sel_rmin.locked = True + if self.sel_rmin.locked: self.sel_rmin.locked = False + else: self.sel_rmin.locked = True if self.sel_rmin == self.sel_min: # when we lock / unlock the selected mini make sure it isn't still selected # or it might easily get moved by accident and be hard to move back self.sel_min.selected = False self.sel_min.isUpdated = True self.sel_min = None - recycle_bin = {MIN_HEADING_NONE: FACE_NONE, MIN_HEADING_NORTH: FACE_NORTH, MIN_HEADING_NORTHWEST: FACE_NORTHWEST, MIN_HEADING_NORTHEAST: FACE_NORTHEAST, MIN_HEADING_EAST: FACE_EAST, MIN_HEADING_SOUTHEAST: FACE_SOUTHEAST, MIN_HEADING_SOUTHWEST: FACE_SOUTHWEST, MIN_HEADING_SOUTH: FACE_SOUTH, MIN_HEADING_WEST: FACE_WEST} + recycle_bin = {MIN_HEADING_NONE: FACE_NONE, MIN_HEADING_NORTH: FACE_NORTH, + MIN_HEADING_NORTHWEST: FACE_NORTHWEST, MIN_HEADING_NORTHEAST: FACE_NORTHEAST, + MIN_HEADING_EAST: FACE_EAST, MIN_HEADING_SOUTHEAST: FACE_SOUTHEAST, MIN_HEADING_SOUTHWEST: FACE_SOUTHWEST, + MIN_HEADING_SOUTH: FACE_SOUTH, MIN_HEADING_WEST: FACE_WEST} if recycle_bin.has_key(id): self.sel_rmin.heading = recycle_bin[id] - recycle_bin = {} - recycle_bin = {MIN_FACING_NONE: FACE_NONE, MIN_FACING_NORTH: FACE_NORTH, MIN_FACING_NORTHWEST: FACE_NORTHWEST, MIN_FACING_NORTHEAST: FACE_NORTHEAST, MIN_FACING_EAST: FACE_EAST, MIN_FACING_SOUTHEAST: FACE_SOUTHEAST, MIN_FACING_SOUTHWEST: FACE_SOUTHWEST, MIN_FACING_SOUTH: FACE_SOUTH, MIN_FACING_WEST: FACE_WEST} + del recycle_bin + recycle_bin = {MIN_FACING_NONE: FACE_NONE, MIN_FACING_NORTH: FACE_NORTH, + MIN_FACING_NORTHWEST: FACE_NORTHWEST, MIN_FACING_NORTHEAST: FACE_NORTHEAST, + MIN_FACING_EAST: FACE_EAST, MIN_FACING_SOUTHEAST: FACE_SOUTHEAST, MIN_FACING_SOUTHWEST: FACE_SOUTHWEST, + MIN_FACING_SOUTH: FACE_SOUTH, MIN_FACING_WEST: FACE_WEST} if recycle_bin.has_key(id): self.sel_rmin.face = recycle_bin[id] - recycle_bin = {} - elif id == MIN_ALIGN_GRID_CENTER: - self.sel_rmin.snap_to_align = SNAPTO_ALIGN_CENTER - elif id == MIN_ALIGN_GRID_TL: - self.sel_rmin.snap_to_align = SNAPTO_ALIGN_TL + del recycle_bin + elif id == MIN_ALIGN_GRID_CENTER: self.sel_rmin.snap_to_align = SNAPTO_ALIGN_CENTER + elif id == MIN_ALIGN_GRID_TL: self.sel_rmin.snap_to_align = SNAPTO_ALIGN_TL elif id == MIN_PROP_DLG: old_lock_value = self.sel_rmin.locked dlg = min_edit_dialog(self.canvas.frame.GetParent(),self.sel_rmin) @@ -487,16 +474,10 @@ elif id == MIN_FRONTBACK_UNLOCK: #print "Unlocked/ unstickified..." - if self.sel_rmin.zorder == MIN_STICKY_BACK: - self.sel_rmin.zorder = MIN_STICKY_BACK + 1 - elif self.sel_rmin.zorder == MIN_STICKY_FRONT: - self.sel_rmin.zorder = MIN_STICKY_FRONT - 1 - elif id == MIN_LOCK_BACK: - #print "lock back" - self.sel_rmin.zorder = MIN_STICKY_BACK - elif id == MIN_LOCK_FRONT: - #print "lock front" - self.sel_rmin.zorder = MIN_STICKY_FRONT + if self.sel_rmin.zorder == MIN_STICKY_BACK: self.sel_rmin.zorder = MIN_STICKY_BACK + 1 + elif self.sel_rmin.zorder == MIN_STICKY_FRONT: self.sel_rmin.zorder = MIN_STICKY_FRONT - 1 + elif id == MIN_LOCK_BACK: self.sel_rmin.zorder = MIN_STICKY_BACK + elif id == MIN_LOCK_FRONT: self.sel_rmin.zorder = MIN_STICKY_FRONT # Pretty much, we always want to refresh when we go through here # This helps us remove the redundant self.Refresh() on EVERY menu event # that we process above. @@ -511,20 +492,16 @@ return min_url = self.min_url.GetValue() # build url - if min_url == "" or min_url == "http://": - return - if min_url[:7] != "http://" : - min_url = "http://" + min_url + if min_url == "" or min_url == "http://": return + if min_url[:7] != "http://" : min_url = "http://" + min_url # make label if self.auto_label and min_url[-4:-3] == '.': start = min_url.rfind("/") + 1 min_label = min_url[start:len(min_url)-4] if self.use_serial: min_label = '%s %d' % ( min_label, self.canvas.layers['miniatures'].next_serial() ) - else: - min_label = "" - if self.min_url.FindString(min_url) == -1: - self.min_url.Append(min_url) + else: min_label = "" + if self.min_url.FindString(min_url) == -1: self.min_url.Append(min_url) try: id = 'mini-' + self.canvas.frame.session.get_next_id() # make the new mini appear in top left of current viewable map @@ -560,8 +537,7 @@ return #d = min_list_panel(self.frame.GetParent(),self.canvas.layers,"Miniature list") d = min_list_panel(self.canvas.frame,self.canvas.layers,"Miniature list") - if d.ShowModal() == wx.ID_OK: - d.Destroy() + if d.ShowModal() == wx.ID_OK: d.Destroy() self.canvas.Refresh(False) def on_serial(self, evt): @@ -578,23 +554,15 @@ ## old functions, changed an awful lot def on_left_down(self, evt): - if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): - return + if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): return mini = self.find_mini(evt, evt.CmdDown() and self.role_is_gm()) if mini: deselecting_selected_mini = (mini == self.sel_min) #clicked on the selected mini self.deselectAndRefresh() self.drag_mini = mini - if deselecting_selected_mini: - return + if deselecting_selected_mini: return self.sel_min = mini self.sel_min.selected = True - """ - dc = wx.ClientDC(self.canvas) - self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) - self.sel_min.draw(dc, self.canvas.layers['miniatures']) - """ self.canvas.Refresh() else: self.drag_mini = None @@ -603,23 +571,18 @@ self.deselectAndRefresh() def on_right_down(self, evt): - if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): - return + if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): return self.last_rclick_pos = self.getLogicalPosition(evt) mini = self.find_mini(evt, evt.CmdDown() and self.role_is_gm()) if mini: self.sel_rmin = mini - if self.sel_min: - self.min_menu.Enable(MIN_MOVE, True) - else: - self.min_menu.Enable(MIN_MOVE, False) + if self.sel_min: self.min_menu.Enable(MIN_MOVE, True) + else: self.min_menu.Enable(MIN_MOVE, False) self.prepare_mini_rclick_menu(evt) self.do_min_menu(evt.GetPosition()) else:# pass it on - if self.sel_min: - self.main_menu.Enable(MIN_MOVE, True) - else: - self.main_menu.Enable(MIN_MOVE, False) + if self.sel_min: self.main_menu.Enable(MIN_MOVE, True) + else: self.main_menu.Enable(MIN_MOVE, False) self.prepare_background_rclick_menu(evt) base_layer_handler.on_right_down(self, evt) @@ -631,12 +594,11 @@ filepath = filepaths[0] start1 = filepath.rfind("\\") + 1 # check for both slashes in path to be on the safe side start2 = filepath.rfind("/") + 1 - if start1 < start2: - start1 = start2 + if start1 < start2: start1 = start2 filename = filepath[start1:] pos = filename.rfind('.') ext = filename[pos:].lower() - # ext = filename[-4:].lower() + #ext = filename[-4:].lower() if(ext != ".bmp" and ext != ".gif" and ext != ".jpg" and ext != ".jpeg" and ext != ".png"): self.infoPost("Supported file extensions are: *.bmp, *.gif, *.jpg, *.jpeg, *.png") return @@ -662,8 +624,7 @@ if len(mini_list) > 0: tooltip = self.get_mini_tooltip(mini_list) self.canvas.SetToolTipString(tooltip) - else: - self.canvas.SetToolTipString("") + else: self.canvas.SetToolTipString("") def on_motion(self,evt): if evt.Dragging() and evt.LeftIsDown(): @@ -671,10 +632,12 @@ drag_bmp = self.drag_mini.bmp if self.drag_mini.width and self.drag_mini.height: tmp_image = drag_bmp.ConvertToImage() - tmp_image.Rescale(int(self.drag_mini.width * self.canvas.layers['grid'].mapscale), int(self.drag_mini.height * self.canvas.layers['grid'].mapscale)) + tmp_image.Rescale(int(self.drag_mini.width * self.canvas.layers['grid'].mapscale), + int(self.drag_mini.height * self.canvas.layers['grid'].mapscale)) tmp_image.ConvertAlphaToMask() drag_bmp = tmp_image.ConvertToBitmap() - mask = wx.Mask(drag_bmp, wx.Colour(tmp_image.GetMaskRed(), tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) + mask = wx.Mask(drag_bmp, wx.Colour(tmp_image.GetMaskRed(), + tmp_image.GetMaskGreen(), tmp_image.GetMaskBlue())) drag_bmp.SetMask(mask) tmp_image = tmp_image.ConvertToGreyscale() self.drag_mini.gray = True @@ -685,7 +648,8 @@ wx.CallAfter(refresh) self.canvas.drag = wx.DragImage(drag_bmp) self.drag_offset = self.getLogicalPosition(evt)- self.drag_mini.pos - self.canvas.drag.BeginDrag((int(self.drag_offset.x * self.canvas.layers['grid'].mapscale), int(self.drag_offset.y * self.canvas.layers['grid'].mapscale)), self.canvas, False) + self.canvas.drag.BeginDrag((int(self.drag_offset.x * self.canvas.layers['grid'].mapscale), + int(self.drag_offset.y * self.canvas.layers['grid'].mapscale)), self.canvas, False) elif self.canvas.drag is not None: self.canvas.drag.Move(evt.GetPosition()) self.canvas.drag.Show() @@ -705,13 +669,11 @@ if self.canvas.layers['grid'].mode != GRID_ISOMETRIC: if self.drag_mini.snap_to_align == SNAPTO_ALIGN_CENTER: pos = pos + (int(self.drag_mini.bmp.GetWidth()/2),int(self.drag_mini.bmp.GetHeight()/2)) - else: - pos = pos + (nudge, nudge) + else: pos = pos + (nudge, nudge) else:# GRID_ISOMETRIC if self.drag_mini.snap_to_align == SNAPTO_ALIGN_CENTER: pos = pos + (int(self.drag_mini.bmp.GetWidth()/2), self.drag_mini.bmp.GetHeight()) - else: - pass # no nudge for the isomorphic / top-left + else: pass # no nudge for the isomorphic / top-left self.sel_min = self.drag_mini # check to see if the mouse is inside the window still w = self.canvas.GetClientSizeTuple() # this is the window size, minus any scrollbars @@ -729,13 +691,10 @@ self.drag_mini = None def on_left_dclick(self,evt): - if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): - return + if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): return mini = self.find_mini(evt, evt.CmdDown() and self.role_is_gm()) - if mini: - self.on_mini_dclick(evt, mini) - else:# pass it on - base_layer_handler.on_left_dclick(self, evt) + if mini: self.on_mini_dclick(evt, mini) + else: base_layer_handler.on_left_dclick(self, evt) #################################################################### @@ -765,8 +724,7 @@ # mini_handler.sel_rmin.isUpdated = True # canvas.Refresh(False) # canvas.send_map_data() - if callback_function == None: - del self.mini_rclick_menu_extra_items[label] + if callback_function == None: del self.mini_rclick_menu_extra_items[label] else: if not self.mini_rclick_menu_extra_items.has_key(label): self.mini_rclick_menu_extra_items[label]=wx.NewId() @@ -775,8 +733,7 @@ self.build_menu() def set_background_rclick_menu_item(self, label, callback_function): - if callback_function == None: - del self.background_rclick_menu_extra_items[label] + if callback_function == None: del self.background_rclick_menu_extra_items[label] else: if not self.background_rclick_menu_extra_items.has_key(label): self.background_rclick_menu_extra_items[label]=wx.NewId() @@ -800,8 +757,7 @@ def role_is_gm(self): session = self.canvas.frame.session - if (session.my_role() <> session.ROLE_GM) and (session.use_roles()): - return False + if (session.my_role() <> session.ROLE_GM) and (session.use_roles()): return False return True def alreadyDealingWithMenu(self): @@ -827,8 +783,7 @@ mini_list.append(self.sel_min) return mini_list mini_list = self.canvas.layers['miniatures'].find_miniature(pos, (not include_locked)) - if mini_list: - return mini_list + if mini_list: return mini_list mini_list = [] return mini_list @@ -841,29 +796,23 @@ self.sel_min = None def moveSelectedMini(self, pos): - if self.sel_min: - self.moveMini(pos, self.sel_min) + if self.sel_min: self.moveMini(pos, self.sel_min) def moveMini(self, pos, mini): grid = self.canvas.layers['grid'] mini.pos = grid.get_snapped_to_pos(pos, mini.snap_to_align, mini.bmp.GetWidth(), mini.bmp.GetHeight()) def find_mini(self, evt, include_locked): - if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): - return + if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): return pos = self.getLogicalPosition(evt) mini_list = self.getMiniListOrSelectedMini(pos, include_locked) mini = None if len(mini_list) > 1: - try: - self.do_min_select_menu(mini_list, evt.GetPosition()) - except: - pass + try: self.do_min_select_menu(mini_list, evt.GetPosition()) + except: pass choice = self.getLastMenuChoice() - if choice == None: - return None # left menu without making a choice, eg by clicking outside menu + if choice == None: return None # left menu without making a choice, eg by clicking outside menu mini = mini_list[choice] - elif len(mini_list) == 1: - mini = mini_list[0] + elif len(mini_list) == 1: mini = mini_list[0] return mini
--- a/orpg/mapper/miniatures_msg.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/miniatures_msg.py Fri Jul 31 15:22:11 2009 -0500 @@ -36,8 +36,6 @@ self.tagname = "miniature" # set this to be for minis. Tagname gets used in some base class functions. map_element_msg_base.__init__(self,reentrant_lock_object) # call base class - - # convenience method to use if only this mini is modified # outputs a <map/> element containing only the changes to this mini def standalone_update_text(self,update_id_string): @@ -51,13 +49,11 @@ # outputs a <map/> element that deletes this mini def standalone_delete_text(self,update_id_string): buffer = None - if self._props.has_key("id"): buffer = "<map id='" + update_id_string + "'>" buffer += "<miniatures>" buffer += "<miniature action='del' id='" + self._props("id") + "'/>" buffer += "</miniatures></map>" - return buffer # convenience method to use if only this mini is modified @@ -75,8 +71,6 @@ def get_changed_xml(self,action="update",output_action=1): return map_element_msg_base.get_changed_xml(self,action,output_action) - - class minis_msg(map_element_msg_base): def __init__(self,reentrant_lock_object = None): @@ -92,20 +86,12 @@ for c in xml_dom._get_childNodes(): mini = mini_msg(self.p_lock) - - try: - mini.init_from_dom(c) - except Exception, e: - print e - continue - + try: mini.init_from_dom(c) + except Exception, e: print e; continue id = mini.get_prop("id") action = mini.get_prop("action") - - if action == "new": - self.children[id] = mini - + if action == "new": self.children[id] = mini elif action == "del": if self.children.has_key(id): self.children[id] = None @@ -114,14 +100,11 @@ elif action == "update": if self.children.has_key(id): self.children[id].init_props(mini.get_all_props()) - else: self.p_lock.release() raise Exception, "Error attempting to initialize a " + self.tagname + " from a non-<" + self.tagname + "/> element" self.p_lock.release() - - def set_from_dom(self,xml_dom): self.p_lock.acquire() if xml_dom.tagName == self.tagname: @@ -132,27 +115,18 @@ for c in xml_dom._get_childNodes(): mini = mini_msg(self.p_lock) - try: - mini.set_from_dom(c) - except Exception, e: - print e - continue - + try: mini.set_from_dom(c) + except Exception, e: print e; continue id = mini.get_prop("id") action = mini.get_prop("action") - - if action == "new": - self.children[id] = mini - + if action == "new": self.children[id] = mini elif action == "del": if self.children.has_key(id): self.children[id] = None del self.children[id] - elif action == "update": if self.children.has_key(id): self.children[id].set_props(mini.get_all_props()) - else: self.p_lock.release() raise Exception, "Error attempting to set a " + self.tagname + " from a non-<" + self.tagname + "/> element"
--- a/orpg/mapper/region.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/region.py Fri Jul 31 15:22:11 2009 -0500 @@ -42,24 +42,18 @@ self.cx=self.startx self.bottom=0 self.dir = 0 - if self.endx>self.startx: - self.dx = int((self.endx-self.startx)/self.dy) - else: - self.dx = -int((self.startx-self.endx)/self.dy) + if self.endx>self.startx: self.dx = int((self.endx-self.startx)/self.dy) + else: self.dx = -int((self.startx-self.endx)/self.dy) self.error = 0 - if self.endx >= self.startx: - self.inc = (self.endx-self.startx)%self.dy - else: - self.inc = (self.startx-self.endx)%self.dy + if self.endx >= self.startx: self.inc = (self.endx-self.startx)%self.dy + else: self.inc = (self.startx-self.endx)%self.dy def advance(self): self.cx += self.dx self.error += self.inc if (self.error>=self.dy): - if (self.endx<self.startx): - self.cx -= 1 - else: - self.cx += 1 + if (self.endx<self.startx): self.cx -= 1 + else: self.cx += 1 self.error -= self.dy # Utilitarian class for describing a coordinate in 2D space @@ -85,18 +79,15 @@ return self def equals(self,b): - if self.X==b.X and self.Y==b.Y: - return 1 + if self.X==b.X and self.Y==b.Y: return 1 return 0 def less(self,b): - if self.Y<b.Y or (self.Y==b.Y and self.X<b.X): - return 1 + if self.Y<b.Y or (self.Y==b.Y and self.X<b.X): return 1 return 0 def greater(self,b): - if self.Y>b.Y or (self.Y==b.Y and self.X>b.X): - return 1 + if self.Y>b.Y or (self.Y==b.Y and self.X>b.X): return 1 return 0 # generic rectangle class @@ -155,8 +146,7 @@ sel.bottom+=nB def IsValid(self): - if (self.left<=self.right and self.top<=self.bottom): - return 1 + if (self.left<=self.right and self.top<=self.bottom): return 1 return 0 def add(self,pt): @@ -172,8 +162,7 @@ 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 + if (self.top==rect.top and self.bottom==rect.bottom and self.left==rect.left and self.right==rect.right): return 1 return 0 def make(self,l,t,r,b): @@ -213,8 +202,7 @@ def __str__(self): x="[" - for y in self.GetList(): - x+=" "+str(y.bounds)+" " + for y in self.GetList(): x+=" "+str(y.bounds)+" " x+="]" return x @@ -231,42 +219,33 @@ def AddRect(self,rect): rect.prev=None rect.next=self.first - if not (self.first is None): - self.first.prev=rect + if not (self.first is None): self.first.prev=rect self.first=rect - if self.last is None: - self.last=rect + if self.last is None: self.last=rect self.count += 1 #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 - if not (rect.next is None): - rect.next.prev=rect.prev - else: - self.last=rect.prev + if not (rect.prev is None): rect.prev.next=rect.next + else: self.first=rect.next + if not (rect.next is None): rect.next.prev=rect.prev + else: self.last=rect.prev self.count -= 1 # 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 + if self.count==0: return None rect=self.first self.first=rect.next - if (self.first is None): - self.last=None + if (self.first is None): self.last=None self.count -= 1 return rect # 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 pclist.first is None: return if self.first is None: self.first=pclist.first self.last=pclist.last @@ -292,25 +271,17 @@ # efficiency def _hSortCmp(rect1,rect2): - if (rect1.bounds.left<rect2.bounds.left): - return -1 - if (rect1.bounds.left>rect2.bounds.left): - return 1 - if (rect1.bounds.top<rect2.bounds.top): - return -1 - if (rect1.bounds.top>rect2.bounds.top): - return 1 + if (rect1.bounds.left<rect2.bounds.left): return -1 + if (rect1.bounds.left>rect2.bounds.left): return 1 + if (rect1.bounds.top<rect2.bounds.top): return -1 + if (rect1.bounds.top>rect2.bounds.top): return 1 return 0 def _vSortCmp(rect1,rect2): - if (rect1.bounds.top<rect2.bounds.top): - return -1 - if (rect1.bounds.top>rect2.bounds.top): - return 1 - if (rect1.bounds.left<rect2.bounds.left): - return -1 - if (rect1.bounds.left>rect2.bounds.left): - return 1 + if (rect1.bounds.top<rect2.bounds.top): return -1 + if (rect1.bounds.top>rect2.bounds.top): return 1 + if (rect1.bounds.left<rect2.bounds.left): return -1 + if (rect1.bounds.left>rect2.bounds.left): return 1 return 0 # this is the class for which this whole source file is designed! @@ -335,8 +306,7 @@ self.crects.Clear() def isEmpty(self): - if self.crects.first: - return 0 + if self.crects.first: return 0 return 1 def Copy(self,dest): @@ -383,8 +353,7 @@ newclip=self.__AllocClipRect() newclip.bounds=i newlist.AddRect(newclip) - else: - newlist.AddRect(p) + else: newlist.AddRect(p) self.crects.StealRects(newlist) def __IncludeRect(self,rect): @@ -430,8 +399,7 @@ while not (self.crects.first is None): pcclip=self.crects.RemoveHead() hide=rect.intersect(pcclip.bounds) - if not hide.IsValid(): - newlist.AddRect(pcclip) + if not hide.IsValid(): newlist.AddRect(pcclip) else: #make 4 new rectangles to replace the one taken out # @@ -476,8 +444,7 @@ while not self.crects.first is None: pcclip=self.crects.RemoveHead() hide=rect.intersect(pcclip.bounds) - if not hide.IsValid(): - newlist.AddRect(pcclip) + if not hide.IsValid(): newlist.AddRect(pcclip) else: cnew=[IRect().make(pcclip.bounds.left,hide.top,hide.left-1,hide.bottom), IRect().make(hide.right+1,hide.top,pcclip.bounds.right,hide.bottom), @@ -540,8 +507,7 @@ self.crects.RemoveRect(x) self.__FreeClipRect(x) keepgoing=1 - if len(clist)<=1: - break + if len(clist)<=1: break clist.sort(lambda a,b:_hSortCmp(a,b)) keys=range(len(clist)-1) keys.reverse() @@ -563,8 +529,7 @@ if mode: self.__Examine(r) self.__IncludeRect(r) - else: - self.__ExcludeRect(r) + else: self.__ExcludeRect(r) self.Optimize() def GetRectList(self): @@ -605,18 +570,12 @@ result.append(ISpan(sx,ex,polypt[i].Y)) size = len(polylines) for i in xrange(size): - if i == 0 and polylines[i].dir == -1: - n = size-1 - elif (polylines[i].dir == -1): - n = i-1 - else: - n = (i+1) % size - if (polylines[i].dir != polylines[n].dir): #find out if at bottom end - polylines[i].bottom = 1 - if i == 0 or polylines[i].starty < y: - y = polylines[i].starty - if not ET.has_key(polylines[i].starty): - ET[polylines[i].starty] = [] + if i == 0 and polylines[i].dir == -1: n = size-1 + elif (polylines[i].dir == -1): n = i-1 + else: n = (i+1) % size + if (polylines[i].dir != polylines[n].dir): polylines[i].bottom = 1 + if i == 0 or polylines[i].starty < y: y = polylines[i].starty + if not ET.has_key(polylines[i].starty): ET[polylines[i].starty] = [] ET[polylines[i].starty].append(polylines[i]) #add to edge table, indexed by smaller y coordinate AET = [] #active edge table while len(AET) > 0 or len(ET) > 0:
--- a/orpg/mapper/whiteboard.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/whiteboard.py Fri Jul 31 15:22:11 2009 -0500 @@ -34,16 +34,11 @@ def cmp_zorder(first,second): f = first.zorder s = second.zorder - if f == None: - f = 0 - if s == None: - s = 0 - if f == s: - value = 0 - elif f < s: - value = -1 - else: - value = 1 + if f == None: f = 0 + if s == None: s = 0 + if f == s: value = 0 + elif f < s: value = -1 + else: value = 1 return value class WhiteboardText: @@ -103,14 +98,10 @@ 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 - try: - dc.SetTextForeground(textcolor) - except Exception,e: - dc.SetTextForeground('#000000') + if self.highlighted: textcolor = self.highlight_color + else: textcolor = self.textcolor + try: dc.SetTextForeground(textcolor) + except Exception,e: dc.SetTextForeground('#000000') dc.SetUserScale(self.scale, self.scale) # Draw text @@ -130,28 +121,20 @@ xml_str = "<text" xml_str += " action='" + action + "'" xml_str += " id='" + str(self.id) + "'" - if self.pointsize != None: - xml_str += " pointsize='" + str(self.pointsize) + "'" - if self.style != None: - xml_str += " style='" + str(self.style) + "'" - if self.weight != None: - xml_str += " weight='" + str(self.weight) + "'" - if self.posx != None: - xml_str+= " posx='" + str(self.posx) + "'" - if not (self.posy is None): - xml_str += " posy='" + str(self.posy) + "'" - if self.text_string != None: - xml_str+= " text_string='" + self.text_string + "'" - if self.textcolor != None: - xml_str += " color='" + self.textcolor + "'" + if self.pointsize != None: xml_str += " pointsize='" + str(self.pointsize) + "'" + if self.style != None: xml_str += " style='" + str(self.style) + "'" + if self.weight != None: xml_str += " weight='" + str(self.weight) + "'" + if self.posx != None: xml_str+= " posx='" + str(self.posx) + "'" + if not (self.posy is None): xml_str += " posy='" + str(self.posy) + "'" + 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 '' + else: return '' def takedom(self, xml_dom): self.log.log("Enter WhiteboardText->takedom(self, xml_dom)", ORPG_DEBUG) @@ -179,8 +162,7 @@ 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' + 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) @@ -190,8 +172,7 @@ self.log.log("Enter WhiteboardLine", ORPG_DEBUG) self.scale = 1 self.r_h = RGBHex() - if color == '': - color = "#000000" + if color == '': color = "#000000" self.linecolor = color self.linewidth = width self.lowerright = lowerright @@ -209,7 +190,8 @@ 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): + 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) self.line_string = line_string self.upperleft.x = upperleftx @@ -241,15 +223,11 @@ 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 + if self.highlighted: linecolor = self.highlight_color + else: linecolor = self.linecolor pen = wx.BLACK_PEN - try: - pen.SetColour(linecolor) - except Exception,e: - pen.SetColour('#000000') + try: pen.SetColour(linecolor) + except Exception,e: pen.SetColour('#000000') pen.SetWidth( self.linewidth ) dc.SetPen( pen ) dc.SetBrush(wx.BLACK_BRUSH) @@ -262,8 +240,7 @@ points = x.split(",") x1 = int(points[0]) y1 = int(points[1]) - if x2 != -999: - dc.DrawLine(x2,y2,x1,y1) + if x2 != -999: dc.DrawLine(x2,y2,x1,y1) x2 = x1 y2 = y1 pen.SetColour(wx.Colour(0,0,0)) @@ -298,8 +275,7 @@ 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 + if action == "new": return xml_str return '' def takedom(self, xml_dom): @@ -443,10 +419,8 @@ 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) + 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): @@ -457,8 +431,7 @@ 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) + 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 @@ -470,8 +443,7 @@ 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) + 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 @@ -552,11 +524,9 @@ 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) + for l in self.lines: white_string += l.toxml(action) if self.texts: - for l in self.texts: - white_string += l.toxml(action) + for l in self.texts: white_string += l.toxml(action) if len(white_string): s = "<whiteboard" s += " serial='" + str(self.serial_number) + "'" @@ -573,8 +543,7 @@ 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) + if serial_number != "": self.serial_number = int(serial_number) children = xml_dom._get_childNodes() for l in children: nodename = l._get_nodeName() @@ -583,18 +552,13 @@ if action == "del": 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) + 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) + 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: @@ -606,8 +570,7 @@ upperleft = wx.Point(int(upperleftx),int(upperlefty)) lowerright = wx.Point(int(lowerrightx),int(lowerrighty)) color = l.getAttribute('color') - if color == '#0000000': - color = '#000000' + if color == '#0000000': color = '#000000' id = l.getAttribute('id') width = int(l.getAttribute('width')) except: @@ -624,8 +587,7 @@ pointsize = l.getAttribute('pointsize') weight = l.getAttribute('weight') color = l.getAttribute('color') - if color == '#0000000': - color = '#000000' + if color == '#0000000': color = '#000000' id = l.getAttribute('id') posx = l.getAttribute('posx') posy = l.getAttribute('posy') @@ -641,24 +603,20 @@ 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 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) + 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) + line = WhiteboardLine(0, line_string, wx.Point(0,0), wx.Point(0,0), + color=self.color, width=self.width, log=self.log) self.lines.append(line) return line def del_temp_line(self, line): - if line: - self.lines.remove(line) + if line: self.lines.remove(line)
--- a/orpg/mapper/whiteboard_handler.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/whiteboard_handler.py Fri Jul 31 15:22:11 2009 -0500 @@ -67,7 +67,8 @@ self.radius.SetValue("15") 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= 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" self.sizer.Add(wx.StaticText(self, wx.ID_ANY, "Line Width: "),0,wx.ALIGN_CENTER) self.sizer.Add(self.widthList, 0, wx.EXPAND) @@ -103,7 +104,8 @@ 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) @@ -159,14 +161,10 @@ def on_text_properties(self,evt): text_string = self.text_control.GetValue() - if self.style_control.GetStringSelection() == 'Normal': - style = wx.NORMAL - else: - style = wx.ITALIC - if self.weight_control.GetStringSelection() == 'Normal': - weight = wx.NORMAL - else: - weight = wx.BOLD + if self.style_control.GetStringSelection() == 'Normal': style = wx.NORMAL + else: style = wx.ITALIC + if self.weight_control.GetStringSelection() == 'Normal': weight = wx.NORMAL + else: weight = wx.BOLD point = str(self.point_control.GetValue()) c = self.text_color_control.GetForegroundColour() color = self.canvas.layers['whiteboard'].r_h.hexstring(c.Red(), c.Green(), c.Blue()) @@ -195,21 +193,16 @@ self.text_color_control.SetForegroundColour(self.text_selected_item.textcolor) self.text_control.SetValue(self.text_selected_item.text_string) self.point_control.SetValue(int(self.text_selected_item.pointsize)) - if int(self.text_selected_item.weight) == wx.NORMAL: - self.weight_control.SetSelection(0) - else: - self.weight_control.SetSelection(1) + if int(self.text_selected_item.weight) == wx.NORMAL: self.weight_control.SetSelection(0) + else: self.weight_control.SetSelection(1) - if int(self.text_selected_item.style) == wx.NORMAL: - self.style_control.SetSelection(0) - else: - self.style_control.SetSelection(1) + if int(self.text_selected_item.style) == wx.NORMAL: self.style_control.SetSelection(0) + else: self.style_control.SetSelection(1) self.text_properties_dialog.Center() self.text_properties_dialog.Show(True) def do_text_menu(self, pos, items=None): - if items == None: - self.canvas.PopupMenu(self.text_menu) + if items == None: self.canvas.PopupMenu(self.text_menu) else: menu = wx.Menu() self.ItemList = items @@ -224,8 +217,7 @@ id = evt.GetId()-1 self.text_selected_item = self.ItemList[id] self.text_selected_item.selected = True - if self.tmpPos == 'right': - self.canvas.PopupMenu(self.text_menu) + if self.tmpPos == 'right': self.canvas.PopupMenu(self.text_menu) self.ItemList = None self.tmpPos = None @@ -236,8 +228,7 @@ self.canvas.PrepareDC(dc) dc.SetUserScale(scale,scale) pos = evt.GetLogicalPosition(dc) - if self.drawing_mode == 'Text': - self.on_text_right_down(evt, dc) + if self.drawing_mode == 'Text': self.on_text_right_down(evt, dc) elif self.drawing and ((self.drawing_mode == 'Circle') or (self.drawing_mode == 'Cone')): self.check_draw_mode() self.drawing = False @@ -248,10 +239,8 @@ if self.sel_rline: self.do_line_menu(evt.GetPosition()) self.canvas.Refresh(False) - else: - base_layer_handler.on_right_down(self,evt) - else: - base_layer_handler.on_right_down(self,evt) + else: base_layer_handler.on_right_down(self,evt) + else: base_layer_handler.on_right_down(self,evt) del dc def on_pen_color(self,evt): @@ -286,8 +275,7 @@ open_rpg.get_component("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) - if dlg.ShowModal() != wx.ID_YES: - return + if dlg.ShowModal() != wx.ID_YES: return self.canvas.layers['whiteboard'].del_all_lines() dc = self.create_dc() self.un_highlight(dc) @@ -324,8 +312,7 @@ self.line_string = "0,0;" if self.temp_circle: self.canvas.layers['whiteboard'].del_temp_line(self.temp_circle) - if self.selected == self.temp_circle: - self.selected = None + if self.selected == self.temp_circle: self.selected = None self.canvas.Refresh(True) self.temp_circle = None self.cone_start = None @@ -334,22 +321,14 @@ # drawing modes freeform vs polyline # 05-09-2003 Snowdog def on_left_down(self,evt): - if not self.drawing: - self.check_draw_mode() - if self.drawing_mode == 'Freeform': - #Freeform mode ignores the inital down click - pass - elif self.drawing_mode == 'Polyline': - self.polyline_add_point( evt ) - elif self.drawing_mode == 'Text': - self.on_text_left_down(evt) + if not self.drawing: self.check_draw_mode() + if self.drawing_mode == 'Freeform': pass + elif self.drawing_mode == 'Polyline': self.polyline_add_point( evt ) + elif self.drawing_mode == 'Text': self.on_text_left_down(evt) elif self.drawing_mode == 'Cone': - if self.cone_start == None: - self.on_start_cone(evt) - else: - self.draw_temporary_cone(evt) - elif self.drawing_mode == 'Circle': - self.draw_temporary_circle(evt) + if self.cone_start == None: self.on_start_cone(evt) + else: self.draw_temporary_cone(evt) + elif self.drawing_mode == 'Circle': self.draw_temporary_circle(evt) # Added handling for double clicks within the map # 05-09-2003 Snowdog @@ -357,10 +336,8 @@ if self.drawing_mode == 'Freeform': #Freeform mode ignores the double click pass - elif self.drawing_mode == 'Polyline': - self.polyline_last_point( evt ) - elif self.drawing_mode == 'Text': - pass + elif self.drawing_mode == 'Polyline': self.polyline_last_point( evt ) + elif self.drawing_mode == 'Text': pass elif self.drawing_mode == 'Circle' or self.drawing_mode == 'Cone': self.canvas.layers['whiteboard'].del_temp_line(self.temp_circle) #pointArray = self.temp_circle.line_string.split(";") @@ -373,14 +350,9 @@ # drawing modes freeform vs polyline # 05-09-2003 Snowdog def on_left_up(self,evt): - if self.drawing_mode == 'Freeform': - self.on_freeform_left_up(evt) - elif self.drawing_mode == 'Polyline': - #Polyline mode relies on the down click - #not the mouse button release - pass - elif self.drawing_mode == 'Text': - pass + if self.drawing_mode == 'Freeform': self.on_freeform_left_up(evt) + elif self.drawing_mode == 'Polyline': pass + elif self.drawing_mode == 'Text': pass # Altered on_left_up to toggle between # drawing modes freeform vs polyline @@ -392,23 +364,18 @@ and (session.use_roles()): return if self.drawing_mode == 'Freeform': - if evt.m_leftDown: - self.freeform_motion(evt) + if evt.m_leftDown: self.freeform_motion(evt) elif self.drawing_mode == 'Polyline': - if self.drawing: - self.polyline_preview( evt ) + if self.drawing: self.polyline_preview( evt ) dc = self.create_dc() pos = evt.GetLogicalPosition(dc) hit = self.canvas.layers['whiteboard'].hit_test_lines(pos,dc) - if hit: - self.highlight(hit,dc) + if hit: self.highlight(hit,dc) else: self.un_highlight(dc) hit = self.canvas.layers['whiteboard'].hit_test_text(pos,dc) - if hit: - self.highlight(hit,dc) - else: - self.un_highlight(dc) + if hit: self.highlight(hit,dc) + else: self.un_highlight(dc) del dc def create_dc(self): @@ -441,14 +408,10 @@ dc.SetUserScale(scale,scale) pos = evt.GetLogicalPosition(dc) #reset the bounding points - if pos.x < self.upperleft.x: - self.upperleft.x = pos.x - elif pos.x > self.lowerright.x: - self.lowerright.x = pos.x - if pos.y < self.upperleft.y: - self.upperleft.y = pos.y - elif pos.y > self.lowerright.y: - self.lowerright.y = pos.y + if pos.x < self.upperleft.x: self.upperleft.x = pos.x + elif pos.x > self.lowerright.x: self.lowerright.x = pos.x + if pos.y < self.upperleft.y: self.upperleft.y = pos.y + elif pos.y > self.lowerright.y: self.lowerright.y = pos.y #if this point doens't end the line #add a new point into the line string @@ -467,9 +430,7 @@ self.drawing = True else: #end of line. Send and reset vars for next line self.drawing = False - if self.polypoints < 2: - #not enough points to form a line. Ignore line - pass + if self.polypoints < 2: pass else: #have enough points to create valid line #check to role to make sure user can draw at all.... @@ -477,9 +438,7 @@ 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") self.canvas.Refresh(False) - else: - #user allowed to draw on whiteboard.. send polyline - line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) + else: line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) #resetting variables for next line self.upperleft.x = self.upperleft.y = 0 self.lowerright.x = self.lowerright.y = 0 @@ -491,30 +450,23 @@ # 05-09-2003 Snowdog def polyline_last_point(self, evt): #if we haven't started a line already. Ignore the click - if self.drawing != True: - return + if self.drawing != True: return scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc ) dc.SetUserScale(scale,scale) pos = evt.GetLogicalPosition(dc) #reset the bounding points - if pos.x < self.upperleft.x: - self.upperleft.x = pos.x - elif pos.x > self.lowerright.x: - self.lowerright.x = pos.x - if pos.y < self.upperleft.y: - self.upperleft.y = pos.y - elif pos.y > self.lowerright.y: - self.lowerright.y = pos.y + if pos.x < self.upperleft.x: self.upperleft.x = pos.x + elif pos.x > self.lowerright.x: self.lowerright.x = pos.x + if pos.y < self.upperleft.y: self.upperleft.y = pos.y + elif pos.y > self.lowerright.y: self.lowerright.y = pos.y self.polypoints += 1 #add one to the point counter. self.line_string += `pos.x` + "," + `pos.y` + ";" self.canvas.layers['whiteboard'].draw_working_line(dc,self.line_string) #end of line. Send and reset vars for next line self.drawing = False - if self.polypoints < 2: - #not enough points to form a line. Ignore line - pass + if self.polypoints < 2: pass else: #have enough points to create valid line #check to role to make sure user can draw at all.... @@ -522,9 +474,7 @@ 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") self.canvas.Refresh(False) - else: - #user allowed to draw on whiteboard.. send polyline - line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) + else: line = self.canvas.layers['whiteboard'].add_line(self.line_string,self.upperleft,self.lowerright) #resetting variables for next line self.upperleft.x = self.upperleft.y = 0 self.lowerright.x = self.lowerright.y = 0 @@ -546,17 +496,10 @@ tol = 5 #first point check - if type(self.lastpoint) == type(None): - self.lastpoint = wx.Point(pos.x,pos.y) - return 0 #not end of line - if ((self.lastpoint.x -tol) <= pos.x <= (self.lastpoint.x)): - x_in = 1 - if ((self.lastpoint.y -tol) <= pos.y <= (self.lastpoint.y)): - y_in = 1 - if x_in and y_in: - #point within tolerance. End line - self.lastpoint = None - return 1 + if type(self.lastpoint) == type(None): self.lastpoint = wx.Point(pos.x,pos.y); return 0 #not end of line + if ((self.lastpoint.x -tol) <= pos.x <= (self.lastpoint.x)): x_in = 1 + if ((self.lastpoint.y -tol) <= pos.y <= (self.lastpoint.y)): y_in = 1 + if x_in and y_in: self.lastpoint = None; return 1 #if we've reached here the point is NOT a terminal point. Reset the lastpoint and return False self.lastpoint.x = pos.x self.lastpoint.y = pos.y @@ -567,12 +510,8 @@ # from the last point to mouse position # 05-09-2003 Snowdog def polyline_preview(self, evt): - if self.drawing != True: - #not enough points to form a line. Ignore line - return - if self.live_refresh.GetValue() == 0: - #not using live redraw - return + if self.drawing != True: return + if self.live_refresh.GetValue() == 0: return scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc ) @@ -580,14 +519,10 @@ pos = evt.GetLogicalPosition(dc) #reset the bounding points - if pos.x < self.upperleft.x: - self.upperleft.x = pos.x - elif pos.x > self.lowerright.x: - self.lowerright.x = pos.x - if pos.y < self.upperleft.y: - self.upperleft.y = pos.y - elif pos.y > self.lowerright.y: - self.lowerright.y = pos.y + if pos.x < self.upperleft.x: self.upperleft.x = pos.x + elif pos.x > self.lowerright.x: self.lowerright.x = pos.x + if pos.y < self.upperleft.y: self.upperleft.y = pos.y + elif pos.y > self.lowerright.y: self.lowerright.y = pos.y #redraw the line with a line connected to the cursor temp_string = self.line_string @@ -606,14 +541,10 @@ self.canvas.PrepareDC( dc ) dc.SetUserScale(scale,scale) pos = evt.GetLogicalPosition(dc) - if pos.x < self.upperleft.x: - self.upperleft.x = pos.x - elif pos.x > self.lowerright.x: - self.lowerright.x = pos.x - if pos.y < self.upperleft.y: - self.upperleft.y = pos.y - elif pos.y > self.lowerright.y: - self.lowerright.y = pos.y + if pos.x < self.upperleft.x: self.upperleft.x = pos.x + elif pos.x > self.lowerright.x: self.lowerright.x = pos.x + if pos.y < self.upperleft.y: self.upperleft.y = pos.y + elif pos.y > self.lowerright.y: self.lowerright.y = pos.y if evt.m_leftDown: if self.drawing == True: self.line_string += `pos.x` + "," + `pos.y` + ";" @@ -663,8 +594,7 @@ pos = evt.GetLogicalPosition(dc) test_text = self.canvas.layers['whiteboard'].hit_test_text(pos,dc) if len(test_text) > 0: - if len(test_text) > 1: - self.do_text_menu('left', test_text) + if len(test_text) > 1: self.do_text_menu('left', test_text) else: self.text_selected_item = test_text[0] self.text_selected_item.selected = True @@ -674,7 +604,8 @@ dlg = wx.TextEntryDialog(self,"Text to add to whiteboard", caption="Enter text",defaultValue=" ") if dlg.ShowModal() == wx.ID_OK: text_string = dlg.GetValue() - self.canvas.layers['whiteboard'].add_text(text_string,pos, self.style, self.pointsize, self.weight, self.canvas.layers['whiteboard'].color) + self.canvas.layers['whiteboard'].add_text(text_string,pos, self.style, + self.pointsize, self.weight, self.canvas.layers['whiteboard'].color) else: self.text_selected_item.posx = pos.x self.text_selected_item.posy = pos.y @@ -693,8 +624,7 @@ pos = evt.GetLogicalPosition(dc) test_text = self.canvas.layers['whiteboard'].hit_test_text(pos, dc) if len(test_text) > 0: - if len(test_text) > 1: - self.do_text_menu('right', test_text) + if len(test_text) > 1: self.do_text_menu('right', test_text) else: self.text_selected_item = test_text[0] self.do_text_menu('right') @@ -728,23 +658,19 @@ pos = evt.GetLogicalPosition(dc) pos2 = self.get_snapped_to_logical_pos(evt) size = self.canvas.layers['grid'].unit_size #60 - if abs(pos.x-pos2.x)<=size/10 and abs(pos.y-pos2.y)<=size/10: - pos = pos2 + if abs(pos.x-pos2.x)<=size/10 and abs(pos.y-pos2.y)<=size/10: pos = pos2 radius = int(int(self.radius.GetValue())/5) curve = self.calculate_circle(self.cone_start, radius, size) edge1 = [] edge2 = [] horizontal_inc = wx.Point(size,0) - if pos.x <= self.cone_start.x: - horizontal_inc = wx.Point(-size,0) + if pos.x <= self.cone_start.x: horizontal_inc = wx.Point(-size,0) vertical_inc = wx.Point(0,size) - if pos.y <= self.cone_start.y: - vertical_inc = wx.Point(0,-size) + if pos.y <= self.cone_start.y: vertical_inc = wx.Point(0,-size) x_diff = float(pos.x - self.cone_start.x) y_diff = float(pos.y - self.cone_start.y) ratio = float(1) - if abs(x_diff) <= abs(y_diff): - ratio = x_diff / y_diff + if abs(x_diff) <= abs(y_diff): ratio = x_diff / y_diff elif abs(y_diff) < abs(x_diff): ratio = -(y_diff / x_diff) horizontal_inc,vertical_inc = vertical_inc,horizontal_inc #swap @@ -815,8 +741,7 @@ curve = `pos.x`+","+`pos.y`+";" + curve + `qos.x`+","+`qos.y`+";" if(self.temp_circle): self.canvas.layers['whiteboard'].del_temp_line(self.temp_circle) - if self.selected == self.temp_circle: - self.selected = None + if self.selected == self.temp_circle: self.selected = None self.temp_circle = self.canvas.layers['whiteboard'].add_temp_line(curve) self.canvas.Refresh(True)
--- a/orpg/mapper/whiteboard_msg.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/mapper/whiteboard_msg.py Fri Jul 31 15:22:11 2009 -0500 @@ -71,6 +71,7 @@ def get_changed_xml(self,action="update",output_action=1): return map_element_msg_base.get_changed_xml(self,action,output_action) + class whiteboard_msg(map_element_msg_base): def __init__(self,reentrant_lock_object = None): @@ -85,22 +86,19 @@ self.init_prop(k,xml_dom.getAttribute(k)) for c in xml_dom._get_childNodes(): item = item_msg(self.p_lock,c._get_nodeName()) - try: - item.init_from_dom(c) + try: item.init_from_dom(c) except Exception, e: print e continue id = item.get_prop("id") action = item.get_prop("action") - if action == "new": - self.children[id] = item + if action == "new": self.children[id] = item elif action == "del": if self.children.has_key(id): self.children[id] = None del self.children[id] elif action == "update": - if self.children.has_key(id): - self.children[id].init_props(item.get_all_props()) + if self.children.has_key(id): self.children[id].init_props(item.get_all_props()) else: self.p_lock.release() raise Exception, "Error attempting to initialize a " + self.tagname + " from a non-<" + self.tagname + "/> element in whiteboard" @@ -114,22 +112,19 @@ self.set_prop(k,xml_dom.getAttribute(k)) for c in xml_dom._get_childNodes(): item = item_msg(self.p_lock, c._get_nodeName()) - try: - item.set_from_dom(c) + try: item.set_from_dom(c) except Exception, e: print e continue id = item.get_prop("id") action = item.get_prop("action") - if action == "new": - self.children[id] = item + if action == "new": self.children[id] = item elif action == "del": if self.children.has_key(id): self.children[id] = None del self.children[id] elif action == "update": - if self.children.has_key(id): - self.children[id].set_props(item.get_all_props()) + if self.children.has_key(id): self.children[id].set_props(item.get_all_props()) else: self.p_lock.release() raise Exception, "Error attempting to set a " + self.tagname + " from a non-<" + self.tagname + "/> element"
--- a/orpg/minidom.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/minidom.py Fri Jul 31 15:22:11 2009 -0500 @@ -43,14 +43,12 @@ if Node._debug: index = repr(id(self)) + repr(self.__class__) Node.allnodes[index] = repr(self.__dict__) - if Node.debug is None: - Node.debug = StringIO() + if Node.debug is None: Node.debug = StringIO() #open( "debug4.out", "w" ) Node.debug.write("create %s\n" % index) def __getattr__(self, key): - if key[0:2] == "__": - raise AttributeError + if key[0:2] == "__": raise AttributeError # getattr should never call getattr! if self.__dict__.has_key("inGetAttr"): del self.inGetAttr @@ -67,10 +65,8 @@ raise AttributeError, key else: self.inGetAttr = 1 - try: - func = getattr(self, "_get_" + key) - except AttributeError: - raise AttributeError, key + try: func = getattr(self, "_get_" + key) + except AttributeError: raise AttributeError, key del self.inGetAttr return func() @@ -83,26 +79,21 @@ return str(writer.getvalue()) def hasChildNodes(self): - if self.childNodes: - return 1 - else: - return 0 + if self.childNodes: return 1 + else: return 0 def getChildren(self): return self.childNodes def _get_firstChild(self): - if self.hasChildNodes(): - return self.childNodes[0] - else: - return None + if self.hasChildNodes(): return self.childNodes[0] + else: return None def _get_lastChild(self): return self.childNodes[-1] def insertBefore(self, newChild, refChild): - if refChild == None: - return self.appendChild(newChild) + if refChild == None: return self.appendChild(newChild) index = self.childNodes.index(refChild) self.childNodes.insert(index, newChild) if self._makeParentNodes: @@ -115,8 +106,7 @@ last = self.lastChild node.previousSibling = last last.nextSibling = node - else: - node.previousSibling = None + else: node.previousSibling = None node.nextSibling = None node.ownerDocument = self.ownerDocument node.parentNode = self @@ -136,8 +126,7 @@ def cloneNode(self, deep=0): newNode = Node() - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode def deep_clone(self, newNode): @@ -163,8 +152,7 @@ i = i - 1 del self.childNodes[i] continue - elif cn.nodeType == Node.ELEMENT_NODE: - cn.normalize() + elif cn.nodeType == Node.ELEMENT_NODE: cn.normalize() i = i + 1 def unlink(self): @@ -176,8 +164,7 @@ self.previousSibling = None self.nextSibling = None if self.attributes: - for attr in self._attrs.values(): - self.removeAttributeNode(attr) + for attr in self._attrs.values(): self.removeAttributeNode(attr) assert not len(self._attrs) assert not len(self._attrsNS) if Node._debug: @@ -223,17 +210,14 @@ # nodeValue and value are set elsewhere def __setattr__(self, name, value): - if name in ("value", "nodeValue"): - self.__dict__["value"] = self.__dict__["nodeValue"] = value - else: - self.__dict__[name] = value + if name in ("value", "nodeValue"): self.__dict__["value"] = self.__dict__["nodeValue"] = value + else: self.__dict__[name] = value def cloneNode(self, deep=0): newNode = Attr(self.__dict__["name"],self.__dict__["namespaceURI"], self.__dict__["localName"],self.__dict__["prefix"]) newNode.__dict__["value"] = newNode.__dict__["nodeValue"] = self.value - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode class AttributeList: @@ -250,10 +234,8 @@ return clone def item(self, index): - try: - return self[self.keys()[index]] - except IndexError: - return None + try: return self[self.keys()[index]] + except IndexError: return None def items(self): return map(lambda node: (node.tagName, node.value), @@ -276,17 +258,13 @@ return self.length def __cmp__(self, other): - if self._attrs is getattr(other, "_attrs", None): - return 0 - else: - return cmp(id(self), id(other)) + if self._attrs is getattr(other, "_attrs", None): return 0 + else: return cmp(id(self), id(other)) #FIXME: is it appropriate to return .value? def __getitem__(self, attname_or_tuple): - if type(attname_or_tuple) is types.TupleType: - return self._attrsNS[attname_or_tuple] - else: - return self._attrs[attname_or_tuple] + if type(attname_or_tuple) is types.TupleType: return self._attrsNS[attname_or_tuple] + else: return self._attrs[attname_or_tuple] # same as set def __setitem__(self, attname, value): @@ -297,8 +275,7 @@ assert isinstance(value, Attr) or type(value) is types.StringType node = value old = self._attrs.get(attname, None) - if old: - old.unlink() + if old: old.unlink() self._attrs[node.name] = node self._attrsNS[(node.namespaceURI, node.localName)] = node @@ -332,8 +309,7 @@ for k in keys: attr = self._attrs[k].cloneNode(1) newNode.setAttributeNode(attr) - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode def _get_tagName(self): @@ -341,16 +317,12 @@ def getAttributeKeys(self): result = [] - if self._attrs: - return self._attrs.keys() - else: - return None + if self._attrs: return self._attrs.keys() + else: return None def getAttribute(self, attname): - if self.hasAttribute(attname): - return str(self._attrs[attname].value) - else: - return "" + if self.hasAttribute(attname): return str(self._attrs[attname].value) + else: return "" def getAttributeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)].value @@ -377,8 +349,7 @@ def setAttributeNode(self, attr): old = self._attrs.get(attr.name, None) - if old: - old.unlink() + if old: old.unlink() self._attrs[attr.name] = attr self._attrsNS[(attr.namespaceURI, attr.localName)] = attr # FIXME: return old value if something changed @@ -432,8 +403,7 @@ if self.childNodes[0].nodeType == Node.TEXT_NODE: tab_str = "" writer.write(tab_str + "</%s>" % self.tagName) - else: - writer.write("/>") + else: writer.write("/>") def _get_attributes(self): return AttributeList(self._attrs, self._attrsNS) @@ -452,8 +422,7 @@ def cloneNode(self, deep=0): newNode = Comment(self.data) - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode class ProcessingInstruction(Node): @@ -470,8 +439,7 @@ def cloneNode(self, deep=0): newNode = ProcessingInstruction(self.target, self.data) - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode class Text(Node): @@ -484,10 +452,8 @@ self.attributes = None def __repr__(self): - if len(self.data) > 10: - dotdotdot = "..." - else: - dotdotdot = "" + if len(self.data) > 10: dotdotdot = "..." + else: dotdotdot = "" return "<DOM Text node \"%s%s\">" % (self.data[0:10], dotdotdot) def writexml(self, writer, tabs=0): @@ -501,16 +467,13 @@ def cloneNode(self, deep=0): newNode = Text(self.data) - if deep: - self.deep_clone(newNode) + if deep: self.deep_clone(newNode) return newNode def _nssplit(qualifiedName): fields = string.split(qualifiedName,':', 1) - if len(fields) == 2: - return fields - elif len(fields) == 1: - return ('', fields[0]) + if len(fields) == 2: return fields + elif len(fields) == 1: return ('', fields[0]) class Document(Node): nodeType = Node.DOCUMENT_NODE @@ -525,10 +488,8 @@ def appendChild(self, node): if node.nodeType == Node.ELEMENT_NODE: - if self.documentElement: - raise TypeError, "Two document elements disallowed" - else: - self.documentElement = node + if self.documentElement: raise TypeError, "Two document elements disallowed" + else: self.documentElement = node Node.appendChild(self, node) return node createElement = Element @@ -558,8 +519,7 @@ return rc def writexml(self, writer): - for node in self.childNodes: - node.writexml(writer) + for node in self.childNodes: node.writexml(writer) def _doparse(func, args, kwargs): events = apply(func, args, kwargs)
--- a/orpg/networking/mplay_server_gui.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/networking/mplay_server_gui.py Fri Jul 31 15:22:11 2009 -0500 @@ -91,7 +91,7 @@ def __init__(self, owner ): """ Loads default configuration settings. """ - OPENRPG_PORT = 9775 + OPENRPG_PORT = 9557 self.owner = owner def load_xml(self, xml): @@ -122,8 +122,7 @@ if type(mesg) == types.TupleType: func, msg = mesg event = MessageFunctionEvent( func, msg ) - else: - event = MessageLogEvent( mesg ) + else: event = MessageLogEvent( mesg ) wx.PostEvent( self.conf.owner, event ) del event @@ -132,8 +131,7 @@ self.server = mplay_server(self.log, self.serverName ) self.server.initServer(bootPassword=self.bootPwd, reg="No") self.alive = 1 - while self.alive: - time.sleep(3) + while self.alive: time.sleep(3) def stop(self): """ Stop the server. """ @@ -190,8 +188,8 @@ self.SetStringItem( i, 3, "ROOM" ) self.SetStringItem( i, 4, self.stripHtml( player["version"] ) ) self.SetStringItem( i, 5, self.stripHtml( player["role"] ) ) - self.SetStringItem( i, 6, self.stripHtml( player["ip"] ) ) - self.SetStringItem (i, 7, "PING" ) + self.SetStringItem( i, 6, self.stripHtml( player["ip"] ) ) + self.SetStringItem (i, 7, "PING" ) self.SetItemData( i, int(player["id"]) ) self.AutoAjust() @@ -207,8 +205,8 @@ self.SetColumnWidth(3, -1) self.SetColumnWidth(4, -1) self.SetColumnWidth(5, -1) - self.SetColumnWidth(6, -1) - self.SetColumnWidth(7, -1) + self.SetColumnWidth(6, -1) + self.SetColumnWidth(7, -1) self.Refresh() def update(self, player): @@ -217,8 +215,7 @@ self.SetStringItem(i, 1, player["name"]) self.SetStringItem(i, 2, self.stripHtml( player["status"] ) ) self.AutoAjust() - else: - self.add(player) + else: self.add(player) def updateRoom( self, data ): (from_id, id) = data @@ -237,14 +234,10 @@ in_tag = 0 for x in range( len(name) ): if name[x] == "<" or name[x] == ">" or in_tag == 1 : - if name[x] == "<" : - in_tag = 1 - elif name[x] == ">" : - in_tag = 0 - else : - pass - else : - ret_string = ret_string + name[x] + if name[x] == "<": in_tag = 1 + elif name[x] == ">": in_tag = 0 + else: pass + else: ret_string = ret_string + name[x] return ret_string # When we right click, cause our popup menu to appear @@ -271,14 +264,13 @@ elif menuItem == MENU_PLAYER_SEND_MESSAGE: print "send a message..." msg = self.GetMessageInput( "Send a message to player" ) - if len(msg): - self.main.server.server.send( msg, playerID, str(groupID) ) -# Leave this in for now. -# elif menuItem == MENU_PLAYER_SEND_TO_ROOM: -# 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, GroupID, msg ) + if len(msg): self.main.server.server.send( msg, playerID, str(groupID) ) + #Leave this in for now. + #elif menuItem == MENU_PLAYER_SEND_TO_ROOM: + # 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, GroupID, msg ) elif menuItem == MENU_PLAYER_SEND_SERVER_MESSAGE: print "broadcast a message..." @@ -299,10 +291,8 @@ 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( 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 ) self.SetIcon(icon) self.serverName = "Server Name" self.bootPwd = "" @@ -395,7 +385,8 @@ nb = wx.Notebook( splitter, -1 ) self.conns = Connections( nb, self ) nb.AddPage( self.conns, "Players" ) -#Not sure why this is Remarked TaS - Sirebral + + #Not sure why this is Remarked TaS - Sirebral #nb.AddPage( self.conns, "Rooms" ) #self.msgWindow = HTMLMessageWindow( nb ) #nb.AddPage( self.msgWindow, "Messages" ) @@ -463,12 +454,12 @@ def OnCreateGroup( self, data ): print "room list: ", self.conns.roomList self.conns.roomList[id] = name - (id, name) = data + (id, name) = data print "room list: ", self.conns.roomList def OnDeleteGroup( self, data ): (from_id, id) = data -# del self.conns.roomList[id] + #del self.conns.roomList[id] print "OnDeleteGroup room list: ", self.conns.roomList, id def OnJoinGroup( self, data ): @@ -484,12 +475,10 @@ if self.STATUS == SERVER_STOPPED: serverNameEntry = wx.TextEntryDialog( self, "Please Enter The Server Name You Wish To Use:", "Server's Name", self.serverName, wx.OK|wx.CANCEL|wx.CENTRE ) - if serverNameEntry.ShowModal() == wx.ID_OK: - self.serverName = serverNameEntry.GetValue() + if serverNameEntry.ShowModal() == wx.ID_OK: self.serverName = serverNameEntry.GetValue() 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 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) @@ -501,8 +490,7 @@ self.mainMenu.Enable( MENU_STOP_SERVER, True ) self.mainMenu.Enable( MENU_REGISTER_SERVER, True ) wx.EndBusyCursor() - else: - self.show_error("Server is already running.", "Error Starting Server") + else: self.show_error("Server is already running.", "Error Starting Server") def OnStop(self, event = None): """ Stop server. """
--- a/orpg/orpg_version.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/orpg_version.py Fri Jul 31 15:22:11 2009 -0500 @@ -4,7 +4,7 @@ #BUILD NUMBER FORMAT: "YYMMDD-##" where ## is the incremental daily build index (if needed) DISTRO = "Traipse" DIS_VER = "Grumpy Goblin" -BUILD = "090724-00" +BUILD = "090731-00" # This version is for network capability. PROTOCOL_VERSION = "1.2"
--- a/orpg/orpg_windows.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/orpg_windows.py Fri Jul 31 15:22:11 2009 -0500 @@ -43,12 +43,9 @@ img_type = self.get_type(path) try: data = urllib.urlretrieve(path) - if data: - img = wx.Bitmap(data[0], img_type) - else: - raise IOError, "Image refused to load!" - except IOError, e: - img = None + if data: img = wx.Bitmap(data[0], img_type) + else: raise IOError, "Image refused to load!" + except IOError, e: img = None return img def load_file(self,path): @@ -60,12 +57,11 @@ ext = string.lower(file_name[pos+1:]) img_type = 0 # TaS - sirebral. Replaces 10 lines with 6 lines. - recycle_bin = {"gif": wx.BITMAP_TYPE_GIF, "jpg": wx.BITMAP_TYPE_JPEG, "jpeg": wx.BITMAP_TYPE_JPEG, "bmp": wx.BITMAP_TYPE_BMP, "png": wx.BITMAP_TYPE_PNG} - if recycle_bin.has_key(ext): - img_type = recycle_bin[ext] - else: - img_type = None ## this was imf_type = None. imf? - recycle_bin = {}; return img_type + recycle_bin = {"gif": wx.BITMAP_TYPE_GIF, "jpg": wx.BITMAP_TYPE_JPEG, + "jpeg": wx.BITMAP_TYPE_JPEG, "bmp": wx.BITMAP_TYPE_BMP, "png": wx.BITMAP_TYPE_PNG} + if recycle_bin.has_key(ext): img_type = recycle_bin[ext] + else: img_type = None ## this was imf_type = None. imf? + del recycle_bin; return img_type ################################ ## Tabs @@ -85,10 +81,11 @@ tabbedwindows.append(self) open_rpg.add_component("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, 'slanted&colorful': FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS, 'slant&colorful': FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS} + 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, + 'slanted&colorful': FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS, 'slant&colorful': FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS} nbstyle |= theme_dict[tabtheme] - if style: - nbstyle |= style + if style: nbstyle |= style self.SetWindowStyleFlag(nbstyle) #Tas - sirebral. Planned changes to the huge statement below. @@ -179,8 +176,7 @@ (screen_x,screen_y) = wx.GetMousePosition() (x,y) = self.ScreenToClientXY(screen_x,screen_y) # translate coordinates (w,h) = self.GetSizeTuple() - if x >= 0 and x < w and y >= 0 and y < h: - self.OnMotion(x,y) + if x >= 0 and x < w and y >= 0 and y < h: self.OnMotion(x,y) event.Skip() def OnMotion(self,mouse_X,mouse_Y): @@ -276,21 +272,17 @@ def on_text_format(self,event): id = event.GetId() - if wx.Platform == '__WXMSW__': - txt = self.text.GetLabel() - else: - txt = self.text.GetValue() + if wx.Platform == '__WXMSW__': txt = self.text.GetLabel() + else: txt = self.text.GetValue() (beg,end) = self.text.GetSelection() - if beg != end: - sel_txt = txt[beg:end] - else: - return + if beg != end: sel_txt = txt[beg:end] + else: return print txt # TaS - sirebral. Replaces 6 lines with 4 lines. recycle_bin = {self.BOLD: "b", self.ITALIC: "i", self.UNDER: "u"} if recycle_bin.has_key(id): sel_txt = "<" + recycle_bin[id] + ">" + sel_txt + "</" + recycle_bin[id] + ">" - recycle_bin = {} + del recycle_bin elif id == self.COLOR: hexcolor = self.r_h.do_hex_color_dlg(self) @@ -299,11 +291,8 @@ self.color_button.SetBackgroundColour(hexcolor) txt = txt[:beg] + sel_txt + txt[end:] - # print txt - if wx.Platform == '__WXMSW__': - txt = self.text.SetLabel(txt) - else: - txt = self.text.SetValue(txt) + if wx.Platform == '__WXMSW__': txt = self.text.SetLabel(txt) + else: txt = self.text.SetValue(txt) self.text.SetInsertionPoint(beg) self.text.SetFocus() self.callback(wx.Event(self.text.GetId())) @@ -336,10 +325,8 @@ if address[:4] == "http": self.load_url(address) self.local = 0 - elif address[0] == "#" or self.local: - self.base_OnLinkClicked(linkinfo) - else: - self.load_url(self.path+address) + elif address[0] == "#" or self.local: self.base_OnLinkClicked(linkinfo) + else: self.load_url(self.path+address) def load_url(self,path): print path @@ -352,9 +339,7 @@ self.SetPage(file.read()) i = string.rfind(path,"/") self.path = path[:i+1] - except: - wx.MessageBox("Invalid URL","Browser Error",wx.OK) - #self.SetPage("<h3>Invalid URL</h3>") + except: wx.MessageBox("Invalid URL","Browser Error",wx.OK) dlg.Update(3) dlg.Destroy() @@ -373,8 +358,7 @@ sizers = { 'ctrls' : wx.BoxSizer(wx.VERTICAL), 'buttons' : wx.BoxSizer(wx.HORIZONTAL) } self.opts = opts self.list = wx.CheckListBox(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,opts) - for s in selected: - self.list.Check(s,1) + for s in selected: self.list.Check(s,1) sizers['ctrls'].Add(wx.StaticText(self, -1, text), 0, 0) sizers['ctrls'].Add(wx.Size(10,10)) sizers['ctrls'].Add(self.list, 1, wx.EXPAND) @@ -390,8 +374,7 @@ def on_ok(self,evt): checked = [] for i in range(len(self.opts)): - if self.list.IsChecked(i): - checked.append(i) + if self.list.IsChecked(i): checked.append(i) self.checked = checked self.EndModal(wx.ID_OK) @@ -432,8 +415,7 @@ self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK) def on_ok(self,evt): - for i in range(len(self.ctrls)): - self.vlist[i] = self.ctrls[i].GetValue() + for i in range(len(self.ctrls)): self.vlist[i] = self.ctrls[i].GetValue() self.EndModal(wx.ID_OK) def get_values(self): @@ -537,8 +519,7 @@ def Update(self,pos,text=None): self.gauge.SetValue(pos) - if text: - self.text.SetLabel(text) + if text: self.text.SetLabel(text) ######################### #status frame window @@ -590,10 +571,8 @@ self.connect_status = connect def Notify(self, event): - if self.window == 1: - self.bar0() - elif self.window == 2: - self.bar1() + if self.window == 1: self.bar0() + elif self.window == 2: self.bar1() pass def bar1(self): @@ -633,8 +612,7 @@ dlg.Centre() dlg.Show(1) dlg.Raise() - else: - dlg = wx.ProgressDialog(title,text,range,parent) + else: dlg = wx.ProgressDialog(title,text,range,parent) return dlg def parseXml_with_dlg(parent,s,ownerDocument=None):
--- a/orpg/orpg_xml.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/orpg_xml.py Fri Jul 31 15:22:11 2009 -0500 @@ -53,10 +53,8 @@ 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], '{?}') + try: txt = txt.replace(txt[i], '&#' + str(ord(txt[i])) + ';') + except: txt = txt.replace(txt[i], '{?}') return txt def strip_text(txt): @@ -65,10 +63,7 @@ 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" + 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
--- a/orpg/player_list.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/player_list.py Fri Jul 31 15:22:11 2009 -0500 @@ -78,8 +78,9 @@ 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 ) + ##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') @@ -198,7 +199,8 @@ self.chat = open_rpg.get_component("chat") boot_pwd = self.password_manager.GetPassword("admin",int(self.session.group_id)) if boot_pwd != None: - alter_pwd_dialog = wx.TextEntryDialog(self,"Enter new room password: (blank for no password)","Alter Room Password") + alter_pwd_dialog = wx.TextEntryDialog(self, + "Enter new room password: (blank for no password)","Alter Room Password") if alter_pwd_dialog.ShowModal() == wx.ID_OK: new_pass = alter_pwd_dialog.GetValue() self.chat.InfoPost( "Requesting password change on server..." ) @@ -255,10 +257,8 @@ try: self.wgMenu.Remove(WG_MENU_LIST[mid]["menuid"]) WG_MENU_LIST[mid]["menu"].Destroy() - except: - self.wgMenu.UpdateUI() - if self.wgMenu.GetMenuItemCount() == 2: - WG_MENU_LIST.clear() + except: self.wgMenu.UpdateUI() + if self.wgMenu.GetMenuItemCount() == 2: WG_MENU_LIST.clear() return def on_menu_whispergroup( self, evt ): @@ -275,23 +275,13 @@ group_name = create_new_group_dialog.GetValue() WG_LIST[group_name] = {} return - elif id == PLAYER_WG_CLEAR_ALL: - WG_LIST.clear() - return + elif id == PLAYER_WG_CLEAR_ALL: WG_LIST.clear(); return #Check Sub Menus for mid in WG_MENU_LIST: - if id == WG_MENU_LIST[mid]["add"]: - WG_LIST[mid][int(item.GetText())] = int(item.GetText()) - return - elif id == WG_MENU_LIST[mid]["remove"]: - del WG_LIST[mid][int(item.GetText())] - return - elif id == WG_MENU_LIST[mid]["clear"]: - WG_LIST[mid].clear() - return - elif id == WG_MENU_LIST[mid]["whisper"]: - self.chat.set_chat_text("/gw " + mid + "=") - return + if id == WG_MENU_LIST[mid]["add"]: WG_LIST[mid][int(item.GetText())] = int(item.GetText()); return + elif id == WG_MENU_LIST[mid]["remove"]: del WG_LIST[mid][int(item.GetText())]; return + elif id == WG_MENU_LIST[mid]["clear"]: WG_LIST[mid].clear(); return + elif id == WG_MENU_LIST[mid]["whisper"]: self.chat.set_chat_text("/gw " + mid + "="); return return #--------------------------------------------------------- @@ -368,8 +358,7 @@ if id == PLAYER_BOOT: id = str(self.GetItemData(self.selected_item)) boot_pwd = self.password_manager.GetPassword("admin",int(self.session.group_id)) - if boot_pwd != None: - self.session.boot_player(id,boot_pwd) + 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") @@ -378,17 +367,15 @@ id = str(self.GetItemData(self.selected_item)) self.chat = open_rpg.get_component("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")) - else: - self.chat.Post(self.chat.colorize(self.chat.syscolor, "Player " + name + " with ID:" + id +" now being ignored")) + if result == 0: self.chat.Post(self.chat.colorize(self.chat.syscolor, + "Player " + name + " with ID:" + id +" no longer ignored")) + else: self.chat.Post(self.chat.colorize(self.chat.syscolor, + "Player " + name + " with ID:" + id +" now being ignored")) elif id == PLAYER_SHOW_VERSION: id = str(self.GetItemData(self.selected_item)) version_string = self.session.players[id][6] - if version_string: - wx.MessageBox("Running client version " + version_string,"Version") - else: - wx.MessageBox("No client version available for this player","Version") + if version_string: wx.MessageBox("Running client version " + version_string,"Version") + else: wx.MessageBox("No client version available for this player","Version") def on_menu(self, evt): pos = wx.Point(evt.GetX(),evt.GetY()) @@ -396,7 +383,7 @@ if item > -1: 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. + # 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": # self.menu.Enable(PLAYER_BOOT,0) # self.menu.SetLabel(PLAYER_BOOT,"Can't boot from Lobby") @@ -408,12 +395,9 @@ #--------------------------------------------------------- self.menu.Enable(PLAYER_WG_MENU, True) item = self.GetItem( self.selected_item ) - if len(WG_MENU_LIST) > len(WG_LIST): - self.clean_sub_menus() - if len(WG_LIST) == 0: - self.wgMenu.Enable(PLAYER_WG_CLEAR_ALL, False) - else: - self.wgMenu.Enable(PLAYER_WG_CLEAR_ALL, True) + if len(WG_MENU_LIST) > len(WG_LIST): self.clean_sub_menus() + if len(WG_LIST) == 0: self.wgMenu.Enable(PLAYER_WG_CLEAR_ALL, False) + else: self.wgMenu.Enable(PLAYER_WG_CLEAR_ALL, True) for gid in WG_LIST: if not WG_MENU_LIST.has_key(gid): WG_MENU_LIST[gid] = {} @@ -474,8 +458,7 @@ # [START] Digitalxero Multi Whisper Group 1/1/05 #--------------------------------------------------------- for gid in WG_LIST: - if WG_LIST[gid].has_key(int(player[2])): - del WG_LIST[gid][int(player[2])] + if WG_LIST[gid].has_key(int(player[2])): del WG_LIST[gid][int(player[2])] #--------------------------------------------------------- # [END] Digitalxero Multi Whisper Group 1/1/05 #--------------------------------------------------------- @@ -491,8 +474,7 @@ index = 0 while index < ic: item = self.GetItem( index ) - if item.GetImage(): - self.whisperCount += 1 + if item.GetImage(): self.whisperCount += 1 index += 1 self.colorize_player_list() self.Refresh() @@ -516,8 +498,7 @@ session = open_rpg.get_component("session") settings = open_rpg.get_component('settings') mode = settings.get_setting("ColorizeRoles") - if mode.lower() == "0": - return + if mode.lower() == "0": return players = session.players for m in players.keys(): item_list_location = self.FindItemData(-1,int(m)) @@ -526,8 +507,7 @@ item = self.GetItem(item_list_location) role = player_info[7] color = wx.GREEN - if self.session.group_id != "0": - item.SetTextColour(settings.get_setting(role + "RoleColor")) + if self.session.group_id != "0": item.SetTextColour(settings.get_setting(role + "RoleColor")) self.SetItem(item) def reset(self): @@ -542,26 +522,20 @@ self.DeleteAllItems() def strip_html(self,player): - ret_string = "" - x = 0 - in_tag = 0 + ret_string = ""; x = 0; in_tag = 0 for x in range(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] + if player[0][x] == "<": in_tag = 1 + elif player[0][x] == ">": in_tag = 0 + else: pass + else: ret_string = ret_string + player[0][x] return ret_string def size_cols(self): -## # moved skip here to see if it breaks -## w,h = self.GetClientSizeTuple() -## w /= 8 -## self.SetColumnWidth( 0, w*2 ) -## self.SetColumnWidth( 1, w*2 ) -## self.SetColumnWidth( 2, w*3 ) + ##moved skip here to see if it breaks + ## w,h = self.GetClientSizeTuple() + ## w /= 8 + ## self.SetColumnWidth( 0, w*2 ) + ## self.SetColumnWidth( 1, w*2 ) + ## self.SetColumnWidth( 2, w*3 ) pass
--- a/orpg/plugindb.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/plugindb.py Fri Jul 31 15:22:11 2009 -0500 @@ -16,12 +16,9 @@ for child in plugin._dir: if child._name == strname: #str() on this to make sure it's ASCII, not unicode, since orpg can't handle unicode. - if verbose: - print "successfully found the value" - if len(child): - return str( self.normal(child[0]) ) - else: - return "" + if verbose: print "successfully found the value" + if len(child): return str( self.normal(child[0]) ) + else: return "" else: if verbose: print "plugindb: no value has been stored for " + strname + " in " + plugname + " so the default has been returned" @@ -43,24 +40,16 @@ def FetchList(self, parent): retlist = [] - if not len(parent): - return [] + if not len(parent): return [] for litem in parent[0]._dir: if len(litem): - if litem._attrs["type"] == "int": - retlist += [int(litem[0])] - elif litem._attrs["type"] == "long": - retlist += [long(litem[0])] - elif litem._attrs["type"] == "float": - retlist += [float(litem[0])] - elif litem._attrs["type"] == "list": - retlist += [self.FetchList(litem)] - elif litem._attrs["type"] == "dict": - retlist += [self.FetchDict(litem)] - else: - retlist += [str( self.normal(litem[0]) )] - else: - retlist += [""] + if litem._attrs["type"] == "int": retlist += [int(litem[0])] + elif litem._attrs["type"] == "long": retlist += [long(litem[0])] + elif litem._attrs["type"] == "float": retlist += [float(litem[0])] + elif litem._attrs["type"] == "list": retlist += [self.FetchList(litem)] + elif litem._attrs["type"] == "dict": retlist += [self.FetchDict(litem)] + else: retlist += [str( self.normal(litem[0]) )] + else: retlist += [""] return retlist def GetList(self, plugname, listname, defaultval, verbose=0): @@ -70,8 +59,7 @@ for child in plugin._dir: if child._name == listname and child._attrs["type"] == "list": retlist = self.FetchList(child) - if verbose: - print "successfully found the value" + if verbose: print "successfully found the value" return retlist else: if verbose: @@ -157,20 +145,13 @@ for ditem in parent[0]._dir: if len(ditem): ditem._attrs["name"] = self.normal(ditem._attrs["name"]) - if ditem._attrs["type"] == "int": - retdict[ditem._attrs["name"]] = int(ditem[0]) - elif ditem._attrs["type"] == "long": - retdict[ditem._attrs["name"]] = long(ditem[0]) - elif ditem._attrs["type"] == "float": - retdict[ditem._attrs["name"]] = float(ditem[0]) - elif ditem._attrs["type"] == "list": - retdict[ditem._attrs["name"]] = self.FetchList(ditem) - elif ditem._attrs["type"] == "dict": - retdict[ditem._attrs["name"]] = self.FetchDict(ditem) - else: - retdict[ditem._attrs["name"]] = str( self.normal(ditem[0]) ) - else: - retdict[ditem._attrs["name"]] = "" + if ditem._attrs["type"] == "int": retdict[ditem._attrs["name"]] = int(ditem[0]) + elif ditem._attrs["type"] == "long": retdict[ditem._attrs["name"]] = long(ditem[0]) + elif ditem._attrs["type"] == "float": retdict[ditem._attrs["name"]] = float(ditem[0]) + elif ditem._attrs["type"] == "list": retdict[ditem._attrs["name"]] = self.FetchList(ditem) + elif ditem._attrs["type"] == "dict": retdict[ditem._attrs["name"]] = self.FetchDict(ditem) + else: retdict[ditem._attrs["name"]] = str( self.normal(ditem[0]) ) + else: retdict[ditem._attrs["name"]] = "" return retdict def GetDict(self, plugname, dictname, defaultval, verbose=0): @@ -178,8 +159,7 @@ for plugin in self.xml_dom: if plugname == plugin._name: for child in plugin._dir: - if child._name == dictname and child._attrs["type"] == "dict": - return self.FetchDict(child) + if child._name == dictname and child._attrs["type"] == "dict": return self.FetchDict(child) else: if verbose: print "plugindb: no value has been stored for " + dictname + " in " + plugname + " so the default has been returned"
--- a/orpg/pulldom.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/pulldom.py Fri Jul 31 15:22:11 2009 -0500 @@ -2,15 +2,11 @@ import xml.sax,xml.sax.handler import types -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO +try: from cStringIO import StringIO +except ImportError: from StringIO import StringIO -try: - _StringTypes = [types.StringType, types.UnicodeType] -except AttributeError: - _StringTypes = [types.StringType] +try: _StringTypes = [types.StringType, types.UnicodeType] +except AttributeError: _StringTypes = [types.StringType] START_ELEMENT = "START_ELEMENT" END_ELEMENT = "END_ELEMENT" @@ -43,8 +39,7 @@ # When using namespaces, the reader may or may not # provide us with the original name. If not, create # *a* valid tagName from the current context. - if tagName is None: - tagName = self._current_context[uri] + ":" + localname + if tagName is None: tagName = self._current_context[uri] + ":" + localname node = self.document.createElementNS(uri, tagName) else: # When the tagname is not prefixed, it just appears as @@ -55,8 +50,7 @@ if a_uri: qname = self._current_context[a_uri] + ":" + a_localname attr = self.document.createAttributeNS(a_uri, qname) - else: - attr = self.document.createAttribute(a_localname) + else: attr = self.document.createAttribute(a_localname) attr.value = value node.setAttributeNode(attr) parent = self.curNode @@ -134,8 +128,7 @@ def endDocument(self): assert not self.curNode.parentNode for node in self.curNode.childNodes: - if node.nodeType == node.ELEMENT_NODE: - self.document.documentElement = node + if node.nodeType == node.ELEMENT_NODE: self.document.documentElement = node #if not self.document.documentElement: # raise Error, "No document element" self.lastEvent[1] = [(END_DOCUMENT, node), None] @@ -164,23 +157,19 @@ def __getitem__(self, pos): rc = self.getEvent() - if rc: - return rc + if rc: return rc raise IndexError def expandNode(self, node): event = self.getEvent() while event: token, cur_node = event - if cur_node is node: - return - if token != END_ELEMENT: - cur_node.parentNode.appendChild(cur_node) + if cur_node is node: return + if token != END_ELEMENT: cur_node.parentNode.appendChild(cur_node) event = self.getEvent() def getEvent(self): - if not self.pulldom.firstEvent[1]: - self.pulldom.lastEvent = self.pulldom.firstEvent + if not self.pulldom.firstEvent[1]: self.pulldom.lastEvent = self.pulldom.firstEvent while not self.pulldom.firstEvent[1]: buf=self.stream.read(self.bufsize) if not buf: @@ -220,17 +209,13 @@ default_bufsize = (2 ** 14) - 20 def parse(stream_or_string, parser=None, bufsize=default_bufsize): - if type(stream_or_string) in _StringTypes: - stream = open(stream_or_string) - else: - stream = stream_or_string - if not parser: - parser = xml.sax.make_parser() + if type(stream_or_string) in _StringTypes: stream = open(stream_or_string) + else: stream = stream_or_string + if not parser: parser = xml.sax.make_parser() return DOMEventStream(stream, parser, bufsize) def parseString(string, parser=None): bufsize = len(string) buf = StringIO(string) - if not parser: - parser = xml.sax.make_parser() + if not parser: parser = xml.sax.make_parser() return DOMEventStream(buf, parser, bufsize)
--- a/orpg/tools/orpg_settings.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/tools/orpg_settings.py Fri Jul 31 15:22:11 2009 -0500 @@ -45,16 +45,13 @@ temp_file.close() self.xml_dom = self.xml.parseXml(txt) - if self.xml_dom is None: - self.rebuildSettings() + 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) - try: - os.remove(self.filename) - except: - pass + try: os.remove(self.filename) + except: pass self.validate.config_file("settings.xml","default_settings.xml") temp_file = open(self.filename) @@ -63,10 +60,8 @@ self.xml_dom = self.xml.parseXml(txt) def get_setting(self, name): - try: - return self.xml_dom.getElementsByTagName(name)[0].getAttribute("value") - except: - return 0 + try: return self.xml_dom.getElementsByTagName(name)[0].getAttribute("value") + except: return 0 def get_setting_keys(self): keys = [] @@ -74,16 +69,14 @@ for i in xrange(0, len(tabs)): if tabs[i].getAttribute("type") == 'grid': children = tabs[i]._get_childNodes() - for c in children: - keys.append(c._get_tagName()) + for c in children: keys.append(c._get_tagName()) return keys def set_setting(self, name, value): self.xml_dom.getElementsByTagName(name)[0].setAttribute("value", value) def add_setting(self, tab, setting, value, options, help): - if len(self.xml_dom.getElementsByTagName(setting)) > 0: - return False + 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() for i in xrange(0, len(tabs)): @@ -94,10 +87,8 @@ def add_tab(self, parent, tabname, tabtype): tab_xml = '<tab ' - if tabtype == 'text': - tab_xml += 'name="' + tabname + '" type="text" />' - else: - tab_xml += 'name="' + tabname + '" type="' + tabtype + '"></tab>' + if tabtype == 'text': tab_xml += 'name="' + tabname + '" type="text" />' + else: tab_xml += 'name="' + tabname + '" type="' + tabtype + '"></tab>' newtab = self.xml.parseXml(tab_xml)._get_documentElement() if parent != None: tabs = self.xml_dom.getElementsByTagName("tab") @@ -105,15 +96,13 @@ if tabs[i].getAttribute("name") == parent and tabs[i].getAttribute("type") == 'tab': children = tabs[i]._get_childNodes() for c in children: - if c.getAttribute("name") == tabname: - return False + if c.getAttribute("name") == tabname: return False tabs[i].appendChild(newtab) return True else: children = self.xml_dom._get_childNodes() for c in children: - if c.getAttribute("name") == tabname: - return False + if c.getAttribute("name") == tabname: return False self.xml_dom.appendChild(newtab) return True return False @@ -125,8 +114,7 @@ temp_file.close() default_dom = self.xml.parseXml(txt)._get_documentElement() for child in default_dom.getChildren(): - if child._get_tagName() == 'tab' and child.hasChildNodes(): - self.proccessChildren(child) + if child._get_tagName() == 'tab' and child.hasChildNodes(): self.proccessChildren(child) default_dom.unlink() def proccessChildren(self, dom, parent=None): @@ -180,14 +168,12 @@ temp_file = open(filename) temp_file.close() children = self.settings.xml_dom._get_childNodes() - for c in children: - self.build_window(c,self.tabber) + for c in children: self.build_window(c,self.tabber) def build_window(self, xml_dom, parent_wnd): name = xml_dom._get_nodeName() #container = 0 - if name=="tab": - temp_wnd = self.do_tab_window(xml_dom,parent_wnd) + if name=="tab": temp_wnd = self.do_tab_window(xml_dom,parent_wnd) return temp_wnd def do_tab_window(self, xml_dom, parent_wnd): @@ -201,15 +187,13 @@ temp_wnd = orpgTabberWnd(parent_wnd, style=FNB.FNB_NO_X_BUTTON) children = xml_dom._get_childNodes() for c in children: - if c._get_nodeName() == "tab": - self.do_tab_window(c, temp_wnd) + if c._get_nodeName() == "tab": self.do_tab_window(c, temp_wnd) temp_wnd.SetSelection(0) parent_wnd.AddPage(temp_wnd, name, False) elif type == "text": temp_wnd = wx.TextCtrl(parent_wnd,-1) parent_wnd.AddPage(temp_wnd, name, False) - else: - temp_wnd = None + else: temp_wnd = None return temp_wnd def do_grid_tab(self, xml_dom, parent_wnd): @@ -233,8 +217,7 @@ try: style = wnd.GetWindowStyleFlag() new.append(wnd) - except: - pass + except: pass tabbedwindows = new open_rpg.add_component("tabbedWindows", tabbedwindows) rgbconvert = RGBHex() @@ -277,27 +260,19 @@ top_frame.players.SetForegroundColour('black') top_frame.players.Refresh() - if self.changes[i][0] == 'GMWhisperTab' and self.changes[i][1] == '1': - self.chat.parent.create_gm_tab() + if self.changes[i][0] == 'GMWhisperTab' and self.changes[i][1] == '1': self.chat.parent.create_gm_tab() self.toggleToolBars(self.chat, self.changes[i]) - try: - self.toggleToolBars(self.chat.parent.GMChatPanel, self.changes[i]) - except: - pass - for panel in self.chat.parent.whisper_tabs: - self.toggleToolBars(panel, self.changes[i]) - for panel in self.chat.parent.group_tabs: - self.toggleToolBars(panel, self.changes[i]) - for panel in self.chat.parent.null_tabs: - self.toggleToolBars(panel, self.changes[i]) + try: self.toggleToolBars(self.chat.parent.GMChatPanel, self.changes[i]) + except: pass + for panel in self.chat.parent.whisper_tabs: self.toggleToolBars(panel, self.changes[i]) + for panel in self.chat.parent.group_tabs: self.toggleToolBars(panel, self.changes[i]) + for panel in self.chat.parent.null_tabs: self.toggleToolBars(panel, self.changes[i]) - if self.changes[i][0] == 'player': - self.session.name = self.changes[i][1] + if self.changes[i][0] == 'player': self.session.name = str(self.changes[i][1]) - if (self.changes[i][0] == 'TabTheme' and (self.changes[i][1] == 'customflat' or self.changes[i][1] == 'customslant')) or\ - (self.changes[i][0] == 'TabTextColor' and (self.settings.get_setting('TabTheme') == 'customflat' or self.settings.get_setting('TabTheme') == 'customslant')) or\ - (self.changes[i][0] == 'TabGradientFrom' and (self.settings.get_setting('TabTheme') == 'customflat' or self.settings.get_setting('TabTheme') == 'customslant')) or\ - (self.changes[i][0] == 'TabGradientTo' and (self.settings.get_setting('TabTheme') == 'customflat' or self.settings.get_setting('TabTheme') == 'customslant')): + if (self.changes[i][0][:3] == 'Tab' and self.changes[i][1][:6] == 'custom') or\ + (self.changes[i][0][:3] == 'Tab' and self.settings.get_setting('TabTheme')[:6] == 'custom'): + gfrom = self.settings.get_setting('TabGradientFrom') (fred, fgreen, fblue) = rgbconvert.rgb_tuple(gfrom) @@ -306,15 +281,14 @@ tabtext = self.settings.get_setting('TabTextColor') (tred, tgreen, tblue) = rgbconvert.rgb_tuple(tabtext) + for wnd in tabbedwindows: style = wnd.GetWindowStyleFlag() # remove old tabs style mirror = ~(FNB.FNB_VC71 | FNB.FNB_VC8 | FNB.FNB_FANCY_TABS | FNB.FNB_COLORFUL_TABS) style &= mirror - if self.settings.get_setting('TabTheme') == 'customslant': - style |= FNB.FNB_VC8 - else: - style |= FNB.FNB_FANCY_TABS + if self.settings.get_setting('TabTheme') == 'customslant': style |= FNB.FNB_VC8 + else: style |= FNB.FNB_FANCY_TABS wnd.SetWindowStyleFlag(style) wnd.SetGradientColourTo(wx.Color(tored, togreen, toblue)) wnd.SetGradientColourFrom(wx.Color(fred, fgreen, fblue)) @@ -330,12 +304,9 @@ self.Destroy() def toggleToolBars(self, panel, changes): - if changes[0] == 'AliasTool_On': - panel.toggle_alias(changes[1]) - elif changes[0] == 'DiceButtons_On': - panel.toggle_dice(changes[1]) - elif changes[0] == 'FormattingButtons_On': - panel.toggle_formating(changes[1]) + if changes[0] == 'AliasTool_On': panel.toggle_alias(changes[1]) + elif changes[0] == 'DiceButtons_On': panel.toggle_dice(changes[1]) + elif changes[0] == 'FormattingButtons_On': panel.toggle_formating(changes[1]) class settings_grid(wx.grid.Grid): """grid for gen info""" @@ -354,15 +325,13 @@ for i in range(len(settings)): self.SetCellValue(i,0,settings[i][0]) self.SetCellValue(i,1,settings[i][1]) - if settings[i][1] and settings[i][1][0] == '#': - self.SetCellBackgroundColour(i,1,settings[i][1]) + if settings[i][1] and settings[i][1][0] == '#': self.SetCellBackgroundColour(i,1,settings[i][1]) self.SetCellValue(i,2,settings[i][2]) def on_left_click(self,evt): row = evt.GetRow() col = evt.GetCol() - if col == 2: - return + if col == 2: return elif col == 0: name = self.GetCellValue(row,0) str = self.settings[row][3] @@ -379,14 +348,12 @@ self.Refresh() setting = self.GetCellValue(row,0) self.setting_data.append([setting, hexcolor]) - else: - evt.Skip() + else: evt.Skip() def on_cell_change(self,evt): row = evt.GetRow() col = evt.GetCol() - if col != 1: - return + if col != 1: return setting = self.GetCellValue(row,0) value = self.GetCellValue(row,1) self.setting_data.append([setting, value]) @@ -395,8 +362,7 @@ (w,h) = self.GetClientSizeTuple() rows = self.GetNumberRows() minh = 0 - for i in range (0,rows): - minh += self.GetRowSize(i) + for i in range (0,rows): minh += self.GetRowSize(i) minh += 120 return minh @@ -404,6 +370,5 @@ (w,h) = self.GetClientSizeTuple() cols = self.GetNumberCols() col_w = w/(cols) - for i in range(0,cols): - self.SetColSize(i,col_w) + for i in range(0,cols): self.SetColSize(i,col_w) self.Refresh()
--- a/orpg/tools/toolBars.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/tools/toolBars.py Fri Jul 31 15:22:11 2009 -0500 @@ -80,13 +80,11 @@ if id == TB_MAP_MODE: mode = 1 self.mapmode +=1 - if self.mapmode >3: - self.mapmode = 1 + if self.mapmode >3: self.mapmode = 1 bm = wx.Image(self.modeicons[self.mapmode-1],wx.BITMAP_TYPE_GIF).ConvertToBitmap() self.butt= wx.BitmapButton(self,TB_MAP_MODE,bm) data = self.mapmode - if self.callback != None: - self.callback(mode,data) + if self.callback != None: self.callback(mode,data) class DiceToolBar(wx.Panel): """This is where all of the dice related tools belong for quick reference.""" @@ -142,18 +140,13 @@ numDie = self.numDieText.GetValue() dieMod = self.dieModText.GetValue() # Init the die roll text - if not len(numDie): - numDie = 1 + if not len(numDie): numDie = 1 dieRoll = str(numDie) # Figure out which die roll was selected id = evt.GetId() - recycle_bin = {TB_IDC_D4: "d4", TB_IDC_D6: "d6", TB_IDC_D8: "d8", TB_IDC_D10: "d10", TB_IDC_D12: "d12", TB_IDC_D20: "d20", TB_IDC_D100: "d100"} - dieType = recycle_bin[id]; recycle_bin = {} - # To appease tdb...I personally disagree with this! - if len(dieMod) and dieMod[0] not in "*/-+": - dieMod = "+" + dieMod - # Build the complete die roll text now - rollString = "[" + dieRoll + dieType + dieMod + "]" - # Now, call the post method to send everything off with - if self.callBack != None: - self.callBack( rollString,1,1 ) + recycle_bin = {TB_IDC_D4: "d4", TB_IDC_D6: "d6", TB_IDC_D8: "d8", TB_IDC_D10: "d10", + TB_IDC_D12: "d12", TB_IDC_D20: "d20", TB_IDC_D100: "d100"} + dieType = recycle_bin[id]; del recycle_bin + if len(dieMod) and dieMod[0] not in "*/-+": dieMod = "+" + dieMod #Add Modifier + rollString = "[" + dieRoll + dieType + dieMod + "]" # Build the complete die roll text now + if self.callBack != None: self.callBack( rollString,1,1 ) # Now, call the post method to send everything off with
--- a/orpg/xmltramp.py Fri Jul 24 10:03:22 2009 -0500 +++ b/orpg/xmltramp.py Fri Jul 31 15:22:11 2009 -0500 @@ -37,12 +37,9 @@ def __repr__(self, recursive=0, multiline=0, inprefixes=None): def qname(name, inprefixes): if islst(name): - if inprefixes[name[0]] is not None: - return inprefixes[name[0]]+':'+name[1] - else: - return name[1] - else: - return name + if inprefixes[name[0]] is not None: return inprefixes[name[0]]+':'+name[1] + else: return name[1] + else: return name def arep(a, inprefixes, addns=1): out = '' @@ -67,26 +64,23 @@ out += '>' if recursive: content = 0 - for x in self._dir: + for x in self._dir: if isinstance(x, Element): content = 1 pad = '\n' + ('\t' * recursive) for x in self._dir: if multiline and content: out += pad if isstr(x): out += quote(x) - elif isinstance(x, Element): - out += x.__repr__(recursive+1, multiline, inprefixes.copy()) - else: - raise TypeError, "I wasn't expecting "+`x`+"." + elif isinstance(x, Element): out += x.__repr__(recursive+1, multiline, inprefixes.copy()) + else: raise TypeError, "I wasn't expecting "+`x`+"." if multiline and content: out += '\n' + ('\t' * (recursive-1)) - else: + else: if self._dir: out += '...' out += '</'+qname(self._name, inprefixes)+'>' return out def __unicode__(self): text = '' - for x in self._dir: - text += unicode(x) + for x in self._dir: text += unicode(x) return ' '.join(text.split()) def __str__(self): @@ -170,12 +164,9 @@ if _set: for k in _set.keys(): self._attrs[k] = _set[k] if len(_pos) > 1: - for i in range(0, len(_pos), 2): - self._attrs[_pos[i]] = _pos[i+1] - if len(_pos) == 1 is not None: - return self._attrs[_pos[0]] - if len(_pos) == 0: - return self._attrs + for i in range(0, len(_pos), 2): self._attrs[_pos[i]] = _pos[i+1] + if len(_pos) == 1 is not None: return self._attrs[_pos[0]] + if len(_pos) == 0: return self._attrs def __len__(self): return len(self._dir) @@ -214,10 +205,8 @@ ch = self.ch; self.ch = '' if ch and not ch.isspace(): self.stack[-1]._dir.append(ch) element = self.stack.pop() - if self.stack: - self.stack[-1]._dir.append(element) - else: - self.result = element + if self.stack: self.stack[-1]._dir.append(element) + else: self.result = element from xml.sax import make_parser from xml.sax.handler import feature_namespaces