diff options
author | olpc user <olpc@xo-74-32-56.localdomain> | 2012-06-16 18:18:25 (GMT) |
---|---|---|
committer | olpc user <olpc@xo-74-32-56.localdomain> | 2012-06-16 18:18:25 (GMT) |
commit | 1c8cf1f18784f9db7d5fa980c71ed70297e2c548 (patch) | |
tree | f6b0f671fa23fb6d71536c7d0937836cc10ec49d /pynxc/waxy | |
parent | 351ced843ead1dee29fb59f805815a60f3e203a6 (diff) |
Added pynxc
Diffstat (limited to 'pynxc/waxy')
129 files changed, 9345 insertions, 0 deletions
diff --git a/pynxc/waxy/.DS_Store b/pynxc/waxy/.DS_Store Binary files differnew file mode 100644 index 0000000..e9b3bb0 --- /dev/null +++ b/pynxc/waxy/.DS_Store diff --git a/pynxc/waxy/__init__.py b/pynxc/waxy/__init__.py new file mode 100644 index 0000000..b9cae90 --- /dev/null +++ b/pynxc/waxy/__init__.py @@ -0,0 +1,95 @@ +WAXY_VERSION = "0.0.1" +WAXY_VERSION_TUPLE = tuple(map(int, WAXY_VERSION.split("."))) + +__version__ = WAXY_VERSION + +__original_copyright__ = "Copyright 2003-2006 Hans Nowak" +__original_author__ = "Hans Nowak (hans@zephyrfalcon.org)" + +# this code is lifted from the, now unsupported, project wax +# i've cleaned things up a bit, taken out some things that +# don't work in the new wx, and keep modifying it to suit +# my needs + +__license__ = "BSD" +__author__ = "Brian Blais (bblais@bryant.edu)" + + + +# updated for recent wx, and modified as needed by bblais + +import sys +import core # builtin functions and such +import wx + +from wx import Yield +from constants import * +from wx import Point + +from aboutbox import AboutBox +from application import Application +from artprovider import ArtProvider +from bitmap import Bitmap, BitmapFromData, BitmapFromFile +from bitmapbutton import BitmapButton +from button import Button +from canvas import Canvas +from checkbox import CheckBox +from checklistbox import CheckListBox +from colordb import ColorDB +from colourdialog import ColourDialog,ColorDialog +from combobox import ComboBox +from containers import Container # do we need to publish this? +from customdialog import CustomDialog +from dialog import Dialog, showdialog +from directorydialog import DirectoryDialog,ChooseDirectory +from dragdrop import FileDropTarget, TextDropTarget, URLDropTarget +from dropdownbox import DropDownBox +from filedialog import FileDialog +##from filetreeview import FileTreeView +##from findreplacedialog import FindReplaceDialog +##from flexgridframe import FlexGridFrame +from flexgridpanel import FlexGridPanel +from font import Font +##from fontdialog import FontDialog +from frame import Frame, HorizontalFrame, VerticalFrame +from grid import Grid +##from gridframe import GridFrame +from gridpanel import GridPanel +##from groupbox import GroupBox +from htmlwindow import HTMLWindow +from image import Image, AddImageHandler, AddAllImageHandlers, ImageAsBitmap,ImagePanel +from imagelist import ImageList +from keys import keys +from label import Label +from line import Line +from listbox import ListBox +##from listview import ListView, ListItemAttr +#from maskedtextbox import MaskedTextBox +from menu import Menu, MenuBar +from messagedialog import MessageDialog, ShowMessage, Error +##from mdiframes import MDIChildFrame, MDIParentFrame +from mousepointer import MousePointers +from multichoicedialog import MultiChoiceDialog +from notebook import NoteBook +##from overlaypanel import OverlayPanel +from panel import Panel, HorizontalPanel, VerticalPanel +##from plainframe import PlainFrame +##from plainpanel import PlainPanel +from progressdialog import ProgressDialog +##from radiobutton import RadioButton +##from scrollframe import ScrollFrame +##from shell import PyCrust, PyCrustFilling +##from simpleeditor import SimpleEditor +from singlechoicedialog import SingleChoiceDialog +from slider import Slider,FloatSlider +from splitter import Splitter +from statusbar import StatusBar +##from styledtextbox import StyledTextBox +##from systemsettings import SystemSettings +from textbox import TextBox +from textentrydialog import TextEntryDialog,IntegerInputDialog,Input_Integer,FloatInputDialog,FloatInputDialog +##from timer import Timer +from treelistview import TreeListView +from treeview import TreeView +from waxyobject import WaxyObject + diff --git a/pynxc/waxy/__init__.py~ b/pynxc/waxy/__init__.py~ new file mode 100644 index 0000000..1964639 --- /dev/null +++ b/pynxc/waxy/__init__.py~ @@ -0,0 +1,77 @@ +WAXY_VERSION = "0.0.1" +WAXY_VERSION_TUPLE = tuple(map(int, WAXY_VERSION.split("."))) + +__version__ = WAXY_VERSION +__license__ = "BSD" +__author__ = "Brian Blais (bblais@bryant.edu)" + +import sys +import core # builtin functions and such +import wx + +from aboutbox import AboutBox +from application import Application +from artprovider import ArtProvider +from bitmap import Bitmap, BitmapFromData, BitmapFromFile +from bitmapbutton import BitmapButton +from button import Button +###from canvas import Canvas +from checkbox import CheckBox +from checklistbox import CheckListBox +from colordb import ColorDB +from colourdialog import ColourDialog,ColorDialog +from combobox import ComboBox +from containers import Container # do we need to publish this? +from customdialog import CustomDialog +from dialog import Dialog, showdialog +from directorydialog import DirectoryDialog,ChooseDirectory +###from dragdrop import FileDropTarget, TextDropTarget, URLDropTarget +from dropdownbox import DropDownBox +from filedialog import FileDialog +##from filetreeview import FileTreeView +##from findreplacedialog import FindReplaceDialog +##from flexgridframe import FlexGridFrame +from flexgridpanel import FlexGridPanel +from font import Font +##from fontdialog import FontDialog +from frame import Frame, HorizontalFrame, VerticalFrame +##from grid import Grid +##from gridframe import GridFrame +##from gridpanel import GridPanel +##from groupbox import GroupBox +from htmlwindow import HTMLWindow +from image import Image, AddImageHandler, AddAllImageHandlers, ImageAsBitmap +##from imagelist import ImageList +from keys import keys +from label import Label +from line import Line +from listbox import ListBox +##from listview import ListView, ListItemAttr +#from maskedtextbox import MaskedTextBox +from menu import Menu, MenuBar +from messagedialog import MessageDialog, ShowMessage +##from mdiframes import MDIChildFrame, MDIParentFrame +##from mousepointer import MousePointers +from multichoicedialog import MultiChoiceDialog +from notebook import NoteBook +##from overlaypanel import OverlayPanel +from panel import Panel, HorizontalPanel, VerticalPanel +##from plainframe import PlainFrame +##from plainpanel import PlainPanel +from progressdialog import ProgressDialog +##from radiobutton import RadioButton +##from scrollframe import ScrollFrame +##from shell import PyCrust, PyCrustFilling +##from simpleeditor import SimpleEditor +from singlechoicedialog import SingleChoiceDialog +from splitter import Splitter +##from statusbar import StatusBar +##from styledtextbox import StyledTextBox +##from systemsettings import SystemSettings +from textbox import TextBox +from textentrydialog import TextEntryDialog +##from timer import Timer +##from treelistview import TreeListView +##from treeview import TreeView +from waxyobject import WaxyObject + diff --git a/pynxc/waxy/aboutbox.py b/pynxc/waxy/aboutbox.py new file mode 100644 index 0000000..884e406 --- /dev/null +++ b/pynxc/waxy/aboutbox.py @@ -0,0 +1,43 @@ +import wx +from wx.lib.wordwrap import wordwrap + +def AboutBox(parent,info=None, + name='',version='',copyright='',description='',url='', + webtitle='',developers=[],license=''): + + + if not info: + + info={} + info['name']=name + info['version']=version + info['copyright']=copyright + info['description']=description + info['url']=url + info['webtitle']=webtitle + info['developers']=developers + info['license']=license + + + + ainfo = wx.AboutDialogInfo() + ainfo.Name = info['name'] + ainfo.Version = info['version'] + ainfo.Copyright = info['copyright'] + + if '(C)' not in ainfo.Copyright: + ainfo.Copyright='(C) '+info.Copyright + + ainfo.Description = wordwrap(info['description'], + 350, wx.ClientDC(parent)) + ainfo.WebSite = (info['url'],info['webtitle']) + ainfo.Developers = info['developers'] + + ainfo.License = wordwrap(info['license'], 500, wx.ClientDC(parent)) + + # Then we call wx.AboutBox giving it that info object + + + + wx.AboutBox(ainfo) + diff --git a/pynxc/waxy/aboutbox.py~ b/pynxc/waxy/aboutbox.py~ new file mode 100644 index 0000000..d84fc97 --- /dev/null +++ b/pynxc/waxy/aboutbox.py~ @@ -0,0 +1,43 @@ +import wx +from wx.lib.wordwrap import wordwrap + +def AboutBox(parent,info=None, + name='',version='',copyright='',description='',url='', + webtitle='',developers=[],license=''): + + + if not info: + + info={} + info['name']=name + info['version']=version + info['copyright']=copyright + info['description']=description + info['url']=url + info['webtitle']=webtitle + info['developers']=developers + info['license']=license + + + + ainfo = wx.AboutDialogInfo() + ainfo.Name = info['name'] + ainfo.Version = info['version'] + ainfo.Copyright = info['copyright'] + + if '(C)' not in ainfo.Copyright: + ainfo.Copyright='(C) '+info.Copyright + + ainfo.Description = wordwrap(info['description'], + 350, wx.ClientDC(parent)) + ainfo.WebSite = (info['url'],info['webtitle']) + ainfo.Developers = info['developers'] + + ainfo.License = wordwrap(info['license'], 500, wx.ClientDC(parent)) + + # Then we call wx.AboutBox giving it that info object + + + + wx.AboutBox(info) + diff --git a/pynxc/waxy/application.py b/pynxc/waxy/application.py new file mode 100644 index 0000000..c6c01fd --- /dev/null +++ b/pynxc/waxy/application.py @@ -0,0 +1,32 @@ +# application.py + +import wx +import sys +#from waxconfig import WaxConfig +#import font + +class Application(wx.App): + def __init__(self, frameklass, *args, **kwargs): + # takes a frame *class* plus arbitrary options. these options will + # be passed to the frame constructor. + self.frameklass = frameklass + self.args = args + self.kwargs = kwargs + + # when set, the app uses the stdout/stderr window; off by default + use_stdout_window = 0 + if kwargs.has_key('use_stdout_window'): + use_stdout_window = kwargs['use_stdout_window'] + del kwargs['use_stdout_window'] + wx.App.__init__(self, use_stdout_window) + + def OnInit(self): + self.mainframe = self.frameklass(*self.args, **self.kwargs) + if hasattr(self.mainframe.__class__, "__ExceptHook__"): + sys.excepthook = self.mainframe.__ExceptHook__ + self.mainframe.Show(True) + self.SetTopWindow(self.mainframe) + return True + + def Run(self): + self.MainLoop() diff --git a/pynxc/waxy/application.py~ b/pynxc/waxy/application.py~ new file mode 100644 index 0000000..eab2e66 --- /dev/null +++ b/pynxc/waxy/application.py~ @@ -0,0 +1,36 @@ +# application.py + +import wx +import sys +#from waxconfig import WaxConfig +#import font + +class Application(wx.App): + def __init__(self, frameklass, *args, **kwargs): + # takes a frame *class* plus arbitrary options. these options will + # be passed to the frame constructor. + self.frameklass = frameklass + self.args = args + self.kwargs = kwargs + + # when set, the app uses the stdout/stderr window; off by default + use_stdout_window = 0 + if kwargs.has_key('use_stdout_window'): + use_stdout_window = kwargs['use_stdout_window'] + del kwargs['use_stdout_window'] + wx.App.__init__(self, use_stdout_window) + + def OnInit(self): + if isinstance(WaxConfig.default_font, tuple): + WaxConfig.default_font = font.Font(*WaxConfig.default_font) + else: + print >> sys.stderr, "Warning: This construct will not work in future wxPython versions" + self.mainframe = self.frameklass(*self.args, **self.kwargs) + if hasattr(self.mainframe.__class__, "__ExceptHook__"): + sys.excepthook = self.mainframe.__ExceptHook__ + self.mainframe.Show(True) + self.SetTopWindow(self.mainframe) + return True + + def Run(self): + self.MainLoop() diff --git a/pynxc/waxy/artprovider.py b/pynxc/waxy/artprovider.py new file mode 100644 index 0000000..29014ad --- /dev/null +++ b/pynxc/waxy/artprovider.py @@ -0,0 +1,126 @@ +# artprovider.py + +import wx, os +import string +import cStringIO + +ARTCLIENTS = [ "ART_TOOLBAR", + "ART_MENU", + "ART_FRAME_ICON", + "ART_CMN_DIALOG", + "ART_HELP_BROWSER", + "ART_MESSAGE_BOX", + "ART_OTHER", + ] + +ARTIDS = [ "ART_ADD_BOOKMARK", + "ART_DEL_BOOKMARK", + "ART_HELP_SIDE_PANEL", + "ART_HELP_SETTINGS", + "ART_HELP_BOOK", + "ART_HELP_FOLDER", + "ART_HELP_PAGE", + "ART_GO_BACK", + "ART_GO_FORWARD", + "ART_GO_UP", + "ART_GO_DOWN", + "ART_GO_TO_PARENT", + "ART_GO_HOME", + "ART_FILE_OPEN", + "ART_PRINT", + "ART_HELP", + "ART_TIP", + "ART_REPORT_VIEW", + "ART_LIST_VIEW", + "ART_NEW_DIR", + "ART_FOLDER", + "ART_GO_DIR_UP", + "ART_EXECUTABLE_FILE", + "ART_NORMAL_FILE", + "ART_TICK_MARK", + "ART_CROSS_MARK", + "ART_ERROR", + "ART_QUESTION", + "ART_WARNING", + "ART_INFORMATION", + ] + +class ArtProvider(object): + def __init__(self, size=wx.DefaultSize): + self.custom = {} + self.clients = [] + for client in ARTCLIENTS: + self.clients.append(client[4:].lower()) + self.images = [] + for image in ARTIDS: + self.images.append(image[4:].lower()) + self.size = size + self._usecustom = False + + def _SetUseCustom(self, value): + if self._usecustom and not value: + wx.ArtProvider_PopProvider() + elif value and not self._usecustom: + wx.ArtProvider_PushProvider(ArtPushProvider(self)) + self._usecustom = value + + def _GetUseCustom(self): + return self.__usecustom + + UseCustom = property(_GetUseCustom, _SetUseCustom, doc="Custom art enable") + + def _GetWxArtIds(self, name, client): + imageid = "ART_" + name.upper() + clientid = "ART_" + client.upper() + wx_image = getattr(wx, imageid, name) + wx_client = getattr(wx, clientid, client) + return wx_image, wx_client + + def GetBitmap(self, image, client='other', size=None): + wx_image, wx_client = self._GetWxArtIds(image, client) + if size == None: + size = self.size + return wx.ArtProvider_GetBitmap(wx_image, wx_client, size) + + def GetIcon(self, name, client='other', size=None): + wx_image, wx_client = self._GetWxArtIds(name, client) + if size == None: + size = self.size + return wx.ArtProvider_GetIcon(wx_image, wx_client, size) + + def RegisterImage(self, image, name, client='other', size=None): + wx_image, wx_client = self._GetWxArtIds(name, client) + if size == None: + size = self.size + keyword = string.join([wx_client,"::", wx_image, "::", str(size[0]),":", str(size[1])],'') + if size != (-1,-1): + image.Rescale(size[0], size[1]) + self.custom[keyword] = wx.BitmapFromImage(image) + if wx_client not in self.clients: + if not wx_client.startswith('wxART'): + self.clients.append(wx_client) + if wx_image not in self.images: + if not wx_image.startswith('wxART'): + self.images.append(wx_image) + + def RegisterFromFile(self, filename, name, client='other', size=None): + image = wx.Image(opj(filename), wx.BITMAP_TYPE_ANY) + self.RegisterImage(image, name, client, size) + + def RegisterFromData(self, stream, name, client='other', size=None): + image = wx.ImageFromStream(stream) + self.RegisterImage(image, name, client, size) + +class ArtPushProvider(wx.ArtProvider): + # custom class for push_provider + def __init__(self, waxArtProvider): + wx.ArtProvider.__init__(self) + self.__AP = waxArtProvider + + def CreateBitmap(self, artid, client, size): + keyword = string.join([client,"::", artid, "::", str(size[0]),":", str(size[1])],'') + bmp = wx.NullBitmap + if self.__AP.custom.has_key(keyword): + bmp = self.__AP.custom[keyword] + return bmp + diff --git a/pynxc/waxy/bitmap.py b/pynxc/waxy/bitmap.py new file mode 100644 index 0000000..49f0f8a --- /dev/null +++ b/pynxc/waxy/bitmap.py @@ -0,0 +1,29 @@ +# bitmap.py + +import wx +import waxyobject +import image +import cStringIO + +# XXX not sure what to do with this +class Bitmap(wx.StaticBitmap, waxyobject.WaxyObject): + + def __init__(self, parent, bitmap): + if isinstance(bitmap, str) or isinstance(bitmap, unicode): + bitmap = BitmapFromFile(bitmap) + wx.StaticBitmap.__init__(self, parent, wx.NewId(), bitmap) + # XXX supposedly you can load this from file too? + +# +# use these functions for convenience... +# unfortunately, they return wxBitmaps, not Bitmaps + +def BitmapFromData(data): + stream = cStringIO.StringIO(data) + z = wx.ImageFromStream(stream) + return wx.BitmapFromImage(z) + +def BitmapFromFile(filename): + data = open(filename, 'rb').read() + return BitmapFromData(data) + diff --git a/pynxc/waxy/bitmap.py~ b/pynxc/waxy/bitmap.py~ new file mode 100644 index 0000000..7a3629c --- /dev/null +++ b/pynxc/waxy/bitmap.py~ @@ -0,0 +1,29 @@ +# bitmap.py + +import wx +import waxobject +import image +import cStringIO + +# XXX not sure what to do with this +class Bitmap(wx.StaticBitmap, waxobject.WaxObject): + + def __init__(self, parent, bitmap): + if isinstance(bitmap, str) or isinstance(bitmap, unicode): + bitmap = BitmapFromFile(bitmap) + wx.StaticBitmap.__init__(self, parent, wx.NewId(), bitmap) + # XXX supposedly you can load this from file too? + +# +# use these functions for convenience... +# unfortunately, they return wxBitmaps, not Bitmaps + +def BitmapFromData(data): + stream = cStringIO.StringIO(data) + z = wx.ImageFromStream(stream) + return wx.BitmapFromImage(z) + +def BitmapFromFile(filename): + data = open(filename, 'rb').read() + return BitmapFromData(data) + diff --git a/pynxc/waxy/bitmapbutton.py b/pynxc/waxy/bitmapbutton.py new file mode 100644 index 0000000..0955387 --- /dev/null +++ b/pynxc/waxy/bitmapbutton.py @@ -0,0 +1,49 @@ +# bitmapbutton.py + +import button +import containers +import waxyobject +import wx +import os +import styles + +def opj(path): + """Convert paths to the platform-specific separator""" + return apply(os.path.join, tuple(path.split('/'))) + +def loadbitmap(filename): + """Load a bitmap from an image file""" + return wx.Image(opj(filename), wx.BITMAP_TYPE_ANY).ConvertToBitmap() + +class BitmapButton(wx.BitmapButton, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_BUTTON, + } + + def __init__(self, parent, bmp, event=None, default_style=1, size=None, **kwargs): + if isinstance(bmp, str) or isinstance(bmp, unicode): + bmp = loadbitmap(bmp) + style = default_style and 4 or 0 + style |= self._params(kwargs) + style |= self._params(kwargs, button.Button.__styles__) + style |= styles.window(kwargs) + + wx.BitmapButton.__init__(self, parent, wx.NewId(), bmp, + size=size or (-1,-1), style=style) + + self.BindEvents() + if event: + self.OnClick = event + styles.properties(self, kwargs) + + __styles__ = { + 'align': ({ + 'left': wx.BU_LEFT, + 'top': wx.BU_TOP, + 'right': wx.BU_RIGHT, + 'bottom': wx.BU_BOTTOM, + }, styles.DICTSTART), + 'autodraw': (wx.BU_AUTODRAW, styles.NORMAL), + } + diff --git a/pynxc/waxy/bitmapbutton.py~ b/pynxc/waxy/bitmapbutton.py~ new file mode 100644 index 0000000..2c4e286 --- /dev/null +++ b/pynxc/waxy/bitmapbutton.py~ @@ -0,0 +1,50 @@ +# bitmapbutton.py + +import button +import containers +import waxyobject +import wx +import os +import styles + +def opj(path): + """Convert paths to the platform-specific separator""" + return apply(os.path.join, tuple(path.split('/'))) + +def loadbitmap(filename): + """Load a bitmap from an image file""" + return wx.Image(opj(filename), wx.BITMAP_TYPE_ANY).ConvertToBitmap() + +class BitmapButton(wx.BitmapButton, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_BUTTON, + } + + def __init__(self, parent, bmp, event=None, default_style=1, size=None, **kwargs): + if isinstance(bmp, str) or isinstance(bmp, unicode): + bmp = loadbitmap(bmp) + style = default_style and 4 or 0 + style |= self._params(kwargs) + style |= self._params(kwargs, button.Button.__styles__) + style |= styles.window(kwargs) + + wx.BitmapButton.__init__(self, parent, wx.NewId(), bmp, + size=size or (-1,-1), style=style) + + self.SetDefaultFont() + self.BindEvents() + if event: + self.OnClick = event + styles.properties(self, kwargs) + + __styles__ = { + 'align': ({ + 'left': wx.BU_LEFT, + 'top': wx.BU_TOP, + 'right': wx.BU_RIGHT, + 'bottom': wx.BU_BOTTOM, + }, styles.DICTSTART), + 'autodraw': (wx.BU_AUTODRAW, styles.NORMAL), + } + diff --git a/pynxc/waxy/button.py b/pynxc/waxy/button.py new file mode 100644 index 0000000..1538abc --- /dev/null +++ b/pynxc/waxy/button.py @@ -0,0 +1,54 @@ +# button.py + +import containers +import waxyobject +import wx +import styles + + +class Button(wx.Button, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_BUTTON, + } + + def __init__(self, parent, text="", event=None, size=None, + tooltip="", default=False, disabled=False, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.Button.__init__(self, parent, wx.NewId(), text, size=size or (-1,-1), + style=style) + + self.BindEvents() + if event: + self.OnClick = event + + if tooltip: + self.SetToolTipString(tooltip) + + if default: + self.SetDefault() + + if disabled: + self.Enable(False) + + styles.properties(self, kwargs) + + # + # style parameters + + __styles__ = { + 'align': ({ + "left": wx.BU_LEFT, + "right": wx.BU_RIGHT, + "bottom": wx.BU_BOTTOM, + "top": wx.BU_TOP, + "exact": wx.BU_EXACTFIT, + }, styles.DICTSTART), + 'flat': (wx.NO_BORDER, styles.NORMAL), + # seems to have no effect on Windows XP + 'exactfit': (wx.BU_EXACTFIT, styles.NORMAL), + } + diff --git a/pynxc/waxy/button.py~ b/pynxc/waxy/button.py~ new file mode 100644 index 0000000..764674d --- /dev/null +++ b/pynxc/waxy/button.py~ @@ -0,0 +1,51 @@ +# button.py + +import containers +import waxyobject +import wx +import styles + + +class Button(wx.Button, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_BUTTON, + } + + def __init__(self, parent, text="", event=None, size=None, + tooltip="", default=False, disabled=False, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.Button.__init__(self, parent, wx.NewId(), text, size=size or (-1,-1), + style=style) + + self.BindEvents() + if event: + self.OnClick = event + + if tooltip: + self.SetToolTipString(tooltip) + + if default: + self.SetDefault() + + styles.properties(self, kwargs) + + # + # style parameters + + __styles__ = { + 'align': ({ + "left": wx.BU_LEFT, + "right": wx.BU_RIGHT, + "bottom": wx.BU_BOTTOM, + "top": wx.BU_TOP, + "exact": wx.BU_EXACTFIT, + }, styles.DICTSTART), + 'flat': (wx.NO_BORDER, styles.NORMAL), + # seems to have no effect on Windows XP + 'exactfit': (wx.BU_EXACTFIT, styles.NORMAL), + } + diff --git a/pynxc/waxy/canvas.py b/pynxc/waxy/canvas.py new file mode 100644 index 0000000..072fb85 --- /dev/null +++ b/pynxc/waxy/canvas.py @@ -0,0 +1,33 @@ +# canvas.py + +import wx +import waxyobject + +class Canvas(wx.ScrolledWindow, waxyobject.WaxyObject): + + __events__ = { + 'Paint': wx.EVT_PAINT, + } + + def __init__(self, parent): + wx.ScrolledWindow.__init__(self, parent, wx.NewId()) + self.Init() + + self.BindEvents() + + def _OnPaint(self, event=None): + self.OnPaint(event) + def OnPaint(self, event=None): + dc = wx.PaintDC(self) + self.PrepareDC(dc) + self.OnDraw(dc) + event.Skip() + + def OnDraw(self, dc): + # override to draw on the canvas + pass + + def Init(self): + # override to place scrollbars, set color, etc. + pass + diff --git a/pynxc/waxy/checkbox.py b/pynxc/waxy/checkbox.py new file mode 100644 index 0000000..143a260 --- /dev/null +++ b/pynxc/waxy/checkbox.py @@ -0,0 +1,71 @@ +# checkbox.py
+
+import wx
+import waxyobject
+import styles
+
+class CheckBox(wx.CheckBox, waxyobject.WaxyObject):
+
+ __events__ = {
+ 'Check': wx.EVT_CHECKBOX,
+ }
+
+
+ def __init__(self, parent, text='', size=None, border=1, **kwargs):
+ flags = 0
+ if not border:
+ flags |= wx.NO_BORDER
+ # XXX not sure what border does... there doesn't seem to be a visible
+ # difference?
+ flags |= self._params(kwargs)
+ flags |= styles.window(kwargs)
+
+ wx.CheckBox.__init__(self, parent, wx.NewId(), text, None,
+ size or (-1, -1), flags)
+
+ self.BindEvents()
+ styles.properties(self, kwargs)
+
+ _3states = {
+ 'checked': wx.CHK_CHECKED,
+ 'unchecked': wx.CHK_UNCHECKED,
+ 'undetermined': wx.CHK_UNDETERMINED,
+ }
+
+ def Set3StateValue(self, state):
+ for name, flag in self._3states.items():
+ if name.startswith(state):
+ wx.CheckBox.Set3StateValue(self, flag)
+ break
+ else:
+ raise KeyError, "Unknown state: %s" % (state,)
+
+ def Get3StateValue(self):
+ value = wx.CheckBox.Get3StateValue(self)
+ if value == wx.CHK_CHECKED:
+ return 'checked'
+ elif value == wx.CHK_UNCHECKED:
+ return 'unchecked'
+ elif value == wx.CHK_UNDETERMINED:
+ return 'undetermined'
+ else:
+ return '?'
+
+ #
+ # style parameters
+
+ _checkbox_states = {
+ 2: wx.CHK_2STATE,
+ 3: wx.CHK_3STATE,
+ }
+
+ _checkbox_align = {
+ 'left': 0,
+ 'right': wx.ALIGN_RIGHT,
+ }
+
+ def _params(self, kwargs):
+ flags = 0
+ flags |= styles.styledict('states', self._checkbox_states, kwargs, wx.CHK_2STATE)
+ flags |= styles.styledictstart('align', self._checkbox_align, kwargs, 0)
+ return flags
diff --git a/pynxc/waxy/checkbox.py~ b/pynxc/waxy/checkbox.py~ new file mode 100644 index 0000000..4a595f6 --- /dev/null +++ b/pynxc/waxy/checkbox.py~ @@ -0,0 +1,72 @@ +# checkbox.py
+
+import wx
+import waxyobject
+import styles
+
+class CheckBox(wx.CheckBox, waxyobject.WaxyObject):
+
+ __events__ = {
+ 'Check': wx.EVT_CHECKBOX,
+ }
+
+
+ def __init__(self, parent, text='', size=None, border=1, **kwargs):
+ flags = 0
+ if not border:
+ flags |= wx.NO_BORDER
+ # XXX not sure what border does... there doesn't seem to be a visible
+ # difference?
+ flags |= self._params(kwargs)
+ flags |= styles.window(kwargs)
+
+ wx.CheckBox.__init__(self, parent, wx.NewId(), text, None,
+ size or (-1, -1), flags)
+
+ self.BindEvents()
+ self.SetDefaultFont()
+ styles.properties(self, kwargs)
+
+ _3states = {
+ 'checked': wx.CHK_CHECKED,
+ 'unchecked': wx.CHK_UNCHECKED,
+ 'undetermined': wx.CHK_UNDETERMINED,
+ }
+
+ def Set3StateValue(self, state):
+ for name, flag in self._3states.items():
+ if name.startswith(state):
+ wx.CheckBox.Set3StateValue(self, flag)
+ break
+ else:
+ raise KeyError, "Unknown state: %s" % (state,)
+
+ def Get3StateValue(self):
+ value = wx.CheckBox.Get3StateValue(self)
+ if value == wx.CHK_CHECKED:
+ return 'checked'
+ elif value == wx.CHK_UNCHECKED:
+ return 'unchecked'
+ elif value == wx.CHK_UNDETERMINED:
+ return 'undetermined'
+ else:
+ return '?'
+
+ #
+ # style parameters
+
+ _checkbox_states = {
+ 2: wx.CHK_2STATE,
+ 3: wx.CHK_3STATE,
+ }
+
+ _checkbox_align = {
+ 'left': 0,
+ 'right': wx.ALIGN_RIGHT,
+ }
+
+ def _params(self, kwargs):
+ flags = 0
+ flags |= styles.styledict('states', self._checkbox_states, kwargs, wx.CHK_2STATE)
+ flags |= styles.styledictstart('align', self._checkbox_align, kwargs, 0)
+ return flags
diff --git a/pynxc/waxy/checklistbox.py b/pynxc/waxy/checklistbox.py new file mode 100644 index 0000000..67176a6 --- /dev/null +++ b/pynxc/waxy/checklistbox.py @@ -0,0 +1,27 @@ +# checklistbox.py +# XXX doesn't work on Mac. + +# todo: styles (if any) + +import wx +import waxyobject +import styles + +class CheckListBox(wx.CheckListBox, waxyobject.WaxyObject): + + __events__ = { + 'CheckListBox': wx.EVT_CHECKLISTBOX, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + #style |= checklistbox_params(kwargs) + style |= styles.window(kwargs) + + wx.CheckListBox.__init__(self, parent, wx.NewId(), choices=choices, style=style) + + self.BindEvents() + + styles.properties(self, kwargs) + + diff --git a/pynxc/waxy/checklistbox.py~ b/pynxc/waxy/checklistbox.py~ new file mode 100644 index 0000000..34c7dd2 --- /dev/null +++ b/pynxc/waxy/checklistbox.py~ @@ -0,0 +1,28 @@ +# checklistbox.py +# XXX doesn't work on Mac. + +# todo: styles (if any) + +import wx +import waxyobject +import styles + +class CheckListBox(wx.CheckListBox, waxyobject.WaxyObject): + + __events__ = { + 'CheckListBox': wx.EVT_CHECKLISTBOX, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + #style |= checklistbox_params(kwargs) + style |= styles.window(kwargs) + + wx.CheckListBox.__init__(self, parent, wx.NewId(), choices=choices, style=style) + + self.SetDefaultFont() + self.BindEvents() + + styles.properties(self, kwargs) + + diff --git a/pynxc/waxy/colordb.py b/pynxc/waxy/colordb.py new file mode 100644 index 0000000..b2cb6cd --- /dev/null +++ b/pynxc/waxy/colordb.py @@ -0,0 +1,844 @@ +# colordb.py +# Allows access to Tk's color names, plus adds some other functions. +# You can now do obj.SetForegroundColor(colordb['papayawhip'])! ;-) +# Or: obj.SetForegroundColor('papayawhip'). +# or even: obj.ForegroundColor = 'papayawhip'! + +import math +import operator +import string + +def convert_color(color): + if isinstance(color, str): + color = _colordb.byname(color) + # TODO: maybe colors in the format "#007FC0"? + return color + +data = { + 'alice blue': (240, 248, 255), + 'aliceblue': (240, 248, 255), + 'antique white': (250, 235, 215), + 'antiquewhite': (250, 235, 215), + 'antiquewhite1': (255, 239, 219), + 'antiquewhite2': (238, 223, 204), + 'antiquewhite3': (205, 192, 176), + 'antiquewhite4': (139, 131, 120), + 'aquamarine': (127, 255, 212), + 'aquamarine1': (127, 255, 212), + 'aquamarine2': (118, 238, 198), + 'aquamarine3': (102, 205, 170), + 'aquamarine4': (69, 139, 116), + 'azure': (240, 255, 255), + 'azure1': (240, 255, 255), + 'azure2': (224, 238, 238), + 'azure3': (193, 205, 205), + 'azure4': (131, 139, 139), + 'beige': (245, 245, 220), + 'bisque': (255, 228, 196), + 'bisque1': (255, 228, 196), + 'bisque2': (238, 213, 183), + 'bisque3': (205, 183, 158), + 'bisque4': (139, 125, 107), + 'black': (0, 0, 0), + 'blanched almond': (255, 235, 205), + 'blanchedalmond': (255, 235, 205), + 'blue': (0, 0, 255), + 'blue violet': (138, 43, 226), + 'blue1': (0, 0, 255), + 'blue2': (0, 0, 238), + 'blue3': (0, 0, 205), + 'blue4': (0, 0, 139), + 'blueviolet': (138, 43, 226), + 'brown': (165, 42, 42), + 'brown1': (255, 64, 64), + 'brown2': (238, 59, 59), + 'brown3': (205, 51, 51), + 'brown4': (139, 35, 35), + 'burlywood': (222, 184, 135), + 'burlywood1': (255, 211, 155), + 'burlywood2': (238, 197, 145), + 'burlywood3': (205, 170, 125), + 'burlywood4': (139, 115, 85), + 'cadet blue': (95, 158, 160), + 'cadetblue': (95, 158, 160), + 'cadetblue1': (152, 245, 255), + 'cadetblue2': (142, 229, 238), + 'cadetblue3': (122, 197, 205), + 'cadetblue4': (83, 134, 139), + 'chartreuse': (127, 255, 0), + 'chartreuse1': (127, 255, 0), + 'chartreuse2': (118, 238, 0), + 'chartreuse3': (102, 205, 0), + 'chartreuse4': (69, 139, 0), + 'chocolate': (210, 105, 30), + 'chocolate1': (255, 127, 36), + 'chocolate2': (238, 118, 33), + 'chocolate3': (205, 102, 29), + 'chocolate4': (139, 69, 19), + 'coral': (255, 127, 80), + 'coral1': (255, 114, 86), + 'coral2': (238, 106, 80), + 'coral3': (205, 91, 69), + 'coral4': (139, 62, 47), + 'cornflower blue': (100, 149, 237), + 'cornflowerblue': (100, 149, 237), + 'cornsilk': (255, 248, 220), + 'cornsilk1': (255, 248, 220), + 'cornsilk2': (238, 232, 205), + 'cornsilk3': (205, 200, 177), + 'cornsilk4': (139, 136, 120), + 'cyan': (0, 255, 255), + 'cyan1': (0, 255, 255), + 'cyan2': (0, 238, 238), + 'cyan3': (0, 205, 205), + 'cyan4': (0, 139, 139), + 'dark blue': (0, 0, 139), + 'dark cyan': (0, 139, 139), + 'dark goldenrod': (184, 134, 11), + 'dark gray': (169, 169, 169), + 'dark green': (0, 100, 0), + 'dark grey': (169, 169, 169), + 'dark khaki': (189, 183, 107), + 'dark magenta': (139, 0, 139), + 'dark olive green': (85, 107, 47), + 'dark orange': (255, 140, 0), + 'dark orchid': (153, 50, 204), + 'dark red': (139, 0, 0), + 'dark salmon': (233, 150, 122), + 'dark sea green': (143, 188, 143), + 'dark slate blue': (72, 61, 139), + 'dark slate gray': (47, 79, 79), + 'dark slate grey': (47, 79, 79), + 'dark turquoise': (0, 206, 209), + 'dark violet': (148, 0, 211), + 'darkblue': (0, 0, 139), + 'darkcyan': (0, 139, 139), + 'darkgoldenrod': (184, 134, 11), + 'darkgoldenrod1': (255, 185, 15), + 'darkgoldenrod2': (238, 173, 14), + 'darkgoldenrod3': (205, 149, 12), + 'darkgoldenrod4': (139, 101, 8), + 'darkgray': (169, 169, 169), + 'darkgreen': (0, 100, 0), + 'darkgrey': (169, 169, 169), + 'darkkhaki': (189, 183, 107), + 'darkmagenta': (139, 0, 139), + 'darkolivegreen': (85, 107, 47), + 'darkolivegreen1': (202, 255, 112), + 'darkolivegreen2': (188, 238, 104), + 'darkolivegreen3': (162, 205, 90), + 'darkolivegreen4': (110, 139, 61), + 'darkorange': (255, 140, 0), + 'darkorange1': (255, 127, 0), + 'darkorange2': (238, 118, 0), + 'darkorange3': (205, 102, 0), + 'darkorange4': (139, 69, 0), + 'darkorchid': (153, 50, 204), + 'darkorchid1': (191, 62, 255), + 'darkorchid2': (178, 58, 238), + 'darkorchid3': (154, 50, 205), + 'darkorchid4': (104, 34, 139), + 'darkred': (139, 0, 0), + 'darksalmon': (233, 150, 122), + 'darkseagreen': (143, 188, 143), + 'darkseagreen1': (193, 255, 193), + 'darkseagreen2': (180, 238, 180), + 'darkseagreen3': (155, 205, 155), + 'darkseagreen4': (105, 139, 105), + 'darkslateblue': (72, 61, 139), + 'darkslategray': (47, 79, 79), + 'darkslategray1': (151, 255, 255), + 'darkslategray2': (141, 238, 238), + 'darkslategray3': (121, 205, 205), + 'darkslategray4': (82, 139, 139), + 'darkslategrey': (47, 79, 79), + 'darkturquoise': (0, 206, 209), + 'darkviolet': (148, 0, 211), + 'deep pink': (255, 20, 147), + 'deep sky blue': (0, 191, 255), + 'deeppink': (255, 20, 147), + 'deeppink1': (255, 20, 147), + 'deeppink2': (238, 18, 137), + 'deeppink3': (205, 16, 118), + 'deeppink4': (139, 10, 80), + 'deepskyblue': (0, 191, 255), + 'deepskyblue1': (0, 191, 255), + 'deepskyblue2': (0, 178, 238), + 'deepskyblue3': (0, 154, 205), + 'deepskyblue4': (0, 104, 139), + 'dim gray': (105, 105, 105), + 'dim grey': (105, 105, 105), + 'dimgray': (105, 105, 105), + 'dimgrey': (105, 105, 105), + 'dodger blue': (30, 144, 255), + 'dodgerblue': (30, 144, 255), + 'dodgerblue1': (30, 144, 255), + 'dodgerblue2': (28, 134, 238), + 'dodgerblue3': (24, 116, 205), + 'dodgerblue4': (16, 78, 139), + 'firebrick': (178, 34, 34), + 'firebrick1': (255, 48, 48), + 'firebrick2': (238, 44, 44), + 'firebrick3': (205, 38, 38), + 'firebrick4': (139, 26, 26), + 'floral white': (255, 250, 240), + 'floralwhite': (255, 250, 240), + 'forest green': (34, 139, 34), + 'forestgreen': (34, 139, 34), + 'gainsboro': (220, 220, 220), + 'ghost white': (248, 248, 255), + 'ghostwhite': (248, 248, 255), + 'gold': (255, 215, 0), + 'gold1': (255, 215, 0), + 'gold2': (238, 201, 0), + 'gold3': (205, 173, 0), + 'gold4': (139, 117, 0), + 'goldenrod': (218, 165, 32), + 'goldenrod1': (255, 193, 37), + 'goldenrod2': (238, 180, 34), + 'goldenrod3': (205, 155, 29), + 'goldenrod4': (139, 105, 20), + 'gray': (190, 190, 190), + 'gray0': (0, 0, 0), + 'gray1': (3, 3, 3), + 'gray10': (26, 26, 26), + 'gray100': (255, 255, 255), + 'gray11': (28, 28, 28), + 'gray12': (31, 31, 31), + 'gray13': (33, 33, 33), + 'gray14': (36, 36, 36), + 'gray15': (38, 38, 38), + 'gray16': (41, 41, 41), + 'gray17': (43, 43, 43), + 'gray18': (46, 46, 46), + 'gray19': (48, 48, 48), + 'gray2': (5, 5, 5), + 'gray20': (51, 51, 51), + 'gray21': (54, 54, 54), + 'gray22': (56, 56, 56), + 'gray23': (59, 59, 59), + 'gray24': (61, 61, 61), + 'gray25': (64, 64, 64), + 'gray26': (66, 66, 66), + 'gray27': (69, 69, 69), + 'gray28': (71, 71, 71), + 'gray29': (74, 74, 74), + 'gray3': (8, 8, 8), + 'gray30': (77, 77, 77), + 'gray31': (79, 79, 79), + 'gray32': (82, 82, 82), + 'gray33': (84, 84, 84), + 'gray34': (87, 87, 87), + 'gray35': (89, 89, 89), + 'gray36': (92, 92, 92), + 'gray37': (94, 94, 94), + 'gray38': (97, 97, 97), + 'gray39': (99, 99, 99), + 'gray4': (10, 10, 10), + 'gray40': (102, 102, 102), + 'gray41': (105, 105, 105), + 'gray42': (107, 107, 107), + 'gray43': (110, 110, 110), + 'gray44': (112, 112, 112), + 'gray45': (115, 115, 115), + 'gray46': (117, 117, 117), + 'gray47': (120, 120, 120), + 'gray48': (122, 122, 122), + 'gray49': (125, 125, 125), + 'gray5': (13, 13, 13), + 'gray50': (127, 127, 127), + 'gray51': (130, 130, 130), + 'gray52': (133, 133, 133), + 'gray53': (135, 135, 135), + 'gray54': (138, 138, 138), + 'gray55': (140, 140, 140), + 'gray56': (143, 143, 143), + 'gray57': (145, 145, 145), + 'gray58': (148, 148, 148), + 'gray59': (150, 150, 150), + 'gray6': (15, 15, 15), + 'gray60': (153, 153, 153), + 'gray61': (156, 156, 156), + 'gray62': (158, 158, 158), + 'gray63': (161, 161, 161), + 'gray64': (163, 163, 163), + 'gray65': (166, 166, 166), + 'gray66': (168, 168, 168), + 'gray67': (171, 171, 171), + 'gray68': (173, 173, 173), + 'gray69': (176, 176, 176), + 'gray7': (18, 18, 18), + 'gray70': (179, 179, 179), + 'gray71': (181, 181, 181), + 'gray72': (184, 184, 184), + 'gray73': (186, 186, 186), + 'gray74': (189, 189, 189), + 'gray75': (191, 191, 191), + 'gray76': (194, 194, 194), + 'gray77': (196, 196, 196), + 'gray78': (199, 199, 199), + 'gray79': (201, 201, 201), + 'gray8': (20, 20, 20), + 'gray80': (204, 204, 204), + 'gray81': (207, 207, 207), + 'gray82': (209, 209, 209), + 'gray83': (212, 212, 212), + 'gray84': (214, 214, 214), + 'gray85': (217, 217, 217), + 'gray86': (219, 219, 219), + 'gray87': (222, 222, 222), + 'gray88': (224, 224, 224), + 'gray89': (227, 227, 227), + 'gray9': (23, 23, 23), + 'gray90': (229, 229, 229), + 'gray91': (232, 232, 232), + 'gray92': (235, 235, 235), + 'gray93': (237, 237, 237), + 'gray94': (240, 240, 240), + 'gray95': (242, 242, 242), + 'gray96': (245, 245, 245), + 'gray97': (247, 247, 247), + 'gray98': (250, 250, 250), + 'gray99': (252, 252, 252), + 'green': (0, 255, 0), + 'green yellow': (173, 255, 47), + 'green1': (0, 255, 0), + 'green2': (0, 238, 0), + 'green3': (0, 205, 0), + 'green4': (0, 139, 0), + 'greenyellow': (173, 255, 47), + 'grey': (190, 190, 190), + 'grey0': (0, 0, 0), + 'grey1': (3, 3, 3), + 'grey10': (26, 26, 26), + 'grey100': (255, 255, 255), + 'grey11': (28, 28, 28), + 'grey12': (31, 31, 31), + 'grey13': (33, 33, 33), + 'grey14': (36, 36, 36), + 'grey15': (38, 38, 38), + 'grey16': (41, 41, 41), + 'grey17': (43, 43, 43), + 'grey18': (46, 46, 46), + 'grey19': (48, 48, 48), + 'grey2': (5, 5, 5), + 'grey20': (51, 51, 51), + 'grey21': (54, 54, 54), + 'grey22': (56, 56, 56), + 'grey23': (59, 59, 59), + 'grey24': (61, 61, 61), + 'grey25': (64, 64, 64), + 'grey26': (66, 66, 66), + 'grey27': (69, 69, 69), + 'grey28': (71, 71, 71), + 'grey29': (74, 74, 74), + 'grey3': (8, 8, 8), + 'grey30': (77, 77, 77), + 'grey31': (79, 79, 79), + 'grey32': (82, 82, 82), + 'grey33': (84, 84, 84), + 'grey34': (87, 87, 87), + 'grey35': (89, 89, 89), + 'grey36': (92, 92, 92), + 'grey37': (94, 94, 94), + 'grey38': (97, 97, 97), + 'grey39': (99, 99, 99), + 'grey4': (10, 10, 10), + 'grey40': (102, 102, 102), + 'grey41': (105, 105, 105), + 'grey42': (107, 107, 107), + 'grey43': (110, 110, 110), + 'grey44': (112, 112, 112), + 'grey45': (115, 115, 115), + 'grey46': (117, 117, 117), + 'grey47': (120, 120, 120), + 'grey48': (122, 122, 122), + 'grey49': (125, 125, 125), + 'grey5': (13, 13, 13), + 'grey50': (127, 127, 127), + 'grey51': (130, 130, 130), + 'grey52': (133, 133, 133), + 'grey53': (135, 135, 135), + 'grey54': (138, 138, 138), + 'grey55': (140, 140, 140), + 'grey56': (143, 143, 143), + 'grey57': (145, 145, 145), + 'grey58': (148, 148, 148), + 'grey59': (150, 150, 150), + 'grey6': (15, 15, 15), + 'grey60': (153, 153, 153), + 'grey61': (156, 156, 156), + 'grey62': (158, 158, 158), + 'grey63': (161, 161, 161), + 'grey64': (163, 163, 163), + 'grey65': (166, 166, 166), + 'grey66': (168, 168, 168), + 'grey67': (171, 171, 171), + 'grey68': (173, 173, 173), + 'grey69': (176, 176, 176), + 'grey7': (18, 18, 18), + 'grey70': (179, 179, 179), + 'grey71': (181, 181, 181), + 'grey72': (184, 184, 184), + 'grey73': (186, 186, 186), + 'grey74': (189, 189, 189), + 'grey75': (191, 191, 191), + 'grey76': (194, 194, 194), + 'grey77': (196, 196, 196), + 'grey78': (199, 199, 199), + 'grey79': (201, 201, 201), + 'grey8': (20, 20, 20), + 'grey80': (204, 204, 204), + 'grey81': (207, 207, 207), + 'grey82': (209, 209, 209), + 'grey83': (212, 212, 212), + 'grey84': (214, 214, 214), + 'grey85': (217, 217, 217), + 'grey86': (219, 219, 219), + 'grey87': (222, 222, 222), + 'grey88': (224, 224, 224), + 'grey89': (227, 227, 227), + 'grey9': (23, 23, 23), + 'grey90': (229, 229, 229), + 'grey91': (232, 232, 232), + 'grey92': (235, 235, 235), + 'grey93': (237, 237, 237), + 'grey94': (240, 240, 240), + 'grey95': (242, 242, 242), + 'grey96': (245, 245, 245), + 'grey97': (247, 247, 247), + 'grey98': (250, 250, 250), + 'grey99': (252, 252, 252), + 'honeydew': (240, 255, 240), + 'honeydew1': (240, 255, 240), + 'honeydew2': (224, 238, 224), + 'honeydew3': (193, 205, 193), + 'honeydew4': (131, 139, 131), + 'hot pink': (255, 105, 180), + 'hotpink': (255, 105, 180), + 'hotpink1': (255, 110, 180), + 'hotpink2': (238, 106, 167), + 'hotpink3': (205, 96, 144), + 'hotpink4': (139, 58, 98), + 'indian red': (205, 92, 92), + 'indianred': (205, 92, 92), + 'indianred1': (255, 106, 106), + 'indianred2': (238, 99, 99), + 'indianred3': (205, 85, 85), + 'indianred4': (139, 58, 58), + 'ivory': (255, 255, 240), + 'ivory1': (255, 255, 240), + 'ivory2': (238, 238, 224), + 'ivory3': (205, 205, 193), + 'ivory4': (139, 139, 131), + 'khaki': (240, 230, 140), + 'khaki1': (255, 246, 143), + 'khaki2': (238, 230, 133), + 'khaki3': (205, 198, 115), + 'khaki4': (139, 134, 78), + 'lavender': (230, 230, 250), + 'lavender blush': (255, 240, 245), + 'lavenderblush': (255, 240, 245), + 'lavenderblush1': (255, 240, 245), + 'lavenderblush2': (238, 224, 229), + 'lavenderblush3': (205, 193, 197), + 'lavenderblush4': (139, 131, 134), + 'lawn green': (124, 252, 0), + 'lawngreen': (124, 252, 0), + 'lemon chiffon': (255, 250, 205), + 'lemonchiffon': (255, 250, 205), + 'lemonchiffon1': (255, 250, 205), + 'lemonchiffon2': (238, 233, 191), + 'lemonchiffon3': (205, 201, 165), + 'lemonchiffon4': (139, 137, 112), + 'light blue': (173, 216, 230), + 'light coral': (240, 128, 128), + 'light cyan': (224, 255, 255), + 'light goldenrod': (238, 221, 130), + 'light goldenrod yellow': (250, 250, 210), + 'light gray': (211, 211, 211), + 'light green': (144, 238, 144), + 'light grey': (211, 211, 211), + 'light pink': (255, 182, 193), + 'light salmon': (255, 160, 122), + 'light sea green': (32, 178, 170), + 'light sky blue': (135, 206, 250), + 'light slate blue': (132, 112, 255), + 'light slate gray': (119, 136, 153), + 'light slate grey': (119, 136, 153), + 'light steel blue': (176, 196, 222), + 'light yellow': (255, 255, 224), + 'lightblue': (173, 216, 230), + 'lightblue1': (191, 239, 255), + 'lightblue2': (178, 223, 238), + 'lightblue3': (154, 192, 205), + 'lightblue4': (104, 131, 139), + 'lightcoral': (240, 128, 128), + 'lightcyan': (224, 255, 255), + 'lightcyan1': (224, 255, 255), + 'lightcyan2': (209, 238, 238), + 'lightcyan3': (180, 205, 205), + 'lightcyan4': (122, 139, 139), + 'lightgoldenrod': (238, 221, 130), + 'lightgoldenrod1': (255, 236, 139), + 'lightgoldenrod2': (238, 220, 130), + 'lightgoldenrod3': (205, 190, 112), + 'lightgoldenrod4': (139, 129, 76), + 'lightgoldenrodyellow': (250, 250, 210), + 'lightgray': (211, 211, 211), + 'lightgreen': (144, 238, 144), + 'lightgrey': (211, 211, 211), + 'lightpink': (255, 182, 193), + 'lightpink1': (255, 174, 185), + 'lightpink2': (238, 162, 173), + 'lightpink3': (205, 140, 149), + 'lightpink4': (139, 95, 101), + 'lightsalmon': (255, 160, 122), + 'lightsalmon1': (255, 160, 122), + 'lightsalmon2': (238, 149, 114), + 'lightsalmon3': (205, 129, 98), + 'lightsalmon4': (139, 87, 66), + 'lightseagreen': (32, 178, 170), + 'lightskyblue': (135, 206, 250), + 'lightskyblue1': (176, 226, 255), + 'lightskyblue2': (164, 211, 238), + 'lightskyblue3': (141, 182, 205), + 'lightskyblue4': (96, 123, 139), + 'lightslateblue': (132, 112, 255), + 'lightslategray': (119, 136, 153), + 'lightslategrey': (119, 136, 153), + 'lightsteelblue': (176, 196, 222), + 'lightsteelblue1': (202, 225, 255), + 'lightsteelblue2': (188, 210, 238), + 'lightsteelblue3': (162, 181, 205), + 'lightsteelblue4': (110, 123, 139), + 'lightyellow': (255, 255, 224), + 'lightyellow1': (255, 255, 224), + 'lightyellow2': (238, 238, 209), + 'lightyellow3': (205, 205, 180), + 'lightyellow4': (139, 139, 122), + 'lime green': (50, 205, 50), + 'limegreen': (50, 205, 50), + 'linen': (250, 240, 230), + 'magenta': (255, 0, 255), + 'magenta1': (255, 0, 255), + 'magenta2': (238, 0, 238), + 'magenta3': (205, 0, 205), + 'magenta4': (139, 0, 139), + 'maroon': (176, 48, 96), + 'maroon1': (255, 52, 179), + 'maroon2': (238, 48, 167), + 'maroon3': (205, 41, 144), + 'maroon4': (139, 28, 98), + 'medium aquamarine': (102, 205, 170), + 'medium blue': (0, 0, 205), + 'medium orchid': (186, 85, 211), + 'medium purple': (147, 112, 219), + 'medium sea green': (60, 179, 113), + 'medium slate blue': (123, 104, 238), + 'medium spring green': (0, 250, 154), + 'medium turquoise': (72, 209, 204), + 'medium violet red': (199, 21, 133), + 'mediumaquamarine': (102, 205, 170), + 'mediumblue': (0, 0, 205), + 'mediumorchid': (186, 85, 211), + 'mediumorchid1': (224, 102, 255), + 'mediumorchid2': (209, 95, 238), + 'mediumorchid3': (180, 82, 205), + 'mediumorchid4': (122, 55, 139), + 'mediumpurple': (147, 112, 219), + 'mediumpurple1': (171, 130, 255), + 'mediumpurple2': (159, 121, 238), + 'mediumpurple3': (137, 104, 205), + 'mediumpurple4': (93, 71, 139), + 'mediumseagreen': (60, 179, 113), + 'mediumslateblue': (123, 104, 238), + 'mediumspringgreen': (0, 250, 154), + 'mediumturquoise': (72, 209, 204), + 'mediumvioletred': (199, 21, 133), + 'midnight blue': (25, 25, 112), + 'midnightblue': (25, 25, 112), + 'mint cream': (245, 255, 250), + 'mintcream': (245, 255, 250), + 'misty rose': (255, 228, 225), + 'mistyrose': (255, 228, 225), + 'mistyrose1': (255, 228, 225), + 'mistyrose2': (238, 213, 210), + 'mistyrose3': (205, 183, 181), + 'mistyrose4': (139, 125, 123), + 'moccasin': (255, 228, 181), + 'navajo white': (255, 222, 173), + 'navajowhite': (255, 222, 173), + 'navajowhite1': (255, 222, 173), + 'navajowhite2': (238, 207, 161), + 'navajowhite3': (205, 179, 139), + 'navajowhite4': (139, 121, 94), + 'navy': (0, 0, 128), + 'navy blue': (0, 0, 128), + 'navyblue': (0, 0, 128), + 'old lace': (253, 245, 230), + 'oldlace': (253, 245, 230), + 'olive drab': (107, 142, 35), + 'olivedrab': (107, 142, 35), + 'olivedrab1': (192, 255, 62), + 'olivedrab2': (179, 238, 58), + 'olivedrab3': (154, 205, 50), + 'olivedrab4': (105, 139, 34), + 'orange': (255, 165, 0), + 'orange red': (255, 69, 0), + 'orange1': (255, 165, 0), + 'orange2': (238, 154, 0), + 'orange3': (205, 133, 0), + 'orange4': (139, 90, 0), + 'orangered': (255, 69, 0), + 'orangered1': (255, 69, 0), + 'orangered2': (238, 64, 0), + 'orangered3': (205, 55, 0), + 'orangered4': (139, 37, 0), + 'orchid': (218, 112, 214), + 'orchid1': (255, 131, 250), + 'orchid2': (238, 122, 233), + 'orchid3': (205, 105, 201), + 'orchid4': (139, 71, 137), + 'pale goldenrod': (238, 232, 170), + 'pale green': (152, 251, 152), + 'pale turquoise': (175, 238, 238), + 'pale violet red': (219, 112, 147), + 'palegoldenrod': (238, 232, 170), + 'palegreen': (152, 251, 152), + 'palegreen1': (154, 255, 154), + 'palegreen2': (144, 238, 144), + 'palegreen3': (124, 205, 124), + 'palegreen4': (84, 139, 84), + 'paleturquoise': (175, 238, 238), + 'paleturquoise1': (187, 255, 255), + 'paleturquoise2': (174, 238, 238), + 'paleturquoise3': (150, 205, 205), + 'paleturquoise4': (102, 139, 139), + 'palevioletred': (219, 112, 147), + 'palevioletred1': (255, 130, 171), + 'palevioletred2': (238, 121, 159), + 'palevioletred3': (205, 104, 127), + 'palevioletred4': (139, 71, 93), + 'papaya whip': (255, 239, 213), + 'papayawhip': (255, 239, 213), + 'peach puff': (255, 218, 185), + 'peachpuff': (255, 218, 185), + 'peachpuff1': (255, 218, 185), + 'peachpuff2': (238, 203, 173), + 'peachpuff3': (205, 175, 149), + 'peachpuff4': (139, 119, 101), + 'peru': (205, 133, 63), + 'pink': (255, 192, 203), + 'pink1': (255, 181, 197), + 'pink2': (238, 169, 184), + 'pink3': (205, 145, 158), + 'pink4': (139, 99, 108), + 'plum': (221, 160, 221), + 'plum1': (255, 187, 255), + 'plum2': (238, 174, 238), + 'plum3': (205, 150, 205), + 'plum4': (139, 102, 139), + 'powder blue': (176, 224, 230), + 'powderblue': (176, 224, 230), + 'purple': (160, 32, 240), + 'purple1': (155, 48, 255), + 'purple2': (145, 44, 238), + 'purple3': (125, 38, 205), + 'purple4': (85, 26, 139), + 'red': (255, 0, 0), + 'red1': (255, 0, 0), + 'red2': (238, 0, 0), + 'red3': (205, 0, 0), + 'red4': (139, 0, 0), + 'rosy brown': (188, 143, 143), + 'rosybrown': (188, 143, 143), + 'rosybrown1': (255, 193, 193), + 'rosybrown2': (238, 180, 180), + 'rosybrown3': (205, 155, 155), + 'rosybrown4': (139, 105, 105), + 'royal blue': (65, 105, 225), + 'royalblue': (65, 105, 225), + 'royalblue1': (72, 118, 255), + 'royalblue2': (67, 110, 238), + 'royalblue3': (58, 95, 205), + 'royalblue4': (39, 64, 139), + 'saddle brown': (139, 69, 19), + 'saddlebrown': (139, 69, 19), + 'salmon': (250, 128, 114), + 'salmon1': (255, 140, 105), + 'salmon2': (238, 130, 98), + 'salmon3': (205, 112, 84), + 'salmon4': (139, 76, 57), + 'sandy brown': (244, 164, 96), + 'sandybrown': (244, 164, 96), + 'sea green': (46, 139, 87), + 'seagreen': (46, 139, 87), + 'seagreen1': (84, 255, 159), + 'seagreen2': (78, 238, 148), + 'seagreen3': (67, 205, 128), + 'seagreen4': (46, 139, 87), + 'seashell': (255, 245, 238), + 'seashell1': (255, 245, 238), + 'seashell2': (238, 229, 222), + 'seashell3': (205, 197, 191), + 'seashell4': (139, 134, 130), + 'sienna': (160, 82, 45), + 'sienna1': (255, 130, 71), + 'sienna2': (238, 121, 66), + 'sienna3': (205, 104, 57), + 'sienna4': (139, 71, 38), + 'sky blue': (135, 206, 235), + 'skyblue': (135, 206, 235), + 'skyblue1': (135, 206, 255), + 'skyblue2': (126, 192, 238), + 'skyblue3': (108, 166, 205), + 'skyblue4': (74, 112, 139), + 'slate blue': (106, 90, 205), + 'slate gray': (112, 128, 144), + 'slate grey': (112, 128, 144), + 'slateblue': (106, 90, 205), + 'slateblue1': (131, 111, 255), + 'slateblue2': (122, 103, 238), + 'slateblue3': (105, 89, 205), + 'slateblue4': (71, 60, 139), + 'slategray': (112, 128, 144), + 'slategray1': (198, 226, 255), + 'slategray2': (185, 211, 238), + 'slategray3': (159, 182, 205), + 'slategray4': (108, 123, 139), + 'slategrey': (112, 128, 144), + 'snow': (255, 250, 250), + 'snow1': (255, 250, 250), + 'snow2': (238, 233, 233), + 'snow3': (205, 201, 201), + 'snow4': (139, 137, 137), + 'spring green': (0, 255, 127), + 'springgreen': (0, 255, 127), + 'springgreen1': (0, 255, 127), + 'springgreen2': (0, 238, 118), + 'springgreen3': (0, 205, 102), + 'springgreen4': (0, 139, 69), + 'steel blue': (70, 130, 180), + 'steelblue': (70, 130, 180), + 'steelblue1': (99, 184, 255), + 'steelblue2': (92, 172, 238), + 'steelblue3': (79, 148, 205), + 'steelblue4': (54, 100, 139), + 'tan': (210, 180, 140), + 'tan1': (255, 165, 79), + 'tan2': (238, 154, 73), + 'tan3': (205, 133, 63), + 'tan4': (139, 90, 43), + 'thistle': (216, 191, 216), + 'thistle1': (255, 225, 255), + 'thistle2': (238, 210, 238), + 'thistle3': (205, 181, 205), + 'thistle4': (139, 123, 139), + 'tomato': (255, 99, 71), + 'tomato1': (255, 99, 71), + 'tomato2': (238, 92, 66), + 'tomato3': (205, 79, 57), + 'tomato4': (139, 54, 38), + 'turquoise': (64, 224, 208), + 'turquoise1': (0, 245, 255), + 'turquoise2': (0, 229, 238), + 'turquoise3': (0, 197, 205), + 'turquoise4': (0, 134, 139), + 'violet': (238, 130, 238), + 'violet red': (208, 32, 144), + 'violetred': (208, 32, 144), + 'violetred1': (255, 62, 150), + 'violetred2': (238, 58, 140), + 'violetred3': (205, 50, 120), + 'violetred4': (139, 34, 82), + 'wheat': (245, 222, 179), + 'wheat1': (255, 231, 186), + 'wheat2': (238, 216, 174), + 'wheat3': (205, 186, 150), + 'wheat4': (139, 126, 102), + 'white': (255, 255, 255), + 'white smoke': (245, 245, 245), + 'whitesmoke': (245, 245, 245), + 'yellow': (255, 255, 0), + 'yellow green': (154, 205, 50), + 'yellow1': (255, 255, 0), + 'yellow2': (238, 238, 0), + 'yellow3': (205, 205, 0), + 'yellow4': (139, 139, 0), + 'yellowgreen': (154, 205, 50), +} + +class ColorDB: + + def __init__(self): + self.colordata = data + + def byname(self, name): + """ Find color by name. """ + try: + return self.colordata[name] + except KeyError: + pass + try: + return self.colordata[name.lower()] + except KeyError: + pass + raise KeyError, name + + def blend(self, color1, color2): + """ "Blend" two colors, i.e. take their average RGB values. """ + if isinstance(color1, str): + color1 = self.byname(color1) + if isinstance(color2, str): + color2 = self.byname(color2) + return tuple([(v1+v2)/2 for (v1, v2) in zip(color1, color2)]) + + def blend_weighed(self, color1, weight1, color2, weight2): + """ Blend two colors, using a weighing factor. """ + if isinstance(color1, str): + color1 = self.byname(color1) + if isinstance(color2, str): + color2 = self.byname(color2) + total_weight = weight1 + weight2 + return tuple([(v1*weight1 + v2*weight2) / total_weight + for (v1, v2) in zip(color1, color2)]) + + def invert(self, color): + if isinstance(color, str): + color = self.byname(str) + return tuple([255 - v for v in color]) + + def findcolors(self, color, numresults=5): + """ Find the topmost <numresults> colors in the color database that + are closest to <color>. Useful for finding the name of a color. + <color> is a tuple (r, g, b). + + Returns a list of tuples (distance, name, (r, g, b). + """ + if isinstance(color, str): + color = self.byname(color) + + def sqr(x): return x*x + def distance(color1, color2): + squares = [sqr(abs(v1-v2)) for (v1, v2) in zip(color1, color2)] + sum = reduce(operator.add, squares) + return math.sqrt(sum) + + results = {} + for (name, acolor) in self.colordata.items(): + dist = distance(color, acolor) + results[dist] = (dist, name, acolor) + + results = results.values() + results.sort() + return results[:numresults] + + def __getitem__(self, name): + return self.byname(name) + + def hex(self, name): + rgb = self.byname(name) + return "%02x%02x%02x" % rgb + +_colordb = ColorDB() diff --git a/pynxc/waxy/colourdialog.py b/pynxc/waxy/colourdialog.py new file mode 100644 index 0000000..5ccd797 --- /dev/null +++ b/pynxc/waxy/colourdialog.py @@ -0,0 +1,34 @@ +import wx +import waxyobject +from font import Font + +class ColourDialog(wx.ColourDialog, waxyobject.WaxyObject): + + def __init__(self, parent): + wx.ColourDialog.__init__(self, parent) + # Ensure the full colour dialog is displayed, + # not the abbreviated version. + self.GetColourData().SetChooseFull(True) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.ColourDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenColour(self): + """ Shorthand... """ + data = self.GetColourData() + color = data.GetColour().Get() + return color + +class ColorDialog(ColourDialog): + + + def GetChosenColor(self): + """ Shorthand... """ + data = self.GetColourData() + color = data.GetColour().Get() + return color diff --git a/pynxc/waxy/colourdialog.py~ b/pynxc/waxy/colourdialog.py~ new file mode 100644 index 0000000..5ccd797 --- /dev/null +++ b/pynxc/waxy/colourdialog.py~ @@ -0,0 +1,34 @@ +import wx +import waxyobject +from font import Font + +class ColourDialog(wx.ColourDialog, waxyobject.WaxyObject): + + def __init__(self, parent): + wx.ColourDialog.__init__(self, parent) + # Ensure the full colour dialog is displayed, + # not the abbreviated version. + self.GetColourData().SetChooseFull(True) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.ColourDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenColour(self): + """ Shorthand... """ + data = self.GetColourData() + color = data.GetColour().Get() + return color + +class ColorDialog(ColourDialog): + + + def GetChosenColor(self): + """ Shorthand... """ + data = self.GetColourData() + color = data.GetColour().Get() + return color diff --git a/pynxc/waxy/combobox.py b/pynxc/waxy/combobox.py new file mode 100644 index 0000000..a39cff3 --- /dev/null +++ b/pynxc/waxy/combobox.py @@ -0,0 +1,50 @@ +# combobox.py + +import wx +import containers +import styles +import waxyobject + +class ComboBox(wx.ComboBox, waxyobject.WaxyObject): + + __events__ = { + 'Select': wx.EVT_COMBOBOX, + 'TextChanged': wx.EVT_TEXT, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.ComboBox.__init__(self, parent, wx.NewId(), "", + size=size or (-1,-1), choices=choices, style=style) + + self.BindEvents() + styles.properties(self, kwargs) + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + + # + # style parameters + + def _params(self, kwargs): + flags = wx.CB_DROPDOWN # default + flags |= styles.stylebool('simple', wx.CB_SIMPLE, kwargs) + flags |= styles.stylebool('readonly', wx.CB_READONLY, kwargs) + flags |= styles.stylebool('sort', wx.CB_SORT, kwargs) + return flags diff --git a/pynxc/waxy/combobox.py~ b/pynxc/waxy/combobox.py~ new file mode 100644 index 0000000..853cdb4 --- /dev/null +++ b/pynxc/waxy/combobox.py~ @@ -0,0 +1,51 @@ +# combobox.py + +import wx +import containers +import styles +import waxyobject + +class ComboBox(wx.ComboBox, waxyobject.WaxyObject): + + __events__ = { + 'Select': wx.EVT_COMBOBOX, + 'TextChanged': wx.EVT_TEXT, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.ComboBox.__init__(self, parent, wx.NewId(), "", + size=size or (-1,-1), choices=choices, style=style) + self.SetDefaultFont() + + self.BindEvents() + styles.properties(self, kwargs) + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + + # + # style parameters + + def _params(self, kwargs): + flags = wx.CB_DROPDOWN # default + flags |= styles.stylebool('simple', wx.CB_SIMPLE, kwargs) + flags |= styles.stylebool('readonly', wx.CB_READONLY, kwargs) + flags |= styles.stylebool('sort', wx.CB_SORT, kwargs) + return flags diff --git a/pynxc/waxy/constants.py b/pynxc/waxy/constants.py new file mode 100644 index 0000000..c2a448c --- /dev/null +++ b/pynxc/waxy/constants.py @@ -0,0 +1,3 @@ +from wx import MEDIUM_GREY_PEN + +Medium_Grey_Pen=MEDIUM_GREY_PEN
\ No newline at end of file diff --git a/pynxc/waxy/containers.py b/pynxc/waxy/containers.py new file mode 100644 index 0000000..b781ccc --- /dev/null +++ b/pynxc/waxy/containers.py @@ -0,0 +1,311 @@ +# containers.py
+# Containers are mixin classes that have a sizer and a number of methods to
+# deal with that sizer (add components, etc). Used to implement fairly
+# "basic" controls like Panel and Frame. When in doubt, derive from those
+# two rather than making up your own container construct.
+
+import utils
+import waxyobject
+import wx
+import warnings
+
+class Container(waxyobject.WaxyObject):
+
+ def _create_sizer(self, direction):
+ if direction.lower().startswith("h"):
+ dir = wx.HORIZONTAL
+ elif direction.lower().startswith("v"):
+ dir = wx.VERTICAL
+ else:
+ raise ValueError, "Incorrect direction"
+ self.sizer = wx.BoxSizer(dir)
+ self._packed = 0
+
+ def Body(self):
+ """ Optionally override this to create components. Add them with the
+ AddComponent() method. """
+
+ def AddComponent(self, comp, expand=0, stretch=0, align=None, border=0):
+ # expand: expands a component in the direction of the panel/sizer
+ # stretch: expands a component in the other direction
+ # for example, if we have a horizontal panel, and resize the window
+ # both horizontally and vertically, then a component with 'expand'
+ # will expand horizontally, and one with 'stretch' will expand
+ # vertically. (See simplebuttons.py)
+
+ if isinstance(expand, str):
+ expand = expand.lower()
+ if expand.startswith("h"):
+ if self.GetOrientation() == 'horizontal':
+ expand, stretch = 1, 0
+ else:
+ expand, stretch = 0, 1
+ elif expand.startswith("v"):
+ if self.GetOrientation() == 'horizontal':
+ expand, stretch = 0, 1
+ else:
+ expand, stretch = 1, 0
+ elif expand.startswith("b"):
+ expand = stretch = 1
+ elif expand == '':
+ expand = stretch = 0
+ else:
+ raise ValueError, "Invalid value for expand: %r" % (expand,)
+
+ flags = 0
+ if stretch:
+ flags |= wx.EXPAND
+ if align:
+ flags |= {
+ "t": wx.ALIGN_TOP,
+ "c": wx.ALIGN_CENTER,
+ "b": wx.ALIGN_BOTTOM,
+ "r": wx.ALIGN_RIGHT,
+ "l": wx.ALIGN_LEFT,
+ }.get(align.lower()[:1], 0)
+ if border:
+ flags |= wx.ALL
+
+ flags |= wx.FIXED_MINSIZE
+ if 0 and hasattr(comp, 'sizer') and hasattr(comp, '_include_sizer'):
+ # ugly hack to add nested sizer rather than its frame
+ # only for certain quirky controls, like GroupBox!
+ self.sizer.Add(comp.sizer, expand, flags)
+ else:
+ self.sizer.Add(comp, expand, flags, border)
+ # comp can be a component or a tuple (width, height), but the
+ # Add() method is called just the same, as of wxPython 2.5.1.5
+
+ def AddSpace(self, width, height=None, *args, **kwargs):
+ if height is None:
+ height = width
+ return self.AddComponent((width, height), *args, **kwargs)
+ AddSeparator = AddSpace
+
+ def Pack(self):
+ if not self._packed:
+ self.SetSizerAndFit(self.sizer)
+ self._packed = 1
+
+ def Repack(self):
+ self.sizer.RecalcSizes()
+
+ def GetOrientation(self):
+ """ Return 'horizontal' or 'vertical'. """
+ orientation = self.sizer.GetOrientation()
+ if orientation == wx.HORIZONTAL:
+ return 'horizontal'
+ elif orientation == wx.VERTICAL:
+ return 'vertical'
+ else:
+ raise ValueError, "Unknown direction for sizer"
+
+#
+# GridContainer (used to implement GridPanel)
+
+class GridContainer(Container):
+
+ _sizerclass = wx.GridSizer
+
+ alignment = {
+ 'b': wx.ALIGN_BOTTOM,
+ 'r': wx.ALIGN_RIGHT,
+ 'l': wx.ALIGN_LEFT,
+ 'c': wx.ALIGN_CENTER,
+ 't': wx.ALIGN_TOP,
+ 'h': wx.ALIGN_CENTER_HORIZONTAL,
+ 'v': wx.ALIGN_CENTER_VERTICAL,
+ }
+
+ def _create_sizer(self, rows, cols, hgap=1, vgap=1):
+ self.sizer = self._sizerclass(rows, cols, vgap, hgap)
+ self.controls = {}
+ for row in range(rows):
+ for col in range(cols):
+ self.controls[col, row] = None
+ # (col, row) allows for (x, y)-like calling
+ self._packed = 0
+
+ def AddComponent(self, col, row, obj, expand=1, align='', border=0, stretch=0, proportion=0):
+ # make sure the parents are correct
+ if stretch:
+ warnings.warn("stretch is deprecated and has no effect here")
+
+ if self.controls[col, row]:
+ raise ValueError, "A control has already been set for position (%s, %s)" % (row, col)
+ self.controls[col, row] = {'obj': obj, 'expand': expand, 'align': align,
+ 'border': border, 'proportion': proportion}
+
+ def Pack(self):
+ if not self._packed:
+ controls = self._AllControls()
+ self.sizer.AddMany(controls)
+ self.SetSizerAndFit(self.sizer) # is this still necessary?
+ self._packed = 1
+
+ def __setitem__(self, index, value):
+ col, row = index
+ self.AddComponent(col, row, value)
+
+ def __getitem__(self, index):
+ col, row = index
+ return self.controls[col, row]['obj'] # may raise KeyError
+
+ def _AllControls(self):
+ controls = []
+ for row in range(self.sizer.GetRows()):
+ for col in range(self.sizer.GetCols()):
+ d = self.controls[col, row]
+ if d is None:
+ from panel import Panel
+ p = Panel(self) # hack up a dummy panel
+ controls.append((p, 0, wx.EXPAND|wx.FIXED_MINSIZE))
+ else:
+ obj = d['obj']
+
+ # set alignment
+ align = d['align'].lower()
+ alignment = 0
+ for key, value in self.__class__.alignment.items():
+ if key in align:
+ alignment |= value
+
+ z = d['expand'] and wx.EXPAND
+ z |= alignment
+ border = d['border']
+ #if border and not alignment:
+ if border:
+ z |= wx.ALL
+ z |= wx.FIXED_MINSIZE
+ proportion = d['proportion']
+ controls.append((obj, proportion, z, border))
+
+ return controls
+
+ # XXX maybe a Wax version of AddMany() would be useful?
+
+#
+# FlexGridContainer
+
+class FlexGridContainer(GridContainer):
+ _sizerclass = wx.FlexGridSizer
+
+ def AddGrowableRow(self, row):
+ self.sizer.AddGrowableRow(row)
+
+ def AddGrowableCol(self, col):
+ self.sizer.AddGrowableCol(col)
+
+#
+# OverlayContainer
+
+class OverlaySizer(wx.PySizer):
+ def __init__(self):
+ wx.PySizer.__init__(self)
+
+ def CalcMin(self):
+ maxx, maxy = 0, 0
+ for win in self.GetChildren():
+ x, y = win.CalcMin()
+ maxx = max(maxx, x)
+ maxy = max(maxy, y)
+ return wx.Size(maxx, maxy)
+
+ def RecalcSizes(self):
+ pos = self.GetPosition()
+ size = self.GetSize()
+ for win in self.GetChildren():
+ win.SetDimension(pos, size)
+
+
+class OverlayContainer(Container):
+ """ Container that takes an arbitrary number of windows, and stacks them
+ on top of each other. Controls are hidden by default. """
+
+ def _create_sizer(self):
+ self.sizer = OverlaySizer()
+ self.windows = []
+ self._packed = 0
+
+ def AddComponent(self, window, expand=0, stretch=0, align=None, border=0):
+ """
+ # make sure the parents are correct
+ if waxconfig.WaxConfig.check_parent:
+ if window.GetParent() is not self:
+ utils.parent_warning(window, self)
+
+ flags = 0
+ if stretch:
+ flags |= wx.EXPAND
+ if align:
+ flags |= {
+ "t": wx.ALIGN_TOP,
+ "c": wx.ALIGN_CENTER,
+ "b": wx.ALIGN_BOTTOM,
+ "r": wx.ALIGN_RIGHT,
+ "l": wx.ALIGN_LEFT,
+ }.get(align.lower()[:1], 0)
+ if border:
+ flags |= wx.ALL
+ flags |= wx.FIXED_MINSIZE
+
+ self.sizer.Add(window, expand, flags, border)
+ """
+ Container.AddComponent(self, window, expand, stretch, align, border)
+ self.windows.append(window)
+ window.Hide() # default is hiding
+
+
+
+#
+# GroupBoxContainer
+
+class GroupBoxContainer(Container):
+
+ def _create_sizer(self, groupbox, direction='h'):
+ direction = direction.lower()
+ if direction.startswith('v'):
+ dir = wx.VERTICAL
+ elif direction.startswith('h'):
+ dir = wx.HORIZONTAL
+ else:
+ raise ValueError, "Unknown direction: %s" % (direction,)
+
+ self.sizer = wx.StaticBoxSizer(groupbox, dir)
+ self._packed = 0
+
+#
+# PlainContainer
+
+class PlainContainer(Container):
+ """ A container without a sizer. Controls must be added at a given position.
+ Size can be specified as well.
+ """
+
+ def _create_sizer(self):
+ self.sizer = None
+ self._packed = 0 # included for compatibility
+
+ def AddComponent(self, x, y, comp):
+ # make sure the parents are correct
+
+ comp.SetPosition((x, y))
+
+ def AddComponentAndSize(self, x, y, sx, sy, comp):
+ # make sure the parents are correct
+
+ comp.SetPosition((x, y))
+ comp.SetSize((sx, sy))
+
+ def Pack(self):
+ self._packed = 1 # useless, but included for compatibility
+
+ if len(self.Children) == 1:
+ import panel
+ dummy = panel.Panel(self, size=(0,0))
+ dummy.Position = 0, 0
+ self.__dummy = dummy
+
+ def Repack():
+ pass
+
diff --git a/pynxc/waxy/containers.py~ b/pynxc/waxy/containers.py~ new file mode 100644 index 0000000..5c8c70d --- /dev/null +++ b/pynxc/waxy/containers.py~ @@ -0,0 +1,314 @@ +# containers.py
+# Containers are mixin classes that have a sizer and a number of methods to
+# deal with that sizer (add components, etc). Used to implement fairly
+# "basic" controls like Panel and Frame. When in doubt, derive from those
+# two rather than making up your own container construct.
+
+import utils
+import waxyobject
+import wx
+import warnings
+
+class Container(waxyobject.WaxyObject):
+
+ def _create_sizer(self, direction):
+ if direction.lower().startswith("h"):
+ dir = wx.HORIZONTAL
+ elif direction.lower().startswith("v"):
+ dir = wx.VERTICAL
+ else:
+ raise ValueError, "Incorrect direction"
+ self.sizer = wx.BoxSizer(dir)
+ self._packed = 0
+
+ def Body(self):
+ """ Optionally override this to create components. Add them with the
+ AddComponent() method. """
+
+ def AddComponent(self, comp, expand=0, stretch=0, align=None, border=0):
+ # expand: expands a component in the direction of the panel/sizer
+ # stretch: expands a component in the other direction
+ # for example, if we have a horizontal panel, and resize the window
+ # both horizontally and vertically, then a component with 'expand'
+ # will expand horizontally, and one with 'stretch' will expand
+ # vertically. (See simplebuttons.py)
+
+ if isinstance(expand, str):
+ expand = expand.lower()
+ if expand.startswith("h"):
+ if self.GetOrientation() == 'horizontal':
+ expand, stretch = 1, 0
+ else:
+ expand, stretch = 0, 1
+ elif expand.startswith("v"):
+ if self.GetOrientation() == 'horizontal':
+ expand, stretch = 0, 1
+ else:
+ expand, stretch = 1, 0
+ elif expand.startswith("b"):
+ expand = stretch = 1
+ elif expand == '':
+ expand = stretch = 0
+ else:
+ raise ValueError, "Invalid value for expand: %r" % (expand,)
+
+ flags = 0
+ if stretch:
+ flags |= wx.EXPAND
+ if align:
+ flags |= {
+ "t": wx.ALIGN_TOP,
+ "c": wx.ALIGN_CENTER,
+ "b": wx.ALIGN_BOTTOM,
+ "r": wx.ALIGN_RIGHT,
+ "l": wx.ALIGN_LEFT,
+ }.get(align.lower()[:1], 0)
+ if border:
+ flags |= wx.ALL
+
+ flags |= wx.FIXED_MINSIZE
+ if 0 and hasattr(comp, 'sizer') and hasattr(comp, '_include_sizer'):
+ # ugly hack to add nested sizer rather than its frame
+ # only for certain quirky controls, like GroupBox!
+ self.sizer.Add(comp.sizer, expand, flags)
+ else:
+ self.sizer.Add(comp, expand, flags, border)
+ # comp can be a component or a tuple (width, height), but the
+ # Add() method is called just the same, as of wxPython 2.5.1.5
+
+ def AddSpace(self, width, height=None, *args, **kwargs):
+ if height is None:
+ height = width
+ return self.AddComponent((width, height), *args, **kwargs)
+ AddSeparator = AddSpace
+
+ def Pack(self):
+ if not self._packed:
+ self.SetSizerAndFit(self.sizer)
+ self._packed = 1
+
+ def Repack(self):
+ self.sizer.RecalcSizes()
+
+ def GetOrientation(self):
+ """ Return 'horizontal' or 'vertical'. """
+ orientation = self.sizer.GetOrientation()
+ if orientation == wx.HORIZONTAL:
+ return 'horizontal'
+ elif orientation == wx.VERTICAL:
+ return 'vertical'
+ else:
+ raise ValueError, "Unknown direction for sizer"
+
+#
+# GridContainer (used to implement GridPanel)
+
+class GridContainer(Container):
+
+ _sizerclass = wx.GridSizer
+
+ alignment = {
+ 'b': wx.ALIGN_BOTTOM,
+ 'r': wx.ALIGN_RIGHT,
+ 'l': wx.ALIGN_LEFT,
+ 'c': wx.ALIGN_CENTER,
+ 't': wx.ALIGN_TOP,
+ 'h': wx.ALIGN_CENTER_HORIZONTAL,
+ 'v': wx.ALIGN_CENTER_VERTICAL,
+ }
+
+ def _create_sizer(self, rows, cols, hgap=1, vgap=1):
+ self.sizer = self._sizerclass(rows, cols, vgap, hgap)
+ self.controls = {}
+ for row in range(rows):
+ for col in range(cols):
+ self.controls[col, row] = None
+ # (col, row) allows for (x, y)-like calling
+ self._packed = 0
+
+ def AddComponent(self, col, row, obj, expand=1, align='', border=0, stretch=0, proportion=0):
+ # make sure the parents are correct
+ if stretch:
+ warnings.warn("stretch is deprecated and has no effect here")
+
+ if self.controls[col, row]:
+ raise ValueError, "A control has already been set for position (%s, %s)" % (row, col)
+ self.controls[col, row] = {'obj': obj, 'expand': expand, 'align': align,
+ 'border': border, 'proportion': proportion}
+
+ def Pack(self):
+ if not self._packed:
+ controls = self._AllControls()
+ self.sizer.AddMany(controls)
+ self.SetSizerAndFit(self.sizer) # is this still necessary?
+ self._packed = 1
+
+ def __setitem__(self, index, value):
+ col, row = index
+ self.AddComponent(col, row, value)
+
+ def __getitem__(self, index):
+ col, row = index
+ return self.controls[col, row]['obj'] # may raise KeyError
+
+ def _AllControls(self):
+ controls = []
+ for row in range(self.sizer.GetRows()):
+ for col in range(self.sizer.GetCols()):
+ d = self.controls[col, row]
+ if d is None:
+ from panel import Panel
+ p = Panel(self) # hack up a dummy panel
+ controls.append((p, 0, wx.EXPAND|wx.FIXED_MINSIZE))
+ else:
+ obj = d['obj']
+
+ # set alignment
+ align = d['align'].lower()
+ alignment = 0
+ for key, value in self.__class__.alignment.items():
+ if key in align:
+ alignment |= value
+
+ z = d['expand'] and wx.EXPAND
+ z |= alignment
+ border = d['border']
+ #if border and not alignment:
+ if border:
+ z |= wx.ALL
+ z |= wx.FIXED_MINSIZE
+ proportion = d['proportion']
+ controls.append((obj, proportion, z, border))
+
+ return controls
+
+ # XXX maybe a Wax version of AddMany() would be useful?
+
+#
+# FlexGridContainer
+
+class FlexGridContainer(GridContainer):
+ _sizerclass = wx.FlexGridSizer
+
+ def AddGrowableRow(self, row):
+ self.sizer.AddGrowableRow(row)
+
+ def AddGrowableCol(self, col):
+ self.sizer.AddGrowableCol(col)
+
+#
+# OverlayContainer
+
+class OverlaySizer(wx.PySizer):
+ def __init__(self):
+ wx.PySizer.__init__(self)
+
+ def CalcMin(self):
+ maxx, maxy = 0, 0
+ for win in self.GetChildren():
+ x, y = win.CalcMin()
+ maxx = max(maxx, x)
+ maxy = max(maxy, y)
+ return wx.Size(maxx, maxy)
+
+ def RecalcSizes(self):
+ pos = self.GetPosition()
+ size = self.GetSize()
+ for win in self.GetChildren():
+ win.SetDimension(pos, size)
+
+
+class OverlayContainer(Container):
+ """ Container that takes an arbitrary number of windows, and stacks them
+ on top of each other. Controls are hidden by default. """
+
+ def _create_sizer(self):
+ self.sizer = OverlaySizer()
+ self.windows = []
+ self._packed = 0
+
+ def AddComponent(self, window, expand=0, stretch=0, align=None, border=0):
+ """
+ # make sure the parents are correct
+ if waxconfig.WaxConfig.check_parent:
+ if window.GetParent() is not self:
+ utils.parent_warning(window, self)
+
+ flags = 0
+ if stretch:
+ flags |= wx.EXPAND
+ if align:
+ flags |= {
+ "t": wx.ALIGN_TOP,
+ "c": wx.ALIGN_CENTER,
+ "b": wx.ALIGN_BOTTOM,
+ "r": wx.ALIGN_RIGHT,
+ "l": wx.ALIGN_LEFT,
+ }.get(align.lower()[:1], 0)
+ if border:
+ flags |= wx.ALL
+ flags |= wx.FIXED_MINSIZE
+
+ self.sizer.Add(window, expand, flags, border)
+ """
+ Container.AddComponent(self, window, expand, stretch, align, border)
+ self.windows.append(window)
+ window.Hide() # default is hiding
+
+
+
+#
+# GroupBoxContainer
+
+class GroupBoxContainer(Container):
+
+ def _create_sizer(self, groupbox, direction='h'):
+ direction = direction.lower()
+ if direction.startswith('v'):
+ dir = wx.VERTICAL
+ elif direction.startswith('h'):
+ dir = wx.HORIZONTAL
+ else:
+ raise ValueError, "Unknown direction: %s" % (direction,)
+
+ self.sizer = wx.StaticBoxSizer(groupbox, dir)
+ self._packed = 0
+
+#
+# PlainContainer
+
+class PlainContainer(Container):
+ """ A container without a sizer. Controls must be added at a given position.
+ Size can be specified as well.
+ """
+
+ def _create_sizer(self):
+ self.sizer = None
+ self._packed = 0 # included for compatibility
+
+ def AddComponent(self, x, y, comp):
+ # make sure the parents are correct
+
+ comp.SetPosition((x, y))
+
+ def AddComponentAndSize(self, x, y, sx, sy, comp):
+ # make sure the parents are correct
+ if waxconfig.WaxConfig.check_parent:
+ if comp.GetParent() is not self:
+ utils.parent_warning(comp, self)
+
+ comp.SetPosition((x, y))
+ comp.SetSize((sx, sy))
+
+ def Pack(self):
+ self._packed = 1 # useless, but included for compatibility
+
+ if len(self.Children) == 1:
+ import panel
+ dummy = panel.Panel(self, size=(0,0))
+ dummy.Position = 0, 0
+ self.__dummy = dummy
+
+ def Repack():
+ pass
+
diff --git a/pynxc/waxy/core.py b/pynxc/waxy/core.py new file mode 100644 index 0000000..0b58a48 --- /dev/null +++ b/pynxc/waxy/core.py @@ -0,0 +1,36 @@ +DEBUG = 0 # set to 1 to enable debugging messages + +from wx import BeginBusyCursor, CallAfter, EndBusyCursor, GetActiveWindow, \ + GetApp, Platform, SafeYield, WakeUpIdle, Yield, YieldIfNeeded + + + +if False: + required = (2, 8, 0, 0) # minimum wxPython version + required_str = ".".join(map(str, required)) + + # if a multiversion wxPython is installed, attempt to get a required version + try: + # for wxversion, we only take the first two numbers + import wxversion + wxversion_req = ".".join(map(str, required[:2])) + try: + wxversion.ensureMinimal(wxversion_req) + except wxversion.VersionError, e: + # it should also be possible to import wax after wxPython is imported. + # this VersionError prevents this, so we work around it. + if e.args[0].find("must be called before wxPython is imported") < 0: + raise + except ImportError: # will fail if it's not a multiversion installation + pass + + import wx + + assert wx.VERSION >= required, \ + "This version of Wax requires wxPython %s or later" % (required_str,) + + DEBUG = 0 # set to 1 to enable debugging messages + + from wx import BeginBusyCursor, CallAfter, EndBusyCursor, GetActiveWindow, \ + GetApp, Platform, SafeYield, WakeUpIdle, Yield, YieldIfNeeded + diff --git a/pynxc/waxy/core.py~ b/pynxc/waxy/core.py~ new file mode 100644 index 0000000..ef04e1f --- /dev/null +++ b/pynxc/waxy/core.py~ @@ -0,0 +1,2 @@ +required = (2, 8, 0, 0) # minimum wxPython version +required_str = ".".join(map(str, required)) diff --git a/pynxc/waxy/customdialog.py b/pynxc/waxy/customdialog.py new file mode 100644 index 0000000..dfe73b9 --- /dev/null +++ b/pynxc/waxy/customdialog.py @@ -0,0 +1,66 @@ +# customdialog.py + +import wx +import containers +import dialog + +class CustomDialog(wx.Dialog, containers.Container): + + __events__ = dialog.Dialog.__events__.copy() + + def __init__(self, parent, title=""): + wx.Dialog.__init__(self, parent, wx.NewId(), title, wx.DefaultPosition) + + # this should create self.sizer and give access to self.AddComponent + self._create_sizer('vertical') + + # We use EndModal() internally, and that requires that we return + # IDs. _modalhooks is a mapping from ID to desired return value (as a + # string), used by CustomDialog.ShowModal. _count is used for + # generating the unique IDs. + self._modalhooks = {} + self._count = 0 # enumerator + + self.Body() + + self.BindEvents() + self.Pack() + self.Centre() + + def Body(self): + pass + + def _GetEnumValue(self): + self._count = self._count + 1 + return self._count + + def SetBehavior(self, button, result, validator=None, event=None): + """ Set the behavior for the given button. <result> is the desired + result, as a string ('ok', 'cancel', 'foo', etc). <event> is + called, if defined. + Note 1: EndModal() is always called, causing the dialog to be + closed. If you don't want this (i.e. if you want a "regular" button + on the dialog), don't call SetBehavior. + Note: Any OnClick-event that already exists on the button will + be overwritten. It will *not* be called. + """ + id = self._GetEnumValue() + self._modalhooks[id] = result + def OnClick(zevent): + # XXX there's room for a "validator" here + if validator: + pass # not sure how to do this yet + if event: + event(zevent) + # note: if an exception occurs here, it is not caught + self.EndModal(id) + button.OnClick = OnClick + + def OnClickButton(self, event): + button = event.GetEventObject() + + def ShowModal(self): + r = wx.Dialog.ShowModal(self) + # here, we need to figure out which button was clicked! + return self._modalhooks.get(r, "?") + diff --git a/pynxc/waxy/customdialog.py~ b/pynxc/waxy/customdialog.py~ new file mode 100644 index 0000000..6af64c8 --- /dev/null +++ b/pynxc/waxy/customdialog.py~ @@ -0,0 +1,67 @@ +# customdialog.py + +import wx +import containers +import dialog + +class CustomDialog(wx.Dialog, containers.Container): + + __events__ = dialog.Dialog.__events__.copy() + + def __init__(self, parent, title=""): + wx.Dialog.__init__(self, parent, wx.NewId(), title, wx.DefaultPosition) + + # this should create self.sizer and give access to self.AddComponent + self._create_sizer('vertical') + self.SetDefaultFont() + + # We use EndModal() internally, and that requires that we return + # IDs. _modalhooks is a mapping from ID to desired return value (as a + # string), used by CustomDialog.ShowModal. _count is used for + # generating the unique IDs. + self._modalhooks = {} + self._count = 0 # enumerator + + self.Body() + + self.BindEvents() + self.Pack() + self.Centre() + + def Body(self): + pass + + def _GetEnumValue(self): + self._count = self._count + 1 + return self._count + + def SetBehavior(self, button, result, validator=None, event=None): + """ Set the behavior for the given button. <result> is the desired + result, as a string ('ok', 'cancel', 'foo', etc). <event> is + called, if defined. + Note 1: EndModal() is always called, causing the dialog to be + closed. If you don't want this (i.e. if you want a "regular" button + on the dialog), don't call SetBehavior. + Note: Any OnClick-event that already exists on the button will + be overwritten. It will *not* be called. + """ + id = self._GetEnumValue() + self._modalhooks[id] = result + def OnClick(zevent): + # XXX there's room for a "validator" here + if validator: + pass # not sure how to do this yet + if event: + event(zevent) + # note: if an exception occurs here, it is not caught + self.EndModal(id) + button.OnClick = OnClick + + def OnClickButton(self, event): + button = event.GetEventObject() + + def ShowModal(self): + r = wx.Dialog.ShowModal(self) + # here, we need to figure out which button was clicked! + return self._modalhooks.get(r, "?") + diff --git a/pynxc/waxy/demos/.DS_Store b/pynxc/waxy/demos/.DS_Store Binary files differnew file mode 100644 index 0000000..e162bfd --- /dev/null +++ b/pynxc/waxy/demos/.DS_Store diff --git a/pynxc/waxy/demos/.jedrecent b/pynxc/waxy/demos/.jedrecent new file mode 100644 index 0000000..f4f65e0 --- /dev/null +++ b/pynxc/waxy/demos/.jedrecent @@ -0,0 +1,11 @@ +/home/bblais/python/lib/waxy/progressdialog.py:17:31:0 +/home/bblais/python/work/waxy/demos/ProgressDialog.py:27:30:0 +/home/bblais/python/lib/waxy/multichoicedialog.py:1:1:0 +/home/bblais/python/lib/waxy/keys.py:1:1:0 +/home/bblais/python/lib/waxy/artprovider.py:1:1:0 +/home/bblais/python/lib/waxy/bitmapbutton.py:18:52:0 +/home/bblais/python/lib/waxy/notes.txt:17:9:0 +/home/bblais/python/lib/waxy/__init__.py:20:1:0 +/home/bblais/python/lib/waxy/singlechoicedialog.py:8:1:1 +/home/bblais/python/lib/waxy/listbox.py:5:12:1 +/home/bblais/python/lib/waxy/demos/SingleChoiceDialog.py:54:43:1 diff --git a/pynxc/waxy/demos/AboutBox.py b/pynxc/waxy/demos/AboutBox.py new file mode 100755 index 0000000..7cdea24 --- /dev/null +++ b/pynxc/waxy/demos/AboutBox.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "About Box1",self.About1,default=True) + self.AddComponent(b) + + b = Button(self, "About Box2",self.About2,default=True) + self.AddComponent(b) + + self.Pack() + self.SetSize((640, 480)) + + + def About1(self,event): + + licenseText = "blah " * 250 + "\n\n" +"yadda " * 100 + + AboutBox(self,name='Hello World', + version='1.2.3', + copyright="(C) 2006 Programmers and Coders Everywhere", + description=( + "A \"hello world\" program is a software program that prints out " + "\"Hello world!\" on a display device. It is used in many introductory " + "tutorials for teaching a programming language." + + "\n\nSuch a program is typically one of the simplest programs possible " + "in a computer language. A \"hello world\" program can be a useful " + "sanity test to make sure that a language's compiler, development " + "environment, and run-time environment are correctly installed."), + url="http://en.wikipedia.org/wiki/Hello_world", + webtitle="Hello World home page", + developers=[ "Joe Programmer", + "Jane Coder", + "Vippy the Mascot" ], + license=licenseText) + + + def About2(self,event): + + licenseText = "blah " * 250 + "\n\n" +"yadda " * 100 + + info={} + info['name']='Hello World' + info['version']='1.2.3' + info['copyright']="(C) 2006 Programmers and Coders Everywhere" + info['description']=( + "A \"hello world\" program is a software program that prints out " + "\"Hello world!\" on a display device. It is used in many introductory " + "tutorials for teaching a programming language." + + "\n\nSuch a program is typically one of the simplest programs possible " + "in a computer language. A \"hello world\" program can be a useful " + "sanity test to make sure that a language's compiler, development " + "environment, and run-time environment are correctly installed.") + info['url']="http://en.wikipedia.org/wiki/Hello_world" + info['webtitle']="Hello World home page" + info['developers']=[ "Joe Programmer", + "Jane Coder", + "Vippy the Mascot" ] + info['license']=licenseText + + + AboutBox(self,info) + + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="AboutBox") + app.Run() diff --git a/pynxc/waxy/demos/AboutBox.py~ b/pynxc/waxy/demos/AboutBox.py~ new file mode 100755 index 0000000..eacd55a --- /dev/null +++ b/pynxc/waxy/demos/AboutBox.py~ @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "About Box1",self.About1,default=True) + self.AddComponent(b) + + b = Button(self, "About Box2",self.About2,default=True) + self.AddComponent(b) + + self.Pack() + self.SetSize((640, 480)) + + + def About1(self): + + licenseText = "blah " * 250 + "\n\n" +"yadda " * 100 + + AboutBox(self,name='Hello World', + version='1.2.3', + copyright="(C) 2006 Programmers and Coders Everywhere", + description=( + "A \"hello world\" program is a software program that prints out " + "\"Hello world!\" on a display device. It is used in many introductory " + "tutorials for teaching a programming language." + + "\n\nSuch a program is typically one of the simplest programs possible " + "in a computer language. A \"hello world\" program can be a useful " + "sanity test to make sure that a language's compiler, development " + "environment, and run-time environment are correctly installed."), + url="http://en.wikipedia.org/wiki/Hello_world", + webtitle="Hello World home page", + developers=[ "Joe Programmer", + "Jane Coder", + "Vippy the Mascot" ], + license=licenseText) + + + def About2(self): + + licenseText = "blah " * 250 + "\n\n" +"yadda " * 100 + + info={} + info['name']='Hello World' + info['version']='1.2.3' + info['copyright']="(C) 2006 Programmers and Coders Everywhere" + info['description']=( + "A \"hello world\" program is a software program that prints out " + "\"Hello world!\" on a display device. It is used in many introductory " + "tutorials for teaching a programming language." + + "\n\nSuch a program is typically one of the simplest programs possible " + "in a computer language. A \"hello world\" program can be a useful " + "sanity test to make sure that a language's compiler, development " + "environment, and run-time environment are correctly installed.") + info['url']="http://en.wikipedia.org/wiki/Hello_world" + info['webtitle']="Hello World home page" + info['developers']=[ "Joe Programmer", + "Jane Coder", + "Vippy the Mascot" ] + info['license']=licenseText + + + AboutBox(self,info) + + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="AboutBox") + app.Run() diff --git a/pynxc/waxy/demos/Button.py b/pynxc/waxy/demos/Button.py new file mode 100755 index 0000000..998ef2b --- /dev/null +++ b/pynxc/waxy/demos/Button.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Default Button",self.OnClick,default=True) + self.AddComponent(b) + + b = Button(self, "Hello Again",self.OnClick, + tooltip="This is a Hello button...") + self.AddComponent(b) + + b = Button(self, "Flat Button?",self.OnClick, + tooltip="This button has a style flag of wx.NO_BORDER. On some platforms that will give it a flattened look.",flat=True) + self.AddComponent(b) + + self.Pack() + self.SetSize((640, 480)) + + def OnClick(self,event): + print "Click! (%d)\n" % (event.GetId()) + + def CloseWindow(self,event): + self.Close() + + +if __name__=="__main__": + app = Application(MainFrame, title="Some buttons") + app.Run() diff --git a/pynxc/waxy/demos/Button.py~ b/pynxc/waxy/demos/Button.py~ new file mode 100755 index 0000000..7274a33 --- /dev/null +++ b/pynxc/waxy/demos/Button.py~ @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Default Button",self.OnClick,default=True) + self.AddComponent(b) + + b = Button(self, "Hello Again",self.OnClick, + tooltip="This is a Hello button...") + self.AddComponent(b) + + b = Button(self, "Flat Button?",self.OnClick, + tooltip="This button has a style flag of wx.NO_BORDER. On some platforms that will give it a flattened look.",flat=True) + self.AddComponent(b) + + self.Pack() + self.SetSize((640, 480)) + + def OnClick(self,event): + print "Click! (%d)\n" % (event.GetId()) + + def CloseWindow(self,event): + self.Close() + + +app = Application(MainFrame, title="Some buttons") +app.Run() diff --git a/pynxc/waxy/demos/Calendar.py b/pynxc/waxy/demos/Calendar.py new file mode 100755 index 0000000..1780b0d --- /dev/null +++ b/pynxc/waxy/demos/Calendar.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +from waxy import * +import wx.lib.calendar + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + self.calend = wx.lib.calendar.Calendar(self, -1) + self.calend.SetCurrentDay() + self.calend.grid_color = 'BLUE' + self.calend.SetBusType() + self.calend.Show(True) + + self.Bind(wx.lib.calendar.EVT_CALENDAR, self.MouseClick, self.calend) + + + self.SetSize((640, 480)) + + def MouseClick(self, evt): + text = '%s CLICK %02d/%02d/%d' % (evt.click, evt.day, evt.month, evt.year) # format date + print 'Date Selected: ' + text + '\n' + + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="Calendar") + app.Run() diff --git a/pynxc/waxy/demos/Canvas.py b/pynxc/waxy/demos/Canvas.py new file mode 100644 index 0000000..7822e62 --- /dev/null +++ b/pynxc/waxy/demos/Canvas.py @@ -0,0 +1,43 @@ +from waxy import * + +class MyCanvas(Canvas): + + def Init(self): + self.SetBackgroundColour('WHITE') + + def OnDraw(self, dc): + dc.SetTextForeground('BLACK') + dc.SetPen(MEDIUM_GREY_PEN) + + self.DrawHexagons(dc, 300, 10, radius=40, max_number=11) + + def DrawHexagons(self, dc, x, y, radius, max_number): + for i in range(1, max_number+1): + offset = i * -0.5 * radius + for j in range(i): + self.DrawHexagon(dc, x + offset + j * radius, + y + (i * 0.75 * radius), radius) + + def DrawHexagon(self, dc, x, y, radius): + # does not seem like a 'real' hexagon, but this will do for now + p1 = (x, y) + p2 = (x + 0.5 * radius, y + 0.25 * radius) + p3 = (p2[0], p2[1] + 0.5 * radius) + p4 = (p1[0], p1[1] + radius) + p5 = (x - 0.5 * radius, p3[1]) + p6 = (x - 0.5 * radius, y + 0.25 * radius) + + dc.DrawLinePoint(p1, p2) + dc.DrawLinePoint(p2, p3) + dc.DrawLinePoint(p3, p4) + dc.DrawLinePoint(p4, p5) + dc.DrawLinePoint(p5, p6) + dc.DrawLinePoint(p6, p1) + +class MainFrame(Frame): + def Body(self): + canvas = MyCanvas(self) + self.SetSize((600, 500)) + +app = Application(MainFrame) +app.MainLoop() diff --git a/pynxc/waxy/demos/ColorDialog.py b/pynxc/waxy/demos/ColorDialog.py new file mode 100755 index 0000000..03c3234 --- /dev/null +++ b/pynxc/waxy/demos/ColorDialog.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Color Dialog",self.Color,default=True) + self.AddComponent(b) + + + self.Pack() + self.SetSize((640, 480)) + + + def Color(self,event): + + + dlg=ColorDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenColor() + + else: + print "Canceled!" + + dlg.Destroy() + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="ColorDialog") + app.Run() diff --git a/pynxc/waxy/demos/ColorDialog.py~ b/pynxc/waxy/demos/ColorDialog.py~ new file mode 100644 index 0000000..bf26f0f --- /dev/null +++ b/pynxc/waxy/demos/ColorDialog.py~ @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Colour Dialog",self.Colour,default=True) + self.AddComponent(b) + + + self.Pack() + self.SetSize((640, 480)) + + + def Colour(self,event): + + + dlg=ColourDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenColour() + + else: + print "Canceled!" + + dlg.Destroy() + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="ColourDialog") + app.Run() diff --git a/pynxc/waxy/demos/ColourDialog.py b/pynxc/waxy/demos/ColourDialog.py new file mode 100755 index 0000000..bf26f0f --- /dev/null +++ b/pynxc/waxy/demos/ColourDialog.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Colour Dialog",self.Colour,default=True) + self.AddComponent(b) + + + self.Pack() + self.SetSize((640, 480)) + + + def Colour(self,event): + + + dlg=ColourDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenColour() + + else: + print "Canceled!" + + dlg.Destroy() + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="ColourDialog") + app.Run() diff --git a/pynxc/waxy/demos/ColourDialog.py~ b/pynxc/waxy/demos/ColourDialog.py~ new file mode 100755 index 0000000..761b610 --- /dev/null +++ b/pynxc/waxy/demos/ColourDialog.py~ @@ -0,0 +1,49 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Colour Dialog",self.Colour,default=True) + self.AddComponent(b) + + + self.Pack() + self.SetSize((640, 480)) + + + def Colour(self,event): + + + dlg=ColourDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Here: ",dlg.GetChosenColour() + + else: + print "Canceled!" + + dlg.Destroy() + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="ColourDialog") + app.Run() diff --git a/pynxc/waxy/demos/DirectoryDialog.py b/pynxc/waxy/demos/DirectoryDialog.py new file mode 100755 index 0000000..1943b1f --- /dev/null +++ b/pynxc/waxy/demos/DirectoryDialog.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Directory Dialog",self.Directory,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "Choose Directory",self.Directory2) + self.AddComponent(b,border=10) + + b = Button(self, "Directory Dialog with New Button",self.Directory3,default=True) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def Directory(self,event): + + + dlg=DirectoryDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenDirectory() + + else: + print "Canceled!" + + dlg.Destroy() + + def Directory2(self,event): + + + res=ChooseDirectory(self) + + print "Chose: ",res + + + def Directory3(self,event): + + + dlg=DirectoryDialog(self,new_dir_button=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenDirectory() + + else: + print "Canceled!" + + dlg.Destroy() + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="DirectoryDialog") + app.Run() diff --git a/pynxc/waxy/demos/DirectoryDialog.py~ b/pynxc/waxy/demos/DirectoryDialog.py~ new file mode 100755 index 0000000..3d13c7d --- /dev/null +++ b/pynxc/waxy/demos/DirectoryDialog.py~ @@ -0,0 +1,75 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Directory Dialog",self.Directory,default=True) + self.AddComponent(b,border=20) + + b = Button(self, "Choose Directory",self.Directory2) + self.AddComponent(b,border=20) + + b = Button(self, "Directory Dialog with New Button",self.Directory3,default=True) + self.AddComponent(b,border=20) + + + self.Pack() + self.SetSize((640, 480)) + + + def Directory(self,event): + + + dlg=DirectoryDialog(self) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenDirectory() + + else: + print "Canceled!" + + dlg.Destroy() + + def Directory2(self,event): + + + res=ChooseDirectory(self) + + print "Chose: ",res + + + def Directory3(self,event): + + + dlg=DirectoryDialog(self,new_dir_button=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenDirectory() + + else: + print "Canceled!" + + dlg.Destroy() + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="DirectoryDialog") + app.Run() diff --git a/pynxc/waxy/demos/Drag.py b/pynxc/waxy/demos/Drag.py new file mode 100755 index 0000000..42ae3bf --- /dev/null +++ b/pynxc/waxy/demos/Drag.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python + +from waxy import * +class Sprite: + def __init__(self, fname): + self.bitmap = Image(fname+".png").ConvertToBitmap() + self.bitmap_rev = Image(fname+"rev.png").ConvertToBitmap() + self.background = None + self.pos=wx.Point(0,0) + self.reversed=False + + def Draw(self, dc): + # copy background from dc to memory object + memdc = wx.MemoryDC() + memdc.Blit(0, 0, self.bitmap.GetWidth(), self.bitmap.GetHeight(), dc, + self.pos[0], self.pos[1], wx.COPY, 1) + self.background = memdc # keep around for later + + bitmap = self.bitmap if not self.reversed else self.bitmap_rev + dc.DrawBitmap(bitmap, self.pos[0], self.pos[1], 1) + + def HitTest(self, pt): + rect = self.GetRect() + return rect.InsideXY(pt.x, pt.y) + + + def GetRect(self): + return wx.Rect(self.pos[0], self.pos[1], + self.bitmap.GetWidth(), self.bitmap.GetHeight()) + +class MyCanvas(Canvas): + + def Init(self): + self.SetBackgroundColour('WHITE') + self.SetScrollbars(20, 20, 100, 100) + self.sprite = Sprite('heretic2') + self.sprite.pos=wx.Point(50,50) + self.selected=False + self.starting_mouse_pos=None + self.sprite_orig_pos=None + + def OnLeftDown(self,event=None): + + if self.sprite.HitTest(event.Position): + self.selected=True + self.starting_mouse_pos=event.Position + self.sprite_orig_pos=self.sprite.pos + self.sprite.reversed=not self.sprite.reversed + self.Refresh() + + def OnLeftUp(self,event=None): + self.selected=False + + def OnMotion(self,event=None): + if not event.Dragging(): + return + + if not self.selected: + return + + print "move.",event.Position + self.sprite.pos=self.sprite_orig_pos+event.Position-self.starting_mouse_pos + + self.Refresh() + + + def OnDraw(self, dc): + dc.SetTextForeground('BLUE') + dc.SetPen(wx.MEDIUM_GREY_PEN) + for i in range(50): + dc.DrawLine(0, i*10, i*10, 0) + + self.sprite.Draw(dc) + + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + self.canvas = MyCanvas(self) + self.canvas.SetSize((400,300)) + self.AddComponent(self.canvas, expand=1, stretch=1) + + self.Pack() + + + + self.CenterOnScreen() + + self.Show() + + + def CloseWindow(self,event): + self.Close() + + + +if __name__=="__main__": + app = Application(MainFrame, title=__file__) + app.Run() diff --git a/pynxc/waxy/demos/FileDialog.py b/pynxc/waxy/demos/FileDialog.py new file mode 100755 index 0000000..6c2bc8e --- /dev/null +++ b/pynxc/waxy/demos/FileDialog.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python + +from waxy import * + +wildcard = "Python source (*.py)|*.py|" \ + "Compiled Python (*.pyc)|*.pyc|" \ + "SPAM files (*.spam)|*.spam|" \ + "Egg file (*.egg)|*.egg|" \ + "All files (*.*)|*.*" + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "File OPEN Dialog",self.File1,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "File SAVE Dialog",self.File2) + self.AddComponent(b,border=10) + + b = Button(self, "File MULTIPLE OPEN Dialog",self.File3) + self.AddComponent(b,border=10) + + b = Button(self, "File Dialog (default?)",self.File0) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def File1(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,open=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File2(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,save=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File3(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,open=True,multiple=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File0(self,event): + + + dlg=FileDialog(self,wildcard=wildcard) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="FileDialog") + app.Run() diff --git a/pynxc/waxy/demos/FileDialog.py~ b/pynxc/waxy/demos/FileDialog.py~ new file mode 100755 index 0000000..4bf03bc --- /dev/null +++ b/pynxc/waxy/demos/FileDialog.py~ @@ -0,0 +1,104 @@ +#!/usr/bin/env python + +from waxy import * + +wildcard = "Python source (*.py)|*.py|" \ + "Compiled Python (*.pyc)|*.pyc|" \ + "SPAM files (*.spam)|*.spam|" \ + "Egg file (*.egg)|*.egg|" \ + "All files (*.*)|*.*" + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "File OPEN Dialog",self.File1,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "File SAVE Dialog",self.File2) + self.AddComponent(b,border=10) + + b = Button(self, "File MULTIPLE OPEN Dialog",self.File3) + self.AddComponent(b,border=10) + + b = Button(self, "File Dialog (default?)",self.File2) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def File1(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,open=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File2(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,save=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File3(self,event): + + + dlg=FileDialog(self,wildcard=wildcard,open=True,multiple=True) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def File0(self,event): + + + dlg=FileDialog(self,wildcard=wildcard) + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenFile() + + else: + print "Canceled!" + + dlg.Destroy() + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="FileDialog") + app.Run() diff --git a/pynxc/waxy/demos/Grid.py b/pynxc/waxy/demos/Grid.py new file mode 100755 index 0000000..833d57d --- /dev/null +++ b/pynxc/waxy/demos/Grid.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + self.cellbox=TextBox(self) + self.AddComponent(self.cellbox,border=10,stretch=True) + self.cellbox.OnChar=self.EditCell + + self.grid = Grid(self,100,40) + self.AddComponent(self.grid,border=10,expand='both') + self.grid.OnSelectCell=self.OnSelectCell + + self.Pack() + self.SetSize((1000, 800)) + + self.CenterOnScreen() + + self.Show() + self.grid.SetFocus() + self.cellbox.SetValue(self.grid[0,0]) + + def EditCell(self,event): + + if event.KeyCode>0 and event.KeyCode<255: # a character + + v=self.cellbox.GetValue() + r,c=self.grid.GetGridCursorRow(),self.grid.GetGridCursorCol() + + + if event.KeyCode==13: # return + self.grid[r,c]=v + self.grid.SetFocus() + elif event.KeyCode==27: # escape + self.cellbox.SetValue("") + self.grid.SetFocus() + + event.Skip() + + + def CloseWindow(self,event): + self.Close() + + def OnSelectCell(self,event): + r,c=event.Row,event.Col + self.cellbox.SetValue(self.grid[r,c]) + event.Skip() + + + +if __name__=="__main__": + app = Application(MainFrame, title="Grid") + app.Run() diff --git a/pynxc/waxy/demos/Grid2.py b/pynxc/waxy/demos/Grid2.py new file mode 100755 index 0000000..e8d8f5b --- /dev/null +++ b/pynxc/waxy/demos/Grid2.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python + +from waxy import * +import wx + + +class CustomDataTable(wx.grid.PyGridTableBase): + def __init__(self): + wx.grid.PyGridTableBase.__init__(self) + + self.colLabels = ['ID', 'Description', 'Severity', 'Priority', 'Platform', + 'Opened?', 'Fixed?', 'Tested?', 'TestFloat'] + + self.dataTypes = [wx.grid.GRID_VALUE_NUMBER, + wx.grid.GRID_VALUE_STRING, + wx.grid.GRID_VALUE_CHOICE + ':only in a million years!,wish list,minor,normal,major,critical', + wx.grid.GRID_VALUE_NUMBER + ':1,5', + wx.grid.GRID_VALUE_CHOICE + ':all,MSW,GTK,other', + wx.grid.GRID_VALUE_BOOL, + wx.grid.GRID_VALUE_BOOL, + wx.grid.GRID_VALUE_BOOL, + wx.grid.GRID_VALUE_FLOAT + ':6,2', + ] + + self.data = [ + [1010, "The foo doesn't bar", "major", 1, 'MSW', 1, 1, 1, 1.12], + [1011, "I've got a wicket in my wocket", "wish list", 2, 'other', 0, 0, 0, 1.50], + [1012, "Rectangle() returns a triangle", "critical", 5, 'all', 0, 0, 0, 1.56] + + ] + + + #-------------------------------------------------- + # required methods for the wxPyGridTableBase interface + + def GetNumberRows(self): + return len(self.data) + 1 + + def GetNumberCols(self): + return len(self.data[0]) + + def IsEmptyCell(self, row, col): + try: + return not self.data[row][col] + except IndexError: + return True + + # Get/Set values in the table. The Python version of these + # methods can handle any data-type, (as long as the Editor and + # Renderer understands the type too,) not just strings as in the + # C++ version. + def GetValue(self, row, col): + try: + return self.data[row][col] + except IndexError: + return '' + + def SetValue(self, row, col, value): + try: + self.data[row][col] = value + except IndexError: + # add a new row + self.data.append([''] * self.GetNumberCols()) + self.SetValue(row, col, value) + + # tell the grid we've added a row + msg = wx.grid.GridTableMessage(self, # The table + wx.grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, # what we did to it + 1 # how many + ) + + self.GetView().ProcessTableMessage(msg) + + + #-------------------------------------------------- + # Some optional methods + + # Called when the grid needs to display labels + def GetColLabelValue(self, col): + return self.colLabels[col] + + # Called to determine the kind of editor/renderer to use by + # default, doesn't necessarily have to be the same type used + # natively by the editor/renderer if they know how to convert. + def GetTypeName(self, row, col): + return self.dataTypes[col] + + # Called to determine how the data can be fetched and stored by the + # editor and renderer. This allows you to enforce some type-safety + # in the grid. + def CanGetValueAs(self, row, col, typeName): + colType = self.dataTypes[col].split(':')[0] + if typeName == colType: + return True + else: + return False + + def CanSetValueAs(self, row, col, typeName): + return self.CanGetValueAs(row, col, typeName) + + + +class MyGrid(Grid): + + def __init__(self, parent): + Grid.__init__(self, parent) + table = CustomDataTable() + + self.SetTable(table, True) + + self.SetRowLabelSize(0) + self.SetMargins(0,0) + self.AutoSizeColumns(False) + + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + self.cellbox=TextBox(self) + self.AddComponent(self.cellbox,border=10,stretch=True) + self.cellbox.OnChar=self.EditCell + + self.grid = MyGrid(self) + self.AddComponent(self.grid,border=10,expand='both') + self.grid.OnSelectCell=self.OnSelectCell + + self.Pack() + self.SetSize((1000, 800)) + + self.CenterOnScreen() + + self.Show() + self.grid.SetFocus() + self.cellbox.SetValue(self.grid[0,0]) + + def EditCell(self,event): + + if event.KeyCode>0 and event.KeyCode<255: # a character + + v=self.cellbox.GetValue() + r,c=self.grid.GetGridCursorRow(),self.grid.GetGridCursorCol() + + + if event.KeyCode==13: # return + self.grid[r,c]=v + self.grid.SetFocus() + elif event.KeyCode==27: # escape + self.cellbox.SetValue("") + self.grid.SetFocus() + + event.Skip() + + + def CloseWindow(self,event): + self.Close() + + def OnSelectCell(self,event): + r,c=event.Row,event.Col + self.cellbox.SetValue(self.grid[r,c]) + event.Skip() + + + +if __name__=="__main__": + app = Application(MainFrame, title="Grid") + app.Run() diff --git a/pynxc/waxy/demos/MessageDialog.py b/pynxc/waxy/demos/MessageDialog.py new file mode 100755 index 0000000..96f069a --- /dev/null +++ b/pynxc/waxy/demos/MessageDialog.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Message Dialog: Question",self.Message,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "Choose Message: Statement",self.Message2) + self.AddComponent(b,border=10) + + + panel=Panel(self,direction='h') + + choices = MessageDialog._icons.keys() + choices.sort() + + self.dd = DropDownBox(panel, choices) + panel.AddComponent(self.dd, border=10) + + b = Button(panel, "Show message", self.Message3) + panel.AddComponent(b,border=10) + + + + panel.Pack() + + + self.AddComponent(panel,border=20) + + b = Button(self, "File Exists", self.Message4) + self.AddComponent(b,border=10) + + self.Pack() + self.SetSize((640, 480)) + + + def Message(self,event): + + dlg=MessageDialog(self,title="Holy cow", text="You wanna dance?", + ok=0, yes_no=1) + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + def Message2(self,event): + + dlg=MessageDialog(self,text="Resistance is futile.") + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + + def Message3(self,event): + + choice = self.dd.GetStringSelection() + dlg = MessageDialog(self, "A message", "You chose: " + repr(choice), + icon=choice) + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + def Message4(self,event): + filename='hello.txt' + dlg = MessageDialog(self, '"%s" already exists. Do you want to replace it?' % filename, + 'A file or folder with the same name already exists in plasticity. Replacing it will overwrite its current contents.',icon='Warning',cancel=1) + result = dlg.ShowModal() + + print result + + dlg.Destroy() + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="MessageDialog") + app.Run() diff --git a/pynxc/waxy/demos/MessageDialog.py~ b/pynxc/waxy/demos/MessageDialog.py~ new file mode 100755 index 0000000..5a42619 --- /dev/null +++ b/pynxc/waxy/demos/MessageDialog.py~ @@ -0,0 +1,83 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "Message Dialog: Question",self.Message,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "Choose Message: Statement",self.Message2) + self.AddComponent(b,border=10) + + + panel=Panel(self,direction='h') + + choices = MessageDialog._icons.keys() + choices.sort() + + self.dd = DropDownBox(panel, choices) + panel.AddComponent(self.dd, border=10) + + b = Button(panel, "Show message", self.Message3) + panel.AddComponent(b) + panel.Pack() + + self.AddComponent(panel,border=20) + + self.Pack() + self.SetSize((640, 480)) + + + def Message(self,event): + + dlg=MessageDialog(self,title="Holy cow", text="You wanna dance?", + ok=0, yes_no=1) + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + def Message2(self,event): + + dlg=MessageDialog(self,text="Resistance is futile.") + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + + def Message3(self,event): + + choice = self.dd.GetStringSelection() + dlg = MessageDialog(self, "A message", "You chose: " + repr(choice), + icon=choice) + res=dlg.ShowModal() + + print res + + dlg.Destroy() + + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="MessageDialog") + app.Run() diff --git a/pynxc/waxy/demos/MultiChoiceDialog.py b/pynxc/waxy/demos/MultiChoiceDialog.py new file mode 100755 index 0000000..01644fb --- /dev/null +++ b/pynxc/waxy/demos/MultiChoiceDialog.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "MultiChoice Dialog",self.MultiChoice,default=True) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def MultiChoice(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = MultiChoiceDialog( self, lst, + "Pick some fruit from\nthis list", + "MultiChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenItems() + + else: + print "Canceled!" + + dlg.Destroy() + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="MultiChoiceDialog") + app.Run() diff --git a/pynxc/waxy/demos/MultiChoiceDialog.py~ b/pynxc/waxy/demos/MultiChoiceDialog.py~ new file mode 100644 index 0000000..bf53055 --- /dev/null +++ b/pynxc/waxy/demos/MultiChoiceDialog.py~ @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +from waxy import * + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "MultiChoice Dialog",self.MultiChoice,default=True) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def MultiChoice(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = MultiChoiceDialog( self, lst, + "Pick some fruit from\nthis list", + "MultiChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenMultiChoice() + + else: + print "Canceled!" + + dlg.Destroy() + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="MultiChoiceDialog") + app.Run() diff --git a/pynxc/waxy/demos/ProgressDialog.py b/pynxc/waxy/demos/ProgressDialog.py new file mode 100755 index 0000000..0847d4d --- /dev/null +++ b/pynxc/waxy/demos/ProgressDialog.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python + +from waxy import * +import time + +class MainFrame(Frame): + def Body(self): + self.AddComponent(Button(self, "one", self.OnClick)) + self.AddComponent(Button(self, "two", self.OnClick2)) + self.AddComponent(Button(self, "three", self.OnClick3)) + self.Pack() + + def OnClick(self, event): + # note: does not have a Cancel button, so it cannot be interrupted + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, modal=0) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + keep_going,skip = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + keep_going,skip = dlg.Update(i) + + + time.sleep(.01) + if not keep_going: + break + dlg.Destroy() + + def OnClick2(self, event): + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, abort=1) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + cancel = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + cancel = dlg.Update(i) + time.sleep(.01) + if not cancel[0]: + break + dlg.Destroy() + + def OnClick3(self, event): + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, abort=1, + show_elapsed_time=1, + #show_estimated_time=1, + show_remaining_time=1) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + cancel = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + cancel = dlg.Update(i) + time.sleep(.01) + if not cancel[0]: + dlg2 = MessageDialog(self, title="Continue?", text="Do you want to abort?", yes_no=1) + result = dlg2.ShowModal() + if result == "yes": + dlg.Destroy() + break + else: + dlg.Resume() + dlg2.Destroy() + if dlg: + dlg.Destroy() + + + +if __name__=="__main__": + app = Application(MainFrame, title="ProgressDialog") + app.Run() diff --git a/pynxc/waxy/demos/ProgressDialog.py~ b/pynxc/waxy/demos/ProgressDialog.py~ new file mode 100755 index 0000000..5fc5157 --- /dev/null +++ b/pynxc/waxy/demos/ProgressDialog.py~ @@ -0,0 +1,76 @@ +#!/usr/bin/env python + +from waxy import * +import time + +class MainFrame(Frame): + def Body(self): + self.AddComponent(Button(self, "one", self.OnClick)) + self.AddComponent(Button(self, "two", self.OnClick2)) + self.AddComponent(Button(self, "three", self.OnClick3)) + self.Pack() + + def OnClick(self, event): + # note: does not have a Cancel button, so it cannot be interrupted + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, modal=0) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + keep_going,skip = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + keep_going,skip = dlg.Update(i) + + + time.sleep(.01) + if not cancel[0]: + break + dlg.Destroy() + + def OnClick2(self, event): + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, abort=1) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + cancel = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + cancel = dlg.Update(i) + time.sleep(.01) + if not cancel[0]: + break + dlg.Destroy() + + def OnClick3(self, event): + dlg = ProgressDialog(self, title="Progress Dialog Test", + message="Counting from 1 to 1000", maximum=1000, abort=1, + show_elapsed_time=1, + #show_estimated_time=1, + show_remaining_time=1) + dlg.Show() + cancel = True + for i in range(1000): + if i % 100 == 0: + cancel = dlg.Update(i, "Counting from " + str(i) + " to 1000") + else: + cancel = dlg.Update(i) + time.sleep(.01) + if not cancel[0]: + dlg2 = MessageDialog(self, title="Continue?", text="Do you want to abort?", yes_no=1) + result = dlg2.ShowModal() + if result == "yes": + dlg.Destroy() + break + else: + dlg.Resume() + dlg2.Destroy() + if dlg: + dlg.Destroy() + + + +if __name__=="__main__": + app = Application(MainFrame, title="ProgressDialog") + app.Run() diff --git a/pynxc/waxy/demos/Rubberband.py b/pynxc/waxy/demos/Rubberband.py new file mode 100755 index 0000000..316850a --- /dev/null +++ b/pynxc/waxy/demos/Rubberband.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python + +from waxy import * + +# Modified from: +# Recipe 189744: wxPython Graphics - Drawing rubberbands over a canvas +# http://code.activestate.com/recipes/189744/ + +class Sprite: + def __init__(self, fname): + self.bitmap = Image(fname+".png").ConvertToBitmap() + self.bitmap_rev = Image(fname+"rev.png").ConvertToBitmap() + self.background = None + self.pos=wx.Point(0,0) + self.reversed=False + + def Draw(self, dc): + # copy background from dc to memory object + memdc = wx.MemoryDC() + memdc.Blit(0, 0, self.bitmap.GetWidth(), self.bitmap.GetHeight(), dc, + self.pos[0], self.pos[1], wx.COPY, 1) + self.background = memdc # keep around for later + + bitmap = self.bitmap if not self.reversed else self.bitmap_rev + dc.DrawBitmap(bitmap, self.pos[0], self.pos[1], 1) + + def HitTest(self, pt): + rect = self.GetRect() + return rect.InsideXY(pt.x, pt.y) + + def Intersects(self, rect): + myrect = self.GetRect() + + # adjust for negative + arect=[val for val in rect] + if arect[2]<0: + arect[0]+=arect[2] + arect[2]=-arect[2] + + if arect[3]<0: + arect[1]+=arect[3] + arect[3]=-arect[3] + + return myrect.Intersects(arect) + + def GetRect(self): + return wx.Rect(self.pos[0], self.pos[1], + self.bitmap.GetWidth(), self.bitmap.GetHeight()) + +class MyCanvas(Canvas): + + def Init(self): + self.SetBackgroundColour('WHITE') + self.SetScrollbars(20, 20, 100, 100) + self.sprite = Sprite('heretic2') + self.sprite.pos=wx.Point(50,50) + + # mouse selection start point + self.m_stpoint=Point(0,0) + # mouse selection end point + self.m_endpoint=Point(0,0) + # mouse selection cache point + self.m_savepoint=Point(0,0) + + # flags for left click/ selection + self._leftclicked=False + self._selected=False + + def OnLeftDown(self,event): + + # Left mouse button down, change cursor to + # something else to denote event capture + self.m_stpoint = event.GetPosition() + self.SetCursor('cross') + + # invalidate current canvas + self.Refresh() + # cache current position + self.m_savepoint = self.m_stpoint + self.m_endpoint = self.m_savepoint + self._selected = False + self._leftclicked = True + + + def OnMotion(self,event): + + if event.Dragging() and self._leftclicked: + + # Draw new rectangle + self.m_endpoint = event.GetPosition() + self.m_savepoint = self.m_endpoint # cache current endpoint + self.Refresh() + + def OnLeftUp(self,event): + + # User released left button, change cursor back + self.SetCursor('arrow') + self._selected = True #selection is done + self._leftclicked = False # end of clicking + self.Refresh() + + def OnDraw(self, dc): + dc.SetTextForeground('BLUE') + dc.SetPen(wx.MEDIUM_GREY_PEN) + for i in range(50): + dc.DrawLine(0, i*10, i*10, 0) + + w = (self.m_endpoint.x - self.m_stpoint.x) + h = (self.m_endpoint.y - self.m_stpoint.y) + rect=self.m_stpoint.x, self.m_stpoint.y, w, h + + if self.sprite.Intersects(rect): + self.sprite.reversed=True + else: + self.sprite.reversed=False + + self.sprite.Draw(dc) + + if not self._selected: + dc.SetLogicalFunction(wx.XOR) + wbrush = wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT) + wpen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) + dc.SetBrush(wbrush) + dc.SetPen(wpen) + + + # Set clipping region to rectangle corners + # dc.SetClippingRegion(self.m_stpoint.x, self.m_stpoint.y, w,h) + dc.DrawRectangle(*rect) + + + + def GetCurrentSelection(self): + """ Return the current selected rectangle """ + + # if there is no selection, selection defaults to + # current viewport + + left = Point(0,0) + right = Point(0,0) + + # user dragged mouse to right + if self.m_endpoint.y > self.m_stpoint.y: + right = self.m_endpoint + left = self.m_stpoint + # user dragged mouse to left + elif self.m_endpoint.y < self.m_stpoint.y: + right = self.m_stpoint + left = self.m_endpoint + + return (left.x, left.y, right.x, right.y) + + + def ClearCurrentSelection(self): + """ Clear the current selected rectangle """ + + box = self.GetCurrentSelection() + + dc=wx.ClientDC(self) + + w = box[2] - box[0] + h = box[3] - box[1] + dc.SetClippingRegion(box[0], box[1], w, h) + dc.SetLogicalFunction(wx.XOR) + + # The brush is not really needed since we + # dont do any filling of the dc. It is set for + # sake of completion. + + wbrush = wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT) + wpen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) + dc.SetBrush(wbrush) + dc.SetPen(wpen) + dc.DrawRectangle(box[0], box[1], w,h) + self._selected = false + + # reset selection to canvas size + self.ResetSelection() + + def ResetSelection(self): + """ Resets the mouse selection to entire canvas """ + + self.m_stpoint = Point(0,0) + sz=self._canvas.GetSize() + w,h=sz.GetWidth(), sz.GetHeight() + self.m_endpoint = wxPoint(w,h) + + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + self.canvas = MyCanvas(self) + self.canvas.SetSize((400,300)) + self.AddComponent(self.canvas, expand=1, stretch=1) + + self.Pack() + + self.CenterOnScreen() + + self.Show() + + + def CloseWindow(self,event): + self.Close() + + + +if __name__=="__main__": + app = Application(MainFrame, title=__file__) + app.Run() diff --git a/pynxc/waxy/demos/SingleChoiceDialog.py b/pynxc/waxy/demos/SingleChoiceDialog.py new file mode 100755 index 0000000..0c0815d --- /dev/null +++ b/pynxc/waxy/demos/SingleChoiceDialog.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +from waxy import * + +class MyDialog(SingleChoiceDialog): + + def OnClick(self): + + print "hello!" + + + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "SingleChoice Dialog",self.SingleChoice,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "Custom SingleChoice Dialog",self.SingleChoice2) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def SingleChoice(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = SingleChoiceDialog( self, lst, + "Pick some fruit from\nthis list", + "SingleChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenItem() + + else: + print "Canceled!" + + dlg.Destroy() + + def SingleChoice2(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = MyDialog( self, lst, + "Pick some fruit from\nthis list", + "SingleChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenItem() + + else: + print "Canceled!" + + dlg.Destroy() + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="SingleChoiceDialog") + app.Run() diff --git a/pynxc/waxy/demos/SingleChoiceDialog.py~ b/pynxc/waxy/demos/SingleChoiceDialog.py~ new file mode 100755 index 0000000..90eab15 --- /dev/null +++ b/pynxc/waxy/demos/SingleChoiceDialog.py~ @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +from waxy import * + +class MyDialog(SingleChoiceDialog): + + def OnClick(self): + + print "hello!" + + + +class MainFrame(VerticalFrame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + b = Button(self, "SingleChoice Dialog",self.SingleChoice,default=True) + self.AddComponent(b,border=10) + + b = Button(self, "Custom SingleChoice Dialog",self.SingleChoice2) + self.AddComponent(b,border=10) + + + self.Pack() + self.SetSize((640, 480)) + + + def SingleChoice(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = SingleChoiceDialog( self, lst, + "Pick some fruit from\nthis list", + "SingleChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetString() + + else: + print "Canceled!" + + dlg.Destroy() + + def SingleChoice2(self,event): + + + lst = [ 'apple', 'pear', 'banana', 'coconut', 'orange', 'grape', 'pineapple', + 'blueberry', 'raspberry', 'blackberry', 'snozzleberry', + 'etc', 'etc..', 'etc...' ] + + dlg = MyDialog( self, lst, + "Pick some fruit from\nthis list", + "SingleChoiceDialog") + + + res=dlg.ShowModal() + + if res=='ok': + print "Ok: ",dlg.GetChosenItem() + + else: + print "Canceled!" + + dlg.Destroy() + + + def CloseWindow(self,event): + self.Close() + +if __name__=="__main__": + app = Application(MainFrame, title="SingleChoiceDialog") + app.Run() diff --git a/pynxc/waxy/demos/Slider.py b/pynxc/waxy/demos/Slider.py new file mode 100755 index 0000000..8b53d8e --- /dev/null +++ b/pynxc/waxy/demos/Slider.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python + +from waxy import * +import pylab +import numpy + +def myfunc(x,params): + + y=params[0]+params[1]*x+params[2]*x**2 + + return y + + +def myplot(x,y): + + pylab(x,y,'-o') + title('This is a test') + xlabel('This') + ylabel('That') + + show() + +class MainFrame(VerticalFrame): + + def Body(self): + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + + s=Slider(self,min=-5.0,max=5.0,tickfreq=0.1,ticks='bottom',labels=True) + self.AddComponent(s,stretch=True) + s=FloatSlider(self,min=-5.0,max=5.0,tickfreq=0.1,ticks='bottom',labels=True) + self.AddComponent(s,stretch=True) + self.Pack() + self.SetSize((640, 480)) + + def CloseWindow(self,event): + self.Close() + + +if __name__=="__main__": + app = Application(MainFrame, title="Slider Example") + app.Run() + diff --git a/pynxc/waxy/demos/TreeListView.py b/pynxc/waxy/demos/TreeListView.py new file mode 100755 index 0000000..bf4bb66 --- /dev/null +++ b/pynxc/waxy/demos/TreeListView.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python + +# treelistview-1.py + +from waxy import * +import wx +# uses wx at the moment; will be fixed later + +class MainFrame(Frame): + + def CreateTreeListView(self, parent): + treelistview = TreeListView(parent, + columns=["Main column", "Column 1", "Column 2"], + has_buttons=1, lines=1) + treelistview.Size = (400, 400) + + # add columns + treelistview.SetMainColumn(0) + treelistview.SetColumnWidth(0, 175) + + self.root = treelistview.AddRoot("the root item") + treelistview.SetItemText(self.root, "col 1 root", 1) + treelistview.SetItemText(self.root, "col 2 root", 2) + + for x in range(15): + text = "Item %d" % (x,) + child = treelistview.AppendItem(self.root, text) + # child is a TreeItemId or something like that :-( + treelistview.SetItemText(child, text + "(c1)", 1) + treelistview.SetItemText(child, text + "(c2)", 2) + # this should really be something like: + # child.SetText(column, text) + # or even: + # child[column] = text + # ...can we use a wrapper object without messing up everything? + + for y in range(5): + text = "Item %d-%d" % (x, y) + last = treelistview.AppendItem(child, text) + treelistview.SetItemText(last, text + "(c1)", 1) + treelistview.SetItemText(last, text + "(c1)", 1) + + return treelistview + + def Body(self): + self.treelistview = self.CreateTreeListView(self) + self.AddComponent(self.treelistview, expand='both') + self.Pack() + +app = Application(MainFrame) +app.Run() diff --git a/pynxc/waxy/demos/TreeView.py b/pynxc/waxy/demos/TreeView.py new file mode 100755 index 0000000..50ebe10 --- /dev/null +++ b/pynxc/waxy/demos/TreeView.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python + +from waxy import * + +def filltree(tree): + root = tree.AddRoot("the root item") + for i in range(10): + child = tree.AppendItem(root, "Item %d" % (i,)) + for j in range(5): + grandchild = tree.AppendItem(child, "Item %d" % (i*10+j)) + + print [x for x in tree.GetChildNodes(root)] + + d = { + "Hans": { + "age": 30, + "sign": "Aquarius", + "job": "programmer", + }, + "Fred": { + "age": "unknown", + "sign": "unknown", + "shoe size": "unknown", + }, + "Old Guy John": { + "age": "old", + "sign": "Aquarius", + }, + "Bob": { + "sign": "Taurus", + "job": "proprietor", + }, + "Christine": { + "age": 17, + "sign": "Aries", + "job": "cashier", + } + } + + stuff = tree.AppendItem(root, "stuff") + tree.LoadFromDict(stuff, d) + + return tree + + + +class MainFrame(Frame): # frame has a sizer built in + + def Body(self): + + self.CenterOnScreen() + + self.CreateStatusBar() + self.SetStatusText("This is the statusbar") + + menubar = MenuBar(self) + menu1 = Menu(self) + menu1.Append("E&xit", self.CloseWindow, "Exit demo",hotkey="Ctrl+Q") + menubar.Append(menu1, "&File") + + splitter = Splitter(self) + self.treeview = TreeView(splitter, twist_buttons=1, has_buttons=1) + self.treeview.OnSelectionChanged = self.OnTreeSelectionChanged + self.textbox = TextBox(splitter, multiline=1) + splitter.Split(self.treeview, self.textbox, direction='v') + self.AddComponent(splitter, expand='both') + filltree(self.treeview) + + + + self.Pack() + self.SetSize((640, 480)) + + def CloseWindow(self,event): + self.Close() + + def OnTreeSelectionChanged(self, event): + item = event.GetItem() + data = self.treeview.GetPyData(item) + if data is None: + data = self.treeview.GetItemText(item) + self.textbox.Clear() + self.textbox.AppendText(str(data)) + event.Skip() + + + + +if __name__=="__main__": + app = Application(MainFrame, title="TreeView") + app.Run() diff --git a/pynxc/waxy/demos/heretic2.png b/pynxc/waxy/demos/heretic2.png Binary files differnew file mode 100644 index 0000000..a4ede33 --- /dev/null +++ b/pynxc/waxy/demos/heretic2.png diff --git a/pynxc/waxy/demos/heretic2rev.png b/pynxc/waxy/demos/heretic2rev.png Binary files differnew file mode 100644 index 0000000..fa92a54 --- /dev/null +++ b/pynxc/waxy/demos/heretic2rev.png diff --git a/pynxc/waxy/demos/plotit.py b/pynxc/waxy/demos/plotit.py new file mode 100644 index 0000000..f5eb429 --- /dev/null +++ b/pynxc/waxy/demos/plotit.py @@ -0,0 +1,151 @@ +from numpy import * + +from waxy import * + +from matplotlib.backends.backend_wxagg import FigureCanvasWx as FigureCanvas +from matplotlib.backends.backend_wx import FigureManager +from matplotlib.figure import Figure +from matplotlib.axes import Subplot + +def export_fig(parent,filename=None): + from matplotlib.backends.backend_pdf import FigureCanvasPdf + + if not filename: + +# parent.canvas.Show(False) + + dlg = FileDialog(parent, "Export to...",default_dir=os.getcwd(), + wildcard='PNG Files|*.png|PDF Files|*.pdf|EPS Files|*.eps|SVG Files|*.svg|All Files|*.*',save=1) + result = dlg.ShowModal() + if result == 'ok': + filename = dlg.GetPaths()[0] + else: + filename=None + + filter_index=dlg.GetFilterIndex() + + dlg.Destroy() + + parent.canvas.Show(True) + + + if filename: + + nme,ext=os.path.splitext(filename) + if not ext: # do the filter index + ext='.pdf' + + print filter_index + + if filter_index==0: + ext='.png' + elif filter_index==1: + ext='.pdf' + elif filter_index==2: + ext='.eps' + + filename=nme+ext + + nme,ext=os.path.splitext(filename) + + if os.path.exists(filename): + dlg = MessageDialog(parent, '"%s" already exists. Do you want to replace it?' % filename, + 'A file or folder with the same name already exists in plasticity. Replacing it will overwrite its current contents.',icon='warning',cancel=1) + result = dlg.ShowModal() + + if result=='cancel': + return + + if ext=='.pdf': # hack to fix a problem in the pdf backend + orig_dpi = parent.fig.dpi.get() + canvas_pdf = FigureCanvasPdf(parent.fig) + parent.fig.savefig(filename) + parent.fig.set_canvas(parent.canvas) # restore automagically switched attributes + parent.fig.dpi.set(orig_dpi) + else: + parent.fig.savefig(filename) + + + +class MainFrame(Frame): + + def __init__(self,x,y,style,parent=None): + self.fig=None + Frame.__init__(self,parent,'Plot','H',size=(750,750)) + self.x=x + self.y=y + self.style=style + self.Plot() + + def Body(self): + + self.CreateMenu() + self.CenterOnScreen() + + self.fig = Figure(figsize=(7,5),dpi=100) + self.canvas = FigureCanvas(self, -1, self.fig) + self.figmgr = FigureManager(self.canvas, 1, self) + + self.axes = [self.fig.add_subplot(111)] + + def CreateMenu(self): + + menubar = MenuBar() + + menu = Menu(self) + menu.Append("&Run", self.Run, "Run",hotkey="Ctrl+R") + menu.Append("Export Figure...", self.Export, "Export the Screen") + menu.Append("&Quit", self.Quit, "Quit",hotkey="Ctrl+Q") + + menubar.Append(menu, "&File") + self.running=False + + self.SetMenuBar(menubar) + self.CreateStatusBar() + + def Export(self,event=None): + export_fig(self) + + + def Run(self,event=None): + + if self.running: + self.y=self.y_bak + self.UpdatePlot() + + else: + t=0.0 + self.y_bak=self.y + + for t in linspace(0,2*pi*4,100): + self.y=y*cos(t) + self.UpdatePlot() + + self.running=not self.running + + def UpdatePlot(self): + self.h.set_ydata(self.y) + self.canvas.draw() + self.canvas.gui_repaint() + wx.Yield() + + def Plot(self): + self.axes[0].clear() + self.h,=self.axes[0].plot(self.x,self.y,self.style,linewidth=3) + + self.canvas.draw() + self.canvas.gui_repaint() + + + def Quit(self,event=None): + self.Close() + +def Plot(x,y,style='-'): + app = Application(MainFrame,x,y,style) + app.Run() + +if __name__=="__main__": + + x=linspace(-10,10,100) + y=x*sin(x)+x + Plot(x,y) diff --git a/pynxc/waxy/dialog.py b/pynxc/waxy/dialog.py new file mode 100644 index 0000000..df3397d --- /dev/null +++ b/pynxc/waxy/dialog.py @@ -0,0 +1,115 @@ +# dialog.py + +# TODO: Pressing Esc in a dialog should be the same as Cancel... +# (but how? using EVT_CHAR doesn't work... neither does OnCharHook.) + +import wx + +from button import Button +from containers import Container +from line import Line +from panel import Panel +from keys import keys +import frame + +# TODO: styles (same as Frame?) + +class Dialog(wx.Dialog, Container): + + __events__ = frame.Frame.__events__.copy() + __events__ .update({ + 'CharHook': wx.EVT_CHAR_HOOK, + }) + + def __init__(self, parent, title, cancel_button=1): + wx.Dialog.__init__(self, parent, wx.NewId(), title, wx.DefaultPosition) + + # this should create self.sizer and give access to self.AddComponent + self._create_sizer('vertical') + + # enter stuff here... + self.Body() + + # add line and buttons pane... + line = Line(self, size=(20,-1), direction='horizontal') + self.AddComponent(line, align='center', stretch=1, border=5) + + panel = self.AddButtonPanel(cancel_button) + + self.BindEvents() + + panel.Pack() + self.AddComponent(panel) + + self.Pack() + + self.Centre() + + def AddButtonPanel(self, cancel_button=1): + panel = Panel(self, direction='horizontal') + self.okbutton = Button(panel, "OK", event=self.OnClickOKButton) + self.okbutton.SetDefault() + panel.AddComponent(self.okbutton, expand=1, border=5) + + if cancel_button: + cancelbutton = Button(panel, "Cancel", event=self.OnClickCancelButton) + panel.AddComponent(cancelbutton, expand=1, border=5) + return panel + + def OnClickOKButton(self, event=None): + if self.Validate(): + event.Skip() + # only close the dialog if we validate: + self.EndModal(wx.ID_OK) + else: + self.OnValidateError(event) + + def OnClickCancelButton(self, event=None): + self.EndModal(wx.ID_CANCEL) + + def OnValidateError(self, event=None): + """ Override this to take action when the input does not validate. + (E.g. display an error message, etc.) """ + + def ShowModal(self): + """ Show the dialog modally. Returns 'ok' or 'cancel'. """ + r = wx.Dialog.ShowModal(self) + return { + wx.ID_OK: "ok", + wx.ID_CANCEL: "cancel", + }.get(r, "?") + + def Body(self): + # override this + # NOTE: do not call self.Pack() here, it's called automatically later + return None + + def Validate(self): + """ Override this to validate input and return 0 if it's not correct. + Return 1 otherwise. """ + return 1 + + # this doesn't work -- or does it?: + def OnCharHook(self, event=None): + if event.GetKeyCode() == keys.esc: + self.OnClickCancelButton() + event.Skip() + + +def showdialog(dialogclass, *args, **kwargs): + """ Easy function to call dialogs and clean up when it's done. """ + dlg = dialogclass(*args, **kwargs) + try: + result = dlg.ShowModal() + finally: + dlg.Destroy() + + if result=='ok': + val=dlg.GetValue() + else: + val=None + + dlg.Destroy() + + return val + diff --git a/pynxc/waxy/dialog.py~ b/pynxc/waxy/dialog.py~ new file mode 100644 index 0000000..48444ab --- /dev/null +++ b/pynxc/waxy/dialog.py~ @@ -0,0 +1,108 @@ +# dialog.py + +# TODO: Pressing Esc in a dialog should be the same as Cancel... +# (but how? using EVT_CHAR doesn't work... neither does OnCharHook.) + +import wx + +from button import Button +from containers import Container +from line import Line +from panel import Panel +from keys import keys +import frame + +# TODO: styles (same as Frame?) + +class Dialog(wx.Dialog, Container): + + __events__ = frame.Frame.__events__.copy() + __events__ .update({ + 'CharHook': wx.EVT_CHAR_HOOK, + }) + + def __init__(self, parent, title, cancel_button=1): + wx.Dialog.__init__(self, parent, wx.NewId(), title, wx.DefaultPosition) + + # this should create self.sizer and give access to self.AddComponent + self._create_sizer('vertical') + self.SetDefaultFont() + + # enter stuff here... + self.Body() + + # add line and buttons pane... + line = Line(self, size=(20,-1), direction='horizontal') + self.AddComponent(line, align='center', stretch=1, border=5) + + panel = self.AddButtonPanel(cancel_button) + + self.BindEvents() + + panel.Pack() + self.AddComponent(panel) + + self.Pack() + + self.Centre() + + def AddButtonPanel(self, cancel_button=1): + panel = Panel(self, direction='horizontal') + self.okbutton = Button(panel, "OK", event=self.OnClickOKButton) + self.okbutton.SetDefault() + panel.AddComponent(self.okbutton, expand=1, border=5) + + if cancel_button: + cancelbutton = Button(panel, "Cancel", event=self.OnClickCancelButton) + panel.AddComponent(cancelbutton, expand=1, border=5) + return panel + + def OnClickOKButton(self, event=None): + if self.Validate(): + event.Skip() + # only close the dialog if we validate: + self.EndModal(wx.ID_OK) + else: + self.OnValidateError(event) + + def OnClickCancelButton(self, event=None): + self.EndModal(wx.ID_CANCEL) + + def OnValidateError(self, event=None): + """ Override this to take action when the input does not validate. + (E.g. display an error message, etc.) """ + + def ShowModal(self): + """ Show the dialog modally. Returns 'ok' or 'cancel'. """ + r = wx.Dialog.ShowModal(self) + return { + wx.ID_OK: "ok", + wx.ID_CANCEL: "cancel", + }.get(r, "?") + + def Body(self): + # override this + # NOTE: do not call self.Pack() here, it's called automatically later + return None + + def Validate(self): + """ Override this to validate input and return 0 if it's not correct. + Return 1 otherwise. """ + return 1 + + # this doesn't work -- or does it?: + def OnCharHook(self, event=None): + if event.GetKeyCode() == keys.esc: + self.OnClickCancelButton() + event.Skip() + + +def showdialog(dialogclass, *args, **kwargs): + """ Easy function to call dialogs and clean up when it's done. """ + dlg = dialogclass(*args, **kwargs) + try: + result = dlg.ShowModal() + finally: + dlg.Destroy() + return result + diff --git a/pynxc/waxy/directorydialog.py b/pynxc/waxy/directorydialog.py new file mode 100644 index 0000000..5d1ee2a --- /dev/null +++ b/pynxc/waxy/directorydialog.py @@ -0,0 +1,39 @@ +# choosedirectory.py + +import wx +import waxyobject + +class DirectoryDialog(wx.DirDialog, waxyobject.WaxyObject): + + def __init__(self, parent, title="Choose a directory", new_dir_button=0): + style = wx.DD_DEFAULT_STYLE + if new_dir_button: + style |= wx.DD_NEW_DIR_BUTTON + wx.DirDialog.__init__(self, parent, title, style=style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.DirDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenDirectory(self): + """ Shorthand... """ + path = self.GetPath() + return path + + +# EXPERIMENTAL: +# This dialog returns a list of filenames (dlg.GetPath()) upon success, and +# an empty list upon cancel. + +def ChooseDirectory(parent, title="Choose a directory", new_dir_button=0): + path = None + dlg = DirectoryDialog(parent, title=title, new_dir_button=new_dir_button) + if dlg.ShowModal() == 'ok': + path = dlg.GetPath() + dlg.Destroy() + return path + diff --git a/pynxc/waxy/directorydialog.py~ b/pynxc/waxy/directorydialog.py~ new file mode 100644 index 0000000..866a238 --- /dev/null +++ b/pynxc/waxy/directorydialog.py~ @@ -0,0 +1,40 @@ +# choosedirectory.py + +import wx +import waxyobject + +class DirectoryDialog(wx.DirDialog, waxyobject.WaxyObject): + + def __init__(self, parent, title="Choose a directory", new_dir_button=0): + style = wx.DD_DEFAULT_STYLE + if new_dir_button: + style |= wx.DD_NEW_DIR_BUTTON + wx.DirDialog.__init__(self, parent, title, style=style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.DirDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenDirectory(self): + """ Shorthand... """ + data = self.GetColourData() + color = data.GetColour().Get() + return color + + +# EXPERIMENTAL: +# This dialog returns a list of filenames (dlg.GetPath()) upon success, and +# an empty list upon cancel. + +def ChooseDirectory(parent, title="Choose a directory", new_dir_button=0): + path = None + dlg = DirectoryDialog(parent, title=title, new_dir_button=new_dir_button) + if dlg.ShowModal() == 'ok': + path = dlg.GetPath() + dlg.Destroy() + return path + diff --git a/pynxc/waxy/dragdrop.py b/pynxc/waxy/dragdrop.py new file mode 100644 index 0000000..05a5965 --- /dev/null +++ b/pynxc/waxy/dragdrop.py @@ -0,0 +1,63 @@ +# dragdrop.py + +import wx + +# These can be overridden if you need them: +# def OnDropFiles(self, x, y, files) +# def OnDragOver(self, x, y, d) +# def OnEnter(self, x, y, d) +# def OnLeave(self, d) +# +# However, for most purposes, it will probably suffice to pass in a function +# to <event>. + +class FileDropTarget(wx.FileDropTarget): + # note that you can pass an event, or just override OnDropFiles. + + def __init__(self, window, event=None): + wx.FileDropTarget.__init__(self) + self.window = window + self.event = event + self.window.SetDropTarget(self) + + def OnDropFiles(self, x, y, filenames): + if self.event: + self.event(x, y, filenames) + +class TextDropTarget(wx.TextDropTarget): + + def __init__(self, window, event=None): + wx.TextDropTarget.__init__(self) + self.window = window + self.event = event + self.window.SetDropTarget(self) + + def OnDropText(self, x, y, text): + if self.event: + self.event(x, y, text) + + def OnDragOver(self, x, y, d): + return wx.DragCopy + # XXX not sure what this does; copied from wxPython demo + +class URLDropTarget(wx.PyDropTarget): + + def __init__(self, window, event=None): + # <event> is a function with signature (x, y, d, url). + wx.PyDropTarget.__init__(self) + self.window = window + self.event = event + self.window.SetDropTarget(self) + self.data = wx.URLDataObject() + self.SetDataObject(self.data) + + def OnDragOver(self, x, y, d): + return wx.DragLink + + def OnData(self, x, y, d): + if not self.GetData(): + return wx.DragNone + url = self.data.GetURL() + if self.event: + self.event(x, y, d, url) + return d diff --git a/pynxc/waxy/dropdownbox.py b/pynxc/waxy/dropdownbox.py new file mode 100644 index 0000000..345351a --- /dev/null +++ b/pynxc/waxy/dropdownbox.py @@ -0,0 +1,40 @@ +# dropdownbox.py + +# todo: styles... if any? + +import wx +import containers +import waxyobject +import styles + +class DropDownBox(wx.Choice, waxyobject.WaxyObject): + + __events__ = { + 'Select': wx.EVT_CHOICE, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= styles.window(kwargs) + wx.Choice.__init__(self, parent, wx.NewId(), choices=choices, + size=size or (-1,-1), style=style) + + self.BindEvents() + styles.properties(self, kwargs) + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + diff --git a/pynxc/waxy/dropdownbox.py~ b/pynxc/waxy/dropdownbox.py~ new file mode 100644 index 0000000..4598ff2 --- /dev/null +++ b/pynxc/waxy/dropdownbox.py~ @@ -0,0 +1,40 @@ +# dropdownbox.py + +# todo: styles... if any? + +import wx +import containers +import waxyobject +import styles + +class DropDownBox(wx.Choice, waxyobject.WaxyObject): + + __events__ = { + 'Select': wx.EVT_CHOICE, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= styles.window(kwargs) + wx.Choice.__init__(self, parent, wx.NewId(), choices=choices, + size=size or (-1,-1), style=style) + + self.BindEvents() + styles.properties(self, kwargs) + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + diff --git a/pynxc/waxy/events.py b/pynxc/waxy/events.py new file mode 100644 index 0000000..a9fef15 --- /dev/null +++ b/pynxc/waxy/events.py @@ -0,0 +1,33 @@ +# events.py + +import wx + +# place general events here... OnEnter, OnExit, mouse events, etc. + +events = { + 'Enter': wx.EVT_ENTER_WINDOW, # entering a control w/ mouse pointer + 'EnterWindow': wx.EVT_ENTER_WINDOW, + 'Exit': wx.EVT_LEAVE_WINDOW, # leaving a control w/ mouse pointer + 'ExitWindow': wx.EVT_LEAVE_WINDOW, + 'GetFocus': wx.EVT_SET_FOCUS, # control gets focus + 'HotKey': wx.EVT_HOTKEY, + 'KeyDown': wx.EVT_KEY_DOWN, + 'KeyUp': wx.EVT_KEY_UP, + 'Leave': wx.EVT_LEAVE_WINDOW, + 'LeaveWindow': wx.EVT_LEAVE_WINDOW, + 'LeftClick': wx.EVT_LEFT_DOWN, # alias for LeftDown + 'LeftDown': wx.EVT_LEFT_DOWN, + 'LeftDoubleClick': wx.EVT_LEFT_DCLICK, + 'LeftUp': wx.EVT_LEFT_UP, + 'LoseFocus': wx.EVT_KILL_FOCUS, # control loses focus + 'Motion':wx.EVT_MOTION, + 'Move': wx.EVT_MOVE, # window is moved. is this for frames only? + 'Resize': wx.EVT_SIZE, # same as 'Size' + 'RightClick': wx.EVT_RIGHT_DOWN, # alias for RightDown + 'RightDown': wx.EVT_RIGHT_DOWN, + 'RightUp': wx.EVT_RIGHT_UP, + 'Size': wx.EVT_SIZE, # window is resized + + # NOTE: OnPaint should really be here, but this causes problems with the + # OnPaint method that many controls already have. +} diff --git a/pynxc/waxy/filedialog.py b/pynxc/waxy/filedialog.py new file mode 100644 index 0000000..a11141e --- /dev/null +++ b/pynxc/waxy/filedialog.py @@ -0,0 +1,40 @@ +# filedialog.py + +import wx +import waxyobject + +class FileDialog(wx.FileDialog, waxyobject.WaxyObject): + + def __init__(self, parent, title="Choose a file", default_dir="", + default_file="", wildcard="*.*", open=0, save=0, multiple=0): + style = 0 + if open: + style |= wx.OPEN + elif save: + style |= wx.SAVE + style |= wx.OVERWRITE_PROMPT + if multiple: + style |= wx.MULTIPLE + + self.multiple=multiple + + wx.FileDialog.__init__(self, parent, title, default_dir, default_file, + wildcard, style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.FileDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + + def GetChosenFile(self): + """ Shorthand... """ + data = self.GetPaths() + + if not self.multiple: + data=data[0] + + return data diff --git a/pynxc/waxy/filedialog.py~ b/pynxc/waxy/filedialog.py~ new file mode 100644 index 0000000..2bfd2b6 --- /dev/null +++ b/pynxc/waxy/filedialog.py~ @@ -0,0 +1,35 @@ +# filedialog.py + +import wx +import waxyobject + +class FileDialog(wx.FileDialog, waxyobject.WaxyObject): + + def __init__(self, parent, title="Choose a file", default_dir="", + default_file="", wildcard="*.*", open=0, save=0, multiple=0): + style = 0 + if open: + style |= wx.OPEN + elif save: + style |= wx.SAVE + if multiple: + style |= wx.MULTIPLE + + self.multiple=multiple + + wx.FileDialog.__init__(self, parent, title, default_dir, default_file, + wildcard, style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.FileDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + + def GetChosenFile(self): + """ Shorthand... """ + data = self.GetPaths() + return data diff --git a/pynxc/waxy/flexgridpanel.py b/pynxc/waxy/flexgridpanel.py new file mode 100644 index 0000000..b8e5a90 --- /dev/null +++ b/pynxc/waxy/flexgridpanel.py @@ -0,0 +1,21 @@ +# flexgridpanel.py + +# todo: styles + +import wx +import containers +import panel + +class FlexGridPanel(wx.Panel, containers.FlexGridContainer): + """ Sub-level containers inside a frame, used for layout. """ + def __init__(self, parent=None, rows=3, cols=3, hgap=1, vgap=1, + growable_cols=(), growable_rows=()): + wx.Panel.__init__(self, parent or NULL, wx.NewId()) + + self._create_sizer(rows, cols, hgap, vgap) + self.Body() + + for col in growable_cols: + self.AddGrowableCol(col) + for row in growable_rows: + self.AddGrowableRow(row) diff --git a/pynxc/waxy/flexgridpanel.py~ b/pynxc/waxy/flexgridpanel.py~ new file mode 100644 index 0000000..751e1ae --- /dev/null +++ b/pynxc/waxy/flexgridpanel.py~ @@ -0,0 +1,22 @@ +# flexgridpanel.py + +# todo: styles + +import wx +import containers +import panel + +class FlexGridPanel(wx.Panel, containers.FlexGridContainer): + """ Sub-level containers inside a frame, used for layout. """ + def __init__(self, parent=None, rows=3, cols=3, hgap=1, vgap=1, + growable_cols=(), growable_rows=()): + wx.Panel.__init__(self, parent or NULL, wx.NewId()) + + self._create_sizer(rows, cols, hgap, vgap) + self.SetDefaultFont() + self.Body() + + for col in growable_cols: + self.AddGrowableCol(col) + for row in growable_rows: + self.AddGrowableRow(row) diff --git a/pynxc/waxy/font.py b/pynxc/waxy/font.py new file mode 100644 index 0000000..aefd228 --- /dev/null +++ b/pynxc/waxy/font.py @@ -0,0 +1,18 @@ +# font.py + +import wx + +class Font(wx.Font): + def __init__(self, name, size, italic=0, bold=0, underline=0): + wx.Font.__init__(self, size, wx.DEFAULT, italic and wx.ITALIC or wx.NORMAL, + bold and wx.BOLD or wx.NORMAL, underline, name) + + def IsItalic(self): + return bool(self.GetStyle() & wx.ITALIC) + + def IsBold(self): + return bool(self.GetWeight() & wx.BOLD) + + def IsUnderlined(self): + return self.GetUnderlined() + diff --git a/pynxc/waxy/fontdialog.py b/pynxc/waxy/fontdialog.py new file mode 100644 index 0000000..f4fbdca --- /dev/null +++ b/pynxc/waxy/fontdialog.py @@ -0,0 +1,35 @@ +# fontdialog.py + +# Issues: +# objects' GetFont() really should return a Font instance, not a wx.Font + +import wx +import waxyobject +from font import Font + +class FontDialog(wx.FontDialog, waxyobject.WaxyObject): + + def __init__(self, parent, data=None): + if not data: + data = wx.FontData() + wx.FontDialog.__init__(self, parent, data) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.FontDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenFont(self): + """ Shorthand... """ + data = self.GetFontData() + font = data.GetChosenFont() + font.__class__ = Font + return font + +# XXX +# Problem: GetFontData() returns a wxFontData object, whose GetChosenFont() +# still returns a wxFont, not a wax Font. No big deal really, but inconsistent. +# Maybe Wax needs its own FontData class...? diff --git a/pynxc/waxy/fontdialog.py~ b/pynxc/waxy/fontdialog.py~ new file mode 100644 index 0000000..e6959c0 --- /dev/null +++ b/pynxc/waxy/fontdialog.py~ @@ -0,0 +1,35 @@ +# fontdialog.py + +# Issues: +# objects' GetFont() really should return a Font instance, not a wx.Font + +import wx +import waxyobject +from font import Font + +class FontDialog(wx.FontDialog, waxobject.WaxObject): + + def __init__(self, parent, data=None): + if not data: + data = wx.FontData() + wx.FontDialog.__init__(self, parent, data) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.FontDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenFont(self): + """ Shorthand... """ + data = self.GetFontData() + font = data.GetChosenFont() + font.__class__ = Font + return font + +# XXX +# Problem: GetFontData() returns a wxFontData object, whose GetChosenFont() +# still returns a wxFont, not a wax Font. No big deal really, but inconsistent. +# Maybe Wax needs its own FontData class...? diff --git a/pynxc/waxy/frame.py b/pynxc/waxy/frame.py new file mode 100644 index 0000000..c98e932 --- /dev/null +++ b/pynxc/waxy/frame.py @@ -0,0 +1,67 @@ +# frame.py + +import wx +import containers +import styles + +class Frame(wx.Frame, containers.Container): + """ Top-level frame (window) with built-in sizer. """ + + __events__ = { + 'Close': wx.EVT_CLOSE, + 'Iconize': wx.EVT_ICONIZE, + 'Show': wx.EVT_SHOW, + 'Activate': wx.EVT_ACTIVATE, + 'Idle': wx.EVT_IDLE, + # some of these might be better off in events.py? + + 'MenuHighlight': wx.EVT_MENU_HIGHLIGHT, + } + + def __init__(self, parent=None, title="", direction="H", size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.Frame.__init__(self, parent, wx.NewId(), title, size=size or (-1,-1), + style=style) + + self.BindEvents() + + self._create_sizer(direction) + styles.properties(self, kwargs) + self.Body() + + def SetIcon(self, obj): + """ Like wx.Frame.SetIcon, but also accepts a path to an icon file. """ + if isinstance(obj, str) or isinstance(obj, unicode): + obj = wx.Icon(obj, wx.BITMAP_TYPE_ICO) # FIXME + wx.Frame.SetIcon(self, obj) + + # + # style parameters + + def _params(self, kwargs): + flags = wx.DEFAULT_FRAME_STYLE + + # REMOVE this flag if resize=0: + flags &= ~(styles.styleboolexclude('resize', wx.RESIZE_BORDER, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('close_box', wx.CLOSE_BOX, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('minimize_box', wx.MINIMIZE_BOX, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('maximize_box', wx.MAXIMIZE_BOX, kwargs, reverse=1)) + + flags |= styles.stylebool('shaped', wx.FRAME_SHAPED, kwargs) + flags |= styles.stylebool('stayontop', wx.STAY_ON_TOP, kwargs) + flags |= styles.stylebool('stay_on_top', wx.STAY_ON_TOP, kwargs) + return flags + + + +class HorizontalFrame(Frame): + def __init__(self, parent=None, title="", *args, **kwargs): + Frame.__init__(self, parent=parent, title=title, direction='h', *args, **kwargs) + +class VerticalFrame(Frame): + def __init__(self, parent=None, title="", *args, **kwargs): + Frame.__init__(self, parent=parent, title=title, direction='v', *args, **kwargs) + diff --git a/pynxc/waxy/frame.py~ b/pynxc/waxy/frame.py~ new file mode 100644 index 0000000..0758ca2 --- /dev/null +++ b/pynxc/waxy/frame.py~ @@ -0,0 +1,68 @@ +# frame.py + +import wx +import containers +import styles + +class Frame(wx.Frame, containers.Container): + """ Top-level frame (window) with built-in sizer. """ + + __events__ = { + 'Close': wx.EVT_CLOSE, + 'Iconize': wx.EVT_ICONIZE, + 'Show': wx.EVT_SHOW, + 'Activate': wx.EVT_ACTIVATE, + 'Idle': wx.EVT_IDLE, + # some of these might be better off in events.py? + + 'MenuHighlight': wx.EVT_MENU_HIGHLIGHT, + } + + def __init__(self, parent=None, title="", direction="H", size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.Frame.__init__(self, parent, wx.NewId(), title, size=size or (-1,-1), + style=style) + + self.BindEvents() + + self._create_sizer(direction) +# self.SetDefaultFont() + styles.properties(self, kwargs) + self.Body() + + def SetIcon(self, obj): + """ Like wx.Frame.SetIcon, but also accepts a path to an icon file. """ + if isinstance(obj, str) or isinstance(obj, unicode): + obj = wx.Icon(obj, wx.BITMAP_TYPE_ICO) # FIXME + wx.Frame.SetIcon(self, obj) + + # + # style parameters + + def _params(self, kwargs): + flags = wx.DEFAULT_FRAME_STYLE + + # REMOVE this flag if resize=0: + flags &= ~(styles.styleboolexclude('resize', wx.RESIZE_BORDER, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('close_box', wx.CLOSE_BOX, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('minimize_box', wx.MINIMIZE_BOX, kwargs, reverse=1)) + flags &= ~(styles.styleboolexclude('maximize_box', wx.MAXIMIZE_BOX, kwargs, reverse=1)) + + flags |= styles.stylebool('shaped', wx.FRAME_SHAPED, kwargs) + flags |= styles.stylebool('stayontop', wx.STAY_ON_TOP, kwargs) + flags |= styles.stylebool('stay_on_top', wx.STAY_ON_TOP, kwargs) + return flags + + + +class HorizontalFrame(Frame): + def __init__(self, parent=None, title="", *args, **kwargs): + Frame.__init__(self, parent=parent, title=title, direction='h', *args, **kwargs) + +class VerticalFrame(Frame): + def __init__(self, parent=None, title="", *args, **kwargs): + Frame.__init__(self, parent=parent, title=title, direction='v', *args, **kwargs) + diff --git a/pynxc/waxy/grid.py b/pynxc/waxy/grid.py new file mode 100644 index 0000000..e246405 --- /dev/null +++ b/pynxc/waxy/grid.py @@ -0,0 +1,52 @@ +# grid.py + +# todo: styles + +import wx +import wx.grid as gridlib +import waxyobject + +class Grid(gridlib.Grid, waxyobject.WaxyObject): + + __events__ = { + 'CellLeftClick': gridlib.EVT_GRID_CELL_LEFT_CLICK, + 'CellRightClick': gridlib.EVT_GRID_CELL_RIGHT_CLICK, + 'CellLeftDoubleClick': gridlib.EVT_GRID_CELL_LEFT_DCLICK, + 'CellRightDoubleClick': gridlib.EVT_GRID_CELL_RIGHT_DCLICK, + 'LabelLeftClick': gridlib.EVT_GRID_LABEL_LEFT_CLICK, + 'LabelRightClick': gridlib.EVT_GRID_LABEL_RIGHT_CLICK, + 'LabelLeftDoubleClick': gridlib.EVT_GRID_LABEL_LEFT_DCLICK, + 'LabelRightDoubleClick': gridlib.EVT_GRID_LABEL_RIGHT_DCLICK, + 'RowSize': gridlib.EVT_GRID_ROW_SIZE, + 'ColSize': gridlib.EVT_GRID_COL_SIZE, + 'RangeSelect': gridlib.EVT_GRID_RANGE_SELECT, + 'CellChange':gridlib.EVT_GRID_CELL_CHANGE, + 'SelectCell':gridlib.EVT_GRID_SELECT_CELL, + 'EditorShown':gridlib.EVT_GRID_EDITOR_SHOWN, + 'EditorHidden':gridlib.EVT_GRID_EDITOR_HIDDEN, + 'EditorCreated':gridlib.EVT_GRID_EDITOR_CREATED, + } + + + def __init__(self, parent, numrows=10, numcolumns=10): + gridlib.Grid.__init__(self, parent, wx.NewId()) + self.CreateGrid(numrows, numcolumns) + self.BindEvents() + + def SetGlobalSize(self, rowsize, colsize): + """ Set all cells to the same size. """ + for i in range(self.GetNumberRows()): + self.SetRowSize(i, rowsize) + for i in range(self.GetNumberCols()): + self.SetColSize(i, colsize) + + def __setitem__(self, index, value): + assert isinstance(index, tuple) and len(index) == 2 + row, column = index + self.SetCellValue(row, column, value) + + def __getitem__(self, index): + assert isinstance(index, tuple) and len(index) == 2 + row, column = index + return self.GetCellValue(row, column) + diff --git a/pynxc/waxy/gridpanel.py b/pynxc/waxy/gridpanel.py new file mode 100644 index 0000000..ff010af --- /dev/null +++ b/pynxc/waxy/gridpanel.py @@ -0,0 +1,24 @@ +# gridpanel.py + +# todo: styles + +import wx +import containers +import panel + +class GridPanel(wx.Panel, containers.GridContainer): + """ Sub-level containers inside a frame, used for layout. """ + def __init__(self, parent=None, rows=3, cols=3, hgap=1, vgap=1): + wx.Panel.__init__(self, parent or NULL, wx.NewId()) + + self._create_sizer(rows, cols, hgap, vgap) +# self.SetDefaultFont() + self.Body() + +''' +NOTES + +1. Do not make the mistake of writing GridPanel(parent, 3, 3, 2, 2) or something +like that. This will work, but set the *title* to 3, and cols to 2. +Why does a Panel need a title anyway? Can we remove this? +''' diff --git a/pynxc/waxy/htmlwindow.py b/pynxc/waxy/htmlwindow.py new file mode 100644 index 0000000..4453bcd --- /dev/null +++ b/pynxc/waxy/htmlwindow.py @@ -0,0 +1,15 @@ +# htmlwindow.py + +# todo: styles + +import wx.html +import waxyobject + +class HTMLWindow(wx.html.HtmlWindow, waxyobject.WaxyObject): + + def __init__(self, parent, fullrepaint=1): + style = 0 + if not fullrepaint: + style |= wx.NO_FULL_REPAINT_ON_RESIZE + wx.html.HtmlWindow.__init__(self, parent, wx.NewId(), style=style) + diff --git a/pynxc/waxy/htmlwindow.py~ b/pynxc/waxy/htmlwindow.py~ new file mode 100644 index 0000000..57a649d --- /dev/null +++ b/pynxc/waxy/htmlwindow.py~ @@ -0,0 +1,15 @@ +# htmlwindow.py + +# todo: styles + +import wx.html +import waxobject + +class HTMLWindow(wx.html.HtmlWindow, waxobject.WaxObject): + + def __init__(self, parent, fullrepaint=1): + style = 0 + if not fullrepaint: + style |= wx.NO_FULL_REPAINT_ON_RESIZE + wx.html.HtmlWindow.__init__(self, parent, wx.NewId(), style=style) + diff --git a/pynxc/waxy/image.py b/pynxc/waxy/image.py new file mode 100644 index 0000000..e18bfc8 --- /dev/null +++ b/pynxc/waxy/image.py @@ -0,0 +1,115 @@ +# image.py + +import wx +import waxyobject + +_handlers = {} + +def AddImageHandler(type): + d = { + "bmp": wx.BMPHandler, + "png": wx.PNGHandler, + "jpg": wx.JPEGHandler, + "gif": wx.GIFHandler, + "pcx": wx.PCXHandler, + "pnm": wx.PNMHandler, + "tiff": wx.TIFFHandler, + #"iff": wx.IFFHandler, + #"xpm": wx.XPMHandler, + "ico": wx.ICOHandler, + "cur": wx.CURHandler, + "ani": wx.ANIHandler, + } + key = type.lower() + handler = d[key] + wx.Image_AddHandler(handler()) + _handlers[key] = 1 + +def AddAllImageHandlers(): + wx.InitAllImageHandlers() + +class Image(wx.Image, waxyobject.WaxyObject): + + def __init__(self, filename, type=None, autoinstall=False): + lfilename = filename.lower() + t = 0 + + # if type isn't set, try to grok it from the filename. + if not type: + if lfilename.endswith(".bmp"): + type = 'bmp' + elif lfilename.endswith(".gif"): + type = 'gif' + elif lfilename.endswith(".png"): + type = 'png' + elif lfilename.endswith(".jpg") or lfilename.endswith(".jpeg"): + type = 'jpg' + elif lfilename.endswith(".pcx"): + type = 'pcx' + elif lfilename.endswith(".ico"): + type = 'ico' + + t = { + "bmp": wx.BITMAP_TYPE_BMP, + "gif": wx.BITMAP_TYPE_GIF, + "png": wx.BITMAP_TYPE_PNG, + "jpg": wx.BITMAP_TYPE_JPEG, + "jpeg": wx.BITMAP_TYPE_JPEG, + "pcx": wx.BITMAP_TYPE_PCX, + "ico": wx.BITMAP_TYPE_ICO, + }.get(type.lower(), 0) + + if not t: + raise ValueError, "Could not determine bitmap type of '%s'" % ( + filename,) + + # if autoinstall is true, install handler on demand + if autoinstall: + if not _handlers.has_key(type): + AddImageHandler(type) + + wx.Image.__init__(self, filename, t) + + +def ImageAsBitmap(filename, *args, **kwargs): + return Image(filename, *args, **kwargs).ConvertToBitmap() + +class ImagePanel(wx.Panel, waxyobject.WaxyObject): + + def __init__(self,parent,image,size=(200,200),pos=(0,0)): + + wx.Panel.__init__(self,parent, size=size,pos=pos) + + if isinstance(image,str): + self.image=Image(image) + else: + self.image=image + + self.bitmap=wx.StaticBitmap(self, -1, self.image.ConvertToBitmap(), + style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER) + self.update() + + def SetImage(self,image): + + if isinstance(image,str): + image=Image(image) + + self.image=image + self.update() + + def update(self): + + size=self.GetSizeTuple() + + imsize=(self.image.GetWidth(),self.image.GetHeight()) + + if (float(imsize[0])/float(size[0]))>(float(imsize[1])/float(size[1])): + scale=(float(imsize[0])/float(size[0])) + else: + scale=(float(imsize[1])/float(size[1])) + + newsize=(int(imsize[0]/scale),int(imsize[1]/scale)) + newpos=( (size[0]-newsize[0])/2, (size[1]-newsize[1])/2) + self.bitmap.SetBitmap(self.image.Rescale(newsize[0],newsize[1]).ConvertToBitmap()) + self.bitmap.SetPosition(newpos); + diff --git a/pynxc/waxy/image.py~ b/pynxc/waxy/image.py~ new file mode 100644 index 0000000..7b0d062 --- /dev/null +++ b/pynxc/waxy/image.py~ @@ -0,0 +1,116 @@ +# image.py + +import wx +import waxyobject + +_handlers = {} + +def AddImageHandler(type): + d = { + "bmp": wx.BMPHandler, + "png": wx.PNGHandler, + "jpg": wx.JPEGHandler, + "gif": wx.GIFHandler, + "pcx": wx.PCXHandler, + "pnm": wx.PNMHandler, + "tiff": wx.TIFFHandler, + #"iff": wx.IFFHandler, + #"xpm": wx.XPMHandler, + "ico": wx.ICOHandler, + "cur": wx.CURHandler, + "ani": wx.ANIHandler, + } + key = type.lower() + handler = d[key] + wx.Image_AddHandler(handler()) + _handlers[key] = 1 + +def AddAllImageHandlers(): + wx.InitAllImageHandlers() + +class Image(wx.Image, waxyobject.WaxyObject): + + def __init__(self, filename, type=None, autoinstall=False): + lfilename = filename.lower() + t = 0 + + # if type isn't set, try to grok it from the filename. + if not type: + if lfilename.endswith(".bmp"): + type = 'bmp' + elif lfilename.endswith(".gif"): + type = 'gif' + elif lfilename.endswith(".png"): + type = 'png' + elif lfilename.endswith(".jpg") or lfilename.endswith(".jpeg"): + type = 'jpg' + elif lfilename.endswith(".pcx"): + type = 'pcx' + elif lfilename.endswith(".ico"): + type = 'ico' + + t = { + "bmp": wx.BITMAP_TYPE_BMP, + "gif": wx.BITMAP_TYPE_GIF, + "png": wx.BITMAP_TYPE_PNG, + "jpg": wx.BITMAP_TYPE_JPEG, + "jpeg": wx.BITMAP_TYPE_JPEG, + "pcx": wx.BITMAP_TYPE_PCX, + "ico": wx.BITMAP_TYPE_ICO, + }.get(type.lower(), 0) + + if not t: + raise ValueError, "Could not determine bitmap type of '%s'" % ( + filename,) + + # if autoinstall is true, install handler on demand + if autoinstall: + if not _handlers.has_key(type): + AddImageHandler(type) + + wx.Image.__init__(self, filename, t) + + +def ImageAsBitmap(filename, *args, **kwargs): + return Image(filename, *args, **kwargs).ConvertToBitmap() + +class ImagePanel(wx.Panel, waxyobject.WaxyObject): + + def __init__(self,parent,image_filename,size=(200,200),pos=(0,0)): + + wx.Panel.__init__(self,parent, size=size,pos=pos) + + if isinstance(image_filename,str): + + self.image=Image(image_filename) + else: + self.image=image_filename + + self.bitmap=wx.StaticBitmap(self, -1, self.image.ConvertToBitmap(), + style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER) + self.update() + + def SetImage(self,image): + + if isinstance(image,str): + image=Image(image) + + self.image=image + self.update() + + def update(self): + + size=self.GetSizeTuple() + + imsize=(self.image.GetWidth(),self.image.GetHeight()) + + if (float(imsize[0])/float(size[0]))>(float(imsize[1])/float(size[1])): + scale=(float(imsize[0])/float(size[0])) + else: + scale=(float(imsize[1])/float(size[1])) + + newsize=(int(imsize[0]/scale),int(imsize[1]/scale)) + newpos=( (size[0]-newsize[0])/2, (size[1]-newsize[1])/2) + self.bitmap.SetBitmap(self.image.Rescale(newsize[0],newsize[1]).ConvertToBitmap()) + self.bitmap.SetPosition(newpos); + diff --git a/pynxc/waxy/imagelist.py b/pynxc/waxy/imagelist.py new file mode 100644 index 0000000..f23c91d --- /dev/null +++ b/pynxc/waxy/imagelist.py @@ -0,0 +1,38 @@ +"""\ +imagelist.py + +Wax's version of the wxImageList is a bit more user-friendly: + +Rather than forcing you to keep the indexes around or know them by heart, +you can (optionally) add names for the images you add, then look them up to +retrieve the index: + + imagelist.Add(bitmap, 'folder') + imagelist.Add(bitmap, 'folder_open') + + somecontrol.SetItemImage(node, imagelist['folder']) + +""" + +import wx + +class ImageList(wx.ImageList): + + def __init__(self, *args, **kwargs): + wx.ImageList.__init__(self, *args, **kwargs) + self._names = {} + + def Add(self, bitmap, name=None): + if isinstance(bitmap, str) or isinstance(bitmap, unicode): + bitmap = wx.BitmapFromImage(wx.Image(bitmap)) + + index = wx.ImageList.Add(self, bitmap) + if name: + self._names[name] = index + + return index + def GetIndexByName(self, name): + return self._names[name] + + def __getitem__(self, name): + return self.GetIndexByName(name) diff --git a/pynxc/waxy/imagepanel.py b/pynxc/waxy/imagepanel.py new file mode 100644 index 0000000..d04609c --- /dev/null +++ b/pynxc/waxy/imagepanel.py @@ -0,0 +1,34 @@ +import wx + +class ImagePanel(wx.Panel): + + def __init__(self,parent,id,size=(200,200),image=None,pos=(0,0)): + + wx.Panel.__init__(self,parent, id,size=size,pos=pos) + + self.image=image + + self.bitmap=wx.StaticBitmap(self, -1, image.ConvertToBitmap(), + style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER) + self.update() + + def SetImage(self,image): + self.image=image + self.update() + + def update(self): + + size=self.GetSizeTuple() + imsize=(self.image.GetWidth(),self.image.GetHeight()) + + if (float(imsize[0])/float(size[0]))>(float(imsize[1])/float(size[1])): + scale=(float(imsize[0])/float(size[0])) + else: + scale=(float(imsize[1])/float(size[1])) + + newsize=(int(imsize[0]/scale),int(imsize[1]/scale)) + newpos=( (size[0]-newsize[0])/2, (size[1]-newsize[1])/2) + self.bitmap.SetBitmap(self.image.Rescale(newsize[0],newsize[1]).ConvertToBitmap()) + self.bitmap.SetPosition(newpos); + + diff --git a/pynxc/waxy/imagepanel.py~ b/pynxc/waxy/imagepanel.py~ new file mode 100644 index 0000000..af2081f --- /dev/null +++ b/pynxc/waxy/imagepanel.py~ @@ -0,0 +1,33 @@ +import wx + +class ImagePanel(wx.Panel): + + def __init__(self,parent,id,size=(200,200),image=None,pos=(0,0)): + + wx.Panel.__init__(self,parent, id,size=size,pos=pos) + + self.image=image + + self.bitmap=wx.StaticBitmap(self, -1, image.ConvertToBitmap(), + style=wx.TAB_TRAVERSAL|wx.SIMPLE_BORDER) + self.update() + + def SetImage(self,image): + self.image=image + self.update() + + def update(self): + + size=self.GetSizeTuple() + imsize=(self.image.GetWidth(),self.image.GetHeight()) + + if (float(imsize[0])/float(size[0]))>(float(imsize[1])/float(size[1])): + scale=(float(imsize[0])/float(size[0])) + else: + scale=(float(imsize[1])/float(size[1])) + + newsize=(int(imsize[0]/scale),int(imsize[1]/scale)) + newpos=( (size[0]-newsize[0])/2, (size[1]-newsize[1])/2) + self.bitmap.SetBitmap(self.image.Rescale(newsize[0],newsize[1]).ConvertToBitmap()) + self.bitmap.SetPosition(newpos); + diff --git a/pynxc/waxy/keys.py b/pynxc/waxy/keys.py new file mode 100644 index 0000000..dc3b355 --- /dev/null +++ b/pynxc/waxy/keys.py @@ -0,0 +1,44 @@ +# keys.py + +import wx + +class keys: + enter = wx.WXK_RETURN + # 'return' is not valid; reserved word + + alt = wx.WXK_ALT + control = ctrl = wx.WXK_CONTROL + shift = wx.WXK_SHIFT + + f1 = F1 = wx.WXK_F1 + f2 = F2 = wx.WXK_F2 + f3 = F3 = wx.WXK_F3 + f4 = F4 = wx.WXK_F4 + f5 = F5 = wx.WXK_F5 + f6 = F6 = wx.WXK_F6 + f7 = F7 = wx.WXK_F7 + f8 = F8 = wx.WXK_F8 + f9 = F9 = wx.WXK_F9 + f10 = F10 = wx.WXK_F10 + f11 = F11 = wx.WXK_F11 + f12 = F12 = wx.WXK_F12 + + insert = wx.WXK_INSERT + delete = wx.WXK_DELETE + home = wx.WXK_HOME + end = wx.WXK_END + + up = cursor_up = wx.WXK_UP + down = cursor_down = wx.WXK_DOWN + left = cursor_left = wx.WXK_LEFT + right = cursor_right = wx.WXK_RIGHT + + pageup = pgup = wx.WXK_PRIOR # not: wx.WXK_PAGEUP + pagedown = pgdown = pgdn = wx.WXK_NEXT # not: wx.WXK_PAGEDOWN + + tab = wx.WXK_TAB + backspace = bsp = wx.WXK_BACK + esc = escape = wx.WXK_ESCAPE + + # XXX more later...? + diff --git a/pynxc/waxy/label.py b/pynxc/waxy/label.py new file mode 100644 index 0000000..ed77117 --- /dev/null +++ b/pynxc/waxy/label.py @@ -0,0 +1,33 @@ +# label.py + +import wx +import containers +import waxyobject +import styles + +class Label(wx.StaticText, waxyobject.WaxyObject): + + def __init__(self, parent, text="", size=None, **kwargs): + #assert isinstance(parent, containers.Container) + + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.StaticText.__init__(self, parent, wx.NewId(), text, + size=size or (-1,-1), style=style) + styles.properties(self, kwargs) + + # + # style parameters + + __styles__ = { + 'align': ({ + 'left': wx.ALIGN_LEFT, + 'right': wx.ALIGN_RIGHT, + 'center': wx.ALIGN_CENTRE, + 'centre': wx.ALIGN_CENTRE, + }, styles.DICTSTART), + 'noresize': (wx.ST_NO_AUTORESIZE, styles.NORMAL), + } + diff --git a/pynxc/waxy/label.py~ b/pynxc/waxy/label.py~ new file mode 100644 index 0000000..eb2e266 --- /dev/null +++ b/pynxc/waxy/label.py~ @@ -0,0 +1,33 @@ +# label.py + +import wx +import containers +import waxyobject +import styles + +class Label(wx.StaticText, waxyobject.WaxObject): + + def __init__(self, parent, text="", size=None, **kwargs): + #assert isinstance(parent, containers.Container) + + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.StaticText.__init__(self, parent, wx.NewId(), text, + size=size or (-1,-1), style=style) + styles.properties(self, kwargs) + + # + # style parameters + + __styles__ = { + 'align': ({ + 'left': wx.ALIGN_LEFT, + 'right': wx.ALIGN_RIGHT, + 'center': wx.ALIGN_CENTRE, + 'centre': wx.ALIGN_CENTRE, + }, styles.DICTSTART), + 'noresize': (wx.ST_NO_AUTORESIZE, styles.NORMAL), + } + diff --git a/pynxc/waxy/line.py b/pynxc/waxy/line.py new file mode 100644 index 0000000..f25448c --- /dev/null +++ b/pynxc/waxy/line.py @@ -0,0 +1,18 @@ +# line.py + +import wx +import waxyobject + +class Line(wx.StaticLine, waxyobject.WaxyObject): + + def __init__(self, parent, size=(20,-1), direction='horizontal'): + style = 0 + if direction.lower().startswith('h'): + style |= wx.LI_HORIZONTAL + elif direction.lower().startswith('v'): + style |= wx.LI_HORIZONTAL + else: + raise ValueError, "direction should be horizontal or vertical" + + wx.StaticLine.__init__(self, parent, wx.NewId(), size=size, style=style) + diff --git a/pynxc/waxy/line.py~ b/pynxc/waxy/line.py~ new file mode 100644 index 0000000..6653a3e --- /dev/null +++ b/pynxc/waxy/line.py~ @@ -0,0 +1,18 @@ +# line.py + +import wx +import waxyobject + +class Line(wx.StaticLine, waxyobject.WaxObject): + + def __init__(self, parent, size=(20,-1), direction='horizontal'): + style = 0 + if direction.lower().startswith('h'): + style |= wx.LI_HORIZONTAL + elif direction.lower().startswith('v'): + style |= wx.LI_HORIZONTAL + else: + raise ValueError, "direction should be horizontal or vertical" + + wx.StaticLine.__init__(self, parent, wx.NewId(), size=size, style=style) + diff --git a/pynxc/waxy/listbox.py b/pynxc/waxy/listbox.py new file mode 100644 index 0000000..c1283cc --- /dev/null +++ b/pynxc/waxy/listbox.py @@ -0,0 +1,92 @@ +# listbox.py + +import wx +import containers +import waxyobject +import styles + +class ListBox(wx.ListBox, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_LISTBOX, + 'DoubleClick': wx.EVT_LISTBOX_DCLICK, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.ListBox.__init__(self, parent, wx.NewId(), size=size or (-1,-1), + choices=choices, style=style) + + self.BindEvents() + + styles.properties(self, kwargs) + + def SetSelectionType(self, selection): + style = 0 + selection = selection.lower() + if selection == "single": + style |= wx.LB_SINGLE + elif selection == "multiple": + style |= wx.LB_MULTIPLE + elif selection == "extended": + style |= wx.LB_EXTENDED + else: + raise ValueError, "selection must be single, multiple or extended" + return style + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def Fill(self, items): + """ Like SetItems, but just uses a list of strings. """ + self.Clear() + for s in items: + self.Append(s) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + + # TODO: + # Add __getitem__, __setitem__, __delitem__ + # These should probably work with tuples (string, data). + # 1-tuples can be used, in which case data are left alone. + # Non-tuples are not allowed. + + # We should also be able to iterate over a ListBox... + # Although for (s, data) in listbox.GetItems() would work too. + + # + # style parameters + + _listbox_selection = { + 'single': wx.LB_SINGLE, + 'multiple': wx.LB_MULTIPLE, + 'extended': wx.LB_EXTENDED, + } + + _listbox_scrollbar = { + 'always': wx.LB_ALWAYS_SB, + 'needed': wx.LB_NEEDED_SB, + } + + def _params(self, kwargs): + flags = 0 + flags |= styles.styledictstart('selection', self._listbox_selection, kwargs) + flags |= styles.styledictstart('scrollbar', self._listbox_scrollbar, kwargs) + flags |= styles.stylebool('sort', wx.LB_SORT, kwargs) + flags |= styles.stylebool('horizontal_scrollbar', wx.LB_HSCROLL, kwargs) + + return flags diff --git a/pynxc/waxy/listbox.py~ b/pynxc/waxy/listbox.py~ new file mode 100644 index 0000000..377694a --- /dev/null +++ b/pynxc/waxy/listbox.py~ @@ -0,0 +1,92 @@ +# listbox.py + +import wx +import containers +import waxobject +import styles + +class ListBox(wx.ListBox, waxyobject.WaxyObject): + + __events__ = { + 'Click': wx.EVT_LISTBOX, + 'DoubleClick': wx.EVT_LISTBOX_DCLICK, + } + + def __init__(self, parent, choices=[], size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.ListBox.__init__(self, parent, wx.NewId(), size=size or (-1,-1), + choices=choices, style=style) + + self.BindEvents() + + styles.properties(self, kwargs) + + def SetSelectionType(self, selection): + style = 0 + selection = selection.lower() + if selection == "single": + style |= wx.LB_SINGLE + elif selection == "multiple": + style |= wx.LB_MULTIPLE + elif selection == "extended": + style |= wx.LB_EXTENDED + else: + raise ValueError, "selection must be single, multiple or extended" + return style + + def SetItems(self, items): + """ Clear the internal list of items, and set new items. <items> is + a list of 2-tuples (string, data). """ + self.Clear() + for s, data in items: + self.Append(s, data) + + def Fill(self, items): + """ Like SetItems, but just uses a list of strings. """ + self.Clear() + for s in items: + self.Append(s) + + def GetItems(self): + """ Return a list of 2-tuples (string, data). """ + items = [] + for i in range(self.GetCount()): + s = self.GetString(i) + data = self.GetClientData(i) + items.append((s, data)) + return items + + # TODO: + # Add __getitem__, __setitem__, __delitem__ + # These should probably work with tuples (string, data). + # 1-tuples can be used, in which case data are left alone. + # Non-tuples are not allowed. + + # We should also be able to iterate over a ListBox... + # Although for (s, data) in listbox.GetItems() would work too. + + # + # style parameters + + _listbox_selection = { + 'single': wx.LB_SINGLE, + 'multiple': wx.LB_MULTIPLE, + 'extended': wx.LB_EXTENDED, + } + + _listbox_scrollbar = { + 'always': wx.LB_ALWAYS_SB, + 'needed': wx.LB_NEEDED_SB, + } + + def _params(self, kwargs): + flags = 0 + flags |= styles.styledictstart('selection', self._listbox_selection, kwargs) + flags |= styles.styledictstart('scrollbar', self._listbox_scrollbar, kwargs) + flags |= styles.stylebool('sort', wx.LB_SORT, kwargs) + flags |= styles.stylebool('horizontal_scrollbar', wx.LB_HSCROLL, kwargs) + + return flags diff --git a/pynxc/waxy/menu.py b/pynxc/waxy/menu.py new file mode 100644 index 0000000..ef587fc --- /dev/null +++ b/pynxc/waxy/menu.py @@ -0,0 +1,135 @@ +# menu.py + +import wx +import waxyobject +import string + +class Menu(wx.Menu, waxyobject.WaxyObject): + + def __init__(self, parent, autoevents=1): + wx.Menu.__init__(self) + self.parent = parent # necessary for hooking up events + self.autoevents = autoevents + + def Append(self, title, event=None, tooltip="", type="", hotkey="",special=''): + # Note: the order is different from wx.Menu.Append! + style = 0 + style |= { + "r": wx.ITEM_RADIO, + "c": wx.ITEM_CHECK, + }.get(type.lower()[:1], wx.ITEM_NORMAL) + + if hotkey: + title = title + "\t" + hotkey + + if special.lower()=='about': + id=wx.ID_ABOUT + elif special.lower()=='exit': + id=wx.ID_EXIT + else: + id = wx.NewId() + + item = wx.Menu.Append(self, id, title, tooltip, style) + if event: + # you *can* choose to specify no event, but that doesn't seem very + # useful + wx.EVT_MENU(self.parent, id, event) + elif self.autoevents: + wx.EVT_MENU(self.parent, id, self.HandleAutoEvent) + + return item + + def AppendMenu(self, title, menu): + id = wx.NewId() + return wx.Menu.AppendMenu(self, id, title, menu) + # I suppose there's room for an event here, but why bother...? + + def GetItem(self, title): + """ Find item by title, bypassing the internal id. """ + id = self.FindItem(title) + item = self.FindItemById(id) + return item + + def Delete(self, obj): + # according to the wxWindows reference, wx.Menu.Delete() also accepts + # MenuItems... but apparently that isn't true, at least not in wxPython. + # So let's fix it: + if isinstance(obj, wx.MenuItem): + id = obj.GetId() + return wx.Menu.Delete(self, id) + else: + # assume it's a number + return wx.Menu.Delete(self, obj) + + def HandleAutoEvent(self, event): + id = event.GetId() + menuitem = self.FindItemById(id) + + def GetFullTitle(id): + menubar = self.parent.GetMenuBar() + if menubar: + for mwitem in menubar.Walk(): + if mwitem.items and mwitem.items[-1].GetId() == id: + title = mwitem.name + for menuitem in mwitem.items: + title = title + " " + menuitem.GetLabel() + return title + return None + + title = GetFullTitle(id) + if title: + methodname = "Menu_" + genmethodname(title) + #print "Looking for:", methodname + if hasattr(self.parent, methodname): + f = getattr(self.parent, methodname) + f(event) + + # these aliases make sense... + Add = Append + AddMenu = AppendMenu + + def Walk(self): + for menuitem in self.GetMenuItems(): + yield [menuitem] + submenu = menuitem.GetSubMenu() + if submenu: + for subitem in submenu.Walk(): + yield [menuitem] + subitem + + # TODO: Is it possible to write a better GetTitle() or GetRealTitle() + # or something, that gives us the actual label of the menu? + +class MenuBar(wx.MenuBar, waxyobject.WaxyObject): + def __init__(self, parent=None, *args, **kwargs): + wx.MenuBar.__init__(self, *args, **kwargs) + if parent: parent.SetMenuBar(self) + + def Append(self, menu, text): + wx.MenuBar.Append(self, menu, text) + + def Walk(self): + for i in range(self.GetMenuCount()): + menu = self.GetMenu(i) + for items in menu.Walk(): + menuwalkitem = _MenuWalkItem() + menuwalkitem.name = self.GetLabelTop(i) + menuwalkitem.menu = menu + menuwalkitem.items = items + yield menuwalkitem + +class _MenuWalkItem: + pass + +# +# auxiliary methods + +def genmethodname(title): + allowed = string.letters + string.digits + "_" + name = "" + for char in title: + if char in allowed: + name = name + char + elif char == ' ': + name = name + '_' + return name + diff --git a/pynxc/waxy/menu.py~ b/pynxc/waxy/menu.py~ new file mode 100644 index 0000000..2cab266 --- /dev/null +++ b/pynxc/waxy/menu.py~ @@ -0,0 +1,129 @@ +# menu.py + +import wx +import waxyobject +import string + +class Menu(wx.Menu, waxyobject.WaxyObject): + + def __init__(self, parent, autoevents=1): + wx.Menu.__init__(self) + self.parent = parent # necessary for hooking up events + self.autoevents = autoevents + + def Append(self, title, event=None, tooltip="", type="", hotkey=""): + # Note: the order is different from wx.Menu.Append! + style = 0 + style |= { + "r": wx.ITEM_RADIO, + "c": wx.ITEM_CHECK, + }.get(type.lower()[:1], wx.ITEM_NORMAL) + + if hotkey: + title = title + "\t" + hotkey + + id = wx.NewId() + item = wx.Menu.Append(self, id, title, tooltip, style) + if event: + # you *can* choose to specify no event, but that doesn't seem very + # useful + wx.EVT_MENU(self.parent, id, event) + elif self.autoevents: + wx.EVT_MENU(self.parent, id, self.HandleAutoEvent) + + return item + + def AppendMenu(self, title, menu): + id = wx.NewId() + return wx.Menu.AppendMenu(self, id, title, menu) + # I suppose there's room for an event here, but why bother...? + + def GetItem(self, title): + """ Find item by title, bypassing the internal id. """ + id = self.FindItem(title) + item = self.FindItemById(id) + return item + + def Delete(self, obj): + # according to the wxWindows reference, wx.Menu.Delete() also accepts + # MenuItems... but apparently that isn't true, at least not in wxPython. + # So let's fix it: + if isinstance(obj, wx.MenuItem): + id = obj.GetId() + return wx.Menu.Delete(self, id) + else: + # assume it's a number + return wx.Menu.Delete(self, obj) + + def HandleAutoEvent(self, event): + id = event.GetId() + menuitem = self.FindItemById(id) + + def GetFullTitle(id): + menubar = self.parent.GetMenuBar() + if menubar: + for mwitem in menubar.Walk(): + if mwitem.items and mwitem.items[-1].GetId() == id: + title = mwitem.name + for menuitem in mwitem.items: + title = title + " " + menuitem.GetLabel() + return title + return None + + title = GetFullTitle(id) + if title: + methodname = "Menu_" + genmethodname(title) + #print "Looking for:", methodname + if hasattr(self.parent, methodname): + f = getattr(self.parent, methodname) + f(event) + + # these aliases make sense... + Add = Append + AddMenu = AppendMenu + + def Walk(self): + for menuitem in self.GetMenuItems(): + yield [menuitem] + submenu = menuitem.GetSubMenu() + if submenu: + for subitem in submenu.Walk(): + yield [menuitem] + subitem + + # TODO: Is it possible to write a better GetTitle() or GetRealTitle() + # or something, that gives us the actual label of the menu? + +class MenuBar(wx.MenuBar, waxobject.WaxObject): + def __init__(self, parent=None, *args, **kwargs): + wx.MenuBar.__init__(self, *args, **kwargs) + if parent: parent.SetMenuBar(self) + + def Append(self, menu, text): + wx.MenuBar.Append(self, menu, text) + + def Walk(self): + for i in range(self.GetMenuCount()): + menu = self.GetMenu(i) + for items in menu.Walk(): + menuwalkitem = _MenuWalkItem() + menuwalkitem.name = self.GetLabelTop(i) + menuwalkitem.menu = menu + menuwalkitem.items = items + yield menuwalkitem + +class _MenuWalkItem: + pass + +# +# auxiliary methods + +def genmethodname(title): + allowed = string.letters + string.digits + "_" + name = "" + for char in title: + if char in allowed: + name = name + char + elif char == ' ': + name = name + '_' + return name + diff --git a/pynxc/waxy/messagedialog.py b/pynxc/waxy/messagedialog.py new file mode 100644 index 0000000..534878b --- /dev/null +++ b/pynxc/waxy/messagedialog.py @@ -0,0 +1,70 @@ +# messagedialog.py + +import wx +import waxyobject +import core + +class MessageDialog(wx.MessageDialog, waxyobject.WaxyObject): + """Displays a message dialog. Title, text, buttons (OK/Cancel/Yes/No), + and icon are configurable. + """ + + _icons = { + 'asterisk': wx.ICON_ASTERISK, + 'error': wx.ICON_ERROR, + 'exclamation': wx.ICON_EXCLAMATION, + 'hand': wx.ICON_HAND, + 'information': wx.ICON_INFORMATION, + 'mask': wx.ICON_MASK, + 'question': wx.ICON_QUESTION, + 'stop': wx.ICON_STOP, + 'warning': wx.ICON_WARNING, + } + + def __init__(self, parent, title="Message", text="A message", ok=0, + cancel=0, yes_no=0, icon=""): + style = 0 + if ok: style |= wx.OK + if cancel: style |= wx.CANCEL + if yes_no: style |= wx.YES_NO + + # set icon... some of these values show the same icon, at least on + # Windows. + icon = self._icons.get(icon.lower(), None) + if icon: + style |= icon + + # use a sensible default + if not (ok or cancel or yes_no): + style |= wx.OK + + wx.MessageDialog.__init__(self, parent, text, title, style) + + def ShowModal(self): + r = wx.MessageDialog.ShowModal(self) + return { + wx.ID_OK: 'ok', + wx.ID_CANCEL: 'cancel', + wx.ID_YES: 'yes', + wx.ID_NO: 'no', + }.get(r, "?") + + +def ShowMessage(title, text, icon=""): + """ Displays a message with an OK button. A bit like Delphi's ShowMessage + procedure. """ + parent = core.GetActiveWindow() + dlg = MessageDialog(parent, title, text, ok=1, icon=icon) + try: + dlg.ShowModal() + finally: + dlg.Destroy() + + +def Error(msg,parent=None): + + dlg = MessageDialog(parent, "Error", + msg,icon='error') + dlg.ShowModal() + dlg.Destroy() + diff --git a/pynxc/waxy/messagedialog.py~ b/pynxc/waxy/messagedialog.py~ new file mode 100644 index 0000000..896d33b --- /dev/null +++ b/pynxc/waxy/messagedialog.py~ @@ -0,0 +1,63 @@ +# messagedialog.py + +import wx +import waxyobject +import core + +class MessageDialog(wx.MessageDialog, waxyobject.WaxyObject): + """Displays a message dialog. Title, text, buttons (OK/Cancel/Yes/No), + and icon are configurable. + """ + + _icons = { + 'asterisk': wx.ICON_ASTERISK, + 'error': wx.ICON_ERROR, + 'exclamation': wx.ICON_EXCLAMATION, + 'hand': wx.ICON_HAND, + 'information': wx.ICON_INFORMATION, + 'mask': wx.ICON_MASK, + 'question': wx.ICON_QUESTION, + 'stop': wx.ICON_STOP, + 'warning': wx.ICON_WARNING, + } + + def __init__(self, parent, title="Message", text="A message", ok=0, + cancel=0, yes_no=0, icon=""): + style = 0 + if ok: style |= wx.OK + if cancel: style |= wx.CANCEL + if yes_no: style |= wx.YES_NO + + # set icon... some of these values show the same icon, at least on + # Windows. + icon = self._icons.get(icon.lower(), None) + if icon: + style |= icon + + # use a sensible default + if not (ok or cancel or yes_no): + style |= wx.OK + + wx.MessageDialog.__init__(self, parent, text, title, style) + self.SetDefaultFont() + + def ShowModal(self): + r = wx.MessageDialog.ShowModal(self) + return { + wx.ID_OK: 'ok', + wx.ID_CANCEL: 'cancel', + wx.ID_YES: 'yes', + wx.ID_NO: 'no', + }.get(r, "?") + + +def ShowMessage(title, text, icon=""): + """ Displays a message with an OK button. A bit like Delphi's ShowMessage + procedure. """ + parent = core.GetActiveWindow() + dlg = MessageDialog(parent, title, text, ok=1, icon=icon) + try: + dlg.ShowModal() + finally: + dlg.Destroy() + diff --git a/pynxc/waxy/mousepointer.py b/pynxc/waxy/mousepointer.py new file mode 100644 index 0000000..7809cc3 --- /dev/null +++ b/pynxc/waxy/mousepointer.py @@ -0,0 +1,95 @@ +# mousepointer.py + +# TODO: +# - remove code duplication in LoadImage/LoadStream + +import wx +import colordb +import os +import sys +import utils + +POINTERS = { + "arrow" : wx.CURSOR_ARROW, + "arrowright" : wx.CURSOR_RIGHT_ARROW, + "bullseye" : wx.CURSOR_BULLSEYE, + "char" : wx.CURSOR_CHAR, + "cross" : wx.CURSOR_CROSS, + "hand" : wx.CURSOR_HAND, + "ibeam" : wx.CURSOR_IBEAM, + "buttonleft" : wx.CURSOR_LEFT_BUTTON, + "magnifier" : wx.CURSOR_MAGNIFIER, + "buttonmiddle" : wx.CURSOR_MIDDLE_BUTTON, + "noentry" : wx.CURSOR_NO_ENTRY, + "paintbrush" : wx.CURSOR_PAINT_BRUSH, + "pencil" : wx.CURSOR_PENCIL, + "pointleft" : wx.CURSOR_POINT_LEFT, + "pointright" : wx.CURSOR_POINT_RIGHT, + "arrowquestion" : wx.CURSOR_QUESTION_ARROW, + "buttonright" : wx.CURSOR_RIGHT_BUTTON, + "sizenesw" : wx.CURSOR_SIZENESW, + "sizens" : wx.CURSOR_SIZENS, + "sizenwse" : wx.CURSOR_SIZENWSE, + "sizewe" : wx.CURSOR_SIZEWE, + "sizing" : wx.CURSOR_SIZING, + "spraycan" : wx.CURSOR_SPRAYCAN, + "wait" : wx.CURSOR_WAIT, + "watch" : wx.CURSOR_WATCH, + "blank" : wx.CURSOR_BLANK, + "default" : wx.CURSOR_DEFAULT, + "arrowcopy" : wx.CURSOR_COPY_ARROW, + "arrowwait" : wx.CURSOR_ARROWWAIT, + } + +class MousePointerRegistry: + def __init__(self): + self.custom = {} + def Get(self, name): + if POINTERS.has_key(name): + return wx.StockCursor(POINTERS[name]) # return a cursor + elif self.custom.has_key(name): + return self.custom[name] # return an image-as-cursor + else: + raise KeyError, "Unknown pointer name: %s" % (name,) + def Set(self, name, value): + self.custom[name] = value + Register = Set + def GetBuiltinNames(self): + return POINTERS.keys() + def GetCustomNames(self): + return self.custom.keys() + def GetNames(self): + return self.GetBuiltinNames() + self.GetCustomNames() + + def _RegisterImage(self, name, image, maskcolor='white', hotx=None, hoty=None): + """ Register a wx.Image as a cursor. """ + if sys.platform =='win32': + #cursors fixed size 32,32 + xratio = image.GetWidth() / 32 + yratio = image.GetHeight() / 32 + else: + xratio = yratio = 1 + if not image.HasMask(): + c = colordb.convert_color(maskcolor) + image.SetMaskColour(c[0], c[1], c[2]) + if not hotx: + hotx = image.GetWidth() / 2 + hotx = hotx / xratio + image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, hotx) + if not hoty: + hoty = image.GetHeight() / 2 + hoty = hoty / yratio + image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, hoty) + self.custom[name] = wx.CursorFromImage(image) + + def RegisterImage(self, name, filename, maskcolor='white', hotx=None, hoty=None): + i = wx.Image(utils.opj(filename), wx.BITMAP_TYPE_ANY) + self._RegisterImage(name, i, maskcolor, hotx, hoty) + + def RegisterStream(self, name, stream, maskcolor='white', hotx=None, hoty=None): + i = wx.ImageFromStream(stream) + self._RegisterImage(name, i, maskcolor, hotx, hoty) + + +# global registry +MousePointers = MousePointerRegistry() diff --git a/pynxc/waxy/multichoicedialog.py b/pynxc/waxy/multichoicedialog.py new file mode 100644 index 0000000..e0ec608 --- /dev/null +++ b/pynxc/waxy/multichoicedialog.py @@ -0,0 +1,29 @@ +import wx +import waxyobject +from font import Font + +# would be nice with a select all or something + +class MultiChoiceDialog(wx.MultiChoiceDialog, waxyobject.WaxyObject): + + def __init__(self, parent,lst,text='Choose',title='Multi Choice Dialog'): + wx.MultiChoiceDialog.__init__(self, parent,text,title,lst) + + self.lst=lst + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.MultiChoiceDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenItems(self): + selections = self.GetSelections() + strings = [self.lst[x] for x in selections] + + return strings + + + diff --git a/pynxc/waxy/multichoicedialog.py~ b/pynxc/waxy/multichoicedialog.py~ new file mode 100644 index 0000000..564e0fc --- /dev/null +++ b/pynxc/waxy/multichoicedialog.py~ @@ -0,0 +1,27 @@ +import wx +import waxyobject +from font import Font + +class MultiChoiceDialog(wx.MultiChoiceDialog, waxyobject.WaxyObject): + + def __init__(self, parent,lst,text='Choose',title='Multi Choice Dialog'): + wx.MultiChoiceDialog.__init__(self, parent,text,title,lst) + + self.lst=lst + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.MultiChoiceDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenItems(self): + selections = self.GetSelections() + strings = [self.lst[x] for x in selections] + + return strings + + + diff --git a/pynxc/waxy/notebook.py b/pynxc/waxy/notebook.py new file mode 100644 index 0000000..5ef5515 --- /dev/null +++ b/pynxc/waxy/notebook.py @@ -0,0 +1,51 @@ +# notebook.py + +import waxyobject +import wx +import styles +import utils + +class NoteBook(wx.Notebook, waxyobject.WaxyObject): + + __events__ = { + 'PageChanging': wx.EVT_NOTEBOOK_PAGE_CHANGING, + 'PageChanged': wx.EVT_NOTEBOOK_PAGE_CHANGED, + } + + def __init__(self, parent, size=(640,480), **kwargs): + + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + self.id = wx.NewId() + wx.Notebook.__init__(self, parent, self.id, style=style, size=size) + self.BindEvents() + styles.properties(self, kwargs) + +# def AddPage(self, window, *args, **kwargs): +# wx.Notebook.AddPage(self, window, *args, **kwargs) + + def GetCurrentPage(self): + idx = self.GetSelection() + if idx == -1: + raise ValueError, "NoteBook currently has no pages" + else: + return self.GetPage(idx) + + # + # style parameters + + _notebook_orientation = { + "left": wx.NB_LEFT, + "right": wx.NB_RIGHT, + "bottom": wx.NB_BOTTOM, + "top": 0, + } + + def _params(self, kwargs): + flags = 0 + flags |= styles.styledictstart('orientation', self._notebook_orientation, kwargs) + flags |= styles.stylebool('fixedwidth', wx.NB_FIXEDWIDTH, kwargs) + flags |= styles.stylebool('multiline', wx.NB_MULTILINE, kwargs) + return flags diff --git a/pynxc/waxy/notebook.py~ b/pynxc/waxy/notebook.py~ new file mode 100644 index 0000000..66024a0 --- /dev/null +++ b/pynxc/waxy/notebook.py~ @@ -0,0 +1,51 @@ +# notebook.py + +import waxyobject +import wx +import styles +import utils + +class NoteBook(wx.Notebook, waxyobject.WaxyObject): + + __events__ = { + 'PageChanging': wx.EVT_NOTEBOOK_PAGE_CHANGING, + 'PageChanged': wx.EVT_NOTEBOOK_PAGE_CHANGED, + } + + def __init__(self, parent, size=(640,480), **kwargs): + + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + self.id = wx.NewId() + wx.Notebook.__init__(self, parent, self.id, style=style, size=size) + self.BindEvents() + styles.properties(self, kwargs) + + def AddPage(self, window, *args, **kwargs): + wx.Notebook.AddPage(self, window, *args, **kwargs) + + def GetCurrentPage(self): + idx = self.GetSelection() + if idx == -1: + raise ValueError, "NoteBook currently has no pages" + else: + return self.GetPage(idx) + + # + # style parameters + + _notebook_orientation = { + "left": wx.NB_LEFT, + "right": wx.NB_RIGHT, + "bottom": wx.NB_BOTTOM, + "top": 0, + } + + def _params(self, kwargs): + flags = 0 + flags |= styles.styledictstart('orientation', self._notebook_orientation, kwargs) + flags |= styles.stylebool('fixedwidth', wx.NB_FIXEDWIDTH, kwargs) + flags |= styles.stylebool('multiline', wx.NB_MULTILINE, kwargs) + return flags diff --git a/pynxc/waxy/notes.txt b/pynxc/waxy/notes.txt new file mode 100644 index 0000000..bc6a7be --- /dev/null +++ b/pynxc/waxy/notes.txt @@ -0,0 +1,21 @@ +removing references to fonts +removed the autoinstall on the Image type (memory leak?) +added aboutbox +added colourdialog, and colordialog +added multichoicedialog +added singlechoicedialog + +code to look at: +canvas.py + + +demos to do: + +artprovider +bitmap +bitmapbutton +checkbox +checklistbox +combobox +customdialog +listbox diff --git a/pynxc/waxy/notes.txt~ b/pynxc/waxy/notes.txt~ new file mode 100644 index 0000000..df69f54 --- /dev/null +++ b/pynxc/waxy/notes.txt~ @@ -0,0 +1,20 @@ +removing references to fonts +removed the autoinstall on the Image type (memory leak?) +added aboutbox +added colourdialog, and colordialog +added multichoicedialog +added singlechoicedialog + +code to look at: +canvas.py + + +demos to do: + +artprovider +bitmap +bitmapbutton +checkbox +checklistbox +combobox +customdialog diff --git a/pynxc/waxy/panel.py b/pynxc/waxy/panel.py new file mode 100644 index 0000000..a4222cb --- /dev/null +++ b/pynxc/waxy/panel.py @@ -0,0 +1,27 @@ +# panel.py + +import wx +import containers +import styles + +class Panel(wx.Panel, containers.Container): + """ Sub-level containers inside a frame, used for layout. """ + def __init__(self, parent, direction="H", size=None, **kwargs): + style = 0 + style |= styles.window(kwargs) + wx.Panel.__init__(self, parent, wx.NewId(), size=size or (-1,-1), + style=style) + + self.BindEvents() + self._create_sizer(direction) + styles.properties(self, kwargs) + self.Body() + +class HorizontalPanel(Panel): + def __init__(self, parent, **kwargs): + Panel.__init__(self, parent, direction='h', **kwargs) + +class VerticalPanel(Panel): + def __init__(self, parent, **kwargs): + Panel.__init__(self, parent, direction='v', **kwargs) + diff --git a/pynxc/waxy/panel.py~ b/pynxc/waxy/panel.py~ new file mode 100644 index 0000000..c6992fa --- /dev/null +++ b/pynxc/waxy/panel.py~ @@ -0,0 +1,28 @@ +# panel.py + +import wx +import containers +import styles + +class Panel(wx.Panel, containers.Container): + """ Sub-level containers inside a frame, used for layout. """ + def __init__(self, parent, direction="H", size=None, **kwargs): + style = 0 + style |= styles.window(kwargs) + wx.Panel.__init__(self, parent, wx.NewId(), size=size or (-1,-1), + style=style) + + self.BindEvents() + self._create_sizer(direction) + self.SetDefaultFont() + styles.properties(self, kwargs) + self.Body() + +class HorizontalPanel(Panel): + def __init__(self, parent, **kwargs): + Panel.__init__(self, parent, direction='h', **kwargs) + +class VerticalPanel(Panel): + def __init__(self, parent, **kwargs): + Panel.__init__(self, parent, direction='v', **kwargs) + diff --git a/pynxc/waxy/progressdialog.py b/pynxc/waxy/progressdialog.py new file mode 100644 index 0000000..e43f96e --- /dev/null +++ b/pynxc/waxy/progressdialog.py @@ -0,0 +1,28 @@ +# progressdialog.py + +import wx +import waxyobject + +class ProgressDialog(wx.ProgressDialog, waxyobject.WaxyObject): + + def __init__(self,parent=None,title="Progress", message="Progress", + maximum=100,abort=1,modal=1,show_elapsed_time=1,show_remaining_time=1): + style = 0 + if abort: + style |= wx.PD_CAN_ABORT + if modal: + style |= wx.PD_APP_MODAL + if show_elapsed_time: + style |= wx.PD_ELAPSED_TIME + if show_remaining_time: + style |= wx.PD_REMAINING_TIME + wx.ProgressDialog.__init__(self, title, message, + maximum, parent,style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.ProgressDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' diff --git a/pynxc/waxy/progressdialog.py~ b/pynxc/waxy/progressdialog.py~ new file mode 100644 index 0000000..17f44a5 --- /dev/null +++ b/pynxc/waxy/progressdialog.py~ @@ -0,0 +1,28 @@ +# progressdialog.py + +import wx +import waxyobject + +class ProgressDialog(wx.ProgressDialog, waxyobject.WaxyObject): + + def __init__(self,parent=None,title="Progress", message="Progress", + maximum=100,abort=1,modal=1,show_elapsed_time=1,show_remaining_time=1): + style = 0 + if abort: + style |= wx.PD_CAN_ABORT + if modal: + style |= wx.PD_APP_MODAL + if elapsed: + style |= wx.PD_ELAPSED_TIME + if remaining: + style |= wx.PD_REMAINING_TIME + wx.ProgressDialog.__init__(self, title, message, + maximum, parent,style) + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.ProgressDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' diff --git a/pynxc/waxy/singlechoicedialog.py b/pynxc/waxy/singlechoicedialog.py new file mode 100644 index 0000000..e6dffdc --- /dev/null +++ b/pynxc/waxy/singlechoicedialog.py @@ -0,0 +1,29 @@ +import wx +import waxyobject +from font import Font + +# would be nice with a select all or something + +class SingleChoiceDialog(wx.SingleChoiceDialog, waxyobject.WaxyObject): + + def __init__(self, parent,lst,text='Choose',title='Single Choice Dialog'): + wx.SingleChoiceDialog.__init__(self, parent,text,title,lst) + + self.lst=lst + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.SingleChoiceDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenItem(self): + s = self.GetStringSelection() + + + return s + + + diff --git a/pynxc/waxy/singlechoicedialog.py~ b/pynxc/waxy/singlechoicedialog.py~ new file mode 100644 index 0000000..2941dbc --- /dev/null +++ b/pynxc/waxy/singlechoicedialog.py~ @@ -0,0 +1,29 @@ +import wx +import waxyobject +from font import Font + +# would be nice with a select all or something + +class SingleChoiceDialog(wx.SingleChoiceDialog, waxyobject.WaxyObject): + + def __init__(self, parent,lst,text='Choose',title='Single Choice Dialog'): + wx.SingleChoiceDialog.__init__(self, parent,text,title,lst) + + self.lst=lst + + def ShowModal(self): + """ Simplified ShowModal(), returning strings 'ok' or 'cancel'. """ + result = wx.SingleChoiceDialog.ShowModal(self) + if result == wx.ID_OK: + return 'ok' + else: + return 'cancel' + + def GetChosenItems(self): + selections = self.GetSelections() + strings = [self.lst[x] for x in selections] + + return strings + + + diff --git a/pynxc/waxy/slider.py b/pynxc/waxy/slider.py new file mode 100644 index 0000000..1f70e64 --- /dev/null +++ b/pynxc/waxy/slider.py @@ -0,0 +1,104 @@ +# slider.py + +import wx +import containers +import waxyobject +import styles +from panel import Panel +from label import Label + +class Slider(wx.Slider, waxyobject.WaxyObject): + __events__ = { + 'Scroll': wx.EVT_SCROLL, + } + + def __init__(self, parent, tickfreq=5, min=0, max=100, event=None, size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.Slider.__init__(self, parent, wx.NewId(), size=size or (-1,-1), style=style) + self.SetTickFreq(tickfreq) + self.SetRange(min, max) + + self.BindEvents() + if event: + self.OnScroll = event + styles.properties(self, kwargs) + + # + # style parameters + + __styles__ = { + 'labels': (wx.SL_LABELS, styles.NORMAL), + 'ticks': ({ + "left": wx.SL_LEFT | wx.SL_AUTOTICKS, + "right": wx.SL_RIGHT | wx.SL_AUTOTICKS, + "top": wx.SL_TOP | wx.SL_AUTOTICKS, + "bottom": wx.SL_BOTTOM | wx.SL_AUTOTICKS, + }, styles.DICTSTART), + 'orientation': ({ + "horizontal": wx.SL_HORIZONTAL, + "vertical": wx.SL_VERTICAL, + }, styles.DICTSTART), + } + + +class FloatSlider(Panel): + + def __init__(self, parent, tickfreq=0.5, min=-5.0, max=5.0, format='%.1f',event=None, size=None, **kwargs): + + if 'labels' in kwargs: + labels=kwargs['labels'] + kwargs['labels']=False + + Panel.__init__(self,parent,direction='v') + + + intmin=0 + intmax=int(float(max-min)/tickfreq) + inttickfreq=1 + + self.min=min + self.max=max + self.tickfreq=tickfreq + self.format=format + + self.slider=Slider(self, inttickfreq,intmin,intmax,event,size,**kwargs) + self.slider.SetValue(self.slider.GetMax()/2) + self.slider.OnScroll=self.OnScroll + self.AddComponent(self.slider,stretch=True,border=10) + + if labels: + p=Panel(self,direction='h') + self.text1=Label(p,self.format % self.min,align='left') + self.text2=Label(p,self.format % self.max,align='right') + self.text3=Label(p,self.format % self.GetValue(),align='center') + p.AddComponent(self.text1,expand=True,border=3) + p.AddComponent(self.text3,expand=False,border=3) + p.AddComponent(self.text2,expand=True,border=3) + p.Pack() + + self.AddComponent(p,stretch=True) + + + + self.Pack() + + def OnScroll(self,event): + self.text3.SetLabel(self.format % self.GetValue()) + self.text3.SetExtraStyle(wx.ALIGN_CENTER) + self.OnUpdate() + + def OnUpdate(self): + pass + + def GetValue(self): + + intval=float(self.slider.GetValue()) + intmax=float(self.slider.GetMax()) + + val=(intval*self.tickfreq)+self.min + + return val + diff --git a/pynxc/waxy/splitter.py b/pynxc/waxy/splitter.py new file mode 100644 index 0000000..4afcb4b --- /dev/null +++ b/pynxc/waxy/splitter.py @@ -0,0 +1,56 @@ +# splitter.py + +import wx +import waxyobject +import styles +import utils + +class Splitter(wx.SplitterWindow, waxyobject.WaxyObject): + + __events__ = { + 'SashPosChanging': wx.EVT_SPLITTER_SASH_POS_CHANGING, + 'SashPosChanged': wx.EVT_SPLITTER_SASH_POS_CHANGED, + 'Unsplit': wx.EVT_SPLITTER_UNSPLIT, + 'DoubleClick': wx.EVT_SPLITTER_DCLICK, + } + + def __init__(self, parent, size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + wx.SplitterWindow.__init__(self, parent, wx.NewId(), style=style) + + if size: + self.SetSize(size) + + self.BindEvents() + styles.properties(self, kwargs) + + # I would have liked to add the windows to the constructor, but it's + # not possible because the Splitter needs to be present as the + # windows' parent... hmm... + + def Split(self, window1, window2, direction="horizontal", sashposition=100, + minsize=20): + + if direction.lower().startswith("h"): + self.SplitHorizontally(window1, window2, sashposition) + elif direction.lower().startswith("v"): + self.SplitVertically(window1, window2, sashposition) + else: + raise ValueError, "direction must be horizontal or vertical" + + self.SetMinimumPaneSize(minsize) + + # + # style parameters + + def _params(self, kwargs): + flags = 0 + flags |= styles.stylebool('permit_unsplit', wx.SP_PERMIT_UNSPLIT, kwargs) + flags |= styles.stylebool('live_update', wx.SP_LIVE_UPDATE, kwargs) + flags |= styles.stylebool('no_xp_theme', wx.SP_NO_XP_THEME, kwargs) + flags |= styles.stylebool('border', wx.SP_BORDER, kwargs) + flags |= styles.stylebool('sash3d', wx.SP_3DSASH, kwargs) + flags |= styles.stylebool('all3d', wx.SP_3D, kwargs) + return flags diff --git a/pynxc/waxy/splitter.py~ b/pynxc/waxy/splitter.py~ new file mode 100644 index 0000000..e1fac80 --- /dev/null +++ b/pynxc/waxy/splitter.py~ @@ -0,0 +1,62 @@ +# splitter.py + +import wx +import waxyobject +import styles +import utils + +class Splitter(wx.SplitterWindow, waxyobject.WaxyObject): + + __events__ = { + 'SashPosChanging': wx.EVT_SPLITTER_SASH_POS_CHANGING, + 'SashPosChanged': wx.EVT_SPLITTER_SASH_POS_CHANGED, + 'Unsplit': wx.EVT_SPLITTER_UNSPLIT, + 'DoubleClick': wx.EVT_SPLITTER_DCLICK, + } + + def __init__(self, parent, size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + wx.SplitterWindow.__init__(self, parent, wx.NewId(), style=style) + + if size: + self.SetSize(size) + + self.BindEvents() + styles.properties(self, kwargs) + + # I would have liked to add the windows to the constructor, but it's + # not possible because the Splitter needs to be present as the + # windows' parent... hmm... + + def Split(self, window1, window2, direction="horizontal", sashposition=100, + minsize=20): + # check parents + if waxconfig.WaxConfig.check_parent: + if window1.GetParent() is not self: + utils.parent_warning(window1, self) + if window2.GetParent() is not self: + utils.parent_warning(window2, self) + + if direction.lower().startswith("h"): + self.SplitHorizontally(window1, window2, sashposition) + elif direction.lower().startswith("v"): + self.SplitVertically(window1, window2, sashposition) + else: + raise ValueError, "direction must be horizontal or vertical" + + self.SetMinimumPaneSize(minsize) + + # + # style parameters + + def _params(self, kwargs): + flags = 0 + flags |= styles.stylebool('permit_unsplit', wx.SP_PERMIT_UNSPLIT, kwargs) + flags |= styles.stylebool('live_update', wx.SP_LIVE_UPDATE, kwargs) + flags |= styles.stylebool('no_xp_theme', wx.SP_NO_XP_THEME, kwargs) + flags |= styles.stylebool('border', wx.SP_BORDER, kwargs) + flags |= styles.stylebool('sash3d', wx.SP_3DSASH, kwargs) + flags |= styles.stylebool('all3d', wx.SP_3D, kwargs) + return flags diff --git a/pynxc/waxy/statusbar.py b/pynxc/waxy/statusbar.py new file mode 100644 index 0000000..ba9643c --- /dev/null +++ b/pynxc/waxy/statusbar.py @@ -0,0 +1,37 @@ +# statusbar.py + +import wx +import waxyobject +import styles + +class StatusBar(wx.StatusBar, waxyobject.WaxyObject): + + def __init__(self, parent, numpanels=1, add=1, **kwargs): + # note: does not support the 'size' parameter + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.StatusBar.__init__(self, parent, wx.NewId(), style=style) + +# self.SetDefaultFont() + self.SetFieldsCount(numpanels) + if add: + parent.SetStatusBar(self) + + self.BindEvents() + styles.properties(self, kwargs) + + + # allows for: statusbar[0] = "text" + def __setitem__(self, index, text): + self.SetStatusText(text, index) + + # + # style parameters + + def _params(self, kwargs): + flags = 0 + flags |= styles.stylebool('sizegrip', wx.ST_SIZEGRIP, kwargs) + return flags + diff --git a/pynxc/waxy/styles.py b/pynxc/waxy/styles.py new file mode 100644 index 0000000..d89b0f2 --- /dev/null +++ b/pynxc/waxy/styles.py @@ -0,0 +1,160 @@ +# styles.py + +import wx + + +NORMAL = 0 +EXCLUDE = 1 +DICT = 2 +DICTSTART = 3 +REVERSE = 32 + + +def styledict(name, dict, kwargs, default=0): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + try: + value = value.lower() + except AttributeError: + pass + flags |= dict.get(value, default) + del kwargs[name] + return flags + +def styledictstart(name, dict, kwargs, default=0): + """ Like styledict, but matches the first letter(s) rather than the + complete value. For example, if "lower" is the only key in the dict + starting with "l", then by passing the value "l" we match "lower". + Used e.g. in _button_align. + """ + flags = 0 + if kwargs.has_key(name): + value = kwargs[name].lower() + # note that we traverse the dict pair by pair, so ambiguous matches + # *are* possible + for key, flag in dict.items(): + if key.startswith(value): + flags |= flag + break + else: + flags |= default + del kwargs[name] + return flags + +def stylebool(name, flag, kwargs, reverse=0): + """ If <name> is in kwargs and is true, then return <flag>. + If <reverse> is set, then the condition needs to be false in order + for the flag to be returned. + (E.g. stylebool('lines', wx.BLAH_NOLINES, kwargs, reverse=1) + will return wx.BLAH_NOLINES if lines==0, not if lines==1.) + """ + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if reverse: + value = not value + if value: + flags |= flag + del kwargs[name] + return flags + +def styleboolexclude(name, flag, kwargs, reverse=0): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if reverse: + value = not value + if value: + flags |= flag + del kwargs[name] + return flags + +def stylebooleither(name, flagtrue, flagfalse, kwargs): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if value: + flags |= flagtrue + else: + flags |= flagfalse + del kwargs[name] + return flags + +# not sure if this can be used... +def stylefunc(name, func, kwargs): + if kwargs.has_key(name): + value = kwargs[name] + func(value) + del kwargs[value] + return 0 + +# +# +# +def dostyle(styledict, kwargs): + """ Set styles for a given control, using a "style dict". Return the + eventual flag value. Mostly for internal use. """ + flags = 0 + for k, (style, type) in styledict.items(): + #style, type = styledict[k] + # First check for reversing + reverse = 0 + if (type & REVERSE) == REVERSE: + reverse = 1 + # Get everything but the `reverse` bits + type = type & (reverse - 1) + # Now see what we're dealing with + if type == NORMAL: + flags |= stylebool(k, style, kwargs, reverse=reverse) + elif type == DICT: + flags |= styledict(k, style, kwargs) + elif type == DICTSTART: + flags |= styledictstart(k, style, kwargs) + elif type == EXCLUDE: + flags &= ~styleboolexclude(k, style, kwargs, reverse=reverse) + + return flags +# +# the following functions do not handle flags + +def properties(obj, kwargs): + """ Called by constructors to set properties from a dict. Must be called + *after* the parent's constructor (unlike most of the other styles + functions). """ + if kwargs.has_key('properties'): + d = kwargs['properties'] + for key, value in d.items(): + setattr(obj, key, value) # attempt to set property + del kwargs['properties'] + + # attempt to set the remaining attributes as properties (this will raise + # an error if an invalid property name is specified). + obj.SetProperties(**kwargs) + + # XXX could be a method in WaxyObject... if it doesn't already exist? + + +# +# window styles + +_window_border = { + "simple": wx.SIMPLE_BORDER, + "double": wx.DOUBLE_BORDER, + "sunken": wx.SUNKEN_BORDER, + "raised": wx.RAISED_BORDER, + "static": wx.STATIC_BORDER, + "no": wx.NO_BORDER, + "none": wx.NO_BORDER, +} + +def window(kwargs): + """ Styles applicable to any wx.Window descendant. """ + flags = 0 + flags |= styledict('border', _window_border, kwargs) + flags |= stylebool('transparent', wx.TRANSPARENT_WINDOW, kwargs) + flags |= stylebool('tab_traversal', wx.TAB_TRAVERSAL, kwargs) + flags |= stylebool('wants_chars', wx.WANTS_CHARS, kwargs) + + return flags + diff --git a/pynxc/waxy/styles.py~ b/pynxc/waxy/styles.py~ new file mode 100644 index 0000000..ed39f77 --- /dev/null +++ b/pynxc/waxy/styles.py~ @@ -0,0 +1,160 @@ +# styles.py + +import wx + + +NORMAL = 0 +EXCLUDE = 1 +DICT = 2 +DICTSTART = 3 +REVERSE = 32 + + +def styledict(name, dict, kwargs, default=0): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + try: + value = value.lower() + except AttributeError: + pass + flags |= dict.get(value, default) + del kwargs[name] + return flags + +def styledictstart(name, dict, kwargs, default=0): + """ Like styledict, but matches the first letter(s) rather than the + complete value. For example, if "lower" is the only key in the dict + starting with "l", then by passing the value "l" we match "lower". + Used e.g. in _button_align. + """ + flags = 0 + if kwargs.has_key(name): + value = kwargs[name].lower() + # note that we traverse the dict pair by pair, so ambiguous matches + # *are* possible + for key, flag in dict.items(): + if key.startswith(value): + flags |= flag + break + else: + flags |= default + del kwargs[name] + return flags + +def stylebool(name, flag, kwargs, reverse=0): + """ If <name> is in kwargs and is true, then return <flag>. + If <reverse> is set, then the condition needs to be false in order + for the flag to be returned. + (E.g. stylebool('lines', wx.BLAH_NOLINES, kwargs, reverse=1) + will return wx.BLAH_NOLINES if lines==0, not if lines==1.) + """ + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if reverse: + value = not value + if value: + flags |= flag + del kwargs[name] + return flags + +def styleboolexclude(name, flag, kwargs, reverse=0): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if reverse: + value = not value + if value: + flags |= flag + del kwargs[name] + return flags + +def stylebooleither(name, flagtrue, flagfalse, kwargs): + flags = 0 + if kwargs.has_key(name): + value = kwargs[name] + if value: + flags |= flagtrue + else: + flags |= flagfalse + del kwargs[name] + return flags + +# not sure if this can be used... +def stylefunc(name, func, kwargs): + if kwargs.has_key(name): + value = kwargs[name] + func(value) + del kwargs[value] + return 0 + +# +# +# +def dostyle(styledict, kwargs): + """ Set styles for a given control, using a "style dict". Return the + eventual flag value. Mostly for internal use. """ + flags = 0 + for k, (style, type) in styledict.items(): + #style, type = styledict[k] + # First check for reversing + reverse = 0 + if (type & REVERSE) == REVERSE: + reverse = 1 + # Get everything but the `reverse` bits + type = type & (reverse - 1) + # Now see what we're dealing with + if type == NORMAL: + flags |= stylebool(k, style, kwargs, reverse=reverse) + elif type == DICT: + flags |= styledict(k, style, kwargs) + elif type == DICTSTART: + flags |= styledictstart(k, style, kwargs) + elif type == EXCLUDE: + flags &= ~styleboolexclude(k, style, kwargs, reverse=reverse) + + return flags +# +# the following functions do not handle flags + +def properties(obj, kwargs): + """ Called by constructors to set properties from a dict. Must be called + *after* the parent's constructor (unlike most of the other styles + functions). """ + if kwargs.has_key('properties'): + d = kwargs['properties'] + for key, value in d.items(): + setattr(obj, key, value) # attempt to set property + del kwargs['properties'] + + # attempt to set the remaining attributes as properties (this will raise + # an error if an invalid property name is specified). + obj.SetProperties(**kwargs) + + # XXX could be a method in WaxObject... if it doesn't already exist? + + +# +# window styles + +_window_border = { + "simple": wx.SIMPLE_BORDER, + "double": wx.DOUBLE_BORDER, + "sunken": wx.SUNKEN_BORDER, + "raised": wx.RAISED_BORDER, + "static": wx.STATIC_BORDER, + "no": wx.NO_BORDER, + "none": wx.NO_BORDER, +} + +def window(kwargs): + """ Styles applicable to any wx.Window descendant. """ + flags = 0 + flags |= styledict('border', _window_border, kwargs) + flags |= stylebool('transparent', wx.TRANSPARENT_WINDOW, kwargs) + flags |= stylebool('tab_traversal', wx.TAB_TRAVERSAL, kwargs) + flags |= stylebool('wants_chars', wx.WANTS_CHARS, kwargs) + + return flags + diff --git a/pynxc/waxy/textbox.py b/pynxc/waxy/textbox.py new file mode 100644 index 0000000..7595b5a --- /dev/null +++ b/pynxc/waxy/textbox.py @@ -0,0 +1,128 @@ +# textbox.py
+
+import waxyobject
+import wx
+import core
+import styles
+
+class TextBox(wx.TextCtrl, waxyobject.WaxyObject):
+
+ __events__ = {
+ 'Char': wx.EVT_CHAR, # do all controls have this?
+ 'MaxLength': wx.EVT_TEXT_MAXLEN, # alias for TextMaxLen
+ 'Text': wx.EVT_TEXT,
+ 'TextEnter': wx.EVT_TEXT_ENTER,
+ 'TextMaxLen': wx.EVT_TEXT_MAXLEN,
+ 'TextURL': wx.EVT_TEXT_URL,
+ }
+
+ def __init__(self, parent, text="", size=None, **kwargs):
+ style = 0
+ style |= self._params(kwargs)
+ style |= styles.window(kwargs)
+
+ wx.TextCtrl.__init__(self, parent, wx.NewId(), text,
+ size=size or (125,-1), style=style)
+
+ self.BindEvents()
+ styles.properties(self, kwargs)
+
+ def write(self, s):
+ # Added so we can use a TextBox as a file-like object and redirect
+ # stdout to it.
+ self.AppendText(s)
+ try:
+ core.Yield()
+ except:
+ pass
+
+ def GetCurrentLineNumber(self):
+ """ Return the current line number (i.e. the number of the line the
+ cursor is on). """
+ pos = self.GetInsertionPoint()
+ x, y = self.PositionToXY(pos)
+ return y
+
+ def GetLines(self):
+ """ Return the current text as a list of lines. (Changing the list
+ does not affect the contents of the TextBox.) """
+ text = self.GetValue()
+ lines = text.split("\n")
+ return lines
+
+ def SetModified(self, modified):
+ if modified:
+ # set to modified by appending a dummy space and removing it again
+ self.AppendText(' ')
+ lastpos = self.GetLastPosition()
+ self.Remove(lastpos-1, lastpos)
+ else:
+ self.DiscardEdits()
+
+ def GetModified(self):
+ """ Returns true if the contents of the control were modified. (Alias
+ for IsModified(). """
+ return self.IsModified()
+
+ def InsertText(self, pos, text):
+ """ Insert text at the given position. """
+ old_insertion_point = self.GetInsertionPoint()
+ self.SetInsertionPoint(pos)
+ self.WriteText(text)
+ # put cursor at original insertion point
+ if old_insertion_point <= pos:
+ self.SetInsertionPoint(old_insertion_point)
+ else:
+ self.SetInsertionPoint(old_insertion_point + len(text))
+
+ # ideas:
+ # should Remove support negative indexes? (like slices)
+ # should it support slicing? e.g. del atextbox[10:20]
+
+ #
+ # style parameters
+
+ #_textbox_justify = {
+ # "left": wx.TE_LEFT,
+ # "center": wx.TE_CENTRE,
+ # "centre": wx.TE_CENTRE,
+ # "middle": wx.TE_CENTRE,
+ # "right": wx.TE_RIGHT,
+ #}
+
+ __styles__ = {
+ 'justify': ({
+ 'left': wx.TE_LEFT,
+ 'center': wx.TE_CENTRE,
+ 'centre': wx.TE_CENTRE,
+ 'middle': wx.TE_CENTRE,
+ 'right': wx.TE_RIGHT,
+ }, styles.DICTSTART),
+ 'multiline': (wx.TE_MULTILINE, styles.NORMAL),
+ 'password': (wx.TE_PASSWORD, styles.NORMAL),
+ 'readonly': (wx.TE_READONLY, styles.NORMAL),
+ 'wrap': (wx.TE_DONTWRAP, styles.NORMAL | styles.REVERSE),
+ 'process_enter': (wx.TE_PROCESS_ENTER, styles.NORMAL),
+ 'process_tab': (wx.TE_PROCESS_TAB, styles.NORMAL),
+ 'rich': (wx.TE_RICH, styles.NORMAL),
+ 'rich2': (wx.TE_RICH2, styles.NORMAL),
+ 'auto_url': (wx.TE_AUTO_URL, styles.NORMAL),
+ 'hscroll': (wx.HSCROLL, styles.NORMAL),
+ }
+
+ def _params(self, kwargs):
+ flags = 0 | wx.TE_NOHIDESEL # maybe add the option of changing this one
+ #flags |= styles.stylebool('multiline', wx.TE_MULTILINE, kwargs)
+ #flags |= styles.stylebool('password', wx.TE_PASSWORD, kwargs)
+ #flags |= styles.stylebool('readonly', wx.TE_READONLY, kwargs)
+ #flags |= styles.stylebool('wrap', wx.TE_DONTWRAP, kwargs, reverse=1)
+ #flags |= styles.stylebool('process_enter', wx.TE_PROCESS_ENTER, kwargs)
+ #flags |= styles.stylebool('process_tab', wx.TE_PROCESS_TAB, kwargs)
+ #flags |= styles.stylebool('rich', wx.TE_RICH, kwargs)
+ #flags |= styles.stylebool('rich2', wx.TE_RICH2, kwargs)
+ #flags |= styles.stylebool('auto_url', wx.TE_AUTO_URL, kwargs)
+ #flags |= styles.stylebool('hscroll', wx.HSCROLL, kwargs)
+ #flags |= styles.styledictstart('justify', self._textbox_justify, kwargs, 0)
+ flags |= styles.dostyle(self.__styles__, kwargs)
+ return flags
+
diff --git a/pynxc/waxy/textbox.py~ b/pynxc/waxy/textbox.py~ new file mode 100644 index 0000000..88d42b4 --- /dev/null +++ b/pynxc/waxy/textbox.py~ @@ -0,0 +1,128 @@ +# textbox.py
+
+import waxyobject
+import wx
+import core
+import styles
+
+class TextBox(wx.TextCtrl, waxyobject.WaxObject):
+
+ __events__ = {
+ 'Char': wx.EVT_CHAR, # do all controls have this?
+ 'MaxLength': wx.EVT_TEXT_MAXLEN, # alias for TextMaxLen
+ 'Text': wx.EVT_TEXT,
+ 'TextEnter': wx.EVT_TEXT_ENTER,
+ 'TextMaxLen': wx.EVT_TEXT_MAXLEN,
+ 'TextURL': wx.EVT_TEXT_URL,
+ }
+
+ def __init__(self, parent, text="", size=None, **kwargs):
+ style = 0
+ style |= self._params(kwargs)
+ style |= styles.window(kwargs)
+
+ wx.TextCtrl.__init__(self, parent, wx.NewId(), text,
+ size=size or (125,-1), style=style)
+
+ self.BindEvents()
+ styles.properties(self, kwargs)
+
+ def write(self, s):
+ # Added so we can use a TextBox as a file-like object and redirect
+ # stdout to it.
+ self.AppendText(s)
+ try:
+ core.Yield()
+ except:
+ pass
+
+ def GetCurrentLineNumber(self):
+ """ Return the current line number (i.e. the number of the line the
+ cursor is on). """
+ pos = self.GetInsertionPoint()
+ x, y = self.PositionToXY(pos)
+ return y
+
+ def GetLines(self):
+ """ Return the current text as a list of lines. (Changing the list
+ does not affect the contents of the TextBox.) """
+ text = self.GetValue()
+ lines = text.split("\n")
+ return lines
+
+ def SetModified(self, modified):
+ if modified:
+ # set to modified by appending a dummy space and removing it again
+ self.AppendText(' ')
+ lastpos = self.GetLastPosition()
+ self.Remove(lastpos-1, lastpos)
+ else:
+ self.DiscardEdits()
+
+ def GetModified(self):
+ """ Returns true if the contents of the control were modified. (Alias
+ for IsModified(). """
+ return self.IsModified()
+
+ def InsertText(self, pos, text):
+ """ Insert text at the given position. """
+ old_insertion_point = self.GetInsertionPoint()
+ self.SetInsertionPoint(pos)
+ self.WriteText(text)
+ # put cursor at original insertion point
+ if old_insertion_point <= pos:
+ self.SetInsertionPoint(old_insertion_point)
+ else:
+ self.SetInsertionPoint(old_insertion_point + len(text))
+
+ # ideas:
+ # should Remove support negative indexes? (like slices)
+ # should it support slicing? e.g. del atextbox[10:20]
+
+ #
+ # style parameters
+
+ #_textbox_justify = {
+ # "left": wx.TE_LEFT,
+ # "center": wx.TE_CENTRE,
+ # "centre": wx.TE_CENTRE,
+ # "middle": wx.TE_CENTRE,
+ # "right": wx.TE_RIGHT,
+ #}
+
+ __styles__ = {
+ 'justify': ({
+ 'left': wx.TE_LEFT,
+ 'center': wx.TE_CENTRE,
+ 'centre': wx.TE_CENTRE,
+ 'middle': wx.TE_CENTRE,
+ 'right': wx.TE_RIGHT,
+ }, styles.DICTSTART),
+ 'multiline': (wx.TE_MULTILINE, styles.NORMAL),
+ 'password': (wx.TE_PASSWORD, styles.NORMAL),
+ 'readonly': (wx.TE_READONLY, styles.NORMAL),
+ 'wrap': (wx.TE_DONTWRAP, styles.NORMAL | styles.REVERSE),
+ 'process_enter': (wx.TE_PROCESS_ENTER, styles.NORMAL),
+ 'process_tab': (wx.TE_PROCESS_TAB, styles.NORMAL),
+ 'rich': (wx.TE_RICH, styles.NORMAL),
+ 'rich2': (wx.TE_RICH2, styles.NORMAL),
+ 'auto_url': (wx.TE_AUTO_URL, styles.NORMAL),
+ 'hscroll': (wx.HSCROLL, styles.NORMAL),
+ }
+
+ def _params(self, kwargs):
+ flags = 0 | wx.TE_NOHIDESEL # maybe add the option of changing this one
+ #flags |= styles.stylebool('multiline', wx.TE_MULTILINE, kwargs)
+ #flags |= styles.stylebool('password', wx.TE_PASSWORD, kwargs)
+ #flags |= styles.stylebool('readonly', wx.TE_READONLY, kwargs)
+ #flags |= styles.stylebool('wrap', wx.TE_DONTWRAP, kwargs, reverse=1)
+ #flags |= styles.stylebool('process_enter', wx.TE_PROCESS_ENTER, kwargs)
+ #flags |= styles.stylebool('process_tab', wx.TE_PROCESS_TAB, kwargs)
+ #flags |= styles.stylebool('rich', wx.TE_RICH, kwargs)
+ #flags |= styles.stylebool('rich2', wx.TE_RICH2, kwargs)
+ #flags |= styles.stylebool('auto_url', wx.TE_AUTO_URL, kwargs)
+ #flags |= styles.stylebool('hscroll', wx.HSCROLL, kwargs)
+ #flags |= styles.styledictstart('justify', self._textbox_justify, kwargs, 0)
+ flags |= styles.dostyle(self.__styles__, kwargs)
+ return flags
+
diff --git a/pynxc/waxy/textentrydialog.py b/pynxc/waxy/textentrydialog.py new file mode 100644 index 0000000..afe31ca --- /dev/null +++ b/pynxc/waxy/textentrydialog.py @@ -0,0 +1,179 @@ +# textentrydialog.py +# Simple dialog for entering a string. +# Note: Not based on wxPython's TextEntryDialog. + +from dialog import Dialog +from textbox import TextBox +from label import Label +from keys import keys +import string + +class TextEntryDialog(Dialog): + + def __init__(self, parent, title="Enter some text", prompt="Enter some text", + default="", cancel_button=1): + self.prompt = prompt + self.default = default + Dialog.__init__(self, parent, title, cancel_button=cancel_button) + + def Body(self): + label = Label(self, self.prompt) + self.AddComponent(label, expand='h', border=7) + + self.text = TextBox(self, size=(100,25), process_enter=1) + self.text.SetValue(self.default) + self.text.OnChar = self.OnTextBoxChar + self.AddComponent(self.text, expand='h', border=5) + + def OnTextBoxChar(self, event=None): + # pressing Enter in the TextBox is the same as clicking OK + if event.GetKeyCode() == keys.enter: + self.OnClickOKButton(event) + else: + event.Skip() + + def GetValue(self): + return self.text.GetValue() + + + + +class IntegerInputDialog(TextEntryDialog): + + def __init__(self, parent, title='Enter some text', + prompt='Enter some text', default='', cancel_button=1): + + TextEntryDialog.__init__(self, parent, title=title, + prompt=prompt, default=str(default), + cancel_button=cancel_button) + + + def GetValue(self): + + try: + val=TextEntryDialog.GetValue(self) + except ValueError: + return None + + try: + int_val=eval("int("+val+")") + except (SyntaxError,NameError): + int_val=None + + return int_val + + + def OnCharHook(self, event): + key = event.KeyCode() + + if key == wx.WXK_ESCAPE: + self.OnClickCancelButton() + + if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255: + event.Skip() + return + + + good_chars=string.digits+'+*-()' + if chr(key) in good_chars: + event.Skip() + return + + if not wx.Validator_IsSilent(): + wx.Bell() + + # Returning without calling even.Skip eats the event before it + # gets to the text control + return + + + + def Validate(self): + val = TextEntryDialog.GetValue(self) # make sure the get a string + + good_chars=string.digits+'+*-()' + for x in val: + if x not in good_chars: + return False + + try: + int_val=eval("int("+val+")") + except (SyntaxError,NameError): + Error("Syntax Error") + return False + + return True + + +def Input_Integer(title, + prompt, default=None,parent=None): + + + a=IntegerInputDialog(parent,title,prompt,default) + result=a.ShowModal() + + if result=='ok': + r=a.GetValue() + else: + r=None + + a.Destroy() + + return r + + +class FloatInputDialog(TextEntryDialog): + + def __init__(self, parent, title='Enter some text', + prompt='Enter some text', default=None, cancel_button=1): + + TextEntryDialog.__init__(self, parent, title=title, + prompt=prompt, default=str(default), + cancel_button=cancel_button) + + + def GetValue(self): + + try: + val=TextEntryDialog.GetValue(self) + except ValueError: + return None + + try: + float_val=eval("float("+val+")") + except SyntaxError: + float_val=None + + return float_val + + + + def Validate(self): + val = TextEntryDialog.GetValue(self) # make sure the get a string + + try: + float_val=eval("float("+val+")") + except (SyntaxError,NameError): + Error("Syntax Error") + return False + + return True + + + +def Input_Float(title, + prompt, default=None,parent=None): + + a=FloatInputDialog(parent,title,prompt,default) + result=a.ShowModal() + + if result=='ok': + r=a.GetValue() + else: + r=None + + a.Destroy() + + return r + + diff --git a/pynxc/waxy/treelistview.py b/pynxc/waxy/treelistview.py new file mode 100644 index 0000000..e4d3d40 --- /dev/null +++ b/pynxc/waxy/treelistview.py @@ -0,0 +1,28 @@ +# treelistview.py + +import styles +import wx +import wx.gizmos as gizmos +import waxyobject +import treeview + +class TreeListView(gizmos.TreeListCtrl, waxyobject.WaxyObject): + + def __init__(self, parent, columns=(), size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + gizmos.TreeListCtrl.__init__(self, parent, wx.NewId(), + size=size or (-1,-1), style=style) + + for name in columns: + self.AddColumn(name) + + self.BindEvents() + styles.properties(self, kwargs) + + # some deviltry to copy styles stuff from TreeView... + _treeview_selection = treeview.TreeView._treeview_selection + _params = treeview.TreeView._params.im_func + # I'll come up with a better solution later. + diff --git a/pynxc/waxy/treeview.py b/pynxc/waxy/treeview.py new file mode 100644 index 0000000..eea90ca --- /dev/null +++ b/pynxc/waxy/treeview.py @@ -0,0 +1,119 @@ +# treeview.py + +# todo: can we access tree like a dict? + +from __future__ import generators +import wx +import waxyobject +import styles +import types +import utils + +class TreeView(wx.TreeCtrl, waxyobject.WaxyObject): + + __events__ = { + 'ItemExpanded': wx.EVT_TREE_ITEM_EXPANDED, + 'ItemExpanding': wx.EVT_TREE_ITEM_EXPANDING, + 'ItemCollapsed': wx.EVT_TREE_ITEM_COLLAPSED, + 'ItemCollapsing': wx.EVT_TREE_ITEM_COLLAPSING, + 'SelectionChanged': wx.EVT_TREE_SEL_CHANGED, + 'BeginEdit': wx.EVT_TREE_BEGIN_LABEL_EDIT, + 'EndEdit': wx.EVT_TREE_END_LABEL_EDIT, + 'ItemActivated': wx.EVT_TREE_ITEM_ACTIVATED, + 'BeginDrag': wx.EVT_TREE_BEGIN_DRAG, + 'BeginRightDrag': wx.EVT_TREE_BEGIN_RDRAG, + 'DeleteItem': wx.EVT_TREE_DELETE_ITEM, + } + + def __init__(self, parent, size=None, **kwargs): + style = 0 + style |= self._params(kwargs) + style |= styles.window(kwargs) + + wx.TreeCtrl.__init__(self, parent, wx.NewId(), size=size or (-1,-1), + style=style) + + self.BindEvents() + styles.properties(self, kwargs) + + def GetChildNodes(self, node): + """ Generator returning a node's children. <node> has to be a tree + node, e.g. the root, or any item. """ + child, cookie = self.GetFirstChild(node) + while child.IsOk(): + yield child + child, cookie = self.GetNextChild(node, cookie) + + def HasChildren(self, node): + child, cookie = self.GetFirstChild(node) + return child.IsOk() + + def Clear(self): + self.DeleteAllItems() + # Clear() is used for other controls, so it makes sense to use it here + # as well. + + def LoadFromDict(self, node, adict): + # XXX extend this to work with objects + items = adict.items() + items.sort() + for key, value in items: + if isinstance(value, dict): + child = self.AppendItem(node, utils.asstring(key)) + self.SetPyData(child, None) # hmm... + self.LoadFromDict(child, value) + else: + child = self.AppendItem(node, utils.asstring(key)) + self.SetPyData(child, value) + + def LoadFromNestedList(self, root, list): + """ + loads a nested list of (key, value, [children]) tuples (or lists) + as children of the given root node. preserves the + order of elements as they appear in the list. + """ + for item in list: + if (type(item) not in (types.TupleType, types.ListType) + or len(item) not in (0, 3)): + raise Exception, "LoadFromNestedList requires a list of (key, value, children) tuples" + (key, value, children) = item + node = self.AppendItem(root, utils.asstring(key)) + self.SetPyData(node, value) + if type(children) == types.ListType: + self.LoadFromNestedList(node, children) + + def SetImageList(self, imagelist): + wx.TreeCtrl.SetImageList(self, imagelist) + self._imagelist = imagelist + # a copy must be kept around, or the images will be freed + + def SetItemImage(self, node, index, expanded=0): + return wx.TreeCtrl.SetItemImage(self, node, index, [wx.TreeItemIcon_Normal, wx.TreeItemIcon_Expanded][expanded]) + + # + # style parameters + + _treeview_selection = { + 'single': wx.TR_SINGLE, + 'multiple': wx.TR_MULTIPLE, + 'extended': wx.TR_EXTENDED, + } + + def _params(self, kwargs): + flags = wx.TR_DEFAULT_STYLE + flags |= styles.stylebool('edit_labels', wx.TR_EDIT_LABELS, kwargs) + flags |= styles.stylebool('twist_buttons', wx.TR_TWIST_BUTTONS, kwargs) + flags |= styles.stylebool('lines', wx.TR_NO_LINES, kwargs, reverse=1) + flags |= styles.stylebool('hide_root', wx.TR_HIDE_ROOT, kwargs) + flags |= styles.styledictstart('selection', self._treeview_selection, kwargs) + + # has_buttons requires special code: + if kwargs.has_key('has_buttons'): + if kwargs['has_buttons']: + flags |= wx.TR_HAS_BUTTONS + else: + flags &= ~wx.TR_HAS_BUTTONS # make sure flag is NOT set + del kwargs['has_buttons'] + # Note that TR_NO_BUTTONS is useless... it's 0! + + return flags diff --git a/pynxc/waxy/utils.py b/pynxc/waxy/utils.py new file mode 100644 index 0000000..467b325 --- /dev/null +++ b/pynxc/waxy/utils.py @@ -0,0 +1,29 @@ +# tools.py +# Miscellaneous utility functions. + +import os +import warnings + +def asstring(x): + """ Ensure that x is a string, i.e. if it's not of the str or unicode + types, convert it with str. Otherwise, leave it unchanged. """ + if not (isinstance(x, str) or isinstance(x, unicode)): + x = str(x) + return x + +def opj(path): + """Convert paths to the platform-specific separator""" + str = apply(os.path.join, tuple(path.split('/'))) + # HACK: on Linux, a leading / gets lost... + if path.startswith('/'): + str = '/' + str + return str + +class CheckParentWarning(Warning): + pass + +def parent_warning(obj, container): + s = "obj %r has parent %r, but is added to container %r" % ( + obj, obj.GetParent(), container) + warnings.warn(s, CheckParentWarning) + diff --git a/pynxc/waxy/waxyobject.py b/pynxc/waxy/waxyobject.py new file mode 100644 index 0000000..952dd27 --- /dev/null +++ b/pynxc/waxy/waxyobject.py @@ -0,0 +1,246 @@ +# waxyobject.py + +import wx +import core +import colordb +import events +import mousepointer +import styles + +class MetaWaxyObject(type): + +## def inject_SetFont(cls): +## if hasattr(cls, "SetFont"): +## real_SetFont = getattr(cls, "SetFont") +## def SetFont(self, obj): +## if isinstance(obj, tuple): +## import font +## obj = font.Font(*obj) +## real_SetFont(self, obj) +## SetFont.__doc__ = real_SetFont.__doc__ +## setattr(cls, "SetFont", SetFont) +## if core.DEBUG: +## print "%s: SetFont replaced" % (cls,) +## +## def inject_GetFont(cls): +## if hasattr(cls, "GetFont"): +## real_GetFont = getattr(cls, "GetFont") +## import font +## def GetFont(self): +## wxfont = real_GetFont(self) +## wxfont.__class__ = font.Font +## return wxfont +## GetFont.__doc__ = real_GetFont.__doc__ +## setattr(cls, "GetFont", GetFont) +## if core.DEBUG: +## print "%s: GetFont replaced" % (cls,) + + def inject_SetCursor(cls): + if hasattr(cls, "SetCursor"): + real_SetCursor = getattr(cls, "SetCursor") + def SetCursor(self, x): + if isinstance(x, basestring): + c = mousepointer.MousePointers.Get(x) + real_SetCursor(self, c) + else: + real_SetCursor(self, x) + SetCursor.__doc__ = real_SetCursor.__doc__ + setattr(cls, "SetCursor", SetCursor) + if core.DEBUG: + print "%s: SetCursor replaced" % (cls,) + + def inject_SetWindowStyle(cls): + if hasattr(cls, "SetWindowStyle"): + real_SetWindowStyle = getattr(cls, "SetWindowStyle") + def SetWindowStyle(self, __default__=0, **kwargs): + """ Wax-style SetWindowStyle that supports the old way of + setting styles (using an integer flag value), and/or + named keywords, depending on the class's _params method. + """ + flags = __default__ + flags |= self._params(kwargs) + if isinstance(self, wx.Window): + flags |= styles.window(kwargs) + real_SetWindowStyle(self, flags) + setattr(cls, "SetWindowStyle", SetWindowStyle) + if core.DEBUG: + print "%s: SetWindowStyle replaced" % (cls,) + + def inject_ColorMethods(cls): + if hasattr(cls, "SetBackgroundColour"): + real_SetBackgroundColour = getattr(cls, "SetBackgroundColour") + real_SetForegroundColour = getattr(cls, "SetForegroundColour") + + def SetForegroundColour(self, color): + color = colordb.convert_color(color) + real_SetForegroundColour(self, color) + SetForegroundColour.__doc__ = real_SetForegroundColour.__doc__ + setattr(cls, "SetForegroundColour", SetForegroundColour) + + def SetBackgroundColour(self, color): + color = colordb.convert_color(color) + real_SetBackgroundColour(self, color) + SetBackgroundColour.__doc__ = real_SetBackgroundColour.__doc__ + setattr(cls, "SetBackgroundColour", SetBackgroundColour) + + # make aliases for "Color" + setattr(cls, "SetBackgroundColor", cls.SetBackgroundColour) + setattr(cls, "SetForegroundColor", cls.SetForegroundColour) + setattr(cls, "GetBackgroundColor", cls.GetBackgroundColour) + setattr(cls, "GetForegroundColor", cls.GetForegroundColour) + + if core.DEBUG: + print "%s: SetForegroundColour/SetBackgroundColour replaced" % (cls,) + + def __init__(cls, name, bases, dict): +# cls.inject_SetFont() +# cls.inject_GetFont() + cls.inject_SetCursor() + cls.inject_ColorMethods() + cls.inject_SetWindowStyle() + + +class WaxyObject: + """ Mixin class for Wax controls. + Stick attributes and methods here that every Wax control should have. + """ + __metaclass__ = MetaWaxyObject + # yes, I don't like metaclasses, but they're actually useful here :-) + + __events__ = {} + __styles__ = {} + +## def SetDefaultFont(self): +## if hasattr(self, 'SetFont'): +## self.SetFont(waxconfig.WaxConfig.default_font) + + def SetSizeX(self, ix): + x, y = self.GetSize() + self.SetSize((ix, y)) + + def SetSizeY(self, iy): + x, y = self.GetSize() + self.SetSize((x, iy)) + + def GetSizeX(self): + return self.GetSize()[0] + + def GetSizeY(self): + return self.GetSize()[1] + + def BindEvents(self): + items = [] + if hasattr(self, "__events__"): + items = getattr(self, "__events__").items() + items.extend(events.events.items()) + for name, wxevent in items: + if hasattr(self, "On" + name): + f = getattr(self, "On" + name) + self.Bind(wxevent, f) + if core.DEBUG: + print "Binding %s to %s" % (name, f) + + def GetAllChildren(self): + """ Return a generator returning all children, grandchildren, etc, + of the given widget. The widgets are traversed depth-first. + """ + if hasattr(self, 'GetChildren'): + for child in self.GetChildren(): + yield child + for grandchild in child.GetAllChildren(): + yield grandchild + + # + # pseudo-properties + + def __getattr__(self, name): + if hasattr(self.__class__, "Get" + name): + # use self.__class__ rather than self to avoid recursion + f = getattr(self, "Get" + name) + return f() + else: + raise AttributeError, name + + def __setattr__(self, name, value): + if hasattr(self, "Set" + name): + f = getattr(self, "Set" + name) + return f(value) + elif name.startswith("On"): + shortname = name[2:] + if self.__events__.has_key(shortname): + wxevent = self.__events__[shortname] + elif events.events.has_key(shortname): + wxevent = events.events[shortname] + else: + wxevent = None + self.__dict__[name] = value + if wxevent: + self.Bind(wxevent, value) + if core.DEBUG: + print "Binding %s to %s" % (name, value) + else: + self.__dict__[name] = value + + def SetAttributes(self, **kwargs): + """ Set a number of attributes at once. E.g. + widget.SetAttributes(Font=MYFONT, Size=(100,200)) + """ + for (key, value) in kwargs.items(): + self.__setattr__(key, value) + + def SetProperties(self, **kwargs): + """ As SetAttributes, but raises an error if an unknown property name + is specified. """ + for (key, value) in kwargs.items(): + f = getattr(self, "Set" + key, None) + if f: + f(value) + else: + raise AttributeError, "Unknown property: %s" % (key,) + + def _params(self, kwargs, thesestyles={}): + # default method for those controls that don't have a _params() + if thesestyles: + return styles.dostyle(thesestyles, kwargs) + else: + return styles.dostyle(self.__styles__, kwargs) + + def HasStyle(self, style, substyle=None): + """ Returns whether or not a style is set for this object. """ + try: + sval = self.__styles__[style][0] + if isinstance(sval, dict): + # The style returned is a complex style so... + if substyle: + # ...checking for a specific substyle, return if it's set + subval = sval[substyle] + ws = self.GetWindowStyle() + # If we're dealing with a zero based style, things + # get a bit trickier + if subval == 0: + for k in sval: + temp = sval[k] + if k != substyle and (ws & temp) == temp: + return False + return (ws & subval) == subval + else: + # ...not checking for specific, so see if either is set and + # return the key value associated with what is set + mystyle = self.GetWindowStyle() + for k in sval: + v = sval[k] + if (mystyle & v) == v: + return k + return False + else: + # Style is not complex, return if it is set or not + return (self.GetWindowStyle() & sval) == sval + except: + return False + + def GetStyleDict(self): + """ Returns a dictionary with style info for this object. """ + ret = {} + for k in self.__styles__: + ret[k] = self.HasStyle(k) + return ret diff --git a/pynxc/waxy/waxyobject.py~ b/pynxc/waxy/waxyobject.py~ new file mode 100644 index 0000000..a11937e --- /dev/null +++ b/pynxc/waxy/waxyobject.py~ @@ -0,0 +1,246 @@ +# waxobject.py + +import wx +import core +import colordb +import events +import mousepointer +import styles + +class MetaWaxyObject(type): + +## def inject_SetFont(cls): +## if hasattr(cls, "SetFont"): +## real_SetFont = getattr(cls, "SetFont") +## def SetFont(self, obj): +## if isinstance(obj, tuple): +## import font +## obj = font.Font(*obj) +## real_SetFont(self, obj) +## SetFont.__doc__ = real_SetFont.__doc__ +## setattr(cls, "SetFont", SetFont) +## if core.DEBUG: +## print "%s: SetFont replaced" % (cls,) +## +## def inject_GetFont(cls): +## if hasattr(cls, "GetFont"): +## real_GetFont = getattr(cls, "GetFont") +## import font +## def GetFont(self): +## wxfont = real_GetFont(self) +## wxfont.__class__ = font.Font +## return wxfont +## GetFont.__doc__ = real_GetFont.__doc__ +## setattr(cls, "GetFont", GetFont) +## if core.DEBUG: +## print "%s: GetFont replaced" % (cls,) + + def inject_SetCursor(cls): + if hasattr(cls, "SetCursor"): + real_SetCursor = getattr(cls, "SetCursor") + def SetCursor(self, x): + if isinstance(x, basestring): + c = mousepointer.MousePointers.Get(x) + real_SetCursor(self, c) + else: + real_SetCursor(self, x) + SetCursor.__doc__ = real_SetCursor.__doc__ + setattr(cls, "SetCursor", SetCursor) + if core.DEBUG: + print "%s: SetCursor replaced" % (cls,) + + def inject_SetWindowStyle(cls): + if hasattr(cls, "SetWindowStyle"): + real_SetWindowStyle = getattr(cls, "SetWindowStyle") + def SetWindowStyle(self, __default__=0, **kwargs): + """ Wax-style SetWindowStyle that supports the old way of + setting styles (using an integer flag value), and/or + named keywords, depending on the class's _params method. + """ + flags = __default__ + flags |= self._params(kwargs) + if isinstance(self, wx.Window): + flags |= styles.window(kwargs) + real_SetWindowStyle(self, flags) + setattr(cls, "SetWindowStyle", SetWindowStyle) + if core.DEBUG: + print "%s: SetWindowStyle replaced" % (cls,) + + def inject_ColorMethods(cls): + if hasattr(cls, "SetBackgroundColour"): + real_SetBackgroundColour = getattr(cls, "SetBackgroundColour") + real_SetForegroundColour = getattr(cls, "SetForegroundColour") + + def SetForegroundColour(self, color): + color = colordb.convert_color(color) + real_SetForegroundColour(self, color) + SetForegroundColour.__doc__ = real_SetForegroundColour.__doc__ + setattr(cls, "SetForegroundColour", SetForegroundColour) + + def SetBackgroundColour(self, color): + color = colordb.convert_color(color) + real_SetBackgroundColour(self, color) + SetBackgroundColour.__doc__ = real_SetBackgroundColour.__doc__ + setattr(cls, "SetBackgroundColour", SetBackgroundColour) + + # make aliases for "Color" + setattr(cls, "SetBackgroundColor", cls.SetBackgroundColour) + setattr(cls, "SetForegroundColor", cls.SetForegroundColour) + setattr(cls, "GetBackgroundColor", cls.GetBackgroundColour) + setattr(cls, "GetForegroundColor", cls.GetForegroundColour) + + if core.DEBUG: + print "%s: SetForegroundColour/SetBackgroundColour replaced" % (cls,) + + def __init__(cls, name, bases, dict): +# cls.inject_SetFont() +# cls.inject_GetFont() + cls.inject_SetCursor() + cls.inject_ColorMethods() + cls.inject_SetWindowStyle() + + +class WaxyObject: + """ Mixin class for Wax controls. + Stick attributes and methods here that every Wax control should have. + """ + __metaclass__ = MetaWaxyObject + # yes, I don't like metaclasses, but they're actually useful here :-) + + __events__ = {} + __styles__ = {} + +## def SetDefaultFont(self): +## if hasattr(self, 'SetFont'): +## self.SetFont(waxconfig.WaxConfig.default_font) + + def SetSizeX(self, ix): + x, y = self.GetSize() + self.SetSize((ix, y)) + + def SetSizeY(self, iy): + x, y = self.GetSize() + self.SetSize((x, iy)) + + def GetSizeX(self): + return self.GetSize()[0] + + def GetSizeY(self): + return self.GetSize()[1] + + def BindEvents(self): + items = [] + if hasattr(self, "__events__"): + items = getattr(self, "__events__").items() + items.extend(events.events.items()) + for name, wxevent in items: + if hasattr(self, "On" + name): + f = getattr(self, "On" + name) + self.Bind(wxevent, f) + if core.DEBUG: + print "Binding %s to %s" % (name, f) + + def GetAllChildren(self): + """ Return a generator returning all children, grandchildren, etc, + of the given widget. The widgets are traversed depth-first. + """ + if hasattr(self, 'GetChildren'): + for child in self.GetChildren(): + yield child + for grandchild in child.GetAllChildren(): + yield grandchild + + # + # pseudo-properties + + def __getattr__(self, name): + if hasattr(self.__class__, "Get" + name): + # use self.__class__ rather than self to avoid recursion + f = getattr(self, "Get" + name) + return f() + else: + raise AttributeError, name + + def __setattr__(self, name, value): + if hasattr(self, "Set" + name): + f = getattr(self, "Set" + name) + return f(value) + elif name.startswith("On"): + shortname = name[2:] + if self.__events__.has_key(shortname): + wxevent = self.__events__[shortname] + elif events.events.has_key(shortname): + wxevent = events.events[shortname] + else: + wxevent = None + self.__dict__[name] = value + if wxevent: + self.Bind(wxevent, value) + if core.DEBUG: + print "Binding %s to %s" % (name, value) + else: + self.__dict__[name] = value + + def SetAttributes(self, **kwargs): + """ Set a number of attributes at once. E.g. + widget.SetAttributes(Font=MYFONT, Size=(100,200)) + """ + for (key, value) in kwargs.items(): + self.__setattr__(key, value) + + def SetProperties(self, **kwargs): + """ As SetAttributes, but raises an error if an unknown property name + is specified. """ + for (key, value) in kwargs.items(): + f = getattr(self, "Set" + key, None) + if f: + f(value) + else: + raise AttributeError, "Unknown property: %s" % (key,) + + def _params(self, kwargs, thesestyles={}): + # default method for those controls that don't have a _params() + if thesestyles: + return styles.dostyle(thesestyles, kwargs) + else: + return styles.dostyle(self.__styles__, kwargs) + + def HasStyle(self, style, substyle=None): + """ Returns whether or not a style is set for this object. """ + try: + sval = self.__styles__[style][0] + if isinstance(sval, dict): + # The style returned is a complex style so... + if substyle: + # ...checking for a specific substyle, return if it's set + subval = sval[substyle] + ws = self.GetWindowStyle() + # If we're dealing with a zero based style, things + # get a bit trickier + if subval == 0: + for k in sval: + temp = sval[k] + if k != substyle and (ws & temp) == temp: + return False + return (ws & subval) == subval + else: + # ...not checking for specific, so see if either is set and + # return the key value associated with what is set + mystyle = self.GetWindowStyle() + for k in sval: + v = sval[k] + if (mystyle & v) == v: + return k + return False + else: + # Style is not complex, return if it is set or not + return (self.GetWindowStyle() & sval) == sval + except: + return False + + def GetStyleDict(self): + """ Returns a dictionary with style info for this object. """ + ret = {} + for k in self.__styles__: + ret[k] = self.HasStyle(k) + return ret |