Mercurial > openrpg
changeset 542:7d60d6747209
bug #79 is ready for testing
line wrap: on
line diff
--- a/orpg/chat/chatwnd.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/chat/chatwnd.py Thu Mar 25 17:56:48 2010 -0600 @@ -42,32 +42,32 @@ import sys import webbrowser import traceback + +import wx +import wx.html from wx.lib.expando import EVT_ETC_LAYOUT_NEEDED - -from orpg.orpg_windows import * -from orpg.player_list import WG_LIST +try: + import wx.lib.agw.flatnotebook as FNB +except ImportError: + import orpg.external.agw.flatnotebook as FNB import orpg.tools.rgbhex import orpg.tools.inputValidator import orpg.tools.predTextCtrl -from orpg.tools.metamenus import MenuEx - -from orpg.orpgCore import open_rpg +from orpg.player_list import WG_LIST +from orpg.ui.util.tab import TabberWindow +from orpg.ui.util.misc import create_masked_button +from orpg.external.metamenus import MenuEx +from orpg.orpgCore import open_rpg, ParserContext from orpg.dirpath import dir_struct from orpg.tools.settings import settings from orpg.tools.orpg_log import logger from orpg.tools.decorators import debugging - from orpg.ui.toolbars import DiceToolBar, TextFormatToolBar, AliasToolBar - from orpg.orpg_version import VERSION - -# needed to only send typing/not_typing messages while connected from orpg.networking.mplay_client import MPLAY_CONNECTED - from orpg.chat import commands, chat_msg, chat_util from orpg.gametree.nodehandlers.core import is_integer, node_handler - from orpg.dieroller import roller_manager NEWCHAT = False @@ -320,7 +320,7 @@ GROUP_TAB = wx.NewId() NULL_TAB = wx.NewId() -class chat_notebook(orpgTabberWnd): +class chat_notebook(TabberWindow): """ This class defines the tabbed 'notebook' that holds multiple chatpanels. It's the widget attached to the main application frame. @@ -336,7 +336,7 @@ """ @debugging def __init__(self, parent, size): - orpgTabberWnd.__init__(self, parent, True, size=size, style=FNB.FNB_DROPDOWN_TABS_LIST|FNB.FNB_NO_NAV_BUTTONS|FNB.FNB_MOUSE_MIDDLE_CLOSES_TABS) + TabberWindow.__init__(self, parent, True, size=size, style=FNB.FNB_DROPDOWN_TABS_LIST|FNB.FNB_NO_NAV_BUTTONS|FNB.FNB_MOUSE_MIDDLE_CLOSES_TABS) self.whisper_tabs = [] self.group_tabs = [] @@ -1067,7 +1067,7 @@ @debugging def build_text(self): tip = 'Open Text View Of Chat Session' - self.textpop_lock = createMaskedButton(self, + self.textpop_lock = create_masked_button(self, dir_struct["icon"]+'note.gif', tip, wx.ID_ANY, '#bdbdbd') @@ -1102,7 +1102,7 @@ self.toolbar_sizer.Layout() def build_misc_controls(self): - self.saveButton = createMaskedButton(self, + self.saveButton = create_masked_button(self, dir_struct["icon"]+'save.bmp', 'Save the chatbuffer', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP)
--- a/orpg/chat/commands.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/chat/commands.py Thu Mar 25 17:56:48 2010 -0600 @@ -9,34 +9,16 @@ import time import traceback - -import orpg.orpg_version -import orpg.orpg_windows - -from orpg.orpgCore import * - -from orpg.dieroller import roller_manager -from orpg.external.etree.ElementTree import ElementTree, Element -from orpg.external.etree.ElementTree import fromstring, tostring - -from orpg.tools.settings import settings -from orpg.tools.decorators import debugging +import re from wx import TextEntryDialog, ID_OK -##-------------------------------------------------------------- -## dynamically loading module for extended developer commands -## allows developers to work on new chat commands without -## integrating them directly into the ORPG code allowing -## updating of their code without merging changes -## cmd_ext.py should NOT be included in the CVS or Actual Releases - -try: - import cmd_ext - print "Importing Developer Extended Command Set" -except: - pass -##---------------------------------------------------------------- +from orpg.orpgCore import open_rpg, ParserContext +from orpg.dieroller import roller_manager +from orpg.tools.settings import settings +from orpg.tools.decorators import debugging +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring ANTI_LOG_CHAR = '!'
--- a/orpg/dirpath/dirpath_tools.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/dirpath/dirpath_tools.py Thu Mar 25 17:56:48 2010 -0600 @@ -98,7 +98,11 @@ """Notify the user of directory problems and show directory selection dialog """ - from orpg.orpg_wx import wx, WXLOADED + try: + import wx + WXLOADED = True + except ImportError: + WXLOADED = False if WXLOADED: class tmpApp(wx.App):
--- a/orpg/gametree/gametree.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/gametree.py Thu Mar 25 17:56:48 2010 -0600 @@ -33,10 +33,11 @@ import os import re -from orpg.orpg_wx import * -from orpg.orpg_windows import * +import wx +from wx.lib.filebrowsebutton import * + +from orpg.ui.util.misc import ImageHelper from orpg.orpgCore import open_rpg - from orpg.dirpath import dir_struct from orpg.tools.settings import settings from orpg.tools.orpg_log import logger @@ -54,7 +55,6 @@ import orpg.gametree.nodehandlers.rpg_grid import orpg.gametree.nodehandlers.d20 import orpg.gametree.nodehandlers.StarWarsd20 -import orpg.gametree.nodehandlers.voxchat from orpg.gametree.gametree_version import GAMETREE_VERSION import orpg.external.etree.ElementTree as ET from xml.parsers.expat import ExpatError @@ -93,7 +93,7 @@ TOP_TREE_PROP = wx.NewId() TOP_FEATURES = wx.NewId() -class Namespace: +class Namespace(object): def __init__(self, name): self.name = name self.pathmap = {} @@ -147,7 +147,7 @@ sizer.Add(wx.Size(10,10)) sizer.Add(self.CreateButtonSizer(wx.OK|wx.CANCEL)) self.SetSizer(sizer) - + class game_tree(wx.TreeCtrl): @debugging @@ -220,7 +220,6 @@ self.add_nodehandler('rpg_grid_handler', orpg.gametree.nodehandlers.rpg_grid.rpg_grid_handler) self.add_nodehandler('d20char_handler', orpg.gametree.nodehandlers.d20.d20char_handler) self.add_nodehandler('SWd20char_handler', orpg.gametree.nodehandlers.StarWarsd20.SWd20char_handler) - self.add_nodehandler('voxchat_handler', orpg.gametree.nodehandlers.voxchat.voxchat_handler) self.add_nodehandler('file_loader', core.file_loader) self.add_nodehandler('node_loader', core.node_loader) self.add_nodehandler('url_loader', core.url_loader) @@ -636,7 +635,7 @@ clone_xml.set("name", base_name+str(suffix)) parent_xml.insert(pos+1, clone_xml) #copy placed below self.load_xml(clone_xml, parent_node, item) - + @debugging def on_clone_and_replace(self, evt): self.on_clone(evt, True) @@ -823,7 +822,7 @@ @debugging def build_img_list(self): """make image list""" - helper = img_helper() + helper = ImageHelper() self.icons = { } self._imageList= wx.ImageList(16,16,False) icons_xml = ET.parse(orpg.dirpath.dir_struct["icon"]+"icons.xml") @@ -1115,7 +1114,7 @@ # add path only after checking namepace path uniqueness self.set_referenceable(item, True) self.root_namespace.add_path(path, handler) - + if not self.ItemHasChildren(item): self.root_namespace.add_leaf(name, handler) if namespace: @@ -1139,7 +1138,7 @@ self.set_namespace(item, False) self.validation_message("Duplicate namespace: '"+name+"'") return - namespace = Namespace(name) + namespace = Namespace(name) self.set_namespace(item, True) self.namespacemap[name]=namespace self.traverse(item, self.on_new_namespace_traverse, namespace) @@ -1148,7 +1147,7 @@ def check_no_namespaces_traverse(self, item, errors): if self.is_namespace(item): errors.append(self.GetItemText(item)) - + @debugging def on_new_namespace_traverse(self, item, namespace): # this item just became part of the new namepace @@ -1178,7 +1177,7 @@ self.root_namespace.delete_leaf(name, handler) if namespace: namespace.delete_leaf(name, handler) - + @debugging def remove_namespace(self, item): name = self.GetItemText(item).lower().strip()
--- a/orpg/gametree/nodehandlers/chatmacro.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/chatmacro.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,9 +26,9 @@ # Description: The file contains code for the form based nodehanlers # -__version__ = "$Id: chatmacro.py,v 1.15 2006/11/15 12:11:23 digitalxero Exp $" +from orpg.orpgCore import ParserContext -from core import * +from .core import * ########################## ## text node handler
--- a/orpg/gametree/nodehandlers/containers.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/containers.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,9 +26,17 @@ # Description: The file contains code for the container nodehandlers # +import wx.lib.splitter +try: + import wx.lib.agw.flatnotebook as FNB +except ImportError: + import orpg.external.agw.flatnotebook as FNB -from core import * -import wx.lib.splitter +from orpg.ui.util.tab import TabberWindow +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring + +from .core import * ########################## @@ -118,7 +126,7 @@ else: self.tree.load_xml(child_xml,self.mytree_node) if self.atts is None: - self.atts = ET.Element('group_atts') + self.atts = Element('group_atts') self.atts.set("cols","1") self.atts.set("border","1") self.xml.append(self.atts) @@ -222,9 +230,9 @@ return tabbed_panel(parent,self,2) -class tabbed_panel(orpgTabberWnd): +class tabbed_panel(TabberWindow): def __init__(self, parent, handler, mode): - orpgTabberWnd.__init__(self, parent, style=FNB.FNB_NO_X_BUTTON) + TabberWindow.__init__(self, parent, style=FNB.FNB_NO_X_BUTTON) self.handler = handler self.parent = parent handler.tree.traverse(handler.mytree_node, self.pick_panel, mode, False) @@ -261,7 +269,7 @@ else: self.tree.load_xml(child_xml,self.mytree_node) if self.atts is None: - self.atts = ET.Element('splitter_atts') + self.atts = Element('splitter_atts') self.atts.set("horizontal","0") self.xml.append(self.atts)
--- a/orpg/gametree/nodehandlers/core.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/core.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,21 +26,19 @@ # Description: The file contains code for the core nodehanlers # -__version__ = "$Id: core.py,v 1.49 2007/12/07 20:39:48 digitalxero Exp $" +import os +import webbrowser +import urllib + +import wx + +from orpg.mapper import map +from orpg.orpgCore import open_rpg +from orpg.dirpath import dir_struct +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring from nodehandler_version import NODEHANDLER_VERSION -try: - from orpg.orpg_windows import * - import orpg.dirpath - from orpg.orpgCore import open_rpg - import webbrowser - from orpg.mapper import map - import os - from wx import DisplaySize -except: - import wx - -import orpg.external.etree.ElementTree as ET # this might be better as an alteration to the ElelementTree code # ElementTree returns an element's .text as None if the Element @@ -82,7 +80,7 @@ if len(frame): (sx,sy,px,py) = [int(value) for value in frame.split(',')] self.frame_size = (sx, sy) - (maxx, maxy) = DisplaySize() + (maxx, maxy) = wx.DisplaySize() if px < maxx-80 and py < maxy-50:#if it's off screen ignore the saved pos self.frame_pos = (px, py) except: @@ -127,7 +125,7 @@ self.myeditor = wx.Frame(None, -1, title) self.myeditor.Freeze() if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myeditor.SetIcon(icon) del icon @@ -176,7 +174,7 @@ self.mywindow.Freeze() if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO) self.mywindow.SetIcon(icon) del icon self.mywindow.panel = self.get_use_panel(self.mywindow) @@ -218,7 +216,7 @@ caption = self.xml.get('name') self.myviewer = wx.Frame(None, -1, caption) if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myviewer.SetIcon(icon) del icon self.myviewer.panel = self.get_html_panel(self.myviewer) @@ -267,7 +265,7 @@ self.tree.load_xml(drop_xml, parent_node, prev_sib) def toxml(self,pretty=0): - return ET.tostring(self.xml) #toxml(self.master_dom,pretty) + return tostring(self.xml) #toxml(self.master_dom,pretty) def tohtml(self): """ returns the value of the node plus perhaps some mark-up, such as the title of the node in bold @@ -297,9 +295,9 @@ self.tree.Refresh() def on_save(self,evt): - f = wx.FileDialog(self.tree,"Select a file", orpg.dirpath.dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE) + f = wx.FileDialog(self.tree,"Select a file", dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE) if f.ShowModal() == wx.ID_OK: - ET.ElementTree(self.xml).write(f.GetPath()) + ElementTree(self.xml).write(f.GetPath()) f.Destroy() def get_design_panel(self,parent): @@ -423,7 +421,7 @@ def on_ldclick(self,evt): title = self.xml.get('name') - new_xml = ET.XML(ET.tostring(self.xml[0])) + new_xml = fromstring(tostring(self.xml[0])) self.tree.root_xml.insert(0, new_xml) tree_node = self.tree.load_xml(new_xml,self.tree.root,self.tree.root) return 1 @@ -447,20 +445,19 @@ def on_ldclick(self,evt): file_name = self.file_node.get("name") - self.tree.insert_xml(open(orpg.dirpath.dir_struct["nodes"] + file_name,"r").read()) + self.tree.insert_xml(open(dir_struct["nodes"] + file_name,"r").read()) return 1 def on_design(self,evt): - tlist = ['Title','File Name'] - vlist = [self.xml.get("name"), - self.file_node.get("name")] - dlg = orpgMultiTextEntry(self.tree.GetParent(),tlist,vlist,"File Loader Edit") - if dlg.ShowModal() == wx.ID_OK: - vlist = dlg.get_values() - self.file_node.set('name', vlist[1]) - self.xml.set('name', vlist[0]) - self.tree.SetItemText(self.mytree_node,vlist[0]) - dlg.Destroy() + opts = {'Title': self.xml.get("name"), + 'File Name': self.file_node.get("name")} + with MultiTextEntry(self.tree.GetParent(), opts, + "File Loader Edit") as dlg: + if dlg.ShowModal() == wx.ID_OK: + opts = dlg.get_values() + self.file_node.set('name', opts['File Name'].Value) + self.xml.set('name', opts['Title'].Value) + self.tree.SetItemText(self.mytree_node, opts['Title'].Value) ########################## ## URL loader @@ -484,16 +481,15 @@ return 1 def on_design(self,evt): - tlist = ['Title','URL'] - vlist = [self.xml.get("name"), - self.file_node.get("url")] - dlg = orpgMultiTextEntry(self.tree.GetParent(),tlist,vlist,"File Loader Edit") - if dlg.ShowModal() == wx.ID_OK: - vlist = dlg.get_values() - self.file_node.set('url', vlist[1]) - self.xml.set('name', vlist[0]) - self.tree.SetItemText(self.mytree_node,vlist[0]) - dlg.Destroy() + opts = {'Title': self.xml.get("name"), + 'URL': self.file_node.get("url")} + with MultiTextEntry(self.tree.GetParent(), opts, + "File Loader Edit") as dlg: + if dlg.ShowModal() == wx.ID_OK: + opts = dlg.get_values() + self.file_node.set('url', opts['URL'].Value) + self.xml.set('name', opts['Title'].Value) + self.tree.SetItemText(self.mytree_node, opts['Title'].Value) ##########################
--- a/orpg/gametree/nodehandlers/dnd35.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/dnd35.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,4 +1,3 @@ -import orpg.tools.orpg_settings from core import * from containers import * from string import * #a 1.6003 @@ -173,7 +172,7 @@ self.CreateGrid(len(self.n_list),2) self.SetRowLabelSize(0) self.SetColLabelSize(0) - + i = 0 for i in range(len(self.n_list)): self.refresh_row(i)
--- a/orpg/gametree/nodehandlers/dnd3e.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/dnd3e.py Thu Mar 25 17:56:48 2010 -0600 @@ -143,7 +143,7 @@ # r- resolved # o- open # -import orpg.tools.orpg_settings + from core import * from containers import * from string import * #a 1.6003 @@ -416,7 +416,7 @@ self.CreateGrid(len(self.n_list),2) self.SetRowLabelSize(0) self.SetColLabelSize(0) - + i = 0 for i in range(len(self.n_list)): self.refresh_row(i)
--- a/orpg/gametree/nodehandlers/forms.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/gametree/nodehandlers/forms.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,10 +26,10 @@ # Description: The file contains code for the form based nodehanlers # -__version__ = "$Id: forms.py,v 1.53 2007/04/21 23:00:51 digitalxero Exp $" +import wx.lib.scrolledpanel +from orpg.ui.util.misc import ImageHelper from containers import * -import wx.lib.scrolledpanel def bool2int(b): #in wxPython 2.5+, evt.Checked() returns True or False instead of 1.0 or 0. @@ -241,7 +241,7 @@ def set_value(self, new_value): self.text_elem.text = str(new_value) - + FORM_TEXT_CTRL = wx.NewId() @@ -265,7 +265,7 @@ if self.handler.chat.contains_reference(txt): txt = self.handler.chat.parse_multiline(txt, ParserContext(self.handler), False) text_style |= wx.TE_READONLY - + self.text = wx.TextCtrl(self, FORM_TEXT_CTRL, txt, style=text_style) sizer.Add(wx.StaticText(self, -1, handler.xml.get('name')+": "), 0, sizer_style) sizer.Add(wx.Size(5,0)) @@ -525,7 +525,7 @@ self.list.Check(i) else: self.list.SetSelection(i) - + if type == L_DROP: sizer = wx.BoxSizer(wx.HORIZONTAL) else: @@ -597,7 +597,7 @@ self.listbox.SetColumnWidth(0, 300) self.listbox.SetColumnWidth(1, 54) self.reload_options() - + opts = ['Drop Down', 'List Box', 'Radio Box', 'Check List'] self.type_radios = wx.RadioBox(self,F_TYPE, choices=opts) self.type_radios.SetSelection(handler.get_type()) @@ -637,7 +637,7 @@ sizer.Add(self.listbox,1,wx.EXPAND); sizer.Add(text_sizer,0,wx.EXPAND) sizer.Add(but_sizer,0,wx.EXPAND) - + self.SetSizer(sizer) self.SetAutoLayout(True) self.Fit() @@ -788,7 +788,7 @@ return link_edit_panel(parent,self) def get_use_panel(self,parent): - img = img_helper().load_url(self.link.get("href")) + img = ImageHelper().load_url(self.link.get("href")) if not img is None: return wx.StaticBitmap(parent,-1,img,size= wx.Size(img.GetWidth(),img.GetHeight())) return wx.EmptyBitmap(1, 1)
--- a/orpg/gametree/nodehandlers/voxchat.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,65 +0,0 @@ -# Copyright (C) 2000-2001 The OpenRPG Project -# -# openrpg-dev@lists.sourceforge.net -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -# -- -# -# File: voxchat.py -# Author: Ted Berg -# Maintainer: -# Version: -# $Id: voxchat.py,v 1.37 2007/05/06 16:42:55 digitalxero Exp $ -# -# Description: nodehandler for alias. -# - -__version__ = "$Id: voxchat.py,v 1.37 2007/05/06 16:42:55 digitalxero Exp $" - -import re -import os -import string - -from orpg.orpg_windows import * -import core -import orpg.tools.scriptkit -import orpg.tools.predTextCtrl -import orpg.tools.rgbhex -import orpg.tools.inputValidator - -import orpg.dirpath -import orpg.networking.mplay_client -from orpg.orpgCore import open_rpg - -# -# Good things to add: -# 1.u'use filter' per alias [ this should be done ] -# 2. make aliases remember which filter they're using [ lisbox in gtk appaears to ignore SetSelection( <= 0 ) -# - - -class voxchat_handler(core.node_handler): - def __init__(self, xml, tree_node): - core.node_handler.__init__( self, xml, tree_node) - - def get_design_panel( self, parent ): - aliasLib = open_rpg.get_component('alias') - aliasLib.ImportFromTree(self.xml) - return None - - def get_use_panel( self, parent ): - aliasLib = open_rpg.get_component('alias') - aliasLib.ImportFromTree(self.xml) - return None
--- a/orpg/main.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/main.py Thu Mar 25 17:56:48 2010 -0600 @@ -28,11 +28,19 @@ # from __future__ import with_statement -from orpg.orpg_wx import * -from orpg.orpgCore import * +import traceback +from xml.parsers.expat import ExpatError + +import wx +import wx.py +try: + import wx.lib.agw.aui as AUI +except ImportError: + import wx.aui as AUI + from orpg_version import * -#from orpg.orpg_windows import * +#These should be fixed to from bla import stuff import orpg.player_list import orpg.tools.passtool import orpg.tools.orpg_sound @@ -43,26 +51,18 @@ import orpg.mapper.map import orpg.mapper.images -import orpg.networking.gsclient -import orpg.tools.pluginui as pluginUI -import orpg.tools.toolBars -import orpg.tools.orpg_settings - -from orpg.ui import AliasLib -from orpg.ui.toolbars import StatusBar +from orpg.orpgCore import open_rpg +from orpg.ui import AliasLib, SettingsWindow, BrowseServerWindow, PluginFrame +from orpg.ui.toolbars import StatusBar, DiceToolBar from orpg.dieroller import roller_manager from orpg.dirpath import dir_struct from orpg.tools.settings import settings from orpg.tools.orpg_log import logger from orpg.tools.validate import validate from orpg.tools.decorators import debugging, pending_deprecation -from orpg.tools.metamenus import MenuBarEx - +from orpg.external.metamenus import MenuBarEx from orpg.external.etree.ElementTree import ElementTree, Element from orpg.external.etree.ElementTree import fromstring, tostring -from xml.parsers.expat import ExpatError - -import wx.py #################################### ## Main Frame @@ -508,7 +508,7 @@ #OpenRPG Menu @debugging def OnMB_OpenRPGSettings(self): - dlg = orpg.tools.orpg_settings.orpgSettingsWnd(self) + dlg = SettingsWindow(self) dlg.Centre() dlg.ShowModal() @@ -719,7 +719,7 @@ base = etree.getroot() #Plugins Window - self.pluginsFrame = pluginUI.PluginFrame(self) + self.pluginsFrame = PluginFrame(self) open_rpg.add_component('plugins', self.get_activeplugins()) open_rpg.add_component('startplugs', self.get_startplugins()) @@ -765,8 +765,7 @@ logger.debug("Status Window Created") # Create and show the floating dice toolbar - self.dieToolBar = orpg.tools.toolBars.DiceToolBar(self, - callBack=self.chat.ParsePost) + self.dieToolBar = DiceToolBar(self, callback=self.chat.ParsePost) wndinfo = AUI.AuiPaneInfo() wndinfo.DestroyOnClose(False) wndinfo.Name('Dice Tool Bar') @@ -779,7 +778,7 @@ logger.debug("Dice Tool Bar Created") #Create the Browse Server Window - self.gs = orpg.networking.gsclient.game_server_panel(self) + self.gs = BrowseServerWindow(self) wndinfo = AUI.AuiPaneInfo() wndinfo.DestroyOnClose(False) wndinfo.Name('Browse Server Window') @@ -1148,10 +1147,12 @@ logger.general("[WARNING] Map error pre_exit_cleanup()", True) try: - save_tree = string.upper(settings.get('SaveGameTreeOnExit')) - if save_tree.lower() not in ['0', 'false', 'no']: + if settings.get('SaveGameTreeOnExit').lower() not in ['0', + 'false', + 'no']: self.tree.save_tree(settings.get('gametree')) except Exception: + logger.exception(traceback.format_exc()) logger.general("[WARNING] Error saving gametree", True) if self.session.get_status() == orpg.networking.mplay_client.MPLAY_CONNECTED:
--- a/orpg/mapper/base.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/base.py Thu Mar 25 17:56:48 2010 -0600 @@ -25,15 +25,18 @@ # # Description: # -__version__ = "$Id: base.py,v 1.18 2007/02/12 02:29:08 digitalxero Exp $" + +import time +from threading import Lock +from math import * -from images import ImageHandler -from orpg.tools.rgbhex import * -from orpg.orpg_windows import * -from math import * -from threading import Lock -import time -import orpg.external.etree.ElementTree as ET +import wx + +from orpg.tools.rgbhex import RGBHex +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring + +from .images import ImageHandler class cmpPoint(wx.Point): def __init__(self,*_args,**_kwargs):
--- a/orpg/mapper/base_handler.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/base_handler.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,11 +26,12 @@ # Description: base layer handler. # layer handlers are responsible for the GUI elements of the layer # -__version__ = "$Id: base_handler.py,v 1.20 2007/11/04 17:32:25 digitalxero Exp $" +import wx -from orpg.orpg_windows import * +from orpg.ui.util.misc import create_masked_button from orpg.orpgCore import open_rpg +from orpg.dirpath import dir_struct class base_layer_handler(wx.Panel): @@ -54,11 +55,23 @@ 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 = create_masked_button(self, + dir_struct["icon"] + 'zoom_in.gif', + "Zoom in from x1.0", wx.ID_ANY) + self.zoom_out_button = create_masked_button(self, + dir_struct["icon"] + 'zoom_out.gif', + "Zoom out from x1.0", wx.ID_ANY) + props = create_masked_button(self, + dir_struct["icon"]+'compass.gif', + 'Edit map properties', wx.ID_ANY) + mapopen = create_masked_button(self, + dir_struct["icon"]+'open.bmp', + 'Load a map', wx.ID_ANY, + '#c0c0c0', wx.BITMAP_TYPE_BMP) + mapsave = create_masked_button(self, + 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.EXPAND) self.buttonsizer.Add(self.zoom_out_button, 0, wx.EXPAND) self.buttonsizer.Add(props, 0, wx.EXPAND) @@ -67,8 +80,8 @@ self.SetSizer(self.basesizer) self.SetAutoLayout(True) self.Fit() - self.basesizer.Add( self.sizer, 1, wx.EXPAND) - self.basesizer.Add( self.buttonsizer, 0, wx.ALIGN_RIGHT) + self.basesizer.Add(self.sizer, 1, wx.EXPAND) + self.basesizer.Add(self.buttonsizer, 0, wx.ALIGN_RIGHT) self.Bind(wx.EVT_BUTTON, self.canvas.on_zoom_in, self.zoom_in_button) self.Bind(wx.EVT_BUTTON, self.canvas.on_zoom_out, self.zoom_out_button) self.Bind(wx.EVT_BUTTON, self.map_frame.on_open, mapopen) @@ -78,9 +91,12 @@ self.SetSizer(self.basesizer) def build_menu(self,label = "Map"): - "Menu is built based on the type of grid (rectangle or hex) we have in use." + """ + 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) 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) @@ -98,10 +114,11 @@ self.main_menu = main_menu def on_save_map_jpg(self, evt): - directory = orpg.dirpath.dir_struct["user"] + directory = dir_struct["user"] if directory == None: directory = "" - d = wx.FileDialog(self.GetParent(), "Save map as a jpg", directory, "", "*.jpg", wx.SAVE) + d = wx.FileDialog(self.GetParent(), "Save map as a jpg", directory, "", + "*.jpg", wx.SAVE) if d.ShowModal() != wx.ID_OK: return filename = d.GetPath()
--- a/orpg/mapper/images.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/images.py Thu Mar 25 17:56:48 2010 -0600 @@ -30,11 +30,12 @@ import urllib import Queue import thread +import time from threading import Lock -import time -from orpg.orpg_wx import * -from orpg.orpgCore import * +import wx + +from orpg.orpgCore import open_rpg from orpg.dirpath import dir_struct from orpg.tools.orpg_log import logger from orpg.tools.settings import settings
--- a/orpg/mapper/map.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/map.py Thu Mar 25 17:56:48 2010 -0600 @@ -33,7 +33,20 @@ import gc import traceback +import wx +from wx.lib.expando import EVT_ETC_LAYOUT_NEEDED +try: + import wx.lib.agw.flatnotebook as FNB +except ImportError: + import orpg.external.agw.flatnotebook as FNB + +from orpg.ui.util.tab import TabberWindow from orpg.orpgCore import open_rpg +from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger +from orpg.tools.settings import settings + +from orpg.external.etree.ElementTree import tostring, iselement import orpg.external.etree.ElementTree as ET from orpg.mapper.map_version import MAP_VERSION @@ -48,12 +61,6 @@ from orpg.mapper.grid_handler import * from orpg.mapper.map_handler import * -from orpg.dirpath import dir_struct -from orpg.tools.orpg_log import logger -from orpg.tools.settings import settings - -from orpg.external.etree.ElementTree import tostring, iselement - # Various marker modes for player tools on the map MARKER_MODE_NONE = 0 MARKER_MODE_MEASURE = 1 @@ -778,7 +785,8 @@ self.top_frame = open_rpg.get_component('frame') self.root_dir = os.getcwd() self.current_layer = 2 - self.layer_tabs = orpgTabberWnd(self, style=FNB.FNB_NO_X_BUTTON|FNB.FNB_BOTTOM|FNB.FNB_NO_NAV_BUTTONS) + self.layer_tabs = TabberWindow(self, + style=FNB.FNB_NO_X_BUTTON|FNB.FNB_BOTTOM|FNB.FNB_NO_NAV_BUTTONS) self.layer_handlers = [] self.layer_handlers.append(background_handler(self.layer_tabs,-1,self.canvas)) self.layer_tabs.AddPage(self.layer_handlers[0],"Background")
--- a/orpg/mapper/map_prop_dialog.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/map_prop_dialog.py Thu Mar 25 17:56:48 2010 -0600 @@ -25,9 +25,7 @@ # # Description: # -__version__ = "$Id: map_prop_dialog.py,v 1.16 2006/11/04 21:24:21 digitalxero Exp $" -from orpg.orpg_windows import * from background import * from grid import * from miniatures import *
--- a/orpg/mapper/miniatures_handler.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/mapper/miniatures_handler.py Thu Mar 25 17:56:48 2010 -0600 @@ -21,7 +21,7 @@ # Author: OpenRPG Team # Maintainer: # Version: -# $Id: miniatures_handler.py,v 1.43 2007/12/07 20:39:50 digitalxero Exp $ +# $Id: miniatures_handler.py, v 1.43 2007/12/07 20:39:50 digitalxero Exp $ # # Description: Miniature layer handler # @@ -32,16 +32,17 @@ import mimetypes import urllib +from orpg.ui.util.misc import create_masked_button +from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger +from orpg.tools.settings import settings + from orpg.mapper.base_handler import * from orpg.mapper.min_dialogs import * from orpg.mapper.grid import GRID_RECTANGLE from orpg.mapper.grid import GRID_HEXAGON from orpg.mapper.grid import GRID_ISOMETRIC -from orpg.dirpath import dir_struct -from orpg.tools.orpg_log import logger -from orpg.tools.settings import settings - SHOW_LABELS_TOOL = wx.NewId() AUTO_LABEL_TOOL = wx.NewId() LAYER_TOOL = wx.NewId() @@ -113,7 +114,8 @@ self.lastMenuChoice = None self.drag_mini = None self.tooltip_delay_miliseconds = 500 - self.tooltip_timer = wx.CallLater(self.tooltip_delay_miliseconds, self.on_tooltip_timer) + self.tooltip_timer = wx.CallLater(self.tooltip_delay_miliseconds, + self.on_tooltip_timer) self.tooltip_timer.Stop() dt = myFileDropTarget(self) self.canvas.SetDropTarget(dt) @@ -121,16 +123,23 @@ def build_ctrls(self): base_layer_handler.build_ctrls(self) - # add controls in reverse order! (unless you want them after the default tools) - self.min_url = wx.ComboBox(self, wx.ID_ANY, "http://", style=wx.CB_DROPDOWN | wx.CB_SORT) - self.localBrowse = wx.Button(self, wx.ID_ANY, 'Browse', style=wx.BU_EXACTFIT) - minilist = createMaskedButton(self, dir_struct["icon"]+'questionhead.gif', 'Edit miniature properties', wx.ID_ANY) - miniadd = wx.Button(self, wx.ID_OK, "Add Miniature", style=wx.BU_EXACTFIT) + # add controls in reverse order! (unless you want them + #after the default tools) + self.min_url = wx.ComboBox(self, wx.ID_ANY, "http://", + style=wx.CB_DROPDOWN | wx.CB_SORT) + self.localBrowse = wx.Button(self, wx.ID_ANY, 'Browse', + style=wx.BU_EXACTFIT) + minilist = create_masked_button(self, + dir_struct["icon"]+'questionhead.gif', + 'Edit miniature properties', + wx.ID_ANY) + miniadd = wx.Button(self, wx.ID_OK, "Add Miniature", + style=wx.BU_EXACTFIT) self.sizer.Add(self.min_url, 1, wx.ALIGN_CENTER) self.sizer.Add(miniadd, 0, wx.EXPAND) self.sizer.Add(self.localBrowse, 0, wx.EXPAND) - self.sizer.Add(wx.Size(20,25)) + self.sizer.Add(wx.Size(20, 25)) self.sizer.Add(minilist, 0, wx.EXPAND) self.Bind(wx.EVT_BUTTON, self.on_min_list, minilist) self.Bind(wx.EVT_BUTTON, self.on_miniature, miniadd) @@ -140,7 +149,10 @@ def on_browse(self, evt): if not self.role_is_gm_or_player(): return - dlg = wx.FileDialog(None, "Select a Miniature to load", dir_struct["user"], wildcard="Image files (*.bmp, *.gif, *.jpg, *.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) + dlg = wx.FileDialog(None, "Select a Miniature to load", + dir_struct["user"], + wildcard="Image files (*.bmp, *.gif, *.jpg, "\ + "*.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) if not dlg.ShowModal() == wx.ID_OK: dlg.Destroy() return @@ -148,16 +160,20 @@ imgdata = f.read() filename = dlg.GetFilename() - (imgtype,j) = mimetypes.guess_type(filename) - postdata = urllib.urlencode({'filename':filename, 'imgdata':imgdata, 'imgtype':imgtype}) + (imgtype, j) = mimetypes.guess_type(filename) + postdata = urllib.urlencode({'filename': filename, 'imgdata': imgdata, + 'imgtype': imgtype}) if settings.get('LocalorRemote') == 'Remote': # make the new mini appear in top left of current viewable map dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(0) y = dc.DeviceToLogicalY(0) - thread.start_new_thread(self.canvas.layers['miniatures'].upload, (postdata, dlg.GetPath()), {'pos':cmpPoint(x,y)}) + thread.start_new_thread(self.canvas.layers['miniatures'].upload, + (postdata, dlg.GetPath()), + {'pos':cmpPoint(x, y)}) else: try: min_url = open_rpg.get_component("cherrypy") + filename @@ -184,7 +200,8 @@ 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()) + min_label = '%s %d' % (min_label, + self.canvas.layers['miniatures'].next_serial()) else: min_label = "" if self.min_url.FindString(min_url) == -1: @@ -194,15 +211,22 @@ # make the new mini appear in top left of current viewable map dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(0) y = dc.DeviceToLogicalY(0) - self.canvas.layers['miniatures'].add_miniature(id, min_url, pos=cmpPoint(x,y), label=min_label) + self.canvas.layers['miniatures'].add_miniature(id, min_url, + pos=cmpPoint(x, y), + label=min_label) except: - # When there is an exception here, we should be decrementing the serial_number for reuse!! - unablemsg= "Unable to load/resolve URL: " + min_url + " on resource \"" + min_label + "\"!!!\n\n" + # When there is an exception here, we should be decrementing + #the serial_number for reuse!! + unablemsg = "Unable to load/resolve URL: " + unablemsg += min_url + " on resource \"" + unablemsg += min_label + "\"!!!\n\n" #print unablemsg - dlg = wx.MessageDialog(self,unablemsg, 'Url not found',wx.ICON_EXCLAMATION) + dlg = wx.MessageDialog(self, unablemsg, 'Url not found', + wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() self.canvas.layers['miniatures'].rollback_serial() @@ -210,20 +234,23 @@ self.canvas.Refresh(False) - def build_menu(self,label = "Miniature"): - base_layer_handler.build_menu(self,label) + def build_menu(self, label = "Miniature"): + base_layer_handler.build_menu(self, label) self.main_menu.AppendSeparator() - self.main_menu.Append(SHOW_LABELS_TOOL,"&Show labels","", 1) - self.main_menu.Check(SHOW_LABELS_TOOL, self.canvas.layers['miniatures'].show_labels) - self.main_menu.Append(AUTO_LABEL_TOOL,"&Auto label","",1) - self.main_menu.Check(AUTO_LABEL_TOOL,self.auto_label) - self.main_menu.Append(SERIAL_TOOL,"&Number minis","",1) + self.main_menu.Append(SHOW_LABELS_TOOL, "&Show labels", "", 1) + self.main_menu.Check(SHOW_LABELS_TOOL, + self.canvas.layers['miniatures'].show_labels) + self.main_menu.Append(AUTO_LABEL_TOOL, "&Auto label", "", 1) + self.main_menu.Check(AUTO_LABEL_TOOL, self.auto_label) + self.main_menu.Append(SERIAL_TOOL, "&Number minis", "", 1) self.main_menu.Check(SERIAL_TOOL, self.use_serial) - self.main_menu.Append(MAP_REFRESH_MINI_URLS,"&Refresh miniatures") # Add the menu item + self.main_menu.Append(MAP_REFRESH_MINI_URLS, "&Refresh miniatures") self.main_menu.AppendSeparator() self.main_menu.Append(MIN_MOVE, "Move") - self.canvas.Bind(wx.EVT_MENU, self.on_map_board_menu_item, id=MAP_REFRESH_MINI_URLS) # Set the handler - self.canvas.Bind(wx.EVT_MENU, self.on_show_labels, id=SHOW_LABELS_TOOL) + self.canvas.Bind(wx.EVT_MENU, self.on_map_board_menu_item, + id=MAP_REFRESH_MINI_URLS) + self.canvas.Bind(wx.EVT_MENU, self.on_show_labels, + id=SHOW_LABELS_TOOL) self.canvas.Bind(wx.EVT_MENU, self.on_auto_label, id=AUTO_LABEL_TOOL) self.canvas.Bind(wx.EVT_MENU, self.on_serial, id=SERIAL_TOOL) # build miniature meenu @@ -232,54 +259,57 @@ # facing and heading possibilities. heading_menu = wx.Menu() face_menu = wx.Menu() - face_menu.Append(MIN_FACING_NONE,"&None") - face_menu.Append(MIN_FACING_NORTH,"&North") - face_menu.Append(MIN_FACING_NORTHEAST,"Northeast") - face_menu.Append(MIN_FACING_EAST,"East") - face_menu.Append(MIN_FACING_SOUTHEAST,"Southeast") - face_menu.Append(MIN_FACING_SOUTH,"&South") - face_menu.Append(MIN_FACING_SOUTHWEST,"Southwest") - face_menu.Append(MIN_FACING_WEST,"West") - face_menu.Append(MIN_FACING_NORTHWEST,"Northwest") - heading_menu.Append(MIN_HEADING_NONE,"&None") - heading_menu.Append(MIN_HEADING_NORTH,"&North") - heading_menu.Append(MIN_HEADING_NORTHEAST,"Northeast") - heading_menu.Append(MIN_HEADING_EAST,"East") - heading_menu.Append(MIN_HEADING_SOUTHEAST,"Southeast") - heading_menu.Append(MIN_HEADING_SOUTH,"&South") - heading_menu.Append(MIN_HEADING_SOUTHWEST,"Southwest") - heading_menu.Append(MIN_HEADING_WEST,"West") - heading_menu.Append(MIN_HEADING_NORTHWEST,"Northwest") + face_menu.Append(MIN_FACING_NONE, "&None") + face_menu.Append(MIN_FACING_NORTH, "&North") + face_menu.Append(MIN_FACING_NORTHEAST, "Northeast") + face_menu.Append(MIN_FACING_EAST, "East") + face_menu.Append(MIN_FACING_SOUTHEAST, "Southeast") + face_menu.Append(MIN_FACING_SOUTH, "&South") + face_menu.Append(MIN_FACING_SOUTHWEST, "Southwest") + face_menu.Append(MIN_FACING_WEST, "West") + face_menu.Append(MIN_FACING_NORTHWEST, "Northwest") + heading_menu.Append(MIN_HEADING_NONE, "&None") + heading_menu.Append(MIN_HEADING_NORTH, "&North") + heading_menu.Append(MIN_HEADING_NORTHEAST, "Northeast") + heading_menu.Append(MIN_HEADING_EAST, "East") + heading_menu.Append(MIN_HEADING_SOUTHEAST, "Southeast") + heading_menu.Append(MIN_HEADING_SOUTH, "&South") + heading_menu.Append(MIN_HEADING_SOUTHWEST, "Southwest") + heading_menu.Append(MIN_HEADING_WEST, "West") + heading_menu.Append(MIN_HEADING_NORTHWEST, "Northwest") align_menu = wx.Menu() - align_menu.Append(MIN_ALIGN_GRID_CENTER,"&Center") - align_menu.Append(MIN_ALIGN_GRID_TL,"&Top-Left") + 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) else: - self.min_menu.Append(MIN_TITLE_HACK,label) + self.min_menu.Append(MIN_TITLE_HACK, label) self.min_menu.AppendSeparator() - self.min_menu.Append(MIN_SHOW_HIDE,"Show / Hide") + self.min_menu.Append(MIN_SHOW_HIDE, "Show / Hide") self.min_menu.Append(MIN_LOCK_UNLOCK, "Lock / Unlock") - self.min_menu.Append(MIN_REMOVE,"&Remove") - self.min_menu.Append(MIN_TO_GAMETREE,"To &Gametree") - self.min_menu.AppendMenu(MIN_HEADING_SUBMENU,"Set &Heading",heading_menu) - self.min_menu.AppendMenu(MIN_FACING_SUBMENU,"Set &Facing",face_menu) - self.min_menu.AppendMenu(MIN_ALIGN_SUBMENU,"Snap-to &Alignment",align_menu) + self.min_menu.Append(MIN_REMOVE, "&Remove") + self.min_menu.Append(MIN_TO_GAMETREE, "To &Gametree") + self.min_menu.AppendMenu(MIN_HEADING_SUBMENU, "Set &Heading", + heading_menu) + self.min_menu.AppendMenu(MIN_FACING_SUBMENU, "Set &Facing", face_menu) + self.min_menu.AppendMenu(MIN_ALIGN_SUBMENU, "Snap-to &Alignment", + align_menu) self.min_menu.AppendSeparator() zorder_menu = wx.Menu() - zorder_menu.Append(MIN_BACK_ONE,"Back one") - zorder_menu.Append(MIN_FORWARD_ONE,"Forward one") - zorder_menu.Append(MIN_TO_BACK,"To back") - zorder_menu.Append(MIN_TO_FRONT,"To front") + zorder_menu.Append(MIN_BACK_ONE, "Back one") + zorder_menu.Append(MIN_FORWARD_ONE, "Forward one") + zorder_menu.Append(MIN_TO_BACK, "To back") + zorder_menu.Append(MIN_TO_FRONT, "To front") zorder_menu.AppendSeparator() - zorder_menu.Append(MIN_LOCK_BACK,"Lock to back") - zorder_menu.Append(MIN_LOCK_FRONT,"Lock to front") - zorder_menu.Append(MIN_FRONTBACK_UNLOCK,"Unlock Front/Back") - self.min_menu.AppendMenu(MIN_ZORDER_SUBMENU, "Miniature Z-Order",zorder_menu) - #self.min_menu.Append(MIN_LOCK,"&Lock") + zorder_menu.Append(MIN_LOCK_BACK, "Lock to back") + zorder_menu.Append(MIN_LOCK_FRONT, "Lock to front") + zorder_menu.Append(MIN_FRONTBACK_UNLOCK, "Unlock Front/Back") + self.min_menu.AppendMenu(MIN_ZORDER_SUBMENU, "Miniature Z-Order", + zorder_menu) + #self.min_menu.Append(MIN_LOCK, "&Lock") self.min_menu.AppendSeparator() - self.min_menu.Append(MIN_PROP_DLG,"&Properties") + self.min_menu.Append(MIN_PROP_DLG, "&Properties") self.min_menu.AppendSeparator() self.min_menu.Append(MIN_MOVE, "Move") self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_MOVE) @@ -289,33 +319,60 @@ self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_TO_GAMETREE) #self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_LOCK) self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_PROP_DLG) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_NONE) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_EAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_WEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_NORTH) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_SOUTH) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_NORTHEAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_SOUTHEAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_SOUTHWEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FACING_NORTHWEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_NONE) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_EAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_WEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_NORTH) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_SOUTH) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_NORTHEAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_SOUTHEAST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_SOUTHWEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_HEADING_NORTHWEST) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_ALIGN_GRID_CENTER) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_ALIGN_GRID_TL) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_BACK_ONE) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FORWARD_ONE) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_TO_BACK) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_TO_FRONT) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_LOCK_BACK) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_LOCK_FRONT) - self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, id=MIN_FRONTBACK_UNLOCK) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_NONE) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_EAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_WEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_NORTH) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_SOUTH) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_NORTHEAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_SOUTHEAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_SOUTHWEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FACING_NORTHWEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_NONE) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_EAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_WEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_NORTH) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_SOUTH) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_NORTHEAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_SOUTHEAST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_SOUTHWEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_HEADING_NORTHWEST) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_ALIGN_GRID_CENTER) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_ALIGN_GRID_TL) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_BACK_ONE) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FORWARD_ONE) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_TO_BACK) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_TO_FRONT) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_LOCK_BACK) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_LOCK_FRONT) + self.canvas.Bind(wx.EVT_MENU, self.on_min_menu_item, + id=MIN_FRONTBACK_UNLOCK) ######### add plugin added menu items ######### if len(self.mini_rclick_menu_extra_items)>0: self.min_menu.AppendSeparator() @@ -326,8 +383,8 @@ for item in self.background_rclick_menu_extra_items.items(): self.main_menu.Append(item[1], item[0]) - def do_min_menu(self,pos): - self.canvas.PopupMenu(self.min_menu,pos) + def do_min_menu(self, pos): + self.canvas.PopupMenu(self.min_menu, pos) def do_min_select_menu(self, min_list, pos): # to prevent another event being processed @@ -342,16 +399,17 @@ 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,"/",) + string_split = string.split(m.path, "/", ) last_string = string_split[len(string_split)-1] - self.min_select_menu.Append(loop_count, 'Unlabeled - ' + last_string[:len(last_string)-4]) + self.min_select_menu.Append(loop_count, 'Unlabeled - ' +\ + last_string[:len(last_string)-4]) self.canvas.Bind(wx.EVT_MENU, self.min_selected, id=loop_count) loop_count += 1 - self.canvas.PopupMenu(self.min_select_menu,pos) + self.canvas.PopupMenu(self.min_select_menu, pos) except: pass - def min_selected(self,evt): + def min_selected(self, evt): # this is the callback function for the menu that is used to choose # between minis when you right click, left click or left double click # on a stack of two or more @@ -359,7 +417,7 @@ self.canvas.send_map_data() self.lastMenuChoice = evt.GetId()-1 - def on_min_menu_item(self,evt): + def on_min_menu_item(self, evt): id = evt.GetId() if id == MIN_MOVE: self.moveSelectedMinis(self.last_rclick_pos) @@ -368,7 +426,8 @@ 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='" + node_begin = "<nodehandler module='map_miniature_nodehandler' " + node_begin += "class='map_miniature_handler' name='" if self.sel_rmin.label: node_begin += self.sel_rmin.label + "'" else: @@ -389,17 +448,34 @@ else: self.sel_rmin.locked = True if self.sel_rmin.selected: - # 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 + # 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_rmin.selected = False self.sel_rmin.isUpdated = True - 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} + 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 = {} @@ -410,11 +486,14 @@ 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) + dlg = min_edit_dialog(self.canvas.frame.GetParent(), + self.sel_rmin) if dlg.ShowModal() == wx.ID_OK: - if self.sel_rmin.selected and self.sel_rmin.locked != old_lock_value: - # 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 + if self.sel_rmin.selected and\ + self.sel_rmin.locked != old_lock_value: + # 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_rmin.selected = False self.sel_rmin.isUpdated = True self.canvas.Refresh(False) @@ -513,8 +592,11 @@ def on_miniature(self, evt): session = self.canvas.frame.session - if (session.my_role() != session.ROLE_GM) and (session.my_role() != session.ROLE_PLAYER) and (session.use_roles()): - self.infoPost("You must be either a player or GM to use the miniature Layer") + if (session.my_role() != session.ROLE_GM) and\ + (session.my_role() != session.ROLE_PLAYER) and\ + (session.use_roles()): + self.infoPost("You must be either a player or GM to use "\ + "the miniature Layer") return min_url = self.min_url.GetValue() # build url @@ -527,7 +609,8 @@ 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()) + min_label = '%s %d' % (min_label, + self.canvas.layers['miniatures'].next_serial()) else: min_label = "" if self.min_url.FindString(min_url) == -1: @@ -537,39 +620,47 @@ # make the new mini appear in top left of current viewable map dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(0) y = dc.DeviceToLogicalY(0) - self.canvas.layers['miniatures'].add_miniature(id, min_url, pos=cmpPoint(x,y), label=min_label) + self.canvas.layers['miniatures'].add_miniature(id, min_url, + pos=cmpPoint(x, y), + label=min_label) except Exception, e: - # When there is an exception here, we should be decrementing the serial_number for reuse!! - unablemsg= "Unable to load/resolve URL: " + min_url + " on resource \"" + min_label + "\"!!!\n\n" + # When there is an exception here, we should be decrementing the + #serial_number for reuse!! + unablemsg = "Unable to load/resolve URL: " + unablemsg += min_url + " on resource \"" + unablemsg += min_label + "\"!!!\n\n" #print unablemsg - dlg = wx.MessageDialog(self,unablemsg, 'Url not found',wx.ICON_EXCLAMATION) + dlg = wx.MessageDialog(self, unablemsg, 'Url not found', + wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() self.canvas.layers['miniatures'].rollback_serial() self.canvas.send_map_data() self.canvas.Refresh(False) #except Exception, e: - #wx.MessageBox(str(e),"Miniature Error") + #wx.MessageBox(str(e), "Miniature Error") - def on_show_labels(self,evt): + def on_show_labels(self, evt): show_labels = not self.canvas.layers['miniatures'].show_labels self.canvas.layers['miniatures'].show_labels = show_labels self.canvas.Refresh() - def on_auto_label(self,evt): + def on_auto_label(self, evt): self.auto_label = not self.auto_label self.auto_label_cb.SetValue(self.auto_label) - def on_min_list(self,evt): + def on_min_list(self, evt): session = self.canvas.frame.session if (session.my_role() != session.ROLE_GM): self.infoPost("You must be a GM to use this feature") 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") + + d = min_list_panel(self.canvas.frame, self.canvas.layers, + "Miniature list") if d.ShowModal() == wx.ID_OK: d.Destroy() self.canvas.Refresh(False) @@ -577,11 +668,12 @@ def on_serial(self, evt): self.use_serial = not self.use_serial - def on_map_board_menu_item(self,evt): + def on_map_board_menu_item(self, evt): id = evt.GetId() - if id == MAP_REFRESH_MINI_URLS: # Note: this doesn't change the mini, so no need to update the map - for mini in self.canvas.layers['miniatures'].miniatures: # For all minis - mini.set_image(ImageHandler.load(mini.path, 'miniature', mini.id)) # Reload their bmp member + if id == MAP_REFRESH_MINI_URLS: + for mini in self.canvas.layers['miniatures'].miniatures: + mini.set_image(ImageHandler.load(mini.path, 'miniature', + mini.id)) self.canvas.Refresh(False) #################################################################### @@ -600,7 +692,8 @@ self.canvas.send_map_data() else: if not evt.AltDown():# deselect any previous selected minis - selected_list, minxy_pos, maxxy_pos = self.canvas.layers['miniatures'].getSelected() + selected_list, minxy_pos, maxxy_pos =\ + self.canvas.layers['miniatures'].getSelected() for m in selected_list: m.selected = False m.isUpdated = True @@ -608,7 +701,8 @@ mini.selected = True dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) mini.draw(dc, self.canvas.layers['miniatures']) else: self.drag_mini = None @@ -637,7 +731,7 @@ def on_drop_files(self, x, y, filepaths): # currently we ignore multiple files filepath = filepaths[0] - start1 = filepath.rfind("\\") + 1 # check for both slashes in path to be on the safe side + start1 = filepath.rfind("\\") + 1 start2 = filepath.rfind("/") + 1 if start1 < start2: start1 = start2 @@ -645,26 +739,31 @@ pos = filename.rfind('.') ext = filename[pos:].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") + if ext not in [".bmp", ".gif", ".jpg", ".jpeg", ".png"]: + self.infoPost("Supported file extensions are: *.bmp, *.gif, "\ + "*.jpg, *.jpeg, *.png") return with open(filepath, "rb") as f: imgdata = f.read() dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(x) y = dc.DeviceToLogicalY(y) - (imgtype,j) = mimetypes.guess_type(filename) - postdata = urllib.urlencode({'filename':filename, 'imgdata':imgdata, 'imgtype':imgtype}) - thread.start_new_thread(self.canvas.layers['miniatures'].upload, (postdata, filepath), {'pos':cmpPoint(x,y)}) + (imgtype, j) = mimetypes.guess_type(filename) + postdata = urllib.urlencode({'filename': filename, 'imgdata': imgdata, + 'imgtype': imgtype}) + thread.start_new_thread(self.canvas.layers['miniatures'].upload, + (postdata, filepath), {'pos':cmpPoint(x, y)}) def on_tooltip_timer(self, *args): pos = args[0] dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) pos = wx.Point(dc.DeviceToLogicalX(pos.x), dc.DeviceToLogicalY(pos.y)) mini_list = self.getMiniListOrSelectedMini(pos) if len(mini_list) > 0: @@ -673,20 +772,26 @@ else: self.canvas.SetToolTipString("") - def on_motion(self,evt): + def on_motion(self, evt): if evt.Dragging() and evt.LeftIsDown(): if self.canvas.drag is None and self.drag_mini is not None: 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.selected = True - selected_list, minxy_pos, maxxy_pos = self.canvas.layers['miniatures'].getSelected() + selected_list, minxy_pos, maxxy_pos =\ + self.canvas.layers['miniatures'].getSelected() for mini in selected_list: mini.gray = True mini.isUpdated = True @@ -695,16 +800,22 @@ self.canvas.Refresh(False) 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.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) elif self.canvas.drag is not None: self.canvas.drag.Move(evt.GetPosition()) self.canvas.drag.Show() # reset tool tip timer self.canvas.SetToolTipString("") - self.tooltip_timer.Restart(self.tooltip_delay_miliseconds, evt.GetPosition()) + self.tooltip_timer.Restart(self.tooltip_delay_miliseconds, + evt.GetPosition()) - def on_left_up(self,evt): + def on_left_up(self, evt): if self.canvas.drag: self.canvas.drag.Hide() self.canvas.drag.EndDrag() @@ -715,25 +826,27 @@ nudge = int(self.canvas.layers['grid'].unit_size/2) 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)) + pos = pos + (int(self.drag_mini.bmp.GetWidth()/2), + int(self.drag_mini.bmp.GetHeight()/2)) 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()) + pos = pos + (int(self.drag_mini.bmp.GetWidth()/2), + self.drag_mini.bmp.GetHeight()) else: pass # no nudge for the isomorphic / top-left # check to see if the mouse is inside the window still - w = self.canvas.GetClientSizeTuple() # this is the window size, minus any scrollbars - p = evt.GetPosition() # compare the window size, w with the non-logical position - c = self.canvas.size # this is the grid size, compare with the logical position, pos - # both are [width, height] - if p.x>=0 and pos.x<c[0] and p.x<w[0] and p.y>=0 and pos.y<c[1] and p.y<w[1]: + w = self.canvas.GetClientSizeTuple() + p = evt.GetPosition() + c = self.canvas.size + if p.x>=0 and pos.x<c[0] and p.x<w[0] and p.y>=0 and\ + pos.y<c[1] and p.y<w[1]: self.moveSelectedMinis(pos, self.drag_mini.pos) self.drag_mini = None - def on_left_dclick(self,evt): + def on_left_dclick(self, evt): if not self.role_is_gm_or_player() or self.alreadyDealingWithMenu(): return mini = self.find_mini(evt, evt.CmdDown() and self.role_is_gm()) @@ -744,7 +857,7 @@ #################################################################### - ## hook functions (although with python you can override any of the functions) +## hook functions (although with python you can override any of the functions) def prepare_mini_rclick_menu(self, evt): # override the entire right-click on a mini menu @@ -766,7 +879,8 @@ ## easy way to add a single menu item def set_mini_rclick_menu_item(self, label, callback_function): - # remember you might want to call these at the end of your callback function: + # remember you might want to call these at the end of your callback + #function: # canvas.Refresh(False) # canvas.send_map_data() if callback_function == None: @@ -797,14 +911,17 @@ def role_is_gm_or_player(self): session = self.canvas.frame.session - if (session.my_role() <> session.ROLE_GM) and (session.my_role() <> session.ROLE_PLAYER) and (session.use_roles()): - self.infoPost("You must be either a player or GM to use the miniature Layer") + if (session.my_role() != session.ROLE_GM) and\ + (session.my_role() != session.ROLE_PLAYER) and\ + (session.use_roles()): + self.infoPost("You must be either a player or GM to "\ + "use the miniature Layer") return False return True def role_is_gm(self): session = self.canvas.frame.session - if (session.my_role() <> session.ROLE_GM) and (session.use_roles()): + if (session.my_role() != session.ROLE_GM) and (session.use_roles()): return False return True @@ -819,12 +936,14 @@ def getLogicalPosition(self, evt): dc = wx.ClientDC(self.canvas) self.canvas.PrepareDC(dc) - dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) + dc.SetUserScale(self.canvas.layers['grid'].mapscale, + self.canvas.layers['grid'].mapscale) pos = evt.GetLogicalPosition(dc) return pos def getMiniListOrSelectedMini(self, pos, include_locked=False): - mini_list = self.canvas.layers['miniatures'].find_miniature(pos, (not include_locked)) + mini_list = self.canvas.layers['miniatures'].find_miniature(pos, + (not include_locked)) if mini_list is None: return [] if len(mini_list)<2: @@ -834,14 +953,15 @@ for mini in mini_list: if mini.selected: if found_selected_mini: - return mini_list # at least 2 selected minis in list; return all + return mini_list found_selected_mini = mini if found_selected_mini: return [found_selected_mini]# return only selected return mini_list def moveSelectedMinis(self, pos, origin=None): - selected_list, minxy_pos, maxxy_pos = self.canvas.layers['miniatures'].getSelected() + selected_list, minxy_pos, maxxy_pos =\ + self.canvas.layers['miniatures'].getSelected() # check for size of rectangle to big if origin is None: origin = minxy_pos @@ -856,7 +976,9 @@ 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()) + 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(): @@ -871,7 +993,7 @@ pass choice = self.getLastMenuChoice() if choice == None: - return None # left menu without making a choice, eg by clicking outside menu + return None mini = mini_list[choice] elif len(mini_list) == 1: mini = mini_list[0]
--- a/orpg/networking/gsclient.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/networking/gsclient.py Thu Mar 25 17:56:48 2010 -0600 @@ -28,23 +28,23 @@ from __future__ import with_statement import traceback + +import wx from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin, CheckListCtrlMixin import meta_server_lib -from orpg.orpg_windows import * from orpg.chat.chat_util import strip_html, strip_unicode -import orpg.tools.rgbhex +from orpg.tools.rgbhex import RGBHex from orpg.orpgCore import open_rpg from orpg.dirpath import dir_struct from orpg.tools.decorators import debugging from orpg.tools.orpg_log import logger from orpg.tools.settings import settings from orpg.tools.validate import validate - from orpg.external.etree.ElementTree import ElementTree, Element from orpg.external.etree.ElementTree import fromstring, tostring -class server_instance: +class server_instance(object): def __init__(self, id, name="[Unknown]", users="0", address="127.0.0.1", port="6774"): self.id = id @@ -442,9 +442,9 @@ self.room_list.DeleteAllItems() self.set_cur_room_text("Not Connected!") self.cur_room_index = -1 - self.frame.status.set_connect_status("Not Connected") + self.frame.status.connect_status = "Not Connected" else: - self.frame.status.set_connect_status(self.name) + self.frame.status.connect_status = self.name self.set_cur_room_text("Lobby") @debugging @@ -510,7 +510,7 @@ groups = self.session.get_groups() - hex = orpg.tools.rgbhex.RGBHex() + hex = RGBHex() color1 = settings.get("RoomColor_Active") color2 = settings.get("RoomColor_Locked") color3 = settings.get("RoomColor_Empty") @@ -570,7 +570,7 @@ def refresh_server_list(self): try: self.server_list.DeleteAllItems() - hex = orpg.tools.rgbhex.RGBHex() + hex = RGBHex() color1 = settings.get("RoomColor_Active") color2 = settings.get("RoomColor_Locked") color3 = settings.get("RoomColor_Empty")
--- a/orpg/networking/mplay_server_gui.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/networking/mplay_server_gui.py Thu Mar 25 17:56:48 2010 -0600 @@ -15,14 +15,18 @@ import sys import time import types -import orpg.dirpath -import orpg.systempath -from orpg.orpg_wx import * import webbrowser from threading import Thread + +import wx + +from orpg.dirpath import dir_struct +from orpg.tools.validate import validate +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring + from meta_server_lib import post_server_data, remove_server from mplay_server import mplay_server -from xml.dom import minidom # Constants ###################################### SERVER_RUNNING = 1 @@ -69,16 +73,16 @@ # wxEVT_LOG_MESSAGE # MessageLogEvent ############################### class MessageLogEvent(wx.PyEvent): - def __init__( self, message ): - wx.PyEvent.__init__( self ) + def __init__(self, message): + wx.PyEvent.__init__(self) self.SetEventType(wxEVT_LOG_MESSAGE) self.message = message # wxEVT_TUPLE_MESSAGE # MessageLogEvent ############################### class MessageFunctionEvent(wx.PyEvent): - def __init__( self, func, message ): - wx.PyEvent.__init__( self ) + def __init__(self, func, message): + wx.PyEvent.__init__(self) self.SetEventType(wxEVT_FUNCTION_MESSAGE) self.func = func self.message = message @@ -89,7 +93,7 @@ setting used to control the server. """ - def __init__(self, owner ): + def __init__(self, owner): """ Loads default configuration settings. """ OPENRPG_PORT = 6774 @@ -122,15 +126,15 @@ def log(self, mesg): if type(mesg) == types.TupleType: func, msg = mesg - event = MessageFunctionEvent( func, msg ) + event = MessageFunctionEvent(func, msg) else: - event = MessageLogEvent( mesg ) - wx.PostEvent( self.conf.owner, event ) + event = MessageLogEvent(mesg) + wx.PostEvent(self.conf.owner, event) del event def run(self): """ Start the server. """ - self.server = mplay_server(self.log, self.serverName ) + self.server = mplay_server(self.log, self.serverName) self.server.initServer(bootPassword=self.bootPwd, reg="No") self.alive = 1 while self.alive: @@ -145,16 +149,16 @@ # Parent = notebook # Main = GUI class Connections(wx.ListCtrl): - def __init__( self, parent, main ): - wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) + def __init__(self, parent, main): + wx.ListCtrl.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES) self.main = main self.roomList = { "0" : "Lobby" } - self._imageList = wx.ImageList( 16, 16, False ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - self._imageList.Add( img ) - img = wx.Image(orpg.dirpath.dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - self._imageList.Add( img ) - self.SetImageList( self._imageList, wx.IMAGE_LIST_SMALL ) + self._imageList = wx.ImageList(16, 16, False) + img = wx.Image(dir_struct["icon"]+"player.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + self._imageList.Add(img) + img = wx.Image(dir_struct["icon"]+"player-whisper.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() + self._imageList.Add(img) + self.SetImageList(self._imageList, wx.IMAGE_LIST_SMALL) # Set The columns self.InsertColumn(0, "ID") @@ -171,11 +175,11 @@ # Build our pop up menu to do cool things with the players in the list self.menu = wx.Menu() - self.menu.SetTitle( "Player Menu" ) - self.menu.Append( MENU_PLAYER_BOOT, "Boot Player" ) + self.menu.SetTitle("Player Menu") + self.menu.Append(MENU_PLAYER_BOOT, "Boot Player") self.menu.AppendSeparator() - self.menu.Append( MENU_PLAYER_SEND_MESSAGE, "Send Message" ) - self.menu.Append( MENU_PLAYER_SEND_SERVER_MESSAGE, "Broadcast Server Message" ) + self.menu.Append(MENU_PLAYER_SEND_MESSAGE, "Send Message") + self.menu.Append(MENU_PLAYER_SEND_SERVER_MESSAGE, "Broadcast Server Message") # Associate our events self.Bind(wx.EVT_RIGHT_DOWN, self.OnPopupMenu) @@ -185,20 +189,20 @@ self.Bind(wx.EVT_MENU, self.OnPopupMenuItem, id=MENU_PLAYER_SEND_SERVER_MESSAGE) def add(self, player): - i = self.InsertImageStringItem( 0, player["id"], 0 ) - self.SetStringItem( i, 1, self.stripHtml( player["name"] ) ) - self.SetStringItem( i, 2, self.stripHtml( player["status"] ) ) - 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.SetItemData( i, int(player["id"]) ) + i = self.InsertImageStringItem(0, player["id"], 0) + self.SetStringItem(i, 1, self.stripHtml(player["name"])) + self.SetStringItem(i, 2, self.stripHtml(player["status"])) + 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.SetItemData(i, int(player["id"])) self.AutoAjust() def remove(self, id): - i = self.FindItemData( -1, int(id) ) - self.DeleteItem( i ) + i = self.FindItemData(-1, int(id)) + self.DeleteItem(i) self.AutoAjust() def AutoAjust(self): @@ -213,30 +217,30 @@ self.Refresh() def update(self, player): - i = self.FindItemData( -1, int(player["id"]) ) + i = self.FindItemData(-1, int(player["id"])) if i > -1: self.SetStringItem(i, 1, player["name"]) - self.SetStringItem(i, 2, self.stripHtml( player["status"] ) ) + self.SetStringItem(i, 2, self.stripHtml(player["status"])) self.AutoAjust() else: self.add(player) - def updateRoom( self, data ): + def updateRoom(self, data): (from_id, id) = data - i = self.FindItemData( -1, int(from_id) ) - self.SetStringItem( i, 3, self.roomList[id] ) - self.SetStringItem( i, 5, "Lurker") + i = self.FindItemData(-1, int(from_id)) + self.SetStringItem(i, 3, self.roomList[id]) + self.SetStringItem(i, 5, "Lurker") self.Refresh() - def setPlayerRole( self, id, role ): - i = self.FindItemData( -1, int(id) ) - self.SetStringItem( i, 5, role ) + def setPlayerRole(self, id, role): + i = self.FindItemData(-1, int(id)) + self.SetStringItem(i, 5, role) - def stripHtml( self, name ): + def stripHtml(self, name): ret_string = "" x = 0 in_tag = 0 - for x in range( len(name) ): + for x in range(len(name)): if name[x] == "<" or name[x] == ">" or in_tag == 1 : if name[x] == "<" : in_tag = 1 @@ -249,46 +253,46 @@ return ret_string # When we right click, cause our popup menu to appear - def OnPopupMenu( self, event ): - pos = wx.Point( event.GetX(), event.GetY() ) - (item, flag) = self.HitTest( pos ) + def OnPopupMenu(self, event): + pos = wx.Point(event.GetX(), event.GetY()) + (item, flag) = self.HitTest(pos) if item > -1: self.selectedItem = item - self.PopupMenu( self.menu, pos ) + self.PopupMenu(self.menu, pos) # Process the events associated with our popup menu - def OnPopupMenuItem( self, event ): + def OnPopupMenuItem(self, event): # if we are not running, the player list is empty anyways if self.main.STATUS == SERVER_RUNNING: menuItem = event.GetId() - playerID = str( self.GetItemData( self.selectedItem ) ) + playerID = str(self.GetItemData(self.selectedItem)) idList = self.main.server.server.groups groupID = 0 if menuItem == MENU_PLAYER_BOOT: print "booting player: ", playerID - self.main.server.server.del_player( playerID, groupID ) - self.main.server.server.check_group( playerID, groupID ) - self.remove( playerID ) + self.main.server.server.del_player(playerID, groupID) + self.main.server.server.check_group(playerID, groupID) + self.remove(playerID) elif menuItem == MENU_PLAYER_SEND_MESSAGE: print "send a message..." - msg = self.GetMessageInput( "Send a message to player" ) + msg = self.GetMessageInput("Send a message to player") if len(msg): - self.main.server.server.send( msg, playerID, str(groupID) ) + 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") +# msg = self.GetMessageInput("Send message to room of this player") # if len(msg): -# self.main.server.server.send_to_group( 0, GroupID, msg ) +# self.main.server.server.send_to_group(0, GroupID, msg) elif menuItem == MENU_PLAYER_SEND_SERVER_MESSAGE: print "broadcast a message..." - msg = self.GetMessageInput( "Broadcast Server Message" ) + msg = self.GetMessageInput("Broadcast Server Message") # If we got a message back, send it if len(msg): - self.main.server.server.broadcast( msg ) + self.main.server.server.broadcast(msg) - def GetMessageInput( self, title ): + def GetMessageInput(self, title): prompt = "Please enter the message you wish to send:" msg = wx.TextEntryDialog(self, prompt, title) msg.ShowModal() @@ -299,11 +303,11 @@ STATUS = SERVER_STOPPED def __init__(self, parent, id, title): - wx.Frame.__init__(self, parent, id, title, size = (760, 560) ) + 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 ) + icon = wx.Icon(dir_struct["icon"]+'WAmisc9.ico', wx.BITMAP_TYPE_ICO) else: - icon = wx.Icon( orpg.dirpath.dir_struct["icon"]+'connect.gif', wx.BITMAP_TYPE_GIF ) + icon = wx.Icon(dir_struct["icon"]+'connect.gif', wx.BITMAP_TYPE_GIF) self.SetIcon(icon) self.serverName = "Server Name" self.bootPwd = "" @@ -347,62 +351,62 @@ # File Menu menu = wx.Menu() # Start - menu.Append( MENU_START_SERVER, 'Start', 'Start server.') + menu.Append(MENU_START_SERVER, 'Start', 'Start server.') self.Bind(wx.EVT_MENU, self.OnStart, id=MENU_START_SERVER) # Stop - menu.Append( MENU_STOP_SERVER, 'Stop', 'Shutdown server.') + menu.Append(MENU_STOP_SERVER, 'Stop', 'Shutdown server.') self.Bind(wx.EVT_MENU, self.OnStop, id=MENU_STOP_SERVER) # Exit menu.AppendSeparator() - menu.Append( MENU_EXIT, 'E&xit', 'Exit application.') + menu.Append(MENU_EXIT, 'E&xit', 'Exit application.') self.Bind(wx.EVT_MENU, self.OnExit, id=MENU_EXIT) self.mainMenu.Append(menu, '&Server') # Registration Menu menu = wx.Menu() # Register - menu.Append( MENU_REGISTER_SERVER, 'Register', 'Register with OpenRPG server directory.') + menu.Append(MENU_REGISTER_SERVER, 'Register', 'Register with OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnRegister, id=MENU_REGISTER_SERVER) # Unregister - menu.Append( MENU_UNREGISTER_SERVER, 'Unregister', 'Unregister from OpenRPG server directory.') + menu.Append(MENU_UNREGISTER_SERVER, 'Unregister', 'Unregister from OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnUnregister, id=MENU_UNREGISTER_SERVER) # Add the registration menu - self.mainMenu.Append( menu, '&Registration' ) + self.mainMenu.Append(menu, '&Registration') # Server Configuration Menu menu = wx.Menu() # Ping Connected Players - menu.Append( MENU_START_PING_PLAYERS, 'Start Ping', 'Ping players to validate remote connection.' ) + menu.Append(MENU_START_PING_PLAYERS, 'Start Ping', 'Ping players to validate remote connection.') self.Bind(wx.EVT_MENU, self.PingPlayers, id=MENU_START_PING_PLAYERS) # Stop Pinging Connected Players - menu.Append( MENU_STOP_PING_PLAYERS, 'Stop Ping', 'Stop validating player connections.' ) + menu.Append(MENU_STOP_PING_PLAYERS, 'Stop Ping', 'Stop validating player connections.') self.Bind(wx.EVT_MENU, self.StopPingPlayers, id=MENU_STOP_PING_PLAYERS) # Set Ping Interval - menu.Append( MENU_PING_INTERVAL, 'Ping Interval', 'Change the ping interval.' ) + menu.Append(MENU_PING_INTERVAL, 'Ping Interval', 'Change the ping interval.') self.Bind(wx.EVT_MENU, self.ConfigPingInterval, id=MENU_PING_INTERVAL) - self.mainMenu.Append( menu, '&Configuration' ) + self.mainMenu.Append(menu, '&Configuration') # Add the menus to the main menu bar - self.SetMenuBar( self.mainMenu ) + self.SetMenuBar(self.mainMenu) # Disable register, unregister & stop server by default - self.mainMenu.Enable( MENU_STOP_SERVER, False ) - self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) - self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) + self.mainMenu.Enable(MENU_STOP_SERVER, False) + self.mainMenu.Enable(MENU_REGISTER_SERVER, False) + self.mainMenu.Enable(MENU_UNREGISTER_SERVER, False) # Disable the ping menu items - self.mainMenu.Enable( MENU_START_PING_PLAYERS, False ) - self.mainMenu.Enable( MENU_STOP_PING_PLAYERS, False ) - self.mainMenu.Enable( MENU_PING_INTERVAL, False ) + self.mainMenu.Enable(MENU_START_PING_PLAYERS, False) + self.mainMenu.Enable(MENU_STOP_PING_PLAYERS, False) + self.mainMenu.Enable(MENU_PING_INTERVAL, False) def build_body(self): """ Create the ViewNotebook and logger. """ splitter = wx.SplitterWindow(self, -1, style=wx.NO_3D | wx.SP_3D) - nb = wx.Notebook( splitter, -1 ) - self.conns = Connections( nb, self ) - nb.AddPage( self.conns, "Players" ) + nb = wx.Notebook(splitter, -1) + self.conns = Connections(nb, self) + nb.AddPage(self.conns, "Players") #Not sure why this is Remarked TaS - Sirebral - #nb.AddPage( self.conns, "Rooms" ) - #self.msgWindow = HTMLMessageWindow( nb ) - #nb.AddPage( self.msgWindow, "Messages" ) + #nb.AddPage(self.conns, "Rooms") + #self.msgWindow = HTMLMessageWindow(nb) + #nb.AddPage(self.msgWindow, "Messages") log = wx.TextCtrl(splitter, -1, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL) - wx.Log.SetActiveTarget( wx.LogTextCtrl(log) ) + wx.Log.SetActiveTarget(wx.LogTextCtrl(log)) splitter.SplitHorizontally(nb, log, 400) splitter.SetMinimumPaneSize(40) self.nb = nb @@ -431,12 +435,12 @@ # Event handler for out logging event - def OnLogMessage( self, event ): - self.Log( event.message ) + def OnLogMessage(self, event): + self.Log(event.message) # Event handler for out logging event - def OnFunctionMessage( self, event ): - self.callbacks[event.func]( event.message ) + def OnFunctionMessage(self, event): + self.callbacks[event.func](event.message) ### Server Callbacks ##################################### def Log(self, log): @@ -461,30 +465,30 @@ self.total_data_received += bytes self.sb.SetStatusText("Recv: %s (%d)" % (format_bytes(self.total_data_received), self.total_messages_received), 2) - def OnCreateGroup( self, data ): + def OnCreateGroup(self, data): print "room list: ", self.conns.roomList self.conns.roomList[id] = name (id, name) = data print "room list: ", self.conns.roomList - def OnDeleteGroup( self, data ): + def OnDeleteGroup(self, data): (from_id, id) = data #del self.conns.roomList[id] print "OnDeleteGroup room list: ", self.conns.roomList, id - def OnJoinGroup( self, data ): - self.conns.updateRoom( data ) + def OnJoinGroup(self, data): + self.conns.updateRoom(data) - def OnSetRole( self, data ): + def OnSetRole(self, data): (id, role) = data - self.conns.setPlayerRole( id, role ) + self.conns.setPlayerRole(id, role) ### Misc. ################################################ def OnStart(self, event = None): """ Start server. """ 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 ) + 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() # see if we already have password specified @@ -492,10 +496,10 @@ # check the server_ini for a password # duplicates code in mplay_server's initServer() and initServerConfig() # needs refactoring - userPath = orpg.dirpath.dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + userPath = dir_struct["user"] + validate.config_file("server_ini.xml", "default_server_ini.xml") + configDom = ElementTree(file=userPath + 'server_ini.xml').\ + getroot() configDom.normalize() configDoc = configDom.documentElement if configDoc.hasAttribute("admin"): @@ -516,9 +520,9 @@ self.STATUS = SERVER_RUNNING self.sb.SetStatusText("Running", 3) self.SetTitle(__appname__ + "- (running) - (unregistered)") - self.mainMenu.Enable( MENU_START_SERVER, False ) - self.mainMenu.Enable( MENU_STOP_SERVER, True ) - self.mainMenu.Enable( MENU_REGISTER_SERVER, True ) + self.mainMenu.Enable(MENU_START_SERVER, False) + 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") @@ -531,10 +535,10 @@ self.STATUS = SERVER_STOPPED self.sb.SetStatusText("Stopped", 3) self.SetTitle(__appname__ + "- (stopped) - (unregistered)") - self.mainMenu.Enable( MENU_STOP_SERVER, False ) - self.mainMenu.Enable( MENU_START_SERVER, True ) - self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) - self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) + self.mainMenu.Enable(MENU_STOP_SERVER, False) + self.mainMenu.Enable(MENU_START_SERVER, True) + self.mainMenu.Enable(MENU_REGISTER_SERVER, False) + self.mainMenu.Enable(MENU_UNREGISTER_SERVER, False) # Delete any items that are still in the player list self.conns.DeleteAllItems() @@ -543,13 +547,13 @@ This will begin registerThread(s) to keep server registered with configured metas """ - if len( self.serverName ): + if len(self.serverName): wx.BeginBusyCursor() self.server.server.register(self.serverName) - self.sb.SetStatusText( ("%s" % (self.serverName)), 4 ) - self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) - self.mainMenu.Enable( MENU_UNREGISTER_SERVER, True ) - self.mainMenu.Enable( MENU_STOP_SERVER, False ) + self.sb.SetStatusText(("%s" % (self.serverName)), 4) + self.mainMenu.Enable(MENU_REGISTER_SERVER, False) + self.mainMenu.Enable(MENU_UNREGISTER_SERVER, True) + self.mainMenu.Enable(MENU_STOP_SERVER, False) self.SetTitle(__appname__ + "- (running) - (registered)") wx.EndBusyCursor() @@ -561,23 +565,23 @@ """ wx.BeginBusyCursor() self.server.server.unregister() - self.sb.SetStatusText( "Unregistered", 4 ) - self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) - self.mainMenu.Enable( MENU_REGISTER_SERVER, True ) - self.mainMenu.Enable( MENU_STOP_SERVER, True ) + self.sb.SetStatusText("Unregistered", 4) + self.mainMenu.Enable(MENU_UNREGISTER_SERVER, False) + self.mainMenu.Enable(MENU_REGISTER_SERVER, True) + self.mainMenu.Enable(MENU_STOP_SERVER, True) self.SetTitle(__appname__ + "- (running) - (unregistered)") wx.EndBusyCursor() - def PingPlayers( self, event = None ): + def PingPlayers(self, event = None): "Ping all players that are connected at a periodic interval, detecting dropped connections." wx.BeginBusyCursor() wx.Yield() wx.EndBusyCursor() - def StopPingPlayers( self, event = None ): + def StopPingPlayers(self, event = None): "Stop pinging connected players." - def ConfigPingInterval( self, event = None ): + def ConfigPingInterval(self, event = None): "Configure the player ping interval. Note that all players are pinged on a single timer." def OnExit(self, event = None): @@ -589,7 +593,7 @@ def OnInit(self): # Make sure our image handlers are loaded before we try to display anything wx.InitAllImageHandlers() - self.splash = wx.SplashScreen(wx.Bitmap(orpg.dirpath.dir_struct["icon"]+'splash.gif'), + self.splash = wx.SplashScreen(wx.Bitmap(dir_struct["icon"]+'splash.gif'), wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT, 2000, None) @@ -609,12 +613,12 @@ "Widget used to present user to admin messages, in HTML format, to the server administrator" # Init using the derived from class - def __init__( self, parent ): - wx.html.HtmlWindow.__init__( self, parent ) - def OnLinkClicked( self, ref ): + def __init__(self, parent): + wx.html.HtmlWindow.__init__(self, parent) + def OnLinkClicked(self, ref): "Open an external browser to resolve our About box links!!!" href = ref.GetHref() - webbrowser.open( href ) + webbrowser.open(href) if __name__ == '__main__': app = ServerGUIApp(0)
--- a/orpg/orpg_windows.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/orpg_windows.py Thu Mar 25 17:56:48 2010 -0600 @@ -25,6 +25,11 @@ # # Description: orpg custom windows # +import warnings + +warnings.warn("The orpg_windows module is depreciated, please find "\ + "the class you are looking for in the new ui package", + DeprecationWarning, 2) from orpg.orpg_wx import * from orpg.orpgCore import *
--- a/orpg/player_list.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/player_list.py Thu Mar 25 17:56:48 2010 -0600 @@ -26,11 +26,9 @@ # # Description: This is the main entry point of the oprg application # - -__version__ = '$Id: player_list.py,v 1.29 2007/03/30 19:12:06 digitalxero Exp $' +import wx -from orpg.orpg_windows import * - +from orpg.orpgCore import open_rpg from orpg.dirpath import dir_struct from orpg.tools.settings import settings from orpg.tools.orpg_log import logger
--- a/orpg/pluginhandler.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/pluginhandler.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,4 +1,5 @@ -from orpg.orpg_wx import * +import wx + from orpg.orpgCore import open_rpg from orpg.dirpath import dir_struct from orpg.tools.settings import settings
--- a/orpg/tools/ButtonPanel.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,5 +0,0 @@ -import warnings -warnings.warn("The new way to access this is orpg.external.agw.buttonpanel", - category=PendingDeprecationWarning) - -from orpg.external.agw.buttonpanel import * \ No newline at end of file
--- a/orpg/tools/FlatNotebook.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,5 +0,0 @@ -import warnings -warnings.warn("The new way to access this is orpg.external.agw.flatnotebook", - category=PendingDeprecationWarning) - -from orpg.external.agw.flatnotebook import * \ No newline at end of file
--- a/orpg/tools/NotebookCtrl.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,5 +0,0 @@ -import warnings -warnings.warn("The new way to access this is orpg.external.notebookctrl", - category=PendingDeprecationWarning) - -from orpg.external.notebookctrl import * \ No newline at end of file
--- a/orpg/tools/PyAUI.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,4935 +0,0 @@ -import warnings -warnings.warn("PyAUI is no longer supported", - category=DeprecationWarning) - -# --------------------------------------------------------------------------- # -# PYAUI Library wxPython IMPLEMENTATION -# -# Original C++ Code From Kirix (wxAUI). You Can Find It At: -# -# License: wxWidgets license -# -# http://www.kirix.com/en/community/opensource/wxaui/about_wxaui.html -# -# Current wxAUI Version Tracked: 0.9.2 -# -# -# Python Code By: -# -# Andrea Gavana, @ 23 Dec 2005 -# Latest Revision: 30 Jun 2006, 21.00 GMT -# -# -# PyAUI version 0.9.2 Adds: -# -# * Fixes For Display Glitches; -# * Fixes For Other Bugs Found In Previous Versions. -# -# -# TODO List/Caveats -# -# 1. Using The New Versions Of wxPython (2.6.2.1pre.20060106 Or Higher) There -# Is A New Method Called wx.GetMouseState() That Gets Rid Of The Import Of -# win32all or ctypes. Moreover, It Should Make PyAUI Working On All -# Platforms (I Hope). -# -# -# Latest Patches: -# -# 1) Reduced Flicker While Drawing The Dock Hint -# 2) Made Impossoible To Drag The Sash Separator Outside The Main Frame -# 3) Improved Repaint When Using The Active Pane Option -# 4) Fixed The Mac Problem (Thanks To David Pratt) And Applied The wxGTK Patches -# Suggested By Robin Dunn To Correctly Draw The Dock Hint -# -# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please -# Write To Me At: -# -# andrea.gavana@agip.it -# andrea_gavan@tin.it -# -# Or, Obviously, To The wxPython Mailing List!!! -# -# with OS X support and refactoring implemented by Chris Mellon (arkanes@gmail.com) - -# contact me directly or on wxPython ML for more info -# -# -# End Of Comments -# --------------------------------------------------------------------------- # - -""" -PyAUI is an Advanced User Interface library that aims to implement "cutting-edge" -interface usability and design features so developers can quickly and easily create -beautiful and usable application interfaces. - -Vision and Design Principles - -PyAUI attempts to encapsulate the following aspects of the user interface: - -* Frame Management: Frame management provides the means to open, move and hide common -controls that are needed to interact with the document, and allow these configurations -to be saved into different perspectives and loaded at a later time. - -* Toolbars: Toolbars are a specialized subset of the frame management system and should -behave similarly to other docked components. However, they also require additional -functionality, such as "spring-loaded" rebar support, "chevron" buttons and end-user -customizability. - -* Modeless Controls: Modeless controls expose a tool palette or set of options that -float above the application content while allowing it to be accessed. Usually accessed -by the toolbar, these controls disappear when an option is selected, but may also be -"torn off" the toolbar into a floating frame of their own. - -* Look and Feel: Look and feel encompasses the way controls are drawn, both when shown -statically as well as when they are being moved. This aspect of user interface design -incorporates "special effects" such as transparent window dragging as well as frame animation. - -PyAUI adheres to the following principles: - -- Use native floating frames to obtain a native look and feel for all platforms; -- Use existing wxPython code where possible, such as sizer implementation for frame management; -- Use standard wxPython coding conventions. - - -Usage: - -The following example shows a simple implementation that utilizes AuiManager to manage -three text controls in a frame window: - -class MyFrame(wx.Frame): - - def __init__(self, parent, id=-1, title="PyAUI Test", pos=wx.DefaultPosition, - size=(800, 600), style=wx.DEFAULT_FRAME_STYLE): - - wx.Frame.__init__(self, parent, id, title, pos, size, style) - - self._mgr = PyAUI.AuiManager() - - # notify PyAUI which frame to use - self._mgr.SetFrame(self) - - # create several text controls - text1 = wx.TextCtrl(self, -1, "Pane 1 - sample text", - wx.DefaultPosition, wx.Size(200,150), - wx.NO_BORDER | wx.TE_MULTILINE) - - text2 = wx.TextCtrl(self, -1, "Pane 2 - sample text", - wx.DefaultPosition, wx.Size(200,150), - wx.NO_BORDER | wx.TE_MULTILINE) - - text3 = wx.TextCtrl(self, -1, "Main content window", - wx.DefaultPosition, wx.Size(200,150), - wx.NO_BORDER | wx.TE_MULTILINE) - - # add the panes to the manager - self._mgr.AddPane(text1, wx.LEFT, "Pane Number One") - self._mgr.AddPane(text2, wx.BOTTOM, "Pane Number Two") - self._mgr.AddPane(text3, wx.CENTER) - - # tell the manager to "commit" all the changes just made - self._mgr.Update() - - self.Bind(wx.EVT_CLOSE, self.OnClose) - - - def OnClose(self, event): - - # deinitialize the frame manager - self._mgr.UnInit() - - self.Destroy() - event.Skip() - - -# our normal wxApp-derived class, as usual - -app = wx.PySimpleApp() - -frame = MyFrame(None) -app.SetTopWindow(frame) -frame.Show() - -app.MainLoop() - -What's New: - -PyAUI version 0.9.2 Adds: - -* Fixes For Display Glitches; -* Fixes For Other Bugs Found In Previous Versions. - - -License And Version: - -PyAUI Library Is Freeware And Distributed Under The wxPython License. - -Latest Revision: Andrea Gavana @ 30 Jun 2006, 21.00 GMT -Version 0.9.2. - -""" - -from orpg.orpg_wx import * -import cStringIO, zlib -import time - -_libimported = None -_newversion = False - -# Check For The New wxVersion: It Should Be > 2.6.2.1pre.20060102 -# In Order To Let PyAUI Working On All Platforms - -wxver = wx.VERSION_STRING -if wxver < "2.7": - wx.Rect.Contains = lambda self, point: wx.Rect.Inside(self, point) - -if hasattr(wx, "GetMouseState"): - _newversion = True - if wx.Platform == "__WXMSW__": - try: - import win32api - import win32con - import winxpgui - _libimported = "MH" - except: - try: - import ctypes - _libimported = "ctypes" - except: - pass - -else: - if wx.Platform == "__WXMSW__": - try: - import win32api - import win32con - import winxpgui - _libimported = "MH" - except: - try: - import ctypes - _libimported = "ctypes" - except: - raise "\nERROR: At Present, On Windows Machines, You Need To Install "\ - "Mark Hammond's pywin32 Extensions Or The ctypes Module, Or Download" \ - "The Latest wxPython Version." - - else: - raise "\nSorry: I Still Don't Know How To Work On GTK/MAC Platforms... " \ - "Please Download The Latest wxPython Version." - - -if wx.Platform == "__WXMAC__": - try: - import ctypes - _carbon_dll = ctypes.cdll.LoadLibrary(r'/System/Frameworks/Carbon.framework/Carbon') - except: - _carbon_dll = None - -# Docking Styles -AUI_DOCK_NONE = 0 -AUI_DOCK_TOP = 1 -AUI_DOCK_RIGHT = 2 -AUI_DOCK_BOTTOM = 3 -AUI_DOCK_LEFT = 4 -AUI_DOCK_CENTER = 5 -AUI_DOCK_CENTRE = AUI_DOCK_CENTER - -# Floating/Dragging Styles -AUI_MGR_ALLOW_FLOATING = 1 -AUI_MGR_ALLOW_ACTIVE_PANE = 2 -AUI_MGR_TRANSPARENT_DRAG = 4 -AUI_MGR_TRANSPARENT_HINT = 8 -AUI_MGR_TRANSPARENT_HINT_FADE = 16 - -AUI_MGR_DEFAULT = AUI_MGR_ALLOW_FLOATING | \ - AUI_MGR_TRANSPARENT_HINT | \ - AUI_MGR_TRANSPARENT_HINT_FADE | \ - AUI_MGR_TRANSPARENT_DRAG - -# Panes Customization -AUI_ART_SASH_SIZE = 0 -AUI_ART_CAPTION_SIZE = 1 -AUI_ART_GRIPPER_SIZE = 2 -AUI_ART_PANE_BORDER_SIZE = 3 -AUI_ART_PANE_BUTTON_SIZE = 4 -AUI_ART_BACKGROUND_COLOUR = 5 -AUI_ART_SASH_COLOUR = 6 -AUI_ART_ACTIVE_CAPTION_COLOUR = 7 -AUI_ART_ACTIVE_CAPTION_GRADIENT_COLOUR = 8 -AUI_ART_INACTIVE_CAPTION_COLOUR = 9 -AUI_ART_INACTIVE_CAPTION_GRADIENT_COLOUR = 10 -AUI_ART_ACTIVE_CAPTION_TEXT_COLOUR = 11 -AUI_ART_INACTIVE_CAPTION_TEXT_COLOUR = 12 -AUI_ART_BORDER_COLOUR = 13 -AUI_ART_GRIPPER_COLOUR = 14 -AUI_ART_CAPTION_FONT = 15 -AUI_ART_GRADIENT_TYPE = 16 - -# Caption Gradient Type -AUI_GRADIENT_NONE = 0 -AUI_GRADIENT_VERTICAL = 1 -AUI_GRADIENT_HORIZONTAL = 2 - -# Pane Button State -AUI_BUTTON_STATE_NORMAL = 0 -AUI_BUTTON_STATE_HOVER = 1 -AUI_BUTTON_STATE_PRESSED = 2 - -# Pane Insert Level -AUI_INSERT_PANE = 0 -AUI_INSERT_ROW = 1 -AUI_INSERT_DOCK = 2 - -# some built in bitmaps -close_bits = '\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00' \ - '\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00' \ - '\xef\x00\x00\x00\xfb\x00\x00\x00\xcf\x00\x00\x00\xf9\x00\x00\x00' \ - '\x9f\x00\x00\x00\xfc\x00\x00\x00?\x00\x00\x00\xfe\x00\x00\x00?\x00' \ - '\x00\x00\xfe\x00\x00\x00\x9f\x00\x00\x00\xfc\x00\x00\x00\xcf\x00' \ - '\x00\x00\xf9\x00\x00\x00\xef\x00\x00\x00\xfb\x00\x00\x00\xff\x00' \ - '\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00' \ - '\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00' - -pin_bits = '\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff' \ - '\x00\x00\x00\xff\x00\x00\x00\x1f\x00\x00\x00\xfc\x00\x00\x00\xdf\x00' \ - '\x00\x00\xfc\x00\x00\x00\xdf\x00\x00\x00\xfc\x00\x00\x00\xdf\x00\x00' \ - '\x00\xfc\x00\x00\x00\xdf\x00\x00\x00\xfc\x00\x00\x00\xdf\x00\x00\x00' \ - '\xfc\x00\x00\x00\x0f\x00\x00\x00\xf8\x00\x00\x00\x7f\x00\x00\x00\xff' \ - '\x00\x00\x00\x7f\x00\x00\x00\xff\x00\x00\x00\x7f\x00\x00\x00\xff\x00' \ - '\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00\x00\xff\x00\x00' \ - '\x00\xff\x00\x00\x00\xff\x00\x00\x00' - -# PyAUI Event -wxEVT_AUI_PANEBUTTON = wx.NewEventType() -EVT_AUI_PANEBUTTON = wx.PyEventBinder(wxEVT_AUI_PANEBUTTON, 0) -wxEVT_AUI_PANECLOSE = wx.NewEventType() -EVT_AUI_PANECLOSE = wx.PyEventBinder(wxEVT_AUI_PANECLOSE, 0) - - -def GetCloseData(): - return zlib.decompress( -'x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\x02 \xcc\xc1\ -\x06$\xe5?\xffO\x04R,\xc5N\x9e!\x1c@P\xc3\x91\xd2\x01\xe4Gy\xba8\x86X\xf4\ -\x9e\r:\xcd\xc7\xa0\xc0\xe1\xf5\xfb\xbf\xff\xbb\xc2\xacb6\xdbg\xaez\xb9|\x1c\ -\x9a\x82kU\x99xW\x16K\xf5\xdccS\xdad\xe9\xf3\xe0\xa4\x0f\x0f\xaf\xcb\xea\x88\ -\x8bV\xd7k\x1eoN\xdf\xb2\xdd\xc8\xd0\xe7Cw2{\xdd\\uf\xfd}3\x0f\xb0\xd4=\x0ff\ -\xdfr$\\\xe5\xcf\xa9\xfd3\xfa\xcdu\xa4\x7fk\xa6\x89\x03ma\xf0t\xf5sY\xe7\x94\ -\xd0\x04\x00\x1714z') - - -def GetCloseBitmap(): - return wx.BitmapFromImage(GetCloseImage()) - - -def GetCloseImage(): - stream = cStringIO.StringIO(GetCloseData()) - return wx.ImageFromStream(stream) - - -def StepColour(c, percent): - """ - StepColour() it a utility function that simply darkens - a color by the specified percentage. - """ - - r = c.Red() - g = c.Green() - b = c.Blue() - - return wx.Colour(min((r*percent)/100, 255), - min((g*percent)/100, 255), - min((b*percent)/100, 255)) - - -def LightContrastColour(c): - - amount = 120 - - # if the color is especially dark, then - # make the contrast even lighter - if c.Red() < 128 and c.Green() < 128 and c.Blue() < 128: - amount = 160 - - return StepColour(c, amount) - - -def BitmapFromBits(color, type=0): - """ - BitmapFromBits() is a utility function that creates a - masked bitmap from raw bits (XBM format). - """ - - if type == 0: # Close Bitmap - img = GetCloseImage() - else: - # this should be GetClosePin()... but what the hell is a "pin"? - img = GetCloseImage() - - img.Replace(255, 255, 255, 123, 123, 123) - img.Replace(0, 0, 0, color.Red(), color.Green(), color.Blue()) - - return img.ConvertToBitmap() - - -def DrawGradientRectangle(dc, rect, start_color, end_color, direction): - - rd = end_color.Red() - start_color.Red() - gd = end_color.Green() - start_color.Green() - bd = end_color.Blue() - start_color.Blue() - - if direction == AUI_GRADIENT_VERTICAL: - high = rect.GetHeight() - 1 - else: - high = rect.GetWidth() - 1 - - for ii in xrange(high+1): - r = start_color.Red() + ((ii*rd*100)/high)/100 - g = start_color.Green() + ((ii*gd*100)/high)/100 - b = start_color.Blue() + ((ii*bd*100)/high)/100 - - p = wx.Pen(wx.Colour(r, g, b)) - dc.SetPen(p) - - if direction == AUI_GRADIENT_VERTICAL: - dc.DrawLine(rect.x, rect.y+ii, rect.x+rect.width, rect.y+ii) - else: - dc.DrawLine(rect.x+ii, rect.y, rect.x+ii, rect.y+rect.height) - - -class DockInfo: - - def __init__(self): - - self.dock_direction = 0 - self.dock_layer = 0 - self.dock_row = 0 - self.size = 0 - self.min_size = 0 - self.resizable = True - self.fixed = False - self.toolbar = False - self.rect = wx.Rect() - self.panes = [] - - - def IsOk(self): - - return (self.dock_direction != 0 and [True] or [False])[0] - - - def IsHorizontal(self): - - return ((self.dock_direction == AUI_DOCK_TOP or \ - self.dock_direction == AUI_DOCK_BOTTOM) and \ - [True] or [False])[0] - - - def IsVertical(self): - - return ((self.dock_direction == AUI_DOCK_LEFT or \ - self.dock_direction == AUI_DOCK_RIGHT or \ - self.dock_direction == AUI_DOCK_CENTER) and [True] or [False])[0] - - -class DockUIPart: - - typeCaption = 0 - typeGripper = 1 - typeDock = 2 - typeDockSizer = 3 - typePane = 4 - typePaneSizer = 5 - typeBackground = 6 - typePaneBorder = 7 - typePaneButton = 8 - - def __init__(self): - - self.orientation = wx.VERTICAL - self.type = 0 - self.rect = wx.Rect() - - -class PaneButton: - - def __init__(self, button_id): - - self.button_id = button_id - - -# event declarations/classes - -class AuiManagerEvent(wx.PyCommandEvent): - - def __init__(self, eventType, id=1): - - wx.PyCommandEvent.__init__(self, eventType, id) - - self.pane = None - self.button = 0 - - - def SetPane(self, p): - - self.pane = p - - - def SetButton(self, b): - - self.button = b - - - def GetPane(self): - - return self.pane - - - def GetButton(self): - - return self.button - - -# -- DefaultDockArt class implementation -- -# -# DefaultDockArt is an art provider class which does all of the drawing for -# AuiManager. This allows the library caller to customize the dock art -# (probably by deriving from this class), or to completely replace all drawing -# with custom dock art. The active dock art class can be set via -# AuiManager.SetDockArt() - -class DefaultDockArt: - - def __init__(self): - - base_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DFACE) - darker1_color = StepColour(base_color, 85) - darker2_color = StepColour(base_color, 70) - darker3_color = StepColour(base_color, 60) - darker4_color = StepColour(base_color, 50) - darker5_color = StepColour(base_color, 40) - - self._active_caption_colour = LightContrastColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)) - self._active_caption_gradient_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT) - self._active_caption_text_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT) - self._inactive_caption_colour = StepColour(darker1_color, 80) - self._inactive_caption_gradient_colour = darker1_color - self._inactive_caption_text_colour = wx.BLACK - - sash_color = base_color - caption_color = darker1_color - paneborder_color = darker2_color - selectbutton_color = base_color - selectbuttonpen_color = darker3_color - - self._sash_brush = wx.Brush(base_color) - self._background_brush = wx.Brush(base_color) - self._border_pen = wx.Pen(darker2_color) - self._gripper_brush = wx.Brush(base_color) - self._gripper_pen1 = wx.Pen(darker5_color) - self._gripper_pen2 = wx.Pen(darker3_color) - self._gripper_pen3 = wx.WHITE_PEN - - self._caption_font = wx.Font(8, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False) - - self._inactive_close_bitmap = BitmapFromBits(self._inactive_caption_text_colour, 0) - self._inactive_pin_bitmap = BitmapFromBits(self._inactive_caption_text_colour, 1) - self._active_close_bitmap = BitmapFromBits(self._active_caption_text_colour, 0) - self._active_pin_bitmap = BitmapFromBits(self._active_caption_text_colour, 1) - - # default metric values - self._sash_size = 4 - self._caption_size = 17 - self._border_size = 1 - self._button_size = 14 - self._gripper_size = 9 - self._gradient_type = AUI_GRADIENT_VERTICAL - - - def GetMetric(self, id): - - if id == AUI_ART_SASH_SIZE: - return self._sash_size - elif id == AUI_ART_CAPTION_SIZE: - return self._caption_size - elif id == AUI_ART_GRIPPER_SIZE: - return self._gripper_size - elif id == AUI_ART_PANE_BORDER_SIZE: - return self._border_size - elif id == AUI_ART_PANE_BUTTON_SIZE: - return self._button_size - elif id == AUI_ART_GRADIENT_TYPE: - return self._gradient_type - else: - raise "\nERROR: Invalid Metric Ordinal. " - - - def SetMetric(self, id, new_val): - - if id == AUI_ART_SASH_SIZE: - self._sash_size = new_val - elif id == AUI_ART_CAPTION_SIZE: - self._caption_size = new_val - elif id == AUI_ART_GRIPPER_SIZE: - self._gripper_size = new_val - elif id == AUI_ART_PANE_BORDER_SIZE: - self._border_size = new_val - elif id == AUI_ART_PANE_BUTTON_SIZE: - self._button_size = new_val - elif id == AUI_ART_GRADIENT_TYPE: - self._gradient_type = new_val - else: - raise "\nERROR: Invalid Metric Ordinal. " - - - def GetColor(self, id): - - if id == AUI_ART_BACKGROUND_COLOUR: - return self._background_brush.GetColour() - elif id == AUI_ART_SASH_COLOUR: - return self._sash_brush.GetColour() - elif id == AUI_ART_INACTIVE_CAPTION_COLOUR: - return self._inactive_caption_colour - elif id == AUI_ART_INACTIVE_CAPTION_GRADIENT_COLOUR: - return self._inactive_caption_gradient_colour - elif id == AUI_ART_INACTIVE_CAPTION_TEXT_COLOUR: - return self._inactive_caption_text_colour - elif id == AUI_ART_ACTIVE_CAPTION_COLOUR: - return self._active_caption_colour - elif id == AUI_ART_ACTIVE_CAPTION_GRADIENT_COLOUR: - return self._active_caption_gradient_colour - elif id == AUI_ART_ACTIVE_CAPTION_TEXT_COLOUR: - return self._active_caption_text_colour - elif id == AUI_ART_BORDER_COLOUR: - return self._border_pen.GetColour() - elif id == AUI_ART_GRIPPER_COLOUR: - return self._gripper_brush.GetColour() - else: - raise "\nERROR: Invalid Metric Ordinal. " - - - def SetColor(self, id, colour): - - if id == AUI_ART_BACKGROUND_COLOUR: - self._background_brush.SetColour(colour) - elif id == AUI_ART_SASH_COLOUR: - self._sash_brush.SetColour(colour) - elif id == AUI_ART_INACTIVE_CAPTION_COLOUR: - self._inactive_caption_colour = colour - elif id == AUI_ART_INACTIVE_CAPTION_GRADIENT_COLOUR: - self._inactive_caption_gradient_colour = colour - elif id == AUI_ART_INACTIVE_CAPTION_TEXT_COLOUR: - self._inactive_caption_text_colour = colour - elif id == AUI_ART_ACTIVE_CAPTION_COLOUR: - self._active_caption_colour = colour - elif id == AUI_ART_ACTIVE_CAPTION_GRADIENT_COLOUR: - self._active_caption_gradient_colour = colour - elif id == AUI_ART_ACTIVE_CAPTION_TEXT_COLOUR: - self._active_caption_text_colour = colour - elif id == AUI_ART_BORDER_COLOUR: - self._border_pen.SetColour(colour) - elif id == AUI_ART_GRIPPER_COLOUR: - self._gripper_brush.SetColour(colour) - self._gripper_pen1.SetColour(StepColour(colour, 40)) - self._gripper_pen2.SetColour(StepColour(colour, 60)) - else: - raise "\nERROR: Invalid Metric Ordinal. " - - - GetColour = GetColor - SetColour = SetColor - - def SetFont(self, id, font): - - if id == AUI_ART_CAPTION_FONT: - self._caption_font = font - - - def GetFont(self, id): - - if id == AUI_ART_CAPTION_FONT: - return self._caption_font - - return wx.NoneFont - - - def DrawSash(self, dc, orient, rect): - - dc.SetPen(wx.TRANSPARENT_PEN) - dc.SetBrush(self._sash_brush) - dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height) - - - def DrawBackground(self, dc, orient, rect): - - dc.SetPen(wx.TRANSPARENT_PEN) - dc.SetBrush(self._background_brush) - dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height) - - - def DrawBorder(self, dc, rect, pane): - - drect = wx.Rect() - drect.x = rect.x - drect.y = rect.y - drect.width = rect.width - drect.height = rect.height - - dc.SetPen(self._border_pen) - dc.SetBrush(wx.TRANSPARENT_BRUSH) - - border_width = self.GetMetric(AUI_ART_PANE_BORDER_SIZE) - - if pane.IsToolbar(): - - for ii in xrange(0, border_width): - - dc.SetPen(wx.WHITE_PEN) - dc.DrawLine(drect.x, drect.y, drect.x+drect.width, drect.y) - dc.DrawLine(drect.x, drect.y, drect.x, drect.y+drect.height) - dc.SetPen(self._border_pen) - dc.DrawLine(drect.x, drect.y+drect.height-1, - drect.x+drect.width, drect.y+drect.height-1) - dc.DrawLine(drect.x+drect.width-1, drect.y, - drect.x+drect.width-1, drect.y+drect.height) - drect.Deflate(1, 1) - - else: - - for ii in xrange(0, border_width): - - dc.DrawRectangle(drect.x, drect.y, drect.width, drect.height) - drect.Deflate(1, 1) - - - def DrawCaptionBackground(self, dc, rect, active): - - if self._gradient_type == AUI_GRADIENT_NONE: - if active: - dc.SetBrush(wx.Brush(self._active_caption_colour)) - else: - dc.SetBrush(wx.Brush(self._inactive_caption_colour)) - - dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height) - else: - if active: - DrawGradientRectangle(dc, rect, self._active_caption_colour, - self._active_caption_gradient_colour, - self._gradient_type) - else: - DrawGradientRectangle(dc, rect, self._inactive_caption_colour, - self._inactive_caption_gradient_colour, - self._gradient_type) - - - def DrawCaption(self, dc, text, rect, pane): - - dc.SetPen(wx.TRANSPARENT_PEN) - dc.SetFont(self._caption_font) - - self.DrawCaptionBackground(dc, rect, ((pane.state & AuiPaneInfo.optionActive) and \ - [True] or [False])[0]) - - if pane.state & AuiPaneInfo.optionActive: - dc.SetTextForeground(self._active_caption_text_colour) - else: - dc.SetTextForeground(self._inactive_caption_text_colour) - - w, h = dc.GetTextExtent("ABCDEFHXfgkj") - - dc.SetClippingRegion(rect.x, rect.y, rect.width, rect.height) - dc.DrawText(text, rect.x+3, rect.y+(rect.height/2)-(h/2)-1) - dc.DestroyClippingRegion() - - - def DrawGripper(self, dc, rect, pane): - - dc.SetPen(wx.TRANSPARENT_PEN) - dc.SetBrush(self._gripper_brush) - - dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height) - - if not pane.HasGripperTop(): - y = 5 - while 1: - dc.SetPen(self._gripper_pen1) - dc.DrawPoint(rect.x+3, rect.y+y) - dc.SetPen(self._gripper_pen2) - dc.DrawPoint(rect.x+3, rect.y+y+1) - dc.DrawPoint(rect.x+4, rect.y+y) - dc.SetPen(self._gripper_pen3) - dc.DrawPoint(rect.x+5, rect.y+y+1) - dc.DrawPoint(rect.x+5, rect.y+y+2) - dc.DrawPoint(rect.x+4, rect.y+y+2) - y = y + 4 - if y > rect.GetHeight() - 5: - break - else: - x = 5 - while 1: - dc.SetPen(self._gripper_pen1) - dc.DrawPoint(rect.x+x, rect.y+3) - dc.SetPen(self._gripper_pen2) - dc.DrawPoint(rect.x+x+1, rect.y+3) - dc.DrawPoint(rect.x+x, rect.y+4) - dc.SetPen(self._gripper_pen3) - dc.DrawPoint(rect.x+x+1, rect.y+5) - dc.DrawPoint(rect.x+x+2, rect.y+5) - dc.DrawPoint(rect.x+x+2, rect.y+4) - x = x + 4 - if x > rect.GetWidth() - 5: - break - - - def DrawPaneButton(self, dc, button, button_state, rect, pane): - - drect = wx.Rect() - drect.x = rect.x - drect.y = rect.y - drect.width = rect.width - drect.height = rect.height - - if button_state == AUI_BUTTON_STATE_PRESSED: - - drect.x = drect.x + 1 - drect.y = drect.y + 1 - - if button_state in [AUI_BUTTON_STATE_HOVER, AUI_BUTTON_STATE_PRESSED]: - - if pane.state & AuiPaneInfo.optionActive: - dc.SetBrush(wx.Brush(StepColour(self._active_caption_colour, 120))) - dc.SetPen(wx.Pen(StepColour(self._active_caption_colour, 70))) - else: - dc.SetBrush(wx.Brush(StepColour(self._inactive_caption_colour, 120))) - dc.SetPen(wx.Pen(StepColour(self._inactive_caption_colour, 70))) - - # draw the background behind the button - dc.DrawRectangle(drect.x, drect.y, 15, 15) - - if button == AuiPaneInfo.buttonClose: - if pane.state & AuiPaneInfo.optionActive: - - bmp = self._active_close_bitmap - - else: - bmp = self._inactive_close_bitmap - elif button == AuiPaneInfo.buttonPin: - if pane.state & AuiPaneInfo.optionActive: - - bmp = self._active_pin_bitmap - - else: - bmp = self._inactive_pin_bitmap - - # draw the button itself - dc.DrawBitmap(bmp, drect.x, drect.y, True) - - -# -- AuiPaneInfo class implementation -- -# -# AuiPaneInfo specifies all the parameters for a pane. These parameters specify where -# the pane is on the screen, whether it is docked or floating, or hidden. In addition, -# these parameters specify the pane's docked position, floating position, preferred -# size, minimum size, caption text among many other parameters. - -class AuiPaneInfo: - - optionFloating = 2**0 - optionHidden = 2**1 - optionLeftDockable = 2**2 - optionRightDockable = 2**3 - optionTopDockable = 2**4 - optionBottomDockable = 2**5 - optionFloatable = 2**6 - optionMovable = 2**7 - optionResizable = 2**8 - optionPaneBorder = 2**9 - optionCaption = 2**10 - optionGripper = 2**11 - optionDestroyOnClose = 2**12 - optionToolbar = 2**13 - optionActive = 2**14 - optionGripperTop = 2**15 - - buttonClose = 2**24 - buttonMaximize = 2**25 - buttonMinimize = 2**26 - buttonPin = 2**27 - buttonCustom1 = 2**28 - buttonCustom2 = 2**29 - buttonCustom3 = 2**30 - actionPane = 2**31 # used internally - - def __init__(self): - - wx.DefaultSize = wx.Size(-1, -1) - self.window = None - self.frame = None - self.state = 0 - self.dock_direction = AUI_DOCK_LEFT - self.dock_layer = 0 - self.dock_row = 0 - self.dock_pos = 0 - self.floating_pos = wx.Point(-1, -1) - self.floating_size = wx.Size(-1, -1) - self.best_size = wx.Size(-1, -1) - self.min_size = wx.Size(-1, -1) - self.max_size = wx.Size(-1, -1) - self.dock_proportion = 0 - self.caption = "" - self.buttons = [] - self.name = "" - self.rect = wx.Rect() - - self.DefaultPane() - - - def IsOk(self): - """ IsOk() returns True if the AuiPaneInfo structure is valid. """ - - return (self.window != None and [True] or [False])[0] - - - def IsFixed(self): - """ IsFixed() returns True if the pane cannot be resized. """ - - return not self.HasFlag(self.optionResizable) - - - def IsResizable(self): - """ IsResizeable() returns True if the pane can be resized. """ - - return self.HasFlag(self.optionResizable) - - - def IsShown(self): - """ IsShown() returns True if the pane should be drawn on the screen. """ - - return not self.HasFlag(self.optionHidden) - - - def IsFloating(self): - """ IsFloating() returns True if the pane is floating. """ - - return self.HasFlag(self.optionFloating) - - - def IsDocked(self): - """ IsDocked() returns True if the pane is docked. """ - - return not self.HasFlag(self.optionFloating) - - - def IsToolbar(self): - """ IsToolbar() returns True if the pane contains a toolbar. """ - - return self.HasFlag(self.optionToolbar) - - - def IsTopDockable(self): - """ - IsTopDockable() returns True if the pane can be docked at the top - of the managed frame. - """ - - return self.HasFlag(self.optionTopDockable) - - - def IsBottomDockable(self): - """ - IsBottomDockable() returns True if the pane can be docked at the bottom - of the managed frame. - """ - - return self.HasFlag(self.optionBottomDockable) - - - def IsLeftDockable(self): - """ - IsLeftDockable() returns True if the pane can be docked at the left - of the managed frame. - """ - - return self.HasFlag(self.optionLeftDockable) - - - def IsRightDockable(self): - """ - IsRightDockable() returns True if the pane can be docked at the right - of the managed frame. - """ - - return self.HasFlag(self.optionRightDockable) - - - def IsDockable(self): - """ IsDockable() returns True if the pane can be docked. """ - - return self.IsTopDockable() or self.IsBottomDockable() or self.IsLeftDockable() or \ - self.IsRightDockable() - - - def IsFloatable(self): - """ - IsFloatable() returns True if the pane can be undocked and displayed as a - floating window. - """ - - return self.HasFlag(self.optionFloatable) - - - def IsMovable(self): - """ - IsMoveable() returns True if the docked frame can be undocked or moved to - another dock position. - """ - - return self.HasFlag(self.optionMovable) - - - def HasCaption(self): - """ HasCaption() returns True if the pane displays a caption. """ - - return self.HasFlag(self.optionCaption) - - - def HasGripper(self): - """ HasGripper() returns True if the pane displays a gripper. """ - - return self.HasFlag(self.optionGripper) - - - def HasBorder(self): - """ HasBorder() returns True if the pane displays a border. """ - - return self.HasFlag(self.optionPaneBorder) - - - def HasCloseButton(self): - """ - HasCloseButton() returns True if the pane displays a button to close - the pane. - """ - - return self.HasFlag(self.buttonClose) - - - def HasMaximizeButton(self): - """ - HasMaximizeButton() returns True if the pane displays a button to - maximize the pane. - """ - - return self.HasFlag(self.buttonMaximize) - - - def HasMinimizeButton(self): - """ - HasMinimizeButton() returns True if the pane displays a button to - minimize the pane. - """ - - return self.HasFlag(self.buttonMinimize) - - - def HasPinButton(self): - """ HasPinButton() returns True if the pane displays a button to float the pane. """ - - return self.HasFlag(self.buttonPin) - - - def HasGripperTop(self): - - return self.HasFlag(self.optionGripperTop) - - - def Window(self, w): - - self.window = w - return self - - - def Name(self, n): - """ Name() sets the name of the pane so it can be referenced in lookup functions. """ - - self.name = n - return self - - - def Caption(self, c): - """ Caption() sets the caption of the pane. """ - - self.caption = c - return self - - - def Left(self): - """ Left() sets the pane dock position to the left side of the frame. """ - - self.dock_direction = AUI_DOCK_LEFT - return self - - - def Right(self): - """ Right() sets the pane dock position to the right side of the frame. """ - - self.dock_direction = AUI_DOCK_RIGHT - return self - - - def Top(self): - """ Top() sets the pane dock position to the top of the frame. """ - - self.dock_direction = AUI_DOCK_TOP - return self - - - def Bottom(self): - """ Bottom() sets the pane dock position to the bottom of the frame. """ - - self.dock_direction = AUI_DOCK_BOTTOM - return self - - - def Center(self): - """ Center() sets the pane to the center position of the frame. """ - - self.dock_direction = AUI_DOCK_CENTER - return self - - - def Centre(self): - """ Centre() sets the pane to the center position of the frame. """ - - self.dock_direction = AUI_DOCK_CENTRE - return self - - - def Direction(self, direction): - """ Direction() determines the direction of the docked pane. """ - - self.dock_direction = direction - return self - - - def Layer(self, layer): - """ Layer() determines the layer of the docked pane. """ - - self.dock_layer = layer - return self - - - def Row(self, row): - """ Row() determines the row of the docked pane. """ - - self.dock_row = row - return self - - - def Position(self, pos): - """ Position() determines the position of the docked pane. """ - - self.dock_pos = pos - return self - - - def MinSize(self, arg1=None, arg2=None): - """ MinSize() sets the minimum size of the pane. """ - - if isinstance(arg1, wx.Size): - ret = self.MinSize1(arg1) - else: - ret = self.MinSize2(arg1, arg2) - - return ret - - - def MinSize1(self, size): - - self.min_size = size - return self - - - def MinSize2(self, x, y): - - self.min_size.Set(x,y) - return self - - - def MaxSize(self, arg1=None, arg2=None): - """ MaxSize() sets the maximum size of the pane. """ - - if isinstance(arg1, wx.Size): - ret = self.MaxSize1(arg1) - else: - ret = self.MaxSize2(arg1, arg2) - - return ret - - - def MaxSize1(self, size): - - self.max_size = size - return self - - - def MaxSize2(self, x, y): - - self.max_size.Set(x,y) - return self - - - def BestSize(self, arg1=None, arg2=None): - """ BestSize() sets the ideal size for the pane. """ - - if isinstance(arg1, wx.Size): - ret = self.BestSize1(arg1) - else: - ret = self.BestSize2(arg1, arg2) - - return ret - - - def BestSize1(self, size): - - self.best_size = size - return self - - - def BestSize2(self, x, y): - - self.best_size.Set(x,y) - return self - - - def FloatingPosition(self, pos): - """ FloatingPosition() sets the position of the floating pane. """ - - self.floating_pos = pos - return self - - - def FloatingSize(self, size): - """ FloatingSize() sets the size of the floating pane. """ - - self.floating_size = size - return self - - - def Fixed(self): - """ Fixed() forces a pane to be fixed size so that it cannot be resized. """ - - return self.SetFlag(self.optionResizable, False) - - - def Resizable(self, resizable=True): - """ - Resizable() allows a pane to be resizable if resizable is True, and forces - it to be a fixed size if resizeable is False. - """ - - return self.SetFlag(self.optionResizable, resizable) - - - def Dock(self): - """ Dock() indicates that a pane should be docked. """ - - return self.SetFlag(self.optionFloating, False) - - - def Float(self): - """ Float() indicates that a pane should be floated. """ - - return self.SetFlag(self.optionFloating, True) - - - def Hide(self): - """ Hide() indicates that a pane should be hidden. """ - - return self.SetFlag(self.optionHidden, True) - - - def Show(self, show=True): - """ Show() indicates that a pane should be shown. """ - - return self.SetFlag(self.optionHidden, not show) - - - def CaptionVisible(self, visible=True): - """ CaptionVisible() indicates that a pane caption should be visible. """ - - return self.SetFlag(self.optionCaption, visible) - - - def PaneBorder(self, visible=True): - """ PaneBorder() indicates that a border should be drawn for the pane. """ - - return self.SetFlag(self.optionPaneBorder, visible) - - - def Gripper(self, visible=True): - """ Gripper() indicates that a gripper should be drawn for the pane. """ - - return self.SetFlag(self.optionGripper, visible) - - - def GripperTop(self, attop=True): - """ GripperTop() indicates that a gripper should be drawn for the pane. """ - - return self.SetFlag(self.optionGripperTop, attop) - - - def CloseButton(self, visible=True): - """ CloseButton() indicates that a close button should be drawn for the pane. """ - - return self.SetFlag(self.buttonClose, visible) - - - def MaximizeButton(self, visible=True): - """ MaximizeButton() indicates that a maximize button should be drawn for the pane. """ - - return self.SetFlag(self.buttonMaximize, visible) - - - def MinimizeButton(self, visible=True): - """ MinimizeButton() indicates that a minimize button should be drawn for the pane. """ - - return self.SetFlag(self.buttonMinimize, visible) - - - def PinButton(self, visible=True): - """ PinButton() indicates that a pin button should be drawn for the pane. """ - - return self.SetFlag(self.buttonPin, visible) - - - def DestroyOnClose(self, b=True): - """ DestroyOnClose() indicates whether a pane should be destroyed when it is closed. """ - - return self.SetFlag(self.optionDestroyOnClose, b) - - - def TopDockable(self, b=True): - """ TopDockable() indicates whether a pane can be docked at the top of the frame. """ - - return self.SetFlag(self.optionTopDockable, b) - - - def BottomDockable(self, b=True): - """ BottomDockable() indicates whether a pane can be docked at the bottom of the frame. """ - - return self.SetFlag(self.optionBottomDockable, b) - - - def LeftDockable(self, b=True): - """ LeftDockable() indicates whether a pane can be docked on the left of the frame. """ - - return self.SetFlag(self.optionLeftDockable, b) - - - def RightDockable(self, b=True): - """ RightDockable() indicates whether a pane can be docked on the right of the frame. """ - - return self.SetFlag(self.optionRightDockable, b) - - - def Floatable(self, b=True): - """ Floatable() indicates whether a frame can be floated. """ - - return self.SetFlag(self.optionFloatable, b) - - - def Movable(self, b=True): - """ Movable() indicates whether a frame can be moved. """ - - return self.SetFlag(self.optionMovable, b) - - - def Dockable(self, b=True): - - return self.TopDockable(b).BottomDockable(b).LeftDockable(b).RightDockable(b) - - - def DefaultPane(self): - """ DefaultPane() specifies that the pane should adopt the default pane settings. """ - - state = self.state - state |= self.optionTopDockable | self.optionBottomDockable | \ - self.optionLeftDockable | self.optionRightDockable | \ - self.optionFloatable | self.optionMovable | self.optionResizable | \ - self.optionCaption | self.optionPaneBorder | self.buttonClose - - self.state = state - - return self - - - def CentrePane(self): - """ CentrePane() specifies that the pane should adopt the default center pane settings. """ - - return self.CenterPane() - - - def CenterPane(self): - """ CenterPane() specifies that the pane should adopt the default center pane settings. """ - - self.state = 0 - return self.Center().PaneBorder().Resizable() - - - def ToolbarPane(self): - """ ToolbarPane() specifies that the pane should adopt the default toolbar pane settings. """ - - self.DefaultPane() - state = self.state - - state |= (self.optionToolbar | self.optionGripper) - state &= ~(self.optionResizable | self.optionCaption) - - if self.dock_layer == 0: - self.dock_layer = 10 - - self.state = state - - return self - - - def SetFlag(self, flag, option_state): - """ SetFlag() turns the property given by flag on or off with the option_state parameter. """ - - state = self.state - - if option_state: - state |= flag - else: - state &= ~flag - - self.state = state - - return self - - - def HasFlag(self, flag): - """ HasFlag() returns True if the the property specified by flag is active for the pane. """ - - return (self.state & flag and [True] or [False])[0] - - -NoneAuiPaneInfo = AuiPaneInfo() - -# -- AuiFloatingPane class implementation -- -# -# AuiFloatingPane implements a frame class with some special functionality -# which allows the library to sense when the frame move starts, is active, -# and completes. Note that it contains it's own AuiManager instance, -# which, in the future, would allow for nested managed frames. -# For now, with wxMSW, the wx.MiniFrame window is used, but on wxGTK, wx.Frame - -if wx.Platform == "__WXGTK__": - - class AuiFloatingPaneBaseClass(wx.Frame): - def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, - size=wx.DefaultSize, style=0): - wx.Frame.__init__(self, parent, id, title, pos, size, style) - -else: - - class AuiFloatingPaneBaseClass(wx.MiniFrame): - def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, - size=wx.DefaultSize, style=0): - wx.MiniFrame.__init__(self, parent, id, title, pos, size, style) - if wx.Platform == "__WXMAC__": - self.MacSetMetalAppearance(True) - - -class AuiFloatingPane(AuiFloatingPaneBaseClass): - - def __init__(self, parent, owner_mgr, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, - size=wx.DefaultSize, style=wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | - wx.CLOSE_BOX | wx.FRAME_NO_TASKBAR | - wx.FRAME_FLOAT_ON_PARENT | wx.CLIP_CHILDREN, - resizeborder=0): - - if not resizeborder: - style = style & ~wx.RESIZE_BORDER - - AuiFloatingPaneBaseClass.__init__(self, parent, id, title, pos, size, style) - self._owner_mgr = owner_mgr - self._moving = False - self._last_rect = wx.Rect() - self._mgr = AuiManager(None) - self._mgr.SetFrame(self) - self._mousedown = False - self.SetExtraStyle(wx.WS_EX_PROCESS_IDLE) - - self.Bind(wx.EVT_CLOSE, self.OnClose) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_MOVE, self.OnMoveEvent) - self.Bind(wx.EVT_MOVING, self.OnMoveEvent) - self.Bind(wx.EVT_IDLE, self.OnIdle) - self.Bind(wx.EVT_ACTIVATE, self.OnActivate) - - - def CopyAttributes(self, pane, contained_pane): - - contained_pane.name = pane.name - contained_pane.caption = pane.caption - contained_pane.window = pane.window - contained_pane.frame = pane.frame - contained_pane.state = pane.state - contained_pane.dock_direction = pane.dock_direction - contained_pane.dock_layer = pane.dock_layer - contained_pane.dock_row = pane.dock_row - contained_pane.dock_pos = pane.dock_pos - contained_pane.best_size = pane.best_size - contained_pane.min_size = pane.min_size - contained_pane.max_size = pane.max_size - contained_pane.floating_pos = pane.floating_pos - contained_pane.floating_size = pane.floating_size - contained_pane.dock_proportion = pane.dock_proportion - contained_pane.buttons = pane.buttons - contained_pane.rect = pane.rect - - return contained_pane - - - def SetPaneWindow(self, pane): - - self._pane_window = pane.window - self._pane_window.Reparent(self) - - contained_pane = AuiPaneInfo() - - contained_pane = self.CopyAttributes(pane, contained_pane) - - contained_pane.Dock().Center().Show(). \ - CaptionVisible(False). \ - PaneBorder(False). \ - Layer(0).Row(0).Position(0) - - indx = self._owner_mgr._panes.index(pane) - self._owner_mgr._panes[indx] = pane - - self._mgr.AddPane(self._pane_window, contained_pane) - self._mgr.Update() - - if pane.min_size.IsFullySpecified(): - tmp = self.GetSize() - self.GetSizer().SetSizeHints(self) - self.SetSize(tmp) - - self.SetTitle(pane.caption) - - if pane.floating_size != wx.DefaultSize: - self.SetSize(pane.floating_size) - self._owner_mgr._panes[indx] = pane - else: - size = pane.best_size - if size == wx.DefaultSize: - size = pane.min_size - if size == wx.DefaultSize: - size = self._pane_window.GetSize() - if pane.HasGripper(): - if pane.HasGripperTop(): - size.y += self._owner_mgr._art.GetMetric(AUI_ART_GRIPPER_SIZE) - else: - size.x += self._owner_mgr._art.GetMetric(AUI_ART_GRIPPER_SIZE) - - pane.floating_size = size - self._owner_mgr._panes[indx] = pane - self.SetClientSize(size) - - - def OnSize(self, event): - - self._owner_mgr.OnAuiFloatingPaneResized(self._pane_window, event.GetSize()) - - - def OnClose(self, event): - self._owner_mgr.OnAuiFloatingPaneClosed(self._pane_window, event) - if event.GetSkipped(): - self.Destroy() - self._mgr.UnInit() - - - def OnMoveEvent(self, event): - - win_rect = self.GetRect() - - # skip the first move event - if self._last_rect.IsEmpty(): - self._last_rect = win_rect - return - - # prevent frame redocking during resize - if self._last_rect.GetSize() != win_rect.GetSize(): - self._last_rect = win_rect - return - - self._last_rect = win_rect - - if not self.IsMouseDown(): - return - - if not self._moving: - self.OnMoveStart() - self._moving = True - - self.OnMoving(event.GetRect()) - - - def IsMouseDown(self): - - if _newversion: - ms = wx.GetMouseState() - return ms.leftDown - else: - if wx.Platform == "__WXMSW__": - if _libimported == "MH": - return ((win32api.GetKeyState(win32con.VK_LBUTTON) & (1<<15))\ - and [True] or [False])[0] - elif _libimported == "ctypes": - return ((ctypes.windll.user32.GetKeyState(1) & (1<<15)) and \ - [True] or [False])[0] - - - def OnIdle(self, event): - - if self._moving: - if not self.IsMouseDown(): - self._moving = False - self.OnMoveFinished() - else: - event.RequestMore() - - event.Skip() - - - def OnMoveStart(self): - - # notify the owner manager that the pane has started to move - self._owner_mgr.OnAuiFloatingPaneMoveStart(self._pane_window) - - - def OnMoving(self, window_rect): - - # notify the owner manager that the pane is moving - self._owner_mgr.OnAuiFloatingPaneMoving(self._pane_window) - - - def OnMoveFinished(self): - - # notify the owner manager that the pane has finished moving - self._owner_mgr.OnAuiFloatingPaneMoved(self._pane_window) - - - def OnActivate(self, event): - - if event.GetActive(): - self._owner_mgr.OnAuiFloatingPaneActivated(self._pane_window) - - -# -- static utility functions -- - -def PaneCreateStippleBitmap(): - - data = [0, 0, 0, 192, 192, 192, 192, 192, 192, 0, 0, 0] - img = wx.EmptyImage(2, 2) - counter = 0 - - for ii in xrange(2): - for jj in xrange(2): - img.SetRGB(ii, jj, data[counter], data[counter+1], data[counter+2]) - counter = counter + 3 - - return img.ConvertToBitmap() - - -def DrawResizeHint(dc, rect): - - stipple = PaneCreateStippleBitmap() - brush = wx.BrushFromBitmap(stipple) - dc.SetBrush(brush) - dc.SetPen(wx.TRANSPARENT_PEN) - - dc.SetLogicalFunction(wx.XOR) - dc.DrawRectangleRect(rect) - - -def CopyDocksAndPanes(src_docks, src_panes): - """ - CopyDocksAndPanes() - this utility function creates shallow copies of - the dock and pane info. DockInfo's usually contain pointers - to AuiPaneInfo classes, thus this function is necessary to reliably - reconstruct that relationship in the new dock info and pane info arrays. - """ - - dest_docks = src_docks - dest_panes = src_panes - - for ii in xrange(len(dest_docks)): - dock = dest_docks[ii] - for jj in xrange(len(dock.panes)): - for kk in xrange(len(src_panes)): - if dock.panes[jj] == src_panes[kk]: - dock.panes[jj] = dest_panes[kk] - - return dest_docks, dest_panes - - -def CopyDocksAndPanes2(src_docks, src_panes): - """ - CopyDocksAndPanes2() - this utility function creates full copies of - the dock and pane info. DockInfo's usually contain pointers - to AuiPaneInfo classes, thus this function is necessary to reliably - reconstruct that relationship in the new dock info and pane info arrays. - """ - - dest_docks = [] - - for ii in xrange(len(src_docks)): - dest_docks.append(DockInfo()) - dest_docks[ii].dock_direction = src_docks[ii].dock_direction - dest_docks[ii].dock_layer = src_docks[ii].dock_layer - dest_docks[ii].dock_row = src_docks[ii].dock_row - dest_docks[ii].size = src_docks[ii].size - dest_docks[ii].min_size = src_docks[ii].min_size - dest_docks[ii].resizable = src_docks[ii].resizable - dest_docks[ii].fixed = src_docks[ii].fixed - dest_docks[ii].toolbar = src_docks[ii].toolbar - dest_docks[ii].panes = src_docks[ii].panes - dest_docks[ii].rect = src_docks[ii].rect - - dest_panes = [] - - for ii in xrange(len(src_panes)): - dest_panes.append(AuiPaneInfo()) - dest_panes[ii].name = src_panes[ii].name - dest_panes[ii].caption = src_panes[ii].caption - dest_panes[ii].window = src_panes[ii].window - dest_panes[ii].frame = src_panes[ii].frame - dest_panes[ii].state = src_panes[ii].state - dest_panes[ii].dock_direction = src_panes[ii].dock_direction - dest_panes[ii].dock_layer = src_panes[ii].dock_layer - dest_panes[ii].dock_row = src_panes[ii].dock_row - dest_panes[ii].dock_pos = src_panes[ii].dock_pos - dest_panes[ii].best_size = src_panes[ii].best_size - dest_panes[ii].min_size = src_panes[ii].min_size - dest_panes[ii].max_size = src_panes[ii].max_size - dest_panes[ii].floating_pos = src_panes[ii].floating_pos - dest_panes[ii].floating_size = src_panes[ii].floating_size - dest_panes[ii].dock_proportion = src_panes[ii].dock_proportion - dest_panes[ii].buttons = src_panes[ii].buttons - dest_panes[ii].rect = src_panes[ii].rect - - for ii in xrange(len(dest_docks)): - dock = dest_docks[ii] - for jj in xrange(len(dock.panes)): - for kk in xrange(len(src_panes)): - if dock.panes[jj] == src_panes[kk]: - dock.panes[jj] = dest_panes[kk] - - dest_docks[ii] = dock - - return dest_docks, dest_panes - - -def GetMaxLayer(docks, dock_direction): - """ - GetMaxLayer() is an internal function which returns - the highest layer inside the specified dock. - """ - - max_layer = 0 - - for dock in docks: - if dock.dock_direction == dock_direction and dock.dock_layer > max_layer and not dock.fixed: - max_layer = dock.dock_layer - - return max_layer - - -def GetMaxRow(panes, direction, layer): - """ - GetMaxRow() is an internal function which returns - the highest layer inside the specified dock. - """ - - max_row = 0 - - for pane in panes: - if pane.dock_direction == direction and pane.dock_layer == layer and \ - pane.dock_row > max_row: - max_row = pane.dock_row - - return max_row - - -def DoInsertDockLayer(panes, dock_direction, dock_layer): - """ - DoInsertDockLayer() is an internal function that inserts a new dock - layer by incrementing all existing dock layer values by one. - """ - - for ii in xrange(len(panes)): - pane = panes[ii] - if not pane.IsFloating() and pane.dock_direction == dock_direction and pane.dock_layer >= dock_layer: - pane.dock_layer = pane.dock_layer + 1 - - panes[ii] = pane - - return panes - - -def DoInsertDockRow(panes, dock_direction, dock_layer, dock_row): - """ - DoInsertDockRow() is an internal function that inserts a new dock - row by incrementing all existing dock row values by one. - """ - - for ii in xrange(len(panes)): - pane = panes[ii] - if not pane.IsFloating() and pane.dock_direction == dock_direction and \ - pane.dock_layer == dock_layer and pane.dock_row >= dock_row: - pane.dock_row = pane.dock_row + 1 - - panes[ii] = pane - - return panes - - -def DoInsertPane(panes, dock_direction, dock_layer, dock_row, dock_pos): - - for ii in xrange(len(panes)): - pane = panes[ii] - if not pane.IsFloating() and pane.dock_direction == dock_direction and \ - pane.dock_layer == dock_layer and pane.dock_row == dock_row and \ - pane.dock_pos >= dock_pos: - pane.dock_pos = pane.dock_pos + 1 - - panes[ii] = pane - - return panes - - -def FindDocks(docks, dock_direction, dock_layer=-1, dock_row=-1, arr=[]): - """ - FindDocks() is an internal function that returns a list of docks which meet - the specified conditions in the parameters and returns a sorted array - (sorted by layer and then row). - """ - - begin_layer = dock_layer - end_layer = dock_layer - begin_row = dock_row - end_row = dock_row - dock_count = len(docks) - max_row = 0 - max_layer = 0 - - # discover the maximum dock layer and the max row - for ii in xrange(dock_count): - max_row = max(max_row, docks[ii].dock_row) - max_layer = max(max_layer, docks[ii].dock_layer) - - # if no dock layer was specified, search all dock layers - if dock_layer == -1: - begin_layer = 0 - end_layer = max_layer - - # if no dock row was specified, search all dock row - if dock_row == -1: - begin_row = 0 - end_row = max_row - - arr = [] - - for layer in xrange(begin_layer, end_layer+1): - for row in xrange(begin_row, end_row+1): - for ii in xrange(dock_count): - d = docks[ii] - if dock_direction == -1 or dock_direction == d.dock_direction: - if d.dock_layer == layer and d.dock_row == row: - arr.append(d) - - return arr - - -def FindPaneInDock(dock, window): - """ - FindPaneInDock() looks up a specified window pointer inside a dock. - If found, the corresponding AuiPaneInfo pointer is returned, otherwise None. - """ - - for p in dock.panes: - if p.window == window: - return p - - return None - - -def RemovePaneFromDocks(docks, pane, exc=None): - """ - RemovePaneFromDocks() removes a pane window from all docks - with a possible exception specified by parameter "except". - """ - - for ii in xrange(len(docks)): - d = docks[ii] - if d == exc: - continue - pi = FindPaneInDock(d, pane.window) - if pi: - d.panes.remove(pi) - - docks[ii] = d - - return docks - - -def RenumberDockRows(docks): - """ - RenumberDockRows() takes a dock and assigns sequential numbers - to existing rows. Basically it takes out the gaps so if a - dock has rows with numbers 0, 2, 5, they will become 0, 1, 2. - """ - - for ii in xrange(len(docks)): - dock = docks[ii] - dock.dock_row = ii - for jj in xrange(len(dock.panes)): - dock.panes[jj].dock_row = ii - - docks[ii] = dock - - return docks - - -def SetActivePane(panes, active_pane): - - for ii in xrange(len(panes)): - pane = panes[ii] - pane.state &= ~AuiPaneInfo.optionActive - - if pane.window == active_pane: - pane.state |= AuiPaneInfo.optionActive - - panes[ii] = pane - - return panes - - -def PaneSortFunc(p1, p2): - """ This function is used to sort panes by dock position. """ - - return (p1.dock_pos < p2.dock_pos and [-1] or [1])[0] - - -def EscapeDelimiters(s): - """ - EscapeDelimiters() changes "" into "\" and "|" into "\|" - in the input string. This is an internal functions which is - used for saving perspectives. - """ - - result = s.replace(";", "\\") - result = result.replace("|", "|\\") - - return result - - -actionNone = 0 -actionResize = 1 -actionClickButton = 2 -actionClickCaption = 3 -actionDragToolbarPane = 4 -actionDragAuiFloatingPane = 5 - -auiInsertRowPixels = 10 -auiNewRowPixels = 40 -auiLayerInsertPixels = 40 -auiLayerInsertOffset = 5 - -# -- AuiManager class implementation -- -# -# AuiManager manages the panes associated with it for a particular wx.Frame, -# using a pane's AuiPaneInfo information to determine each pane's docking and -# floating behavior. AuiManager uses wxPython's sizer mechanism to plan the -# layout of each frame. It uses a replaceable dock art class to do all drawing, -# so all drawing is localized in one area, and may be customized depending on an -# applications' specific needs. -# -# AuiManager works as follows: The programmer adds panes to the class, or makes -# changes to existing pane properties (dock position, floating state, show state, etc.). -# To apply these changes, AuiManager's Update() function is called. This batch -# processing can be used to avoid flicker, by modifying more than one pane at a time, -# and then "committing" all of the changes at once by calling Update(). -# -# Panes can be added quite easily: -# -# text1 = wx.TextCtrl(self, -1) -# text2 = wx.TextCtrl(self, -1) -# self._mgr.AddPane(text1, wx.LEFT, "Pane Caption") -# self._mgr.AddPane(text2, wx.BOTTOM, "Pane Caption") -# self._mgr.Update() -# -# Later on, the positions can be modified easily. The following will float an -# existing pane in a tool window: - -# self._mgr.GetPane(text1).Float() - -# Layers, Rows and Directions, Positions -# Inside PyAUI, the docking layout is figured out by checking several pane parameters. -# Four of these are important for determining where a pane will end up. -# -# Direction - Each docked pane has a direction, Top, Bottom, Left, Right, or Center. -# This is fairly self-explanatory. The pane will be placed in the location specified -# by this variable. -# -# Position - More than one pane can be placed inside of a "dock." Imagine to panes -# being docked on the left side of a window. One pane can be placed over another. -# In proportionally managed docks, the pane position indicates it's sequential position, -# starting with zero. So, in our scenario with two panes docked on the left side, the -# top pane in the dock would have position 0, and the second one would occupy position 1. -# -# Row - A row can allow for two docks to be placed next to each other. One of the most -# common places for this to happen is in the toolbar. Multiple toolbar rows are allowed, -# the first row being in row 0, and the second in row 1. Rows can also be used on -# vertically docked panes. -# -# Layer - A layer is akin to an onion. Layer 0 is the very center of the managed pane. -# Thus, if a pane is in layer 0, it will be closest to the center window (also sometimes -# known as the "content window"). Increasing layers "swallow up" all layers of a lower -# value. This can look very similar to multiple rows, but is different because all panes -# in a lower level yield to panes in higher levels. The best way to understand layers -# is by running the PyAUI sample (PyAUIDemo.py). - -class AuiManager(wx.EvtHandler): - - def __init__(self, frame=None, flags=None): - """ - Default Class Constructor. frame specifies the wx.Frame which should be managed. - flags specifies options which allow the frame management behavior to be modified. - """ - - wx.EvtHandler.__init__(self) - self._action = actionNone - self._last_mouse_move = wx.Point() - self._hover_button = None - self._art = DefaultDockArt() - self._hint_wnd = None - self._action_window = None - self._last_hint = wx.Rect() - self._hint_fadetimer = wx.Timer(self, wx.NewId()) - self._hintshown = False - - if flags is None: - flags = AUI_MGR_DEFAULT - - self._flags = flags - self._active_pane = None - - if frame: - self.SetFrame(frame) - - self._panes = [] - self._docks = [] - self._uiparts = [] - - self.Bind(wx.EVT_PAINT, self.OnPaint) - self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) - self.Bind(wx.EVT_SIZE, self.OnSize) - self.Bind(wx.EVT_SET_CURSOR, self.OnSetCursor) - self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) - self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) - self.Bind(wx.EVT_MOTION, self.OnMotion) - self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow) - self.Bind(wx.EVT_TIMER, self.OnHintFadeTimer) - self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus) - self.Bind(EVT_AUI_PANEBUTTON, self.OnPaneButton) - - - def GetPaneByWidget(self, window): - """ - This version of GetPane() looks up a pane based on a - 'pane window', see below comment for more info. - """ - - for p in self._panes: - if p.window == window: - return p - - return NoneAuiPaneInfo - - - def GetPaneByName(self, name): - """ - This version of GetPane() looks up a pane based on a - 'pane name', see below comment for more info. - """ - - for p in self._panes: - if p.name == name: - return p - - return NoneAuiPaneInfo - - - def GetPane(self, item): - """ - GetPane() looks up a AuiPaneInfo structure based - on the supplied window pointer. Upon failure, GetPane() - returns an empty AuiPaneInfo, a condition which can be checked - by calling AuiPaneInfo.IsOk(). - - The pane info's structure may then be modified. Once a pane's - info is modified, AuiManager.Update() must be called to - realize the changes in the UI. - - AG: Added To Handle 2 Different Versions Of GetPane() For - wxPython/Python. - """ - - if isinstance(item, type("")): - return self.GetPaneByName(item) - else: - return self.GetPaneByWidget(item) - - - def GetAllPanes(self): - """ GetAllPanes() returns a reference to all the pane info structures. """ - - return self._panes - - - def HitTest(self, x, y): - """ - HitTest() is an internal function which determines - which UI item the specified coordinates are over - (x,y) specify a position in client coordinates. - """ - - result = None - - for item in self._uiparts: - # we are not interested in typeDock, because this space - # isn't used to draw anything, just for measurements - # besides, the entire dock area is covered with other - # rectangles, which we are interested in. - if item.type == DockUIPart.typeDock: - continue - - # if we already have a hit on a more specific item, we are not - # interested in a pane hit. If, however, we don't already have - # a hit, returning a pane hit is necessary for some operations - if (item.type == DockUIPart.typePane or \ - item.type == DockUIPart.typePaneBorder) and result: - continue - - # if the point is inside the rectangle, we have a hit - if item.rect.Contains((x, y)): - result = item - - return result - - - # SetFlags() and GetFlags() allow the owner to set various - # options which are global to AuiManager - - def SetFlags(self, flags): - """ - SetFlags() is used to specify AuiManager's settings flags. flags specifies - options which allow the frame management behavior to be modified. - """ - - self._flags = flags - - - def GetFlags(self): - """ GetFlags() returns the current manager's flags. """ - - return self._flags - - - def SetFrame(self, frame): - """ - SetFrame() is usually called once when the frame - manager class is being initialized. "frame" specifies - the frame which should be managed by the frame manager. - """ - - if not frame: - raise "\nERROR: Specified Frame Must Be Non-Null. " - - self._frame = frame - self._frame.PushEventHandler(self) - - # if the owner is going to manage an MDI parent frame, - # we need to add the MDI client window as the default - # center pane - if isinstance(frame, wx.MDIParentFrame): - mdi_frame = frame - client_window = mdi_frame.GetClientWindow() - - if not client_window: - raise "\nERROR: MDI Client Window Is Null. " - - self.AddPane(client_window, AuiPaneInfo().Name("mdiclient"). - CenterPane().PaneBorder(False)) - - - def GetFrame(self): - """ GetFrame() returns the frame pointer being managed by AuiManager. """ - - return self._frame - - - def UnInit(self): - """ - UnInit() must be called, usually in the destructor - of the frame class. If it is not called, usually this - will result in a crash upon program exit. - """ - - self._frame.RemoveEventHandler(self) - - - def GetArtProvider(self): - """ GetArtProvider() returns the current art provider being used. """ - - return self._art - - - def ProcessMgrEvent(self, event): - - # first, give the owner frame a chance to override - if self._frame: - if self._frame.ProcessEvent(event): - return - - if event.GetEventType() != wxEVT_AUI_PANECLOSE: - self.ProcessEvent(event) - - - def CanMakeWindowsTransparent(self): - if wx.Platform == "__WXMSW__": - version = wx.GetOsDescription() - found = version.find("XP") >= 0 or version.find("2000") >= 0 or version.find("NT") >= 0 - return found and _libimported - elif wx.Platform == "__WXMAC__" and _carbon_dll: - return True - else: - return False - -# on supported windows systems (Win2000 and greater), this function -# will make a frame window transparent by a certain amount - def MakeWindowTransparent(self, wnd, amount): - - if wnd.GetSize() == (0, 0): - return - - # this API call is not in all SDKs, only the newer ones, so - # we will runtime bind this - if wx.Platform == "__WXMSW__": - hwnd = wnd.GetHandle() - - if not hasattr(self, "_winlib"): - if _libimported == "MH": - self._winlib = win32api.LoadLibrary("user32") - elif _libimported == "ctypes": - self._winlib = ctypes.windll.user32 - - if _libimported == "MH": - pSetLayeredWindowAttributes = win32api.GetProcAddress(self._winlib, - "SetLayeredWindowAttributes") - - if pSetLayeredWindowAttributes == None: - return - - exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) - if 0 == (exstyle & 0x80000): - win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000) - - winxpgui.SetLayeredWindowAttributes(hwnd, 0, amount, 2) - - elif _libimported == "ctypes": - style = self._winlib.GetWindowLongA(hwnd, 0xffffffecL) - style |= 0x00080000 - self._winlib.SetWindowLongA(hwnd, 0xffffffecL, style) - self._winlib.SetLayeredWindowAttributes(hwnd, 0, amount, 2) - - elif wx.Platform == "__WXMAC__" and _carbon_dll: - handle = _carbon_dll.GetControlOwner(wnd.GetHandle()) - if amount == 0: - amnt = float(0) - else: - amnt = float(amount)/255.0 #convert from the 0-255 amount to the float that Carbon wants - _carbon_dll.SetWindowAlpha(handle, ctypes.c_float(amnt)) - else: - #shouldn't be called, but just in case... - return - - - def SetArtProvider(self, art_provider): - """ - SetArtProvider() instructs AuiManager to use the - specified art provider for all drawing calls. This allows - plugable look-and-feel features. - """ - - # delete the last art provider, if any - del self._art - - # assign the new art provider - self._art = art_provider - - - def AddPane(self, window, arg1=None, arg2=None): - """ - AddPane() tells the frame manager to start managing a child window. There - are two versions of this function. The first verison allows the full spectrum - of pane parameter possibilities (AddPane1). The second version is used for - simpler user interfaces which do not require as much configuration (AddPane2). - In wxPython, simply call AddPane. - """ - - if type(arg1) == type(1): - # This Is Addpane2 - if arg1 is None: - arg1 = wx.LEFT - if arg2 is None: - arg2 = "" - return self.AddPane2(window, arg1, arg2) - else: - return self.AddPane1(window, arg1) - - - def AddPane1(self, window, pane_info): - - # check if the pane has a valid window - if not window: - return False - - # check if the pane already exists - if self.GetPane(pane_info.window).IsOk(): - return False - - if isinstance(window, wx.ToolBar): - window.SetBestFittingSize() - - self._panes.append(pane_info) - - pinfo = self._panes[-1] - - # set the pane window - pinfo.window = window - - # if the pane's name identifier is blank, create a random string - if len(pinfo.name) == 0 or pinfo.name == "": - pinfo.name = ("%s%08x%08x%08x")%(pinfo.window.GetName(), time.time(), - time.clock(), len(self._panes)) - - # set initial proportion (if not already set) - if pinfo.dock_proportion == 0: - pinfo.dock_proportion = 100000 - - if pinfo.HasCloseButton() and len(pinfo.buttons) == 0: - button = PaneButton(None) - button.button_id = AuiPaneInfo.buttonClose - pinfo.buttons.append(button) - - if pinfo.best_size == wx.DefaultSize and pinfo.window: - pinfo.best_size = pinfo.window.GetClientSize() - - if isinstance(pinfo.window, wx.ToolBar): - # GetClientSize() doesn't get the best size for - # a toolbar under some newer versions of wxWidgets, - # so use GetBestSize() - pinfo.best_size = pinfo.window.GetBestSize() - - # for some reason, wxToolBar::GetBestSize() is returning - # a size that is a pixel shy of the correct amount. - # I believe this to be the correct action, until - # wxToolBar::GetBestSize() is fixed. Is this assumption - # correct? - pinfo.best_size.y = pinfo.best_size.y + 1 - - # this is needed for Win2000 to correctly fill toolbar backround - # it should probably be repeated once system colour change happens - if wx.Platform == "__WXMSW__" and pinfo.window.UseBgCol(): - pinfo.window.SetBackgroundColour(self.GetArtProvider().GetColour(AUI_ART_BACKGROUND_COLOUR)) - - if pinfo.min_size != wx.DefaultSize: - if pinfo.best_size.x < pinfo.min_size.x: - pinfo.best_size.x = pinfo.min_size.x - if pinfo.best_size.y < pinfo.min_size.y: - pinfo.best_size.y = pinfo.min_size.y - - self._panes[-1] = pinfo - - return True - - - def AddPane2(self, window, direction, caption): - - pinfo = AuiPaneInfo() - pinfo.Caption(caption) - - if direction == wx.TOP: - pinfo.Top() - elif direction == wx.BOTTOM: - pinfo.Bottom() - elif direction == wx.LEFT: - pinfo.Left() - elif direction == wx.RIGHT: - pinfo.Right() - elif direction == wx.CENTER: - pinfo.CenterPane() - - return self.AddPane(window, pinfo) - - - def InsertPane(self, window, pane_info, insert_level=AUI_INSERT_PANE): - """ - InsertPane() is used to insert either a previously unmanaged pane window - into the frame manager, or to insert a currently managed pane somewhere else. - InsertPane() will push all panes, rows, or docks aside and insert the window - into the position specified by insert_location. Because insert_location can - specify either a pane, dock row, or dock layer, the insert_level parameter is - used to disambiguate this. The parameter insert_level can take a value of - AUI_INSERT_PANE, AUI_INSERT_ROW or AUI_INSERT_DOCK. - """ - - # shift the panes around, depending on the insert level - if insert_level == AUI_INSERT_PANE: - self._panes = DoInsertPane(self._panes, pane_info.dock_direction, - pane_info.dock_layer, pane_info.dock_row, - pane_info.dock_pos) - - elif insert_level == AUI_INSERT_ROW: - self._panes = DoInsertDockRow(self._panes, pane_info.dock_direction, - pane_info.dock_layer, pane_info.dock_row) - - elif insert_level == AUI_INSERT_DOCK: - self._panes = DoInsertDockLayer(self._panes, pane_info.dock_direction, - pane_info.dock_layer) - - # if the window already exists, we are basically just moving/inserting the - # existing window. If it doesn't exist, we need to add it and insert it - existing_pane = self.GetPane(window) - indx = self._panes.index(existing_pane) - - if not existing_pane.IsOk(): - - return self.AddPane(window, pane_info) - - else: - - if pane_info.IsFloating(): - existing_pane.Float() - if pane_info.floating_pos != wx.DefaultPosition: - existing_pane.FloatingPosition(pane_info.floating_pos) - if pane_info.floating_size != wx.DefaultSize: - existing_pane.FloatingSize(pane_info.floating_size) - else: - existing_pane.Direction(pane_info.dock_direction) - existing_pane.Layer(pane_info.dock_layer) - existing_pane.Row(pane_info.dock_row) - existing_pane.Position(pane_info.dock_pos) - - self._panes[indx] = existing_pane - - return True - - - def DetachPane(self, window): - """ - DetachPane() tells the AuiManager to stop managing the pane specified - by window. The window, if in a floated frame, is reparented to the frame - managed by AuiManager. - """ - - for p in self._panes: - if p.window == window: - if p.frame: - # we have a floating frame which is being detached. We need to - # reparent it to m_frame and destroy the floating frame - - # reduce flicker - p.window.SetSize(1,1) - p.frame.Show(False) - - # reparent to self._frame and destroy the pane - p.window.Reparent(self._frame) - p.frame.SetSizer(None) - p.frame.Destroy() - p.frame = None - - self._panes.remove(p) - return True - - return False - - - def SavePerspective(self): - """ - SavePerspective() saves all pane information as a single string. - This string may later be fed into LoadPerspective() to restore - all pane settings. This save and load mechanism allows an - exact pane configuration to be saved and restored at a later time. - """ - - result = "layout1|" - pane_count = len(self._panes) - - for pane_i in xrange(pane_count): - pane = self._panes[pane_i] - result = result + "name=" + EscapeDelimiters(pane.name) + ";" - result = result + "caption=" + EscapeDelimiters(pane.caption) + ";" - result = result + "state=%u;"%pane.state - result = result + "dir=%d;"%pane.dock_direction - result = result + "layer=%d;"%pane.dock_layer - result = result + "row=%d;"%pane.dock_row - result = result + "pos=%d;"%pane.dock_pos - result = result + "prop=%d;"%pane.dock_proportion - result = result + "bestw=%d;"%pane.best_size.x - result = result + "besth=%d;"%pane.best_size.y - result = result + "minw=%d;"%pane.min_size.x - result = result + "minh=%d;"%pane.min_size.y - result = result + "maxw=%d;"%pane.max_size.x - result = result + "maxh=%d;"%pane.max_size.y - result = result + "floatx=%d;"%pane.floating_pos.x - result = result + "floaty=%d;"%pane.floating_pos.y - result = result + "floatw=%d;"%pane.floating_size.x - result = result + "floath=%d"%pane.floating_size.y - result = result + "|" - - dock_count = len(self._docks) - - for dock_i in xrange(dock_count): - dock = self._docks[dock_i] - result = result + ("dock_size(%d,%d,%d)=%d|")%(dock.dock_direction, - dock.dock_layer, - dock.dock_row, - dock.size) - - return result - - - def LoadPerspective(self, layout, update=True): - """ - LoadPerspective() loads a layout which was saved with SavePerspective() - If the "update" flag parameter is True, the GUI will immediately be updated. - """ - - input = layout - # check layout string version - indx = input.index("|") - part = input[0:indx] - input = input[indx+1:] - part = part.strip() - - if part != "layout1": - return False - - olddocks = self._docks[:] - oldpanes = self._panes[:] - - # mark all panes currently managed as docked and hidden - pane_count = len(self._panes) - for pane_i in xrange(pane_count): - pane = self._panes[pane_i] - pane.Dock().Hide() - self._panes[pane_i] = pane - - # clear out the dock array this will be reconstructed - self._docks = [] - - # replace escaped characters so we can - # split up the string easily - input = input.replace("\\|", "\a") - input = input.replace("\\", "\b") - - input = input.split("|") - - for line in input: - - if line.startswith("dock_size"): - - indx = line.index("=") - size = int(line[indx+1:]) - indx1 = line.index("(") - indx2 = line.index(")") - line2 = line[indx1+1:indx2] - vals = line2.split(",") - dir = int(vals[0]) - layer = int(vals[1]) - row = int(vals[2]) - dock = DockInfo() - dock.dock_direction = dir - dock.dock_layer = layer - dock.dock_row = row - dock.size = size - - self._docks.append(dock) - - elif line.startswith("name"): - - newline = line.split(";") - pane = AuiPaneInfo() - - for newl in newline: - myline = newl.strip() - vals = myline.split("=") - val_name = vals[0] - value = vals[1] - if val_name == "name": - pane.name = value - elif val_name == "caption": - pane.caption = value - elif val_name == "state": - pane.state = int(value) - elif val_name == "dir": - pane.dock_direction = int(value) - elif val_name == "layer": - pane.dock_layer = int(value) - elif val_name == "row": - pane.dock_row = int(value) - elif val_name == "pos": - pane.dock_pos = int(value) - elif val_name == "prop": - pane.dock_proportion = int(value) - elif val_name == "bestw": - pane.best_size.x = int(value) - elif val_name == "besth": - pane.best_size.y = int(value) - pane.best_size = wx.Size(pane.best_size.x, pane.best_size.y) - elif val_name == "minw": - pane.min_size.x = int(value) - elif val_name == "minh": - pane.min_size.y = int(value) - pane.min_size = wx.Size(pane.min_size.x, pane.min_size.y) - elif val_name == "maxw": - pane.max_size.x = int(value) - elif val_name == "maxh": - pane.max_size.y = int(value) - pane.max_size = wx.Size(pane.max_size.x, pane.max_size.y) - elif val_name == "floatx": - pane.floating_pos.x = int(value) - elif val_name == "floaty": - pane.floating_pos.y = int(value) - pane.floating_pos = wx.Point(pane.floating_pos.x, pane.floating_pos.y) - elif val_name == "floatw": - pane.floating_size.x = int(value) - elif val_name == "floath": - pane.floating_size.y = int(value) - pane.floating_size = wx.Size(pane.floating_size.x, pane.floating_size.y) - else: - raise "\nERROR: Bad Perspective String." - - # replace escaped characters so we can - # split up the string easily - pane.name = pane.name.replace("\a", "|") - pane.name = pane.name.replace("\b", ";") - pane.caption = pane.caption.replace("\a", "|") - pane.caption = pane.caption.replace("\b", ";") - - p = self.GetPane(pane.name) - if not p.IsOk(): - # the pane window couldn't be found - # in the existing layout - return False - - indx = self._panes.index(p) - pane.window = p.window - pane.frame = p.frame - pane.buttons = p.buttons - self._panes[indx] = pane - - if update: - self.Update() - - return True - - - def GetPanePositionsAndSizes(self, dock): - """ Returns all the panes positions and sizes. """ - - caption_size = self._art.GetMetric(AUI_ART_CAPTION_SIZE) - pane_border_size = self._art.GetMetric(AUI_ART_PANE_BORDER_SIZE) - gripper_size = self._art.GetMetric(AUI_ART_GRIPPER_SIZE) - - positions = [] - sizes = [] - - action_pane = -1 - pane_count = len(dock.panes) - - # find the pane marked as our action pane - for pane_i in xrange(pane_count): - pane = dock.panes[pane_i] - if pane.state & AuiPaneInfo.actionPane: - action_pane = pane_i - - # set up each panes default position, and - # determine the size (width or height, depending - # on the dock's orientation) of each pane - for pane in dock.panes: - positions.append(pane.dock_pos) - size = 0 - - if pane.HasBorder(): - size = size + pane_border_size*2 - - if dock.IsHorizontal(): - if pane.HasGripper() and not pane.HasGripperTop(): - size = size + gripper_size - - size = size + pane.best_size.x - - else: - if pane.HasGripper() and pane.HasGripperTop(): - size = size + gripper_size - - if pane.HasCaption(): - size = size + caption_size - - size = size + pane.best_size.y - - sizes.append(size) - - # if there is no action pane, just return the default - # positions (as specified in pane.pane_pos) - if action_pane == -1: - return positions, sizes - - offset = 0 - for pane_i in xrange(action_pane-1, -1, -1): - amount = positions[pane_i+1] - (positions[pane_i] + sizes[pane_i]) - if amount >= 0: - offset = offset + amount - else: - positions[pane_i] -= -amount - - offset = offset + sizes[pane_i] - - # if the dock mode is fixed, make sure none of the panes - # overlap we will bump panes that overlap - offset = 0 - for pane_i in xrange(action_pane, pane_count): - amount = positions[pane_i] - offset - if amount >= 0: - offset = offset + amount - else: - positions[pane_i] += -amount - - offset = offset + sizes[pane_i] - - return positions, sizes - - - def LayoutAddPane(self, cont, dock, pane, uiparts, spacer_only): - - sizer_item = wx.SizerItem() - caption_size = self._art.GetMetric(AUI_ART_CAPTION_SIZE) - gripper_size = self._art.GetMetric(AUI_ART_GRIPPER_SIZE) - pane_border_size = self._art.GetMetric(AUI_ART_PANE_BORDER_SIZE) - pane_button_size = self._art.GetMetric(AUI_ART_PANE_BUTTON_SIZE) - - # find out the orientation of the item (orientation for panes - # is the same as the dock's orientation) - - if dock.IsHorizontal(): - orientation = wx.HORIZONTAL - else: - orientation = wx.VERTICAL - - # this variable will store the proportion - # value that the pane will receive - pane_proportion = pane.dock_proportion - - horz_pane_sizer = wx.BoxSizer(wx.HORIZONTAL) - vert_pane_sizer = wx.BoxSizer(wx.VERTICAL) - - if pane.HasGripper(): - - part = DockUIPart() - if pane.HasGripperTop(): - sizer_item = vert_pane_sizer.Add((1, gripper_size), 0, wx.EXPAND) - else: - sizer_item = horz_pane_sizer.Add((gripper_size, 1), 0, wx.EXPAND) - - part.type = DockUIPart.typeGripper - part.dock = dock - part.pane = pane - part.button = None - part.orientation = orientation - part.cont_sizer = horz_pane_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - if pane.HasCaption(): - - # create the caption sizer - part = DockUIPart() - caption_sizer = wx.BoxSizer(wx.HORIZONTAL) - sizer_item = caption_sizer.Add((1, caption_size), 1, wx.EXPAND) - part.type = DockUIPart.typeCaption - part.dock = dock - part.pane = pane - part.button = None - part.orientation = orientation - part.cont_sizer = vert_pane_sizer - part.sizer_item = sizer_item - caption_part_idx = len(uiparts) - uiparts.append(part) - - # add pane buttons to the caption - for button in pane.buttons: - sizer_item = caption_sizer.Add((pane_button_size, - caption_size), - 0, wx.EXPAND) - part = DockUIPart() - part.type = DockUIPart.typePaneButton - part.dock = dock - part.pane = pane - part.button = button - part.orientation = orientation - part.cont_sizer = caption_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - # add the caption sizer - sizer_item = vert_pane_sizer.Add(caption_sizer, 0, wx.EXPAND) - uiparts[caption_part_idx].sizer_item = sizer_item - - # add the pane window itself - if spacer_only: - sizer_item = vert_pane_sizer.Add((1, 1), 1, wx.EXPAND) - else: - sizer_item = vert_pane_sizer.Add(pane.window, 1, wx.EXPAND) - vert_pane_sizer.SetItemMinSize(pane.window, (1, 1)) - - part = DockUIPart() - part.type = DockUIPart.typePane - part.dock = dock - part.pane = pane - part.button = None - part.orientation = orientation - part.cont_sizer = vert_pane_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - # determine if the pane should have a minimum size if the pane is - # non-resizable (fixed) then we must set a minimum size. Alternitavely, - # if the pane.min_size is set, we must use that value as well - - min_size = pane.min_size - if pane.IsFixed(): - if min_size == wx.DefaultSize: - min_size = pane.best_size - pane_proportion = 0 - - if min_size != wx.DefaultSize: - vert_pane_sizer.SetItemMinSize( - len(vert_pane_sizer.GetChildren())-1, (min_size.x, min_size.y)) - - # add the verticle sizer (caption, pane window) to the - # horizontal sizer (gripper, verticle sizer) - horz_pane_sizer.Add(vert_pane_sizer, 1, wx.EXPAND) - - # finally, add the pane sizer to the dock sizer - if pane.HasBorder(): - # allowing space for the pane's border - sizer_item = cont.Add(horz_pane_sizer, pane_proportion, - wx.EXPAND | wx.ALL, pane_border_size) - part = DockUIPart() - part.type = DockUIPart.typePaneBorder - part.dock = dock - part.pane = pane - part.button = None - part.orientation = orientation - part.cont_sizer = cont - part.sizer_item = sizer_item - uiparts.append(part) - else: - sizer_item = cont.Add(horz_pane_sizer, pane_proportion, wx.EXPAND) - - return uiparts - - - def LayoutAddDock(self, cont, dock, uiparts, spacer_only): - - sizer_item = wx.SizerItem() - part = DockUIPart() - - sash_size = self._art.GetMetric(AUI_ART_SASH_SIZE) - orientation = (dock.IsHorizontal() and [wx.HORIZONTAL] or [wx.VERTICAL])[0] - - # resizable bottom and right docks have a sash before them - if not dock.fixed and (dock.dock_direction == AUI_DOCK_BOTTOM or \ - dock.dock_direction == AUI_DOCK_RIGHT): - - sizer_item = cont.Add((sash_size, sash_size), 0, wx.EXPAND) - - part.type = DockUIPart.typeDockSizer - part.orientation = orientation - part.dock = dock - part.pane = None - part.button = None - part.cont_sizer = cont - part.sizer_item = sizer_item - uiparts.append(part) - - # create the sizer for the dock - dock_sizer = wx.BoxSizer(orientation) - - # add each pane to the dock - pane_count = len(dock.panes) - - if dock.fixed: - - # figure out the real pane positions we will - # use, without modifying the each pane's pane_pos member - pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock) - - offset = 0 - for pane_i in xrange(pane_count): - - pane = dock.panes[pane_i] - pane_pos = pane_positions[pane_i] - - amount = pane_pos - offset - if amount > 0: - - if dock.IsVertical(): - sizer_item = dock_sizer.Add((1, amount), 0, wx.EXPAND) - else: - sizer_item = dock_sizer.Add((amount, 1), 0, wx.EXPAND) - - part = DockUIPart() - part.type = DockUIPart.typeBackground - part.dock = dock - part.pane = None - part.button = None - part.orientation = (orientation==wx.HORIZONTAL and \ - [wx.VERTICAL] or [wx.HORIZONTAL])[0] - part.cont_sizer = dock_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - offset = offset + amount - - uiparts = self.LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only) - - offset = offset + pane_sizes[pane_i] - - # at the end add a very small stretchable background area - sizer_item = dock_sizer.Add((1, 1), 1, wx.EXPAND) - part = DockUIPart() - part.type = DockUIPart.typeBackground - part.dock = dock - part.pane = None - part.button = None - part.orientation = orientation - part.cont_sizer = dock_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - else: - - for pane_i in xrange(pane_count): - - pane = dock.panes[pane_i] - - # if this is not the first pane being added, - # we need to add a pane sizer - if pane_i > 0: - sizer_item = dock_sizer.Add((sash_size, sash_size), 0, wx.EXPAND) - part = DockUIPart() - part.type = DockUIPart.typePaneSizer - part.dock = dock - part.pane = dock.panes[pane_i-1] - part.button = None - part.orientation = (orientation==wx.HORIZONTAL and \ - [wx.VERTICAL] or [wx.HORIZONTAL])[0] - part.cont_sizer = dock_sizer - part.sizer_item = sizer_item - uiparts.append(part) - - uiparts = self.LayoutAddPane(dock_sizer, dock, pane, uiparts, spacer_only) - - if dock.dock_direction == AUI_DOCK_CENTER: - sizer_item = cont.Add(dock_sizer, 1, wx.EXPAND) - else: - sizer_item = cont.Add(dock_sizer, 0, wx.EXPAND) - - part = DockUIPart() - part.type = DockUIPart.typeDock - part.dock = dock - part.pane = None - part.button = None - part.orientation = orientation - part.cont_sizer = cont - part.sizer_item = sizer_item - uiparts.append(part) - - if dock.IsHorizontal(): - cont.SetItemMinSize(dock_sizer, (0, dock.size)) - else: - cont.SetItemMinSize(dock_sizer, (dock.size, 0)) - - # top and left docks have a sash after them - if not dock.fixed and (dock.dock_direction == AUI_DOCK_TOP or \ - dock.dock_direction == AUI_DOCK_LEFT): - - sizer_item = cont.Add((sash_size, sash_size), 0, wx.EXPAND) - - part = DockUIPart() - part.type = DockUIPart.typeDockSizer - part.dock = dock - part.pane = None - part.button = None - part.orientation = orientation - part.cont_sizer = cont - part.sizer_item = sizer_item - uiparts.append(part) - - return uiparts - - - def LayoutAll(self, panes, docks, uiparts, spacer_only=False, oncheck=True): - - container = wx.BoxSizer(wx.VERTICAL) - - pane_border_size = self._art.GetMetric(AUI_ART_PANE_BORDER_SIZE) - caption_size = self._art.GetMetric(AUI_ART_CAPTION_SIZE) - cli_size = self._frame.GetClientSize() - - # empty all docks out - for ii in xrange(len(docks)): - docks[ii].panes = [] - - dock_count = len(docks) - - # iterate through all known panes, filing each - # of them into the appropriate dock. If the - # pane does not exist in the dock, add it - for p in panes: - - # find any docks in this layer - arr = FindDocks(docks, p.dock_direction, p.dock_layer, p.dock_row) - - if len(arr) > 0: - dock = arr[0] - else: - # dock was not found, so we need to create a new one - d = DockInfo() - d.dock_direction = p.dock_direction - d.dock_layer = p.dock_layer - d.dock_row = p.dock_row - docks.append(d) - dock = docks[-1] - - if p.IsDocked() and p.IsShown(): - # remove the pane from any existing docks except this one - docks = RemovePaneFromDocks(docks, p, dock) - - # pane needs to be added to the dock, - # if it doesn't already exist - if not FindPaneInDock(dock, p.window): - dock.panes.append(p) - else: - # remove the pane from any existing docks - docks = RemovePaneFromDocks(docks, p) - - # remove any empty docks - for ii in xrange(len(docks)-1, -1, -1): - if len(docks[ii].panes) == 0: - docks.pop(ii) - - dock_count = len(docks) - # configure the docks further - for ii in xrange(len(docks)): - dock = docks[ii] - dock_pane_count = len(dock.panes) - - # sort the dock pane array by the pane's - # dock position (dock_pos), in ascending order - dock.panes.sort(PaneSortFunc) - - # for newly created docks, set up their initial size - if dock.size == 0: - size = 0 - for jj in xrange(dock_pane_count): - pane = dock.panes[jj] - pane_size = pane.best_size - if pane_size == wx.DefaultSize: - pane_size = pane.min_size - if pane_size == wx.DefaultSize: - pane_size = pane.window.GetSize() - - if dock.IsHorizontal(): - size = max(pane_size.y, size) - else: - size = max(pane_size.x, size) - - # add space for the border (two times), but only - # if at least one pane inside the dock has a pane border - for jj in xrange(dock_pane_count): - if dock.panes[jj].HasBorder(): - size = size + pane_border_size*2 - break - - # if pane is on the top or bottom, add the caption height, - # but only if at least one pane inside the dock has a caption - if dock.IsHorizontal(): - for jj in xrange(dock_pane_count): - if dock.panes[jj].HasCaption(): - size = size + caption_size - break - - # new dock's size may not be more than 1/3 of the frame size - if dock.IsHorizontal(): - size = min(size, cli_size.y/3) - else: - size = min(size, cli_size.x/3) - - if size < 10: - size = 10 - - dock.size = size - - # determine the dock's minimum size - plus_border = False - plus_caption = False - dock_min_size = 0 - for jj in xrange(dock_pane_count): - pane = dock.panes[jj] - if pane.min_size != wx.DefaultSize: - if pane.HasBorder(): - plus_border = True - if pane.HasCaption(): - plus_caption = True - if dock.IsHorizontal(): - if pane.min_size.y > dock_min_size: - dock_min_size = pane.min_size.y - else: - if pane.min_size.x > dock_min_size: - dock_min_size = pane.min_size.x - - if plus_border: - dock_min_size = dock_min_size + pane_border_size*2 - if plus_caption and dock.IsHorizontal(): - dock_min_size = dock_min_size + caption_size - - dock.min_size = dock_min_size - - # if the pane's current size is less than it's - # minimum, increase the dock's size to it's minimum - if dock.size < dock.min_size: - dock.size = dock.min_size - - # determine the dock's mode (fixed or proportional) - # determine whether the dock has only toolbars - action_pane_marked = False - dock.fixed = True - dock.toolbar = True - for jj in xrange(dock_pane_count): - pane = dock.panes[jj] - if not pane.IsFixed(): - dock.fixed = False - if not pane.IsToolbar(): - dock.toolbar = False - if pane.state & AuiPaneInfo.actionPane: - action_pane_marked = True - - # if the dock mode is proportional and not fixed-pixel, - # reassign the dock_pos to the sequential 0, 1, 2, 3 - # e.g. remove gaps like 1, 2, 30, 500 - if not dock.fixed: - for jj in xrange(dock_pane_count): - pane = dock.panes[jj] - pane.dock_pos = jj - dock.panes[jj] = pane - - # if the dock mode is fixed, and none of the panes - # are being moved right now, make sure the panes - # do not overlap each other. If they do, we will - # adjust the panes' positions - if dock.fixed and not action_pane_marked: - pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock) - offset = 0 - for jj in xrange(dock_pane_count): - pane = dock.panes[jj] - pane.dock_pos = pane_positions[jj] - amount = pane.dock_pos - offset - if amount >= 0: - offset = offset + amount - else: - pane.dock_pos += -amount - - offset = offset + pane_sizes[jj] - dock.panes[jj] = pane - - if oncheck: - self._docks[ii] = dock - - # discover the maximum dock layer - max_layer = 0 - - for ii in xrange(dock_count): - max_layer = max(max_layer, docks[ii].dock_layer) - - # clear out uiparts - uiparts = [] - - # create a bunch of box sizers, - # from the innermost level outwards. - cont = None - middle = None - - if oncheck: - docks = self._docks - - for layer in xrange(max_layer+1): - # find any docks in this layer - arr = FindDocks(docks, -1, layer, -1) - # if there aren't any, skip to the next layer - if len(arr) == 0: - continue - - old_cont = cont - - # create a container which will hold this layer's - # docks (top, bottom, left, right) - cont = wx.BoxSizer(wx.VERTICAL) - - # find any top docks in this layer - arr = FindDocks(docks, AUI_DOCK_TOP, layer, -1, arr) - arr = RenumberDockRows(arr) - if len(arr) > 0: - for row in xrange(len(arr)): - uiparts = self.LayoutAddDock(cont, arr[row], uiparts, spacer_only) - - # fill out the middle layer (which consists - # of left docks, content area and right docks) - - middle = wx.BoxSizer(wx.HORIZONTAL) - - # find any left docks in this layer - arr = FindDocks(docks, AUI_DOCK_LEFT, layer, -1, arr) - arr = RenumberDockRows(arr) - if len(arr) > 0: - for row in xrange(len(arr)): - uiparts = self.LayoutAddDock(middle, arr[row], uiparts, spacer_only) - - # add content dock (or previous layer's sizer - # to the middle - if not old_cont: - # find any center docks - arr = FindDocks(docks, AUI_DOCK_CENTER, -1, -1, arr) - if len(arr) > 0: - for row in xrange(len(arr)): - uiparts = self.LayoutAddDock(middle, arr[row], uiparts, spacer_only) - else: - # there are no center docks, add a background area - sizer_item = middle.Add((1, 1), 1, wx.EXPAND) - part = DockUIPart() - part.type = DockUIPart.typeBackground - part.pane = None - part.dock = None - part.button = None - part.cont_sizer = middle - part.sizer_item = sizer_item - uiparts.append(part) - else: - middle.Add(old_cont, 1, wx.EXPAND) - - # find any right docks in this layer - arr = FindDocks(docks, AUI_DOCK_RIGHT, layer, -1, arr) - arr = RenumberDockRows(arr) - if len(arr) > 0: - for row in xrange(len(arr)-1, -1, -1): - uiparts = self.LayoutAddDock(middle, arr[row], uiparts, spacer_only) - - cont.Add(middle, 1, wx.EXPAND) - - # find any bottom docks in this layer - arr = FindDocks(docks, AUI_DOCK_BOTTOM, layer, -1, arr) - arr = RenumberDockRows(arr) - if len(arr) > 0: - for row in xrange(len(arr)-1, -1, -1): - uiparts = self.LayoutAddDock(cont, arr[row], uiparts, spacer_only) - - if not cont: - # no sizer available, because there are no docks, - # therefore we will create a simple background area - cont = wx.BoxSizer(wx.VERTICAL) - sizer_item = cont.Add((1, 1), 1, wx.EXPAND) - part = DockUIPart() - part.type = DockUIPart.typeBackground - part.pane = None - part.dock = None - part.button = None - part.cont_sizer = middle - part.sizer_item = sizer_item - uiparts.append(part) - - if oncheck: - self._uiparts = uiparts - self._docks = docks - - container.Add(cont, 1, wx.EXPAND) - - if oncheck: - return container - else: - return container, panes, docks, uiparts - - - def Update(self): - """ - Update() updates the layout. Whenever changes are made to - one or more panes, this function should be called. It is the - external entry point for running the layout engine. - """ - - pane_count = len(self._panes) - # delete old sizer first - self._frame.SetSizer(None) - - # destroy floating panes which have been - # redocked or are becoming non-floating - for ii in xrange(pane_count): - p = self._panes[ii] - if not p.IsFloating() and p.frame: - # because the pane is no longer in a floating, we need to - # reparent it to self._frame and destroy the floating frame - # reduce flicker - p.window.SetSize((1, 1)) - p.frame.Show(False) - - # reparent to self._frame and destroy the pane - p.window.Reparent(self._frame) - p.frame.SetSizer(None) - p.frame.Destroy() - p.frame = None - - self._panes[ii] = p - - # create a layout for all of the panes - sizer = self.LayoutAll(self._panes, self._docks, self._uiparts, False) - - # hide or show panes as necessary, - # and float panes as necessary - - pane_count = len(self._panes) - - for ii in xrange(pane_count): - p = self._panes[ii] - if p.IsFloating(): - if p.frame == None: - # we need to create a frame for this - # pane, which has recently been floated - resizeborder = 1 - if p.IsFixed(): - resizeborder = 0 - - frame = AuiFloatingPane(self._frame, self, -1, "", p.floating_pos, - p.floating_size, resizeborder=resizeborder) - - # on MSW, if the owner desires transparent dragging, and - # the dragging is happening right now, then the floating - # window should have this style by default - - if self._action == actionDragAuiFloatingPane and self.UseTransparentDrag(): - self.MakeWindowTransparent(frame, 150) - - frame.SetPaneWindow(p) - p.frame = frame - if p.IsShown(): - frame.Show() - else: - - # frame already exists, make sure it's position - # and size reflect the information in AuiPaneInfo - if p.frame.GetPosition() != p.floating_pos: - p.frame.SetDimensions(p.floating_pos.x, p.floating_pos.y, - -1, -1, wx.SIZE_USE_EXISTING) - p.frame.Show(p.IsShown()) - else: - - p.window.Show(p.IsShown()) - - # if "active panes" are no longer allowed, clear - # any optionActive values from the pane states - if self._flags & AUI_MGR_ALLOW_ACTIVE_PANE == 0: - p.state &= ~AuiPaneInfo.optionActive - - self._panes[ii] = p - - - old_pane_rects = [] - - for ii in xrange(pane_count): - r = wx.Rect() - p = self._panes[ii] - - if p.window and p.IsShown() and p.IsDocked(): - r = p.rect - - old_pane_rects.append(r) - - # apply the new sizer - self._frame.SetSizer(sizer) - self._frame.SetAutoLayout(False) - self.DoFrameLayout() - - # now that the frame layout is done, we need to check - # the new pane rectangles against the old rectangles that - # we saved a few lines above here. If the rectangles have - # changed, the corresponding panes must also be updated - for ii in xrange(pane_count): - p = self._panes[ii] - if p.window and p.IsShown() and p.IsDocked(): - if p.rect != old_pane_rects[ii]: - p.window.Refresh() - p.window.Update() - - self.Repaint() - - - def DoFrameLayout(self): - """ - DoFrameLayout() is an internal function which invokes wxSizer.Layout - on the frame's main sizer, then measures all the various UI items - and updates their internal rectangles. This should always be called - instead of calling self._frame.Layout() directly - """ - - self._frame.Layout() - - for ii in xrange(len(self._uiparts)): - part = self._uiparts[ii] - - # get the rectangle of the UI part - # originally, this code looked like this: - # part.rect = wx.Rect(part.sizer_item.GetPosition(), - # part.sizer_item.GetSize()) - # this worked quite well, with one exception: the mdi - # client window had a "deferred" size variable - # that returned the wrong size. It looks like - # a bug in wx, because the former size of the window - # was being returned. So, we will retrieve the part's - # rectangle via other means - - part.rect = part.sizer_item.GetRect() - flag = part.sizer_item.GetFlag() - border = part.sizer_item.GetBorder() - - if flag & wx.TOP: - part.rect.y -= border - part.rect.height += border - if flag & wx.LEFT: - part.rect.x -= border - part.rect.width += border - if flag & wx.BOTTOM: - part.rect.height += border - if flag & wx.RIGHT: - part.rect.width += border - - if part.type == DockUIPart.typeDock: - part.dock.rect = part.rect - if part.type == DockUIPart.typePane: - part.pane.rect = part.rect - - self._uiparts[ii] = part - - - def GetPanePart(self, wnd): - """ - GetPanePart() looks up the pane border UI part of the - pane specified. This allows the caller to get the exact rectangle - of the pane in question, including decorations like caption and border. - """ - - for ii in xrange(len(self._uiparts)): - part = self._uiparts[ii] - if part.type == DockUIPart.typePaneBorder and \ - part.pane and part.pane.window == wnd: - return part - - for ii in xrange(len(self._uiparts)): - part = self._uiparts[ii] - if part.type == DockUIPart.typePane and \ - part.pane and part.pane.window == wnd: - return part - - return None - - - def GetDockPixelOffset(self, test): - """ - GetDockPixelOffset() is an internal function which returns - a dock's offset in pixels from the left side of the window - (for horizontal docks) or from the top of the window (for - vertical docks). This value is necessary for calculating - fixel-pane/toolbar offsets when they are dragged. - """ - - # the only way to accurately calculate the dock's - # offset is to actually run a theoretical layout - - docks, panes = CopyDocksAndPanes2(self._docks, self._panes) - panes.append(test) - - sizer, panes, docks, uiparts = self.LayoutAll(panes, docks, [], True, False) - client_size = self._frame.GetClientSize() - sizer.SetDimension(0, 0, client_size.x, client_size.y) - sizer.Layout() - - for ii in xrange(len(uiparts)): - part = uiparts[ii] - pos = part.sizer_item.GetPosition() - size = part.sizer_item.GetSize() - part.rect = wx.Rect(pos[0], pos[1], size[0], size[1]) - if part.type == DockUIPart.typeDock: - part.dock.rect = part.rect - - sizer.Destroy() - - for ii in xrange(len(docks)): - dock = docks[ii] - if test.dock_direction == dock.dock_direction and \ - test.dock_layer == dock.dock_layer and \ - test.dock_row == dock.dock_row: - - if dock.IsVertical(): - return dock.rect.y - else: - return dock.rect.x - - return 0 - - - def ProcessDockResult(self, target, new_pos): - """ - ProcessDockResult() is a utility function used by DoDrop() - it checks - if a dock operation is allowed, the new dock position is copied into - the target info. If the operation was allowed, the function returns True. - """ - - allowed = False - if new_pos.dock_direction == AUI_DOCK_TOP: - allowed = target.IsTopDockable() - elif new_pos.dock_direction == AUI_DOCK_BOTTOM: - allowed = target.IsBottomDockable() - elif new_pos.dock_direction == AUI_DOCK_LEFT: - allowed = target.IsLeftDockable() - elif new_pos.dock_direction == AUI_DOCK_RIGHT: - allowed = target.IsRightDockable() - - if allowed: - target = new_pos - - return allowed, target - - - def DoDrop(self, docks, panes, target, pt, offset=wx.Point(0,0)): - """ - DoDrop() is an important function. It basically takes a mouse position, - and determines where the panes new position would be. If the pane is to be - dropped, it performs the drop operation using the specified dock and pane - arrays. By specifying copy dock and pane arrays when calling, a "what-if" - scenario can be performed, giving precise coordinates for drop hints. - """ - - cli_size = self._frame.GetClientSize() - - drop = AuiPaneInfo() - drop.name = target.name - drop.caption = target.caption - drop.window = target.window - drop.frame = target.frame - drop.state = target.state - drop.dock_direction = target.dock_direction - drop.dock_layer = target.dock_layer - drop.dock_row = target.dock_row - drop.dock_pos = target.dock_pos - drop.best_size = target.best_size - drop.min_size = target.min_size - drop.max_size = target.max_size - drop.floating_pos = target.floating_pos - drop.floating_size = target.floating_size - drop.dock_proportion = target.dock_proportion - drop.buttons = target.buttons - drop.rect = target.rect - - # The result should always be shown - drop.Show() - - # Check to see if the pane has been dragged outside of the window - # (or near to the outside of the window), if so, dock it along the edge - - layer_insert_offset = auiLayerInsertOffset - - if target.IsToolbar(): - layer_insert_offset = 0 - - if pt.x < layer_insert_offset and \ - pt.x > layer_insert_offset-auiLayerInsertPixels: - new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_LEFT), - GetMaxLayer(docks, AUI_DOCK_BOTTOM)), - GetMaxLayer(docks, AUI_DOCK_TOP)) + 1 - - drop.Dock().Left().Layer(new_layer).Row(0). \ - Position(pt.y - self.GetDockPixelOffset(drop) - offset.y) - - return self.ProcessDockResult(target, drop) - - elif pt.y < layer_insert_offset and \ - pt.y > layer_insert_offset-auiLayerInsertPixels: - new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_TOP), - GetMaxLayer(docks, AUI_DOCK_LEFT)), - GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1 - - drop.Dock().Top().Layer(new_layer).Row(0). \ - Position(pt.x - self.GetDockPixelOffset(drop) - offset.x) - - return self.ProcessDockResult(target, drop) - - elif pt.x >= cli_size.x - layer_insert_offset and \ - pt.x < cli_size.x - layer_insert_offset + auiLayerInsertPixels: - - new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_RIGHT), - GetMaxLayer(docks, AUI_DOCK_TOP)), - GetMaxLayer(docks, AUI_DOCK_BOTTOM)) + 1 - - drop.Dock().Right().Layer(new_layer).Row(0). \ - Position(pt.y - self.GetDockPixelOffset(drop) - offset.y) - - return self.ProcessDockResult(target, drop) - - elif pt.y >= cli_size.y - layer_insert_offset and \ - pt.y < cli_size.y - layer_insert_offset + auiLayerInsertPixels: - - new_layer = max(max(GetMaxLayer(docks, AUI_DOCK_BOTTOM), - GetMaxLayer(docks, AUI_DOCK_LEFT)), - GetMaxLayer(docks, AUI_DOCK_RIGHT)) + 1 - - drop.Dock().Bottom().Layer(new_layer).Row(0). \ - Position(pt.x - self.GetDockPixelOffset(drop) - offset.x) - - return self.ProcessDockResult(target, drop) - - part = self.HitTest(pt.x, pt.y) - - if drop.IsToolbar(): - if not part or not part.dock: - return False, target - - # calculate the offset from where the dock begins - # to the point where the user dropped the pane - dock_drop_offset = 0 - if part.dock.IsHorizontal(): - dock_drop_offset = pt.x - part.dock.rect.x - offset.x - else: - dock_drop_offset = pt.y - part.dock.rect.y - offset.y - - # toolbars may only be moved in and to fixed-pane docks, - # otherwise we will try to float the pane. Also, the pane - # should float if being dragged over center pane windows - if not part.dock.fixed or part.dock.dock_direction == AUI_DOCK_CENTER: - if (self._flags & AUI_MGR_ALLOW_FLOATING) and (drop.IsFloatable() or (\ - part.dock.dock_direction != AUI_DOCK_CENTER and \ - part.dock.dock_direction != AUI_DOCK_NONE)): - - drop.Float() - - return self.ProcessDockResult(target, drop) - - drop.Dock(). \ - Direction(part.dock.dock_direction). \ - Layer(part.dock.dock_layer). \ - Row(part.dock.dock_row). \ - Position(dock_drop_offset) - - if pt.y < part.dock.rect.y + 2 and len(part.dock.panes) > 1: - row = drop.dock_row - panes = DoInsertDockRow(panes, part.dock.dock_direction, - part.dock.dock_layer, - part.dock.dock_row) - drop.dock_row = row - - if pt.y > part.dock.rect.y + part.dock.rect.height - 2 and \ - len(part.dock.panes) > 1: - panes = DoInsertDockRow(panes, part.dock.dock_direction, - part.dock.dock_layer, - part.dock.dock_row+1) - drop.dock_row = part.dock.dock_row + 1 - - return self.ProcessDockResult(target, drop) - - if not part: - return False, target - - if part.type == DockUIPart.typePaneBorder or \ - part.type == DockUIPart.typeCaption or \ - part.type == DockUIPart.typeGripper or \ - part.type == DockUIPart.typePaneButton or \ - part.type == DockUIPart.typePane or \ - part.type == DockUIPart.typePaneSizer or \ - part.type == DockUIPart.typeDockSizer or \ - part.type == DockUIPart.typeBackground: - - if part.type == DockUIPart.typeDockSizer: - if len(part.dock.panes) != 1: - return False, target - - part = self.GetPanePart(part.dock.panes[0].window) - - if not part: - return False, target - - # If a normal frame is being dragged over a toolbar, insert it - # along the edge under the toolbar, but over all other panes. - # (this could be done much better, but somehow factoring this - # calculation with the one at the beginning of this function) - if part.dock and (hasattr(part.dock, "toolbar") and part.dock.toolbar): - layer = 0 - - if part.dock.dock_direction == AUI_DOCK_LEFT: - layer = max(max(GetMaxLayer(docks, AUI_DOCK_LEFT), - GetMaxLayer(docks, AUI_DOCK_BOTTOM)), - GetMaxLayer(docks, AUI_DOCK_TOP)) - elif part.dock.dock_direction == AUI_DOCK_TOP: - layer = max(max(GetMaxLayer(docks, AUI_DOCK_TOP), - GetMaxLayer(docks, AUI_DOCK_LEFT)), - GetMaxLayer(docks, AUI_DOCK_RIGHT)) - elif part.dock.dock_direction == AUI_DOCK_RIGHT: - layer = max(max(GetMaxLayer(docks, AUI_DOCK_RIGHT), - GetMaxLayer(docks, AUI_DOCK_TOP)), - GetMaxLayer(docks, AUI_DOCK_BOTTOM)) - elif part.dock.dock_direction == AUI_DOCK_BOTTOM: - layer = max(max(GetMaxLayer(docks, AUI_DOCK_BOTTOM), - GetMaxLayer(docks, AUI_DOCK_LEFT)), - GetMaxLayer(docks, AUI_DOCK_RIGHT)) - - panes = DoInsertDockRow(panes, part.dock.dock_direction, - layer, 0) - drop.Dock(). \ - Direction(part.dock.dock_direction). \ - Layer(layer).Row(0).Position(0) - - return self.ProcessDockResult(target, drop) - - if not part.pane: - return False, target - - part = self.GetPanePart(part.pane.window) - if not part: - return False, target - - insert_dock_row = False - insert_row = part.pane.dock_row - insert_dir = part.pane.dock_direction - insert_layer = part.pane.dock_layer - - if part.pane.dock_direction == AUI_DOCK_TOP: - if pt.y >= part.rect.y and \ - pt.y < part.rect.y+auiInsertRowPixels: - insert_dock_row = True - - elif part.pane.dock_direction == AUI_DOCK_BOTTOM: - if pt.y > part.rect.y+part.rect.height-auiInsertRowPixels and \ - pt.y <= part.rect.y + part.rect.height: - insert_dock_row = True - - elif part.pane.dock_direction == AUI_DOCK_LEFT: - if pt.x >= part.rect.x and \ - pt.x < part.rect.x+auiInsertRowPixels: - insert_dock_row = True - - elif part.pane.dock_direction == AUI_DOCK_RIGHT: - if pt.x > part.rect.x+part.rect.width-auiInsertRowPixels and \ - pt.x <= part.rect.x+part.rect.width: - insert_dock_row = True - - elif part.pane.dock_direction == AUI_DOCK_CENTER: - # "new row pixels" will be set to the default, but - # must never exceed 20% of the window size - new_row_pixels_x = auiNewRowPixels - new_row_pixels_y = auiNewRowPixels - - if new_row_pixels_x > part.rect.width*20/100: - new_row_pixels_x = part.rect.width*20/100 - - if new_row_pixels_y > part.rect.height*20/100: - new_row_pixels_y = part.rect.height*20/100 - - # determine if the mouse pointer is in a location that - # will cause a new row to be inserted. The hot spot positions - # are along the borders of the center pane - - insert_layer = 0 - insert_dock_row = True - - if pt.x >= part.rect.x and \ - pt.x < part.rect.x+new_row_pixels_x: - insert_dir = AUI_DOCK_LEFT - elif pt.y >= part.rect.y and \ - pt.y < part.rect.y+new_row_pixels_y: - insert_dir = AUI_DOCK_TOP - elif pt.x >= part.rect.x + part.rect.width-new_row_pixels_x and \ - pt.x < part.rect.x + part.rect.width: - insert_dir = AUI_DOCK_RIGHT - elif pt.y >= part.rect.y+ part.rect.height-new_row_pixels_y and \ - pt.y < part.rect.y + part.rect.height: - insert_dir = AUI_DOCK_BOTTOM - else: - return False, target - - insert_row = GetMaxRow(panes, insert_dir, insert_layer) + 1 - - if insert_dock_row: - - panes = DoInsertDockRow(panes, insert_dir, insert_layer, - insert_row) - drop.Dock().Direction(insert_dir). \ - Layer(insert_layer). \ - Row(insert_row). \ - Position(0) - - return self.ProcessDockResult(target, drop) - - # determine the mouse offset and the pane size, both in the - # direction of the dock itself, and perpendicular to the dock - - if part.orientation == wx.VERTICAL: - - offset = pt.y - part.rect.y - size = part.rect.GetHeight() - - else: - - offset = pt.x - part.rect.x - size = part.rect.GetWidth() - - drop_position = part.pane.dock_pos - - # if we are in the top/left part of the pane, - # insert the pane before the pane being hovered over - if offset <= size/2: - - drop_position = part.pane.dock_pos - panes = DoInsertPane(panes, - part.pane.dock_direction, - part.pane.dock_layer, - part.pane.dock_row, - part.pane.dock_pos) - - # if we are in the bottom/right part of the pane, - # insert the pane before the pane being hovered over - if offset > size/2: - - drop_position = part.pane.dock_pos+1 - panes = DoInsertPane(panes, - part.pane.dock_direction, - part.pane.dock_layer, - part.pane.dock_row, - part.pane.dock_pos+1) - - drop.Dock(). \ - Direction(part.dock.dock_direction). \ - Layer(part.dock.dock_layer). \ - Row(part.dock.dock_row). \ - Position(drop_position) - - return self.ProcessDockResult(target, drop) - - return False, target - - - def UseTransparentHint(self): - return (self._flags & AUI_MGR_TRANSPARENT_HINT) and self.CanMakeWindowsTransparent() - - def OnHintFadeTimer(self, event): - #sanity check - if not self.UseTransparentHint(): - return - - if not self._hint_wnd or self._hint_fadeamt >= 50: - self._hint_fadetimer.Stop() - return - - self._hint_fadeamt = self._hint_fadeamt + 5 - self.MakeWindowTransparent(self._hint_wnd, self._hint_fadeamt) - - - def ShowHint(self, rect): - self._hintshown = True - if self.UseTransparentHint(): - if wx.Platform == "__WXMSW__": - if self._last_hint == rect: - return - self._last_hint = rect - - initial_fade = 50 - - if self._flags & AUI_MGR_TRANSPARENT_HINT_FADE: - initial_fade = 0 - - if self._hint_wnd == None: - - pt = rect.GetPosition() - size = rect.GetSize() - self._hint_wnd = wx.Frame(self._frame, -1, "", pt, size, - wx.FRAME_TOOL_WINDOW | - wx.FRAME_FLOAT_ON_PARENT | - wx.FRAME_NO_TASKBAR | - wx.NO_BORDER) - - self.MakeWindowTransparent(self._hint_wnd, initial_fade) - self._hint_wnd.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)) - self._hint_wnd.Show() - - # if we are dragging a floating pane, set the focus - - # back to that floating pane (otherwise it becomes unfocused) - - if self._action == actionDragAuiFloatingPane and self._action_window: - self._action_window.SetFocus() - - else: - - pt = rect.GetPosition() - size = rect.GetSize() - self.MakeWindowTransparent(self._hint_wnd, initial_fade) - self._hint_wnd.SetDimensions(pt.x, pt.y, rect.width, rect.height) - - if self._flags & AUI_MGR_TRANSPARENT_HINT_FADE: - # start fade in timer - self._hint_fadeamt = 0 - self._hint_fadetimer.SetOwner(self, 101) - self._hint_fadetimer.Start(5) - return - elif wx.Platform == "__WXMAC__": - if self._last_hint == rect: - return #same rect, already shown, no-op - if self._flags & AUI_MGR_TRANSPARENT_HINT_FADE: - initial_fade = 0 - else: - initial_fade = 80 - - if not self._hint_wnd: - self._hint_wnd = wx.MiniFrame(self._frame, - style=wx.FRAME_FLOAT_ON_PARENT|wx.FRAME_TOOL_WINDOW - |wx.CAPTION#|wx.FRAME_SHAPED - #without wxCAPTION + wx.FRAME_TOOL_WINDOW, the hint window - #gets focus & dims the main frames toolbar, which is both wrong - #and distracting. - #wx.CAPTION + wx.FRAME_TOOL_WINDOW cures the focus problem, - #but then it draws the caption. Adding wx.FRAME_SHAPED takes - #care of that, but then SetRect doesn't work to size - need to - #create a bitmap or mask or something. - ) - #can't set the background of a wx.Frame in OSX - p = wx.Panel(self._hint_wnd) - - #the caption color is a light silver thats really hard to see - #especially transparent. See if theres some other system - #setting that is more appropriate, or just extend the art provider - #to cover this - #p.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION)) - p.SetBackgroundColour(wx.BLUE) - - self.MakeWindowTransparent(self._hint_wnd, initial_fade) - self._hint_wnd.SetRect(rect) - self._hint_wnd.Show() - - if self._action == actionDragAuiFloatingPane and self._action_window: - self._action_window.SetFocus() - - if self._flags & AUI_MGR_TRANSPARENT_HINT_FADE: - # start fade in timer - self._hint_fadeamt = 0 - self._hint_fadetimer.SetOwner(self, 101) - self._hint_fadetimer.Start(5) - return - - - if self._last_hint != rect: - # remove the last hint rectangle - self._last_hint = rect - self._frame.Refresh() - self._frame.Update() - - - - screendc = wx.ScreenDC() - clip = wx.Region(1, 1, 10000, 10000) - - # clip all floating windows, so we don't draw over them - for pane in self._panes: - if pane.IsFloating() and pane.frame.IsShown(): - recta = pane.frame.GetRect() - if wx.Platform == "__WXGTK__": - # wxGTK returns the client size, not the whole frame size - width, height = pane.frame.ClientToScreen((0,0)) - pane.frame.GetPosition() - recta.width = recta.width + width - recta.height = recta.height + height - recta.Inflate(5, 5) - #endif - - clip.SubtractRect(recta) - - screendc.SetClippingRegionAsRegion(clip) - - screendc.SetBrush(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVECAPTION))) - screendc.SetPen(wx.TRANSPARENT_PEN) - - screendc.DrawRectangle(rect.x, rect.y, 5, rect.height) - screendc.DrawRectangle(rect.x+5, rect.y, rect.width-10, 5) - screendc.DrawRectangle(rect.x+rect.width-5, rect.y, 5, rect.height) - screendc.DrawRectangle(rect.x+5, rect.y+rect.height-5, rect.width-10, 5) - - - def HideHint(self): - - self._hintshown = False - - # hides a transparent window hint (currently wxMSW only) - if self.UseTransparentHint(): - if self._hint_wnd: - self._hint_fadetimer.Stop() - #self._hint_wnd.Destroy() - self.MakeWindowTransparent(self._hint_wnd, 0) - self._last_hint = wx.Rect() - - return - - # hides a painted hint by redrawing the frame window - if not self._last_hint.IsEmpty(): - self._frame.Refresh() - self._frame.Update() - self._last_hint = wx.Rect() - - - def DrawHintRect(self, pane_window, pt, offset): - """ - DrawHintRect() draws a drop hint rectangle. First calls DoDrop() to - determine the exact position the pane would be at were if dropped. If - the pame would indeed become docked at the specified drop point, - DrawHintRect() then calls ShowHint() to indicate this drop rectangle. - "pane_window" is the window pointer of the pane being dragged, pt is - the mouse position, in client coordinates. - """ - - # we need to paint a hint rectangle to find out the exact hint rectangle, - # we will create a new temporary layout and then measure the resulting - # rectangle we will create a copy of the docking structures (self._docks) - # so that we don't modify the real thing on screen - - rect = wx.Rect() - pane = self.GetPane(pane_window) - - attrs = self.GetAttributes(pane) - hint = AuiPaneInfo() - hint = self.SetAttributes(hint, attrs) - - if hint.name != "__HINT__": - self._oldname = hint.name - - hint.name = "__HINT__" - - if not hint.IsOk(): - hint.name = self._oldname - return - - docks, panes = CopyDocksAndPanes2(self._docks, self._panes) - - # remove any pane already there which bears the same window - # this happens when you are moving a pane around in a dock - for ii in xrange(len(panes)): - if panes[ii].window == pane_window: - docks = RemovePaneFromDocks(docks, panes[ii]) - panes.pop(ii) - break - - # find out where the new pane would be - allow, hint = self.DoDrop(docks, panes, hint, pt, offset) - - if not allow: - self.HideHint() - return - - panes.append(hint) - - sizer, panes, docks, uiparts = self.LayoutAll(panes, docks, [], True, False) - client_size = self._frame.GetClientSize() - sizer.SetDimension(0, 0, client_size.x, client_size.y) - sizer.Layout() - - for ii in xrange(len(uiparts)): - part = uiparts[ii] - if part.type == DockUIPart.typePaneBorder and \ - part.pane and part.pane.name == "__HINT__": - pos = part.sizer_item.GetPosition() - size = part.sizer_item.GetSize() - rect = wx.Rect(pos[0], pos[1], size[0], size[1]) - break - - sizer.Destroy() - - if rect.IsEmpty(): - self.HideHint() - return - - # actually show the hint rectangle on the screen - rect.x, rect.y = self._frame.ClientToScreen((rect.x, rect.y)) - self.ShowHint(rect) - - - def GetAttributes(self, pane): - - attrs = [] - attrs.extend([pane.window, pane.frame, pane.state, pane.dock_direction, - pane.dock_layer, pane.dock_pos, pane.dock_row, pane.dock_proportion, - pane.floating_pos, pane.floating_size, pane.best_size, - pane.min_size, pane.max_size, pane.caption, pane.name, - pane.buttons, pane.rect]) - - return attrs - - - def SetAttributes(self, pane, attrs): - - pane.window = attrs[0] - pane.frame = attrs[1] - pane.state = attrs[2] - pane.dock_direction = attrs[3] - pane.dock_layer = attrs[4] - pane.dock_pos = attrs[5] - pane.dock_row = attrs[6] - pane.dock_proportion = attrs[7] - pane.floating_pos = attrs[8] - pane.floating_size = attrs[9] - pane.best_size = attrs[10] - pane.min_size = attrs[11] - pane.max_size = attrs[12] - pane.caption = attrs[13] - pane.name = attrs[14] - pane.buttons = attrs[15] - pane.rect = attrs[16] - - return pane - - def UseTransparentDrag(self): - - if self._flags & AUI_MGR_TRANSPARENT_DRAG: - return self.CanMakeWindowsTransparent() - else: - return False - - - def OnAuiFloatingPaneMoveStart(self, wnd): - - # try to find the pane - pane = self.GetPane(wnd) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - if self.UseTransparentDrag() and pane.IsDockable(): - self.MakeWindowTransparent(pane.frame, 150) - - - def OnAuiFloatingPaneMoving(self, wnd): - - # try to find the pane - pane = self.GetPane(wnd) - - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - pt = wx.GetMousePosition() - client_pt = self._frame.ScreenToClient(pt) - - # calculate the offset from the upper left-hand corner - # of the frame to the mouse pointer - frame_pos = pane.frame.GetPosition() - action_offset = wx.Point(pt[0]-frame_pos.x, pt[1]-frame_pos.y) - -## # no hint for toolbar floating windows -## if pane.IsToolbar() and self._action == actionDragAuiFloatingPane: -## -## oldname = pane.name -## indx = self._panes.index(pane) -## hint = pane -## docks, panes = CopyDocksAndPanes2(self._docks, self._panes) -## -## # find out where the new pane would be -## ret, hint = self.DoDrop(docks, panes, hint, client_pt) -## -## if not ret: -## return -## -## if hint.IsFloating(): -## return -## -## pane = hint -## pane.name = oldname -## -## self._panes[indx] = pane -## self._action = actionDragToolbarPane -## self._action_window = pane.window -## -## self.Update() -## -## return - - # if a key modifier is pressed while dragging the frame, - # don't dock the window - if wx.GetKeyState(wx.WXK_CONTROL) or wx.GetKeyState(wx.WXK_ALT): - self.HideHint() - return - - if pane.IsDockable(): - self.DrawHintRect(wnd, client_pt, action_offset) - - # reduces flicker - self._frame.Update() - - - def OnAuiFloatingPaneMoved(self, wnd): - - # try to find the pane - pane = self.GetPane(wnd) - - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - pt = wx.GetMousePosition() - client_pt = self._frame.ScreenToClient(pt) - - indx = self._panes.index(pane) - - # calculate the offset from the upper left-hand corner - # of the frame to the mouse pointer - frame_pos = pane.frame.GetPosition() - action_offset = wx.Point(pt[0]-frame_pos.x, pt[1]-frame_pos.y) - - # if a key modifier is pressed while dragging the frame, - # don't dock the window - if wx.GetKeyState(wx.WXK_CONTROL) or wx.GetKeyState(wx.WXK_ALT): - self.HideHint() - return - - if not pane.IsToolbar() and pane.IsDockable() and not self._hintshown: - if not pane.IsFloating(): - pane.Float() - pane.floating_pos = pane.frame.GetPosition() - self._panes[indx] = pane - if self.UseTransparentDrag(): - self.MakeWindowTransparent(pane.frame, 255) - - # do the drop calculation - allow, pane = self.DoDrop(self._docks, self._panes, pane, client_pt, action_offset) - - # if the pane is still floating, update it's floating - # position (that we store) - if pane.IsFloating(): - pane.floating_pos = pane.frame.GetPosition() - if self.UseTransparentDrag(): - self.MakeWindowTransparent(pane.frame, 255) - - if not pane.IsToolbar() and pane.IsDockable(): - pane.name = self._oldname - - self._panes[indx] = pane - - self.Update() - self.HideHint() - - - def OnAuiFloatingPaneResized(self, wnd, size): - - # try to find the pane - pane = self.GetPane(wnd) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - indx = self._panes.index(pane) - pane.floating_size = size - self._panes[indx] = pane - - - def OnAuiFloatingPaneClosed(self, wnd, event): - # try to find the pane - pane = self.GetPane(wnd) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - e = AuiManagerEvent(wxEVT_AUI_PANECLOSE) - e.SetPane(pane) - self.ProcessMgrEvent(e) - - if e.GetSkipped(): - indx = self._panes.index(pane) - # reparent the pane window back to us and - # prepare the frame window for destruction - pane.window.Show(False) - pane.window.Reparent(self._frame) - pane.frame = None - pane.Hide() - - self._panes[indx] = pane - event.Skip() - - - - def OnAuiFloatingPaneActivated(self, wnd): - - if self.GetFlags() & AUI_MGR_ALLOW_ACTIVE_PANE: - # try to find the pane - pane = self.GetPane(wnd) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - self._panes = SetActivePane(self._panes, wnd) - self.Repaint() - - - def Render(self, dc): - """ - Render() draws all of the pane captions, sashes, - backgrounds, captions, grippers, pane borders and buttons. - It renders the entire user interface. - """ - - for part in self._uiparts: - - # don't draw hidden pane items - if part.sizer_item and not part.sizer_item.IsShown(): - continue - - if part.type == DockUIPart.typeDockSizer or \ - part.type == DockUIPart.typePaneSizer: - self._art.DrawSash(dc, part.orientation, part.rect) - elif part.type == DockUIPart.typeBackground: - self._art.DrawBackground(dc, part.orientation, part.rect) - elif part.type == DockUIPart.typeCaption: - self._art.DrawCaption(dc, part.pane.caption, part.rect, part.pane) - elif part.type == DockUIPart.typeGripper: - self._art.DrawGripper(dc, part.rect, part.pane) - elif part.type == DockUIPart.typePaneBorder: - self._art.DrawBorder(dc, part.rect, part.pane) - elif part.type == DockUIPart.typePaneButton: - self._art.DrawPaneButton(dc, part.button.button_id, - AUI_BUTTON_STATE_NORMAL, part.rect, part.pane) - - - def Repaint(self, dc=None): - - w, h = self._frame.GetClientSize() - # figure out which dc to use if one - # has been specified, use it, otherwise - # make a client dc - client_dc = None - - if not dc: - client_dc = wx.ClientDC(self._frame) - dc = client_dc - - # if the frame has a toolbar, the client area - # origin will not be (0,0). - pt = self._frame.GetClientAreaOrigin() - if pt.x != 0 or pt.y != 0: - dc.SetDeviceOrigin(pt.x, pt.y) - - # render all the items - self.Render(dc) - - # if we created a client_dc, delete it - if client_dc: - del client_dc - - - def OnPaint(self, event): - - dc = wx.PaintDC(self._frame) - - if wx.Platform == "__WXMAC__": - #Macs paint optimizations clip the area we need to paint a log - #of the time, this is a dirty hack to always paint everything - self.Repaint(None) - else: - self.Repaint(dc) - - - def OnEraseBackground(self, event): - - if wx.Platform == "__WXMAC__": - event.Skip() - - - def OnSize(self, event): - - if self._frame: - - self.DoFrameLayout() - wx.CallAfter(self.Repaint) - - if not isinstance(self._frame, wx.MDIParentFrame): - event.Skip() - - - def OnSetCursor(self, event): - - # determine cursor - part = self.HitTest(event.GetX(), event.GetY()) - cursor = None - - if part: - if part.type == DockUIPart.typeDockSizer or \ - part.type == DockUIPart.typePaneSizer: - - # a dock may not be resized if it has a single - # pane which is not resizable - if part.type == DockUIPart.typeDockSizer and part.dock and \ - len(part.dock.panes) == 1 and part.dock.panes[0].IsFixed(): - return - - # panes that may not be resized do not get a sizing cursor - if part.pane and part.pane.IsFixed(): - return - - if part.orientation == wx.VERTICAL: - cursor = wx.StockCursor(wx.CURSOR_SIZEWE) - else: - cursor = wx.StockCursor(wx.CURSOR_SIZENS) - - elif part.type == DockUIPart.typeGripper: - cursor = wx.StockCursor(wx.CURSOR_SIZING) - - if cursor is not None: - event.SetCursor(cursor) - - - def UpdateButtonOnScreen(self, button_ui_part, event): - - hit_test = self.HitTest(event.GetX(), event.GetY()) - state = AUI_BUTTON_STATE_NORMAL - - if hit_test == button_ui_part: - if event.LeftDown(): - state = AUI_BUTTON_STATE_PRESSED - else: - state = AUI_BUTTON_STATE_HOVER - else: - if event.LeftDown(): - state = AUI_BUTTON_STATE_HOVER - - # now repaint the button with hover state - cdc = wx.ClientDC(self._frame) - - # if the frame has a toolbar, the client area - # origin will not be (0,0). - pt = self._frame.GetClientAreaOrigin() - if pt.x != 0 or pt.y != 0: - cdc.SetDeviceOrigin(pt.x, pt.y) - - self._art.DrawPaneButton(cdc, - button_ui_part.button.button_id, - state, - button_ui_part.rect, hit_test.pane) - - - def OnLeftDown(self, event): - - part = self.HitTest(event.GetX(), event.GetY()) - - if part: - if part.dock and part.dock.dock_direction == AUI_DOCK_CENTER: - return - - if part.type == DockUIPart.typeDockSizer or \ - part.type == DockUIPart.typePaneSizer: - - # a dock may not be resized if it has a single - # pane which is not resizable - if part.type == DockUIPart.typeDockSizer and part.dock and \ - len(part.dock.panes) == 1 and part.dock.panes[0].IsFixed(): - return - - # panes that may not be resized should be ignored here - if part.pane and part.pane.IsFixed(): - return - - self._action = actionResize - self._action_part = part - self._action_hintrect = wx.Rect() - self._action_start = wx.Point(event.GetX(), event.GetY()) - self._action_offset = wx.Point(event.GetX() - part.rect.x, - event.GetY() - part.rect.y) - self._frame.CaptureMouse() - - elif part.type == DockUIPart.typePaneButton: - - self._action = actionClickButton - self._action_part = part - self._action_start = wx.Point(event.GetX(), event.GetY()) - self._frame.CaptureMouse() - - self.UpdateButtonOnScreen(part, event) - - elif part.type == DockUIPart.typeCaption or \ - part.type == DockUIPart.typeGripper: - - if self.GetFlags() & AUI_MGR_ALLOW_ACTIVE_PANE: - # set the caption as active - self._panes = SetActivePane(self._panes, part.pane.window) - self.Repaint() - - self._action = actionClickCaption - self._action_part = part - self._action_start = wx.Point(event.GetX(), event.GetY()) - self._action_offset = wx.Point(event.GetX() - part.rect.x, - event.GetY() - part.rect.y) - self._frame.CaptureMouse() - - if wx.Platform != "__WXMAC__": - event.Skip() - - - def OnLeftUp(self, event): - - if self._action == actionResize: - - self._frame.ReleaseMouse() - - # get rid of the hint rectangle - dc = wx.ScreenDC() - DrawResizeHint(dc, self._action_hintrect) - - # resize the dock or the pane - if self._action_part and self._action_part.type == DockUIPart.typeDockSizer: - rect = self._action_part.dock.rect - new_pos = wx.Point(event.GetX() - self._action_offset.x, - event.GetY() - self._action_offset.y) - - if self._action_part.dock.dock_direction == AUI_DOCK_LEFT: - self._action_part.dock.size = new_pos.x - rect.x - elif self._action_part.dock.dock_direction == AUI_DOCK_TOP: - self._action_part.dock.size = new_pos.y - rect.y - elif self._action_part.dock.dock_direction == AUI_DOCK_RIGHT: - self._action_part.dock.size = rect.x + rect.width - \ - new_pos.x - \ - self._action_part.rect.GetWidth() - elif self._action_part.dock.dock_direction == AUI_DOCK_BOTTOM: - self._action_part.dock.size = rect.y + rect.height - \ - new_pos.y - \ - self._action_part.rect.GetHeight() - - self.Update() - self.Repaint(None) - - elif self._action_part and \ - self._action_part.type == DockUIPart.typePaneSizer: - - dock = self._action_part.dock - pane = self._action_part.pane - - total_proportion = 0 - dock_pixels = 0 - new_pixsize = 0 - - caption_size = self._art.GetMetric(AUI_ART_CAPTION_SIZE) - pane_border_size = self._art.GetMetric(AUI_ART_PANE_BORDER_SIZE) - sash_size = self._art.GetMetric(AUI_ART_SASH_SIZE) - - new_pos = wx.Point(event.GetX() - self._action_offset.x, - event.GetY() - self._action_offset.y) - - # determine the pane rectangle by getting the pane part - pane_part = self.GetPanePart(pane.window) - if not pane_part: - raise "\nERROR: Pane border part not found -- shouldn't happen" - - # determine the new pixel size that the user wants - # this will help us recalculate the pane's proportion - if dock.IsHorizontal(): - new_pixsize = new_pos.x - pane_part.rect.x - else: - new_pixsize = new_pos.y - pane_part.rect.y - - # determine the size of the dock, based on orientation - if dock.IsHorizontal(): - dock_pixels = dock.rect.GetWidth() - else: - dock_pixels = dock.rect.GetHeight() - - # determine the total proportion of all resizable panes, - # and the total size of the dock minus the size of all - # the fixed panes - dock_pane_count = len(dock.panes) - pane_position = -1 - - for ii in xrange(dock_pane_count): - p = dock.panes[ii] - if p.window == pane.window: - pane_position = ii - - # while we're at it, subtract the pane sash - # width from the dock width, because this would - # skew our proportion calculations - if ii > 0: - dock_pixels = dock_pixels - sash_size - - # also, the whole size (including decorations) of - # all fixed panes must also be subtracted, because they - # are not part of the proportion calculation - if p.IsFixed(): - if dock.IsHorizontal(): - dock_pixels = dock_pixels - p.best_size.x - else: - dock_pixels = dock_pixels - p.best_size.y - else: - total_proportion = total_proportion + p.dock_proportion - - # find a pane in our dock to 'steal' space from or to 'give' - # space to -- this is essentially what is done when a pane is - # resized the pane should usually be the first non-fixed pane - # to the right of the action pane - borrow_pane = -1 - - for ii in xrange(pane_position+1, dock_pane_count): - p = dock.panes[ii] - if not p.IsFixed(): - borrow_pane = ii - break - - # demand that the pane being resized is found in this dock - # (this assert really never should be raised) - if pane_position == -1: - raise "\nERROR: Pane not found in dock" - - # prevent division by zero - if dock_pixels == 0 or total_proportion == 0 or borrow_pane == -1: - self._action = actionNone - return - - # calculate the new proportion of the pane - new_proportion = new_pixsize*total_proportion/dock_pixels - - # default minimum size - min_size = 0 - - # check against the pane's minimum size, if specified. please note - # that this is not enough to ensure that the minimum size will - # not be violated, because the whole frame might later be shrunk, - # causing the size of the pane to violate it's minimum size - if pane.min_size.IsFullySpecified(): - min_size = 0 - if pane.HasBorder(): - min_size = min_size + pane_border_size*2 - - # calculate minimum size with decorations (border,caption) - if pane_part.orientation == wx.VERTICAL: - min_size = min_size + pane.min_size.y - if pane.HasCaption(): - min_size = min_size + caption_size - else: - min_size = min_size + pane.min_size.x - - # for some reason, an arithmatic error somewhere is causing - # the proportion calculations to always be off by 1 pixel - # for now we will add the 1 pixel on, but we really should - # determine what's causing this. - min_size = min_size + 1 - - min_proportion = min_size*total_proportion/dock_pixels - - if new_proportion < min_proportion: - new_proportion = min_proportion - - prop_diff = new_proportion - pane.dock_proportion - - # borrow the space from our neighbor pane to the - # right or bottom (depending on orientation) - dock.panes[borrow_pane].dock_proportion -= prop_diff - pane.dock_proportion = new_proportion - - indxd = self._docks.index(dock) - indxp = self._panes.index(pane) - - self._docks[indxd] = dock - self._panes[indxp] = pane - - # repaint - self.Update() - self.Repaint(None) - - elif self._action == actionClickButton: - - self._hover_button = None - self._frame.ReleaseMouse() - self.UpdateButtonOnScreen(self._action_part, event) - - # make sure we're still over the item that was originally clicked - if self._action_part == self.HitTest(event.GetX(), event.GetY()): - # fire button-click event - e = AuiManagerEvent(wxEVT_AUI_PANEBUTTON) - e.SetPane(self._action_part.pane) - e.SetButton(self._action_part.button.button_id) - self.ProcessMgrEvent(e) - - elif self._action == actionClickCaption: - - self._frame.ReleaseMouse() - - elif self._action == actionDragAuiFloatingPane: - - self._frame.ReleaseMouse() - - elif self._action == actionDragToolbarPane: - - self._frame.ReleaseMouse() - - pane = self.GetPane(self._action_window) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - # save the new positions - docks = FindDocks(self._docks, pane.dock_direction, - pane.dock_layer, pane.dock_row) - - if len(docks) == 1: - dock = docks[0] - pane_positions, pane_sizes = self.GetPanePositionsAndSizes(dock) - - dock_pane_count = len(dock.panes) - for ii in xrange(dock_pane_count): - dock.panes[ii].dock_pos = pane_positions[ii] - - pane.state &= ~AuiPaneInfo.actionPane - indx = self._panes.index(pane) - self._panes[indx] = pane - - self.Update() - - else: - - event.Skip() - - self._action = actionNone - self._last_mouse_move = wx.Point() # see comment in OnMotion() - - - def OnMotion(self, event): - - # sometimes when Update() is called from inside this method, - # a spurious mouse move event is generated this check will make - # sure that only real mouse moves will get anywhere in this method - # this appears to be a bug somewhere, and I don't know where the - # mouse move event is being generated. only verified on MSW - - mouse_pos = event.GetPosition() - if self._last_mouse_move == mouse_pos: - return - - self._last_mouse_move = mouse_pos - - if self._action == actionResize: - pos = self._action_part.rect.GetPosition() - if self._action_part.orientation == wx.HORIZONTAL: - pos.y = max(0, mouse_pos.y - self._action_offset.y) - pos.y = min(pos.y, self._frame.GetClientSize().y - self._action_part.rect.GetSize().y) - else: - pos.x = max(0, mouse_pos.x - self._action_offset.x) - pos.x = min(pos.x, self._frame.GetClientSize().x - self._action_part.rect.GetSize().x) - - mypos = self._frame.ClientToScreen(pos) - mysize = self._action_part.rect.GetSize() - rect = wx.Rect(mypos[0], mypos[1], mysize[0], mysize[1]) - - # is it the same as the old rectangle? - if self._action_hintrect == rect: - # heck, yes, no need to draw again, it will only bring about flicker - event.Skip() - return - - # otherwise draw the hint - - dc = wx.ScreenDC() - - if not self._action_hintrect.IsEmpty() and self._action_hintrect != rect: - DrawResizeHint(dc, self._action_hintrect) - - DrawResizeHint(dc, rect) - self._action_hintrect = rect - - elif self._action == actionClickCaption: - - drag_x_threshold = wx.SystemSettings_GetMetric(wx.SYS_DRAG_X) - drag_y_threshold = wx.SystemSettings_GetMetric(wx.SYS_DRAG_Y) - - # caption has been clicked. we need to check if the mouse - # is now being dragged. if it is, we need to change the - # mouse action to 'drag' - if abs(mouse_pos.x - self._action_start.x) > drag_x_threshold or \ - abs(mouse_pos.y - self._action_start.y) > drag_y_threshold: - - pane_info = self._action_part.pane - indx = self._panes.index(pane_info) - - if not pane_info.IsToolbar(): - - if self._flags & AUI_MGR_ALLOW_FLOATING and \ - pane_info.IsFloatable(): - - self._action = actionDragAuiFloatingPane - - # set initial float position - pt = self._frame.ClientToScreen(event.GetPosition()) - pane_info.floating_pos = wx.Point(pt.x - self._action_offset.x, - pt.y - self._action_offset.y) - # float the window - pane_info.Float() - self._panes[indx] = pane_info - - self.Update() - - self._action_window = pane_info.frame - - # action offset is used here to make it feel "natural" to the user - # to drag a docked pane and suddenly have it become a floating frame. - # Sometimes, however, the offset where the user clicked on the docked - # caption is bigger than the width of the floating frame itself, so - # in that case we need to set the action offset to a sensible value - frame_size = self._action_window.GetSize() - if frame_size.x <= self._action_offset.x: - self._action_offset.x = 30 - - else: - - self._action = actionDragToolbarPane - self._action_window = pane_info.window - - elif self._action == actionDragAuiFloatingPane: - - pt = self._frame.ClientToScreen(event.GetPosition()) - if self._action_window: - self._action_window.Move((pt.x - self._action_offset.x, - pt.y - self._action_offset.y)) - - elif self._action == actionDragToolbarPane: - - pane = self.GetPane(self._action_window) - if not pane.IsOk(): - raise "\nERROR: Pane Window Not Found" - - indx = self._panes.index(pane) - pane.state |= AuiPaneInfo.actionPane - - pt = event.GetPosition() - ret, pane = self.DoDrop(self._docks, self._panes, pane, pt, self._action_offset) - - if not ret: - return - - # if DoDrop() decided to float the pane, set up - # the floating pane's initial position - if pane.IsFloating(): - - pt = self._frame.ClientToScreen(event.GetPosition()) - pane.floating_pos = wx.Point(pt.x - self._action_offset.x, - pt.y - self._action_offset.y) - - self._panes[indx] = pane - - # this will do the actiual move operation - # in the case that the pane has been floated, - # this call will create the floating pane - # and do the reparenting - self.Update() - - # if the pane has been floated, change the mouse - # action actionDragAuiFloatingPane so that subsequent - # EVT_MOTION() events will move the floating pane - if pane.IsFloating(): - - pane.state &= ~AuiPaneInfo.actionPane - self._action = actionDragAuiFloatingPane - self._action_window = pane.frame - - self._panes[indx] = pane - - else: - - part = self.HitTest(event.GetX(), event.GetY()) - if part and part.type == DockUIPart.typePaneButton: - if part != self._hover_button: - # make the old button normal - if self._hover_button: - self.UpdateButtonOnScreen(self._hover_button, event) - - # mouse is over a button, so repaint the - # button in hover mode - self.UpdateButtonOnScreen(part, event) - self._hover_button = part - else: - if self._hover_button: - - self._hover_button = None - self.Repaint() - - else: - - event.Skip() - - - def OnLeaveWindow(self, event): - - if self._hover_button: - self._hover_button = None - self.Repaint() - - - def OnChildFocus(self, event): - - # when a child pane has it's focus set, we should change the - # pane's active state to reflect this. (this is only true if - # active panes are allowed by the owner) - if self.GetFlags() & AUI_MGR_ALLOW_ACTIVE_PANE: - if self.GetPane(event.GetWindow()).IsOk(): - self._panes = SetActivePane(self._panes, event.GetWindow()) - self._frame.Refresh() - - event.Skip() - - - def OnPaneButton(self, event): - """ - OnPaneButton() is an event handler that is called - when a pane button has been pressed. - """ - - pane = event.pane - indx = self._panes.index(pane) - - if event.button == AuiPaneInfo.buttonClose: - e = AuiManagerEvent(wxEVT_AUI_PANECLOSE) - e.SetPane(pane) - self.ProcessMgrEvent(e) - - if e.GetSkipped(): - pane.Hide() - self._panes[indx] = pane - self.Update() - - elif event.button == AuiPaneInfo.buttonPin: - - if self._flags & AUI_MGR_ALLOW_FLOATING and pane.IsFloatable(): - pane.Float() - - self._panes[indx] = pane - self.Update()
--- a/orpg/tools/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,2 +1,2 @@ __all__ = ['inittool','inputValidatior', 'orpg_settings' , 'orpg_update', 'predTextCtrl', 'orpg_log', - 'rgbhex', 'scriptkit', 'server_probe', 'toolBars' ] + 'rgbhex', 'server_probe', 'toolBars' ]
--- a/orpg/tools/aliaslib.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,943 +0,0 @@ -# Copyright (C) 2000-2001 The OpenRPG Project -# -# openrpg-dev@lists.sourceforge.netfilter - -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -# -- -# -# File: aliaslib.py -# Author: Dj Gilcrease -# Maintainer: -# Version: -# $Id: aliaslib.py,v 1.20 2007/08/09 05:23:21 digitalxero Exp $ -# -# Description: nodehandler for alias. -# -from __future__ import with_statement - -from orpg.orpg_wx import * -from orpg.orpgCore import * -from orpg.ui.util.misc import create_masked_button -from orpg.ui.util.dlg import MultiCheckBoxDlg -from orpg.ui.toolbars import TextFormatToolBar -from orpg.tools.rgbhex import RGBHex -from orpg.tools.orpg_log import logger -from orpg.dirpath import dir_struct -from orpg.tools.validate import validate -from orpg.tools.settings import settings -from orpg.tools.decorators import debugging -import orpg.external.etree.ElementTree as ET - -class AliasLib(wx.Frame): - @debugging - def __init__(self): - self.orpgframe = open_rpg.get_component('frame') - wx.Frame.__init__(self, None, wx.ID_ANY, title="Alias Lib") - self.orpgframe.Freeze() - self.Freeze() - self.SetOwnBackgroundColour('#EFEFEF') - self.filename = settings.get('aliasfile') + '.alias' - - validate.config_file(self.filename, "default_alias.alias") - - self.buildMenu() - self.buildButtons() - self.buildGUI() - wx.CallAfter(self.InitSetup) - wx.CallAfter(self.loadFile) - self.Thaw() - self.orpgframe.Thaw() - self.Bind(wx.EVT_CLOSE, self.OnMB_FileExit) - - @debugging - def InitSetup(self): - self.chat = open_rpg.get_component('chat') - self.gametree = open_rpg.get_component('tree') - self.map = open_rpg.get_component('map') - self.session = open_rpg.get_component('session') - - @debugging - def buildMenu(self): - filemenu = wx.Menu() - item = wx.MenuItem(filemenu, wx.ID_ANY, "&New\tCtrl+N", "New ALias Lib") - self.Bind(wx.EVT_MENU, self.OnMB_FileNew, item) - filemenu.AppendItem(item) - item = wx.MenuItem(filemenu, wx.ID_ANY, "&Open\tCtrl+O", "Open Alias Lib") - self.Bind(wx.EVT_MENU, self.OnMB_FileOpen, item) - filemenu.AppendItem(item) - item = wx.MenuItem(filemenu, wx.ID_ANY, "&Save\tCtrl+S", "Save Alias Lib") - self.Bind(wx.EVT_MENU, self.OnMB_FileSave, item) - filemenu.AppendItem(item) - item = wx.MenuItem(filemenu, wx.ID_ANY, "&Export to Tree", "Export to Tree") - self.Bind(wx.EVT_MENU, self.OnMB_FileExportToTree, item) - filemenu.AppendItem(item) - item = wx.MenuItem(filemenu, wx.ID_ANY, "&Exit\tCtrl+X", "Exit") - self.Bind(wx.EVT_MENU, self.OnMB_FileExit, item) - filemenu.AppendItem(item) - aliasmenu = wx.Menu() - item = wx.MenuItem(aliasmenu, wx.ID_ANY, "New", "New") - self.Bind(wx.EVT_MENU, self.OnMB_AliasNew, item) - aliasmenu.AppendItem(item) - item = wx.MenuItem(aliasmenu, wx.ID_ANY, "Add Temporary", "Add Temporary") - self.Bind(wx.EVT_MENU, self.OnMB_AliasAddTemporary, item) - aliasmenu.AppendItem(item) - item = wx.MenuItem(aliasmenu, wx.ID_ANY, "Edit", "Edit") - self.Bind(wx.EVT_MENU, self.OnMB_AliasEdit, item) - aliasmenu.AppendItem(item) - item = wx.MenuItem(aliasmenu, wx.ID_ANY, "Delete", "Delete") - self.Bind(wx.EVT_MENU, self.OnMB_AliasDelete, item) - aliasmenu.AppendItem(item) - filtermenu = wx.Menu() - item = wx.MenuItem(filtermenu, wx.ID_ANY, "New", "New") - self.Bind(wx.EVT_MENU, self.OnMB_FilterNew, item) - filtermenu.AppendItem(item) - item = wx.MenuItem(filtermenu, wx.ID_ANY, "Edit", "Edit") - self.Bind(wx.EVT_MENU, self.OnMB_FilterEdit, item) - filtermenu.AppendItem(item) - item = wx.MenuItem(filtermenu, wx.ID_ANY, "Delete", "Delete") - self.Bind(wx.EVT_MENU, self.OnMB_FilterDelete, item) - filtermenu.AppendItem(item) - transmitmenu = wx.Menu() - item = wx.MenuItem(transmitmenu, wx.ID_ANY, "Send\tCtrl+Enter", "Send") - self.Bind(wx.EVT_MENU, self.OnMB_TransmitSend, item) - transmitmenu.AppendItem(item) - item = wx.MenuItem(transmitmenu, wx.ID_ANY, "Emote\tCtrl+E", "Emote") - self.Bind(wx.EVT_MENU, self.OnMB_TransmitEmote, item) - transmitmenu.AppendItem(item) - item = wx.MenuItem(transmitmenu, wx.ID_ANY, "Whisper\tCtrl+W", "Whisper") - self.Bind(wx.EVT_MENU, self.OnMB_TransmitWhisper, item) - transmitmenu.AppendItem(item) - menu = wx.MenuBar() - menu.Append(filemenu, "&File") - menu.Append(aliasmenu, "&Alias") - menu.Append(filtermenu, "&Filter") - menu.Append(transmitmenu, "&Transmit") - self.SetMenuBar(menu) - - @debugging - def OnMB_FileNew(self, event): - oldfilename = self.filename - dlg = wx.TextEntryDialog(self, "Please Name This Alias Lib", - "New Alias Lib") - if dlg.ShowModal() == wx.ID_OK: - self.filename = dlg.GetValue() + '.alias' - dlg.Destroy() - if oldfilename != self.filename: - self.OnMB_FileSave(None, oldfilename) - self.aliasList = [] - self.filterList = [] - self.OnMB_FileSave(None) - settings.set('aliasfile', self.filename[:-6]) - - @debugging - def OnMB_FileOpen(self, event): - oldfilename = self.filename - dlg = wx.FileDialog(self, "Select an Alias Lib to Open", - dir_struct["user"], wildcard="*.alias", - style=wx.HIDE_READONLY|wx.OPEN) - if dlg.ShowModal() == wx.ID_OK: - self.filename = dlg.GetFilename() - - dlg.Destroy() - - if oldfilename != self.filename: - self.OnMB_FileSave(None, oldfilename) - self.loadFile() - - settings.set('aliasfile', self.filename[:-6]) - - @debugging - def OnMB_FileSave(self, event, file=None): - idx = self.aliasIdx - if file == None: - file = self.filename - xml = "<aliaslib>\n" - for n in xrange(self.selectAliasWnd.GetItemCount()): - self.alias = n - xml += "\t<alias " - xml += 'name="' + self.MakeHTMLSafe(self.alias[0]) + '" ' - xml += 'color="' + self.alias[1] + '" ' - xml += "/>\n" - - for n in xrange(1, len(self.filterList)): - xml += "\t<filter " - xml += 'name="' + self.filterList[n] + '">' + "\n" - for rule in self.regExList[n-1]: - xml += "\t\t<rule " - xml += 'match="' + self.MakeHTMLSafe(rule[0]) + '" ' - xml += 'sub="' + self.MakeHTMLSafe(rule[1]) + '" ' - xml += "/>\n" - xml += "\t</filter>\n" - - xml += "</aliaslib>" - self.alias = idx - with open(dir_struct["user"] + file, "w") as f: - f.write(xml) - - @debugging - def OnMB_FileExportToTree(self, event): - #tree = open_rpg.get_component("tree") - xml = '<nodehandler class="voxchat_handler" icon="player"' - xml += ' module="voxchat" name="' + self.filename[:-6] - xml += '" use.filter="0" version="1.0">' + "\n" - idx = self.aliasIdx - for n in xrange(self.selectAliasWnd.GetItemCount()): - self.alias = n - xml += "\t<voxchat.alias " - xml += 'name="' + self.MakeHTMLSafe(self.alias[0]) + '" ' - xml += 'color="' + self.alias[1] + '" ' - xml += "/>\n" - self.alias = idx - for n in xrange(1, len(self.filterList)): - xml += "\t<voxchat.filter " - xml += 'name="' + self.filterList[n] + '">' + "\n" - for rule in self.regExList[n-1]: - xml += "\t\t<rule " - xml += 'match="' + self.MakeHTMLSafe(rule[0]) + '" ' - xml += 'sub="' + self.MakeHTMLSafe(rule[1]) + '" ' - xml += "/>\n" - xml += "\t</voxchat.filter>\n" - xml += "</nodehandler>" - self.gametree.insert_xml(xml) - - @debugging - def OnMB_FileExit(self, event): - self.OnMB_FileSave(0) - self.Hide() - self.orpgframe.mainmenu.Check( - self.orpgframe.mainmenu.FindMenuItem("Windows", "Alias Lib"), - False) - - @debugging - def OnMB_AliasNew(self, event): - self.NewEditAliasDialog("New") - - @debugging - def OnMB_AliasAddTemporary(self, event): - minis = self.map.canvas.layers['miniatures'].miniatures - for min in minis: - name = min.label - if name not in self.aliasList: - i = self.selectAliasWnd.InsertStringItem(self.selectAliasWnd.GetItemCount(), name) - self.selectAliasWnd.SetStringItem(i, 1, "Default") - self.selectAliasWnd.RefreshItem(i) - self.RefreshAliases() - - @debugging - def OnMB_AliasEdit(self, event): - if self.aliasIdx != -1: - self.NewEditAliasDialog("Edit") - - @debugging - def NewEditAliasDialog(self, type): - dlg = wx.Dialog(self, wx.ID_ANY, type + " Alias", - style=wx.DEFAULT_DIALOG_STYLE|wx.STAY_ON_TOP) - txt = wx.TextCtrl(dlg, wx.ID_ANY) - if type == 'Edit': - txt.SetValue(self.alias[0]) - self.colorbtn = wx.Button(dlg, wx.ID_ANY, "Default Color") - dlg.Bind(wx.EVT_BUTTON, self.ChangeAliasColor, self.colorbtn) - if self.alias[1] != 'Default': - self.colorbtn.SetLabel("Chat Color") - self.colorbtn.SetForegroundColour(self.alias[1]) - okbtn = wx.Button(dlg, wx.ID_OK) - sizer = wx.BoxSizer(wx.HORIZONTAL) - sizer.Add(wx.StaticText(dlg, wx.ID_ANY, "Alias: "), 0, wx.EXPAND) - sizer.Add(txt, 1, wx.EXPAND) - sizer.Add(self.colorbtn, 0, wx.EXPAND) - sizer.Add(okbtn, 0, wx.EXPAND) - dlg.SetSizer(sizer) - dlg.SetAutoLayout(True) - dlg.Fit() - if dlg.ShowModal() == wx.ID_OK: - (r, g, b) = self.colorbtn.GetForegroundColour().Get() - if type == 'Edit': - self.selectAliasWnd.SetStringItem(self.aliasIdx, 0, txt.GetValue()) - if self.colorbtn.GetLabel() != 'Default Color': - self.aliasColor = RGBHex().hexstring(r, g, b) - self.selectAliasWnd.RefreshItem(self.aliasIdx) - else: - i = self.selectAliasWnd.InsertStringItem(self.selectAliasWnd.GetItemCount(), txt.GetValue()) - if self.colorbtn.GetLabel() == 'Default Color': - self.selectAliasWnd.SetStringItem(i, 1, "Default") - else: - self.selectAliasWnd.SetStringItem(i, 1, RGBHex().hexstring(r, g, b)) - self.selectAliasWnd.SetItemTextColour(i, RGBHex().hexstring(r, g, b)) - self.selectAliasWnd.RefreshItem(i) - self.RefreshAliases() - - @debugging - def ChangeAliasColor(self, event): - color = RGBHex().do_hex_color_dlg(self) - self.colorbtn.SetLabel("Chat Color") - self.colorbtn.SetForegroundColour(color) - - @debugging - def OnMB_AliasDelete(self, event): - if self.aliasIdx != -1: - self.selectAliasWnd.DeleteItem(self.aliasIdx) - self.RefreshAliases() - - @debugging - def OnMB_FilterNew(self, event): - dlg = wx.TextEntryDialog(self, 'Filter Name: ', - 'Please name this filter') - if dlg.ShowModal() != wx.ID_OK: - dlg.Destroy() - return - filterName = dlg.GetValue() - i = self.selectFilterWnd.InsertStringItem(self.selectFilterWnd.GetItemCount(), filterName) - self.filter = i - self.regExList.append([]) - self.OnMB_FilterEdit(None) - - @debugging - def OnMB_FilterEdit(self, event): - wnd = FilterEditWnd(self, self.filter, self.filterRegEx) - wnd.MakeModal(True) - wnd.Show() - - @debugging - def OnMB_FilterDelete(self, event): - dlg = wx.MessageDialog(self, "Are you sure you want to delete that filter?","Delete Filter",wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) - if dlg.ShowModal() != wx.ID_YES: - return - if self.filterIdx != -1: - self.selectFilterWnd.DeleteItem(self.filterIdx) - - @debugging - def OnMB_TransmitSend(self, event): - self.orpgframe.Freeze() - if self.alias[1] != 'Default': - defaultcolor = settings.get("mytextcolor") - settings.set("mytextcolor", self.alias[1]) - self.chat.set_colors() - line = self.textWnd.GetValue() - alias = self.alias[0] - if alias == self.chat.defaultAliasName: - alias = self.chat.session.get_my_info()[0] - self.chat.ParsePost(line, True, True, ParserContext(alias)) - if self.alias[1] != 'Default': - settings.set("mytextcolor", defaultcolor) - self.chat.set_colors() - if self.checkClearText.IsChecked(): - self.textWnd.SetValue("") - self.orpgframe.Thaw() - - @debugging - def OnMB_TransmitEmote(self, event): - self.orpgframe.Freeze() - line = self.textWnd.GetValue() - alias = self.alias[0] - if alias == self.chat.defaultAliasName: - alias = self.chat.session.get_my_info()[0] - self.chat.emote_message(line, ParserContext(alias)) - if self.checkClearText.IsChecked(): - self.textWnd.SetValue("") - self.orpgframe.Thaw() - - @debugging - def OnMB_TransmitWhisper(self, event): - self.orpgframe.Freeze() - players = self.session.get_players() - if self.alias[1] != 'Default': - defaultcolor = settings.get("mytextcolor") - settings.set("mytextcolor", self.alias[1]) - self.chat.set_colors() - opts = [] - myid = session.get_id() - for p in players: - if p[2] != myid: - opts.append("(" + p[2] + ") " + self.chat.html_strip(p[0])) - dlg = orpgMultiCheckBoxDlg(self, opts, "Select Players:", "Whisper To", []) - sendto = [] - if dlg.ShowModal() == wx.ID_OK: - selections = dlg.get_selections() - for s in selections: - sendto.append(players[s][2]) - line = self.textWnd.GetValue() - if len(sendto): - alias = self.alias[0] - if alias == self.chat.defaultAliasName: - alias = self.chat.session.get_my_info()[0] - self.chat.whisper_to_players(line, sendto, ParserContext(alias)) - if self.alias[1] != 'Default': - settings.set("mytextcolor", defaultcolor) - self.chat.set_colors() - if self.checkClearText.IsChecked(): - self.textWnd.SetValue("") - self.orpgframe.Thaw() - - @debugging - def buildButtons(self): - self.topBtnSizer = wx.BoxSizer(wx.HORIZONTAL) - self.middleBtnSizer = wx.BoxSizer(wx.HORIZONTAL) - self.bottomBtnSizer = wx.BoxSizer(wx.HORIZONTAL) - self.addFromMapBtn = create_masked_button(self, - dir_struct["icon"] + 'install.gif', - 'Add temporary aliases from map', - wx.ID_ANY, "#C0C0C0") - self.newAliasBtn = create_masked_button(self, - dir_struct["icon"] + 'player.gif', - 'Add a new Alias', wx.ID_ANY) - self.delAliasBtn = create_masked_button(self, - dir_struct["icon"] + 'noplayer.gif', - 'Delete selected Alias', wx.ID_ANY) - self.editAliasBtn = create_masked_button(self, - dir_struct["icon"] + 'note.gif', - 'Edit selected Alias', wx.ID_ANY) - self.Bind(wx.EVT_BUTTON, self.OnMB_AliasNew, self.newAliasBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_AliasAddTemporary, self.addFromMapBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_AliasEdit, self.editAliasBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_AliasDelete, self.delAliasBtn) - - self.newFilterBtn = create_masked_button(self, - dir_struct["icon"] + 'add_filter.gif', - 'Add a new Filter', wx.ID_ANY, - "#0000FF") - self.editFilterBtn = create_masked_button(self, - dir_struct["icon"] + 'edit_filter.gif', - 'Edit selected Filter', wx.ID_ANY, - "#FF0000") - self.delFilterBtn = create_masked_button(self, - dir_struct["icon"] + 'delete_filter.gif', - 'Delete selected Filter', wx.ID_ANY, - "#0000FF") - self.Bind(wx.EVT_BUTTON, self.OnMB_FilterNew, self.newFilterBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_FilterEdit, self.editFilterBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_FilterDelete, self.delFilterBtn) - - self.format_bar = TextFormatToolBar(self, self.textWnd) - - self.exportBtn = create_masked_button(self, - dir_struct["icon"] + 'grid.gif', - 'Export to Tree', wx.ID_ANY) - self.Bind(wx.EVT_BUTTON, self.OnMB_FileExportToTree, self.exportBtn) - - self.topBtnSizer.Add(self.newAliasBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.addFromMapBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.editAliasBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.delAliasBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.newFilterBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.editFilterBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.delFilterBtn, 0, wx.EXPAND) - self.topBtnSizer.Add(self.format_bar, 0, wx.EXPAND) - self.topBtnSizer.Add(self.exportBtn, 0, wx.EXPAND|wx.ALIGN_RIGHT) - self.checkFilterText = wx.CheckBox(self, wx.ID_ANY, "Filter Text") - self.Bind(wx.EVT_CHECKBOX, self.FilterTextChecked, - self.checkFilterText) - self.checkClearText = wx.CheckBox(self, wx.ID_ANY, "Auto Clear Text") - self.middleBtnSizer.Add(self.checkFilterText, 0, wx.EXPAND) - self.middleBtnSizer.Add(self.checkClearText, 0, wx.EXPAND) - self.sayBtn = wx.Button(self, wx.ID_ANY, "Say") - self.emoteBtn = wx.Button(self, wx.ID_ANY, "Emote") - self.whisperBtn = wx.Button(self, wx.ID_ANY, "Whisper") - self.doneBtn = wx.Button(self, wx.ID_ANY, "Done") - self.Bind(wx.EVT_BUTTON, self.OnMB_TransmitSend, self.sayBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_TransmitEmote, self.emoteBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_TransmitWhisper, self.whisperBtn) - self.Bind(wx.EVT_BUTTON, self.OnMB_FileExit, self.doneBtn) - self.bottomBtnSizer.Add(self.sayBtn, 0, wx.EXPAND) - self.bottomBtnSizer.Add(self.emoteBtn, 0, wx.EXPAND) - self.bottomBtnSizer.Add(self.whisperBtn, 0, wx.EXPAND) - self.bottomBtnSizer.Add(self.doneBtn, 0, wx.EXPAND|wx.ALIGN_RIGHT) - - @debugging - def buildGUI(self): - self.sizer = wx.BoxSizer(wx.VERTICAL) - rightwnd = wx.SplitterWindow(self, wx.ID_ANY, - style=wx.SP_LIVE_UPDATE|wx.SP_NO_XP_THEME|wx.SP_3DSASH) - leftwnd = wx.SplitterWindow(rightwnd, wx.ID_ANY, - style=wx.SP_LIVE_UPDATE|wx.SP_NO_XP_THEME|wx.SP_3DSASH) - self.selectAliasWnd = wx.ListCtrl(leftwnd, wx.ID_ANY, - style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES) - self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.NewAliasSelection, - self.selectAliasWnd) - self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.NoAliasSelection, - self.selectAliasWnd) - self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnMB_AliasEdit, - self.selectAliasWnd) - self.selectFilterWnd = wx.ListCtrl(leftwnd, wx.ID_ANY, - style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES) - self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.NewFilterSelection, - self.selectFilterWnd) - self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.NoFilterSelection, - self.selectFilterWnd) - self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnMB_FilterEdit, - self.selectFilterWnd) - self.textWnd = wx.TextCtrl(rightwnd, wx.ID_ANY, - style=wx.TE_MULTILINE|wx.TE_BESTWRAP) - leftwnd.SplitHorizontally(self.selectAliasWnd, - self.selectFilterWnd) - rightwnd.SplitVertically(leftwnd, self.textWnd) - self.sizer.Add(self.topBtnSizer, 0, wx.EXPAND) - self.sizer.Add(rightwnd, 1, wx.EXPAND) - self.sizer.Add(self.middleBtnSizer, 0, wx.EXPAND) - self.sizer.Add(self.bottomBtnSizer, 0, wx.EXPAND) - self.SetSizer(self.sizer) - self.SetAutoLayout(True) - self.Fit() - - @debugging - def loadFile(self): - xml = ET.parse(dir_struct["user"] + self.filename).getroot() - self.alias = -1 - self.filter = -1 - alist = [] - for alias in xml.findall('alias'): - if 'color' in alias.attrib: - color = alias.get("color") - else: - color = 'Default' - aname = self.MakeSafeHTML(alias.get("name", '')) - alist.append([aname, color]) - alist.sort() - self.aliasList = alist - flist = [] - self.regExList = [] - for filter in xml.findall('filter'): - flist.append(filter.get("name")) - sub = [] - for rule in filter.findall("rule"): - sub.append([self.MakeSafeHTML(rule.get("match", '')), - self.MakeSafeHTML(rule.get("sub", ''))]) - self.regExList.append(sub) - self.filterList = flist - self.alias = -1 - self.filter = -1 - - @debugging - def MakeSafeHTML(self, str): - return str.replace("&", "&").replace("<", "<").\ - replace(""", '"').replace(">", ">").\ - replace("'", "'") - - @debugging - def MakeHTMLSafe(self, str): - return str.replace("&", "&").replace("<", "<").\ - replace('"', """).replace(">", ">").\ - replace("'", "'") - - @debugging - def ImportFromTree(self, xml): - - oldfilename = self.filename - if xml.get('name') == 'Alias Library': - dlg = wx.TextEntryDialog(self, "Please Name This Alias Lib", - "New Alias Lib") - if dlg.ShowModal() == wx.ID_OK: - self.filename = dlg.GetValue() + '.alias' - dlg.Destroy() - else: - dlg.Destroy() - return - else: - self.filename = xml.get('name') + '.alias' - settings.set('aliasfile', self.filename[:-6]) - if oldfilename != self.filename: - self.OnMB_FileSave(None, oldfilename) - with open(dir_struct["user"] + self.filename, "w") as f: - f.write(ET.tostring(xml).replace('nodehandler', - 'aliaslib').replace('voxchat.', '')) - - wx.CallAfter(self.loadFile) - - @debugging - def NewAliasSelection(self, event): - self.alias = event.GetIndex() - wx.CallAfter(self.chat.aliasList.SetStringSelection, self.alias[0]) - - @debugging - def NoAliasSelection(self, event): - self.aliasIdx = -1 - wx.CallAfter(self.chat.aliasList.SetStringSelection, self.alias[0]) - - @debugging - def GetSelectedAlias(self): - self.InitSetup() - if self.aliasIdx != -1: - return [self.selectAliasWnd.GetItem(self.aliasIdx, 0).GetText(), - self.selectAliasWnd.GetItem(self.aliasIdx, 1).GetText()] - return [self.chat.alias_bar.default_alias, "Default"] - - @debugging - def SetSelectedAlias(self, alias): - found = False - if isinstance(alias, (int, long)): - self.aliasIdx = alias - found = True - else: - for n in xrange(self.selectAliasWnd.GetItemCount()): - if self.selectAliasWnd.GetItem(n, 0).GetText() == alias: - self.aliasIdx = n - found = True - if not found: - self.aliasIdx = -1 - - @debugging - def GetAliasList(self): - alist = [] - for n in xrange(0, self.selectAliasWnd.GetItemCount()): - self.alias = n - alist.append(self.alias[0]) - alist.sort() - alist.insert(0, self.chat.defaultAliasName) - return alist - - @debugging - def SetAliasList(self, alist): - self.selectAliasWnd.ClearAll() - self.selectAliasWnd.InsertColumn(0, "Alias") - self.selectAliasWnd.InsertColumn(1, "Chat Color") - for item in alist: - i = self.selectAliasWnd.InsertStringItem(self.selectAliasWnd.GetItemCount(), item[0]) - self.selectAliasWnd.SetStringItem(i, 1, item[1]) - if item[1] != 'Default': - self.selectAliasWnd.SetItemTextColour(i, item[1]) - self.selectAliasWnd.RefreshItem(i) - self.aliasIdx = -1 - self.RefreshAliases() - - @debugging - def GetAliasColor(self): - return self.alias[1] - - @debugging - def RefreshAliases(self): - self.orpgframe.Freeze() - self.Freeze() - self.alias = -1 - l1 = len(self.aliasList) - l2 = len(self.filterList) - if self.chat != None: - tmp = self.chat.alias_bar.alias - self.alias = tmp - aidx = self.aliasIdx+1 - if len(self.aliasList) <= aidx: - aidx = 0 - self.chat.aliasList.Clear() - for n in xrange(l1): - self.chat.alias_bar._alias_list.Insert(self.aliasList[n], n) - self.chat.aliasList.SetStringSelection(self.aliasList[aidx]) - fidx = self.chat.filterList.GetSelection() - if len(self.filterList) <= fidx: - fidx = 0 - self.chat.filterList.Clear() - for n in xrange(l2): - self.chat.filterList.Insert(self.filterList[n], n) - self.chat.filterList.SetStringSelection(self.filterList[fidx]) - if self.chat.parent.GMChatPanel != None: - aidx = self.chat.parent.GMChatPanel.aliasList.GetSelection() - if len(self.aliasList) <- aidx: - aidx = 0 - self.chat.parent.GMChatPanel.aliasList.Clear() - for n in xrange(l1): - self.chat.parent.GMChatPanel.aliasList.Insert(self.aliasList[n], n) - self.chat.parent.GMChatPanel.aliasList.SetStringSelection(self.aliasList[aidx]) - fidx = self.chat.parent.GMChatPanel.filterList.GetSelection() - self.chat.parent.GMChatPanel.filterList.Clear() - for n in xrange(l2): - self.chat.parent.GMChatPanel.filterList.Insert(self.filterList[n], n) - self.chat.parent.GMChatPanel.filterList.SetStringSelection(self.filterList[fidx]) - for tab in self.chat.parent.whisper_tabs: - aidx = tab.aliasList.GetSelection() - if len(self.aliasList) <= aidx: - aidx = 0 - tab.aliasList.Clear() - for n in xrange(l1): - tab.aliasList.Insert(self.aliasList[n], n) - tab.aliasList.SetStringSelection(self.aliasList[aidx]) - fidx = tab.filterList.GetSelection() - tab.filterList.Clear() - for n in xrange(l2): - tab.filterList.Insert(self.filterList[n], n) - tab.filterList.SetStringSelection(self.filterList[fidx]) - - for tab in self.chat.parent.group_tabs: - aidx = tab.aliasList.GetSelection() - if len(self.aliasList) <= aidx: - aidx = 0 - tab.aliasList.Clear() - for n in xrange(l1): - tab.aliasList.Insert(self.aliasList[n], n) - tab.aliasList.SetStringSelection(self.aliasList[aidx]) - fidx = tab.filterList.GetSelection() - tab.filterList.Clear() - for n in xrange(l2): - tab.filterList.Insert(self.filterList[n], n) - tab.filterList.SetStringSelection(self.filterList[fidx]) - - for tab in self.chat.parent.null_tabs: - aidx = tab.aliasList.GetSelection() - if len(self.aliasList) <= aidx: - aidx = 0 - tab.aliasList.Clear() - for n in xrange(l1): - tab.aliasList.Insert(self.aliasList[n], n) - tab.aliasList.SetStringSelection(self.aliasList[aidx]) - fidx = tab.filterList.GetSelection() - tab.filterList.Clear() - for n in xrange(l2): - tab.filterList.Insert(self.filterList[n], n) - tab.filterList.SetStringSelection(self.filterList[fidx]) - self.Thaw() - wx.CallAfter(self.orpgframe.Thaw) - - @debugging - def SetAliasColor(self, color): - if self.aliasIdx != -1: - self.selectAliasWnd.SetStringItem(self.aliasIdx, 1, color) - self.selectAliasWnd.SetItemTextColour(self.aliasIdx, color) - - @debugging - def FilterTextChecked(self, event): - if self.checkFilterText.IsChecked(): - self.chat.filterList.SetStringSelection(self.filter) - else: - self.chat.filterList.SetStringSelection(self.chat.defaultFilterName) - - @debugging - def NewFilterSelection(self, event): - self.filter = event.GetIndex() - if self.checkFilterText.IsChecked(): - wx.CallAfter(self.chat.filterList.SetStringSelection, self.filter) - - @debugging - def NoFilterSelection(self, event): - self.filter = -1 - wx.CallAfter(self.chat.filterList.SetStringSelection, self.filter) - - @debugging - def GetSelectedFilter(self): - if self.filterIdx != -1: - return self.selectFilterWnd.GetItem(self.filterIdx, 0).GetText() - - return self.chat.defaultFilterName - - @debugging - def SetSelectedFilter(self, idx): - self.filterIdx = idx - - @debugging - def GetFilterList(self): - list = [] - for n in xrange(-1, self.selectFilterWnd.GetItemCount()): - self.filter = n - list.append(self.filter) - return list - - @debugging - def SetFilterList(self, list): - self.selectFilterWnd.ClearAll() - self.selectFilterWnd.InsertColumn(0, "Filter Name") - for item in list: - i = self.selectFilterWnd.InsertStringItem(self.selectFilterWnd.GetItemCount(), item) - self.selectFilterWnd.RefreshItem(i) - self.selectFilterWnd.SetColumnWidth(0, wx.LIST_AUTOSIZE) - self.filter = -1 - self.RefreshAliases() - - @debugging - def GetFilterRegEx(self): - if self.filterIdx == -1: - return [] - return self.regExList[self.filterIdx] - - @debugging - def SetFilterRegEx(self, list): - self.regExList[self.filterIdx] = list - - @debugging - def FormatText(self, event): - id = event.GetId() - txt = self.textWnd.GetValue() - (beg, end) = self.textWnd.GetSelection() - if beg != end: - sel_txt = txt[beg:end] - else: - sel_txt = txt - if id == self.textBoldBtn.GetId(): - sel_txt = "<b>" + sel_txt + "</b>" - elif id == self.textItalicBtn.GetId(): - sel_txt = "<i>" + sel_txt + "</i>" - elif id == self.textUnderlineBtn.GetId(): - sel_txt = "<u>" + sel_txt + "</u>" - elif id == self.textColorBtn.GetId(): - dlg = wx.ColourDialog(self) - if not dlg.ShowModal() == wx.ID_OK: - dlg.Destroy() - return - color = dlg.GetColourData().GetColour() - color = RGBHex().hexstring(color[0], color[1], color[2]) - dlg.Destroy() - sel_txt = '<font color="' + color + '">' + sel_txt + '</font>' - if beg != end: - txt = txt[:beg] + sel_txt + txt[end:] - else: - txt = sel_txt - self.textWnd.SetValue(txt) - self.textWnd.SetInsertionPointEnd() - self.textWnd.SetFocus() - - #Properties - alias = property(GetSelectedAlias, SetSelectedAlias) - aliasList = property(GetAliasList, SetAliasList) - aliasColor = property(GetAliasColor, SetAliasColor) - - filter = property(GetSelectedFilter, SetSelectedFilter) - filterList = property(GetFilterList, SetFilterList) - filterRegEx = property(GetFilterRegEx, SetFilterRegEx) - - - -class FilterEditWnd(wx.Frame): - @debugging - def __init__(self, parent, filterName, filterList): - wx.Frame.__init__(self, parent, wx.ID_ANY, "Edit Filter: " + filterName) - - self.filterList = filterList - self.parent = parent - - self.Freeze() - self.buildGUI() - self.fillList() - self.Layout() - self.grid.Select(0) - self.Thaw() - - self.Bind(wx.EVT_CLOSE, self.OnExit) - - @debugging - def buildGUI(self): - bsizer = wx.BoxSizer(wx.VERTICAL) - self.panel = wx.Panel(self, wx.ID_ANY) - bsizer.Add(self.panel, 1, wx.EXPAND) - self.SetSizer(bsizer) - self.SetAutoLayout(True) - - self.grid = wx.ListCtrl(self.panel, wx.ID_ANY, style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES) - self.grid.InsertColumn(0, "Replace") - self.grid.InsertColumn(1, "With") - self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.selectRule, self.grid) - self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.RuleEdit, self.grid) - - self.addBtn = wx.Button(self.panel, wx.ID_ANY, 'Add') - self.editBtn = wx.Button(self.panel, wx.ID_ANY, 'Edit') - self.deleteBtn = wx.Button(self.panel, wx.ID_ANY, 'Delete') - self.okBtn = wx.Button(self.panel, wx.ID_OK, 'Done') - - self.Bind(wx.EVT_BUTTON, self.RuleAdd, self.addBtn) - self.Bind(wx.EVT_BUTTON, self.RuleEdit, self.editBtn) - self.Bind(wx.EVT_BUTTON, self.RuleDelete, self.deleteBtn) - self.Bind(wx.EVT_BUTTON, self.OnDone, self.okBtn) - - btsizer = wx.BoxSizer(wx.VERTICAL) - btsizer.Add(self.addBtn, 0, wx.EXPAND) - btsizer.Add(self.editBtn, 0, wx.EXPAND) - btsizer.Add(self.deleteBtn, 0, wx.EXPAND) - btsizer.Add(self.okBtn, 0, wx.EXPAND) - - sizer = wx.GridBagSizer(5,5) - - sizer.Add(self.grid, (0,0), flag=wx.EXPAND) - sizer.Add(btsizer, (0,1), flag=wx.EXPAND) - - sizer.AddGrowableCol(0) - sizer.AddGrowableRow(0) - sizer.SetEmptyCellSize((0,0)) - - self.panel.SetSizer(sizer) - self.panel.SetAutoLayout(True) - - @debugging - def fillList(self): - for rule in self.filterList: - i = self.grid.InsertStringItem(self.grid.GetItemCount(), rule[0]) - self.grid.SetStringItem(i, 1, rule[1]) - - self.grid.SetColumnWidth(0, wx.LIST_AUTOSIZE) - self.grid.SetColumnWidth(1, wx.LIST_AUTOSIZE) - - @debugging - def selectRule(self, event): - self.currentIdx = event.GetIndex() - self.Freeze() - for i in xrange(0, self.grid.GetItemCount()): - self.grid.SetItemBackgroundColour(i, (255,255,255)) - - self.grid.SetItemBackgroundColour(self.currentIdx, (0,255,0)) - self.grid.SetItemState(self.currentIdx, 0, wx.LIST_STATE_SELECTED) - self.grid.EnsureVisible(self.currentIdx) - self.Thaw() - - @debugging - def RuleEdit(self, event): - dlg = wx.Dialog(self, wx.ID_ANY, 'Edit Filter Rule') - sizer = wx.BoxSizer(wx.HORIZONTAL) - sizer.Add(wx.StaticText(dlg, wx.ID_ANY, 'Replace: '), 0, wx.EXPAND) - rpltxt = wx.TextCtrl(dlg, wx.ID_ANY) - sizer.Add(rpltxt, 0, wx.EXPAND) - sizer.Add(wx.StaticText(dlg, wx.ID_ANY, 'With: '), 0, wx.EXPAND) - withtxt = wx.TextCtrl(dlg, wx.ID_ANY) - sizer.Add(withtxt, 0, wx.EXPAND) - sizer.Add(wx.Button(dlg, wx.ID_OK, 'Ok'), 0, wx.EXPAND) - sizer.Add(wx.Button(dlg, wx.ID_CANCEL, 'Cancel'), 0, wx.EXPAND) - - dlg.SetSizer(sizer) - dlg.SetAutoLayout(True) - dlg.Fit() - - rpltxt.SetValue(self.grid.GetItem(self.currentIdx, 0).GetText()) - withtxt.SetValue(self.grid.GetItem(self.currentIdx, 1).GetText()) - - if dlg.ShowModal() != wx.ID_OK: - dlg.Destroy() - return - - self.grid.SetStringItem(self.currentIdx, 0, rpltxt.GetValue()) - self.grid.SetStringItem(self.currentIdx, 1, withtxt.GetValue()) - self.grid.RefreshItem(self.currentIdx) - self.grid.SetColumnWidth(0, wx.LIST_AUTOSIZE) - self.grid.SetColumnWidth(1, wx.LIST_AUTOSIZE) - - dlg.Destroy() - - @debugging - def RuleAdd(self, event): - i = self.grid.InsertStringItem(self.grid.GetItemCount(), '') - self.grid.SetStringItem(i, 1, '') - self.grid.Select(i) - self.RuleEdit(None) - - @debugging - def RuleDelete(self, event): - self.grid.DeleteItem(self.currentIdx) - self.grid.Select(0) - - @debugging - def OnExit(self, event): - self.MakeModal(False) - - list = [] - for i in xrange(0, self.grid.GetItemCount()): - list.append([self.grid.GetItem(i, 0).GetText(), self.grid.GetItem(i, 1).GetText()]) - - self.parent.filterRegEx = list - event.Skip() - - @debugging - def OnDone(self, event): - self.Close()
--- a/orpg/tools/inputValidator.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/inputValidator.py Thu Mar 25 17:56:48 2010 -0600 @@ -24,52 +24,36 @@ # Description: Contains simple input validators to help reduce the amount of # user input generated text. # - -__version__ = "$Id: inputValidator.py,v 1.11 2006/11/04 21:24:22 digitalxero Exp $" - +from string import ascii_letters, digits -## -## Module Loading -## -from orpg.orpg_wx import * -import string +import wx - -## -## Text Only input (no numbers allowed) -## class TextOnlyValidator(wx.PyValidator): def __init__( self ): wx.PyValidator.__init__( self ) self.Bind(wx.EVT_CHAR, self.onChar) - - def Clone( self ): return TextOnlyValidator() - - def Validate( self, win ): tc = self.GetWindow() val = tc.GetValue() retVal = True for x in val: - if x not in string.letters: + if x not in ascii_letters: retVal = False break return retVal - - def onChar( self, event ): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip() - elif chr(key) in string.letters: + elif chr(key) in ascii_letters: event.Skip() else: @@ -80,8 +64,6 @@ # gets to the text control return - - ## ## Number Only input (no text allowed) ## @@ -90,33 +72,27 @@ wx.PyValidator.__init__( self ) self.Bind(wx.EVT_CHAR, self.onChar) - - def Clone( self ): return NumberOnlyValidator() - - def Validate( self, win ): tc = self.GetWindow() val = tc.GetValue() retVal = True for x in val: - if x not in string.digits: + if x not in digits: retVal = False break return retVal - - def onChar( self, event ): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: event.Skip() - elif chr(key) in string.digits: + elif chr(key) in digits: event.Skip() else: @@ -128,10 +104,6 @@ return - - - - ## ## Math Only input (no text allowed, only numbers of math symbols) ## @@ -143,13 +115,9 @@ self.allowedInput = "0123456789()*/+-<>" self.Bind(wx.EVT_CHAR, self.onChar) - - def Clone( self ): return MathOnlyValidator() - - def Validate( self, win ): tc = self.GetWindow() val = tc.GetValue() @@ -162,8 +130,6 @@ return retVal - - def onChar( self, event ): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: @@ -181,10 +147,6 @@ return - - - - ## ## Text and number input but DO NOT allow ANY HTML type input (no numbers allowed) ## @@ -196,13 +158,9 @@ self.allowedInput = " 1234567890!@#$%^&*()_-+=`~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,[]{}|;:'\",./?\\" self.Bind(wx.EVT_CHAR, self.onChar) - - def Clone( self ): return NoHTMLValidator() - - def Validate( self, win ): tc = self.GetWindow() val = tc.GetValue() @@ -215,8 +173,6 @@ return retVal - - def onChar( self, event ): key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255:
--- a/orpg/tools/metamenus.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,5 +0,0 @@ -import warnings -warnings.warn("The new way to access this is orpg.external.metamenus", - category=PendingDeprecationWarning) - -from orpg.external.metamenus import * \ No newline at end of file
--- a/orpg/tools/orpg_settings.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,313 +0,0 @@ -# Copyright (C) 2000-2001 The OpenRPG Project -# -# openrpg-dev@lists.sourceforge.net -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -# -- -# -# File: orpg_settings.py -# Author: Dj Gilcrease -# Maintainer: -# Version: -# $Id: orpg_settings.py,v 1.51 2007/07/15 14:25:12 digitalxero Exp $ -# -# Description: classes for orpg settings -# - -import sys -import os - -from orpg.orpgCore import open_rpg -from orpg.orpg_windows import * -from orpg.dirpath import dir_struct -from orpg.tools.rgbhex import * -from orpg.tools.settings import settings -from orpg.tools.validate import validate - -class orpgSettingsWnd(wx.Dialog): - def __init__(self, parent): - wx.Dialog.__init__(self, parent, wx.ID_ANY, "OpenRPG Preferences", - wx.DefaultPosition, size=wx.Size(-1,-1), - style=wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CAPTION) - self.Freeze() - - self.chat = open_rpg.get_component('chat') - self.changes = [] - self.SetMinSize((545,500)) - self.tabber = orpgTabberWnd(self, style=FNB.FNB_NO_X_BUTTON) - self.build_gui() - self.tabber.SetSelection(0) - winsizer = wx.BoxSizer(wx.VERTICAL) - sizer = wx.BoxSizer(wx.HORIZONTAL) - sizer.Add(wx.Button(self, wx.ID_OK, "OK"), 1, wx.EXPAND) - sizer.Add(wx.Size(10,10)) - sizer.Add(wx.Button(self, wx.ID_CANCEL, "Cancel"), 1, wx.EXPAND) - winsizer.Add(self.tabber, 1, wx.EXPAND) - winsizer.Add(sizer, 0, wx.EXPAND | wx.ALIGN_BOTTOM) - self.winsizer = winsizer - self.SetSizer(self.winsizer) - self.SetAutoLayout(True) - self.Fit() - self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK) - self.Thaw() - - def on_size(self,evt): - (w,h) = self.GetClientSizeTuple() - self.winsizer.SetDimension(0,0,w,h-25) - - def build_gui(self): - validate.config_file('settings.xml', 'default_settings.xml') - filename = dir_struct['user'] + 'settings.xml' - - for c in settings._settings.getroot().getchildren(): - self.build_window(c, self.tabber) - - def build_window(self, el, parent_wnd): - if el.tag == 'tab': - temp_wnd = self.do_tab_window(el, parent_wnd) - - return temp_wnd - - def do_tab_window(self, el, parent_wnd): - tab_type = el.get('type') - name = el.get('name') - - if tab_type == 'grid': - temp_wnd = self.do_grid_tab(el, parent_wnd) - parent_wnd.AddPage(temp_wnd, name, False) - elif tab_type == 'tab': - temp_wnd = orpgTabberWnd(parent_wnd, style=FNB.FNB_NO_X_BUTTON) - - for c in el.getchildren(): - if c.tag == 'tab': - self.do_tab_window(c, temp_wnd) - temp_wnd.SetSelection(0) - parent_wnd.AddPage(temp_wnd, name, False) - elif tab_type == 'text': - temp_wnd = wx.TextCtrl(parent_wnd, wx.ID_ANY) - parent_wnd.AddPage(temp_wnd, name, False) - else: - temp_wnd = None - return temp_wnd - - def do_grid_tab(self, el, parent_wnd): - tab_settings = [] - - for c in el.getchildren(): - tab_settings.append([c.tag, c.get('value'), c.get('options'), - c.get('help')]) - temp_wnd = settings_grid(parent_wnd, tab_settings, self.changes) - return temp_wnd - - def onOk(self, evt): - #This will write the settings back to the XML - self.session = open_rpg.get_component("session") - tabbedwindows = open_rpg.get_component("tabbedWindows") - new = [] - for wnd in tabbedwindows: - try: - style = wnd.GetWindowStyleFlag() - new.append(wnd) - except: - pass - tabbedwindows = new - open_rpg.add_component("tabbedWindows", tabbedwindows) - rgbconvert = RGBHex() - - for i in xrange(0,len(self.changes)): - settings.set(str(self.changes[i][0]), self.changes[i][1]) - top_frame = open_rpg.get_component('frame') - - if self.changes[i][0] == 'bgcolor' or self.changes[i][0] == 'textcolor': - self.chat.chatwnd.SetPage(self.chat.ResetPage()) - self.chat.chatwnd.scroll_down() - if settings.get('ColorTree') == '1': - top_frame.tree.SetBackgroundColour(settings.get('bgcolor')) - top_frame.tree.SetForegroundColour(settings.get('textcolor')) - top_frame.tree.Refresh() - top_frame.players.SetBackgroundColour(settings.get('bgcolor')) - top_frame.players.SetForegroundColour(settings.get('textcolor')) - top_frame.players.Refresh() - else: - top_frame.tree.SetBackgroundColour('white') - top_frame.tree.SetForegroundColour('black') - top_frame.tree.Refresh() - top_frame.players.SetBackgroundColour('white') - top_frame.players.SetForegroundColour('black') - top_frame.players.Refresh() - - if self.changes[i][0] == 'ColorTree': - if self.changes[i][1] == '1': - top_frame.tree.SetBackgroundColour(settings.get('bgcolor')) - top_frame.tree.SetForegroundColour(settings.get('textcolor')) - top_frame.tree.Refresh() - top_frame.players.SetBackgroundColour(settings.get('bgcolor')) - top_frame.players.SetForegroundColour(settings.get('textcolor')) - top_frame.players.Refresh() - else: - top_frame.tree.SetBackgroundColour('white') - top_frame.tree.SetForegroundColour('black') - top_frame.tree.Refresh() - top_frame.players.SetBackgroundColour('white') - 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() - - 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]) - - if self.changes[i][0] == 'player': - self.session.name = 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\ - (settings.get('TabTheme') == 'customflat' or\ - settings.get('TabTheme') == 'customslant')) or\ - (self.changes[i][0] == 'TabGradientFrom' and\ - (settings.get('TabTheme') == 'customflat' or\ - settings.get('TabTheme') == 'customslant')) or\ - (self.changes[i][0] == 'TabGradientTo' and\ - (settings.get('TabTheme') == 'customflat' or\ - settings.get('TabTheme') == 'customslant')): - - gfrom = settings.get('TabGradientFrom') - (fred, fgreen, fblue) = rgbconvert.rgb_tuple(gfrom) - - gto = settings.get('TabGradientTo') - (tored, togreen, toblue) = rgbconvert.rgb_tuple(gto) - - tabtext = settings.get('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 settings.get('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)) - wnd.SetNonActiveTabTextColour(wx.Color(tred, tgreen, tblue)) - wnd.Refresh() - - if self.changes[i][0] == 'TabBackgroundGradient': - for wnd in tabbedwindows: - red, green, blue = rgbconvert.rgb_tuple(self.changes[i][1]) - wnd.SetTabAreaColour(wx.Color(red, green, blue)) - wnd.Refresh() - settings.save() - 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]) - -class settings_grid(wx.grid.Grid): - """grid for gen info""" - def __init__(self, parent, grid_settings, changed=list()): - wx.grid.Grid.__init__(self, parent, wx.ID_ANY, - style=wx.SUNKEN_BORDER|wx.WANTS_CHARS) - - self.setting_data = changed - self.Bind(wx.EVT_SIZE, self.on_size) - self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_cell_change) - self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_left_click) - self.CreateGrid(len(grid_settings),3) - self.SetRowLabelSize(0) - self.SetColLabelValue(0,"Setting") - self.SetColLabelValue(1,"Value") - self.SetColLabelValue(2,"Available Options") - self.settings = grid_settings - for i in range(len(grid_settings)): - self.SetCellValue(i, 0, grid_settings[i][0]) - self.SetCellValue(i, 1, grid_settings[i][1]) - - if grid_settings[i][1] and grid_settings[i][1][0] == '#': - self.SetCellBackgroundColour(i, 1, grid_settings[i][1]) - self.SetCellValue(i, 2, grid_settings[i][2]) - - def on_left_click(self,evt): - row = evt.GetRow() - col = evt.GetCol() - if col == 2: - return - elif col == 0: - name = self.GetCellValue(row,0) - str = self.settings[row][3] - msg = wx.MessageBox(str,name) - return - elif col == 1: - setting = self.GetCellValue(row,0) - value = self.GetCellValue(row,1) - if value and value[0] == '#': - hexcolor = orpg.tools.rgbhex.RGBHex().do_hex_color_dlg(self) - if hexcolor: - self.SetCellValue(row,2, hexcolor) - self.SetCellBackgroundColour(row,1,hexcolor) - self.Refresh() - setting = self.GetCellValue(row,0) - self.setting_data.append([setting, hexcolor]) - else: - evt.Skip() - - def on_cell_change(self,evt): - row = evt.GetRow() - col = evt.GetCol() - if col != 1: - return - setting = self.GetCellValue(row,0) - value = self.GetCellValue(row,1) - self.setting_data.append([setting, value]) - - def get_h(self): - (w,h) = self.GetClientSizeTuple() - rows = self.GetNumberRows() - minh = 0 - for i in range (0,rows): - minh += self.GetRowSize(i) - minh += 120 - return minh - - def on_size(self,evt): - (w,h) = self.GetClientSizeTuple() - cols = self.GetNumberCols() - col_w = w/(cols) - for i in range(0,cols): - self.SetColSize(i,col_w) - self.Refresh()
--- a/orpg/tools/orpg_sound.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/orpg_sound.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,4 +1,5 @@ -from orpg.orpg_wx import * +import wx +import wx.media from orpg.tools.decorators import debugging from orpg.tools.settings import settings
--- a/orpg/tools/passtool.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/passtool.py Thu Mar 25 17:56:48 2010 -0600 @@ -28,8 +28,8 @@ import traceback -#import orpg.orpg_windows -from orpg.orpg_wx import * +import wx + from orpg.orpgCore import open_rpg from orpg.tools.settings import settings from orpg.tools.orpg_log import logger @@ -39,7 +39,7 @@ ##################### ## Password Assistant ##################### -class PassSet: +class PassSet(object): "set of passwords for a given room id on a server" @debugging def __init__(self): @@ -50,7 +50,7 @@ self.room = None -class PassTool: +class PassTool(object): "Password Management System" @debugging def __init__(self):
--- a/orpg/tools/pluginui.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,301 +0,0 @@ -from orpg.orpg_wx import * -from orpg.orpgCore import * -from orpg.plugindb import plugindb -from orpg.dirpath import dir_struct -from orpg.tools.orpg_log import logger - -sys.path.append(dir_struct["plugins"]) - -class PluginFrame(wx.Frame): - def __init__(self, parent): - wx.Frame.__init__(self, parent, wx.ID_ANY, "Plugin Control Panel") - self.panel = wx.Panel(self, wx.ID_ANY) - self.parent = parent - self.startplugs = plugindb.GetList("plugincontroller", "startup_plugins", []) - self.available_plugins = {} - self.enabled_plugins = {} - self.pluginNames = [] - self.SetMinSize((380, 480)) - self._selectedPlugin = None - self.Bind(wx.EVT_CLOSE, self._close) - - #Public Methods - def Start(self): - self.__buildGUI() - self._update(None) - self.base_sizer = wx.BoxSizer(wx.VERTICAL) - self.base_sizer.Add(self.panel, 1, wx.EXPAND) - self.panel.SetSizer(self.main_sizer) - self.panel.SetAutoLayout(True) - self.panel.Fit() - self.SetSizer(self.base_sizer) - self.SetAutoLayout(True) - self.Fit() - - def get_activeplugins(self): - return self.enabled_plugins - - def get_startplugins(self): - return self.startplugs - - #Private Methods - def __buildGUI(self): - self.main_sizer = wx.BoxSizer(wx.VERTICAL) - self.btn_sizer = wx.BoxSizer(wx.HORIZONTAL) - self.btn_sizer2 = wx.BoxSizer(wx.HORIZONTAL) - self.head_sizer = wx.BoxSizer(wx.HORIZONTAL) - #pnl = wx.Panel(self.panel, wx.ID_ANY) - self.err_sizer = wx.BoxSizer(wx.VERTICAL) - self.err_sizer.Add(self.head_sizer, 0, wx.EXPAND) - self.errorMessage = wx.StaticText(self.panel, wx.ID_ANY, "") - self.err_sizer.Add(self.errorMessage, 0, wx.EXPAND) - self.main_sizer.Add(self.err_sizer, 0, wx.EXPAND) - self.pluginList = wx.ListCtrl(self.panel, wx.ID_ANY, style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES|wx.LC_SORT_ASCENDING) - self.pluginList.InsertColumn(1, "Name") - self.pluginList.InsertColumn(2, "Autostart") - self.pluginList.InsertColumn(3, "Author") - self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._selectPlugin, self.pluginList) - self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._deselectPlugin, self.pluginList) - self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._togglePlugin, self.pluginList) - self.Bind(wx.EVT_LIST_COL_CLICK, self._sort, self.pluginList) - self.main_sizer.Add(self.pluginList, 1, wx.EXPAND) - - self.enableAllBtn = wx.Button(self.panel, wx.ID_ANY, "Enable All") - self.enableBtn = wx.Button(self.panel, wx.ID_ANY, "Enable") - self.disableAllBtn = wx.Button(self.panel, wx.ID_ANY, "Disable All") - self.disableBtn = wx.Button(self.panel, wx.ID_ANY, "Disable") - self.autostartBtn = wx.Button(self.panel, wx.ID_ANY, "Autostart") - self.helpBtn = wx.Button(self.panel, wx.ID_ANY, "Plugin Info") - self.updateBtn = wx.Button(self.panel, wx.ID_ANY, "Update List") - - self.Bind(wx.EVT_BUTTON, self._enableAll, self.enableAllBtn) - self.Bind(wx.EVT_BUTTON, self._enable, self.enableBtn) - self.Bind(wx.EVT_BUTTON, self._disableAll, self.disableAllBtn) - self.Bind(wx.EVT_BUTTON, self._disable, self.disableBtn) - self.Bind(wx.EVT_BUTTON, self._autostart, self.autostartBtn) - self.Bind(wx.EVT_BUTTON, self._help, self.helpBtn) - self.Bind(wx.EVT_BUTTON, self._update, self.updateBtn) - - self.btn_sizer.Add(self.enableBtn, 0, wx.EXPAND) - self.btn_sizer.Add(self.disableBtn, 0, wx.EXPAND) - self.btn_sizer.Add(self.autostartBtn, 0, wx.EXPAND) - self.btn_sizer.Add(self.helpBtn, 0, wx.EXPAND) - - self.btn_sizer2.Add(self.updateBtn, 0, wx.EXPAND) - self.btn_sizer2.Add(self.enableAllBtn, 0, wx.EXPAND) - self.btn_sizer2.Add(self.disableAllBtn, 0, wx.EXPAND) - - self.__disablePluginBtns() - - self.main_sizer.Add(self.btn_sizer, 0, wx.EXPAND) - self.main_sizer.Add(self.btn_sizer2, 0, wx.EXPAND) - - def __disablePluginBtns(self): - self.enableBtn.Disable() - self.disableBtn.Disable() - self.autostartBtn.Disable() - self.helpBtn.Disable() - - def __enablePluginBtns(self): - self.autostartBtn.Label = "Autostart" - self.enableBtn.Enable() - self.disableBtn.Enable() - self.autostartBtn.Enable() - self.helpBtn.Enable() - - def __error(self, errMsg): - self.errorMessage.Label += "\n" + str(errMsg) - self.__doLayout() - - def __clearError(self): - self.errorMessage.Label = "" - self.__doLayout() - - def __checkIdx(self, evt): - if isinstance(evt, int): - return evt - elif self._selectedPlugin is not None: - return self._selectedPlugin - else: - dlg = wx.MessageDialog(None, "You need to select a plugin before you can use this!", 'ERROR', wx.OK) - dlg.ShowModal() - dlg.Destroy() - return None - - def __impPlugin(self, pname): - try: - if "plugins." + pname in sys.modules: - del sys.modules["plugins." + pname]#to ensure that the newly-imported one will be used correctly. No, reload() is not a better way to do this. - mod = __import__("plugins." + pname) - plugin = getattr(mod, pname) - pdata = plugin.Plugin(plugindb, self.parent) - self.available_plugins[pdata.name] = [pname, pdata, pdata.author, pdata.help] - return plugin - - except Exception, e: - self.__error(e) - logger.exception(traceback.format_exc()) - - def __doLayout(self): - self.Freeze() - self.panel.Layout() - self.Fit() - self.Thaw() - - def __pluginSort(self, item1, item2): - return cmp(self.pluginNames[item1], self.pluginNames[item2]) - - #Events - def _selectPlugin(self, evt): - self._selectedPlugin = evt.GetIndex() - self.__enablePluginBtns() - pname = self.pluginList.GetItem(self._selectedPlugin, 0).GetText() - info = self.available_plugins[pname] - - if info[0] in self.enabled_plugins: - self.enableBtn.Disable() - else: - self.disableBtn.Disable() - if self.pluginList.GetItem(self._selectedPlugin, 1).GetText() == "X": - self.autostartBtn.Label = "Disable Autostart" - - self.__doLayout() - self.pluginList.SetItemState(self._selectedPlugin, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED) - - def _deselectPlugin(self, evt): - self.__disablePluginBtns() - self._selectedPlugin = None - - def _togglePlugin(self, evt): - idx = evt.GetIndex() - pname = self.pluginList.GetItem(idx, 0).GetText() - info = self.available_plugins[pname] - - if info[0] in self.enabled_plugins: - self._disable(idx) - else: - self._enable(idx) - - self.pluginList.SetItemState(self._selectedPlugin, 0, wx.LIST_STATE_SELECTED) - - def _enableAll(self, evt): - for pname in self.available_plugins.iterkeys(): - info = self.available_plugins[pname] - if info[0] not in self.enabled_plugins: - idx = self.pluginList.FindItem(-1, pname) - self._enable(idx) - - def _enable(self, evt): - idx = self.__checkIdx(evt) - if idx is None: - return - pname = self.pluginList.GetItem(idx, 0).GetText() - info = self.available_plugins[pname] - info[1].menu_start() - - try: - info[1].plugin_enabled() - except Exception, e: - self.__error(e) - logger.exception(traceback.format_exc()) - self.pluginList.SetItemBackgroundColour(idx, (255,0,0)) - info[1].menu_cleanup() - return - - self.enabled_plugins[info[0]] = info[1] - self.pluginList.SetItemBackgroundColour(idx, (0,255,0)) - self.enableBtn.Disable() - self.disableBtn.Enable() - - def _disableAll(self, evt): - for entry in self.enabled_plugins.keys(): - idx = self.pluginList.FindItem(0, self.enabled_plugins[entry].name) - self._disable(idx) - - def _disable(self, evt): - idx = self.__checkIdx(evt) - if idx is None: - return - pname = self.pluginList.GetItem(idx, 0).GetText() - info = self.available_plugins[pname] - info[1].menu_cleanup() - try: - info[1].plugin_disabled() - del self.enabled_plugins[info[0]] - except Exception, e: - self.__error(e) - logger.exception(traceback.format_exc()) - self.pluginList.SetItemBackgroundColour(idx, (255,0,0)) - return - self.pluginList.SetItemBackgroundColour(idx, (255,255,255)) - self.disableBtn.Disable() - self.enableBtn.Enable() - - def _autostart(self, evt): - idx = self.__checkIdx(evt) - if idx is None: - return - if self.pluginList.GetItem(idx, 1).GetText() == "X": - self.startplugs.remove(self.pluginList.GetItem(idx, 0).GetText()) - self.pluginList.SetStringItem(idx, 1, "") - self.autostartBtn.Label = "Autostart" - else: - self.startplugs.append(self.pluginList.GetItem(idx, 0).GetText()) - self.pluginList.SetStringItem(idx, 1, "X") - self.autostartBtn.Label = "Disable Autostart" - - plugindb.SetList("plugincontroller", "startup_plugins", self.startplugs) - self.__doLayout() - - def _help(self, evt): - if isinstance(evt, int): - idx = evt - elif self._selectedPlugin is not None: - idx = self._selectedPlugin - else: - dlg = wx.MessageDialog(None, "You need to select a plugin before you can use this!", 'ERROR', wx.OK) - dlg.ShowModal() - dlg.Destroy() - return - - pname = self.pluginList.GetItem(idx, 0).GetText() - info = self.available_plugins[pname] - - msg = "Author(s):\t" + info[2] + "\n\n" + info[3] - - dlg = wx.MessageDialog(None, msg, 'Plugin Information: ' + pname, wx.OK) - dlg.ShowModal() - dlg.Destroy() - - def _update(self, evt): - self.__clearError() - self._disableAll(None) - self.available_plugins = {} - self.errorMessage.Label = "" - self.pluginList.DeleteAllItems() - self.pluginNames = [] - - list_of_plugin_dir = os.listdir(dir_struct["plugins"]) - for p in list_of_plugin_dir: - if p[:2].lower()=="xx" and p[-3:]==".py": - self.__impPlugin(p[:-3]) - - i = 0 - for plugname, info in self.available_plugins.iteritems(): - self.pluginNames.append(plugname) - idx = self.pluginList.InsertStringItem(self.pluginList.GetItemCount(), plugname) - self.pluginList.SetStringItem(idx, 2, info[2]) - if plugname in self.startplugs: - self.pluginList.SetStringItem(idx, 1, "X") - self._enable(idx) - self.pluginList.SetItemData(idx, i) - i += 1 - self.pluginList.SetColumnWidth(0, wx.LIST_AUTOSIZE) - self.__doLayout() - self.__disablePluginBtns() - - def _close(self, evt): - self.Hide() - - def _sort(self, evt): - self.pluginList.SortItems(self.__pluginSort)
--- a/orpg/tools/predTextCtrl.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/predTextCtrl.py Thu Mar 25 17:56:48 2010 -0600 @@ -27,27 +27,18 @@ # adjusting a weight for each word based on how often you type it. # -## -## Module Loading -## +from string import ascii_letters -import string -from orpg.orpg_windows import * +import wx from wx.lib.expando import ExpandoTextCtrl -# This line added to test CVS commit - -## -## Class Definitions -## - # This class implements a tree node that represents a letter # # Defines: # __init__(self,filename) # -class Letter: - def __init__(self,asciiCharIn,parentNodeIn): +class Letter(object): + def __init__(self, asciiCharIn, parentNodeIn): self.asciiChar = asciiCharIn # should be an ASCII char self.parentNode = parentNodeIn # should be ref to a class Letter self.priority = 0 # should be an int @@ -251,38 +242,19 @@ # and returns it's guess of the rest of the word, based on the highest priority letter in the rest of the branch. def getPrediction(self,k,cur): - if cur.children.has_key(k) : # check to see if the key typed is a sub branch - # If so, make a prediction. Otherwise, do the else at the bottom of - # the method (see below). - - cur = cur.children[k] # set the cur to the typed key's class Letter in the sub-branch - - backtrace = cur.mostCommon # backtrace is a class Letter. It's used as a placeholder to back trace - # from the last letter of the mostCommon word in the - # sub-tree up through the tree until we meet ourself at cur. We'll - # build the guess text this way - - returnText = "" # returnText is a string. This will act as a buffer to hold the string - # we build. - - while cur is not backtrace: # Here's the loop. We loop until we've snaked our way back to cur - - returnText = backtrace.asciiChar + returnText # Create a new string that is the character at backtrace + everything - # so far. So, for "tion" we'll build "n","on","ion","tion" as we .. - - backtrace = backtrace.parentNode # ... climb back towards cur - - return returnText # And, having reached here, we've met up with cur, and returnText holds - # the string we built. Return it. - - else: # This is the else to the original if. - # If the letter typed isn't in a sub branch, then - # the letter being typed isn't in our tree, so - return "" # return the empty string + if cur.children.has_key(k) : + cur = cur.children[k] + backtrace = cur.mostCommon + returnText = "" + while cur is not backtrace: + returnText = backtrace.asciiChar + returnText + backtrace = backtrace.parentNode + return returnText + else: + return "" # End of class LetterTree! - LetterTree = LetterTreeClass() @@ -369,8 +341,8 @@ # initialized to 0 begin = 0 - for offset in range(insert - 1): - if st[-(offset + 2)] not in string.letters: + for offset in xrange(insert - 1): + if st[-(offset + 2)] not in ascii_letters: begin = insert - (offset + 1) break return st[begin:insert] @@ -434,7 +406,7 @@ # This block of code, by popular demand, changes the behavior of the control to ignore any prediction that # hasn't been "accepted" when the enter key is struck. - (startSel,endSel) = self.GetSelection() # get the curren selection + startSel, endSel = self.GetSelection() # get the curren selection # # Start update @@ -446,8 +418,8 @@ # st = front + back # This expression creates a string that get rid of any selected text. # self.SetValue(st) - self.Remove( startSel, endSel ) - st = string.strip( self.GetValue() ) + self.Remove(startSel, endSel) + st = self.Value.strip() # # End update # @@ -456,7 +428,7 @@ # newSt if it's a letter. If it's not a letter, (e.g. a comma or # hyphen) a space is added to newSt in it's place. for ch in st: - if ch not in string.letters: + if ch not in ascii_letters: newSt += " " else: newSt += ch @@ -465,8 +437,8 @@ # split it and to a LetterTree.incWord on the lowercase version of it. # Reminder: incWord will increment the priority of existing words and add # new ones - for aWord in string.split(newSt): - self.tree.incWord(string.lower(aWord)) + for aWord in newSt.strip(): + self.tree.incWord(aWord.lower()) self.parent.OnChar(event) # Now that all of the words are added, pass the event and return return @@ -495,7 +467,7 @@ return - elif asciiKey in string.letters: + elif asciiKey in ascii_letters: # This is the real meat and potatoes of predTextCtrl. This is where most of the # wx.TextCtrl logic is changed. @@ -516,7 +488,7 @@ curWord = "" # Assume there's a problem with finding the curWord - if (len(back) == 0) or (back[0] not in string.letters): # We should only insert a prediction if we are typing + if (len(back) == 0) or (back[0] not in ascii_letters): # We should only insert a prediction if we are typing # at the end of a word, not in the middle. There are # three cases: we are typing at the end of the string or # we are typing in the middle of the string and the next @@ -551,7 +523,7 @@ self.parent.OnChar(event) # we're done here return - self.cur = self.tree.findWordNode(string.lower(curWord[:-1])) # Still with me? We're almost done. At this point, we + self.cur = self.tree.findWordNode(curWord[:-1].lower()) # Still with me? We're almost done. At this point, we # need to convert our word string to a Letter node, # because that's what getPrediction expects. Notice # that we're feeding in the string with the last @@ -566,7 +538,7 @@ # get the prediction - predictText = self.tree.getPrediction(string.lower(asciiKey),self.cur) # This is the big prediction, as noted above + predictText = self.tree.getPrediction(asciiKey.lower(), self.cur) # This is the big prediction, as noted above # Note the use of string.lower() because we # keep the word list in all lower case,but we # want to be able to match any capitalization
--- a/orpg/tools/rgbhex.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/rgbhex.py Thu Mar 25 17:56:48 2010 -0600 @@ -25,7 +25,7 @@ # # Description: rgb to hex utility -from orpg.orpg_wx import * +import wx #####################
--- a/orpg/tools/scriptkit.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/tools/scriptkit.py Thu Mar 25 17:56:48 2010 -0600 @@ -27,15 +27,18 @@ # of exposing a simple API to users of an as yet uncreated scripting interface. # +import warnings + +warnings.warn("The skriptkit module is depreciated", DeprecationWarning, 2) import time -from orpg.orpg_windows import * -from orpg.orpg_wx import * -import orpg.chat.chat_msg + +import wx + from orpg.tools.orpg_log import logger from orpg.tools.settings import settings -class scriptkit: +class scriptkit(object): def __init__(self): """Simple constructor. It currently only assigns the openrpg reference to a local variable. <ul>
--- a/orpg/tools/toolBars.py Thu Mar 25 15:48:49 2010 -0600 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,164 +0,0 @@ -# Copyright (C) 2000-2001 The OpenRPG Project -# -# openrpg-dev@lists.sourceforge.net -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -# -- -# -# File: toolBars.py -# Author: Greg Copeland -# Maintainer: -# -# Description: Contains all of the toolbars used in the application. -# -# - -__version__ = "$Id: toolBars.py,v 1.13 2006/11/04 21:24:22 digitalxero Exp $" - - -## -## Module Loading -## -from inputValidator import * -import string -import orpg.dirpath - -# DICE stuff -TB_IDC_D4 = wx.NewId() -TB_IDC_D6 = wx.NewId() -TB_IDC_D8 = wx.NewId() -TB_IDC_D10 = wx.NewId() -TB_IDC_D12 = wx.NewId() -TB_IDC_D20 = wx.NewId() -TB_IDC_D100 = wx.NewId() -TB_IDC_NUMDICE = wx.NewId() -TB_IDC_MODS = wx.NewId() - -# MAP stuff -TB_MAP_MODE = wx.NewId() -# Caution: the use of wxFRAME_TOOL_WINDOW screws up the window on GTK. Please don't use!!! - -class MapToolBar(wx.Panel): - """This is where all of the map related tools belong for quick reference.""" - def __init__( self, parent, id=-1, title="Map Tool Bar", size= wx.Size(300, 45), callBack=None ): - wx.Panel.__init__(self, parent, id, size=size) - self.callback = callBack - self.mapmode = 1 - self.modeicons = [orpg.dirpath.dir_struct["icon"]+"move.gif", - orpg.dirpath.dir_struct["icon"]+"draw.gif", - orpg.dirpath.dir_struct["icon"]+"tape.gif"] - # Make a sizer for everything to belong to - self.sizer = wx.BoxSizer( wx.HORIZONTAL ) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"move.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - self.butt = wx.BitmapButton( self, TB_MAP_MODE, bm ) - self.sizer.Add( self.butt,0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_MAP_MODE) - # Build the toolbar now - # Stubbed, but nothing here yet! - # Now, attach the sizer to the panel and tell it to do it's magic - self.SetSizer(self.sizer) - self.SetAutoLayout(True) - self.Fit() - - def onToolBarClick(self,evt): - data = "" - id = evt.GetId() - data = "" - mode = 1 - if id == TB_MAP_MODE: - mode = 1 - 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) - -class DiceToolBar(wx.Panel): - """This is where all of the dice related tools belong for quick reference.""" - def __init__( self, parent, id=-1, title="Dice Tool Bar", size=wx.Size(300, 45), callBack=None ): - wx.Panel.__init__(self, parent, id, size=size) - # Save our post callback - self.callBack = callBack - # Make a sizer for everything to belong to - self.sizer = wx.BoxSizer( wx.HORIZONTAL ) - # Build the toolbar now - self.numDieText = wx.TextCtrl( self, TB_IDC_NUMDICE, "1", size= wx.Size(50, 25), - validator=MathOnlyValidator() ) - self.sizer.Add( self.numDieText, 1, wx.EXPAND | wx.ALIGN_LEFT ) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d4.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D4, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D4) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d6.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D6, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D6) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d8.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D8, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D8) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d10.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D10, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D10) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d12.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D12, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D12) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d20.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D20, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D20) - bm = wx.Image(orpg.dirpath.dir_struct["icon"]+"b_d100.gif", wx.BITMAP_TYPE_GIF).ConvertToBitmap() - butt = wx.BitmapButton( self, TB_IDC_D100, bm, size=(bm.GetWidth(), bm.GetHeight()) ) - self.sizer.Add( butt, 0, wx.ALIGN_CENTER ) - self.Bind(wx.EVT_BUTTON, self.onToolBarClick, id=TB_IDC_D100) - # Add our other text control to the sizer - self.dieModText = wx.TextCtrl( self, TB_IDC_MODS, "+0", size= wx.Size(50, 25), - validator=MathOnlyValidator() ) - self.sizer.Add( self.dieModText, 1, wx.EXPAND | wx.ALIGN_RIGHT ) - # Now, attach the sizer to the panel and tell it to do it's magic - self.SetSizer(self.sizer) - self.SetAutoLayout(True) - self.Fit() - - def onToolBarClick( self, evt ): - # Get our modifiers - numDie = self.numDieText.GetValue() - dieMod = self.dieModText.GetValue() - - # Init the die roll text - 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 )
--- a/orpg/ui/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,3 +1,7 @@ -__all__ = ['util', 'toolbars', 'AliasLib'] +__all__ = ['util', 'toolbars', 'AliasLib', 'SettingsWindow', + 'BrowseServerWindow', 'PluginFrame'] -from ._alias_lib import AliasLib \ No newline at end of file +from ._alias_lib import AliasLib +from ._settings import SettingsWindow +from ._browse_server import BrowseServerWindow +from ._plugin import PluginFrame \ No newline at end of file
--- a/orpg/ui/_alias_lib.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/_alias_lib.py Thu Mar 25 17:56:48 2010 -0600 @@ -15,8 +15,6 @@ from orpg.tools.validate import validate from orpg.tools.settings import settings from orpg.tools.decorators import debugging -from orpg.tools.events import (orpgEVT_ALIAS_LIST_CHANGED, - orpgEVT_FILTER_LIST_CHANGED) from orpg.tools.pubsub import Publisher from orpg.external.etree.ElementTree import ElementTree, Element from orpg.external.etree.ElementTree import fromstring, tostring @@ -614,32 +612,3 @@ return self def __exit__(self, *args, **kwargs): self.Destroy() - -class AliasLibEvent(wx.PyCommandEvent): - def __init__(self, eventType, id=1, list_=[]): - wx.PyCommandEvent.__init__(self, eventType, id) - self._eventType = eventType - - self._list = list_ - - self.notify = wx.NotifyEvent(eventType, id) - - def GetNotifyEvent(self): - """Returns the actual wx.NotifyEvent.""" - return self.notify - - def IsAllowed(self): - """Returns whether the event is allowed or not.""" - return self.notify.IsAllowed() - - def Veto(self): - """Vetos the event.""" - self.notify.Veto() - - def Allow(self): - """The event is allowed.""" - self.notify.Allow() - - def _get_list(self): - return self._list - list = property(_get_list) \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/_browse_server.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,701 @@ +# Copyright (C) 2000-2001 The OpenRPG Project +# +# openrpg-dev@lists.sourceforge.net +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +# -- +# +# File: gsclient.py +# Author: Chris Davis +# Maintainer: +# Version: +# $Id: gsclient.py,v 1.53 2007/10/25 21:49:34 digitalxero Exp $ +# +# Description: The file contains code for the game server browser +# +from __future__ import with_statement + +import traceback + +import wx +from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin, CheckListCtrlMixin + +from orpg.networking.meta_server_lib import get_server_list +from orpg.chat.chat_util import strip_html, strip_unicode +from orpg.tools.rgbhex import RGBHex +from orpg.orpgCore import open_rpg +from orpg.dirpath import dir_struct +from orpg.tools.decorators import debugging +from orpg.tools.orpg_log import logger +from orpg.tools.settings import settings +from orpg.tools.validate import validate +from orpg.external.etree.ElementTree import ElementTree, Element +from orpg.external.etree.ElementTree import fromstring, tostring + +class server_instance(object): + def __init__(self, id, name="[Unknown]", users="0", address="127.0.0.1", + port="6774"): + self.id = id + self.name = name + self.user = users + self.addy = address + self.port = port + +@debugging +def server_instance_compare(x, y): + """compares server insances for list sort""" + DEV_SERVER = "OpenRPG DEV" + xname = x.get('name', '') + xuser = int(x.get('num_users', 0)) + yname = y.get('name', '') + yuser = int(y.get('num_users', 0)) + + who_name = cmp(yname, xname) + who_user = cmp(yuser, xuser) + + if xname.startswith(DEV_SERVER): + if yname.startswith(DEV_SERVER): + if not who_name: + return who_user + else: + return who_name + else: + return -1 + elif yname.startswith(DEV_SERVER): + return 1 + elif not who_user: + return who_name + else: + return who_user + +@debugging +def roomCmp(room1, room2): + if int(room1) > int(room2): + return 1 + elif int(room1) < int(room2): + return -1 + return 0 + +class BrowseServerWindow(wx.Panel): + @debugging + def __init__(self,parent): + wx.Panel.__init__(self, parent, -1) + self.parent = parent + self.password_manager = open_rpg.get_component('password_manager') + self.frame = open_rpg.get_component('frame') + self.session = open_rpg.get_component('session') + self.serverNameSet = 0 + self.last_motd = "" + self.buttons = {} + self.texts = {} + self.svrList = [] + self.build_ctrls() + self.build_bookmarks() + self.refresh_server_list() + self.refresh_room_list() + + @debugging + def build_ctrls(self): + ## Section Sizers (with frame edges and text captions) + self.box_sizers = {} + self.box_sizers["server"] = wx.StaticBox(self, -1, "Server") + self.box_sizers["window"] = wx.StaticBox(self, -1, "Exit" ) + self.box_sizers["room"] = wx.StaticBox(self, -1, "Rooms") + self.box_sizers["c_room"] = wx.StaticBox(self, -1, "Create Room") + + ## Layout Sizers + self.sizers = {} + self.sizers["main"] = wx.GridBagSizer(hgap=1, vgap=1) + self.sizers["server"] = wx.StaticBoxSizer(self.box_sizers["server"], + wx.VERTICAL) + self.sizers["rooms"] = wx.StaticBoxSizer(self.box_sizers["room"], + wx.VERTICAL) + self.sizers["close"] = wx.StaticBoxSizer(self.box_sizers["window"], + wx.HORIZONTAL) + self.sizers["c_room"] = wx.StaticBoxSizer(self.box_sizers["c_room"], + wx.VERTICAL) + + #Build Server Sizer + adder = wx.StaticText(self, -1, "Address:") + self.texts["address"] = wx.TextCtrl(self, wx.ID_ANY) + servers = wx.StaticText(self, -1, "Servers:") + self.server_list = ServerListCtrl(self, self.on_bookmark_check) + #wx.ListCtrl(self, wx.ID_ANY, style=wx.LC_REPORT|wx.SUNKEN_BORDER) + self.server_list.InsertColumn(0, "") + self.server_list.InsertColumn(1, "Players", wx.LIST_FORMAT_LEFT, 0) + self.server_list.InsertColumn(2, "Name", wx.LIST_FORMAT_LEFT, 0) + self.buttons['gs_connect'] = wx.Button(self, wx.ID_ANY, "Connect") + self.buttons['gs_refresh'] = wx.Button(self, wx.ID_ANY, "Refresh") + self.buttons['gs_disconnect'] = wx.Button(self, wx.ID_ANY, "Disconnect") + self.sizers["svrbtns"] = wx.BoxSizer(wx.HORIZONTAL) + self.sizers["svrbtns"].Add(self.buttons['gs_connect'], 0, wx.EXPAND) + self.sizers["svrbtns"].Add(self.buttons['gs_refresh'], 0, wx.EXPAND) + self.sizers["svrbtns"].Add(self.buttons['gs_disconnect'], 0, wx.EXPAND) + self.sizers["server"].Add(adder, 0, wx.EXPAND) + self.sizers["server"].Add(self.texts["address"], 0, wx.EXPAND) + self.sizers["server"].Add(servers, 0, wx.EXPAND) + self.sizers["server"].Add(self.server_list, 1, wx.EXPAND) + self.sizers["server"].Add(self.sizers["svrbtns"], 0, wx.EXPAND) + + #Build Rooms Sizer + self.room_list = wx.ListCtrl(self, wx.ID_ANY, + style=wx.LC_REPORT|wx.SUNKEN_BORDER) + self.room_list.InsertColumn(0,"Game", wx.LIST_FORMAT_LEFT,0) + self.room_list.InsertColumn(1,"Players", wx.LIST_FORMAT_LEFT,0) + self.room_list.InsertColumn(2,"PW", wx.LIST_FORMAT_LEFT,0) + self.buttons['gs_join_room'] = wx.Button(self, wx.ID_ANY, "Join Room") + self.buttons['gs_join_lobby'] = wx.Button(self, wx.ID_ANY, "Lobby") + self.sizers["roombtns"] = wx.BoxSizer(wx.HORIZONTAL) + self.sizers["roombtns"].Add(self.buttons['gs_join_room'], 0, wx.EXPAND) + self.sizers["roombtns"].Add(self.buttons['gs_join_lobby'], 0, wx.EXPAND) + self.sizers["rooms"].Add(self.room_list, 1, wx.EXPAND) + self.sizers["rooms"].Add(self.sizers["roombtns"], 0, wx.EXPAND) + + #Build Close Sizer + self.buttons['close_openrpg'] = wx.Button(self, wx.ID_ANY, + "Exit OpenRPG") + self.buttons['gs_close'] = wx.Button(self, wx.ID_ANY,"Close Window") + self.sizers["close"].Add(self.buttons['close_openrpg'], 1, + wx.ALIGN_CENTER_VERTICAL) + self.sizers["close"].Add(self.buttons['gs_close'], 1, + wx.ALIGN_CENTER_VERTICAL) + + #Build Create Room Sizer + rname = wx.StaticText(self,-1, "Room Name:") + self.texts["room_name"] = wx.TextCtrl(self, -1) + rpass = wx.StaticText(self,-1, "Password:") + self.buttons['gs_pwd'] = wx.CheckBox(self, wx.ID_ANY, "") + self.texts["room_pwd"] = wx.TextCtrl(self, -1) + self.texts["room_pwd"].Enable(0) + pwsizer = wx.BoxSizer(wx.HORIZONTAL) + pwsizer.Add(self.buttons['gs_pwd'],0,0) + pwsizer.Add(self.texts["room_pwd"], 1, wx.EXPAND) + apass = wx.StaticText(self,-1, "Admin Password:") + self.texts["room_boot_pwd"] = wx.TextCtrl(self, -1) + minver = wx.StaticText(self,-1, "Minimum Version:") + self.texts["room_min_version"] = wx.TextCtrl(self, -1) + self.sizers["c_room_layout"] = wx.FlexGridSizer(rows=8, cols=2, hgap=1, + vgap=1) + self.sizers["c_room_layout"].Add(rname, 0, + wx.ALIGN_RIGHT| + wx.ALIGN_CENTER_VERTICAL|wx.ALL) + self.sizers["c_room_layout"].Add(self.texts["room_name"], 0, wx.EXPAND) + self.sizers["c_room_layout"].Add(rpass, 0, + wx.ALIGN_RIGHT| + wx.ALIGN_CENTER_VERTICAL|wx.ALL) + self.sizers["c_room_layout"].Add(pwsizer, 0, wx.EXPAND) + self.sizers["c_room_layout"].Add(apass, 0, + wx.ALIGN_RIGHT| + wx.ALIGN_CENTER_VERTICAL|wx.ALL) + self.sizers["c_room_layout"].Add(self.texts["room_boot_pwd"], 0, + wx.EXPAND) + self.sizers["c_room_layout"].Add(minver, 0, + wx.ALIGN_RIGHT| + wx.ALIGN_CENTER_VERTICAL|wx.ALL) + self.sizers["c_room_layout"].Add(self.texts["room_min_version"], 0, + wx.EXPAND) + self.sizers["c_room_layout"].AddGrowableCol(1) + self.buttons['gs_create_room'] = wx.Button(self, wx.ID_ANY, + "Create Room") + self.sizers["c_room"].Add(self.sizers["c_room_layout"], 1, + wx.EXPAND) + self.sizers["c_room"].Add(self.buttons['gs_create_room'], 0, + wx.EXPAND) + + #Build Main Sizer + self.sizers["main"].Add(self.sizers["server"], (0,0), span=(2,1), + flag=wx.EXPAND) + self.sizers["main"].Add(self.sizers["rooms"], (0,1), flag=wx.EXPAND) + self.sizers["main"].Add(self.sizers["close"], (2,0), flag=wx.EXPAND) + self.sizers["main"].Add(self.sizers["c_room"], (1,1), span=(2,1), + flag=wx.EXPAND) + self.sizers["main"].AddGrowableCol(0) + self.sizers["main"].AddGrowableCol(1) + self.sizers["main"].AddGrowableRow(0) + self.SetSizer(self.sizers["main"]) + self.SetAutoLayout(True) + self.Fit() + + ## Event Handlers + self.Bind(wx.EVT_BUTTON, self.on_connect_btn, + self.buttons['gs_connect']) + self.Bind(wx.EVT_BUTTON, self.on_disconnect_btn, + self.buttons['gs_disconnect']) + self.Bind(wx.EVT_BUTTON, self.on_create_room_btn, + self.buttons['gs_create_room']) + self.Bind(wx.EVT_BUTTON, self.on_join_room_btn, + self.buttons['gs_join_room']) + self.Bind(wx.EVT_BUTTON, self.on_join_lobby_btn, + self.buttons['gs_join_lobby']) + self.Bind(wx.EVT_BUTTON, self.on_refresh_btn, + self.buttons['gs_refresh']) + self.Bind(wx.EVT_BUTTON, self.on_close_btn, self.buttons['gs_close']) + self.Bind(wx.EVT_BUTTON, self.on_close_openrpg_btn, + self.buttons['close_openrpg']) + self.Bind(wx.EVT_CHECKBOX, self.on_pwd_check, self.buttons['gs_pwd']) + + # Added double click handlers 5/05 -- Snowdog + self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_server_dbclick, + self.server_list) + self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_room_dbclick, + self.room_list) + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_room_select, + self.room_list) + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.on_server_select, + self.server_list) + self.texts['address'].Bind(wx.EVT_SET_FOCUS, self.on_text) + self.set_connected(self.session.is_connected()) + self.cur_room_index = -1 + self.cur_server_index = -1 + self.rmList = {} + + @debugging + def build_bookmarks(self): + gsm = self.frame.mainmenu.GetMenu( + self.frame.mainmenu.FindMenu('Game Server')) + self.bookmarks_menu = wx.Menu() + + validate.config_file('server_bookmarks.xml', + 'default_server_bookmarks.xml') + self.bookmarks = ElementTree() + self.bookmarks.parse(dir_struct['user'] + 'server_bookmarks.xml') + + for server in self.bookmarks.findall('server'): + item = wx.MenuItem(self.bookmarks_menu, wx.ID_ANY, + server.get('name'), server.get('name')) + open_rpg.get_component('frame').Bind(wx.EVT_MENU, + self.on_bookmarks_menu, item) + self.bookmarks_menu.AppendItem(item) + + gsm.AppendSubMenu(self.bookmarks_menu, "Bookmarks") + + @debugging + def on_bookmarks_menu(self, evt): + id = evt.GetId() + menu = self.bookmarks_menu.FindItemById(id) + for server in self.bookmarks.findall('server'): + if server.get('name') == menu.GetLabel(): + address = server.get('address') + self.cur_server_index = 999 + self.name = server.get('name') + + if self.session.is_connected(): + if self.session.host_server == address : + #currently connected to address. Do nothing. + return + else: + #address differs, disconnect. + self.frame.kill_mplay_session() + + self.do_connect(address) + break + + @debugging + def on_bookmark_check(self, item, flag): + name = self.svrList[item].get('name') + address = self.svrList[item].get('address') + port = self.svrList[item].get('port') + + if not flag: + for server in self.bookmarks.findall('server'): + if server.get('name') == name: + self.bookmarks_menu.Remove( + self.bookmarks_menu.FindItem(server.get('name'))) + self.bookmarks.getroot().remove(server) + break + else: + server = Element('server') + server.set('name', name) + server.set('address', address + ':' + port) + self.bookmarks.getroot().append(server) + item = wx.MenuItem(self.bookmarks_menu, wx.ID_ANY, name, name) + open_rpg.get_component('frame').Bind(wx.EVT_MENU, + self.on_bookmarks_menu, item) + self.bookmarks_menu.AppendItem(item) + + self.save_bookmarks() + + @debugging + def save_bookmarks(self): + with open(dir_struct['user'] + 'server_bookmarks.xml', 'w') as f: + self.bookmarks.write(f) + + @debugging + def on_server_dbclick(self, evt=None): + #make sure address is updated just in case list select wasn't done + try: + self.on_select(evt) + except: + pass + address = self.texts["address"].GetValue() + if self.session.is_connected(): + if self.session.host_server == address : + #currently connected to address. Do nothing. + return + else: + #address differs, disconnect. + self.frame.kill_mplay_session() + self.do_connect(address) + + @debugging + def on_room_dbclick(self, evt=None): + #make sure address is updated just in case list select wasn't done + try: + self.on_select(evt) + except: + pass + group_id = str(self.room_list.GetItemData(self.cur_room_index)) + + if self.NoGroups: + self.NoGroups = False + self.session.group_id = group_id + self.on_server_dbclick() + return + + if self.cur_room_index >= 0: + if self.cur_room_index != 0: + self.set_lobbybutton(1); + else: + self.set_lobbybutton(0); + group = self.session.get_group_info(group_id) + pwd = "" + if (group[2] == "True") or (group[2] == "1"): + pwd = self.password_manager.GetPassword("room", group_id) + else: + pwd = "" + self.session.send_join_group(group_id, pwd) + + @debugging + def on_room_select(self,evt): + self.cur_room_index = evt.m_itemIndex + + @debugging + def on_server_select(self,evt): + self.cur_server_index = evt.m_itemIndex + self.name = self.svrList[self.cur_server_index].get('name') + address = self.svrList[self.cur_server_index].get('address') + port = self.svrList[self.cur_server_index].get('port') + self.texts["address"].SetValue(address + ":" + str(port)) + self.refresh_room_list() + + @debugging + def on_text(self,evt): + if self.cur_server_index >= 0: + self.cur_server_index = -1 + evt.Skip() + + @debugging + def add_room(self,data): + i = self.room_list.GetItemCount() + if (data[2]=="1") or (data[2]=="True"): pwd="yes" + else: pwd="no" + self.room_list.InsertStringItem(i,data[1]) + self.room_list.SetStringItem(i,1,data[3]) + self.room_list.SetStringItem(i,2,pwd) + self.room_list.SetItemData(i,int(data[0])) + self.refresh_room_list() + + @debugging + def del_room(self, data): + i = self.room_list.FindItemData(-1, int(data[0])) + self.room_list.DeleteItem(i) + self.refresh_room_list() + + @debugging + def update_room(self,data): + i = self.room_list.FindItemData(-1,int(data[0])) + if data[2]=="1" : pwd="yes" + else: pwd="no" + self.room_list.SetStringItem(i,0,data[1]) + self.room_list.SetStringItem(i,1,data[3]) + self.room_list.SetStringItem(i,2,pwd) + self.refresh_room_list() + + @debugging + def set_cur_room_text(self,name): pass + + @debugging + def set_lobbybutton(self,allow): + self.buttons['gs_join_lobby'].Enable(allow) + + @debugging + def set_connected(self,connected): + self.buttons['gs_connect'].Enable(not connected) + self.buttons['gs_disconnect'].Enable(connected) + self.buttons['gs_join_room'].Enable(connected) + self.buttons['gs_create_room'].Enable(connected) + + if not connected: + self.buttons['gs_join_lobby'].Enable(connected) + self.room_list.DeleteAllItems() + self.set_cur_room_text("Not Connected!") + self.cur_room_index = -1 + self.frame.status.connect_status = "Not Connected" + else: + self.frame.status.connect_status = self.name + self.set_cur_room_text("Lobby") + + @debugging + def on_connect_btn(self, evt): + address = self.texts["address"].GetValue() + # check to see if this is a manual entry vs. list entry. + try: + dummy = self.name + except: + self.name = str(address) + self.do_connect(address) + + @debugging + def on_disconnect_btn(self, evt): + self.frame.kill_mplay_session() + + @debugging + def on_refresh_btn(self, evt): + self.refresh_server_list() + + @debugging + def on_join_room_btn(self, evt): + self.do_join_group() + + @debugging + def on_join_lobby_btn(self, evt): + self.do_join_lobby() + + @debugging + def on_create_room_btn(self, evt): + self.do_create_group() + + @debugging + def on_pwd_check(self, evt): + self.texts["room_pwd"].Enable(evt.Checked()) + + @debugging + def on_close_btn(self, evt): + self.parent.OnMB_GameServerBrowseServers() + + @debugging + def on_close_openrpg_btn(self,evt): + dlg = wx.MessageDialog(self,"Quit OpenRPG?","OpenRPG",wx.YES_NO) + if dlg.ShowModal() == wx.ID_YES: + dlg.Destroy() + self.frame.kill_mplay_session() + self.frame.closed_confirmed() + + @debugging + def refresh_room_list(self): + self.room_list.DeleteAllItems() + address = self.texts["address"].GetValue() + try: + cadder = self.session.host_server + except: + cadder = '' + if address in self.rmList and len(self.rmList[address]) > 0 and\ + cadder != address: + groups = self.rmList[address] + self.NoGroups = True + else: + self.NoGroups = False + groups = self.session.get_groups() + + + hex = RGBHex() + color1 = settings.get("RoomColor_Active") + color2 = settings.get("RoomColor_Locked") + color3 = settings.get("RoomColor_Empty") + color4 = settings.get("RoomColor_Lobby") + + for g in groups: + i = self.room_list.GetItemCount() + if isinstance(g, tuple): + og = g + g = Element('room') + g.set('pwd', og[2]) + g.set('id', og[0]) + g.set('name', og[1]) + g.set('num_users', og[3]) + + if g.get('pwd') in ["True","1"]: + pwd="yes" + else: + pwd="no" + + self.room_list.InsertStringItem(i, g.get('name')) + self.room_list.SetStringItem(i, 1, g.get('num_users')) + self.room_list.SetStringItem(i, 2, pwd) + self.room_list.SetItemData(i, int(g.get('id'))) + + #Do colorization + if g.get('id') == '0': + r,g,b = hex.rgb_tuple(color4) + rmcolor = wx.Colour(red=r,green=g,blue=b) + elif g.get('num_users') != '0': + if g.get('pwd') in ["True","1"]: + r,g,b = hex.rgb_tuple(color2) + rmcolor = wx.Colour(red=r,green=g,blue=b) + else: + r,g,b = hex.rgb_tuple(color1) + rmcolor = wx.Colour(red=r,green=g,blue=b) + else: + r,g,b = hex.rgb_tuple(color3) + rmcolor = wx.Colour(red=r,green=g,blue=b) + + item = self.room_list.GetItem(i) + color = wx.Colour(red=r,green=g,blue=b) + item.SetTextColour(rmcolor) + self.room_list.SetItem(item) + + if self.room_list.GetItemCount() > 0: + self.room_list.SortItems(roomCmp) + wx.CallAfter(self.autosizeRooms) + + @debugging + def autosizeRooms(self): + self.room_list.SetColumnWidth(0, wx.LIST_AUTOSIZE) + self.room_list.SetColumnWidth(1, wx.LIST_AUTOSIZE) + self.room_list.SetColumnWidth(2, wx.LIST_AUTOSIZE) + + @debugging + def refresh_server_list(self): + try: + self.server_list.DeleteAllItems() + hex = RGBHex() + color1 = settings.get("RoomColor_Active") + color2 = settings.get("RoomColor_Locked") + color3 = settings.get("RoomColor_Empty") + color4 = settings.get("RoomColor_Lobby") + + etree = get_server_list(["2"]); + self.svrList = sorted(etree.findall('server'), + server_instance_compare) + for server in self.svrList: + address = server.get('address') + ':' + server.get('port') + + i = self.server_list.GetItemCount() + self.server_list.InsertStringItem(i, "") + self.server_list.SetStringItem(i, 1, server.get('num_users')) + self.server_list.SetStringItem(i, 2, server.get('name')) + + for s in self.bookmarks.findall('server'): + if s.get('address') == address: + self.server_list.SetItemImage(i, 1) + + #Setup the server color + if server.get('name').startswith("OpenRPG DEV"): + r,g,b = hex.rgb_tuple(color2) + svrcolor = wx.Colour(red=r,green=g,blue=b) + elif server.get('num_users') == '0': + r,g,b = hex.rgb_tuple(color3) + svrcolor = wx.Colour(red=r,green=g,blue=b) + else: + r,g,b = hex.rgb_tuple(color1) + svrcolor = wx.Colour(red=r,green=g,blue=b) + + item = self.server_list.GetItem(i) + item.SetTextColour(svrcolor) + self.server_list.SetItem(item) + + #Add the server rooms to the rmList + self.rmList[address] = server.findall('room') + + # No server is currently selected!!! Versus the broken and random 0! + self.cur_server_index = -1 + self.server_list.SetColumnWidth(0, wx.LIST_AUTOSIZE) + self.server_list.SetColumnWidth(1, wx.LIST_AUTOSIZE) + self.server_list.SetColumnWidth(2, wx.LIST_AUTOSIZE) + + if self.serverNameSet == 0: + self.texts["address"].SetValue("127.0.0.1:6774") + self.serverNameSet = 1 + else: + pass + + except Exception, e: + logger.exception(traceback.print_exc()) + logger.general("Server List not available.") + + @debugging + def failed_connection(self): pass + + @debugging + def do_connect(self, address): + chat = open_rpg.get_component('chat') + chat.InfoPost("Locating server at " + address + "...") + if self.session.connect(address): + self.frame.start_timer() + else: + chat.SystemPost("Failed to connect to game server...") + self.failed_connection() + + @debugging + def do_join_lobby(self): + self.cur_room_index = 0 + self.session.send_join_group("0","") + self.set_lobbybutton(0); + + @debugging + def do_join_group(self): + if self.cur_room_index >= 0: + if self.cur_room_index != 0: + self.set_lobbybutton(1); + else: + self.set_lobbybutton(0); + group_id = str(self.room_list.GetItemData(self.cur_room_index)) + group = self.session.get_group_info(group_id) + pwd = "" + if (group[2] == "True") or (group[2] == "1"): + pwd = self.password_manager.GetPassword("room", group_id) + else: + pwd = "" + if pwd != None: + self.session.send_join_group(group_id, pwd) + + @debugging + def do_create_group(self): + name = self.texts["room_name"].GetValue() + boot_pwd = self.texts["room_boot_pwd"].GetValue() + minversion = self.texts["room_min_version"].GetValue() + name = name.replace('"', '"').replace("'", ''') + strip_html(strip_unicode(name)) + + if self.buttons['gs_pwd'].GetValue(): + pwd = self.texts["room_pwd"].GetValue() + else: + pwd = "" + if name == "": + wx.MessageBox("Invalid Name","Error"); + else: + msg = "%s is creating room \'%s.\'" % (self.session.name, name) + self.session.send( msg ) + self.session.send_create_group(name,pwd,boot_pwd,minversion) + self.set_lobbybutton(1) #enable the Lobby quickbutton + + @debugging + def on_size(self,evt): + evt.Skip() + + @debugging + def colorize_group_list(self, groups): pass + + +class ServerListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin, CheckListCtrlMixin): + def __init__(self, parent, check_callback): + wx.ListCtrl.__init__(self, parent, wx.ID_ANY, + style=wx.LC_REPORT|wx.SUNKEN_BORDER) + ListCtrlAutoWidthMixin.__init__(self) + CheckListCtrlMixin.__init__(self) + self._callback = check_callback + + def OnCheckItem(self, index, flag): + self._callback(index, flag)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/_plugin.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,304 @@ +import sys +import os +import traceback + +import wx + +from orpg.orpgCore import open_rpg +from orpg.plugindb import plugindb +from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger + +class PluginFrame(wx.Frame): + def __init__(self, parent): + wx.Frame.__init__(self, parent, wx.ID_ANY, "Plugin Control Panel") + self.panel = wx.Panel(self, wx.ID_ANY) + self.parent = parent + self.startplugs = plugindb.GetList("plugincontroller", "startup_plugins", []) + self.available_plugins = {} + self.enabled_plugins = {} + self.pluginNames = [] + self.SetMinSize((380, 480)) + self._selectedPlugin = None + self.Bind(wx.EVT_CLOSE, self._close) + + #Public Methods + def Start(self): + self.__buildGUI() + self._update(None) + self.base_sizer = wx.BoxSizer(wx.VERTICAL) + self.base_sizer.Add(self.panel, 1, wx.EXPAND) + self.panel.SetSizer(self.main_sizer) + self.panel.SetAutoLayout(True) + self.panel.Fit() + self.SetSizer(self.base_sizer) + self.SetAutoLayout(True) + self.Fit() + + def get_activeplugins(self): + return self.enabled_plugins + + def get_startplugins(self): + return self.startplugs + + #Private Methods + def __buildGUI(self): + self.main_sizer = wx.BoxSizer(wx.VERTICAL) + self.btn_sizer = wx.BoxSizer(wx.HORIZONTAL) + self.btn_sizer2 = wx.BoxSizer(wx.HORIZONTAL) + self.head_sizer = wx.BoxSizer(wx.HORIZONTAL) + #pnl = wx.Panel(self.panel, wx.ID_ANY) + self.err_sizer = wx.BoxSizer(wx.VERTICAL) + self.err_sizer.Add(self.head_sizer, 0, wx.EXPAND) + self.errorMessage = wx.StaticText(self.panel, wx.ID_ANY, "") + self.err_sizer.Add(self.errorMessage, 0, wx.EXPAND) + self.main_sizer.Add(self.err_sizer, 0, wx.EXPAND) + self.pluginList = wx.ListCtrl(self.panel, wx.ID_ANY, style=wx.LC_SINGLE_SEL|wx.LC_REPORT|wx.LC_HRULES|wx.LC_SORT_ASCENDING) + self.pluginList.InsertColumn(1, "Name") + self.pluginList.InsertColumn(2, "Autostart") + self.pluginList.InsertColumn(3, "Author") + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._selectPlugin, self.pluginList) + self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._deselectPlugin, self.pluginList) + self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._togglePlugin, self.pluginList) + self.Bind(wx.EVT_LIST_COL_CLICK, self._sort, self.pluginList) + self.main_sizer.Add(self.pluginList, 1, wx.EXPAND) + + self.enableAllBtn = wx.Button(self.panel, wx.ID_ANY, "Enable All") + self.enableBtn = wx.Button(self.panel, wx.ID_ANY, "Enable") + self.disableAllBtn = wx.Button(self.panel, wx.ID_ANY, "Disable All") + self.disableBtn = wx.Button(self.panel, wx.ID_ANY, "Disable") + self.autostartBtn = wx.Button(self.panel, wx.ID_ANY, "Autostart") + self.helpBtn = wx.Button(self.panel, wx.ID_ANY, "Plugin Info") + self.updateBtn = wx.Button(self.panel, wx.ID_ANY, "Update List") + + self.Bind(wx.EVT_BUTTON, self._enableAll, self.enableAllBtn) + self.Bind(wx.EVT_BUTTON, self._enable, self.enableBtn) + self.Bind(wx.EVT_BUTTON, self._disableAll, self.disableAllBtn) + self.Bind(wx.EVT_BUTTON, self._disable, self.disableBtn) + self.Bind(wx.EVT_BUTTON, self._autostart, self.autostartBtn) + self.Bind(wx.EVT_BUTTON, self._help, self.helpBtn) + self.Bind(wx.EVT_BUTTON, self._update, self.updateBtn) + + self.btn_sizer.Add(self.enableBtn, 0, wx.EXPAND) + self.btn_sizer.Add(self.disableBtn, 0, wx.EXPAND) + self.btn_sizer.Add(self.autostartBtn, 0, wx.EXPAND) + self.btn_sizer.Add(self.helpBtn, 0, wx.EXPAND) + + self.btn_sizer2.Add(self.updateBtn, 0, wx.EXPAND) + self.btn_sizer2.Add(self.enableAllBtn, 0, wx.EXPAND) + self.btn_sizer2.Add(self.disableAllBtn, 0, wx.EXPAND) + + self.__disablePluginBtns() + + self.main_sizer.Add(self.btn_sizer, 0, wx.EXPAND) + self.main_sizer.Add(self.btn_sizer2, 0, wx.EXPAND) + + def __disablePluginBtns(self): + self.enableBtn.Disable() + self.disableBtn.Disable() + self.autostartBtn.Disable() + self.helpBtn.Disable() + + def __enablePluginBtns(self): + self.autostartBtn.Label = "Autostart" + self.enableBtn.Enable() + self.disableBtn.Enable() + self.autostartBtn.Enable() + self.helpBtn.Enable() + + def __error(self, errMsg): + self.errorMessage.Label += "\n" + str(errMsg) + self.__doLayout() + + def __clearError(self): + self.errorMessage.Label = "" + self.__doLayout() + + def __checkIdx(self, evt): + if isinstance(evt, int): + return evt + elif self._selectedPlugin is not None: + return self._selectedPlugin + else: + dlg = wx.MessageDialog(None, "You need to select a plugin before you can use this!", 'ERROR', wx.OK) + dlg.ShowModal() + dlg.Destroy() + return None + + def __impPlugin(self, pname): + try: + if "plugins." + pname in sys.modules: + del sys.modules["plugins." + pname]#to ensure that the newly-imported one will be used correctly. No, reload() is not a better way to do this. + mod = __import__("plugins." + pname) + plugin = getattr(mod, pname) + pdata = plugin.Plugin(plugindb, self.parent) + self.available_plugins[pdata.name] = [pname, pdata, pdata.author, pdata.help] + return plugin + + except Exception, e: + self.__error(e) + logger.exception(traceback.format_exc()) + + def __doLayout(self): + self.Freeze() + self.panel.Layout() + self.Fit() + self.Thaw() + + def __pluginSort(self, item1, item2): + return cmp(self.pluginNames[item1], self.pluginNames[item2]) + + #Events + def _selectPlugin(self, evt): + self._selectedPlugin = evt.GetIndex() + self.__enablePluginBtns() + pname = self.pluginList.GetItem(self._selectedPlugin, 0).GetText() + info = self.available_plugins[pname] + + if info[0] in self.enabled_plugins: + self.enableBtn.Disable() + else: + self.disableBtn.Disable() + if self.pluginList.GetItem(self._selectedPlugin, 1).GetText() == "X": + self.autostartBtn.Label = "Disable Autostart" + + self.__doLayout() + self.pluginList.SetItemState(self._selectedPlugin, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED) + + def _deselectPlugin(self, evt): + self.__disablePluginBtns() + self._selectedPlugin = None + + def _togglePlugin(self, evt): + idx = evt.GetIndex() + pname = self.pluginList.GetItem(idx, 0).GetText() + info = self.available_plugins[pname] + + if info[0] in self.enabled_plugins: + self._disable(idx) + else: + self._enable(idx) + + self.pluginList.SetItemState(self._selectedPlugin, 0, wx.LIST_STATE_SELECTED) + + def _enableAll(self, evt): + for pname in self.available_plugins.iterkeys(): + info = self.available_plugins[pname] + if info[0] not in self.enabled_plugins: + idx = self.pluginList.FindItem(-1, pname) + self._enable(idx) + + def _enable(self, evt): + idx = self.__checkIdx(evt) + if idx is None: + return + pname = self.pluginList.GetItem(idx, 0).GetText() + info = self.available_plugins[pname] + info[1].menu_start() + + try: + info[1].plugin_enabled() + except Exception, e: + self.__error(e) + logger.exception(traceback.format_exc()) + self.pluginList.SetItemBackgroundColour(idx, (255,0,0)) + info[1].menu_cleanup() + return + + self.enabled_plugins[info[0]] = info[1] + self.pluginList.SetItemBackgroundColour(idx, (0,255,0)) + self.enableBtn.Disable() + self.disableBtn.Enable() + + def _disableAll(self, evt): + for entry in self.enabled_plugins.keys(): + idx = self.pluginList.FindItem(0, self.enabled_plugins[entry].name) + self._disable(idx) + + def _disable(self, evt): + idx = self.__checkIdx(evt) + if idx is None: + return + pname = self.pluginList.GetItem(idx, 0).GetText() + info = self.available_plugins[pname] + info[1].menu_cleanup() + try: + info[1].plugin_disabled() + del self.enabled_plugins[info[0]] + except Exception, e: + self.__error(e) + logger.exception(traceback.format_exc()) + self.pluginList.SetItemBackgroundColour(idx, (255,0,0)) + return + self.pluginList.SetItemBackgroundColour(idx, (255,255,255)) + self.disableBtn.Disable() + self.enableBtn.Enable() + + def _autostart(self, evt): + idx = self.__checkIdx(evt) + if idx is None: + return + if self.pluginList.GetItem(idx, 1).GetText() == "X": + self.startplugs.remove(self.pluginList.GetItem(idx, 0).GetText()) + self.pluginList.SetStringItem(idx, 1, "") + self.autostartBtn.Label = "Autostart" + else: + self.startplugs.append(self.pluginList.GetItem(idx, 0).GetText()) + self.pluginList.SetStringItem(idx, 1, "X") + self.autostartBtn.Label = "Disable Autostart" + + plugindb.SetList("plugincontroller", "startup_plugins", self.startplugs) + self.__doLayout() + + def _help(self, evt): + if isinstance(evt, int): + idx = evt + elif self._selectedPlugin is not None: + idx = self._selectedPlugin + else: + dlg = wx.MessageDialog(None, "You need to select a plugin before you can use this!", 'ERROR', wx.OK) + dlg.ShowModal() + dlg.Destroy() + return + + pname = self.pluginList.GetItem(idx, 0).GetText() + info = self.available_plugins[pname] + + msg = "Author(s):\t" + info[2] + "\n\n" + info[3] + + dlg = wx.MessageDialog(None, msg, 'Plugin Information: ' + pname, wx.OK) + dlg.ShowModal() + dlg.Destroy() + + def _update(self, evt): + self.__clearError() + self._disableAll(None) + self.available_plugins = {} + self.errorMessage.Label = "" + self.pluginList.DeleteAllItems() + self.pluginNames = [] + + list_of_plugin_dir = os.listdir(dir_struct["plugins"]) + for p in list_of_plugin_dir: + if p[:2].lower()=="xx" and p[-3:]==".py": + self.__impPlugin(p[:-3]) + + i = 0 + for plugname, info in self.available_plugins.iteritems(): + self.pluginNames.append(plugname) + idx = self.pluginList.InsertStringItem(self.pluginList.GetItemCount(), plugname) + self.pluginList.SetStringItem(idx, 2, info[2]) + if plugname in self.startplugs: + self.pluginList.SetStringItem(idx, 1, "X") + self._enable(idx) + self.pluginList.SetItemData(idx, i) + i += 1 + self.pluginList.SetColumnWidth(0, wx.LIST_AUTOSIZE) + self.__doLayout() + self.__disablePluginBtns() + + def _close(self, evt): + self.Hide() + + def _sort(self, evt): + self.pluginList.SortItems(self.__pluginSort)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/_settings.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,315 @@ +# Copyright (C) 2000-2001 The OpenRPG Project +# +# openrpg-dev@lists.sourceforge.net +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +# -- +# +# File: orpg_settings.py +# Author: Dj Gilcrease +# Maintainer: +# Version: +# $Id: orpg_settings.py,v 1.51 2007/07/15 14:25:12 digitalxero Exp $ +# +# Description: classes for orpg settings +# + +import sys +import os + +import wx +import wx.grid + +from orpg.orpgCore import open_rpg +from orpg.dirpath import dir_struct +from orpg.tools.rgbhex import RGBHex +from orpg.tools.settings import settings +from orpg.tools.validate import validate + +class SettingsWindow(wx.Dialog): + def __init__(self, parent): + wx.Dialog.__init__(self, parent, wx.ID_ANY, "OpenRPG Preferences", + wx.DefaultPosition, size=wx.Size(-1,-1), + style=wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CAPTION) + self.Freeze() + + self.chat = open_rpg.get_component('chat') + self.changes = [] + self.SetMinSize((545,500)) + self.tabber = orpgTabberWnd(self, style=FNB.FNB_NO_X_BUTTON) + self.build_gui() + self.tabber.SetSelection(0) + winsizer = wx.BoxSizer(wx.VERTICAL) + sizer = wx.BoxSizer(wx.HORIZONTAL) + sizer.Add(wx.Button(self, wx.ID_OK, "OK"), 1, wx.EXPAND) + sizer.Add(wx.Size(10,10)) + sizer.Add(wx.Button(self, wx.ID_CANCEL, "Cancel"), 1, wx.EXPAND) + winsizer.Add(self.tabber, 1, wx.EXPAND) + winsizer.Add(sizer, 0, wx.EXPAND | wx.ALIGN_BOTTOM) + self.winsizer = winsizer + self.SetSizer(self.winsizer) + self.SetAutoLayout(True) + self.Fit() + self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK) + self.Thaw() + + def on_size(self,evt): + (w,h) = self.GetClientSizeTuple() + self.winsizer.SetDimension(0,0,w,h-25) + + def build_gui(self): + validate.config_file('settings.xml', 'default_settings.xml') + filename = dir_struct['user'] + 'settings.xml' + + for c in settings._settings.getroot().getchildren(): + self.build_window(c, self.tabber) + + def build_window(self, el, parent_wnd): + if el.tag == 'tab': + temp_wnd = self.do_tab_window(el, parent_wnd) + + return temp_wnd + + def do_tab_window(self, el, parent_wnd): + tab_type = el.get('type') + name = el.get('name') + + if tab_type == 'grid': + temp_wnd = self.do_grid_tab(el, parent_wnd) + parent_wnd.AddPage(temp_wnd, name, False) + elif tab_type == 'tab': + temp_wnd = orpgTabberWnd(parent_wnd, style=FNB.FNB_NO_X_BUTTON) + + for c in el.getchildren(): + if c.tag == 'tab': + self.do_tab_window(c, temp_wnd) + temp_wnd.SetSelection(0) + parent_wnd.AddPage(temp_wnd, name, False) + elif tab_type == 'text': + temp_wnd = wx.TextCtrl(parent_wnd, wx.ID_ANY) + parent_wnd.AddPage(temp_wnd, name, False) + else: + temp_wnd = None + return temp_wnd + + def do_grid_tab(self, el, parent_wnd): + tab_settings = [] + + for c in el.getchildren(): + tab_settings.append([c.tag, c.get('value'), c.get('options'), + c.get('help')]) + temp_wnd = settings_grid(parent_wnd, tab_settings, self.changes) + return temp_wnd + + def onOk(self, evt): + #This will write the settings back to the XML + self.session = open_rpg.get_component("session") + tabbedwindows = open_rpg.get_component("tabbedWindows") + new = [] + for wnd in tabbedwindows: + try: + style = wnd.GetWindowStyleFlag() + new.append(wnd) + except: + pass + tabbedwindows = new + open_rpg.add_component("tabbedWindows", tabbedwindows) + rgbconvert = RGBHex() + + for i in xrange(0,len(self.changes)): + settings.set(str(self.changes[i][0]), self.changes[i][1]) + top_frame = open_rpg.get_component('frame') + + if self.changes[i][0] == 'bgcolor' or self.changes[i][0] == 'textcolor': + self.chat.chatwnd.SetPage(self.chat.ResetPage()) + self.chat.chatwnd.scroll_down() + if settings.get('ColorTree') == '1': + top_frame.tree.SetBackgroundColour(settings.get('bgcolor')) + top_frame.tree.SetForegroundColour(settings.get('textcolor')) + top_frame.tree.Refresh() + top_frame.players.SetBackgroundColour(settings.get('bgcolor')) + top_frame.players.SetForegroundColour(settings.get('textcolor')) + top_frame.players.Refresh() + else: + top_frame.tree.SetBackgroundColour('white') + top_frame.tree.SetForegroundColour('black') + top_frame.tree.Refresh() + top_frame.players.SetBackgroundColour('white') + top_frame.players.SetForegroundColour('black') + top_frame.players.Refresh() + + if self.changes[i][0] == 'ColorTree': + if self.changes[i][1] == '1': + top_frame.tree.SetBackgroundColour(settings.get('bgcolor')) + top_frame.tree.SetForegroundColour(settings.get('textcolor')) + top_frame.tree.Refresh() + top_frame.players.SetBackgroundColour(settings.get('bgcolor')) + top_frame.players.SetForegroundColour(settings.get('textcolor')) + top_frame.players.Refresh() + else: + top_frame.tree.SetBackgroundColour('white') + top_frame.tree.SetForegroundColour('black') + top_frame.tree.Refresh() + top_frame.players.SetBackgroundColour('white') + 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() + + 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]) + + if self.changes[i][0] == 'player': + self.session.name = 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\ + (settings.get('TabTheme') == 'customflat' or\ + settings.get('TabTheme') == 'customslant')) or\ + (self.changes[i][0] == 'TabGradientFrom' and\ + (settings.get('TabTheme') == 'customflat' or\ + settings.get('TabTheme') == 'customslant')) or\ + (self.changes[i][0] == 'TabGradientTo' and\ + (settings.get('TabTheme') == 'customflat' or\ + settings.get('TabTheme') == 'customslant')): + + gfrom = settings.get('TabGradientFrom') + (fred, fgreen, fblue) = rgbconvert.rgb_tuple(gfrom) + + gto = settings.get('TabGradientTo') + (tored, togreen, toblue) = rgbconvert.rgb_tuple(gto) + + tabtext = settings.get('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 settings.get('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)) + wnd.SetNonActiveTabTextColour(wx.Color(tred, tgreen, tblue)) + wnd.Refresh() + + if self.changes[i][0] == 'TabBackgroundGradient': + for wnd in tabbedwindows: + red, green, blue = rgbconvert.rgb_tuple(self.changes[i][1]) + wnd.SetTabAreaColour(wx.Color(red, green, blue)) + wnd.Refresh() + settings.save() + 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]) + +class settings_grid(wx.grid.Grid): + """grid for gen info""" + def __init__(self, parent, grid_settings, changed=list()): + wx.grid.Grid.__init__(self, parent, wx.ID_ANY, + style=wx.SUNKEN_BORDER|wx.WANTS_CHARS) + + self.setting_data = changed + self.Bind(wx.EVT_SIZE, self.on_size) + self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.on_cell_change) + self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_left_click) + self.CreateGrid(len(grid_settings),3) + self.SetRowLabelSize(0) + self.SetColLabelValue(0,"Setting") + self.SetColLabelValue(1,"Value") + self.SetColLabelValue(2,"Available Options") + self.settings = grid_settings + for i in range(len(grid_settings)): + self.SetCellValue(i, 0, grid_settings[i][0]) + self.SetCellValue(i, 1, grid_settings[i][1]) + + if grid_settings[i][1] and grid_settings[i][1][0] == '#': + self.SetCellBackgroundColour(i, 1, grid_settings[i][1]) + self.SetCellValue(i, 2, grid_settings[i][2]) + + def on_left_click(self,evt): + row = evt.GetRow() + col = evt.GetCol() + if col == 2: + return + elif col == 0: + name = self.GetCellValue(row,0) + str = self.settings[row][3] + msg = wx.MessageBox(str,name) + return + elif col == 1: + setting = self.GetCellValue(row,0) + value = self.GetCellValue(row,1) + if value and value[0] == '#': + hexcolor = orpg.tools.rgbhex.RGBHex().do_hex_color_dlg(self) + if hexcolor: + self.SetCellValue(row,2, hexcolor) + self.SetCellBackgroundColour(row,1,hexcolor) + self.Refresh() + setting = self.GetCellValue(row,0) + self.setting_data.append([setting, hexcolor]) + else: + evt.Skip() + + def on_cell_change(self,evt): + row = evt.GetRow() + col = evt.GetCol() + if col != 1: + return + setting = self.GetCellValue(row,0) + value = self.GetCellValue(row,1) + self.setting_data.append([setting, value]) + + def get_h(self): + (w,h) = self.GetClientSizeTuple() + rows = self.GetNumberRows() + minh = 0 + for i in range (0,rows): + minh += self.GetRowSize(i) + minh += 120 + return minh + + def on_size(self,evt): + (w,h) = self.GetClientSizeTuple() + cols = self.GetNumberCols() + col_w = w/(cols) + for i in range(0,cols): + self.SetColSize(i,col_w) + self.Refresh()
--- a/orpg/ui/util/dlg/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/util/dlg/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,3 +1,4 @@ -__all__ = ['MultiCheckBoxDlg'] +__all__ = ['MultiCheckBoxDlg', 'ProgressDlg'] -from ._checkbox import MultiCheckBoxDlg \ No newline at end of file +from ._checkbox import MultiCheckBoxDlg +from ._progress import ProgressDlg \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/util/dlg/_progress.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,26 @@ +import wx + +from orpg.tools.decorators import debugging + +class ProgressDlg(wx.Dialog): + @debugging + def __init__(self, parent, title="", text="", range=10): + wx.Dialog.__init__(self, parent, -1, title, size= wx.Size(200,75)) + self.sizer = wx.BoxSizer(wx.VERTICAL) + self.text = wx.StaticText(self, -1, text) + self.gauge = wx.Gauge(self,-1,range) + self.sizer.Add(self.text,1,wx.ALIGN_CENTER | wx.EXPAND) + self.sizer.Add(self.gauge,1,wx.ALIGN_CENTER | wx.EXPAND) + (w,h) = self.GetClientSizeTuple() + self.sizer.SetDimension(10,10,w-20,h-20) + + @debugging + def Update(self,pos,text=None): + self.gauge.SetValue(pos) + if text: + self.text.SetLabel(text) + + def __enter__(self, *args, **kwargs): + return self + def __exit__(self, *args, **kwargs): + self.Destroy() \ No newline at end of file
--- a/orpg/ui/util/misc/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/util/misc/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,3 +1,4 @@ -__all__ = ['create_masked_button'] +__all__ = ['create_masked_button', 'ImageHelper'] -from ._buttons import create_masked_button \ No newline at end of file +from ._buttons import create_masked_button +from ._img import ImageHelper \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/util/misc/_img.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,39 @@ +import urllib + +import wx + +from orpg.tools.decorators import debugging + +class ImageHelper(object): + img_types = {"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} + + @debugging + def __init__(self): + pass + + @debugging + def load_url(self, path): + 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 + return img + + @debugging + def load_file(self, path): + img_type = self.get_type(path) + return wx.Bitmap(path, img_type) + + @debugging + def get_type(self, file_name): + ext = file_name.split('.')[-1].lower() + img_type = 0 + img_type = self.img_types.get(ext) + return img_type \ No newline at end of file
--- a/orpg/ui/util/tab/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/util/tab/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,3 @@ +__all__ = ['TabberWindow'] + +from ._tabber import TabberWindow \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/util/tab/_tabber.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,80 @@ +import wx +try: + import wx.lib.agw.flatnotebook as FNB +except ImportError: + import orpg.external.agw.flatnotebook as FNB + +from orpg.orpgCore import open_rpg +from orpg.tools.rgbhex import RGBHex +from orpg.tools.settings import settings +from orpg.tools.decorators import debugging + +class TabberWindow(FNB.FlatNotebook): + @debugging + def __init__(self, parent, closeable=False, size=wx.DefaultSize, + style=False): + nbstyle = FNB.FNB_HIDE_ON_SINGLE_TAB|FNB.FNB_BACKGROUND_GRADIENT + FNB.FlatNotebook.__init__(self, parent, -1, size=size, style=nbstyle) + rgbcovert = RGBHex() + tabtheme = settings.get('TabTheme') + tabtext = settings.get('TabTextColor') + (tred, tgreen, tblue) = rgbcovert.rgb_tuple(tabtext) + tabbedwindows = open_rpg.get_component("tabbedWindows") + 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} + nbstyle |= theme_dict[tabtheme] + if style: + nbstyle |= style + self.SetWindowStyleFlag(nbstyle) + + #Tas - sirebral. Planned changes to the huge statement below. + if tabtheme == 'slanted&aqua': + self.SetGradientColourTo(wx.Color(0, 128, 255)) + self.SetGradientColourFrom(wx.WHITE) + + elif tabtheme == 'slanted&bw': + self.SetGradientColourTo(wx.WHITE) + self.SetGradientColourFrom(wx.WHITE) + + elif tabtheme == 'flat&aqua': + self.SetGradientColourFrom(wx.Color(0, 128, 255)) + self.SetGradientColourTo(wx.WHITE) + self.SetNonActiveTabTextColour(wx.BLACK) + + elif tabtheme == 'flat&bw': + self.SetGradientColourTo(wx.WHITE) + self.SetGradientColourFrom(wx.WHITE) + self.SetNonActiveTabTextColour(wx.BLACK) + + elif tabtheme == 'customflat': + gfrom = settings.get('TabGradientFrom') + (red, green, blue) = rgbcovert.rgb_tuple(gfrom) + self.SetGradientColourFrom(wx.Color(red, green, blue)) + + gto = settings.get('TabGradientTo') + (red, green, blue) = rgbcovert.rgb_tuple(gto) + self.SetGradientColourTo(wx.Color(red, green, blue)) + self.SetNonActiveTabTextColour(wx.Color(tred, tgreen, tblue)) + + elif tabtheme == 'customslant': + gfrom = settings.get('TabGradientFrom') + (red, green, blue) = rgbcovert.rgb_tuple(gfrom) + self.SetGradientColourFrom(wx.Color(red, green, blue)) + + gto = settings.get('TabGradientTo') + (red, green, blue) = rgbcovert.rgb_tuple(gto) + self.SetGradientColourTo(wx.Color(red, green, blue)) + self.SetNonActiveTabTextColour(wx.Color(tred, tgreen, tblue)) + + tabbg = settings.get('TabBackgroundGradient') + (red, green, blue) = rgbcovert.rgb_tuple(tabbg) + self.SetTabAreaColour(wx.Color(red, green, blue)) + self.Refresh() \ No newline at end of file
--- a/orpg/ui/util/text/__init__.py Thu Mar 25 15:48:49 2010 -0600 +++ b/orpg/ui/util/text/__init__.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,3 @@ +__all__ = ['MultiTextEntry'] + +from ._multi import MultiTextEntry \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/orpg/ui/util/text/_multi.py Thu Mar 25 17:56:48 2010 -0600 @@ -0,0 +1,49 @@ +import wx + +from orpg.tools.decorators import debugging + +class MultiTextEntry(wx.Dialog): + """ a dialog that takes two lists (labels and values) and creates a + 'label: value' style text edit control for each node in the dict""" + @debugging + def __init__(self, parent, opts, caption, pos=wx.DefaultPosition): + wx.Dialog.__init__(self, parent, wx.ID_ANY, caption, pos, + wx.DefaultSize) + num = len(tlist) + sizers = {'ctrls': wx.FlexGridSizer(num, 2, 5, 0), + 'buttons': wx.BoxSizer(wx.HORIZONTAL)} + + add_list = [] + ctrls = {} + + for name, value in opts.iteritems(): + add_list.append((wx.StaticText(self, wx.ID_ANY, name + ": "), 0, + wx.ALIGN_CENTER_VERTICAL)) + ctrls[name] = wx.TextCtrl(self, wx.ID_ANY, value) + add_list.append((ctrls[i], 1, wx.EXPAND)) + + self.ctrls = ctrls + sizers['ctrls'].AddMany(add_list) + sizers['ctrls'].AddGrowableCol(1) + sizers['buttons'].Add(wx.Button(self, wx.ID_OK, "OK"), 1, wx.EXPAND) + sizers['buttons'].Add(wx.Size(10,10)) + sizers['buttons'].Add(wx.Button(self, wx.ID_CANCEL, "Cancel"), 1, + wx.EXPAND) + width = 300 + w, h = ctrls[0].GetSizeTuple() + h = h + 5 + height = ((num)*h)+35 + self.SetClientSizeWH(width,height) + sizers['ctrls'].SetDimension(10, 5, width-20, num*30) + sizers['buttons'].SetDimension(10, (num*h)+5, width-20, 25) + self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK) + + @debugging + def on_ok(self,evt): + for i in range(len(self.ctrls)): + self.vlist[i] = self.ctrls[i].GetValue() + self.EndModal(wx.ID_OK) + + @debugging + def get_values(self): + return self.ctrls \ No newline at end of file
--- a/plugins/xxbonuses.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxbonuses.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,23 +1,26 @@ +import types -import orpg.pluginhandler +import wx + + +#This is a bad import from orpg.mapper.miniatures_handler import * -from orpg.orpgCore import * -from orpg.orpg_windows import * + +from orpg.pluginhandler import PluginHandler +from orpg.orpgCore import open_rpg from orpg.mapper.base_handler import base_layer_handler -import wx -import types from orpg.chat.chatwnd import compiled_simple_arithmetic_regex from orpg.chat.commands import command_args_parser from orpg.gametree.nodehandlers.core import node_handler -class Bonus: +class Bonus(object): def __init__(self, number, path, bonus_type): self.number = int(number) # amount added (can be negative) self.path = path # fullpath or namespace path (not leaf) self.type = bonus_type # arbitrary string or empty -class Effect: +class Effect(object): def __init__(self, name, desc, namespace_name, expire, bonus_list): self.name = name self.desc = desc @@ -30,12 +33,12 @@ self.effects.append(effect) for bonus in effect.bonus_list: self.add_bonus(effect.namespace_name, bonus) - + def delete_effect(self, effect): for bonus in effect.bonus_list: self.delete_bonus(effect.namespace_name, bonus) self.effects.remove(effect) - + def add_bonus(self, namespace_name, bonus): key = (namespace_name, bonus.path) if key in self.bonus_map: @@ -43,18 +46,19 @@ bonus_list.append(bonus) else: self.bonus_map[key]=[bonus] - + def delete_bonus(self, namespace_name, bonus): key = (namespace_name, bonus.path) if key in self.bonus_map: bonus_list = self.bonus_map[key] bonus_list.remove(bonus) -# overrides the existing chat method +# overrides the existing chat method def my_handle_adding_bonuses(self, value, handler): if compiled_simple_arithmetic_regex.match(value): newint = eval(value) - fullpath, v, namespace_name, namespace_path = open_rpg.get_component('tree').get_path_data(handler.mytree_node) + fullpath, v, namespace_name, namespace_path =\ + open_rpg.get_component('tree').get_path_data(handler.mytree_node) if namespace_name: key = (namespace_name, namespace_path) else: @@ -64,7 +68,8 @@ for bonus in self.bonus_map[key]: if bonus.type: if bonus.type in typed_bonuses: - typed_bonuses[bonus.type] = max(bonus.number, typed_bonuses[bonus.type]) + typed_bonuses[bonus.type] =\ + max(bonus.number, typed_bonuses[bonus.type]) else: typed_bonuses[bonus.type] = bonus.number else: @@ -73,11 +78,11 @@ newint += number value = str(newint) return value - + -class Plugin(orpg.pluginhandler.PluginHandler): +class Plugin(PluginHandler): def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) self.name = 'Bonuses and Effects' self.author = 'David' self.help = """Allows on-the-fly temporary modification of character sheet values. @@ -89,20 +94,27 @@ c.bonus_map = {} c.effects = [] self.old_handle_adding_bonuses = c.handle_adding_bonuses - c.handle_adding_bonuses = types.MethodType(my_handle_adding_bonuses, c, c.__class__) + c.handle_adding_bonuses = types.MethodType(my_handle_adding_bonuses, c, + c.__class__) c.add_bonus = types.MethodType(add_bonus, c, c.__class__) c.delete_bonus = types.MethodType(delete_bonus, c, c.__class__) c.add_effect = types.MethodType(add_effect, c, c.__class__) c.delete_effect = types.MethodType(delete_effect, c, c.__class__) - self.plugin_addcommand('/bonus', self.on_bonus, '/bonus number target [type]') - self.plugin_addcommand('/effect', self.on_effect, '/effect name desc= alias= expire= number= path= [type=] number= path= [type=]') + self.plugin_addcommand('/bonus', self.on_bonus, + '/bonus number target [type]') + self.plugin_addcommand('/effect', self.on_effect, + '/effect name desc= alias= expire= number= '\ + 'path= [type=] number= path= [type=]') self.plugin_commandalias('/b', '/bonus') - self.plugin_addcommand('/view_effects', self.on_view_effects, 'bring up the effects view (use this to delete effects)') + self.plugin_addcommand('/view_effects', self.on_view_effects, + 'bring up the effects view (use this to '\ + 'delete effects)') self.plugin_commandalias('/ve', '/view_effects') # load effects from last session db_effects_list = self.plugindb.GetList("xxbonuses", "effect_list", []) for db_effect_data in db_effects_list: - # if the ordering of these data is messed with you will break old saved data + # if the ordering of these data is messed with you will + #break old saved data name = db_effect_data[0] desc = db_effect_data[1] namespace_name = db_effect_data[2] @@ -114,8 +126,11 @@ path = b[1] bonus_type = b[2] bonus_list.append(Bonus(number, path, bonus_type)) - open_rpg.get_component("chat").add_effect(Effect(name, desc, namespace_name, expire, bonus_list)) - + open_rpg.get_component("chat").add_effect(Effect(name, desc, + namespace_name, + expire, + bonus_list)) + def plugin_disabled(self): c = open_rpg.get_component("chat") #save list of effects @@ -124,7 +139,8 @@ db_bonus_list = [] for bonus in effect.bonus_list: db_bonus_list.append([bonus.number, bonus.path, bonus.type]) - db_effect_data = [effect.name, effect.desc, effect.namespace_name, effect.expire, db_bonus_list] + db_effect_data = [effect.name, effect.desc, effect.namespace_name, + effect.expire, db_bonus_list] db_effects_list.append(db_effect_data) self.plugindb.SetList("xxbonuses", "effect_list", db_effects_list) c.handle_adding_bonuses = self.old_handle_adding_bonuses @@ -143,17 +159,21 @@ def on_bonus(self, cmdargs): values, key_values = command_args_parser(cmdargs) if len(values) < 2: - open_rpg.get_component("chat").InfoPost("/effect: Not enough params passed.") + open_rpg.get_component("chat").InfoPost("/effect: Not enough "\ + "params passed.") return try: number = int(values[0]) except: - open_rpg.get_component("chat").InfoPost("First parameter must be an integer.") + open_rpg.get_component("chat").InfoPost("First parameter must "\ + "be an integer.") return path = values[1] - handler = open_rpg.get_component('tree').get_handler_by_path(path, open_rpg.get_component("chat").chat_cmds.context) + handler = open_rpg.get_component('tree').get_handler_by_path(path, + open_rpg.get_component("chat").chat_cmds.context) if handler is None: - open_rpg.get_component("chat").InfoPost("Second parameter must reference a node.") + open_rpg.get_component("chat").InfoPost("Second parameter must "\ + "reference a node.") return ## value = handler.get_value() ## try: @@ -165,11 +185,14 @@ bonus_type = key_values['type'] else: bonus_type = '' - fullpath, v, namespace_name, namespace_path = open_rpg.get_component('tree').get_path_data(handler.mytree_node) + fullpath, v, namespace_name, namespace_path =\ + open_rpg.get_component('tree').get_path_data(handler.mytree_node) if namespace_name: - effect = Effect("", "", namespace_name, "", [Bonus(number, namespace_path, bonus_type)]) + effect = Effect("", "", namespace_name, "", + [Bonus(number, namespace_path, bonus_type)]) else: - effect = Effect("", "", "", "", [Bonus(number, fullpath, bonus_type)]) + effect = Effect("", "", "", "", [Bonus(number, fullpath, + bonus_type)]) open_rpg.get_component("chat").add_effect(effect) def on_effect(self, cmdargs): @@ -189,13 +212,16 @@ # determine namespace_name from one of various sources if 'alias' in key_values: namespace_name = key_values['alias'].lower().strip() - if namespace_name != "" and open_rpg.get_component('tree').get_namespace_by_name(namespace_name) is None: + if namespace_name != "" and\ + open_rpg.get_component('tree').\ + get_namespace_by_name(namespace_name) is None: chat.InfoPost("/effect: the alias passed was not a namespace.") return else: context = chat.chat_cmds.context if isinstance(context.namespace_hint, node_handler): - namespace_name = open_rpg.get_component('tree').get_namespace_name(context.namespace_hint.mytree_node) + namespace_name = open_rpg.get_component('tree').\ + get_namespace_name(context.namespace_hint.mytree_node) elif isinstance(context.namespace_hint, (str, unicode)): namespace_name = context.namespace_hint.lower().strip() else: @@ -218,14 +244,16 @@ if not isinstance(types, list): types = [types] if len(numbers) != len(types): - chat.InfoPost("/effect: number and type params must be matched if any type is given.") + chat.InfoPost("/effect: number and type params must be "\ + "matched if any type is given.") return else: types = [''] * len(numbers) bonus_list = [] for i in range(len(numbers)): # check validity of path / replace with fullpath (not leaf) - handler = open_rpg.get_component('tree').get_handler_by_path(paths[i], ParserContext(namespace_name)) + handler = open_rpg.get_component('tree').\ + get_handler_by_path(paths[i], ParserContext(namespace_name)) if handler is None: chat.InfoPost("Path parameters must be indexed nodes.") return @@ -235,7 +263,8 @@ ## except: ## chat.InfoPost("Value of node to receive bonus must be an integer.") ## return - fullpath, v, n, namespace_path = open_rpg.get_component('tree').get_path_data(handler.mytree_node) + fullpath, v, n, namespace_path = open_rpg.get_component('tree').\ + get_path_data(handler.mytree_node) if namespace_name: path = namespace_path else: @@ -271,8 +300,12 @@ self.listbox.SetColumnWidth(0, 80) self.effects = [] for effect in open_rpg.get_component("chat").effects: - bonus_description = ', '.join([str(bonus.number)+" "+bonus.path for bonus in effect.bonus_list]) - self.listbox.Append((effect.name, effect.desc, effect.namespace_name, effect.expire, bonus_description)) + bonus_description = ', '.join([str(bonus.number)+\ + " "+bonus.path\ + for bonus in effect.bonus_list]) + self.listbox.Append((effect.name, effect.desc, + effect.namespace_name, effect.expire, + bonus_description)) self.effects.append(effect) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.listbox, 1, wx.EXPAND) @@ -292,7 +325,9 @@ self.listbox.DeleteItem(index) def on_delete_all(self, evt): - dlg = wx.MessageDialog(self, "Are you sure you want to delete all bonuses and effects?","Delete All",wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) + dlg = wx.MessageDialog(self, "Are you sure you want to delete all "\ + "bonuses and effects?", "Delete All", + wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() != wx.ID_YES: return open_rpg.get_component("chat").effects = []
--- a/plugins/xxcherrypy.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxcherrypy.py Thu Mar 25 17:56:48 2010 -0600 @@ -4,21 +4,21 @@ import urllib2 from xml.dom.minidom import parseString -import orpg.plugindb # VEG -import orpg.pluginhandler -from orpg.orpgCore import * -from orpg.orpg_wx import * +import wx + +from orpg.pluginhandler import PluginHandler +from orpg.orpgCore import open_rpg from cherrypy.cpg import server # VEG (march 21, 2007): Now remembers your last web server on/off setting -class Plugin(orpg.pluginhandler.PluginHandler): +class Plugin(PluginHandler): # Initialization subroutine. # # !self : instance of self # !openrpg : instance of the the base openrpg control def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) # The Following code should be edited to contain the proper information self.name = 'CherryPy Web Server'
--- a/plugins/xxgsc.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxgsc.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,20 +1,18 @@ import os -from orpg.orpg_wx import * import random -import orpg.pluginhandler +import wx + +from orpg.pluginhandler import PluginHandler from orpg.tools.settings import settings - -ID_ROLL = wx.NewId() - -class Plugin(orpg.pluginhandler.PluginHandler): +class Plugin(PluginHandler): # Initialization subroutine. # # !self : instance of self # !chat : instance of the chat window to write to def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) self.name = 'Game Status Controller' self.author = 'Woody, updated by mDuo13' @@ -79,19 +77,26 @@ self.old_idle = settings.get('IdleStatusAlias') wx.StaticText(self.panel, -1, "AC:", wx.Point(0, 5)) - self.ac = wx.SpinCtrl(self.panel, ID_ROLL, "", wx.Point(18, 0), wx.Size(45, -1), min = -100, max = 100, initial = 10) + self.ac = wx.SpinCtrl(self.panel, wx.ID_ANY, "", wx.Point(18, 0), + wx.Size(45, -1), min=-100, max=100, initial=10) self.ac.SetValue(10) wx.StaticText(self.panel, -1, "/", wx.Point(136, 5)) - self.max_hp = wx.SpinCtrl(self.panel, ID_ROLL, "", wx.Point(144, 0), wx.Size(48, -1), min = -999, max = 999, initial = 10) + self.max_hp = wx.SpinCtrl(self.panel, wx.ID_ANY, "", wx.Point(144, 0), + wx.Size(48, -1), min=-999, max=999, initial=10) self.max_hp.SetValue(10) wx.StaticText(self.panel, -1, "HP:", wx.Point(65, 5)) - self.hp = wx.SpinCtrl(self.panel, ID_ROLL, "", wx.Point(83, 0), wx.Size(48, -1), min = -999, max = 999, initial = 10) + self.hp = wx.SpinCtrl(self.panel, wx.ID_ANY, "", wx.Point(83, 0), + wx.Size(48, -1), min=-999, max=999, initial=10) self.hp.SetValue(10) - self.Bind(wx.EVT_SPINCTRL, self.SetStatus, id=ID_ROLL) - self.Bind(wx.EVT_TEXT, self.SetStatus, id=ID_ROLL) + self.Bind(wx.EVT_SPINCTRL, self.SetStatus, self.ac) + self.Bind(wx.EVT_SPINCTRL, self.SetStatus, self.max_hp) + self.Bind(wx.EVT_SPINCTRL, self.SetStatus, self.hp) + self.Bind(wx.EVT_TEXT, self.SetStatus, self.ac) + self.Bind(wx.EVT_TEXT, self.SetStatus, self.max_hp) + self.Bind(wx.EVT_TEXT, self.SetStatus, self.hp) self.Bind(wx.EVT_MENU, self.TimeToQuit, id=wx.ID_EXIT) self.Bind(wx.EVT_CLOSE, self._close) self.SetStatus(None)
--- a/plugins/xxminimenu.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxminimenu.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,12 +1,13 @@ - -import orpg.pluginhandler -from orpg.mapper.miniatures_handler import * -from orpg.orpgCore import * -from orpg.orpg_windows import * -from orpg.mapper.base_handler import base_layer_handler import wx import types +#This is a bad import fix it +from orpg.mapper.miniatures_handler import * + +from orpg.orpgCore import open_rpg +from orpg.pluginhandler import PluginHandler +from orpg.mapper.base_handler import base_layer_handler + # these functions will be added to the OpenRPG miniatures_handler, some override existing methods def my_on_node_menu_item(self, evt): menuid = evt.GetId() @@ -82,10 +83,10 @@ self.canvas.Unbind(wx.EVT_MENU, id=self.menuid0+i) self.build_menu() - -class Plugin(orpg.pluginhandler.PluginHandler): + +class Plugin(PluginHandler): def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) self.name = 'Mini Menu' self.author = 'David' self.help = """add context menu and double-click popup to map minis. @@ -105,7 +106,7 @@ m.bind_100_ids = types.MethodType(my_bind_100_ids, m, m.__class__) m.unbind_100_ids = types.MethodType(my_unbind_100_ids, m, m.__class__) m.bind_100_ids() - + def plugin_disabled(self): # call unbind, put back old methods, delete methods that didn't exist before m = open_rpg.get_component("map").layer_handlers[2] @@ -120,5 +121,5 @@ del m.menuid0 - +
--- a/plugins/xxminitooltip.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxminitooltip.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,19 +1,21 @@ +import types -import orpg.pluginhandler +import wx + +#This is a bad import fix it from orpg.mapper.miniatures_handler import * -from orpg.orpgCore import * -from orpg.orpg_windows import * + +from orpg.pluginhandler import PluginHandler +from orpg.orpgCore import open_rpg from orpg.mapper.base_handler import base_layer_handler -import wx -import types def my_get_mini_tooltip(self, mini_list): return ", ".join([mini.label for mini in mini_list]) - + -class Plugin(orpg.pluginhandler.PluginHandler): +class Plugin(PluginHandler): def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) self.name = 'Mini Tooltip' self.author = 'David' self.help = """Add a tooltip displaying the name of the mini. For OpenRPG 1.8.0+""" @@ -22,7 +24,7 @@ m = open_rpg.get_component("map").layer_handlers[2] self.old_get_mini_tooltip = m.get_mini_tooltip m.get_mini_tooltip = types.MethodType(my_get_mini_tooltip, m, m.__class__) - + def plugin_disabled(self): m = open_rpg.get_component("map").layer_handlers[2] m.get_mini_tooltip = self.old_get_mini_tooltip
--- a/plugins/xxtextcompletion.py Thu Mar 25 15:48:49 2010 -0600 +++ b/plugins/xxtextcompletion.py Thu Mar 25 17:56:48 2010 -0600 @@ -1,14 +1,15 @@ +import wx -import orpg.pluginhandler +#this is a bad import fix it from orpg.mapper.miniatures_handler import * -from orpg.orpgCore import * -from orpg.orpg_windows import * + +from orpg.orpgCore import open_rpg +from orpg.pluginhandler import PluginHandler from orpg.mapper.base_handler import base_layer_handler -import wx -class Plugin(orpg.pluginhandler.PluginHandler): +class Plugin(PluginHandler): def __init__(self, plugindb, parent): - orpg.pluginhandler.PluginHandler.__init__(self, plugindb, parent) + PluginHandler.__init__(self, plugindb, parent) self.name = 'Text Completion' self.author = 'David' self.help = """Text completion will be based on selecting a node name from the tree (not other player's names). @@ -17,10 +18,10 @@ def plugin_enabled(self): open_rpg.get_component('chat').get_completion_word_set = self.get_node_names_set - + def plugin_disabled(self): open_rpg.get_component('chat').get_completion_word_set = open_rpg.get_component('chat').get_player_set - + def get_node_names_set(self): # could take into account the selected alias # could calculate once instead of re-calculating every time
--- a/start_client.py Thu Mar 25 15:48:49 2010 -0600 +++ b/start_client.py Thu Mar 25 17:56:48 2010 -0600 @@ -9,7 +9,12 @@ import pyver pyver.checkPyVersion() -from orpg.orpg_wx import * +try: + import wx + WXLOADED = True +except ImportError: + WXLOADED = False + import orpg.main from orpg.tools.orpg_log import logger
--- a/start_server_gui.py Thu Mar 25 15:48:49 2010 -0600 +++ b/start_server_gui.py Thu Mar 25 17:56:48 2010 -0600 @@ -6,7 +6,11 @@ import pyver pyver.checkPyVersion() -from orpg.orpg_wx import * +try: + import wx + WXLOADED = True +except ImportError: + WXLOADED = False if __name__ == "__main__": os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))