PyGUI should now work without installation
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Actions - Generic
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Exceptions import ApplicationError
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def action_property(name, doc):
|
||||
attr = intern('_' + name)
|
||||
def getter(self):
|
||||
return getattr(self, attr)
|
||||
def setter(self, value):
|
||||
setattr(self, attr, value)
|
||||
return property(getter, setter, None, doc)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class ActionBase(object):
|
||||
"""Mixin class providing base support for action properties."""
|
||||
|
||||
def do_named_action(self, name):
|
||||
#print "ActionBase.do_named_action:", repr(name) ###
|
||||
action = getattr(self, name)
|
||||
#print "...action =", repr(action) ###
|
||||
if action:
|
||||
try:
|
||||
if isinstance(action, tuple):
|
||||
args = action[1:]
|
||||
action = action[0]
|
||||
else:
|
||||
args = ()
|
||||
if isinstance(action, str):
|
||||
#print "...handling", action ###
|
||||
self.handle(action, *args)
|
||||
else:
|
||||
action(*args)
|
||||
except ApplicationError:
|
||||
raise
|
||||
except:
|
||||
import sys
|
||||
et, ev, tb = sys.exc_info()
|
||||
raise et, et("%s (while doing action %r%r)" % (ev, action, args)), tb
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Action(ActionBase):
|
||||
"""Mixin class providing a single action property called 'action'."""
|
||||
|
||||
action = action_property('action', """Action to be performed.
|
||||
May be <action> or (<action>, <arg>...) where <action> is either
|
||||
a message name or a callable object.""")
|
||||
|
||||
_action = None
|
||||
|
||||
def do_action(self):
|
||||
"Invoke the action."
|
||||
self.do_named_action('action')
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
#-----------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Alert functions - Generic
|
||||
#
|
||||
#-----------------------------------------------------------------------
|
||||
|
||||
from GUI import BaseAlertFunctions
|
||||
|
||||
def alert(kind, prompt, ok_label = "OK", **kwds):
|
||||
"""Displays an alert box with one button. Does not return a value.
|
||||
Kind may be 'stop' for conditions preventing continuation,
|
||||
'caution' for warning messages, 'note' for informational
|
||||
messages, and 'query' for asking a question of the user."""
|
||||
|
||||
BaseAlertFunctions.alert(kind, prompt, ok_label, **kwds)
|
||||
|
||||
|
||||
def alert2(kind, prompt, yes_label = "Yes", no_label = "No",
|
||||
**kwds):
|
||||
"""Displays an alert with two buttons. Returns 1 if the
|
||||
first button is pressed, 0 if the second button is pressed.
|
||||
The 'default' and 'cancel' arguments specify which buttons,
|
||||
if any, are activated by the standard keyboard equivalents,
|
||||
and take the values 1, 0 or None."""
|
||||
|
||||
return BaseAlertFunctions.alert2(kind, prompt, yes_label, no_label,**kwds)
|
||||
|
||||
|
||||
def alert3(kind, prompt,
|
||||
yes_label = "Yes", no_label = "No", other_label = "Cancel",
|
||||
**kwds):
|
||||
"""Displays an alert with 3 buttons. Returns 1 if the
|
||||
first button is pressed, 0 if the second button is pressed,
|
||||
and -1 if the third button is pressed. The 'default' and 'cancel'
|
||||
arguments specify which buttons, if any, are activated by the
|
||||
standard keyboard equivalents, and take the values 1, 0, -1 or None."""
|
||||
|
||||
return BaseAlertFunctions.alert3(kind, prompt, yes_label, no_label, other_label, **kwds)
|
||||
|
||||
|
||||
def stop_alert(*args, **kwds):
|
||||
"""Displays a 1-button alert of type 'stop'. See alert()."""
|
||||
alert('stop', *args, **kwds)
|
||||
|
||||
def note_alert(*args, **kwds):
|
||||
"""Displays a 1-button alert of type 'note'. See alert()."""
|
||||
alert('note', *args, **kwds)
|
||||
|
||||
def confirm(*args, **kwds):
|
||||
"""Displays a 2-button alert of type 'caution'. See alert2()."""
|
||||
return alert2('caution', *args, **kwds)
|
||||
|
||||
def ask(*args, **kwds):
|
||||
"""Displays a 2-button alert of type 'query'. See alert2()."""
|
||||
return alert2('query', *args, **kwds)
|
||||
|
||||
def confirm_or_cancel(*args, **kwds):
|
||||
"""Displays a 3-button alert of type 'caution'. See alert3()."""
|
||||
return alert3('caution', *args, **kwds)
|
||||
|
||||
def ask_or_cancel(*args, **kwds):
|
||||
"""Displays a 3-button alert of type 'query'. See alert3()."""
|
||||
return alert3('query', *args, **kwds)
|
||||
@@ -0,0 +1,26 @@
|
||||
#
|
||||
# Python GUI - Basic alert functions - Generic
|
||||
#
|
||||
|
||||
from GUI.AlertClasses import Alert, Alert2, Alert3
|
||||
|
||||
def present_and_destroy(dlog):
|
||||
dlog.center()
|
||||
try:
|
||||
return dlog.present()
|
||||
finally:
|
||||
dlog.destroy()
|
||||
|
||||
|
||||
def alert(kind, prompt, ok_label, **kwds):
|
||||
present_and_destroy(Alert(kind, prompt, ok_label))
|
||||
|
||||
|
||||
def alert2(kind, prompt, yes_label, no_label, **kwds):
|
||||
return present_and_destroy(
|
||||
Alert2(kind, prompt, yes_label, no_label, **kwds))
|
||||
|
||||
|
||||
def alert3(kind, prompt, yes_label, no_label, other_label, **kwds):
|
||||
return present_and_destroy(
|
||||
Alert3(kind, prompt, yes_label, no_label, other_label, **kwds))
|
||||
@@ -0,0 +1,52 @@
|
||||
#---------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Column layout component - Generic
|
||||
#
|
||||
#---------------------------------------------------------------------------
|
||||
|
||||
from LayoutUtils import equalize_components
|
||||
from GUI import Frame, export
|
||||
|
||||
class Column(Frame):
|
||||
|
||||
def __init__(self, items, spacing = 10, align = 'l', equalize = '',
|
||||
expand = None, padding = (0, 0), **kwds):
|
||||
Frame.__init__(self)
|
||||
hpad, vpad = padding
|
||||
if expand is not None and not isinstance(expand, int):
|
||||
expand = items.index(expand)
|
||||
equalize_components(items, equalize)
|
||||
width = 0
|
||||
for item in items:
|
||||
if item:
|
||||
width = max(width, item.width)
|
||||
y = vpad
|
||||
gap = 0
|
||||
vanchor = 't'
|
||||
hanchor = align
|
||||
for i, item in enumerate(items):
|
||||
if item:
|
||||
y += gap
|
||||
if 'l' in align:
|
||||
x = 0
|
||||
if 'r' in align:
|
||||
item.width = width
|
||||
elif align == 'r':
|
||||
x = width - item.width
|
||||
else:
|
||||
x = (width - item.width) // 2
|
||||
item.position = (x + hpad, y)
|
||||
if i == expand:
|
||||
item.anchor = 'tb' + hanchor
|
||||
vanchor = 'b'
|
||||
else:
|
||||
item.anchor = vanchor + hanchor
|
||||
y += item.height
|
||||
if i == expand:
|
||||
vanchor = 'b'
|
||||
gap = spacing
|
||||
self.size = (width + 2 * hpad, y + vpad)
|
||||
self.add(items)
|
||||
self.set(**kwds)
|
||||
|
||||
export(Column)
|
||||
@@ -0,0 +1,10 @@
|
||||
#-------------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Facilities for compatibility across Python versions
|
||||
#
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
try:
|
||||
from __builtin__ import set
|
||||
except ImportError:
|
||||
from sets import Set as set
|
||||
@@ -0,0 +1,321 @@
|
||||
#
|
||||
# Python GUI - Documents - Generic
|
||||
#
|
||||
|
||||
import os, tempfile
|
||||
from GUI import export
|
||||
from GUI.Alerts import confirm, confirm_or_cancel
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Model
|
||||
from GUI import MessageHandler
|
||||
from GUI.Files import FileRef, DirRef
|
||||
from GUI.FileDialogs import request_new_file
|
||||
from GUI import application
|
||||
from GUI.Exceptions import Cancel, UnimplementedMethod, ApplicationError
|
||||
from GUI.Printing import PageSetup, present_page_setup_dialog
|
||||
|
||||
_next_doc_number = 1 # Counter for generating default titles
|
||||
|
||||
class Document(Model, MessageHandler):
|
||||
"""A Document represents an
|
||||
application data structure that can be stored in a file. It
|
||||
implements the standard parts of asking the user for file names and
|
||||
reading and writing files.
|
||||
|
||||
Each Document can have one or more windows associated with it. When
|
||||
the last window belonging to a document is closed, the document itself
|
||||
is closed.
|
||||
|
||||
A Document provides support for keeping track of whether it has been
|
||||
edited, and asking the user whether to save changes when it is
|
||||
closed."""
|
||||
|
||||
# The following attribute prevents a Document that is the parent
|
||||
# of a Model from being pickled along with that Model.
|
||||
pickle_as_parent_model = False
|
||||
|
||||
needs_saving = overridable_property('needs_saving',
|
||||
"True if the document has been edited and needs to be saved.")
|
||||
|
||||
file = overridable_property('file',
|
||||
"""FileRef of the file that the document was read from or last written
|
||||
to, or None. Changing this causes update_title to be called.""")
|
||||
|
||||
file_type = overridable_property('file_type',
|
||||
"""FileType specifying the type of file handled by this document.""")
|
||||
|
||||
title = overridable_property('title',
|
||||
"""The title of the document. Changing this causes update_title of each
|
||||
associated window to be called.""")
|
||||
|
||||
windows = overridable_property('windows',
|
||||
"List of windows associated with the document. Do not modify directly.")
|
||||
|
||||
page_setup = overridable_property('page_setup',
|
||||
"The PageSetup to be used for printing this document.")
|
||||
|
||||
binary = True # True if files are to be opened in binary mode
|
||||
|
||||
_file_type = None # Type of file to create when saving
|
||||
_needs_saving = 0 # True if has been edited
|
||||
_file = None # FileRef of associated file, if any
|
||||
_title = None # Title for use in window banners, etc.
|
||||
_windows = None # List of associated windows
|
||||
_page_setup = None # Document-specific PageSetup instance
|
||||
|
||||
#
|
||||
# Initialisation and destruction
|
||||
#
|
||||
|
||||
def __init__(self, **kwds):
|
||||
self._windows = []
|
||||
Model.__init__(self, **kwds)
|
||||
application()._add_document(self)
|
||||
|
||||
def destroy(self):
|
||||
"""Destroy any associated windows, then destroy document contents."""
|
||||
#print "Document.destroy:", self ###
|
||||
for win in self._windows[:]:
|
||||
win.destroy()
|
||||
application()._remove_document(self)
|
||||
self.destroy_contents()
|
||||
Model.destroy(self)
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_needs_saving(self):
|
||||
return self._needs_saving
|
||||
|
||||
def set_needs_saving(self, x):
|
||||
if self._needs_saving <> x:
|
||||
self._needs_saving = x
|
||||
for window in self._windows:
|
||||
window._document_needs_saving(x)
|
||||
|
||||
def get_file(self):
|
||||
return self._file
|
||||
|
||||
def set_file(self, x):
|
||||
self._file = x
|
||||
if x is not None:
|
||||
application()._last_directory = x.dir
|
||||
self.update_title()
|
||||
|
||||
def get_file_type(self):
|
||||
return self._file_type
|
||||
|
||||
def set_file_type(self, x):
|
||||
self._file_type = x
|
||||
|
||||
def get_title(self):
|
||||
t = self._title
|
||||
if t == None:
|
||||
t = self.make_title()
|
||||
self._title = t
|
||||
return t
|
||||
|
||||
def set_title(self, x):
|
||||
self._title = x
|
||||
for win in self._windows:
|
||||
win.update_title()
|
||||
|
||||
def get_windows(self):
|
||||
return self._windows
|
||||
|
||||
def get_page_setup(self):
|
||||
ps = self._page_setup
|
||||
if not ps:
|
||||
ps = PageSetup()
|
||||
self._page_setup = ps
|
||||
return ps
|
||||
|
||||
def set_page_setup(self, ps):
|
||||
self._page_setup = ps
|
||||
|
||||
#
|
||||
# Methods
|
||||
#
|
||||
|
||||
def changed(self):
|
||||
"Set the needs_saving property to true."
|
||||
self.needs_saving = 1
|
||||
|
||||
def new_contents(self):
|
||||
"""Should initialise the document to the appropriate state following a New
|
||||
command."""
|
||||
pass
|
||||
|
||||
def read_contents(self, file):
|
||||
"""Should initialise the document's contents by reading it from the given
|
||||
file object."""
|
||||
raise UnimplementedMethod(self, 'read_contents')
|
||||
|
||||
def write_contents(self, file):
|
||||
"""Should write the document's contents to the given file object."""
|
||||
raise UnimplementedMethod(self, 'write_contents')
|
||||
|
||||
def destroy_contents(self):
|
||||
"""Called when the contents of the document are about to be discarded.
|
||||
If the contents contains any Model objects, they should be destroyed."""
|
||||
|
||||
def save_changes(self):
|
||||
"""If the document has been edited, ask the user whether to save changes,
|
||||
and do so if requested."""
|
||||
if self._needs_saving:
|
||||
result = confirm_or_cancel('Save changes to "%s"?' % self.title,
|
||||
"Save", "Don't Save", "Cancel")
|
||||
if result < 0:
|
||||
raise Cancel
|
||||
if result:
|
||||
self.save_cmd()
|
||||
|
||||
def save_cmd(self):
|
||||
"""Implements the standard Save command. Writes the document to its
|
||||
associated file, asking the user for one first if necessary."""
|
||||
if self._file == None:
|
||||
self.get_new_file_name()
|
||||
try:
|
||||
self.write()
|
||||
except EnvironmentError, e:
|
||||
raise ApplicationError("Unable to save '%s'." % self._file.name, e)
|
||||
|
||||
def save_as_cmd(self):
|
||||
"""Implements the standard Save As... command. Asks the user for a new file
|
||||
and writes the document to it."""
|
||||
self.get_new_file_name()
|
||||
self.save_cmd()
|
||||
|
||||
def revert_cmd(self):
|
||||
"""Implements the standard Revert command. Discards the current contents
|
||||
of the document and re-reads it from the associated file."""
|
||||
if self._file != None:
|
||||
if confirm(
|
||||
'Revert to the last saved version of "%s"?' % self.title,
|
||||
"Revert", "Cancel"):
|
||||
self.destroy_contents()
|
||||
self.read()
|
||||
|
||||
def close_cmd(self):
|
||||
"""Implements the standard Close command. Asks whether to save any
|
||||
changes, then destroys the document."""
|
||||
self.save_changes()
|
||||
self.destroy()
|
||||
|
||||
def page_setup_cmd(self):
|
||||
if present_page_setup_dialog(self.page_setup):
|
||||
self.changed()
|
||||
|
||||
def make_title(self):
|
||||
"""Generates a title for the document. If associated with a file,
|
||||
uses its last pathname component, else generates 'Untitled-n'."""
|
||||
global _next_doc_number
|
||||
if self._file != None:
|
||||
return os.path.basename(self._file)
|
||||
else:
|
||||
n = _next_doc_number
|
||||
_next_doc_number = n + 1
|
||||
return "Untitled-%d" % n
|
||||
|
||||
def update_title(self):
|
||||
"""Called when the file property changes, to update the
|
||||
title property appropriately."""
|
||||
file = self._file
|
||||
if file:
|
||||
self.title = file.name
|
||||
|
||||
def get_default_save_directory(self):
|
||||
"""Called when the user is about to be asked for a location in which
|
||||
to save a document that has not been saved before, to find a default
|
||||
directory for request_new_file(). Should return a DirRef or FileRef,
|
||||
or None if there is no particular preferred location."""
|
||||
return None
|
||||
|
||||
def get_default_save_filename(self):
|
||||
"""Called when the user is about to be asked for a location in which
|
||||
to save a document that has not been saved before, to find a default
|
||||
file name for request_new_file(). Should return a suggested file name,
|
||||
or an empty string to require the user to enter a file name."""
|
||||
return ""
|
||||
|
||||
#
|
||||
# Internal methods
|
||||
#
|
||||
|
||||
def get_new_file_name(self):
|
||||
"""Ask the user for a new file and associate the document with it."""
|
||||
old_file = self.file
|
||||
if old_file:
|
||||
old_name = old_file.name
|
||||
old_dir = old_file.dir
|
||||
else:
|
||||
old_name = self.get_default_save_filename()
|
||||
old_dir = self.get_default_save_directory()
|
||||
#print "Document.get_new_file_name: old_dir =", old_dir, "old_name =", old_name ###
|
||||
new_file = request_new_file(
|
||||
#'Save "%s" as:' % self.title,
|
||||
default_dir = old_dir,
|
||||
default_name = old_name,
|
||||
file_type = self.file_type or application().save_file_type)
|
||||
if new_file is None:
|
||||
raise Cancel()
|
||||
self.file = new_file
|
||||
|
||||
def read(self):
|
||||
"""Read the document from its currently associated file. The
|
||||
document must be associated with a file and not have any existing
|
||||
contents when this is called."""
|
||||
if self.binary:
|
||||
mode = "rb"
|
||||
else:
|
||||
mode = "rU"
|
||||
file = self.file.open(mode)
|
||||
try:
|
||||
self.read_contents(file)
|
||||
finally:
|
||||
file.close()
|
||||
self.needs_saving = 0
|
||||
|
||||
def write(self):
|
||||
"""Write the document to its currently associated file. The
|
||||
document must be associated with a file when this is called.
|
||||
The document is initially written to a temporary file which
|
||||
is then renamed, so if writing fails part way through, the
|
||||
original file is undisturbed."""
|
||||
if self.binary:
|
||||
mode = "wb"
|
||||
else:
|
||||
mode = "w"
|
||||
dir_path = self.file.dir.path
|
||||
fd, temp_path = tempfile.mkstemp(dir = dir_path, text = not self.binary)
|
||||
file = os.fdopen(fd, mode)
|
||||
try:
|
||||
try:
|
||||
self.write_contents(file)
|
||||
finally:
|
||||
file.close()
|
||||
except EnvironmentError:
|
||||
os.unlink(fd)
|
||||
raise
|
||||
path = self.file.path
|
||||
try:
|
||||
os.unlink(path)
|
||||
except EnvironmentError:
|
||||
pass
|
||||
os.rename(temp_path, path)
|
||||
self.needs_saving = 0
|
||||
|
||||
def setup_menus(self, m):
|
||||
#print "Document.setup_menus" ###
|
||||
if self._needs_saving or not self._file:
|
||||
m.save_cmd.enabled = 1
|
||||
if self._needs_saving and self._file:
|
||||
m.revert_cmd.enabled = 1
|
||||
m.save_as_cmd.enabled = 1
|
||||
m.page_setup_cmd.enabled = 1
|
||||
|
||||
def next_handler(self):
|
||||
return application()
|
||||
|
||||
export(Document)
|
||||
@@ -0,0 +1,16 @@
|
||||
#
|
||||
# PyGUI - Enumerated type facilities
|
||||
#
|
||||
|
||||
class EnumMap(dict):
|
||||
|
||||
def __init__(self, __name__, *args, **kwds):
|
||||
self.name = __name__
|
||||
dict.__init__(self, *args, **kwds)
|
||||
|
||||
def __getitem__(self, key):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
raise ValueError("Invalid %s '%s', should be one of %s" %
|
||||
(self.name, key, ", ".join(["'%s'" % val for val in self.keys()])))
|
||||
@@ -0,0 +1,67 @@
|
||||
#
|
||||
# Exceptions.py - GUI exception classes
|
||||
#
|
||||
|
||||
class Cancel(Exception):
|
||||
"""Exception raised when user cancels an operation."""
|
||||
pass
|
||||
|
||||
|
||||
#class Quit(Exception):
|
||||
# """Exception raised to exit the main event loop."""
|
||||
# pass
|
||||
|
||||
|
||||
class Error(StandardError):
|
||||
|
||||
def __init__(self, obj, mess):
|
||||
self.obj = obj
|
||||
self.mess = mess
|
||||
Exception.__init__(self, "%s: %s" % (obj, mess))
|
||||
|
||||
|
||||
class ApplicationError(StandardError):
|
||||
"""Exception used for reporting errors to the user."""
|
||||
|
||||
def __init__(self, message, detail = None):
|
||||
self.message = message
|
||||
self.detail = detail
|
||||
if detail:
|
||||
message = "%s\n\n%s" % (message, detail)
|
||||
StandardError.__init__(self, message)
|
||||
|
||||
|
||||
class InternalError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnimplementedMethod(NotImplementedError):
|
||||
|
||||
def __init__(self, obj, meth_name):
|
||||
self.obj = obj
|
||||
StandardError.__init__(self, "%s.%s not implemented" % \
|
||||
(obj.__class__.__name__, meth_name))
|
||||
|
||||
|
||||
class ArgumentError(TypeError):
|
||||
|
||||
def __init__(self, obj, meth_name, arg_name, value):
|
||||
self.obj = obj
|
||||
self.meth_name = meth_name
|
||||
self.arg_name = arg_name
|
||||
self.value = value
|
||||
TypeError.__init__(self,
|
||||
"%s: Invalid value %s for argument %s of method %s",
|
||||
(obj, value, arg_name, meth_name))
|
||||
|
||||
|
||||
class SetAttributeError(AttributeError):
|
||||
|
||||
def __init__(self, obj, attr):
|
||||
self.obj = obj
|
||||
self.attr = attr
|
||||
AttributeError.__init__(self, "Attribute '%s' of %s cannot be set" % (attr, obj))
|
||||
|
||||
|
||||
class UsageError(StandardError):
|
||||
pass
|
||||
@@ -0,0 +1,56 @@
|
||||
#
|
||||
# Python GUI - File selection dialogs - Generic
|
||||
#
|
||||
|
||||
from GUI.BaseFileDialogs import _request_old, _request_new
|
||||
|
||||
|
||||
def request_old_file(prompt = "Open File", default_dir = None, file_types = None):
|
||||
"""Present a dialog for selecting an existing file.
|
||||
Returns a FileRef, or None if cancelled."""
|
||||
|
||||
return _request_old(prompt, default_dir, file_types,
|
||||
dir = False, multiple = False)
|
||||
|
||||
|
||||
def request_old_files(prompt = "Choose Files", default_dir = None, file_types = None):
|
||||
"""Present a dialog for selecting a set of existing files.
|
||||
Returns a list of FileRefs, or None if cancelled."""
|
||||
|
||||
return _request_old(prompt, default_dir, file_types,
|
||||
dir = False, multiple = True)
|
||||
|
||||
|
||||
def request_old_directory(prompt = "Choose Folder", default_dir = None):
|
||||
"""Present a dialog for selecting an existing directory.
|
||||
Returns a FileRef, or None if cancelled."""
|
||||
|
||||
return _request_old(prompt, default_dir, file_types = None,
|
||||
dir = True, multiple = False)
|
||||
|
||||
|
||||
def request_old_directories(prompt = "Choose Folders", default_dir = None,
|
||||
multiple = False):
|
||||
"""Present a dialog for selecting a set of existing directories.
|
||||
Returns a list of FileRefs, or None if cancelled."""
|
||||
|
||||
return _request_old(prompt, default_dir, file_types = None,
|
||||
dir = True, multiple = True)
|
||||
|
||||
|
||||
def request_new_file(prompt = "Save As:", default_dir = None,
|
||||
default_name = "", file_type = None):
|
||||
"""Present a dialog requesting a name and location for a new file.
|
||||
Returns a FileRef, or None if cancelled."""
|
||||
|
||||
return _request_new(prompt, default_dir, default_name, file_type,
|
||||
dir = False)
|
||||
|
||||
|
||||
def request_new_directory(prompt = "Create Folder:", default_dir = None,
|
||||
default_name = ""):
|
||||
"""Present a dialog requesting a name and location for a new directory.
|
||||
Returns a FileRef, or None if cancelled."""
|
||||
|
||||
return _request_new(prompt, default_dir, default_name, file_type = None,
|
||||
dir = True)
|
||||
@@ -0,0 +1,67 @@
|
||||
#
|
||||
# Python GUI - Alerts - Generic
|
||||
#
|
||||
|
||||
from GUI import BaseAlert
|
||||
from GUI import Button
|
||||
from GUI.StdButtons import DefaultButton, CancelButton
|
||||
|
||||
|
||||
class Alert(BaseAlert):
|
||||
|
||||
def __init__(self, kind, prompt,
|
||||
ok_label = "OK", default = 1, **kwds):
|
||||
BaseAlert.__init__(self, kind, prompt,
|
||||
button_labels = [ok_label], default = default, **kwds)
|
||||
|
||||
def _create_buttons(self, ok_label):
|
||||
self.yes_button = DefaultButton(title = ok_label, action = self.yes)
|
||||
#self.default_button = self.ok_button
|
||||
|
||||
def _layout_buttons(self):
|
||||
self.place(self.yes_button,
|
||||
right = self.label.right,
|
||||
top = self.label + self._label_button_spacing)
|
||||
|
||||
|
||||
class Alert2(BaseAlert):
|
||||
|
||||
def __init__(self, kind, prompt,
|
||||
yes_label = "Yes", no_label = "No",
|
||||
default = 1, cancel = 0, **kwds):
|
||||
BaseAlert.__init__(self, kind, prompt,
|
||||
button_labels = [yes_label, no_label],
|
||||
default = default, cancel = cancel, **kwds)
|
||||
|
||||
def _create_buttons(self, yes_label, no_label):
|
||||
self.yes_button = DefaultButton(title = yes_label, action = self.yes)
|
||||
self.no_button = CancelButton(title = no_label, action = self.no)
|
||||
|
||||
def _layout_buttons(self):
|
||||
self.place_row([self.no_button, self.yes_button],
|
||||
right = self.label.right,
|
||||
top = self.label + self._label_button_spacing)
|
||||
|
||||
|
||||
class Alert3(BaseAlert):
|
||||
|
||||
_minimum_width = 300
|
||||
|
||||
def __init__(self, kind, prompt,
|
||||
yes_label = "Yes", no_label = "No", other_label = "Cancel",
|
||||
default = 1, cancel = -1, **kwds):
|
||||
BaseAlert.__init__(self, kind, prompt,
|
||||
button_labels = [yes_label, no_label, other_label],
|
||||
default = default, cancel = cancel, **kwds)
|
||||
|
||||
def _create_buttons(self, yes_label, no_label, cancel_label):
|
||||
self.yes_button = DefaultButton(title = yes_label, action = self.yes)
|
||||
self.no_button = CancelButton(title = no_label, action = self.no)
|
||||
self.other_button = Button(title = cancel_label, action = self.other)
|
||||
|
||||
def _layout_buttons(self):
|
||||
self.place_row([self.other_button, self.yes_button],
|
||||
right = self.label.right,
|
||||
top = self.label + self._label_button_spacing)
|
||||
self.place(self.no_button,
|
||||
left = self._left_margin, top = self.label + self._label_button_spacing)
|
||||
@@ -0,0 +1,547 @@
|
||||
#
|
||||
# Python GUI - Application class - Generic
|
||||
#
|
||||
|
||||
import os, sys, traceback
|
||||
from GUI import Globals
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
from GUI import MessageHandler
|
||||
from GUI.Exceptions import Cancel, UnimplementedMethod, UsageError, \
|
||||
ApplicationError #, Quit
|
||||
from GUI.StdMenus import basic_menus
|
||||
from GUI.GMenus import MenuState
|
||||
from GUI.Files import FileRef
|
||||
from GUI.Printing import PageSetup, present_page_setup_dialog
|
||||
|
||||
class Application(Properties, MessageHandler):
|
||||
"""The user should create exactly one Application object,
|
||||
or subclass thereof. It implements the main event loop
|
||||
and other application-wide behaviour."""
|
||||
|
||||
_windows = None # List of all existing Windows
|
||||
_documents = None # List of all existing Documents
|
||||
_menus = None # Menus to appear in all Windows
|
||||
_clipboard = None
|
||||
_save_file_type = None
|
||||
_exit_event_loop_flag = False
|
||||
_last_directory = None
|
||||
|
||||
windows = overridable_property('windows',
|
||||
"""A list of all existing Windows.""")
|
||||
|
||||
documents = overridable_property('documents',
|
||||
"""A list of all existing documents.""")
|
||||
|
||||
menus = overridable_property('menus',
|
||||
"""A list of Menus that are to be available from all Windows.""")
|
||||
|
||||
open_file_types = overridable_property('open_file_types',
|
||||
"""List of FileTypes openable by the default Open... command.""")
|
||||
|
||||
save_file_type = overridable_property('save_file_type',
|
||||
"""Default FileType for Documents that do not specify their own.""")
|
||||
|
||||
file_type = overridable_property('file_type',
|
||||
"""Write only. Sets open_file_types and save_file_type.""")
|
||||
|
||||
target = overridable_property('target',
|
||||
"""Current target for key events and menu messages.""")
|
||||
|
||||
target_window = overridable_property('target_window',
|
||||
"""Window containing the current target, or None if there are no windows.""")
|
||||
|
||||
page_setup = overridable_property('page_setup',
|
||||
"""Default PageSetup instance.""")
|
||||
|
||||
def __init__(self, title = None):
|
||||
if Globals._application is not None:
|
||||
raise UsageError("More than one Application instance created")
|
||||
if title:
|
||||
Globals.application_name = title
|
||||
self._open_file_types = []
|
||||
self._windows = []
|
||||
self._documents = []
|
||||
self._update_list = []
|
||||
self._idle_tasks = []
|
||||
self._page_setup = None
|
||||
Globals._application = self
|
||||
self._quit_flag = False
|
||||
|
||||
def destroy(self):
|
||||
Globals._application = None
|
||||
|
||||
#
|
||||
# Constants
|
||||
#
|
||||
|
||||
# def get_std_menus(self):
|
||||
# """Returns a list of Menus containing the standard
|
||||
# framework-defined menu commands in their standard
|
||||
# positions."""
|
||||
# return basic_menus()
|
||||
#
|
||||
# std_menus = property(get_std_menus)
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_windows(self):
|
||||
return self._windows
|
||||
|
||||
def get_documents(self):
|
||||
return self._documents
|
||||
|
||||
def get_menus(self):
|
||||
menus = self._menus
|
||||
if menus is None:
|
||||
menus = []
|
||||
return menus
|
||||
|
||||
def set_menus(self, menus):
|
||||
self._menus = menus
|
||||
|
||||
def get_open_file_types(self):
|
||||
return self._open_file_types
|
||||
|
||||
def set_open_file_types(self, x):
|
||||
self._open_file_types = x
|
||||
|
||||
def get_save_file_type(self):
|
||||
return self._save_file_type
|
||||
|
||||
def set_save_file_type(self, x):
|
||||
self._save_file_type = x
|
||||
|
||||
def set_file_type(self, x):
|
||||
self._open_file_types = [x]
|
||||
self._save_file_type = x
|
||||
|
||||
def get_page_setup(self):
|
||||
# This property is initialised lazily, because on Windows it turn out
|
||||
# that calling PageSetupDlg() before the application's first window is
|
||||
# created causes the app not to be brought to the foreground initially.
|
||||
ps = self._page_setup
|
||||
if not ps:
|
||||
ps = PageSetup()
|
||||
self._page_setup = ps
|
||||
return ps
|
||||
|
||||
def set_page_setup(self, x):
|
||||
self._page_setup = x
|
||||
|
||||
#
|
||||
# Event loop
|
||||
#
|
||||
|
||||
def run(self):
|
||||
"""The main event loop. Runs until _quit() is called, or
|
||||
KeyboardInterrupt or SystemExit is raised."""
|
||||
# Implementations may override this together with _quit() to use
|
||||
# a different means of causing the main event loop to exit.
|
||||
self.process_args(sys.argv[1:])
|
||||
if self._menus is None:
|
||||
self.menus = basic_menus()
|
||||
while not self._quit_flag:
|
||||
try:
|
||||
self.event_loop()
|
||||
#except (KeyboardInterrupt, Quit), e:
|
||||
except KeyboardInterrupt:
|
||||
return
|
||||
except SystemExit:
|
||||
raise
|
||||
except:
|
||||
self.report_error()
|
||||
|
||||
def _quit(self):
|
||||
# Causes the main event loop to exit.
|
||||
self._quit_flag = True
|
||||
self._exit_event_loop()
|
||||
|
||||
def event_loop(self):
|
||||
"""Loop reading and handling events until exit_event_loop() is called."""
|
||||
# Implementations may override this together with exit_event_loop() to
|
||||
# implement non-modal event loops in a different way.
|
||||
self._event_loop(None)
|
||||
|
||||
def _event_loop(self, modal_window):
|
||||
# Generic modal and non-modal event loop.
|
||||
# Loop reading and handling events for the given window, or for all
|
||||
# windows if window is None, until exit_event_loop() is called.
|
||||
# Enabled application-wide menu items should be selectable in any case.
|
||||
# If an exception other than Cancel is raised, it should either be
|
||||
# reported using report_error() or propagated. Implementations may
|
||||
# override this together with _exit_event_loop() if handling events
|
||||
# individually is not desirable.
|
||||
save = self._exit_event_loop_flag
|
||||
self._exit_event_loop_flag = False
|
||||
try:
|
||||
while not self._exit_event_loop_flag:
|
||||
try:
|
||||
self.handle_next_event(modal_window)
|
||||
except Cancel:
|
||||
pass
|
||||
finally:
|
||||
self._exit_event_loop_flag = save
|
||||
|
||||
def exit_event_loop(self):
|
||||
"""Cause the current call to event_loop() or modal_event_loop()
|
||||
to exit."""
|
||||
self._exit_event_loop()
|
||||
|
||||
def _exit_event_loop(self):
|
||||
# Exit the generic _event_loop implementation.
|
||||
self._exit_event_loop_flag = True
|
||||
|
||||
# def event_loop_until(self, exit):
|
||||
# """Loop reading and handling events until exit() returns
|
||||
# true, _quit_flag is set or an exception other than Cancel
|
||||
# is raised."""
|
||||
# while not exit() and not self._quit_flag:
|
||||
# try:
|
||||
# self.handle_next_event()
|
||||
# except Cancel:
|
||||
# pass
|
||||
|
||||
# def handle_events(self):
|
||||
# """Handle events until an exception occurs. Waits for at least one event;
|
||||
# may handle more, at the discretion of the implementation."""
|
||||
# self.handle_next_event()
|
||||
|
||||
def handle_next_event(self, modal_window):
|
||||
# Wait for the next event to arrive and handle it. Transparently handles
|
||||
# any internal events such as window updates, etc., and executes any idle
|
||||
# tasks that become due while waiting for an event. If modal_window is
|
||||
# not None, restrict interaction to that window (but allow use of enabled
|
||||
# application-wide menu items).
|
||||
#
|
||||
# This only needs to be implemented if the generic _event_loop() is being
|
||||
# used.
|
||||
raise UnimplementedMethod(self, "handle_next_event")
|
||||
|
||||
#
|
||||
# Menu commands
|
||||
#
|
||||
|
||||
def setup_menus(self, m):
|
||||
m.new_cmd.enabled = 1
|
||||
m.open_cmd.enabled = 1
|
||||
m.page_setup_cmd.enabled = 1
|
||||
m.quit_cmd.enabled = 1
|
||||
|
||||
def new_cmd(self):
|
||||
"Handle the New menu command."
|
||||
doc = self.make_new_document()
|
||||
if not doc:
|
||||
raise UsageError(
|
||||
"Application.make_document(None) did not return a Document.")
|
||||
doc.new_contents()
|
||||
self.make_window(doc)
|
||||
|
||||
def open_cmd(self):
|
||||
"Handle the Open... menu command."
|
||||
from FileDialogs import request_old_file
|
||||
dir = self.get_default_open_directory()
|
||||
fileref = request_old_file(default_dir = dir,
|
||||
file_types = self._open_file_types)
|
||||
if fileref:
|
||||
self.open_fileref(fileref)
|
||||
else:
|
||||
raise Cancel
|
||||
|
||||
def get_default_open_directory(self):
|
||||
"""Called by the default implementation of open_cmd() to find an initial
|
||||
directory for request_old_file(). Should return a DirRef or FileRef, or
|
||||
None if there is no preferred location. By default it returns the last
|
||||
directory in which a document was opened or saved during this session,
|
||||
if any."""
|
||||
return self._last_directory
|
||||
|
||||
def page_setup_cmd(self):
|
||||
present_page_setup_dialog(self.page_setup)
|
||||
|
||||
def quit_cmd(self):
|
||||
"""Handle the Quit menu command."""
|
||||
while self._documents:
|
||||
self._documents[0].close_cmd()
|
||||
windows = self._windows
|
||||
while windows:
|
||||
window = windows[-1]
|
||||
window.destroy()
|
||||
assert not (windows and windows[-1] is window), \
|
||||
"%r failed to remove itself from application on destruction" % window
|
||||
self._quit()
|
||||
|
||||
#
|
||||
# Opening files
|
||||
#
|
||||
|
||||
def process_args(self, args):
|
||||
"""Process command line arguments. Called by run() when the application
|
||||
is starting up."""
|
||||
if not args:
|
||||
self.open_app()
|
||||
else:
|
||||
for arg in args:
|
||||
if os.path.exists(arg):
|
||||
arg = os.path.abspath(arg)
|
||||
self.open_path(arg)
|
||||
|
||||
def open_app(self):
|
||||
"""Called by run() when the application is opened with no arguments."""
|
||||
pass
|
||||
|
||||
def open_path(self, path):
|
||||
"""Open document specified by a pathname. Called for each command line
|
||||
argument when the application is starting up."""
|
||||
self.open_fileref(FileRef(path = path))
|
||||
|
||||
def open_fileref(self, fileref):
|
||||
"""Open document specified by a FileRef."""
|
||||
doc = self.make_file_document(fileref)
|
||||
if not doc:
|
||||
raise ApplicationError("The file '%s' is not recognised by %s." % (
|
||||
fileref.name, Globals.application_name))
|
||||
doc.set_file(fileref)
|
||||
try:
|
||||
doc.read()
|
||||
except EnvironmentError, e:
|
||||
raise ApplicationError("Unable to open '%s'." % fileref.name, e)
|
||||
self.make_window(doc)
|
||||
|
||||
#
|
||||
# Message dispatching
|
||||
#
|
||||
|
||||
# def dispatch(self, message, *args):
|
||||
# target_window = self._find_target_window()
|
||||
# if target_window:
|
||||
# target_window.dispatch(message, *args)
|
||||
# else:
|
||||
# self.handle(message, *args)
|
||||
|
||||
def dispatch(self, message, *args):
|
||||
self.target.handle(message, *args)
|
||||
|
||||
def dispatch_menu_command(self, command):
|
||||
if isinstance(command, tuple):
|
||||
name, index = command
|
||||
self.dispatch(name, index)
|
||||
else:
|
||||
self.dispatch(command)
|
||||
|
||||
def get_target(self):
|
||||
# Implementations may override this to locate the target in a
|
||||
# different way if they choose not to implement the Window.target
|
||||
# property. Should return self if no other target can be found.
|
||||
window = self.target_window
|
||||
if window:
|
||||
return window.target
|
||||
else:
|
||||
return self
|
||||
|
||||
def get_target_window(self):
|
||||
"""Return the window to which messages should be dispatched, or None."""
|
||||
raise NotImplementedError
|
||||
|
||||
#
|
||||
# Abstract
|
||||
#
|
||||
|
||||
def make_new_document(self):
|
||||
"""Create a new Document object of the appropriate
|
||||
class in response to a New command."""
|
||||
return self.make_document(None)
|
||||
|
||||
def make_file_document(self, fileref):
|
||||
"""Create a new Document object of the appropriate
|
||||
class for the given FileRef."""
|
||||
return self.make_document(fileref)
|
||||
|
||||
def make_document(self, fileref):
|
||||
"""Should create a new Document object of the appropriate
|
||||
class for the given FileRef, or if FileRef is None, a new
|
||||
empty Document of the appropriate class for the New command."""
|
||||
return None
|
||||
|
||||
def make_window(self, document):
|
||||
"""Should create a Window set up appropriately for viewing
|
||||
the given Document."""
|
||||
raise UnimplementedMethod(self, 'make_window')
|
||||
|
||||
#
|
||||
# Clipboard
|
||||
#
|
||||
|
||||
def query_clipboard(self):
|
||||
"Tests whether the clipboard contains any data."
|
||||
return not not self._clipboard
|
||||
|
||||
def get_clipboard(self):
|
||||
return self._clipboard
|
||||
|
||||
def set_clipboard(self, x):
|
||||
self._clipboard = x
|
||||
|
||||
#
|
||||
# Window list management
|
||||
#
|
||||
|
||||
def _add_window(self, window):
|
||||
if window not in self._windows:
|
||||
self._windows.append(window)
|
||||
|
||||
def _remove_window(self, window):
|
||||
if window in self._windows:
|
||||
self._windows.remove(window)
|
||||
|
||||
#
|
||||
# Document list management
|
||||
#
|
||||
|
||||
def _add_document(self, doc):
|
||||
if doc not in self._documents:
|
||||
self._documents.append(doc)
|
||||
|
||||
def _remove_document(self, doc):
|
||||
if doc in self._documents:
|
||||
self._documents.remove(doc)
|
||||
|
||||
#
|
||||
# Exception reporting
|
||||
#
|
||||
|
||||
def report_error(self):
|
||||
"""Display an appropriate error message for the most recent
|
||||
exception caught."""
|
||||
try:
|
||||
raise
|
||||
except Cancel:
|
||||
pass
|
||||
except ApplicationError, e:
|
||||
from GUI.Alerts import stop_alert
|
||||
stop_alert(str(e))
|
||||
except:
|
||||
self.report_exception()
|
||||
|
||||
def report_exception(self):
|
||||
"""Display an alert box describing the most recent exception, and
|
||||
giving the options Continue, Traceback or Abort. Traceback displays
|
||||
a traceback and continues; Abort raises SystemExit."""
|
||||
try:
|
||||
exc_type, exc_val, exc_tb = sys.exc_info()
|
||||
exc_desc = "%s: %s" % (exc_type.__name__, exc_val)
|
||||
self.print_traceback(exc_desc, exc_tb)
|
||||
from GUI.Alerts import alert3
|
||||
message = "Sorry, something went wrong."
|
||||
result = alert3('stop', "%s\n\n%s" % (message, exc_desc),
|
||||
"Continue", "Abort", "Traceback",
|
||||
default = 1, cancel = None, width = 450, lines = 5)
|
||||
if result == 1: # Continue
|
||||
return
|
||||
elif result == -1: # Traceback
|
||||
self.display_traceback(exc_desc, exc_tb)
|
||||
return
|
||||
else: # Abort
|
||||
raise SystemExit
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
os._exit(1)
|
||||
except:
|
||||
print >>sys.stderr, "---------- Exception while reporting exception ----------"
|
||||
traceback.print_exc()
|
||||
print >>sys.stderr, "------------------ Original exception -------------------"
|
||||
traceback.print_exception(exc_type, exc_val, exc_tb)
|
||||
#os._exit(1)
|
||||
|
||||
def display_traceback(self, exc_desc, exc_tb):
|
||||
"""Display an exception description and traceback.
|
||||
TODO: display this in a scrolling window."""
|
||||
self.print_traceback(exc_desc, exc_tb)
|
||||
|
||||
def print_traceback(self, exc_desc, exc_tb):
|
||||
"""Print exception description and traceback to standard error."""
|
||||
import traceback
|
||||
sys.stderr.write("\nTraceback (most recent call last):\n")
|
||||
traceback.print_tb(exc_tb)
|
||||
sys.stderr.write("%s\n\n" % exc_desc)
|
||||
|
||||
#
|
||||
# Other
|
||||
#
|
||||
|
||||
def zero_windows_allowed(self):
|
||||
"""Platforms should implement this to return false if there
|
||||
must be at least one window open at all times. Returning false
|
||||
here forces the Quit command to be used instead of Close when
|
||||
there is only one window open."""
|
||||
# TODO: Move this somewhere more global.
|
||||
raise UnimplementedMethod(self, 'zero_windows_allowed')
|
||||
|
||||
def _perform_menu_setup(self, menus = None):
|
||||
"""Given a list of Menu objects, perform menu setup processing
|
||||
and update associated platform menus ready for popping up or
|
||||
pulling down."""
|
||||
if menus is None:
|
||||
menus = self._effective_menus()
|
||||
menu_state = MenuState(menus)
|
||||
menu_state.reset()
|
||||
self._dispatch_menu_setup(menu_state)
|
||||
for menu in menus:
|
||||
menu._update_platform_menu()
|
||||
|
||||
def _dispatch_menu_setup(self, menu_state):
|
||||
self.dispatch('_setup_menus', menu_state)
|
||||
|
||||
def _effective_menus(self):
|
||||
"""Return a list of the menus in effect for the currently active
|
||||
window, including both application-wide and window-specific menus,
|
||||
in an appropriate order according to platform conventions."""
|
||||
window = self.target_window
|
||||
return self._effective_menus_for_window(window)
|
||||
|
||||
def _effective_menus_for_window(self, window):
|
||||
"""Return a list of the menus in effect for the specified
|
||||
window, including both application-wide and window-specific menus,
|
||||
in an appropriate order according to platform conventions."""
|
||||
menus = self.menus
|
||||
if window:
|
||||
menus = menus + window.menus
|
||||
regular_menus = []
|
||||
special_menus = []
|
||||
for menu in menus:
|
||||
if menu.special:
|
||||
special_menus.insert(0, menu)
|
||||
else:
|
||||
regular_menus.append(menu)
|
||||
return regular_menus + special_menus
|
||||
|
||||
# def _may_close_a_window(self):
|
||||
# # On implementations where at least one window is needed in order to
|
||||
# # interact with the application, check whether closing a window would
|
||||
# # leave no more visible windows.
|
||||
# if self.zero_windows_allowed():
|
||||
# return True
|
||||
# count = 0
|
||||
# for window in self.windows:
|
||||
# if window.visible:
|
||||
# count += 1
|
||||
# if count >= 2:
|
||||
# return True
|
||||
# return False
|
||||
|
||||
def _check_for_no_windows(self):
|
||||
# On implementations where at least one window is needed in order to
|
||||
# interact with the application, check whether there are no more visible
|
||||
# windows and take appropriate action.
|
||||
if not self.zero_windows_allowed():
|
||||
for window in self.windows:
|
||||
if window.visible:
|
||||
return
|
||||
self.no_visible_windows()
|
||||
|
||||
def no_visible_windows(self):
|
||||
"""On platforms that require a window in order to interact with the
|
||||
application, this is called when there are no more visible windows.
|
||||
The default action is to close the application; subclasses may override
|
||||
it to take some other action, such as creating a new window."""
|
||||
self.quit_cmd()
|
||||
@@ -0,0 +1,117 @@
|
||||
#
|
||||
# Python GUI - Alert base class - Generic
|
||||
#
|
||||
|
||||
import textwrap
|
||||
from GUI import ModalDialog
|
||||
from GUI import Label
|
||||
|
||||
class BaseAlert(ModalDialog):
|
||||
|
||||
_wrapwidth = 50
|
||||
_minimum_width = 200
|
||||
_left_margin = 24
|
||||
_right_margin = 24
|
||||
_top_margin = 14
|
||||
_bottom_margin = 20
|
||||
_icon_spacing = 16
|
||||
_label_button_spacing = 20
|
||||
_default_width = 380
|
||||
_default_lines = 3
|
||||
|
||||
yes_button = None
|
||||
no_button = None
|
||||
other_button = None
|
||||
|
||||
def __init__(self, kind, prompt, width = None, lines = None,
|
||||
button_labels = None, default = None, cancel = None):
|
||||
#if width is None:
|
||||
# width = self._default_width
|
||||
#if lines is None:
|
||||
# lines = self._default_lines
|
||||
ModalDialog.__init__(self, style = 'alert')
|
||||
self.label = Label(text = self._wrap(prompt), lines = lines)
|
||||
if self.label.width < self._minimum_width:
|
||||
self.label.width = self._minimum_width
|
||||
self._create_buttons(*button_labels)
|
||||
#self.default_button = self._find_button(default)
|
||||
#self.cancel_button = self._find_button(cancel)
|
||||
self._layout(kind)
|
||||
|
||||
def _layout(self, kind):
|
||||
icon_width, icon_height = self._layout_icon(kind)
|
||||
label_left = self._left_margin
|
||||
if icon_width:
|
||||
label_left += icon_width + self._icon_spacing
|
||||
if self.label.height < icon_height:
|
||||
self.label.height = icon_height
|
||||
self.place(self.label,
|
||||
left = label_left,
|
||||
top = self._top_margin)# + icon_height/4)
|
||||
#_wrap_text(self.label, self._default_width - label_left - self._right_margin)
|
||||
self._layout_buttons()
|
||||
self.shrink_wrap(padding = (self._right_margin, self._bottom_margin))
|
||||
|
||||
def _layout_icon(self, kind):
|
||||
# Place icon for the given alert kind, if any, and return its size.
|
||||
# If there is no icon, return (0, 0).
|
||||
return (0, 0)
|
||||
|
||||
def _wrap(self, text):
|
||||
width = self._wrapwidth
|
||||
return "\n\n".join(
|
||||
[textwrap.fill(para, width)
|
||||
for para in text.split("\n\n")])
|
||||
|
||||
def _find_button(self, value):
|
||||
#print "BaseAlert._find_button:", value ###
|
||||
if value == 1:
|
||||
result = self.yes_button
|
||||
elif value == 0:
|
||||
result = self.no_button
|
||||
elif value == -1:
|
||||
result = self.other_button
|
||||
else:
|
||||
result = None
|
||||
#print "BaseAlert._find_button: result =", result ###
|
||||
return result
|
||||
|
||||
def yes(self):
|
||||
self.dismiss(1)
|
||||
|
||||
def no(self):
|
||||
self.dismiss(0)
|
||||
|
||||
def other(self):
|
||||
self.dismiss(-1)
|
||||
|
||||
#def _wrap_text(label, label_width):
|
||||
# hard_lines = [text.split()
|
||||
# for text in label.text.split("\n")]
|
||||
# words = hard_lines[0]
|
||||
# for hard_line in hard_lines[1:]:
|
||||
# words.append("\n")
|
||||
# words.extend(hard_line)
|
||||
# font = label.font
|
||||
# space_width = font.width(" ")
|
||||
# lines = []
|
||||
# line = []
|
||||
# line_width = 0
|
||||
# for word in words:
|
||||
# word_width = font.width(word)
|
||||
# if word == "\n" or (line_width > 0
|
||||
# and line_width + space_width + word_width > label_width):
|
||||
# lines.append(line)
|
||||
# line = []
|
||||
# line_width = 0
|
||||
# if word <> "\n":
|
||||
# line.append(word)
|
||||
# if line_width > 0:
|
||||
# line_width += space_width
|
||||
# line_width += word_width
|
||||
# if line:
|
||||
# lines.append(line)
|
||||
# label.text = "\n".join([" ".join(line) for line in lines])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#
|
||||
# Python GUI - Buttons - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Actions import Action
|
||||
from GUI import Control
|
||||
|
||||
class Button(Control, Action):
|
||||
""" A pushbutton control."""
|
||||
|
||||
style = overridable_property('style',
|
||||
"One of 'normal', 'default', 'cancel'")
|
||||
|
||||
def activate(self):
|
||||
"""Highlight the button momentarily and then perform its action."""
|
||||
self.flash()
|
||||
self.do_action()
|
||||
|
||||
def flash(self):
|
||||
"""Highlight the button momentarily as though it had been clicked,
|
||||
without performing the action."""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,55 @@
|
||||
#
|
||||
# Python GUI - Canvas Paths - Generic
|
||||
#
|
||||
|
||||
class CanvasPaths:
|
||||
# Mixin class providing generic implementations of
|
||||
# canvas path construction operators.
|
||||
|
||||
def __init__(self):
|
||||
self.newpath()
|
||||
|
||||
def newpath(self):
|
||||
self._path = []
|
||||
self._current_subpath = None
|
||||
self._current_point = (0, 0)
|
||||
|
||||
def moveto(self, x, y):
|
||||
self._current_subpath = None
|
||||
self._current_point = self._coords(x, y)
|
||||
|
||||
def rmoveto(self, dx, dy):
|
||||
x, y = self._current_point
|
||||
self.moveto(x + dx, y + dy)
|
||||
|
||||
def lineto(self, x, y):
|
||||
subpath = self._current_subpath
|
||||
if subpath is None:
|
||||
subpath = [self._current_point]
|
||||
self._path.append(subpath)
|
||||
self._current_subpath = subpath
|
||||
p = self._coords(x, y)
|
||||
subpath.append(p)
|
||||
self._current_point = p
|
||||
|
||||
def rlineto(self, dx, dy):
|
||||
x, y = self._current_point
|
||||
self.lineto(x + dx, y + dy)
|
||||
|
||||
def closepath(self):
|
||||
subpath = self._current_subpath
|
||||
if subpath:
|
||||
subpath.append(subpath[0])
|
||||
self._current_subpath = None
|
||||
|
||||
def get_current_point(self):
|
||||
return self._current_point
|
||||
|
||||
# Implementations may set _coords to one of the following
|
||||
|
||||
def _int_coords(self, x, y):
|
||||
return int(round(x)), int(round(y))
|
||||
|
||||
def _float_coords(self, x, y):
|
||||
return x, y
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
#
|
||||
# Python GUI - Drawing - Generic
|
||||
#
|
||||
|
||||
from GUI.StdColors import black, white
|
||||
from GUI.StdFonts import application_font
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
class Canvas(Properties):
|
||||
|
||||
_default_forecolor = black
|
||||
_default_backcolor = white
|
||||
_printing = False
|
||||
|
||||
pencolor = overridable_property('pencolor', "Current color for stroking paths.")
|
||||
fillcolor = overridable_property('fillcolor', "Current color for filling paths.")
|
||||
textcolor = overridable_property('textcolor', "Current color for drawint text.")
|
||||
forecolor = overridable_property('forecolor', "Sets pen, fill and text colors to the same color.")
|
||||
backcolor = overridable_property('backcolor', "Current color for erasing regions.")
|
||||
pensize = overridable_property('pensize', "Width of pen for framing and stroking.")
|
||||
font = overridable_property('font', "Font for drawing text.")
|
||||
current_point = overridable_property('current_point', "The current point, or None.")
|
||||
printing = overridable_property('printing', "True if drawing destination is a non-display device.")
|
||||
|
||||
#forecolor = overridable_property('forecolor', "Sets both pencolor and fillcolor.")
|
||||
|
||||
def __init__(self):
|
||||
self.newpath()
|
||||
|
||||
def get_printing(self):
|
||||
return self._printing
|
||||
|
||||
def initgraphics(self):
|
||||
self.set_forecolor(self._default_forecolor)
|
||||
self.set_backcolor(self._default_backcolor)
|
||||
self.set_pensize(1)
|
||||
self.set_font(application_font)
|
||||
|
||||
def set_forecolor(self, c):
|
||||
self.pencolor = c
|
||||
self.fillcolor = c
|
||||
self.textcolor = c
|
||||
|
||||
def rmoveto(self, dx, dy):
|
||||
x0, y0 = self._current_point()
|
||||
self.moveto(x0 + dx, y0 + dy)
|
||||
|
||||
def rlineto(self, dx, dy):
|
||||
x0, y0 = self.current_point
|
||||
self.lineto(x0 + dx, y0 + dy)
|
||||
|
||||
def curve(self, sp, cp1, cp2, ep):
|
||||
self.moveto(sp)
|
||||
self.curveto(cp1, cp2, ep)
|
||||
|
||||
def rcurveto(self, cp1, cp2, ep):
|
||||
x0, y0 = self.current_point
|
||||
x1, y1 = cp1
|
||||
x2, y2 = cp2
|
||||
x3, y3 = ep
|
||||
self.curveto(
|
||||
(x0 + x1, y0 + y1),
|
||||
(x0 + x2, y0 + y2),
|
||||
(x0 + x3, y0 + y3))
|
||||
|
||||
def fill_stroke(self):
|
||||
self.fill()
|
||||
self.stroke()
|
||||
|
||||
# Rectangles
|
||||
|
||||
def _pen_inset_rect(self, rect):
|
||||
l, t, r, b = rect
|
||||
p = 0.5 * self.pensize
|
||||
return (l + p, t + p, r - p, b - p)
|
||||
|
||||
def rect(self, rect):
|
||||
l, t, r, b = rect
|
||||
self.moveto(l, t)
|
||||
self.lineto(r, t)
|
||||
self.lineto(r, b)
|
||||
self.lineto(l, b)
|
||||
self.closepath()
|
||||
|
||||
def rect_frame(self, rect):
|
||||
self.rect(self._pen_inset_rect(rect))
|
||||
|
||||
def fill_rect(self, rect):
|
||||
self.newpath()
|
||||
self.rect(rect)
|
||||
self.fill()
|
||||
|
||||
def stroke_rect(self, rect):
|
||||
self.newpath()
|
||||
self.rect(rect)
|
||||
self.stroke()
|
||||
|
||||
def frame_rect(self, rect):
|
||||
self.newpath()
|
||||
self.rect_frame(rect)
|
||||
self.stroke()
|
||||
|
||||
def fill_stroke_rect(self, rect):
|
||||
self.rect_path(rect)
|
||||
self.fill_stroke()
|
||||
|
||||
def fill_frame_rect(self, rect):
|
||||
self.fill_rect(rect)
|
||||
self.frame_rect(rect)
|
||||
|
||||
def erase_rect(self, rect):
|
||||
self.newpath()
|
||||
self.rect(rect)
|
||||
self.erase()
|
||||
|
||||
# Ovals
|
||||
|
||||
def oval_frame(self, rect):
|
||||
self.oval(self._pen_inset_rect(rect))
|
||||
|
||||
def fill_oval(self, rect):
|
||||
self.newpath()
|
||||
self.oval_frame(rect)
|
||||
self.fill()
|
||||
|
||||
def stroke_oval(self, rect):
|
||||
self.newpath()
|
||||
self.oval(rect)
|
||||
self.stroke()
|
||||
|
||||
def frame_oval(self, rect):
|
||||
self.newpath()
|
||||
self.oval_frame(rect)
|
||||
self.stroke()
|
||||
|
||||
def fill_stroke_oval(self, rect):
|
||||
self.newpath()
|
||||
self.oval(rect)
|
||||
self.fill_stroke()
|
||||
|
||||
def fill_frame_oval(self, rect):
|
||||
self.fill_oval(rect)
|
||||
self.frame_oval()
|
||||
|
||||
def erase_oval(self, rect):
|
||||
self.newpath()
|
||||
self.oval(rect)
|
||||
self.erase()
|
||||
|
||||
# Arcs
|
||||
|
||||
def _arc_path(self, c, r, a0, a1):
|
||||
# x, y = c
|
||||
# a0r = a0 * deg
|
||||
# x0 = x + r * cos(a0r)
|
||||
# y0 = y + r * sin(a0r)
|
||||
self.newpath()
|
||||
# self.moveto(x0, y0)
|
||||
self.arc(c, r, a0, a1)
|
||||
|
||||
def _arc_frame_path(self, c, r, a0, a1):
|
||||
self._arc_path(c, r - 0.5 * self.pensize, a0, a1)
|
||||
|
||||
def stroke_arc(self, c, r, a0, a1):
|
||||
self._arc_path(c, r, a0, a1)
|
||||
self.stroke()
|
||||
|
||||
def frame_arc(self, c, r, a0, a1):
|
||||
self._arc_frame_path(c, r, a0, a1)
|
||||
self.stroke()
|
||||
|
||||
# Wedges
|
||||
|
||||
def wedge(self, c, r, a0, a1):
|
||||
self.moveto(*c)
|
||||
self.arc(c, r, a0, a1)
|
||||
self.closepath()
|
||||
|
||||
def fill_wedge(self, c, r, a0, a1):
|
||||
self.newpath()
|
||||
self.wedge(c, r, a0, a1)
|
||||
self.fill()
|
||||
|
||||
def stroke_wedge(self, c, r, a0, a1):
|
||||
self.newpath()
|
||||
self.wedge(c, r, a0, a1)
|
||||
self.stroke()
|
||||
|
||||
def fill_stroke_wedge(self, c, r, a0, a1):
|
||||
self.newpath()
|
||||
self.wedge(c, r, a0, a1)
|
||||
self.fill_stroke()
|
||||
|
||||
def erase_wedge(self, c, r, a0, a1):
|
||||
self.newpath()
|
||||
self.wedge(c, r, a0, a1)
|
||||
self.erase()
|
||||
|
||||
# Polylines
|
||||
|
||||
def lines(self, points):
|
||||
point_iter = iter(points)
|
||||
self.moveto(*point_iter.next())
|
||||
for p in point_iter:
|
||||
self.lineto(*p)
|
||||
|
||||
def linesto(self, points):
|
||||
for p in points:
|
||||
self.lineto(*p)
|
||||
|
||||
def stroke_lines(self, points):
|
||||
self.newpath()
|
||||
self.lines(points)
|
||||
self.stroke()
|
||||
|
||||
# Polycurves
|
||||
|
||||
def curves(self, points):
|
||||
self.moveto(*points[0])
|
||||
for i in xrange(1, len(points), 3):
|
||||
self.curveto(*points[i:i+3])
|
||||
|
||||
def curvesto(self, points):
|
||||
for i in xrange(0, len(points), 3):
|
||||
self.curveto(*points[i:i+3])
|
||||
|
||||
def stroke_curves(self, points):
|
||||
self.newpath()
|
||||
self.curves(points)
|
||||
self.stroke()
|
||||
|
||||
# Polygons
|
||||
|
||||
def poly(self, points):
|
||||
self.lines(points)
|
||||
self.closepath()
|
||||
|
||||
def fill_poly(self, points):
|
||||
self.newpath()
|
||||
self.poly(points)
|
||||
self.fill()
|
||||
|
||||
def stroke_poly(self, points):
|
||||
self.newpath()
|
||||
self.poly(points)
|
||||
self.stroke()
|
||||
|
||||
def fill_stroke_poly(self, points):
|
||||
self.newpath()
|
||||
self.poly(points)
|
||||
self.fill_stroke()
|
||||
|
||||
def erase_poly(self, points):
|
||||
self.newpath()
|
||||
self.poly(points)
|
||||
self.erase()
|
||||
|
||||
# Loops
|
||||
|
||||
def loop(self, points):
|
||||
self.curves(points)
|
||||
self.closepath()
|
||||
|
||||
def fill_loop(self, points):
|
||||
self.newpath()
|
||||
self.loop(points)
|
||||
self.fill()
|
||||
|
||||
def stroke_loop(self, points):
|
||||
self.newpath()
|
||||
self.loop(points)
|
||||
self.stroke()
|
||||
|
||||
def fill_stroke_loop(self, points):
|
||||
self.newpath()
|
||||
self.loop(points)
|
||||
self.fill_stroke()
|
||||
|
||||
def erase_loop(self, points):
|
||||
self.newpath()
|
||||
self.loop(points)
|
||||
self.erase()
|
||||
@@ -0,0 +1,43 @@
|
||||
#
|
||||
# Python GUI - Check boxes - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Control
|
||||
from GUI.Actions import Action
|
||||
|
||||
class CheckBox(Control, Action):
|
||||
"""A CheckBox is a control used to represent a binary choice."""
|
||||
|
||||
def __init__(self, **kwds):
|
||||
Control.__init__(self, **kwds)
|
||||
|
||||
on = overridable_property('on', "Boolean value of the check box.")
|
||||
|
||||
auto_toggle = overridable_property('auto_toggle', """If true,
|
||||
the check box's 'on' property will automatically be toggled
|
||||
before performing the action, if any.""")
|
||||
|
||||
mixed = overridable_property('mixed', """If true, the check box
|
||||
is capable of displaying a mixed state.""")
|
||||
|
||||
_auto_toggle = True
|
||||
_mixed = False
|
||||
|
||||
def get_auto_toggle(self):
|
||||
return self._auto_toggle
|
||||
|
||||
def set_auto_toggle(self, v):
|
||||
self._auto_toggle = v
|
||||
|
||||
def get_mixed(self):
|
||||
return self._mixed
|
||||
|
||||
def set_mixed(self, v):
|
||||
self._mixed = v
|
||||
|
||||
def get_value(self):
|
||||
return self.on
|
||||
|
||||
def set_value(self, x):
|
||||
self.on = x
|
||||
@@ -0,0 +1,46 @@
|
||||
#
|
||||
# Python GUI - Colors - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
|
||||
class Color(object):
|
||||
"""A drawing color.
|
||||
|
||||
Constructors:
|
||||
rgb(red, green, blue, alpha = 1.0)
|
||||
where red, green, blue, alpha are in the range 0.0 to 1.0
|
||||
|
||||
Properties:
|
||||
red --> float
|
||||
green --> float
|
||||
blue --> float
|
||||
rgb --> (red, green, blue)
|
||||
rgba --> (red, green, blue, alpha)
|
||||
"""
|
||||
|
||||
red = overridable_property('red', "Red component (0.0 to 1.0)")
|
||||
green = overridable_property('green', "Blue component (0.0 to 1.0)")
|
||||
blue = overridable_property('blue', "Blue component (0.0 to 1.0)")
|
||||
alpha = overridable_property('alpha', "Alpha (opacity) component")
|
||||
rgb = overridable_property('rgb', "Tuple of (red, green, blue) (0.0 to 1.0)")
|
||||
rgba = overridable_property('rgba',
|
||||
"Tuple of (red, green, blue, alpha) (0.0 to 1.0)")
|
||||
|
||||
def get_alpha(self):
|
||||
return 1.0
|
||||
|
||||
def get_rgb(self):
|
||||
return (self.red, self.green, self.blue)
|
||||
|
||||
def set_rgb(self, x):
|
||||
self.red, self.green, self.blue = x
|
||||
|
||||
def get_rgba(self):
|
||||
return (self.red, self.green, self.blue, self.alpha)
|
||||
|
||||
def set_rgba(self, x):
|
||||
self.red, self.green, self.blue, self.alpha = x
|
||||
|
||||
def __str__(self):
|
||||
return "Color(%g,%g,%g,%g)" % self.rgba
|
||||
@@ -0,0 +1,477 @@
|
||||
#
|
||||
# Python GUI - Components - Generic
|
||||
#
|
||||
|
||||
import os
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
from GUI import MessageHandler
|
||||
from GUI.Geometry import add_pt, sub_pt, rect_size, rect_sized, rect_topleft
|
||||
from GUI import application
|
||||
|
||||
_user_tab_stop = os.environ.get("PYGUI_KEYBOARD_NAVIGATION") or None
|
||||
# Allow "False", "True", "0", "1"
|
||||
if _user_tab_stop is not None:
|
||||
_user_tab_stop = _user_tab_stop.strip().capitalize()
|
||||
try:
|
||||
_user_tab_stop = {"False": False, "True": True}[_user_tab_stop]
|
||||
except KeyError:
|
||||
try:
|
||||
_user_tab_stop = int(_user_tab_stop)
|
||||
except ValueError:
|
||||
sys.stderr.write("PYGUI_KEYBOARD_NAVIGATION: Unrecognized value %r"
|
||||
% _user_tab_stop)
|
||||
_user_tab_stop = None
|
||||
|
||||
class Component(Properties, MessageHandler):
|
||||
"""Component is an abstract class representing a user
|
||||
interface component."""
|
||||
|
||||
left = overridable_property('left', "Position of left edge relative to container.")
|
||||
top = overridable_property('top', "Position of top edge relative to container.")
|
||||
right = overridable_property('right', "Position of right edge relative to container.")
|
||||
bottom = overridable_property('bottom', "Position of bottom edge relative to container.")
|
||||
|
||||
x = overridable_property('x', "Horizontal position relative to container.")
|
||||
y = overridable_property('y', "Vertical position relative to container.")
|
||||
width = overridable_property('width')
|
||||
height = overridable_property('height')
|
||||
|
||||
position = overridable_property('position', "Position relative to container.")
|
||||
size = overridable_property('size')
|
||||
|
||||
bounds = overridable_property('bounds', "Bounding rectangle in container's coordinates.")
|
||||
|
||||
container = overridable_property('container',
|
||||
"Container which contains this Component. Setting this property has the "
|
||||
"effect of removing the component from its previous container, if any, "
|
||||
"and adding it to the new one, if any.")
|
||||
|
||||
# visible = overridable_property('visible',
|
||||
# "Whether the component is currently shown.")
|
||||
|
||||
tab_stop = overridable_property('tab_stop',
|
||||
"Whether tab key can navigate into this control.")
|
||||
|
||||
anchor = overridable_property('anchor', "A string of 'ltrb' controlling behaviour when container is resized.")
|
||||
|
||||
border = overridable_property('border', "True if the component should have a border.")
|
||||
|
||||
_is_scrollable = False # Overridden by scrollable subclasses
|
||||
_generic_tabbing = True # Whether to use generic tab navigation code
|
||||
_default_tab_stop = False
|
||||
_user_tab_stop_override = False # Whether user preference overrides _default_tab_stop
|
||||
_tab_stop = None
|
||||
|
||||
#
|
||||
# Class variables defined by implementations:
|
||||
#
|
||||
# _has_local_coords bool True if component has a local coordinate system
|
||||
#
|
||||
|
||||
_container = None
|
||||
_border = False
|
||||
hmove = 0
|
||||
vmove = 0
|
||||
hstretch = 0
|
||||
vstretch = 0
|
||||
|
||||
def __init__(self, tab_stop = None, **kwds):
|
||||
Properties.__init__(self, **kwds)
|
||||
if tab_stop is None:
|
||||
tab_stop = self._get_default_tab_stop()
|
||||
self.tab_stop = tab_stop
|
||||
|
||||
def destroy(self):
|
||||
self.container = None
|
||||
|
||||
#
|
||||
# Geometry properties
|
||||
#
|
||||
# Default implementations of position and size properties
|
||||
# in terms of the bounds property. A minimal implementation
|
||||
# need only implement get_bounds and set_bounds.
|
||||
#
|
||||
# It is the implementation's responsibility to call _resized()
|
||||
# whenever the size of the component changes, either by
|
||||
# explicit assignment to geometry properties or by the user
|
||||
# resizing the containing window. It should not be called if
|
||||
# setting a geometry property does not cause the size to change.
|
||||
#
|
||||
|
||||
def get_left(self):
|
||||
return self.position[0]
|
||||
|
||||
def set_left(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (v, t, r, b)
|
||||
|
||||
def get_top(self):
|
||||
return self.bounds[1]
|
||||
|
||||
def set_top(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, v, r, b)
|
||||
|
||||
def get_right(self):
|
||||
return self.bounds[2]
|
||||
|
||||
def set_right(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, t, v, b)
|
||||
|
||||
def get_bottom(self):
|
||||
return self.bounds[3]
|
||||
|
||||
def set_bottom(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, t, r, v)
|
||||
|
||||
def get_x(self):
|
||||
return self.bounds[0]
|
||||
|
||||
def set_x(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (v, t, v + r - l, b)
|
||||
|
||||
def get_y(self):
|
||||
return self.bounds[1]
|
||||
|
||||
def set_y(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, v, r, v + b - t)
|
||||
|
||||
def get_position(self):
|
||||
l, t, r, b = self.bounds
|
||||
return (l, t)
|
||||
|
||||
def set_position(self, (x, y)):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (x, y, x + r - l, y + b - t)
|
||||
|
||||
def get_width(self):
|
||||
l, t, r, b = self.bounds
|
||||
return r - l
|
||||
|
||||
def set_width(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, t, l + v, b)
|
||||
|
||||
def get_height(self):
|
||||
l, t, r, b = self.bounds
|
||||
return b - t
|
||||
|
||||
def set_height(self, v):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, t, r, t + v)
|
||||
|
||||
def get_size(self):
|
||||
l, t, r, b = self.bounds
|
||||
return (r - l, b - t)
|
||||
|
||||
def set_size(self, (w, h)):
|
||||
l, t, r, b = self.bounds
|
||||
self.bounds = (l, t, l + w, t + h)
|
||||
|
||||
#
|
||||
# Container management
|
||||
#
|
||||
|
||||
def get_container(self):
|
||||
return self._container
|
||||
|
||||
def set_container(self, new_container):
|
||||
if self._container != new_container:
|
||||
self._change_container(new_container)
|
||||
|
||||
def _change_container(self, new_container):
|
||||
old_container = self._container
|
||||
if old_container:
|
||||
self._container = None
|
||||
old_container._remove(self)
|
||||
if new_container:
|
||||
self._container = new_container
|
||||
new_container._add(self)
|
||||
|
||||
#
|
||||
# Message dispatching
|
||||
#
|
||||
|
||||
def become_target(self):
|
||||
"""Arrange for this object to be the first to handle messages
|
||||
dispatched to the containing Window. If the component is not
|
||||
contained in a Window, the effect is undefined."""
|
||||
raise NotImplementedError
|
||||
|
||||
def is_target(self):
|
||||
"""Return true if this is the current target within the containing
|
||||
Window. If the component is not contained in a Window, the result
|
||||
is undefined."""
|
||||
return self.window and self.window.target is self
|
||||
|
||||
#
|
||||
# Message handling
|
||||
#
|
||||
|
||||
def next_handler(self):
|
||||
return self._container
|
||||
|
||||
#
|
||||
# Visibility control
|
||||
#
|
||||
|
||||
# def show(self):
|
||||
# """Make the Component visible (provided its container is visible)."""
|
||||
# self.visible = 1
|
||||
#
|
||||
# def hide(self):
|
||||
# """Make the Component invisible."""
|
||||
# self.visible = 0
|
||||
|
||||
#
|
||||
# Border
|
||||
#
|
||||
|
||||
def get_border(self):
|
||||
return self._border
|
||||
|
||||
def set_border(self, x):
|
||||
self._border = x
|
||||
|
||||
#
|
||||
# Resizing
|
||||
#
|
||||
|
||||
def get_anchor(self):
|
||||
if self.hmove:
|
||||
s1 = 'r'
|
||||
elif self.hstretch:
|
||||
s1 = 'lr'
|
||||
else:
|
||||
s1 = 'l'
|
||||
if self.vmove:
|
||||
s2 = 'b'
|
||||
elif self.vstretch:
|
||||
s2 = 'tb'
|
||||
else:
|
||||
s2 = 't'
|
||||
return s1 + s2
|
||||
|
||||
def set_anchor(self, s):
|
||||
if 'r' in s:
|
||||
if 'l' in s:
|
||||
self.hstretch = True
|
||||
self.hmove = False
|
||||
else:
|
||||
self.hstretch = False
|
||||
self.hmove = True
|
||||
else:
|
||||
self.hstretch = False
|
||||
self.hmove = False
|
||||
if 'b' in s:
|
||||
if 't' in s:
|
||||
self.vstretch = True
|
||||
self.vmove = False
|
||||
else:
|
||||
self.vstretch = False
|
||||
self.vmove = True
|
||||
else:
|
||||
self.vstretch = False
|
||||
self.vmove = False
|
||||
|
||||
def get_auto_layout(self):
|
||||
return self._auto_layout
|
||||
|
||||
def set_auto_layout(self, x):
|
||||
self._auto_layout = x
|
||||
|
||||
def _resized(self, delta):
|
||||
# Called whenever the size of the component changes for
|
||||
# any reason.
|
||||
pass
|
||||
|
||||
def container_resized(self, delta):
|
||||
"""Called whenever the component's container changes size and the
|
||||
container's auto_layout property is true. The default implementation
|
||||
repositions and resizes this component according to its resizing
|
||||
options."""
|
||||
dw, dh = delta
|
||||
left, top, right, bottom = self.bounds
|
||||
if self.hmove:
|
||||
left += dw
|
||||
right += dw
|
||||
elif self.hstretch:
|
||||
right += dw
|
||||
if self.vmove:
|
||||
top += dh
|
||||
bottom += dh
|
||||
elif self.vstretch:
|
||||
bottom += dh
|
||||
self.bounds = (left, top, right, bottom)
|
||||
|
||||
#
|
||||
# Update region maintenance
|
||||
#
|
||||
|
||||
def invalidate(self):
|
||||
"""Mark the whole Component as needing to be redrawn."""
|
||||
self.invalidate_rect(self.viewed_rect())
|
||||
|
||||
# def invalidate_rect(self, r):
|
||||
# print "GComponent.invalidate_rect:", self, r ###
|
||||
# container = self._container
|
||||
# if container:
|
||||
# container.invalidate_rect(r)
|
||||
|
||||
# def _invalidate_in_container(self):
|
||||
# container = self._container
|
||||
# if container:
|
||||
# container._invalidate_subcomponent(self)
|
||||
|
||||
#
|
||||
# Coordinate transformation
|
||||
#
|
||||
|
||||
def local_to_global(self, p):
|
||||
p = self.local_to_container(p)
|
||||
parent = self._container
|
||||
if parent:
|
||||
return parent.local_to_global(p)
|
||||
else:
|
||||
return p
|
||||
|
||||
def global_to_local(self, p):
|
||||
parent = self._container
|
||||
if parent:
|
||||
p = parent.global_to_local(p)
|
||||
return self.container_to_local(p)
|
||||
|
||||
def local_to_container(self, p):
|
||||
if self._has_local_coords:
|
||||
return add_pt(p, self.local_to_container_offset())
|
||||
else:
|
||||
return p
|
||||
|
||||
def container_to_local(self, p):
|
||||
if self._has_local_coords:
|
||||
return sub_pt(p, self.local_to_container_offset())
|
||||
else:
|
||||
return p
|
||||
|
||||
def local_to_container_offset(self):
|
||||
if self._has_local_coords:
|
||||
return self.position
|
||||
else:
|
||||
return (0, 0)
|
||||
|
||||
def transform_from(self, other, p):
|
||||
return transform_coords(other, self, p)
|
||||
|
||||
def transform_to(self, other, p):
|
||||
return transform_coords(self, other, p)
|
||||
|
||||
#
|
||||
# Placement specification support
|
||||
#
|
||||
|
||||
def __add__(self, offset):
|
||||
return (self, offset)
|
||||
|
||||
def __sub__(self, offset):
|
||||
return (self, -offset)
|
||||
|
||||
#
|
||||
# Tabbing
|
||||
#
|
||||
|
||||
# def get_tabbable(self):
|
||||
# return self._tabbable
|
||||
#
|
||||
# def set_tabbable(self, value):
|
||||
# if self._tabbable <> value:
|
||||
# self._tabbable = value
|
||||
# self._invalidate_tab_chain()
|
||||
|
||||
def get_tab_stop(self):
|
||||
return self._tab_stop
|
||||
|
||||
def set_tab_stop(self, x):
|
||||
if self._tab_stop <> x:
|
||||
self._tab_stop = x
|
||||
self._invalidate_tab_chain()
|
||||
|
||||
def _get_default_tab_stop(self):
|
||||
if self._user_tab_stop_override:
|
||||
result = _user_tab_stop
|
||||
else:
|
||||
result = None
|
||||
if result is None:
|
||||
result = self._default_tab_stop
|
||||
return result
|
||||
|
||||
def _tab_out(self):
|
||||
pass
|
||||
|
||||
def _tab_in(self):
|
||||
self.become_target()
|
||||
|
||||
def _build_tab_chain(self, chain):
|
||||
if self._tab_stop:
|
||||
chain.append(self)
|
||||
|
||||
def _invalidate_tab_chain(self):
|
||||
window = self.window
|
||||
if window:
|
||||
window._invalidate_tab_chain()
|
||||
|
||||
def _is_targetable(self):
|
||||
return True
|
||||
|
||||
#
|
||||
# Other
|
||||
#
|
||||
|
||||
window = overridable_property('window', """The Window ultimately containing
|
||||
this Component, or None.""")
|
||||
|
||||
def get_window(self):
|
||||
container = self._container
|
||||
if container:
|
||||
return container.window
|
||||
else:
|
||||
return None
|
||||
|
||||
def reset_blink(self):
|
||||
application().reset_blink()
|
||||
|
||||
def viewed_rect(self):
|
||||
"""Returns the rectangle in local coordinates that is
|
||||
currently visible within the component."""
|
||||
if self._has_local_coords:
|
||||
width, height = self.size
|
||||
return (0, 0, width, height)
|
||||
else:
|
||||
return self.bounds
|
||||
|
||||
def broadcast(self, message, *args):
|
||||
"""Traverse the component hierarchy, calling each component's handler for
|
||||
the given message, if any."""
|
||||
method = getattr(self, message, None)
|
||||
if method:
|
||||
method(*args)
|
||||
|
||||
def _dispatch_mouse_event(self, event):
|
||||
self._handle_mouse_event(event)
|
||||
|
||||
def _handle_mouse_event(self, event):
|
||||
self.handle(event.kind, event)
|
||||
|
||||
|
||||
def transform_coords(from_component, to_component, p):
|
||||
if from_component:
|
||||
g = from_component.local_to_global(p)
|
||||
else:
|
||||
g = p
|
||||
if to_component:
|
||||
return to_component.global_to_local(g)
|
||||
else:
|
||||
return g
|
||||
@@ -0,0 +1,382 @@
|
||||
#
|
||||
# Python GUI - Containers - Generic
|
||||
#
|
||||
|
||||
try:
|
||||
maketrans = str.maketrans
|
||||
except AttributeError:
|
||||
from string import maketrans
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Exceptions import ArgumentError
|
||||
from GUI.Geometry import pt_in_rect
|
||||
from GUI import Component
|
||||
|
||||
anchor_to_sticky = maketrans("ltrb", "wnes")
|
||||
|
||||
class Container(Component):
|
||||
"""A Container is a Component that can contain other Components.
|
||||
The sub-components are clipped to the boundary of their container."""
|
||||
|
||||
contents = overridable_property('contents',
|
||||
"List of subcomponents. Do not modify directly.")
|
||||
|
||||
content_width = overridable_property('content_width', "Width of the content area.")
|
||||
content_height = overridable_property('content_height', "Height of the content area.")
|
||||
content_size = overridable_property('content_size', "Size of the content area.")
|
||||
|
||||
auto_layout = overridable_property('auto_layout',
|
||||
"Automatically adjust layout of subcomponents when resized.")
|
||||
|
||||
_auto_layout = True
|
||||
|
||||
# _contents [Component]
|
||||
|
||||
def __init__(self, **kw):
|
||||
self._contents = []
|
||||
Component.__init__(self, **kw)
|
||||
|
||||
def destroy(self):
|
||||
"""Destroy this Container and all of its contents."""
|
||||
contents = self._contents
|
||||
while contents:
|
||||
comp = contents[-1]
|
||||
comp.destroy()
|
||||
assert not contents or contents[-1] is not comp, \
|
||||
"%r failed to remove itself from container on destruction" % comp
|
||||
Component.destroy(self)
|
||||
|
||||
#
|
||||
# Content area
|
||||
#
|
||||
|
||||
def get_content_width(self):
|
||||
return self.content_size[0]
|
||||
|
||||
def set_content_width(self, w):
|
||||
self.content_size = w, self.content_height
|
||||
|
||||
def get_content_height(self):
|
||||
return self.content_size[1]
|
||||
|
||||
def set_content_height(self, h):
|
||||
self.content_size = self.content_width, h
|
||||
|
||||
get_content_size = Component.get_size
|
||||
set_content_size = Component.set_size
|
||||
|
||||
#
|
||||
# Subcomponent Management
|
||||
#
|
||||
|
||||
def get_contents(self):
|
||||
return self._contents
|
||||
|
||||
def add(self, comp):
|
||||
"""Add the given Component as a subcomponent."""
|
||||
if comp:
|
||||
if isinstance(comp, Component):
|
||||
comp.container = self
|
||||
else:
|
||||
for item in comp:
|
||||
self.add(item)
|
||||
|
||||
def remove(self, comp):
|
||||
"""Remove subcomponent, if present."""
|
||||
if isinstance(comp, Component):
|
||||
if comp in self._contents:
|
||||
comp.container = None
|
||||
else:
|
||||
for item in comp:
|
||||
self.remove(item)
|
||||
|
||||
def _add(self, comp):
|
||||
# Called by comp.set_container() to implement subcomponent addition.
|
||||
self._contents.append(comp)
|
||||
self._invalidate_tab_chain()
|
||||
self.added(comp)
|
||||
|
||||
def _remove(self, comp):
|
||||
# Called by comp.set_container() to implement subcomponent removal.
|
||||
self._contents.remove(comp)
|
||||
self._invalidate_tab_chain()
|
||||
self.removed(comp)
|
||||
|
||||
def added(self, comp):
|
||||
"""Called after a subcomponent has been added."""
|
||||
pass
|
||||
|
||||
def removed(self, comp):
|
||||
"""Called after a subcomponent has been removed."""
|
||||
pass
|
||||
|
||||
#
|
||||
# The infamous 'place' method and friends.
|
||||
#
|
||||
|
||||
_place_default_spacing = 8
|
||||
|
||||
def place(self, item,
|
||||
left = None, right = None, top = None, bottom = None,
|
||||
sticky = 'nw', scrolling = '', border = None, anchor = None):
|
||||
"""Add a component to the frame with positioning,
|
||||
resizing and scrolling options. See the manual for details."""
|
||||
self._place([item], left = left, right = right, top = top, bottom = bottom,
|
||||
sticky = sticky, scrolling = scrolling, border = border, anchor = anchor)
|
||||
|
||||
def place_row(self, items,
|
||||
left = None, right = None, top = None, bottom = None,
|
||||
sticky = 'nw', scrolling = '', border = None, spacing = None,
|
||||
anchor = None):
|
||||
"""Add a row of components to the frame with positioning,
|
||||
resizing and scrolling options. See the manual for details."""
|
||||
if left is not None and right is not None:
|
||||
raise ValueError("Cannot specify both left and right to place_row")
|
||||
elif left is None and right is not None:
|
||||
direction = 'left'
|
||||
items = items[:]
|
||||
items.reverse()
|
||||
else:
|
||||
direction = 'right'
|
||||
self._place(items, left = left, right = right, top = top, bottom = bottom,
|
||||
sticky = sticky, scrolling = scrolling, border = border,
|
||||
direction = direction, spacing = spacing, anchor = anchor)
|
||||
|
||||
def place_column(self, items,
|
||||
left = None, right = None, top = None, bottom = None,
|
||||
sticky = 'nw', scrolling = '', border = None, spacing = None,
|
||||
anchor = None):
|
||||
"""Add a column of components to the frame with positioning,
|
||||
resizing and scrolling options. See the manual for details."""
|
||||
if top is not None and bottom is not None:
|
||||
raise ValueError("Cannot specify both top and bottom to place_column")
|
||||
elif top is None and bottom is not None:
|
||||
direction = 'up'
|
||||
items = items[:]
|
||||
items.reverse()
|
||||
else:
|
||||
direction = 'down'
|
||||
self._place(items, left = left, right = right, top = top, bottom = bottom,
|
||||
sticky = sticky, scrolling = scrolling, border = border,
|
||||
direction = direction, spacing = spacing, anchor = anchor)
|
||||
|
||||
def _place(self, items,
|
||||
left = None,
|
||||
right = None,
|
||||
top = None,
|
||||
bottom = None,
|
||||
sticky = 'nw',
|
||||
scrolling = '',
|
||||
direction = 'right',
|
||||
spacing = None,
|
||||
border = None,
|
||||
anchor = None):
|
||||
|
||||
def side(spec, name):
|
||||
# Process a side specification taking the form of either
|
||||
# (1) an offset, (2) a reference component, or (3) a
|
||||
# tuple (component, offset). Returns a tuple (ref, offset)
|
||||
# where ref is the reference component or None (representing
|
||||
# the Frame being placed into). Checks that the reference
|
||||
# component, if any, is directly contained by this Frame.
|
||||
ref = None
|
||||
offset = None
|
||||
if spec is not None:
|
||||
if isinstance(spec, tuple):
|
||||
ref, offset = spec
|
||||
elif isinstance(spec, Component):
|
||||
ref = spec
|
||||
offset = 0
|
||||
elif isinstance(spec, (int, float)):
|
||||
offset = spec
|
||||
else:
|
||||
raise ArgumentError(self, 'place', name, spec)
|
||||
if ref is self:
|
||||
ref = None
|
||||
elif ref:
|
||||
con = ref.container
|
||||
#if con is not self and isinstance(con, ScrollFrame):
|
||||
# ref = con
|
||||
# con = ref.container
|
||||
if con is not self:
|
||||
raise ValueError("Reference component for place() is not"
|
||||
" directly contained by the frame being placed into.")
|
||||
return ref, offset
|
||||
|
||||
if spacing is None:
|
||||
spacing = self._place_default_spacing
|
||||
|
||||
# Decode the sticky options
|
||||
if anchor is not None:
|
||||
sticky = anchor.translate(anchor_to_sticky)
|
||||
hmove = vmove = hstretch = vstretch = 0
|
||||
if 'e' in sticky:
|
||||
if 'w' in sticky:
|
||||
hstretch = 1
|
||||
else:
|
||||
hmove = 1
|
||||
if 's' in sticky:
|
||||
if 'n' in sticky:
|
||||
vstretch = 1
|
||||
else:
|
||||
vmove = 1
|
||||
|
||||
# Translate the direction argument
|
||||
try:
|
||||
dir = {'right':0, 'down':1, 'left':2, 'up':3}[direction]
|
||||
except KeyError:
|
||||
raise ArgumentError(self, 'place', 'direction', direction)
|
||||
|
||||
# Unpack the side arguments
|
||||
left_obj, left_off = side(left, 'left')
|
||||
right_obj, right_off = side(right, 'right')
|
||||
top_obj, top_off = side(top, 'top')
|
||||
bottom_obj, bottom_off = side(bottom, 'bottom')
|
||||
|
||||
# Process the items
|
||||
#if not isinstance(items, list):
|
||||
# items = [items]
|
||||
for item in items:
|
||||
x, y = item.position
|
||||
w, h = item.size
|
||||
# Calculate left edge position
|
||||
if left_obj:
|
||||
l = left_obj.left + left_obj.width + left_off
|
||||
elif left_off is not None:
|
||||
if left_off < 0:
|
||||
l = self.width + left_off
|
||||
else:
|
||||
l = left_off
|
||||
else:
|
||||
l = None
|
||||
# Calculate top edge position
|
||||
if top_obj:
|
||||
t = top_obj.top + top_obj.height + top_off
|
||||
elif top_off is not None:
|
||||
if top_off < 0:
|
||||
t = self.height + top_off
|
||||
else:
|
||||
t = top_off
|
||||
else:
|
||||
t = None
|
||||
# Calculate right edge position
|
||||
if right_obj:
|
||||
r = right_obj.left + right_off
|
||||
elif right_off is not None:
|
||||
if right_off <= 0:
|
||||
r = self.width + right_off
|
||||
else:
|
||||
r = right_off
|
||||
else:
|
||||
r = None
|
||||
# Calculate bottom edge position
|
||||
if bottom_obj:
|
||||
b = bottom_obj.top + bottom_off
|
||||
elif bottom_off is not None:
|
||||
if bottom_off <= 0:
|
||||
b = self.height + bottom_off
|
||||
else:
|
||||
b = bottom_off
|
||||
else:
|
||||
b = None
|
||||
# Fill in unspecified positions
|
||||
if l is None:
|
||||
if r is not None:
|
||||
l = r - w
|
||||
else:
|
||||
l = x
|
||||
if r is None:
|
||||
r = l + w
|
||||
if t is None:
|
||||
if b is not None:
|
||||
t = b - h
|
||||
else:
|
||||
t = y
|
||||
if b is None:
|
||||
b = t + h
|
||||
if scrolling:
|
||||
item.scrolling = scrolling
|
||||
# Position, resize and add the item
|
||||
item.bounds = (l, t, r, b)
|
||||
self.add(item)
|
||||
# Record resizing and border options
|
||||
item.hmove = hmove
|
||||
item.vmove = vmove
|
||||
item.hstretch = hstretch
|
||||
item.vstretch = vstretch
|
||||
if border is not None:
|
||||
item.border = border
|
||||
# Step to the next item
|
||||
if dir == 0:
|
||||
left_obj = item
|
||||
left_off = spacing
|
||||
elif dir == 1:
|
||||
top_obj = item
|
||||
top_off = spacing
|
||||
elif dir == 2:
|
||||
right_obj = item
|
||||
right_off = -spacing
|
||||
else:
|
||||
bottom_obj = item
|
||||
bottom_off = -spacing
|
||||
|
||||
#
|
||||
# Resizing
|
||||
#
|
||||
|
||||
def _resized(self, delta):
|
||||
if self._auto_layout:
|
||||
self.resized(delta)
|
||||
|
||||
def resized(self, delta):
|
||||
for c in self._contents:
|
||||
c.container_resized(delta)
|
||||
|
||||
def resize(self, auto_layout = False, **kwds):
|
||||
"""Change the geometry of the component, with control over whether
|
||||
the layout of subcomponents is updated. The default is not to do so.
|
||||
Keyword arguments to this method may be any of the properties
|
||||
affecting position and size (i.e. left, top, right, bottom, x, y,
|
||||
width, height, position, size, bounds)."""
|
||||
old_auto_layout = self.auto_layout
|
||||
try:
|
||||
self.auto_layout = auto_layout
|
||||
self.set(**kwds)
|
||||
finally:
|
||||
self.auto_layout = old_auto_layout
|
||||
|
||||
#
|
||||
# Tabbing
|
||||
#
|
||||
|
||||
def _build_tab_chain(self, chain):
|
||||
Component._build_tab_chain(self, chain)
|
||||
for c in self._contents:
|
||||
c._build_tab_chain(chain)
|
||||
|
||||
#
|
||||
# Other
|
||||
#
|
||||
|
||||
def shrink_wrap(self, padding = None):
|
||||
"""Adjust the size of the component so that it neatly encloses its
|
||||
contents. If padding is specified, it specifies the amount of space
|
||||
to leave at right and bottom, otherwise the minimum distance from the
|
||||
left and top sides to the nearest components is used."""
|
||||
contents = self.contents
|
||||
if not contents:
|
||||
return
|
||||
if padding:
|
||||
hpad, vpad = padding
|
||||
else:
|
||||
hpad = min([item.left for item in contents])
|
||||
vpad = min([item.top for item in contents])
|
||||
rights = [item.right for item in contents]
|
||||
bottoms = [item.bottom for item in contents]
|
||||
self.resize(size = (max(rights) + hpad, max(bottoms) + vpad))
|
||||
|
||||
def broadcast(self, message, *args):
|
||||
"""Traverse the component hierarchy, calling each component's handler for
|
||||
the given message, if any."""
|
||||
Component.broadcast(self, message, *args)
|
||||
for comp in self._contents:
|
||||
comp.broadcast(message, *args)
|
||||
@@ -0,0 +1,46 @@
|
||||
#
|
||||
# Python GUI - Controls - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Component
|
||||
|
||||
class Control(Component):
|
||||
"""Abstract base class for components such as buttons, check
|
||||
boxes and text entry boxes."""
|
||||
|
||||
title = overridable_property('title', "Title of the control.")
|
||||
value = overridable_property('value', "Value of the control.")
|
||||
enabled = overridable_property('enabled', "True if user can manipulate the control.")
|
||||
font = overridable_property('font')
|
||||
color = overridable_property('color')
|
||||
just = overridable_property('just', "Justification ('left', 'center' or 'right').")
|
||||
lines = overridable_property('lines',
|
||||
"Height of the control measured in lines of the current font.")
|
||||
tab_stop = overridable_property('tab_stop',
|
||||
"Whether tab key can navigate into this control.")
|
||||
|
||||
_vertical_padding = 0 # Extra height to add when setting 'lines' property
|
||||
_default_tab_stop = True
|
||||
_user_tab_stop_override = True
|
||||
|
||||
def __init__(self, font = None, lines = None, **kwds):
|
||||
Component.__init__(self, **kwds)
|
||||
# If font and lines are both specified, must set font first.
|
||||
if font:
|
||||
self.font = font
|
||||
if lines is not None:
|
||||
self.lines = lines
|
||||
|
||||
def get_lines(self):
|
||||
return int(round((self.height - self._vertical_padding) / self.font.line_height))
|
||||
|
||||
def set_lines(self, num_lines):
|
||||
self.height = self._calc_height(self.font, num_lines)
|
||||
|
||||
def _calc_height(self, font, num_lines = 1):
|
||||
return num_lines * font.line_height + self._vertical_padding
|
||||
|
||||
def _is_targetable(self):
|
||||
return self.enabled
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Cursors - Generic
|
||||
#
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
from GUI.Properties import Properties
|
||||
from GUI.Resources import lookup_resource, find_resource, get_resource
|
||||
from GUI import Image
|
||||
|
||||
def _hotspot_for_resource(resource_name):
|
||||
path = lookup_resource(resource_name, "hot")
|
||||
if path:
|
||||
f = open(path, "rU")
|
||||
xs, ys = f.readline().split()
|
||||
return int(xs), int(ys)
|
||||
else:
|
||||
return None
|
||||
|
||||
class Cursor(Properties):
|
||||
"""A Cursor is an image representing the mouse pointer.
|
||||
|
||||
Constructors:
|
||||
Cursor(resource_name, hotspot)
|
||||
Cursor(image, hotspot)
|
||||
"""
|
||||
|
||||
def from_resource(cls, name, hotspot = None, **kwds):
|
||||
def load(path):
|
||||
image = Image.from_resource(name, **kwds)
|
||||
return cls(image, hotspot or _hotspot_for_resource(name))
|
||||
return get_resource(load, name)
|
||||
|
||||
from_resource = classmethod(from_resource)
|
||||
|
||||
def __init__(self, spec, hotspot = None):
|
||||
"""Construct a Cursor from a resource or Image and a hotspot point.
|
||||
The hotspot defaults to the centre of the image."""
|
||||
if isinstance(spec, basestring):
|
||||
self._init_from_resource(spec, hotspot)
|
||||
else:
|
||||
self._init_from_image(spec, hotspot)
|
||||
|
||||
def _init_from_resource(self, resource_name, hotspot):
|
||||
image = Image(file = find_resource(resource_name))
|
||||
if not hotspot:
|
||||
hotspot = _hotspot_for_resource(resource_name)
|
||||
self._init_from_image(image, hotspot)
|
||||
|
||||
def _init_from_image(self, image, hotspot):
|
||||
if not hotspot:
|
||||
width, height = image.size
|
||||
hotspot = (width // 2, height // 2)
|
||||
self._init_from_image_and_hotspot(image, hotspot)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
#
|
||||
# Python GUI - Dialogs - Generic
|
||||
#
|
||||
|
||||
from GUI import Globals
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Actions import ActionBase, action_property
|
||||
from GUI import Window
|
||||
|
||||
class Dialog(Window, ActionBase):
|
||||
|
||||
_default_keys = "\r"
|
||||
_cancel_keys = "\x1b"
|
||||
|
||||
# default_button = overridable_property('default_button',
|
||||
# "Button to be activated by the default key.")
|
||||
#
|
||||
# cancel_button = overridable_property('cancel_button',
|
||||
# "Button to be activated by the cancel key.")
|
||||
#
|
||||
# _default_button = None
|
||||
# _cancel_button = None
|
||||
|
||||
default_action = action_property('default_action',
|
||||
"Action to perform when Return or Enter is pressed.")
|
||||
|
||||
cancel_action = action_property('cancel_action',
|
||||
"Action to perform when Escape is pressed.")
|
||||
|
||||
_default_action = 'ok'
|
||||
_cancel_action ='cancel'
|
||||
|
||||
def __init__(self, style = 'nonmodal_dialog',
|
||||
closable = 0, zoomable = 0, resizable = 0, **kwds):
|
||||
if 'title' not in kwds:
|
||||
kwds['title'] = Globals.application_name
|
||||
Window.__init__(self, style = style,
|
||||
closable = closable, zoomable = zoomable, resizable = resizable,
|
||||
**kwds)
|
||||
|
||||
# def get_default_button(self):
|
||||
# return self._default_button
|
||||
#
|
||||
# def set_default_button(self, button):
|
||||
# self._default_button = button
|
||||
# if button:
|
||||
# button.style = 'default'
|
||||
#
|
||||
# def get_cancel_button(self):
|
||||
# return self._cancel_button
|
||||
#
|
||||
# def set_cancel_button(self, button):
|
||||
# self._cancel_button = button
|
||||
# if button:
|
||||
# button.style = 'cancel'
|
||||
|
||||
def key_down(self, event):
|
||||
#print "GDialog.key_down:", repr(event.char) ###
|
||||
c = event.char
|
||||
if c:
|
||||
if c in self._default_keys:
|
||||
self.do_default_action()
|
||||
return
|
||||
elif c in self._cancel_keys:
|
||||
self.do_cancel_action()
|
||||
return
|
||||
Window.key_down(self, event)
|
||||
|
||||
def do_default_action(self):
|
||||
self.do_named_action('default_action')
|
||||
|
||||
def do_cancel_action(self):
|
||||
self.do_named_action('cancel_action')
|
||||
|
||||
# def _activate_button(self, button):
|
||||
# if button:
|
||||
# button.activate()
|
||||
@@ -0,0 +1,62 @@
|
||||
#--------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - DrawableContainer - Generic
|
||||
#
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
from GUI.Geometry import rect_sized
|
||||
from GUI import Container
|
||||
from GUI import ViewBase
|
||||
from GUI.Printing import Printable
|
||||
|
||||
default_size = (100, 100)
|
||||
|
||||
class DrawableContainer(ViewBase, Container, Printable):
|
||||
|
||||
#
|
||||
# Construction and destruction
|
||||
#
|
||||
|
||||
def __init__(self, **kwds):
|
||||
Container.__init__(self, **kwds)
|
||||
ViewBase.__init__(self)
|
||||
|
||||
def destroy(self):
|
||||
ViewBase.destroy(self)
|
||||
Container.destroy(self)
|
||||
|
||||
def setup_menus(self, m):
|
||||
ViewBase.setup_menus(self, m)
|
||||
Container.setup_menus(self, m)
|
||||
|
||||
def viewed_rect(self):
|
||||
"""Return the rectangle in local coordinates bounding the currently
|
||||
visible part of the extent."""
|
||||
return rect_sized((0, 0), self.size)
|
||||
|
||||
def with_canvas(self, proc):
|
||||
"""Call the procedure with a canvas suitable for drawing in this
|
||||
view. The canvas is only valid for the duration of the call, and
|
||||
should not be retained beyond it."""
|
||||
raise NotImplementedError
|
||||
|
||||
def update(self):
|
||||
"""Redraw invalidated regions immediately, without waiting for a
|
||||
return to the event loop."""
|
||||
raise NotImplementedError
|
||||
|
||||
def get_print_extent(self):
|
||||
return self.content_size
|
||||
|
||||
def _draw_background(self, canvas, clip_rect):
|
||||
return clip_rect
|
||||
|
||||
#
|
||||
# Callbacks
|
||||
#
|
||||
|
||||
def draw(self, canvas, rect):
|
||||
"""Called when the view needs to be drawn. The rect is the bounding
|
||||
rectangle of the region needing to be drawn. The default implementation
|
||||
does nothing."""
|
||||
pass
|
||||
@@ -0,0 +1,28 @@
|
||||
#
|
||||
# PyGUI - Edit command handling - Generic
|
||||
#
|
||||
|
||||
from GUI import application
|
||||
|
||||
class EditCmdHandler(object):
|
||||
# Mixin for objects that implement the standard editing commands.
|
||||
|
||||
_may_be_password = False
|
||||
|
||||
def setup_menus(self, m):
|
||||
selbeg, selend = self.selection
|
||||
anysel = selbeg < selend
|
||||
anyscrap = application().query_clipboard()
|
||||
passwd = self._may_be_password and self.password
|
||||
m.cut_cmd.enabled = anysel and not passwd
|
||||
m.copy_cmd.enabled = anysel and not passwd
|
||||
m.paste_cmd.enabled = anyscrap
|
||||
m.clear_cmd.enabled = anysel
|
||||
m.select_all_cmd.enabled = True
|
||||
|
||||
def select_all_cmd(self):
|
||||
self.select_all()
|
||||
|
||||
def select_all(self):
|
||||
self.selection = (0, self.get_text_length())
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
#
|
||||
# Python GUI - Events - Generic
|
||||
#
|
||||
|
||||
class Event(object):
|
||||
|
||||
"""An input event.
|
||||
|
||||
Attributes:
|
||||
|
||||
kind Type of event. One of 'mouse_down', 'mouse_up', 'key_down',
|
||||
'key_up'.
|
||||
|
||||
global_position Position of mouse in screen coordinates at the time of the event.
|
||||
|
||||
position For mouse events, position in local coordinates of the View that
|
||||
was the target of this event. Undefined for other event types.
|
||||
|
||||
time Time of event, in platform-dependent units.
|
||||
|
||||
button Button identifier for mouse down/up events.
|
||||
|
||||
num_clicks Number of consecutive clicks within double-click time.
|
||||
|
||||
char For key events, an ASCII character. Undefined for other event types.
|
||||
|
||||
key For non-printing keys, a value identifying the key. Undefined for other event types.
|
||||
|
||||
auto True if key-down event is an autorepeat (not supported on all platforms).
|
||||
|
||||
Platform-independent modifiers (boolean):
|
||||
|
||||
shift The Shift key.
|
||||
control The Control key.
|
||||
option The additional modifier key.
|
||||
extend_contig The contiguous selection extension modifier key.
|
||||
extend_noncontig The noncontiguous selection extension modifier key.
|
||||
"""
|
||||
|
||||
kind = None
|
||||
global_position = None
|
||||
position = None
|
||||
time = None
|
||||
button = None
|
||||
num_clicks = 0
|
||||
char = None
|
||||
key = None
|
||||
auto = False
|
||||
shift = False
|
||||
control = False
|
||||
option = False
|
||||
extend_contig = False
|
||||
extend_noncontig = False
|
||||
delta = (0, 0)
|
||||
_keycode = 0 # Platform-dependent key code
|
||||
_originator = None # Component to which originally delivered by platform
|
||||
_not_handled = False # Reached default event method of originating component
|
||||
|
||||
def position_in(self, view):
|
||||
"""Return the position of this event in the coordinate system
|
||||
of the specified view."""
|
||||
return view.global_to_local(self.global_position)
|
||||
|
||||
def __str__(self):
|
||||
return "<GUI.Event: %s global:%s local:%s time:%s clicks:%s char:%r" \
|
||||
" key:%s shift:%s control:%s option:%s extend_contig:%s" \
|
||||
" extend_noncontig:%s auto:%s%s>" \
|
||||
% (self.kind, self.global_position, self.position, self.time,
|
||||
self.num_clicks, self.char, self.key, self.shift, self.control,
|
||||
self.option, self.extend_contig, self.extend_noncontig, self.auto,
|
||||
self._platform_modifiers_str())
|
||||
@@ -0,0 +1,193 @@
|
||||
#
|
||||
# Python GUI - File references and types - Generic
|
||||
#
|
||||
# Classes for dealing with file references and file types
|
||||
# in as platform-independent a manner as possible.
|
||||
#
|
||||
# In this view of things, a file reference consists
|
||||
# of two parts:
|
||||
#
|
||||
# 1) A directory reference, whose nature is
|
||||
# platform-dependent,
|
||||
#
|
||||
# 2) A name.
|
||||
#
|
||||
|
||||
import os
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
class FileRef(Properties):
|
||||
"""A FileRef represents a file system object in a platform-independent way.
|
||||
It consists of two parts, a directory specification and the name of an
|
||||
object within that directory. The directory specification always refers
|
||||
to an existing directory, but the named object may or may not exist.
|
||||
|
||||
Constructors:
|
||||
FileRef(dir = DirRef or path, name = string)
|
||||
FileRef(path = string)
|
||||
"""
|
||||
|
||||
dir = overridable_property('dir', "DirRef representing the parent directory.")
|
||||
name = overridable_property('name', "Name of the object within the parent directory.")
|
||||
path = overridable_property('path', "Full pathname of the object.")
|
||||
|
||||
_dir = None # DirRef representing the parent directory
|
||||
_name = None # Name, including type suffix if any
|
||||
|
||||
#
|
||||
# Constructor
|
||||
#
|
||||
|
||||
def __init__(self, dir = None, name = None, path = None):
|
||||
if dir and name and not path:
|
||||
if not isinstance(dir, DirRef):
|
||||
dir = DirRef(dir)
|
||||
elif path and not (dir or name):
|
||||
dirpath, name = os.path.split(path)
|
||||
dir = DirRef(path = dirpath)
|
||||
else:
|
||||
raise TypeError("Invalid argument combination to FileRef constructor")
|
||||
self._dir = dir
|
||||
self._name = name
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_dir(self):
|
||||
return self._dir
|
||||
|
||||
def get_name(self):
|
||||
"Return the name of the file."
|
||||
return self._name
|
||||
|
||||
def get_path(self):
|
||||
return os.path.join(self._dir.path, self._name)
|
||||
|
||||
#
|
||||
# Methods
|
||||
#
|
||||
|
||||
def open(self, mode, file_type = None):
|
||||
"""Open as a file with the given mode and return a file object. On
|
||||
platforms which have file-type metadata (e.g. Macintosh), if the
|
||||
mode contains 'w' and a file_type is specified, the newly-created
|
||||
file will be given the specified type."""
|
||||
f = open(self.path, mode)
|
||||
if "w" in mode and file_type:
|
||||
self._set_type(file_type)
|
||||
return f
|
||||
|
||||
def mkdir(self):
|
||||
"""Create a directory with the name and parent directory specified
|
||||
by this FileRef. Returns a DirRef for the created directory."""
|
||||
return DirRef(os.mkdir(self.path))
|
||||
|
||||
def _set_type(self, file_type):
|
||||
# Platforms which have file-type metadata (e.g. Macintosh) use this
|
||||
# to set the type of a file.
|
||||
pass
|
||||
|
||||
def __str__(self):
|
||||
return "FileRef(%r,%r)" % (self.dir.path, self.name)
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
|
||||
class DirRef(Properties):
|
||||
"""A DirRef is an object representing a directory in the
|
||||
file system. Its representation is completely platform
|
||||
dependent.
|
||||
|
||||
Constructor:
|
||||
DirRef(path = string)
|
||||
"""
|
||||
|
||||
_path = None
|
||||
|
||||
path = overridable_property('path', "Full pathname of the directory.")
|
||||
|
||||
def __init__(self, path):
|
||||
self._path = path
|
||||
|
||||
def get_path(self):
|
||||
return self._path
|
||||
|
||||
def __str__(self):
|
||||
return "DirRef(%r)" % self.path
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
|
||||
class FileType(Properties):
|
||||
"""A FileType is a multi-platform representation of a file type."""
|
||||
|
||||
_name = None
|
||||
_suffix = None
|
||||
_mac_creator = None
|
||||
_mac_type = None
|
||||
_mac_force_suffix = True
|
||||
|
||||
name = overridable_property('name', "Human-readable description of the file type")
|
||||
suffix = overridable_property('suffix', "Filename suffix (without dot)")
|
||||
mac_creator = overridable_property('mac_creator', "Macintosh 4-character creator code")
|
||||
mac_type = overridable_property('mac_type', "Macintosh 4-character type code")
|
||||
mac_force_suffix = overridable_property('mac_force_suffix', "Enforce filename suffix on MacOSX")
|
||||
|
||||
def get_name(self):
|
||||
return self._name
|
||||
|
||||
def set_name(self, x):
|
||||
self._name = x
|
||||
|
||||
def get_suffix(self):
|
||||
return self._suffix
|
||||
|
||||
def set_suffix(self, x):
|
||||
self._suffix = x
|
||||
|
||||
def get_mac_creator(self):
|
||||
return self._mac_creator
|
||||
|
||||
def set_mac_creator(self, x):
|
||||
self._mac_creator = x
|
||||
|
||||
def get_mac_type(self):
|
||||
return self._mac_type
|
||||
|
||||
def set_mac_type(self, x):
|
||||
self._mac_type = x
|
||||
|
||||
def get_mac_force_suffix(self):
|
||||
return self._mac_force_suffix
|
||||
|
||||
def set_mac_force_suffix(self, x):
|
||||
self._mac_force_suffix = x
|
||||
|
||||
def _matches(self, name, mac_type):
|
||||
# Return true if the given name or type code matches that of
|
||||
# this file type.
|
||||
this_mac_type = self._mac_type
|
||||
this_suffix = self._suffix
|
||||
if this_mac_type and mac_type == this_mac_type:
|
||||
return True
|
||||
# Allow generic text files to match typeless files for MacOSX
|
||||
if not this_suffix and this_mac_type == "TEXT" and mac_type == "\0\0\0\0":
|
||||
return True
|
||||
if this_suffix and _matches_suffix(name, this_suffix):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _add_suffix(self, name):
|
||||
# Force the given name to have the appropriate suffix for this file
|
||||
# type. Platforms which have other means of representing file types
|
||||
# (e.g. Macintosh) may override this.
|
||||
suffix = self._suffix
|
||||
if suffix and not _matches_suffix(name, suffix):
|
||||
name = "%s.%s" % (name, suffix)
|
||||
return name
|
||||
|
||||
#-------------------------------------------------------------------------
|
||||
|
||||
def _matches_suffix(name, suffix):
|
||||
# Test case-insensitively whether the given filename has
|
||||
# the given suffix.
|
||||
return name.lower().endswith("." + suffix.lower())
|
||||
@@ -0,0 +1,93 @@
|
||||
#
|
||||
# Python GUI - Fonts - Generic
|
||||
#
|
||||
|
||||
import sys
|
||||
from GUI.Properties import overridable_property
|
||||
|
||||
class Font(object):
|
||||
"""A Font object represents a set of characters of a particular
|
||||
typeface, style and size. Font objects are immutable.
|
||||
|
||||
Constructors:
|
||||
Font(family, size, style)
|
||||
family = family name
|
||||
size = size in points
|
||||
style = a list of 'bold', 'italic'
|
||||
|
||||
Properties:
|
||||
family --> string
|
||||
size --> number
|
||||
style --> ['bold', 'italic']
|
||||
ascent --> number
|
||||
descent --> number
|
||||
leading --> number
|
||||
height --> number
|
||||
cap_height --> number
|
||||
x_height --> number
|
||||
line_height --> number
|
||||
"""
|
||||
|
||||
family = overridable_property('family', "Family name ('Times', 'Helvetica', etc.)")
|
||||
size = overridable_property('size', "Size in points")
|
||||
style = overridable_property('style', "A list of 'bold', 'italic'")
|
||||
ascent = overridable_property('ascent', "Distance from baseline to top of highest character")
|
||||
descent = overridable_property('descent', "Distance from baseline to bottom of lowest character")
|
||||
height = overridable_property('height', "Sum of ascent and descent")
|
||||
cap_height = overridable_property('cap_height', "Height above baseline of capital letters")
|
||||
x_height = overridable_property('x_height', "Height above baseline of lowercase letters without ascenders")
|
||||
leading = overridable_property('leading', "Recommended extra space between lines")
|
||||
line_height = overridable_property('line_height', "Recommended distance between baselines")
|
||||
|
||||
def get_cap_height(self):
|
||||
# Approximation for platforms not supporting this
|
||||
return self.ascent
|
||||
|
||||
def get_x_height(self):
|
||||
# Approximation for platforms not supporting this
|
||||
return self.ascent - self.descent
|
||||
|
||||
def get_leading(self):
|
||||
return self.line_height - self.height
|
||||
|
||||
def but(self, family = None, size = None, style = None,
|
||||
style_includes = None, style_excludes = None):
|
||||
"""Return a new Font that is the same as this one except for the
|
||||
specified characteristics."""
|
||||
if not family:
|
||||
family = self.family
|
||||
if not size:
|
||||
size = self.size
|
||||
if style is None:
|
||||
style = self.style
|
||||
style = style[:]
|
||||
if style_includes:
|
||||
for item in style_includes:
|
||||
style.append(item)
|
||||
if style_excludes:
|
||||
for item in style_excludes:
|
||||
if item in style:
|
||||
style.remove(item)
|
||||
return self.__class__(family, size, style)
|
||||
|
||||
def width(self, s, start = 0, end = None):
|
||||
"""width(s [,start [,end ]])
|
||||
The width of the specified part of the given string in this font."""
|
||||
if start or end is not None:
|
||||
if end is None:
|
||||
end = len(s)
|
||||
s = s[start:end]
|
||||
return self._width(s)
|
||||
|
||||
def _width(self, s):
|
||||
raise NotImplementedError
|
||||
|
||||
def x_to_pos(self, s, x):
|
||||
"""Given a number of pixels measured from the left of
|
||||
the given string, returns the nearest inter-character position.
|
||||
Returns 0 if x is negative, and len(string) if x is beyond the
|
||||
right end of the string."""
|
||||
raise NotImplementedError
|
||||
|
||||
def __str__(self):
|
||||
return "Font(%r,%g,%s)" % (self.family, self.size, self.style)
|
||||
@@ -0,0 +1,10 @@
|
||||
#
|
||||
# Python GUI - Frames - Generic
|
||||
#
|
||||
|
||||
from GUI import Container
|
||||
|
||||
class Frame(Container):
|
||||
"""A Frame is a general-purpose instantiable subclass of Container."""
|
||||
|
||||
_default_size = (100, 100)
|
||||
@@ -0,0 +1,162 @@
|
||||
#
|
||||
# PyGUI - OpenGL Pixel Formats - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
class GLConfig(Properties):
|
||||
"""Class holding the attributes of an OpenGL context configuration."""
|
||||
|
||||
# NOTE: When adding a property here, also add it to
|
||||
# _pixel_format_attribute_names below.
|
||||
|
||||
double_buffer = overridable_property("double_buffer", "True if context is to be double-buffered.")
|
||||
alpha = overridable_property("alpha", "True if there is to be an alpha channel.")
|
||||
color_size = overridable_property("color_size", "Number of bits per colour buffer component.")
|
||||
alpha_size = overridable_property("alpha_size", "Number of bits per alpha channel component.")
|
||||
stereo = overridable_property("stereo", "True if stereoscopic context is required.")
|
||||
aux_buffers = overridable_property("aux_buffers", "Number of auxiliary colour buffers to allocate.")
|
||||
depth_buffer = overridable_property("depth_buffer", "True if a depth buffer is required.")
|
||||
depth_size = overridable_property("depth_size", "Number of bits per depth buffer element.")
|
||||
stencil_buffer = overridable_property("stencil_buffer", "True if a stencil buffer is required.")
|
||||
stencil_size = overridable_property("stencil_size", "Number of bits per stencil buffer element.")
|
||||
accum_buffer = overridable_property("accum_buffer", "True if an accumulation buffer is required.")
|
||||
accum_size = overridable_property("accum_size", "Number of bits per accumulation buffer component.")
|
||||
multisample = overridable_property("multisample", "True if a multisampled context is required.")
|
||||
samples_per_pixel = overridable_property("samples_per_pixel", "Number of samples per multisampled pixel.")
|
||||
|
||||
_double_buffer = True
|
||||
_alpha = True
|
||||
_color_size = 8
|
||||
_alpha_size = 8
|
||||
_stereo = False
|
||||
_aux_buffers = 0
|
||||
_depth_buffer = True
|
||||
_depth_size = 32
|
||||
_stencil_buffer = False
|
||||
_stencil_size = 8
|
||||
_accum_buffer = False
|
||||
_accum_size = 8
|
||||
_multisample = False
|
||||
_samples_per_pixel = 4
|
||||
|
||||
_pixel_format_attribute_names = (
|
||||
'double_buffer', 'alpha', 'color_size', 'alpha_size',
|
||||
'stereo', 'aux_buffers', 'depth_buffer', 'depth_size',
|
||||
'stencil_buffer', 'stencil_size', 'accum_buffer', 'accum_size',
|
||||
'multisample', 'samples_per_pixel',
|
||||
)
|
||||
|
||||
def _from_args(cls, config, kwds):
|
||||
# Extract pixel format arguments from arguments of GLView.__init__
|
||||
# or GLPixmap.__init__ and return a GLConfig. Used keyword
|
||||
# arguments are removed from kwds.
|
||||
pf_kwds = {}
|
||||
for name in cls._pixel_format_attribute_names:
|
||||
if name in kwds:
|
||||
pf_kwds[name] = kwds.pop(name)
|
||||
if config and pf_kwds:
|
||||
raise TypeError("Explicit config cannot be used with other configuration keyword arguments")
|
||||
if not config:
|
||||
config = cls(**pf_kwds)
|
||||
return config
|
||||
|
||||
_from_args = classmethod(_from_args)
|
||||
|
||||
def get_double_buffer(self):
|
||||
return self._double_buffer
|
||||
|
||||
def set_double_buffer(self, x):
|
||||
self._double_buffer = x
|
||||
|
||||
def get_alpha(self):
|
||||
return self._alpha
|
||||
|
||||
def set_alpha(self, x):
|
||||
self._alpha = x
|
||||
|
||||
def get_color_size(self):
|
||||
return self._color_size
|
||||
|
||||
def set_color_size(self, x):
|
||||
self._color_size = x
|
||||
|
||||
def get_alpha_size(self):
|
||||
return self._alpha_size
|
||||
|
||||
def set_alpha_size(self, x):
|
||||
self._alpha_size = x
|
||||
|
||||
def get_stereo(self):
|
||||
return self._stereo
|
||||
|
||||
def set_stereo(self, x):
|
||||
self._stereo = x
|
||||
|
||||
def get_aux_buffers(self):
|
||||
return self._aux_buffers
|
||||
|
||||
def set_aux_buffers(self, x):
|
||||
self._aux_buffers = x
|
||||
|
||||
def get_depth_buffer(self):
|
||||
return self._depth_buffer
|
||||
|
||||
def set_depth_buffer(self, x):
|
||||
self._depth_buffer = x
|
||||
|
||||
def get_depth_size(self):
|
||||
return self._depth_size
|
||||
|
||||
def set_depth_size(self, x):
|
||||
self._depth_size = x
|
||||
|
||||
def get_stencil_buffer(self):
|
||||
return self._stencil_buffer
|
||||
|
||||
def set_stencil_buffer(self, x):
|
||||
self._stencil_buffer = x
|
||||
|
||||
def get_stencil_size(self):
|
||||
return self._stencil_size
|
||||
|
||||
def set_stencil_size(self, x):
|
||||
self._stencil_size = x
|
||||
|
||||
def get_accum_buffer(self):
|
||||
return self._accum_buffer
|
||||
|
||||
def set_accum_buffer(self, x):
|
||||
self._accum_buffer = x
|
||||
|
||||
def get_accum_size(self):
|
||||
return self._accum_size
|
||||
|
||||
def set_accum_size(self, x):
|
||||
self._accum_size = x
|
||||
|
||||
def get_multisample(self):
|
||||
return self._multisample
|
||||
|
||||
def set_multisample(self, x):
|
||||
self._multisample = x
|
||||
|
||||
def get_samples_per_pixel(self):
|
||||
return self._samples_per_pixel
|
||||
|
||||
def set_samples_per_pixel(self, x):
|
||||
self._samples_per_pixel = x
|
||||
|
||||
def supported(self):
|
||||
"""Determine whether the combination of attributes requested by this configuration
|
||||
can be satisfied. If successful, a new GLConfig object is returned whose
|
||||
attributes reflect those actually allocated. Otherwise, a GLConfigError is
|
||||
raised."""
|
||||
raise NotImplementedError
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class GLConfigError(ValueError):
|
||||
|
||||
def __init__(self, msg = "OpenGL configuration not available"):
|
||||
ValueError.__init__(self, msg)
|
||||
@@ -0,0 +1,72 @@
|
||||
#
|
||||
# PyGUI - OpenGL Contexts - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.GLShareGroups import ShareGroup
|
||||
|
||||
_current_share_group = None
|
||||
|
||||
class GLContext(object):
|
||||
"""Abstract base class for objects having an OpenGL context."""
|
||||
#
|
||||
# _share_group ShareGroup
|
||||
#
|
||||
|
||||
share_group = overridable_property('share_group',
|
||||
"ShareGroup to which this context should belong, or None.")
|
||||
|
||||
def __init__(self, share_group):
|
||||
if not share_group:
|
||||
share_group = ShareGroup()
|
||||
self._share_group = share_group
|
||||
if share_group:
|
||||
share_group._add(self)
|
||||
|
||||
def destroy(self):
|
||||
pass
|
||||
|
||||
def init_context(self):
|
||||
"""This method is called once after the associated OpenGL context
|
||||
is created. When called, this object's OpenGL context is the current
|
||||
context and the viewport is set to (0, 0, width, height). This method
|
||||
may be used to establish any desired initial OpenGL state."""
|
||||
pass
|
||||
|
||||
def get_share_group(self):
|
||||
return self._share_group
|
||||
|
||||
def _get_shared_context(self):
|
||||
"""Return another arbitrarily-chosen member of the share group of this
|
||||
context, or None if this context has no share group or there are no
|
||||
other members."""
|
||||
return self._share_group._some_member(exclude = self)
|
||||
|
||||
def with_context(self, proc, flush = False):
|
||||
"""The proc should be a callable object of no arguments. Calls
|
||||
the proc with the associated OpenGL context as the current context.
|
||||
If flush is true, after calling proc, a glFlush followed by a
|
||||
buffer flush or swap is performed as appropriate."""
|
||||
self._with_context(proc, flush)
|
||||
|
||||
def _with_context(self, proc, flush):
|
||||
# Subclasses override this to implement with_context.
|
||||
# Should call _with_share_group(proc).
|
||||
# Signature can be changed if with_context is overridden to match.
|
||||
raise NotImplementedError
|
||||
|
||||
def _with_share_group(self, proc):
|
||||
global _current_share_group
|
||||
old_share_group = _current_share_group
|
||||
_current_share_group = self._share_group
|
||||
try:
|
||||
proc()
|
||||
finally:
|
||||
_current_share_group = old_share_group
|
||||
|
||||
|
||||
def current_share_group():
|
||||
group = _current_share_group
|
||||
if not group:
|
||||
raise ValueError("No current PyGUI OpenGL context")
|
||||
return group
|
||||
@@ -0,0 +1,163 @@
|
||||
#
|
||||
# PyGUI - OpenGL Pixel Formats - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
class GLPixelFormat(Properties):
|
||||
"""Class holding the attributes of an OpenGL pixel format."""
|
||||
|
||||
# NOTE: When adding a property here, also add it to
|
||||
# _pixel_format_attribute_names below.
|
||||
|
||||
double_buffer = overridable_property("double_buffer", "True if context is to be double-buffered.")
|
||||
alpha = overridable_property("alpha", "True if there is to be an alpha channel.")
|
||||
color_size = overridable_property("color_size", "Number of bits per colour buffer component.")
|
||||
alpha_size = overridable_property("alpha_size", "Number of bits per alpha channel component.")
|
||||
stereo = overridable_property("stereo", "True if stereoscopic context is required.")
|
||||
aux_buffers = overridable_property("aux_buffers", "Number of auxiliary colour buffers to allocate.")
|
||||
depth_buffer = overridable_property("depth_buffer", "True if a depth buffer is required.")
|
||||
depth_size = overridable_property("depth_size", "Number of bits per depth buffer element.")
|
||||
stencil_buffer = overridable_property("stencil_buffer", "True if a stencil buffer is required.")
|
||||
stencil_size = overridable_property("stencil_size", "Number of bits per stencil buffer element.")
|
||||
accum_buffer = overridable_property("accum_buffer", "True if an accumulation buffer is required.")
|
||||
accum_size = overridable_property("accum_size", "Number of bits per accumulation buffer component.")
|
||||
multisample = overridable_property("multisample", "True if a multisampled context is required.")
|
||||
samples_per_pixel = overridable_property("samples_per_pixel", "Number of samples per multisampled pixel.")
|
||||
|
||||
_double_buffer = True
|
||||
_alpha = True
|
||||
_color_size = 8
|
||||
_alpha_size = 8
|
||||
_stereo = False
|
||||
_aux_buffers = 0
|
||||
_depth_buffer = True
|
||||
_depth_size = 32
|
||||
_stencil_buffer = False
|
||||
_stencil_size = 8
|
||||
_accum_buffer = False
|
||||
_accum_size = 8
|
||||
_multisample = False
|
||||
_samples_per_pixel = False
|
||||
|
||||
_pixel_format_attribute_names = (
|
||||
'double_buffer', 'alpha', 'color_size', 'alpha_size',
|
||||
'stereo', 'aux_buffers', 'depth_buffer', 'depth_size',
|
||||
'stencil_buffer', 'stencil_size', 'accum_buffer', 'accum_size',
|
||||
'multisample', 'samples_per_pixel',
|
||||
)
|
||||
|
||||
def _from_args(cls, pixel_format, kwds):
|
||||
# Extract pixel format arguments from arguments of GLView.__init__
|
||||
# or GLPixmap.__init__ and return a GLPixelFormat. Used keyword
|
||||
# arguments are removed from kwds.
|
||||
pf_kwds = {}
|
||||
for name in cls._pixel_format_attribute_names:
|
||||
if name in kwds:
|
||||
pf_kwds[name] = kwds.pop(name)
|
||||
if pixel_format and pf_kwds:
|
||||
raise TypeError("Explicit pixel_format cannot be used with other pixel format keyword arguments")
|
||||
if not pixel_format:
|
||||
pixel_format = cls(**pf_kwds)
|
||||
return pixel_format
|
||||
|
||||
_from_args = classmethod(_from_args)
|
||||
|
||||
def get_double_buffer(self):
|
||||
return self._double_buffer
|
||||
|
||||
def set_double_buffer(self, x):
|
||||
self._double_buffer = x
|
||||
|
||||
def get_alpha(self):
|
||||
return self._alpha
|
||||
|
||||
def set_alpha(self, x):
|
||||
self._alpha = x
|
||||
|
||||
def get_color_size(self):
|
||||
return self._color_size
|
||||
|
||||
def set_color_size(self, x):
|
||||
self._color_size = x
|
||||
|
||||
def get_alpha_size(self):
|
||||
return self._alpha_size
|
||||
|
||||
def set_alpha_size(self, x):
|
||||
self._alpha_size = x
|
||||
|
||||
def get_stereo(self):
|
||||
return self._stereo
|
||||
|
||||
def set_stereo(self, x):
|
||||
self._stereo = x
|
||||
|
||||
def get_aux_buffers(self):
|
||||
return self._aux_buffers
|
||||
|
||||
def set_aux_buffers(self, x):
|
||||
self._aux_buffers = x
|
||||
|
||||
def get_depth_buffer(self):
|
||||
return self._depth_buffer
|
||||
|
||||
def set_depth_buffer(self, x):
|
||||
self._depth_buffer = x
|
||||
|
||||
def get_depth_size(self):
|
||||
return self._depth_size
|
||||
|
||||
def set_depth_size(self, x):
|
||||
self._depth_size = x
|
||||
|
||||
def get_stencil_buffer(self):
|
||||
return self._stencil_buffer
|
||||
|
||||
def set_stencil_buffer(self, x):
|
||||
self._stencil_buffer = x
|
||||
|
||||
def get_stencil_size(self):
|
||||
return self._stencil_size
|
||||
|
||||
def set_stencil_size(self, x):
|
||||
self._stencil_size = x
|
||||
|
||||
def get_accum_buffer(self):
|
||||
return self._accum_buffer
|
||||
|
||||
def set_accum_buffer(self, x):
|
||||
self._accum_buffer = x
|
||||
|
||||
def get_accum_size(self):
|
||||
return self._accum_size
|
||||
|
||||
def set_accum_size(self, x):
|
||||
self._accum_size = x
|
||||
|
||||
def get_multisample(self):
|
||||
return self._multisample
|
||||
|
||||
def set_multisample(self, x):
|
||||
self._multisample = x
|
||||
|
||||
def get_samples_per_pixel(self):
|
||||
return self._samples_per_pixel
|
||||
|
||||
def set_samples_per_pixel(self, x):
|
||||
self._samples_per_pixel = x
|
||||
|
||||
def supported(self):
|
||||
"""Determine whether the combination of attributes requested by this pixel format
|
||||
can be satisfied. If successful, a new GLPixelFormat object is returned whose
|
||||
attributes reflect those actually allocated. Otherwise, a GLPixelFormatError is
|
||||
raised."""
|
||||
raise NotImplementedError
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class GLPixelFormatError(ValueError):
|
||||
|
||||
def __init__(self):
|
||||
ValueError.__init__(self,
|
||||
"OpenGL pixel format attribute request cannot be satisfied")
|
||||
@@ -0,0 +1,23 @@
|
||||
#
|
||||
# PyGUI - OpenGL Pixmap - Generic
|
||||
#
|
||||
|
||||
from OpenGL.GL import glViewport
|
||||
from GUI import ImageBase
|
||||
from GUI.GLContexts import GLContext
|
||||
|
||||
class GLPixmap(ImageBase, GLContext):
|
||||
"""An offscreen OpenGL drawing area.
|
||||
|
||||
Constructors:
|
||||
GLPixmap(width, height, share = None, config_attr = value...)
|
||||
GLPixmap(width, height, config, share = None)
|
||||
"""
|
||||
|
||||
def destroy(self):
|
||||
GLContext.destroy(self)
|
||||
|
||||
def _init_context(self):
|
||||
width, height = self.size
|
||||
glViewport(0, 0, int(width), int(height))
|
||||
self.init_context()
|
||||
@@ -0,0 +1,122 @@
|
||||
#
|
||||
# PyGUI - OpenGL Textures - Generic
|
||||
#
|
||||
|
||||
from weakref import WeakKeyDictionary
|
||||
from OpenGL.GL import glGenTextures, glBindTexture, glDeleteTextures, \
|
||||
glTexImage2D, GL_TEXTURE_2D, GL_RGBA
|
||||
from OpenGL.GLU import gluBuild2DMipmaps
|
||||
from GUI.GGLContexts import current_share_group
|
||||
from GUI.GLDisplayLists import call_when_not_compiling_display_list
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class TextureIdMap(WeakKeyDictionary):
|
||||
|
||||
def __del__(self):
|
||||
#print "GL.TextureIdMap.__del__:", self ###
|
||||
def free_texture():
|
||||
glDeleteTextures([gl_id])
|
||||
for share_group, gl_id in self.items():
|
||||
context = share_group._some_member()
|
||||
if context:
|
||||
#print "...freeing texture id", gl_id, "for", share_group, "using", context ###
|
||||
context.with_context(free_texture)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class Texture(object):
|
||||
"""This class encapsulates an OpenGL texture and maintains a
|
||||
representation of it for each OpenGL context with which it is used.
|
||||
Allocation and maintentance of texture numbers is handled automatically.
|
||||
|
||||
Constructor:
|
||||
Texture(texture_type)
|
||||
where texture_type is the appropriate GL constant for the type
|
||||
of texture (GL_TEXTURE_2D etc.)
|
||||
"""
|
||||
#
|
||||
# _gl_type int GL_TEXTURE_2D, etc.
|
||||
# _gl_id ShareGroup -> int Mapping from OpenGL share group to texture number
|
||||
|
||||
def __init__(self, texture_type):
|
||||
self._gl_type = texture_type
|
||||
self._gl_id = TextureIdMap()
|
||||
|
||||
def deallocate(self):
|
||||
"""Deallocate any OpenGL resources that have been allocated for this
|
||||
texture in any context."""
|
||||
self._gl_id.__del__()
|
||||
|
||||
def bind(self):
|
||||
"""Makes this texture the current texture for the current context
|
||||
by calling glBindTexture. If this texture has not previously been
|
||||
used with the current context, do_setup() is called to allocate
|
||||
and initialise a representation of the texture."""
|
||||
gl_id = self.gl_id()
|
||||
glBindTexture(self._gl_type, gl_id)
|
||||
|
||||
def gl_id(self):
|
||||
"""Returns the OpenGL texture number corresponding to this texture
|
||||
in the current context. May trigger allocation of a new texture and
|
||||
a call to do_setup(). Does not bind the texture, unless a new texture
|
||||
is allocated, in which case the current texture binding may be changed
|
||||
as a side effect."""
|
||||
share_group = current_share_group()
|
||||
gl_id = self._gl_id.get(share_group)
|
||||
if gl_id is None:
|
||||
gl_id = glGenTextures(1)
|
||||
#print "GLTexture: assigned id %d for %s in share group %s" % (
|
||||
# gl_id, self, share_group) ###
|
||||
self._gl_id[share_group] = gl_id
|
||||
call_when_not_compiling_display_list(lambda: self._setup(gl_id))
|
||||
return gl_id
|
||||
|
||||
def _setup(self, gl_id):
|
||||
glBindTexture(self._gl_type, gl_id)
|
||||
self.do_setup()
|
||||
|
||||
def do_setup(self):
|
||||
"""Subclasses should override this to make the necessary OpenGL
|
||||
calls to initialise the texture, assuming that glBindTexture has
|
||||
already been called."""
|
||||
raise NotImplementedError
|
||||
|
||||
def gl_tex_image_2d(self, image, target = GL_TEXTURE_2D, internal_format = GL_RGBA,
|
||||
border = False, with_mipmaps = False):
|
||||
"""Load the currently bound texture with data from an image, with automatic
|
||||
scaling to power-of-2 size and optional mipmap generation."""
|
||||
border = bool(border)
|
||||
if border and with_mipmaps:
|
||||
raise ValueError("Bordered texture cannot have mipmaps")
|
||||
b2 = 2 * border
|
||||
width, height = image.size
|
||||
twidth = pow2up(width - b2) + b2
|
||||
theight = pow2up(height - b2) + b2
|
||||
#print "GUI.GGLTextures.Texture.gl_tex_image_2d: before scaling: size =", (width, height) ###
|
||||
if width <> twidth or height <> theight:
|
||||
#print "GUI.GGLTextures.Texture.gl_tex_image_2d: scaling image to size", (twidth, theight) ###
|
||||
from Pixmaps import Pixmap
|
||||
image2 = Pixmap(twidth, theight)
|
||||
def scale(canvas):
|
||||
image.draw(canvas, (0, 0, width, height), (0, 0, twidth, theight))
|
||||
image2.with_canvas(scale)
|
||||
image = image2
|
||||
format, type, data = self._gl_get_texture_data(image)
|
||||
if with_mipmaps:
|
||||
#print "GUI.GGLTextures.Texture.gl_tex_image_2d: loading mipmaps" ###
|
||||
gluBuild2DMipmaps(target, internal_format, twidth, theight,
|
||||
format, type, data)
|
||||
else:
|
||||
#print "GUI.GGLTextures.Texture.gl_tex_image_2d: loading texture" ###
|
||||
glTexImage2D(target, 0, internal_format, twidth, theight, border,
|
||||
format, type, data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
def pow2up(size):
|
||||
# Round size up to a power of 2
|
||||
psize = 1
|
||||
while psize < size:
|
||||
psize <<= 1
|
||||
return psize
|
||||
@@ -0,0 +1,73 @@
|
||||
#
|
||||
# PyGUI - OpenGL View - Generic
|
||||
#
|
||||
|
||||
from OpenGL.GL import glViewport, glMatrixMode, glLoadIdentity, \
|
||||
GL_PROJECTION, GL_MODELVIEW
|
||||
from GUI import Component
|
||||
from GUI import ViewBase
|
||||
from GUI.GLContexts import GLContext
|
||||
|
||||
class GLError(StandardError):
|
||||
pass
|
||||
|
||||
class GLView(ViewBase, Component, GLContext):
|
||||
"""A GLView is a Component providing an OpenGL 3D display area.
|
||||
|
||||
Constructors:
|
||||
GLView(config_attr = value..., share = None)
|
||||
GLView(config, share = None)
|
||||
"""
|
||||
|
||||
_default_size = (100, 100)
|
||||
|
||||
def __init__(self, **kwds):
|
||||
Component.__init__(self, **kwds)
|
||||
ViewBase.__init__(self)
|
||||
|
||||
def destroy(self):
|
||||
ViewBase.destroy(self)
|
||||
Component.destroy(self)
|
||||
|
||||
def _render(self):
|
||||
glMatrixMode(GL_MODELVIEW)
|
||||
glLoadIdentity()
|
||||
self.render()
|
||||
|
||||
def render(self):
|
||||
"""This method is called when the contents of the view needs to
|
||||
be redrawn, with the view's OpenGL context as the current context.
|
||||
The modelview matrix has been selected as the current matrix and
|
||||
set to an identity matrix. After calling this method, buffers will
|
||||
be automatically swapped or drawing flushed as appropriate."""
|
||||
pass
|
||||
|
||||
def viewport_changed(self):
|
||||
"""This method is called when the view's size has changed, with
|
||||
the view's OpenGL context as the current context, and the OpenGL
|
||||
viewport set to (0, 0, width, height). The default implementation
|
||||
loads an identity projection matrix and calls init_projection()."""
|
||||
glMatrixMode(GL_PROJECTION)
|
||||
glLoadIdentity()
|
||||
self.init_projection()
|
||||
|
||||
def init_projection(self):
|
||||
"""This method is called to establish the projection whenever the
|
||||
viewport changes. The projection matrix has been selected as the
|
||||
current matrix and set to an identity matrix."""
|
||||
pass
|
||||
|
||||
def update(self):
|
||||
"""Redraws the contents of the view immediately, without waiting
|
||||
for a return to the event loop."""
|
||||
self.with_context(self.render, flush = True)
|
||||
|
||||
def _init_context(self):
|
||||
self.init_context()
|
||||
self._update_viewport()
|
||||
|
||||
def _update_viewport(self):
|
||||
width, height = self.size
|
||||
glViewport(0, 0, int(width), int(height))
|
||||
self.viewport_changed()
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#
|
||||
# Python GUI - Point and rectangle utilities - Generic
|
||||
#
|
||||
|
||||
def add_pt((x1, y1), (x2, y2)):
|
||||
return (x1 + x2), (y1 + y2)
|
||||
|
||||
def sub_pt((x1, y1), (x2, y2)):
|
||||
return (x1 - x2), (y1 - y2)
|
||||
|
||||
def rect_sized((l, t), (w, h)):
|
||||
return (l, t, l + w, t + h)
|
||||
|
||||
def rect_left(r):
|
||||
return r[0]
|
||||
|
||||
def rect_top(r):
|
||||
return r[1]
|
||||
|
||||
def rect_right(r):
|
||||
return r[2]
|
||||
|
||||
def rect_bottom(r):
|
||||
return r[3]
|
||||
|
||||
def rect_width(r):
|
||||
return r[2] - r[0]
|
||||
|
||||
def rect_height(r):
|
||||
return r[3] - r[1]
|
||||
|
||||
def rect_topleft(r):
|
||||
return r[:2]
|
||||
|
||||
def rect_botright(r):
|
||||
return r[2:]
|
||||
|
||||
def rect_center((l, t, r, b)):
|
||||
return ((l + r) // 2, (t + b) // 2)
|
||||
|
||||
def rect_size((l, t, r, b)):
|
||||
return (r - l, b - t)
|
||||
|
||||
def union_rect((l1, t1, r1, b1), (l2, t2, r2, b2)):
|
||||
return (min(l1, l2), min(t1, t2), max(r1, r2), max(b1, b2))
|
||||
|
||||
def sect_rect((l1, t1, r1, b1), (l2, t2, r2, b2)):
|
||||
return (max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2))
|
||||
|
||||
def inset_rect((l, t, r, b), (dx, dy)):
|
||||
return (l + dx, t + dy, r - dx, b - dy)
|
||||
|
||||
def offset_rect((l, t, r, b), (dx, dy)):
|
||||
return (l + dx, t + dy, r + dx, b + dy)
|
||||
|
||||
def offset_rect_neg((l, t, r, b), (dx, dy)):
|
||||
return (l - dx, t - dy, r - dx, b - dy)
|
||||
|
||||
def empty_rect((l, t, r, b)):
|
||||
return r <= l or b <= t
|
||||
|
||||
def pt_in_rect((x, y), (l, t, r, b)):
|
||||
return l <= x < r and t <= y < b
|
||||
|
||||
def rects_intersect((l1, t1, r1, b1), (l2, t2, r2, b2)):
|
||||
return l1 < r2 and l2 < r1 and t1 < b2 and t2 < b1
|
||||
|
||||
def rect_with_center((l, t, r, b), (x, y)):
|
||||
w = r - l
|
||||
h = b - t
|
||||
rl = x - w // 2
|
||||
rt = y - h // 2
|
||||
return (rl, rt, rl + w, rt + h)
|
||||
@@ -0,0 +1,26 @@
|
||||
#
|
||||
# Python GUI - Image Base - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
from GUI.Geometry import rect_sized
|
||||
|
||||
class ImageBase(Properties):
|
||||
"""Abstract base class for Image, Pixmap and GLPixmap."""
|
||||
|
||||
width = overridable_property('width', "Width of the image in pixels (read only).")
|
||||
height = overridable_property('height', "Height of the image in pixels (read only).")
|
||||
size = overridable_property('size', "Size of the image in pixels (read only).")
|
||||
bounds = overridable_property('bounds', "Bounding rectangle of the image in pixels (read only).")
|
||||
|
||||
def get_size(self):
|
||||
return (self.width, self.height)
|
||||
|
||||
def get_bounds(self):
|
||||
return rect_sized((0, 0), self.size)
|
||||
|
||||
def draw(self, canvas, src_rect, dst_rect):
|
||||
"""Draw the part of the image specified by src_rect on the given canvas,
|
||||
scaled to fit within dst_rect."""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
#
|
||||
# Python GUI - Images - Generic
|
||||
#
|
||||
|
||||
from GUI.Files import FileRef
|
||||
from GUI.Resources import get_resource
|
||||
from GUI import ImageBase
|
||||
|
||||
class Image(ImageBase):
|
||||
"""Class Image represents an RGB or RGBA image.
|
||||
|
||||
Constructors:
|
||||
Image(file = FileRef or pathname)
|
||||
"""
|
||||
|
||||
def from_resource(cls, name, **kwds):
|
||||
return get_resource(cls, name, **kwds)
|
||||
|
||||
from_resource = classmethod(from_resource)
|
||||
|
||||
def __init__(self, file):
|
||||
if isinstance(file, FileRef):
|
||||
file = file.path
|
||||
self._init_from_file(file)
|
||||
@@ -0,0 +1,107 @@
|
||||
#
|
||||
# PyGUI - OpenGL Display Lists - Generic
|
||||
#
|
||||
|
||||
from weakref import WeakKeyDictionary
|
||||
from OpenGL.GL import glGenLists, glNewList, glEndList, glCallList, \
|
||||
glDeleteLists, GL_COMPILE
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
from GUI.GGLContexts import current_share_group
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class DisplayListIdMap(WeakKeyDictionary):
|
||||
|
||||
def __del__(self):
|
||||
# Delete any display lists that have been allocated for this map.
|
||||
#print "GL.DisplayListIdMap.__del__:", self ###
|
||||
def free_display_list():
|
||||
glDeleteLists(gl_id, 1)
|
||||
for share_group, gl_id in self.items():
|
||||
context = share_group._some_member()
|
||||
if context:
|
||||
#print "...freeing display list id", gl_id, "for", share_group, "using", context ###
|
||||
context.with_context(free_display_list)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class DisplayList(Properties):
|
||||
"""This class encapsulates an OpenGL display list and maintains a
|
||||
representation of it for each OpenGL context with which it is used.
|
||||
Allocation and maintentance of display list numbers is handled
|
||||
automatically."""
|
||||
#
|
||||
# _gl_id ShareGroup -> int Mapping from OpenGL share group to
|
||||
# display list number
|
||||
|
||||
setup = overridable_property('setup',
|
||||
"""Function to set up the display list by making the necessary
|
||||
OpenGL calls, excluding glNewList and glEndList.""")
|
||||
|
||||
def __init__(self, setup = None):
|
||||
self._gl_id = DisplayListIdMap()
|
||||
self._setup = setup
|
||||
|
||||
def deallocate(self):
|
||||
"""Deallocate any OpenGL resources that have been allocated for this
|
||||
display list in any context."""
|
||||
self._gl_id.__del__()
|
||||
|
||||
def get_setup(self):
|
||||
return self._setup
|
||||
|
||||
def set_setup(self, x):
|
||||
self._setup = x
|
||||
|
||||
def call(self):
|
||||
"""Calls the display list using glCallList(). If this display list
|
||||
has not previously been used with the current context, allocates
|
||||
a display list number and arranges for do_setup() to be called
|
||||
to compile a representation of the display list."""
|
||||
share_group = current_share_group()
|
||||
gl_id = self._gl_id.get(share_group)
|
||||
if gl_id is None:
|
||||
gl_id = glGenLists(1)
|
||||
#print "GLDisplayList: assigned id %d for %s in share group %s" % (
|
||||
# gl_id, self, share_group) ###
|
||||
self._gl_id[share_group] = gl_id
|
||||
call_when_not_compiling_display_list(lambda: self._compile(gl_id))
|
||||
glCallList(gl_id)
|
||||
|
||||
def _compile(self, gl_id):
|
||||
global compiling_display_list
|
||||
compiling_display_list = True
|
||||
glNewList(gl_id, GL_COMPILE)
|
||||
try:
|
||||
self.do_setup()
|
||||
finally:
|
||||
glEndList()
|
||||
compiling_display_list = False
|
||||
|
||||
def do_setup(self):
|
||||
"""Make all the necessary OpenGL calls to compile the display list,
|
||||
except for glNewList() and glEndList() which will be called automatically
|
||||
before and after. The default implementation calls the 'setup' property."""
|
||||
setup = self._setup
|
||||
if setup:
|
||||
setup()
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"No setup function or do_setup method for GL.DisplayList")
|
||||
|
||||
|
||||
compiling_display_list = False
|
||||
pending_functions = []
|
||||
|
||||
def call_when_not_compiling_display_list(func):
|
||||
#print "GLDisplayLists: entering call_when_not_compiling_display_list" ###
|
||||
if compiling_display_list:
|
||||
#print "GLDisplayLists: deferring", func ###
|
||||
pending_functions.append(func)
|
||||
else:
|
||||
#print "GLDisplayLists: immediately calling", func ###
|
||||
func()
|
||||
while pending_functions:
|
||||
#print "GLDisplayLists: calling deferred", func ###
|
||||
pending_functions.pop()()
|
||||
#print "GLDisplayLists: exiting call_when_not_compiling_display_list" ###
|
||||
@@ -0,0 +1,29 @@
|
||||
#
|
||||
# PyGUI - OpenGL Context Sharing - Generic
|
||||
#
|
||||
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
class ShareGroup(object):
|
||||
"""Object representing a shared texture and display list
|
||||
namespace for OpenGL contexts."""
|
||||
|
||||
def __init__(self):
|
||||
self.contexts = WeakKeyDictionary()
|
||||
|
||||
def __contains__(self, context):
|
||||
"Test whether a GLView or GLPixmap is a member of this share group."
|
||||
return context in self.contexts
|
||||
|
||||
def __iter__(self):
|
||||
"Return an iterator over the members of this share group."
|
||||
return iter(self.contexts)
|
||||
|
||||
def _add(self, context):
|
||||
self.contexts[context] = 1
|
||||
|
||||
def _some_member(self, exclude = None):
|
||||
for member in self.contexts:
|
||||
if member is not exclude:
|
||||
return member
|
||||
return None
|
||||
@@ -0,0 +1,14 @@
|
||||
#
|
||||
# Python GUI - Labels - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Control
|
||||
|
||||
class Label(Control):
|
||||
"""A piece of static text for labelling items in a window."""
|
||||
|
||||
_default_tab_stop = False
|
||||
|
||||
text = overridable_property('text')
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#--------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Pop-up list control - Generic
|
||||
#
|
||||
#--------------------------------------------------------------
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Actions import Action
|
||||
from GUI import Control, application
|
||||
|
||||
class ListButton(Control, Action):
|
||||
"""A button that displays a value and provides a pop-up or
|
||||
pull-down list of choices."""
|
||||
|
||||
titles = overridable_property('titles',
|
||||
"List of item title strings")
|
||||
|
||||
values = overridable_property('values',
|
||||
"List of values corresponding to tiles, or None to use item index as value")
|
||||
|
||||
def _extract_initial_items(self, kwds):
|
||||
titles = kwds.pop('titles', None) or []
|
||||
values = kwds.pop('values', None)
|
||||
return titles, values
|
||||
|
||||
def get_titles(self):
|
||||
return self._titles
|
||||
|
||||
def set_titles(self, x):
|
||||
self._titles = x
|
||||
self._update_items()
|
||||
|
||||
def get_values(self):
|
||||
return self._values
|
||||
|
||||
def set_values(self, x):
|
||||
self._values = x
|
||||
|
||||
def get_value(self):
|
||||
i = self._get_selected_index()
|
||||
if i >= 0:
|
||||
values = self.values
|
||||
if values:
|
||||
return values[i]
|
||||
else:
|
||||
return i
|
||||
|
||||
def set_value(self, value):
|
||||
values = self.values
|
||||
if values:
|
||||
try:
|
||||
i = values.index(value)
|
||||
except ValueError:
|
||||
i = -1
|
||||
else:
|
||||
if value is None:
|
||||
i = -1
|
||||
else:
|
||||
i = value
|
||||
self._set_selected_index(i)
|
||||
|
||||
def do_action(self):
|
||||
try:
|
||||
Action.do_action(self)
|
||||
except:
|
||||
application().report_error()
|
||||
@@ -0,0 +1,335 @@
|
||||
#----------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Menus - Generic
|
||||
#
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
from GUI import Globals
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
def search_list_for_key(items, char, shift, option):
|
||||
for i in xrange(len(items)-1, -1, -1):
|
||||
result = items[i]._search_for_key(char, shift, option)
|
||||
if result:
|
||||
return result
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class Menu(Properties):
|
||||
"""Pull-down or pop-up menu class.
|
||||
|
||||
Menu(title, item_descriptors)
|
||||
constructs a menu with the given title and items. Each
|
||||
item_descriptor is of the form
|
||||
|
||||
"-"
|
||||
|
||||
for a separator,
|
||||
|
||||
("text/key", 'command_name')
|
||||
|
||||
for a single menu item, or
|
||||
|
||||
(["text/key", ...], 'command_name')
|
||||
|
||||
for an indexed item group. An indexed group is a group
|
||||
of items sharing the same command name and distinguished
|
||||
by an integer index. Items can be added to and removed
|
||||
from the group dynamically, to implement e.g. a font
|
||||
menu or windows menu.
|
||||
|
||||
The "key" part of the item descriptor (which is optional)
|
||||
specifies the keyboard equivalent. It should consist of
|
||||
a single character together with the following optional
|
||||
modifiers:
|
||||
|
||||
^ representing the Shift key
|
||||
@ representing the Alt or Option key
|
||||
"""
|
||||
|
||||
title = overridable_property('title', "Title string appearing in menu bar")
|
||||
special = overridable_property('special', "Menu appears at right end of menu bar")
|
||||
|
||||
_flat_items = None
|
||||
|
||||
def __init__(self, title, items, special = False, substitutions = {}, **kwds):
|
||||
self._title = title
|
||||
self._items = []
|
||||
self._special = special
|
||||
Properties.__init__(self, **kwds)
|
||||
self.extend(items, substitutions)
|
||||
|
||||
def get_title(self):
|
||||
return self._title
|
||||
|
||||
def get_special(self):
|
||||
return self._special
|
||||
|
||||
def item_with_command(self, cmd):
|
||||
for item in self._items:
|
||||
if item._command_name == cmd:
|
||||
return item
|
||||
return None
|
||||
|
||||
def append(self, item, substitutions = {}):
|
||||
items = self._items
|
||||
item = self._make_item(item, substitutions)
|
||||
if not (items and isinstance(item, MenuSeparator)
|
||||
and isinstance(items[-1], MenuSeparator)):
|
||||
items.append(item)
|
||||
|
||||
def extend(self, items, substitutions = {}):
|
||||
for item in items:
|
||||
self.append(item, substitutions)
|
||||
|
||||
def _make_item(self, item, substitutions):
|
||||
if isinstance(item, MenuItem):
|
||||
return item
|
||||
elif item == "-":
|
||||
return _menu_separator
|
||||
else:
|
||||
(text, cmd) = item
|
||||
if isinstance(text, basestring):
|
||||
return SingleMenuItem(text, cmd, substitutions)
|
||||
else:
|
||||
return MenuItemGroup(text, cmd)
|
||||
|
||||
def _command_and_args_for_item(self, item_num):
|
||||
i = 1
|
||||
for item in self._items:
|
||||
n = item._num_subitems()
|
||||
if item_num < i + n:
|
||||
return item._command_and_args_for_subitem(item_num - i)
|
||||
i += n
|
||||
return '', ()
|
||||
|
||||
def _update_platform_menu(self):
|
||||
# Called during menu setup after items have been enabled/checked.
|
||||
# Generic implementation rebuilds the whole menu from scratch.
|
||||
# Implementations may override this to be more elegant.
|
||||
self._rebuild_platform_menu()
|
||||
|
||||
def _rebuild_platform_menu(self):
|
||||
self._clear_platform_menu()
|
||||
for item in self._items:
|
||||
item._add_to_platform_menu(self)
|
||||
|
||||
def _search_for_key(self, char, shift, option):
|
||||
return search_list_for_key(self._items, char, shift, option)
|
||||
|
||||
def _get_flat_items(self):
|
||||
flat = self._flat_items
|
||||
if flat is None:
|
||||
flat = []
|
||||
for item in self._items:
|
||||
item._collect_flat_items(flat)
|
||||
self._flat_items = flat
|
||||
return flat
|
||||
|
||||
def _get_flat_item(self, i):
|
||||
return self._get_flat_items()[i]
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class MenuItem(Properties):
|
||||
# Internal class representing a menu item, group or separator.
|
||||
#
|
||||
# _command_name string Internal command name
|
||||
|
||||
def _num_subitems(self):
|
||||
return 1
|
||||
|
||||
def _split_text(self, text):
|
||||
# Split menu text into label and key combination.
|
||||
if "/" in text:
|
||||
return text.split("/")
|
||||
else:
|
||||
return text, ""
|
||||
|
||||
def _name(self):
|
||||
return self._label.replace("<app>", Globals.application_name)
|
||||
|
||||
def _collect_flat_items(self, result):
|
||||
result.append(self)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class MenuSeparator(MenuItem):
|
||||
# Internal class representing a menu separator.
|
||||
|
||||
_command_name = ''
|
||||
|
||||
def _add_to_platform_menu(self, menu):
|
||||
menu._add_separator_to_platform_menu()
|
||||
|
||||
def _search_for_key(self, char, shift, option):
|
||||
pass
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class SingleMenuItem(MenuItem):
|
||||
"""Class representing a menu item.
|
||||
|
||||
Properties:
|
||||
enabled boolean
|
||||
checked boolean
|
||||
"""
|
||||
|
||||
enabled = 0
|
||||
checked = 0
|
||||
_key = None
|
||||
_shift = 0
|
||||
_option = 0
|
||||
#_index = None
|
||||
|
||||
def __init__(self, text, cmd, substitutions = {}):
|
||||
label1, keycomb1 = self._split_text(text)
|
||||
label2, keycomb2 = self._split_text(substitutions.get(cmd, ""))
|
||||
self._label = label2 or label1
|
||||
keycomb = keycomb2 or keycomb1
|
||||
for c in keycomb:
|
||||
if c == '^':
|
||||
self._shift = 1
|
||||
elif c == '@':
|
||||
self._option = 1
|
||||
else:
|
||||
self._key = c.upper()
|
||||
self._command_name = cmd
|
||||
|
||||
def __str__(self):
|
||||
return "<SingleMenuItem %r %r Sh:%s Op:%s En:%s>" % (
|
||||
self._label, self._key, self._shift, self._option, self.enabled)
|
||||
|
||||
def _add_to_platform_menu(self, menu):
|
||||
menu._add_item_to_platform_menu(self, self._name(), self._command_name)
|
||||
|
||||
def _command_and_args_for_subitem(self, i):
|
||||
return self._command_name, ()
|
||||
|
||||
def _search_for_key(self, char, shift, option):
|
||||
if self._matches_key(char, shift, option):
|
||||
return self._command_name
|
||||
|
||||
def _matches_key(self, char, shift, option):
|
||||
return self._key == char and self._shift == shift \
|
||||
and self._option == option and self.enabled
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class MenuItemGroup(MenuItem):
|
||||
"""Class representing a menu item group.
|
||||
|
||||
Properties:
|
||||
enabled <- boolean Assigning to these changes the corresponding
|
||||
checked <- boolean property of all the group's items.
|
||||
|
||||
Operators:
|
||||
group[index] -> MenuItem
|
||||
|
||||
Methods:
|
||||
set_items(["text/key", ...])
|
||||
Replaces all the items in the group by the specified items.
|
||||
"""
|
||||
|
||||
enabled = overridable_property('enabled')
|
||||
checked = overridable_property('checked')
|
||||
|
||||
def __init__(self, text_list, cmd):
|
||||
self.set_items(text_list)
|
||||
self._command_name = cmd
|
||||
|
||||
def _num_subitems(self):
|
||||
return len(self._items)
|
||||
|
||||
def _command_and_args_for_subitem(self, i):
|
||||
return self._command_name, (i,)
|
||||
|
||||
def get_enabled(self):
|
||||
raise AttributeError("'enabled' property of MenuItemGroup is write-only")
|
||||
|
||||
def set_enabled(self, state):
|
||||
for item in self._items:
|
||||
item.enabled = state
|
||||
|
||||
def get_checked(self):
|
||||
raise AttributeError("'checked' property of MenuItemGroup is write-only")
|
||||
|
||||
def set_checked(self, state):
|
||||
for item in self._items:
|
||||
item.checked = state
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self._items[index]
|
||||
|
||||
def set_items(self, text_list):
|
||||
self._items = [SingleMenuItem(text, '') for text in text_list]
|
||||
|
||||
def _add_to_platform_menu(self, menu):
|
||||
#for item in self._items:
|
||||
# item._add_to_platform_menu(menu)
|
||||
cmd = self._command_name
|
||||
for index, item in enumerate(self._items):
|
||||
menu._add_item_to_platform_menu(item, item._name(), cmd, index)
|
||||
|
||||
def _search_for_key(self, char, shift, option):
|
||||
items = self._items
|
||||
for i in xrange(len(items)-1, -1, -1):
|
||||
if items[i]._matches_key(char, shift, option):
|
||||
return (self._command_name, i)
|
||||
|
||||
def _collect_flat_items(self, result):
|
||||
for item in self._items:
|
||||
item._collect_flat_items(result)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
_menu_separator = MenuSeparator()
|
||||
_dummy_menu_item = SingleMenuItem("", '')
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class MenuState:
|
||||
"""A MenuState object is used to enable/disable and check/uncheck
|
||||
menu items, and to add or remove items of indexed groups,
|
||||
during the menu setup phase of menu command handling.
|
||||
|
||||
Each single menu item or item group appears as an attribute of
|
||||
the MenuState object, with the command name as the attribute name,
|
||||
allowing operations such as
|
||||
|
||||
menu_state.copy_cmd.enabled = 1
|
||||
menu_state.font_cmd[current_font].checked = 1
|
||||
|
||||
The command name may also be used as a mapping index.
|
||||
|
||||
Operators:
|
||||
menu_state.command_name -> MenuItem
|
||||
menu_state['command_name'] -> MenuItem
|
||||
"""
|
||||
|
||||
def __init__(self, menu_list):
|
||||
mapping = {}
|
||||
for menu in menu_list:
|
||||
for item in menu._items:
|
||||
cmd = item._command_name
|
||||
if cmd:
|
||||
mapping[cmd] = item
|
||||
self._mapping = mapping
|
||||
|
||||
def __getattr__(self, name):
|
||||
try:
|
||||
return self._mapping[name]
|
||||
except KeyError:
|
||||
if name.startswith("__"):
|
||||
raise AttributeError, name
|
||||
return _dummy_menu_item
|
||||
|
||||
__getitem__ = __getattr__
|
||||
|
||||
def reset(self):
|
||||
"""Disable and uncheck all items."""
|
||||
for item in self._mapping.values():
|
||||
item.enabled = 0
|
||||
item.checked = None
|
||||
@@ -0,0 +1,27 @@
|
||||
#
|
||||
# Python GUI - Mouse trackers - Generic
|
||||
#
|
||||
|
||||
from GUI import application
|
||||
|
||||
class MouseTracker(object):
|
||||
"""Iterator used to track movements of the mouse following a mouse_down
|
||||
event in a Views. Each call to the next() method returns a mouse_drag
|
||||
event, except for the last one, which returns a mouse_up event."""
|
||||
|
||||
def __init__(self, view):
|
||||
self._view = view
|
||||
self._finished = 0
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def next(self):
|
||||
if not self._finished:
|
||||
event = self._next_mouse_event()
|
||||
event.position = event.position_in(self._view)
|
||||
if event.kind == 'mouse_up':
|
||||
self._finished = 1
|
||||
return event
|
||||
else:
|
||||
raise StopIteration
|
||||
@@ -0,0 +1,20 @@
|
||||
#
|
||||
# Python GUI - Pixmap - Generic
|
||||
#
|
||||
|
||||
from GUI import ImageBase
|
||||
|
||||
class Pixmap(ImageBase):
|
||||
"""A Pixmap is an offscreen area that can be used both as a
|
||||
destination for drawing and a source of image data for drawing
|
||||
in a View or another Pixmap.
|
||||
|
||||
Constructor:
|
||||
Pixmap(width, height)
|
||||
"""
|
||||
|
||||
def with_canvas(self, proc):
|
||||
"""Call the given procedure with a canvas suitable for drawing on
|
||||
this Pixmap. The canvas is valid only for the duration of the call,
|
||||
and should not be retained beyond it."""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,167 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Printing - Generic
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from __future__ import division
|
||||
from math import ceil
|
||||
import cPickle as pickle
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import application
|
||||
|
||||
class PageSetup(object):
|
||||
"""Holder of information specified by the "Page Setup" command."""
|
||||
|
||||
paper_name = overridable_property('paper_name')
|
||||
paper_width = overridable_property('paper_width')
|
||||
paper_height = overridable_property('paper_height')
|
||||
left_margin = overridable_property('left_margin')
|
||||
top_margin = overridable_property('top_margin')
|
||||
right_margin = overridable_property('right_margin')
|
||||
bottom_margin = overridable_property('bottom_margin')
|
||||
orientation = overridable_property('orientation')
|
||||
|
||||
paper_size = overridable_property('paper_size')
|
||||
margins = overridable_property('margins')
|
||||
page_width = overridable_property('page_width')
|
||||
page_height = overridable_property('page_height')
|
||||
page_size = overridable_property('page_size')
|
||||
page_rect = overridable_property('page_rect')
|
||||
printable_rect = overridable_property('printable_rect') # May not work
|
||||
printer_name = overridable_property('printer_name')
|
||||
|
||||
_pickle_attributes = ['paper_name', 'paper_size', 'margins',
|
||||
'printer_name', 'orientation']
|
||||
|
||||
def __getstate__(self):
|
||||
state = {}
|
||||
for name in self._pickle_attributes:
|
||||
state[name] = getattr(self, name)
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
for name, value in state.iteritems():
|
||||
setattr(self, name, value)
|
||||
|
||||
def from_string(s):
|
||||
"""Restore a pickled PageSetup object from a string."""
|
||||
return pickle.loads(s)
|
||||
|
||||
from_string = staticmethod(from_string)
|
||||
|
||||
def to_string(self):
|
||||
"""Pickle the PageSetup object and return it as a string."""
|
||||
return pickle.dumps(self, 2)
|
||||
|
||||
def get_paper_size(self):
|
||||
return self.paper_width, self.paper_height
|
||||
|
||||
def set_paper_size(self, x):
|
||||
self.paper_width, self.paper_height = x
|
||||
|
||||
def get_margins(self):
|
||||
return self.left_margin, self.top_margin, self.right_margin, self.bottom_margin
|
||||
|
||||
def set_margins(self, x):
|
||||
self.left_margin, self.top_margin, self.right_margin, self.bottom_margin = x
|
||||
|
||||
def get_page_width(self):
|
||||
return self.paper_width - self.left_margin - self.right_margin
|
||||
|
||||
def get_page_height(self):
|
||||
return self.paper_height - self.top_margin - self.bottom_margin
|
||||
|
||||
def get_page_size(self):
|
||||
return (self.page_width, self.page_height)
|
||||
|
||||
def get_page_rect(self):
|
||||
lm, tm, rm, bm = self.margins
|
||||
pw, ph = self.paper_size
|
||||
return (lm, tm, pw - rm, ph - bm)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Printable(object):
|
||||
"""Mixin class for components implementing the "Print" command."""
|
||||
|
||||
printable = overridable_property('printable', "Whether this component should handle the 'Print' command.")
|
||||
page_setup = overridable_property('page_setup', "The PageSetup object to use for printing.")
|
||||
print_title = overridable_property('print_title', "Title for print job.")
|
||||
|
||||
_printable = True
|
||||
|
||||
def get_printable(self):
|
||||
return self._printable
|
||||
|
||||
def set_printable(self, x):
|
||||
self._printable = x
|
||||
|
||||
def get_print_title(self):
|
||||
window = self.window
|
||||
if window:
|
||||
return window.title
|
||||
else:
|
||||
return ""
|
||||
|
||||
def get_page_setup(self):
|
||||
result = None
|
||||
model = getattr(self, 'model', None)
|
||||
if model:
|
||||
result = getattr(model, 'page_setup', None)
|
||||
if not result:
|
||||
result = application().page_setup
|
||||
return result
|
||||
|
||||
def setup_menus(self, m):
|
||||
if self.printable:
|
||||
m.print_cmd.enabled = True
|
||||
|
||||
def print_cmd(self):
|
||||
if self.printable:
|
||||
page_setup = self.page_setup
|
||||
if page_setup:
|
||||
self.print_view(page_setup)
|
||||
else:
|
||||
self.pass_to_next_handler('print_cmd')
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Paginator(object):
|
||||
"""Used internally. A generic pagination algorithm for printing."""
|
||||
|
||||
def __init__(self, view, page_setup):
|
||||
self.view = view
|
||||
extent_width, extent_height = view.get_print_extent()
|
||||
#paper_width, paper_height = page_setup.paper_size
|
||||
#lm, tm, rm, bm = page_setup.margins
|
||||
#page_width = int(paper_width - lm - rm)
|
||||
#page_height = int(paper_height - tm - bm)
|
||||
page_width, page_height = page_setup.page_size
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
from AlertFunctions import stop_alert
|
||||
stop_alert("Margins are too large for the page size.")
|
||||
return
|
||||
self.extent_rect = (0, 0, extent_width, extent_height)
|
||||
self.page_width = page_width
|
||||
self.page_height = page_height
|
||||
self.left_margin = page_setup.left_margin
|
||||
self.top_margin = page_setup.top_margin
|
||||
self.pages_wide = int(ceil(extent_width / page_width))
|
||||
self.pages_high = int(ceil(extent_height / page_height))
|
||||
self.num_pages = self.pages_wide * self.pages_high
|
||||
|
||||
def draw_page(self, canvas, page_num):
|
||||
row, col = divmod(page_num, self.pages_wide)
|
||||
view_left = col * self.page_width
|
||||
view_top = row * self.page_height
|
||||
view_right = view_left + self.page_width
|
||||
view_bottom = view_top + self.page_height
|
||||
view_rect = (view_left, view_top, view_right, view_bottom)
|
||||
dx = self.left_margin - view_left
|
||||
dy = self.top_margin - view_top
|
||||
canvas.translate(dx, dy)
|
||||
canvas.rectclip(self.extent_rect)
|
||||
canvas.rectclip(view_rect)
|
||||
canvas._printing = True
|
||||
self.view.draw(canvas, view_rect)
|
||||
@@ -0,0 +1,52 @@
|
||||
#
|
||||
# Python GUI - Radio buttons - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Control
|
||||
|
||||
class RadioButton(Control):
|
||||
"""RadioButtons are used in groups to represent a 1-of-N
|
||||
choice. A group of RadioButtons is coordinated by a
|
||||
RadioGroup object. The 'group' property indicates the
|
||||
RadioGroup to which it belongs, and the 'value' property
|
||||
is the value to which the RadioGroup's value is set
|
||||
when this RadioButton is selected."""
|
||||
|
||||
group = overridable_property('group', """The RadioGroup to
|
||||
which this radio button belongs.""")
|
||||
|
||||
value = overridable_property('value', """The value to which
|
||||
the associated radio group's 'value' property should be
|
||||
set when this radio button is selected.""")
|
||||
|
||||
_group = None
|
||||
_value = None
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_group(self):
|
||||
return self._group
|
||||
|
||||
def set_group(self, new_group):
|
||||
old_group = self._group
|
||||
if new_group is not old_group:
|
||||
if old_group:
|
||||
old_group._remove_item(self)
|
||||
self._group = new_group
|
||||
if new_group:
|
||||
new_group._add_item(self)
|
||||
|
||||
def get_value(self):
|
||||
return self._value
|
||||
|
||||
def set_value(self, new_value):
|
||||
old_value = self._value
|
||||
if new_value != old_value:
|
||||
self._value = new_value
|
||||
self._value_changed()
|
||||
|
||||
def _value_changed(self):
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,87 @@
|
||||
#
|
||||
# Python GUI - Radio groups - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
from GUI.Actions import Action
|
||||
|
||||
class RadioGroup(Properties, Action):
|
||||
"""A RadioGroup coordinates a group of RadioButtons.
|
||||
It has a 'value' property which is equal to the value
|
||||
of the currently selected RadioButton. It may be given
|
||||
an action procedure to execute when its value changes.
|
||||
|
||||
Operations:
|
||||
iter(group)
|
||||
Returns an iterator over the items of the group.
|
||||
"""
|
||||
|
||||
value = overridable_property('value', """The value of the currently
|
||||
selected radio button.""")
|
||||
|
||||
_items = None
|
||||
_value = None
|
||||
|
||||
def __init__(self, items = [], **kwds):
|
||||
Properties.__init__(self, **kwds)
|
||||
self._items = []
|
||||
self.add_items(items)
|
||||
|
||||
#
|
||||
# Operations
|
||||
#
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._items)
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_value(self):
|
||||
return self._value
|
||||
|
||||
def set_value(self, x):
|
||||
if self._value <> x:
|
||||
self._value = x
|
||||
self._value_changed()
|
||||
self.do_action()
|
||||
|
||||
#
|
||||
# Adding and removing items
|
||||
#
|
||||
|
||||
def add_items(self, items):
|
||||
"Add a sequence of RadioButtons to this group."
|
||||
for item in items:
|
||||
self.add_item(item)
|
||||
|
||||
def add_item(self, item):
|
||||
"Add a RadioButton to this group."
|
||||
item.group = self
|
||||
|
||||
def remove_items(self, items):
|
||||
"Remove a sequence of RadioButtons from this group."
|
||||
for item in items:
|
||||
item.group = None
|
||||
|
||||
def remove_item(self, item):
|
||||
"Remove a RadioButton from this group."
|
||||
item.group = None
|
||||
|
||||
def _add_item(self, item):
|
||||
self._items.append(item)
|
||||
self._item_added(item)
|
||||
|
||||
def _remove_item(self, item):
|
||||
self._items.remove(item)
|
||||
self._item_removed(item)
|
||||
|
||||
def _item_added(self, item):
|
||||
raise NotImplementedError
|
||||
|
||||
def _item_removed(self, item):
|
||||
raise NotImplementedError
|
||||
|
||||
def _value_changed(self):
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,168 @@
|
||||
#
|
||||
# Python GUI - Scrollable Views - Generic
|
||||
#
|
||||
|
||||
from GUI.Geometry import rect_sized, add_pt, sub_pt
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Geometry import sect_rect
|
||||
from GUI import DrawableContainer
|
||||
|
||||
default_extent = (300, 300)
|
||||
default_line_scroll_amount = (16, 16)
|
||||
default_scrolling = 'hv'
|
||||
|
||||
class ScrollableView(DrawableContainer):
|
||||
"""A ScrollableView is a 2D drawing area having its own coordinate
|
||||
system and clipping area, with support for scrolling."""
|
||||
|
||||
scrolling = overridable_property('scrolling',
|
||||
"String containing 'h' for horizontal and 'v' for vertical scrolling.")
|
||||
|
||||
hscrolling = overridable_property('hscrolling',
|
||||
"True if horizontal scrolling is enabled.")
|
||||
|
||||
vscrolling = overridable_property('vscrolling',
|
||||
"True if vertical scrolling is enabled.")
|
||||
|
||||
extent = overridable_property('extent',
|
||||
"Size of scrollable area in local coordinates.")
|
||||
|
||||
scroll_offset = overridable_property('scroll_offset',
|
||||
"Current scrolling position.")
|
||||
|
||||
line_scroll_amount = overridable_property('line_scroll_amount',
|
||||
"Tuple specifying horizontal and vertical line scrolling increments.")
|
||||
|
||||
background_color = overridable_property('background_color',
|
||||
"Color with which to fill areas outside the extent, or None")
|
||||
|
||||
#scroll_bars = overridable_property('scroll_bars',
|
||||
# "Attached ScrollBar instances.")
|
||||
#
|
||||
## _scroll_bars [ScrollBar]
|
||||
|
||||
def set(self, **kwds):
|
||||
if 'scrolling' in kwds:
|
||||
self.scrolling = kwds.pop('scrolling')
|
||||
DrawableContainer.set(self, **kwds)
|
||||
|
||||
def get_scrolling(self):
|
||||
chars = []
|
||||
if self.hscrolling:
|
||||
chars.append('h')
|
||||
if self.vscrolling:
|
||||
chars.append('v')
|
||||
return ''.join(chars)
|
||||
|
||||
def set_scrolling(self, value):
|
||||
self.hscrolling = 'h' in value
|
||||
self.vscrolling = 'v' in value
|
||||
|
||||
def viewed_rect(self):
|
||||
"""Return the rectangle in local coordinates bounding the currently
|
||||
visible part of the extent."""
|
||||
return rect_sized(self.scroll_offset, self.size)
|
||||
|
||||
def get_print_extent(self):
|
||||
return self.extent
|
||||
|
||||
def get_background_color(self):
|
||||
return self._background_color
|
||||
|
||||
def set_background_color(self, x):
|
||||
self._background_color = x
|
||||
self.invalidate()
|
||||
|
||||
#
|
||||
# Coordinate transformation
|
||||
#
|
||||
|
||||
def local_to_container_offset(self):
|
||||
return sub_pt(self.position, self.scroll_offset)
|
||||
|
||||
#
|
||||
# Scrolling
|
||||
#
|
||||
|
||||
def h_line_scroll_amount(self):
|
||||
"""Return the horizontal line scroll increment."""
|
||||
return self.line_scroll_amount[0]
|
||||
|
||||
def v_line_scroll_amount(self):
|
||||
"""Return the vertical line scroll increment."""
|
||||
return self.line_scroll_amount[1]
|
||||
|
||||
def h_page_scroll_amount(self):
|
||||
"""Return the horizontal page scroll increment."""
|
||||
return self.width - self.h_line_scroll_amount()
|
||||
|
||||
def v_page_scroll_amount(self):
|
||||
"""Return the vertical page scroll increment."""
|
||||
return self.height - self.v_line_scroll_amount()
|
||||
|
||||
def scroll_by(self, dx, dy):
|
||||
"""Scroll by the given amount horizontally and vertically."""
|
||||
self.scroll_offset = add_pt(self.scroll_offset, (dx, dy))
|
||||
|
||||
def scroll_line_left(self):
|
||||
"""Called by horizontal scroll bar to scroll left by one line."""
|
||||
self.scroll_by(-self.h_line_scroll_amount(), 0)
|
||||
|
||||
def scroll_line_right(self):
|
||||
"""Called by horizontal scroll bar to scroll right by one line."""
|
||||
self.scroll_by(self.h_line_scroll_amount(), 0)
|
||||
|
||||
def scroll_line_up(self):
|
||||
"""Called by vertical scroll bar to scroll up by one line."""
|
||||
self.scroll_by(0, -self.v_line_scroll_amount())
|
||||
|
||||
def scroll_line_down(self):
|
||||
"""Called by vertical scroll bar to scroll down by one line."""
|
||||
self.scroll_by(0, self.v_line_scroll_amount())
|
||||
|
||||
def scroll_page_left(self):
|
||||
"""Called by horizontal scroll bar to scroll left by one page."""
|
||||
self.scroll_by(-self.h_page_scroll_amount(), 0)
|
||||
|
||||
def scroll_page_right(self):
|
||||
"""Called by horizontal scroll bar to scroll right by one page."""
|
||||
self.scroll_by(self.h_page_scroll_amount(), 0)
|
||||
|
||||
def scroll_page_up(self):
|
||||
"""Called by vertical scroll bar to scroll up by one page."""
|
||||
self.scroll_by(0, -self.v_page_scroll_amount())
|
||||
|
||||
def scroll_page_down(self):
|
||||
"""Called by vertical scroll bar to scroll down by one page."""
|
||||
self.scroll_by(0, self.v_page_scroll_amount())
|
||||
|
||||
#
|
||||
# Background drawing
|
||||
#
|
||||
|
||||
def _draw_background(self, canvas, clip_rect):
|
||||
# If the view has a background color, uses it to fill the parts of the
|
||||
# clip_rect that are outside the view's extent and returns the remaining
|
||||
# rectangle. Otherwise, returns the clip_rect unchanged.
|
||||
color = self._background_color
|
||||
if color:
|
||||
vl, vt, vr, vb = clip_rect
|
||||
ew, eh = self.extent
|
||||
if vr > ew or vb > eh:
|
||||
#if getattr(self, "_debug_bg", False): ###
|
||||
# print "ScrollableView: old backcolor =", canvas.backcolor ###
|
||||
canvas.gsave()
|
||||
canvas.backcolor = color
|
||||
if ew < vr:
|
||||
#if getattr(self, "_debug_bg", False): ###
|
||||
# print "ScrollableView: erasing", (ew, vt, vr, vb) ###
|
||||
canvas.erase_rect((ew, vt, vr, vb))
|
||||
if eh < vb:
|
||||
if getattr(self, "_debug_bg", False): ###
|
||||
print "ScrollableView: erasing", (vl, eh, ew, vb) ###
|
||||
canvas.erase_rect((vl, eh, ew, vb))
|
||||
canvas.grestore()
|
||||
#if getattr(self, "_debug_bg", False): ###
|
||||
# print "ScrollableView: restored backcolor =", canvas.backcolor ###
|
||||
return sect_rect(clip_rect, (0, 0, ew, eh))
|
||||
return clip_rect
|
||||
@@ -0,0 +1,32 @@
|
||||
#
|
||||
# Python GUI - Slider - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Actions import Action
|
||||
from GUI import Control
|
||||
|
||||
class Slider(Control, Action):
|
||||
"""A control for entering a value by moving a knob along a scale.
|
||||
|
||||
Constructor:
|
||||
Slider(orient)
|
||||
where orient = 'h' for horizontal or 'v' for vertical.
|
||||
"""
|
||||
|
||||
_default_length = 100
|
||||
|
||||
value = overridable_property('value', "The current value of the control")
|
||||
min_value = overridable_property('min_value', "Minimum value of the control")
|
||||
max_value = overridable_property('max_value', "Maximum value of the control")
|
||||
range = overridable_property('range', "Tuple (min_value, max_value)")
|
||||
ticks = overridable_property('ticks', "Number of tick marks")
|
||||
discrete = overridable_property('discrete', "Whether to constrain value to ticks")
|
||||
live = overridable_property('live', "Whether to invoke action continuously while dragging")
|
||||
|
||||
def get_range(self):
|
||||
return (self.min_value, self.max_value)
|
||||
|
||||
def set_range(self, x):
|
||||
self.min_value = x[0]
|
||||
self.max_value = x[1]
|
||||
@@ -0,0 +1,117 @@
|
||||
#-------------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Standard Menus - Generic
|
||||
#
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
from GUI.Compatibility import set
|
||||
from GUI import Menu
|
||||
from GUI import MenuList
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
class CommandSet(set):
|
||||
"""A set of menu command names.
|
||||
|
||||
Constructors:
|
||||
CommandSet(string)
|
||||
CommandSet(sequence of strings)
|
||||
|
||||
Operations:
|
||||
string in CommandSet
|
||||
CommandSet + x
|
||||
CommmandSet - x
|
||||
x + CommandSet
|
||||
x - CommandSet
|
||||
CommandSet += x
|
||||
CommandSet -= x
|
||||
where x is a CommandSet, a string or a sequence of strings
|
||||
"""
|
||||
|
||||
def __init__(self, arg = None):
|
||||
if arg:
|
||||
if isinstance(arg, basestring):
|
||||
arg = [arg]
|
||||
set.__init__(self, arg)
|
||||
|
||||
def __or__(self, other):
|
||||
return set.__or__(self, as_command_set(other))
|
||||
|
||||
__ror__ = __add__ = __radd__ = __or__
|
||||
|
||||
def __ior__(self, other):
|
||||
return set.__ior__(self, as_command_set(other))
|
||||
|
||||
__iadd__ = __ior__
|
||||
|
||||
def __sub__(self, other):
|
||||
return set.__sub__(self, as_command_set(other))
|
||||
|
||||
def __rsub__(self, other):
|
||||
return as_command_set(other) - self
|
||||
|
||||
def __isub__(self, other):
|
||||
return set.__isub__(self, as_command_set(other))
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
def as_command_set(x):
|
||||
if not isinstance(x, CommandSet):
|
||||
if isinstance(x, basestring):
|
||||
x = [x]
|
||||
x = CommandSet(x)
|
||||
return x
|
||||
|
||||
def filter_menu_items(items, include):
|
||||
result = []
|
||||
sep = False
|
||||
for item in items:
|
||||
if item == "-":
|
||||
sep = True
|
||||
elif item[1] in include:
|
||||
if sep:
|
||||
result.append("-")
|
||||
sep = False
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
def build_menus(spec_list, substitutions = {}, include = None, exclude = None):
|
||||
if include is None:
|
||||
include = sum(default_includes)
|
||||
include = include + sum(always_include)
|
||||
if exclude is not None:
|
||||
include = include - exclude
|
||||
menus = []
|
||||
for title, items, special in spec_list:
|
||||
items = filter_menu_items(items, include)
|
||||
if items:
|
||||
menus.append(Menu(title, items, special = special, substitutions = substitutions))
|
||||
return MenuList(menus)
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
fundamental_cmds = CommandSet(['quit_cmd'])
|
||||
help_cmds = CommandSet(['about_cmd', 'help_cmd'])
|
||||
pref_cmds = CommandSet(['preferences_cmd'])
|
||||
file_cmds = CommandSet(['new_cmd', 'open_cmd', 'close_cmd', 'save_cmd', 'save_as_cmd', 'revert_cmd'])
|
||||
print_cmds = CommandSet(['page_setup_cmd', 'print_cmd'])
|
||||
edit_cmds = CommandSet(['undo_cmd', 'redo_cmd', 'cut_cmd', 'copy_cmd', 'paste_cmd', 'clear_cmd', 'select_all_cmd'])
|
||||
|
||||
always_include = [fundamental_cmds, edit_cmds]
|
||||
default_includes = [help_cmds, pref_cmds, file_cmds, print_cmds]
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
|
||||
if __name__ == "__main__":
|
||||
s1 = CommandSet('a')
|
||||
print "s1 =", s1
|
||||
s2 = CommandSet(['a', 'b'])
|
||||
print "s2 =", s2
|
||||
s3 = s2 + 'c'
|
||||
print "s3 =", s3
|
||||
s4 = 'd' + s3
|
||||
print "s4 =", s4
|
||||
s5 = s4 - 'b'
|
||||
print "s5 =", s5
|
||||
s6 = ['a', 'b', 'c', 'd', 'e', 'f'] - s5
|
||||
print "s6 =", s6
|
||||
@@ -0,0 +1,37 @@
|
||||
#
|
||||
# PyGUI - Tasks - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
class Task(Properties):
|
||||
"""A Task represents an action to be performed after a specified
|
||||
time interval, either once or repeatedly.
|
||||
|
||||
Constructor:
|
||||
Task(proc, interval, repeat = False, start = True)
|
||||
Creates a task to call the given proc, which should be
|
||||
a callable object of no arguments, after the specified
|
||||
interval in seconds from the time the task is scheduled.
|
||||
If repeat is true, the task will be automatically re-scheduled
|
||||
each time the proc is called. If start is true, the task will be
|
||||
automatically scheduled upon creation; otherwise the start()
|
||||
method must be called to schedule the task.
|
||||
"""
|
||||
|
||||
interval = overridable_property('interval', "Time in seconds between firings")
|
||||
repeat = overridable_property('repeat', "Whether to fire repeatedly or once only")
|
||||
|
||||
def __del__(self):
|
||||
self.stop()
|
||||
|
||||
scheduled = overridable_property('scheduled',
|
||||
"True if the task is currently scheduled. Read-only.")
|
||||
|
||||
def start(self):
|
||||
"""Schedule the task if it is not already scheduled."""
|
||||
raise NotImplementedError("GUI.Task.start")
|
||||
|
||||
def stop(self):
|
||||
"""Unschedules the task if it is currently scheduled."""
|
||||
raise NotImplementedError("GUI.Task.stop")
|
||||
@@ -0,0 +1,34 @@
|
||||
#
|
||||
# Python GUI - Text Editor - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Component
|
||||
from GUI import EditCmdHandler
|
||||
from GUI.Printing import Printable
|
||||
|
||||
class TextEditor(Component, EditCmdHandler, Printable):
|
||||
"""A component for editing substantial amounts of text. The text is
|
||||
kept internally to the component and cannot be shared between views."""
|
||||
|
||||
text = overridable_property('text', "The contents as a string.")
|
||||
text_length = overridable_property('text_length', "Number of characters in the text.")
|
||||
selection = overridable_property('selection', "Range of text selected.")
|
||||
font = overridable_property('font')
|
||||
tab_spacing = overridable_property('tab_spacing', "Distance between tab stops")
|
||||
|
||||
def setup_menus(self, m):
|
||||
Component.setup_menus(self, m)
|
||||
EditCmdHandler.setup_menus(self, m)
|
||||
Printable.setup_menus(self, m)
|
||||
|
||||
def key_down(self, e):
|
||||
if e.key == 'enter':
|
||||
self.pass_to_next_handler('key_down', e)
|
||||
else:
|
||||
Component.key_down(self, e)
|
||||
|
||||
def print_view(self, page_setup):
|
||||
from TextEditorPrinting import TextEditorPrintView
|
||||
view = TextEditorPrintView(self, page_setup)
|
||||
view.print_view(page_setup)
|
||||
@@ -0,0 +1,76 @@
|
||||
#
|
||||
# Python GUI - Text fields - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Actions import ActionBase, action_property
|
||||
from GUI import application
|
||||
from GUI import Control
|
||||
from GUI import EditCmdHandler
|
||||
|
||||
class TextField(Control, ActionBase, EditCmdHandler):
|
||||
"""A control for entering and editing small amounts of text."""
|
||||
|
||||
text = overridable_property('text')
|
||||
selection = overridable_property('selection', "Range of text selected.")
|
||||
multiline = overridable_property('multiline', "Multiple text lines allowed.")
|
||||
password = overridable_property('password', "Display characters obfuscated.")
|
||||
enter_action = action_property('enter_action', "Action to be performed "
|
||||
"when the Return or Enter key is pressed.")
|
||||
escape_action = action_property('escape_action', "Action to be performed "
|
||||
"when the Escape key is pressed.")
|
||||
|
||||
_may_be_password = True
|
||||
|
||||
#_tabbable = True
|
||||
_default_tab_stop = True
|
||||
_user_tab_stop_override = False
|
||||
_enter_action = 'do_default_action'
|
||||
_escape_action = 'do_cancel_action'
|
||||
|
||||
_intercept_tab_key = True
|
||||
|
||||
def __init__(self, **kwds):
|
||||
self._multiline = kwds.pop('multiline')
|
||||
Control.__init__(self, **kwds)
|
||||
|
||||
def get_multiline(self):
|
||||
return self._multiline
|
||||
|
||||
def key_down(self, event):
|
||||
#print "GTextField.key_down for", self ###
|
||||
c = event.char
|
||||
if c == '\r':
|
||||
if event.key == 'enter' or not self._multiline:
|
||||
self.do_enter_action()
|
||||
return
|
||||
if c == '\x1b':
|
||||
self.do_escape_action()
|
||||
return
|
||||
if c == '\t':
|
||||
if self._intercept_tab_key:
|
||||
self.pass_event_to_next_handler(event)
|
||||
return
|
||||
Control.key_down(self, event)
|
||||
|
||||
def setup_menus(self, m):
|
||||
Control.setup_menus(self, m)
|
||||
EditCmdHandler.setup_menus(self, m)
|
||||
|
||||
def do_enter_action(self):
|
||||
self.do_named_action('enter_action')
|
||||
|
||||
def do_escape_action(self):
|
||||
self.do_named_action('escape_action')
|
||||
|
||||
def get_text_length(self):
|
||||
# Implementations can override this if they have a more
|
||||
# efficient way of getting the text length.
|
||||
return len(self.text)
|
||||
|
||||
def get_value(self):
|
||||
return self.text
|
||||
|
||||
def set_value(self, x):
|
||||
self.text = x
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Utilities - Generic
|
||||
#
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
def splitdict(src, *names, **defaults):
|
||||
result = {}
|
||||
for name in names:
|
||||
if name in src:
|
||||
result[name] = src.pop(name)
|
||||
for name, default in defaults.iteritems():
|
||||
result[name] = src.pop(name, default)
|
||||
return result
|
||||
@@ -0,0 +1,135 @@
|
||||
#
|
||||
# Python GUI - View Base - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
|
||||
class ViewBase(object):
|
||||
"""ViewBase is an abstract base class for user-defined views.
|
||||
It provides facilities for handling mouse and keyboard events
|
||||
and associating the view with one or more models, and default
|
||||
behaviour for responding to changes in the models."""
|
||||
|
||||
models = overridable_property('models',
|
||||
"List of Models being observed. Do not modify directly.")
|
||||
|
||||
model = overridable_property('model',
|
||||
"Convenience property for views which observe only one Model.")
|
||||
|
||||
cursor = overridable_property('cursor',
|
||||
"The cursor to display over the view.")
|
||||
|
||||
# _models [Model]
|
||||
|
||||
_cursor = None
|
||||
|
||||
def __init__(self):
|
||||
self._models = []
|
||||
|
||||
def destroy(self):
|
||||
#print "GViewBase.destroy:", self ###
|
||||
for m in self._models[:]:
|
||||
#print "GViewBase.destroy: removing model", m ###
|
||||
self.remove_model(m)
|
||||
|
||||
def setup_menus(self, m):
|
||||
pass
|
||||
|
||||
#
|
||||
# Getting properties
|
||||
#
|
||||
|
||||
def get_model(self):
|
||||
models = self._models
|
||||
if models:
|
||||
return self._models[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_models(self):
|
||||
return self._models
|
||||
|
||||
#
|
||||
# Setting properties
|
||||
#
|
||||
|
||||
def set_model(self, new_model):
|
||||
models = self._models
|
||||
if not (len(models) == 1 and models[0] == new_model):
|
||||
for old_model in models[:]:
|
||||
self.remove_model(old_model)
|
||||
if new_model:
|
||||
self.add_model(new_model)
|
||||
|
||||
#
|
||||
# Model association
|
||||
#
|
||||
|
||||
def add_model(self, model):
|
||||
"""Add the given Model to the set of models being observed."""
|
||||
if model not in self._models:
|
||||
self._models.append(model)
|
||||
model.add_view(self)
|
||||
self.model_added(model)
|
||||
|
||||
def remove_model(self, model):
|
||||
"""Remove the given Model from the set of models being observed."""
|
||||
if model in self._models:
|
||||
self._models.remove(model)
|
||||
model.remove_view(self)
|
||||
self.model_removed(model)
|
||||
|
||||
def model_added(self, model):
|
||||
"""Called after a model has been added to the view."""
|
||||
pass
|
||||
|
||||
def model_removed(self, model):
|
||||
"""Called after a model has been removed from the view."""
|
||||
pass
|
||||
|
||||
#
|
||||
# Input event handling
|
||||
#
|
||||
|
||||
def track_mouse(self):
|
||||
"""Following a mouse_down event, returns an iterator which can be used
|
||||
to track the movements of the mouse until the mouse is released.
|
||||
Each call to the iterator's next() method returns a mouse_drag
|
||||
event, except for the last one, which returns a mouse_up event."""
|
||||
raise NotImplementedError
|
||||
|
||||
def targeted(self):
|
||||
"""Called when the component becomes the target within its Window."""
|
||||
pass
|
||||
|
||||
def untargeted(self):
|
||||
"""Called when the component ceases to be the target within its Window."""
|
||||
pass
|
||||
|
||||
#
|
||||
# Cursors
|
||||
#
|
||||
|
||||
def get_cursor(self, x):
|
||||
return self._cursor
|
||||
|
||||
def set_cursor(self, x):
|
||||
self._cursor = x
|
||||
self._cursor_changed()
|
||||
|
||||
#
|
||||
# Callbacks
|
||||
#
|
||||
|
||||
def model_changed(self, model, *args, **kwds):
|
||||
"""Default method called by the attached Model's notify_views
|
||||
method. Default is to invalidate the whole view."""
|
||||
self.invalidate()
|
||||
|
||||
def model_destroyed(self, model):
|
||||
"""Called when an attached model is destroyed. Default is to
|
||||
destroy the window containing this view."""
|
||||
win = self.window
|
||||
if win:
|
||||
win.destroy()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
#
|
||||
# Python GUI - Views - Generic
|
||||
#
|
||||
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI.Geometry import add_pt, sub_pt, rect_sized
|
||||
from GUI import DrawableContainer
|
||||
|
||||
class View(DrawableContainer):
|
||||
"""A View is a 2D drawing area having its own coordinate
|
||||
system and clipping area."""
|
||||
|
||||
_default_size = (100, 100)
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
#
|
||||
# Python GUI - Windows - Generic
|
||||
#
|
||||
|
||||
import Exceptions
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Container
|
||||
from GUI import application
|
||||
|
||||
class Window(Container):
|
||||
"""Top-level Container."""
|
||||
|
||||
menus = overridable_property('menus', "Menus to be available when this window is active.")
|
||||
document = overridable_property('document', "Document with which this window is associated.")
|
||||
title = overridable_property('title', "Title of the window.")
|
||||
auto_position = overridable_property('auto_position', "Whether to position automatically when first shown.")
|
||||
target = overridable_property('target', "Current target for key events and menu messages.")
|
||||
tab_chain = overridable_property('tab_chain', "List of subcomponents in tabbing order.")
|
||||
visible = overridable_property('visible', "Whether the window is currently shown.")
|
||||
|
||||
keeps_document_open = True
|
||||
|
||||
_default_width = 200
|
||||
_default_height = 200
|
||||
_modal_styles = ('modal_dialog', 'alert')
|
||||
_dialog_styles = ('nonmodal_dialog', 'modal_dialog', 'alert')
|
||||
|
||||
_menus = []
|
||||
_document = None
|
||||
_closable = 0
|
||||
_auto_position = True
|
||||
_tab_chain = None
|
||||
|
||||
def __init__(self, style = 'standard', closable = None, **kwds):
|
||||
if closable is None:
|
||||
raise Exceptions.InternalError(
|
||||
"'closable' parameter unspecified in call to generic Window.__init__")
|
||||
Container.__init__(self, **kwds)
|
||||
self._style = style
|
||||
self._dialog_style = style.find('dialog') >= 0
|
||||
self._closable = closable
|
||||
application()._add_window(self)
|
||||
|
||||
def destroy(self):
|
||||
"""Detaches the window from document and application and removes it
|
||||
from the screen."""
|
||||
self.set_document(None)
|
||||
application()._remove_window(self)
|
||||
Container.destroy(self)
|
||||
|
||||
#
|
||||
# Message handling
|
||||
#
|
||||
|
||||
def next_handler(self):
|
||||
if self._document:
|
||||
return self._document
|
||||
else:
|
||||
return application()
|
||||
|
||||
def dispatch(self, message, *args):
|
||||
self.target.handle(message, *args)
|
||||
|
||||
#
|
||||
# Menus
|
||||
#
|
||||
|
||||
def get_menus(self):
|
||||
return self._menus
|
||||
|
||||
def set_menus(self, x):
|
||||
self._menus = x
|
||||
|
||||
#
|
||||
# Document association
|
||||
#
|
||||
|
||||
def get_document(self):
|
||||
return self._document
|
||||
|
||||
def set_document(self, x):
|
||||
if self._document != x:
|
||||
if self._document:
|
||||
self._document._windows.remove(self)
|
||||
self._document = x
|
||||
if self._document:
|
||||
self._document._windows.append(self)
|
||||
self.update_title()
|
||||
|
||||
#
|
||||
# Title
|
||||
#
|
||||
|
||||
def update_title(self):
|
||||
"""Update the window's title after a change in its document's title."""
|
||||
doc = self._document
|
||||
if doc:
|
||||
self.set_title(doc.title)
|
||||
|
||||
#
|
||||
# Showing and Positioning
|
||||
#
|
||||
|
||||
def get_auto_position(self):
|
||||
return self._auto_position
|
||||
|
||||
def set_auto_position(self, v):
|
||||
self._auto_position = v
|
||||
|
||||
def center(self):
|
||||
"""Position the window in the centre of the screen."""
|
||||
print "GWindow.center" ###
|
||||
sl, st, sr, sb = self._screen_rect()
|
||||
w, h = self.size
|
||||
l = (sr - sl - w) // 2
|
||||
t = (sb - st - h) // 2
|
||||
self.position = (l, t)
|
||||
|
||||
def centre(self):
|
||||
self.center()
|
||||
|
||||
def show(self):
|
||||
if self._auto_position:
|
||||
if self._style == 'standard':
|
||||
self._stagger()
|
||||
else:
|
||||
self.center()
|
||||
self._auto_position = False
|
||||
self._show()
|
||||
|
||||
def _stagger(self):
|
||||
pass
|
||||
|
||||
def _show(self):
|
||||
self.visible = True
|
||||
|
||||
def hide(self):
|
||||
self.visible = False
|
||||
|
||||
#
|
||||
# Menu commands
|
||||
#
|
||||
|
||||
def setup_menus(self, m):
|
||||
Container.setup_menus(self, m)
|
||||
app = application()
|
||||
if self._closable:
|
||||
m.close_cmd.enabled = 1
|
||||
|
||||
def close_cmd(self):
|
||||
"""If this window is the only window belonging to a document
|
||||
whose keeps_document_open attribute is true, then close the
|
||||
document, else destroy the window."""
|
||||
# app = application()
|
||||
# if not app._may_close_a_window():
|
||||
# #print "GWindow.close_cmd: Quitting the application" ###
|
||||
# app.quit_cmd()
|
||||
# else:
|
||||
doc = self._document
|
||||
n = 0
|
||||
if doc:
|
||||
for win in doc._windows:
|
||||
if win is not self and win.keeps_document_open:
|
||||
n += 1
|
||||
if doc and n == 0:
|
||||
doc.close_cmd()
|
||||
else:
|
||||
self.destroy()
|
||||
|
||||
#
|
||||
# Tabbing
|
||||
#
|
||||
|
||||
def get_tab_chain(self):
|
||||
chain = self._tab_chain
|
||||
if chain is None:
|
||||
chain = []
|
||||
self._build_tab_chain(chain)
|
||||
self._tab_chain = chain
|
||||
#print "Window.get_tab_chain:", chain ###
|
||||
return chain
|
||||
|
||||
def _invalidate_tab_chain(self):
|
||||
self._tab_chain = None
|
||||
|
||||
def _tab_to_next(self):
|
||||
self._tab_to(1)
|
||||
|
||||
def _tab_to_prev(self):
|
||||
self._tab_to(-1)
|
||||
|
||||
def _tab_to(self, direction):
|
||||
#print "GWindow._tab_to:", direction ###
|
||||
chain = self.tab_chain
|
||||
if chain:
|
||||
old_target = application().target
|
||||
new_target = None
|
||||
n = len(chain)
|
||||
try:
|
||||
i = chain.index(old_target)
|
||||
except ValueError:
|
||||
if direction > 0:
|
||||
i = -1
|
||||
else:
|
||||
i = n
|
||||
k = n
|
||||
while k:
|
||||
k -= 1
|
||||
i = (i + direction) % n
|
||||
comp = chain[i]
|
||||
if comp._is_targetable():
|
||||
new_target = comp
|
||||
break
|
||||
if new_target:
|
||||
if old_target:
|
||||
old_target._tab_out()
|
||||
new_target._tab_in()
|
||||
|
||||
def key_down(self, event):
|
||||
#print "GWindow.key_down:", event ###
|
||||
if self._generic_tabbing and event.char == '\t':
|
||||
#print "GWindow.key_down: doing generic tabbing" ###
|
||||
if event.shift:
|
||||
self._tab_to_prev()
|
||||
else:
|
||||
self._tab_to_next()
|
||||
else:
|
||||
Container.key_down(self, event)
|
||||
|
||||
# def _default_key_event(self, event):
|
||||
# #print "GWindow._default_key_event" ###
|
||||
# self.pass_event_to_next_handler(event)
|
||||
|
||||
#
|
||||
# Other
|
||||
#
|
||||
|
||||
def get_window(self):
|
||||
return self
|
||||
|
||||
def first_dispatcher(self):
|
||||
return self
|
||||
|
||||
def _document_needs_saving(self, state):
|
||||
pass
|
||||
|
||||
def modal_event_loop(self):
|
||||
"""Loop reading and handling events for the given window until
|
||||
exit_event_loop() is called. Interaction with other windows is prevented
|
||||
(although enabled application-wide menu commands can be used)."""
|
||||
# Implementations can override this together with exit_modal_event_loop()
|
||||
# to implement modal event loops in a different way.
|
||||
application()._event_loop(self)
|
||||
|
||||
def exit_modal_event_loop(self):
|
||||
# Cause the current call to modal_event_loop() to exit.
|
||||
application()._exit_event_loop()
|
||||
@@ -0,0 +1,26 @@
|
||||
#--------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Generic - Global variables and functions
|
||||
#
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
import os, sys
|
||||
|
||||
_main_file_name = os.path.basename(sys.argv[0])
|
||||
application_name = os.path.splitext(_main_file_name)[0]
|
||||
|
||||
_application = None
|
||||
|
||||
def application():
|
||||
"""Returns the global Application object. Creates a default one if needed."""
|
||||
global _application
|
||||
print _application
|
||||
if not _application:
|
||||
from GUI import Application
|
||||
_application = Application()
|
||||
return _application
|
||||
|
||||
def run():
|
||||
"""Runs the application, retaining control until the application is quit."""
|
||||
application().run()
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
#---------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Grid layout component - Generic
|
||||
#
|
||||
#---------------------------------------------------------------------------
|
||||
|
||||
from LayoutUtils import equalize_components
|
||||
from GUI import Frame, export
|
||||
|
||||
class Grid(Frame):
|
||||
|
||||
def __init__(self, items, row_spacing = 5, column_spacing = 10,
|
||||
align = 'l', equalize = '', expand_row = None, expand_column = None,
|
||||
padding = (0, 0), **kwds):
|
||||
Frame.__init__(self)
|
||||
hpad, vpad = padding
|
||||
num_rows = len(items)
|
||||
num_cols = max([len(row) for row in items])
|
||||
col_widths = [0] * num_cols
|
||||
row_heights = [0] * num_rows
|
||||
for i, row in enumerate(items):
|
||||
for j, item in enumerate(row):
|
||||
if item:
|
||||
row_heights[i] = max(row_heights[i], item.height)
|
||||
col_widths[j] = max(col_widths[j], item.width)
|
||||
tot_width = 0
|
||||
row_top = 0
|
||||
row_gap = 0
|
||||
vanchor = 't'
|
||||
for i, row in enumerate(items):
|
||||
row_height = row_heights[i]
|
||||
row_top += row_gap
|
||||
col_left = 0
|
||||
col_gap = 0
|
||||
hanchor = 'l'
|
||||
if i == expand_row:
|
||||
vanchor = 'tb'
|
||||
for j, item in enumerate(row):
|
||||
col_width = col_widths[j]
|
||||
col_left += col_gap
|
||||
if item:
|
||||
if 'l' in align:
|
||||
x = 0
|
||||
elif 'r' in align:
|
||||
x = col_width - item.width
|
||||
else:
|
||||
x = (col_width - item.width) // 2
|
||||
if 't' in align:
|
||||
y = 0
|
||||
elif 'b' in align:
|
||||
y = row_height - item.height
|
||||
else:
|
||||
y = (row_height - item.height) // 2
|
||||
item.position = (hpad + col_left + x, vpad + row_top + y)
|
||||
if j == expand_column:
|
||||
item.anchor = 'lr' + vanchor
|
||||
else:
|
||||
item.anchor = hanchor + vanchor
|
||||
self.add(item)
|
||||
if j == expand_column:
|
||||
hanchor = 'r'
|
||||
col_left += col_width
|
||||
col_gap = column_spacing
|
||||
tot_width = max(tot_width, col_left)
|
||||
if i == expand_row:
|
||||
vanchor = 'b'
|
||||
row_top += row_height
|
||||
row_gap = row_spacing
|
||||
tot_height = row_top
|
||||
self.size = (tot_width + 2 * hpad, tot_height + 2 * vpad)
|
||||
self.set(**kwds)
|
||||
|
||||
export(Grid)
|
||||
@@ -0,0 +1,116 @@
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Grid View - Generic
|
||||
#
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
from GUI import export
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import ScrollableView, rgb
|
||||
|
||||
class GridView(ScrollableView):
|
||||
"""A ScrollableView consisting of a grid of equal-sized cells."""
|
||||
|
||||
num_columns = overridable_property('num_columns',
|
||||
"Width of the view in columns")
|
||||
|
||||
num_rows = overridable_property('num_rows',
|
||||
"Height of the view in rows")
|
||||
|
||||
cell_size = overridable_property('cell_size',
|
||||
"Size of each cell")
|
||||
|
||||
backcolor = overridable_property('backcolor',
|
||||
"Background fill colour")
|
||||
|
||||
_cell_size = (32, 32)
|
||||
_num_rows = 0
|
||||
_num_columns = 0
|
||||
_backcolor = rgb(1, 1, 1, 1)
|
||||
|
||||
def __init__(self, num_rows, num_columns, cell_size, **kwds):
|
||||
ScrollableView.__init__(self)
|
||||
self._num_rows = num_rows
|
||||
self._num_columns = num_columns
|
||||
self._cell_size = cell_size
|
||||
self._update_extent()
|
||||
self.set(**kwds)
|
||||
|
||||
def get_cell_size(self):
|
||||
return self._cell_size
|
||||
|
||||
def set_cell_size(self, x):
|
||||
self._cell_size = x
|
||||
self._update_extent()
|
||||
|
||||
def get_num_rows(self):
|
||||
return self._num_rows
|
||||
|
||||
def set_num_rows(self, x):
|
||||
self._num_rows = x
|
||||
self._update_extent()
|
||||
|
||||
def get_num_columns(self):
|
||||
return self._num_columns
|
||||
|
||||
def set_num_columns(self, x):
|
||||
self._num_columns = x
|
||||
self._update_extent()
|
||||
|
||||
def _update_extent(self):
|
||||
cw, ch = self._cell_size
|
||||
nr = self._num_rows
|
||||
nc = self._num_columns
|
||||
self.extent = (cw * nc, ch * nr)
|
||||
|
||||
def cell_rect(self, row, col):
|
||||
w, h = self._cell_size
|
||||
l = col * w
|
||||
t = row * h
|
||||
return (l, t, l + w, t + h)
|
||||
|
||||
def get_backcolor(self):
|
||||
return self._backcolor
|
||||
|
||||
def set_backcolor(self, x):
|
||||
self._backcolor = x
|
||||
|
||||
def cell_containing_point(self, p):
|
||||
x, y = p
|
||||
cw, ch = self.cell_size
|
||||
return (int(y // ch), int(x // cw))
|
||||
|
||||
def draw(self, canvas, update_rect):
|
||||
canvas.backcolor = self.backcolor
|
||||
canvas.erase_rect(update_rect)
|
||||
ul, ut, ur, ub = update_rect
|
||||
nr = self._num_rows
|
||||
nc = self._num_columns
|
||||
cw, ch = self.cell_size
|
||||
row0 = max(0, int(ut // ch))
|
||||
row1 = min(nr, int(ub // ch) + 1)
|
||||
col0 = max(0, int(ul // cw))
|
||||
col1 = min(nc, int(ur // cw) + 1)
|
||||
row_range = xrange(row0, row1)
|
||||
col_range = xrange(col0, col1)
|
||||
for row in row_range:
|
||||
for col in col_range:
|
||||
rect = self.cell_rect(row, col)
|
||||
self.draw_cell(canvas, row, col, rect)
|
||||
|
||||
def draw_cell(self, canvas, row, col, rect):
|
||||
"""Should draw the cell at the given row and colum inside the given rect."""
|
||||
pass
|
||||
|
||||
def mouse_down(self, event):
|
||||
row, col = self.cell_containing_point(event.position)
|
||||
nr = self._num_rows
|
||||
nc = self._num_columns
|
||||
if 0 <= row < nr and 0 <= col < nc:
|
||||
self.click_cell(row, col, event)
|
||||
|
||||
def click_cell(self, row, col, event):
|
||||
"""Called when a mouse_down event has occured in the indicated cell."""
|
||||
pass
|
||||
|
||||
export(GridView)
|
||||
@@ -0,0 +1,18 @@
|
||||
#---------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Utilities for use by layout components - Generic
|
||||
#
|
||||
#---------------------------------------------------------------------------
|
||||
|
||||
def equalize_components(items, flags):
|
||||
if items:
|
||||
if 'w' in flags:
|
||||
width = max([item.width for item in items if item])
|
||||
for item in items:
|
||||
if item:
|
||||
item.width = width
|
||||
if 'h' in flags:
|
||||
height = max([item.height for item in items if item])
|
||||
for item in items:
|
||||
if item:
|
||||
item.height = height
|
||||
@@ -0,0 +1,28 @@
|
||||
#
|
||||
# Python GUI - Menu Lists - Generic
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
|
||||
class MenuList(list):
|
||||
"""A MenuList is a sequence of Menus with methods for finding
|
||||
menus and menu items by command."""
|
||||
|
||||
def menu_with_command(self, cmd):
|
||||
"""Returns the menu containing the given command, or None
|
||||
if there is no such menu in the list."""
|
||||
for menu in self:
|
||||
if menu.item_with_command(cmd):
|
||||
return menu
|
||||
return None
|
||||
|
||||
def item_with_command(self, cmd):
|
||||
"""Returns the menu item having the given command, or None
|
||||
if there is no such item."""
|
||||
for menu in self:
|
||||
item = menu.item_with_command(cmd)
|
||||
if item:
|
||||
return item
|
||||
return None
|
||||
|
||||
export(MenuList)
|
||||
@@ -0,0 +1,140 @@
|
||||
#
|
||||
# Python GUI - Message handlers - Generic
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
|
||||
class MessageHandler(object):
|
||||
"""A MessageHandler is an object which can form part of the
|
||||
message handling hierarchy. This hierarchy is used to handle
|
||||
keyboard events, menu commands, and action messages generated
|
||||
by buttons or other components.
|
||||
|
||||
At any given moment, one of the application's windows is the
|
||||
'target window' for messages. Within the target window, some
|
||||
component is designated as the 'target object', or just 'target'.
|
||||
|
||||
Messages are initially delivered to the target object, and
|
||||
passed up the hierarchy using the handle() method. At each step,
|
||||
if the object has a method with the same name as the message, it
|
||||
is called with the message's arguments. Otherwise the message is
|
||||
passed on to the object determined by the next_handler() method.
|
||||
Usually this is the object's container, but need not be.
|
||||
|
||||
The become_target() method is used to make a component the target
|
||||
within its window. The targeted() and untargeted() methods are
|
||||
called to notify a component when it has become or ceased to be
|
||||
the target. The is_target() method can be used to test whether a
|
||||
component is currently the target."""
|
||||
|
||||
#----- Event handling -----
|
||||
|
||||
def handle_event_here(self, event):
|
||||
"""Send an event message to this object, ignoring the event if
|
||||
there is no method to handle it."""
|
||||
self.handle_here(event.kind, event)
|
||||
|
||||
def handle_event(self, event):
|
||||
"""Send an event message up the message path until a method
|
||||
is found to handle it."""
|
||||
self.handle(event.kind, event)
|
||||
|
||||
#----- Message handling -----
|
||||
|
||||
def handle_here(self, message, *args):
|
||||
"""If there is a method with the same name as the message, call
|
||||
it with the given args. Otherwise, ignore the message."""
|
||||
method = getattr(self, message, None)
|
||||
if method:
|
||||
method(*args)
|
||||
|
||||
def handle(self, message, *args):
|
||||
"""If there is a method with the same name as the message, call
|
||||
it with the given args. Otherwise, pass the message up to the
|
||||
next handler."""
|
||||
#print "MessageHandler: handling", message, "for", self ###
|
||||
method = getattr(self, message, None)
|
||||
if method:
|
||||
#print "MessageHandler: calling method from", method.im_func.func_code.co_filename ###
|
||||
method(*args)
|
||||
else:
|
||||
#print "MessageHandler: passing to next handler" ###
|
||||
self.pass_to_next_handler(message, *args)
|
||||
|
||||
def pass_event_to_next_handler(self, event):
|
||||
"""Pass the given event on to the next handler, if any."""
|
||||
self.pass_to_next_handler(event.kind, event)
|
||||
|
||||
def pass_to_next_handler(self, message, *args):
|
||||
"""Pass the given message on to the next handler, if any."""
|
||||
next = self.next_handler()
|
||||
if next:
|
||||
next.handle(message, *args)
|
||||
|
||||
def next_handler(self):
|
||||
"""Return the object, if any, to which messages not handled
|
||||
by this object should be passed on."""
|
||||
return None
|
||||
|
||||
#----- Default handlers and callbacks -----
|
||||
|
||||
def _setup_menus(self, m):
|
||||
self.pass_to_next_handler('_setup_menus', m)
|
||||
#print "MessageHandler._setup_menus: calling setup_menus for", self ###
|
||||
self.setup_menus(m)
|
||||
|
||||
def setup_menus(self, m):
|
||||
"""Called before a menu is pulled down, to allow the Component to
|
||||
enable menu commands that it responds to."""
|
||||
pass
|
||||
|
||||
_pass_key_events_to_platform = False
|
||||
|
||||
def _default_key_event(self, event):
|
||||
#print "MessageHandler._default_key_event for", self ###
|
||||
#print "...originator =", event._originator ###
|
||||
if event._originator is self and self._pass_key_events_to_platform:
|
||||
#print "...passing to platform" ###
|
||||
event._not_handled = True
|
||||
else:
|
||||
self.pass_event_to_next_handler(event)
|
||||
|
||||
def _default_mouse_event(self, event):
|
||||
event._not_handled = True
|
||||
|
||||
def _event_custom_handled(self, event):
|
||||
# Give custom event handlers of this component a chance to handle
|
||||
# the event. If it reaches a default event method of this component,
|
||||
# the event is not passed to the next handler and false is returned.
|
||||
# If it is handled by an overridden method or explicitly passed to
|
||||
# the next handler, true is returned.
|
||||
event._originator = self
|
||||
self.handle_event(event)
|
||||
return not event._not_handled
|
||||
|
||||
def key_down(self, event):
|
||||
#print "MessageHandler.key_down for", self ###
|
||||
self._default_key_event(event)
|
||||
|
||||
def key_up(self, event):
|
||||
self._default_key_event(event)
|
||||
|
||||
def mouse_down(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
def mouse_drag(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
def mouse_up(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
def mouse_move(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
def mouse_enter(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
def mouse_leave(self, event):
|
||||
self._default_mouse_event(event)
|
||||
|
||||
export(MessageHandler)
|
||||
@@ -0,0 +1,42 @@
|
||||
#
|
||||
# Python GUI - Modal Dialogs - Generic
|
||||
#
|
||||
|
||||
from GUI import application, export
|
||||
from GUI import Dialog
|
||||
|
||||
class ModalDialog(Dialog):
|
||||
|
||||
def __init__(self, style = 'modal_dialog', **kwds):
|
||||
Dialog.__init__(self, style = style, **kwds)
|
||||
|
||||
def present(self):
|
||||
self._result = None
|
||||
self._dismissed = 0
|
||||
self.show()
|
||||
app = application()
|
||||
try:
|
||||
while not self._dismissed:
|
||||
self.modal_event_loop()
|
||||
finally:
|
||||
self.hide()
|
||||
return self._result
|
||||
|
||||
def dismiss(self, result = 0):
|
||||
self._result = result
|
||||
self._dismissed = 1
|
||||
self.exit_modal_event_loop()
|
||||
|
||||
def close_cmd(self):
|
||||
self.dismiss()
|
||||
|
||||
def next_handler(self):
|
||||
return None
|
||||
|
||||
def ok(self):
|
||||
self.dismiss(True)
|
||||
|
||||
def cancel(self):
|
||||
self.dismiss(False)
|
||||
|
||||
export(ModalDialog)
|
||||
@@ -0,0 +1,126 @@
|
||||
#
|
||||
# Python GUI - Models - Generic
|
||||
#
|
||||
|
||||
import weakref
|
||||
from GUI import export
|
||||
from GUI.Properties import Properties, overridable_property
|
||||
|
||||
# List of views for a model is kept separately so that models
|
||||
# can be pickled without fear of accidentally trying to pickle
|
||||
# the user interface.
|
||||
|
||||
_model_views = weakref.WeakKeyDictionary() # {Model: [object]}
|
||||
|
||||
class Model(Properties):
|
||||
"""A Model represents an application object which can appear in a View.
|
||||
Each Model can have any number of Views attached to it. When a Model is
|
||||
changed, it should notify all of its Views so that they can update
|
||||
themselves.
|
||||
|
||||
The 'parent' attribute of a Model is treated specially when pickling.
|
||||
If it refers to an object having a 'pickle_as_parent_model' attribute
|
||||
whose value is false, the 'parent' attribute is not pickled. This allows
|
||||
a Model to have a Document as a parent without the Document being pickled
|
||||
along with the Model.
|
||||
"""
|
||||
|
||||
views = overridable_property('views',
|
||||
"List of objects observing this model. Do not modify directly.")
|
||||
|
||||
parent = None # Model
|
||||
|
||||
def __init__(self, parent = None, **kwds):
|
||||
Properties.__init__(self, **kwds)
|
||||
if parent:
|
||||
self.parent = parent
|
||||
|
||||
def destroy(self):
|
||||
"""All views currently observing this model are removed, and their
|
||||
'model_destroyed' methods, if any, are called with the model as
|
||||
an argument."""
|
||||
for view in self.views[:]:
|
||||
self.remove_view(view)
|
||||
self._call_if_present(view, 'model_destroyed', self)
|
||||
|
||||
#
|
||||
# Properties
|
||||
#
|
||||
|
||||
def get_views(self):
|
||||
views = _model_views.get(self)
|
||||
if views is None:
|
||||
views = []
|
||||
_model_views[self] = views
|
||||
return views
|
||||
|
||||
#
|
||||
# Pickling behaviour
|
||||
#
|
||||
|
||||
def __getstate__(self):
|
||||
state = self.__dict__
|
||||
parent = self.parent
|
||||
if not getattr(parent, 'pickle_as_parent_model', True):
|
||||
state = state.copy()
|
||||
del state['parent']
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
self.__dict__.update(state)
|
||||
|
||||
#
|
||||
# Adding and removing views
|
||||
#
|
||||
|
||||
def add_view(self, view):
|
||||
"""Add the given object as an observer of this model. The view will
|
||||
typically be a View subclass, but need not be. If the view is not
|
||||
already an observer of this model and defines an 'add_model' method,
|
||||
this method is called with the model as an argument."""
|
||||
views = self.views
|
||||
if view not in views:
|
||||
views.append(view)
|
||||
self._call_if_present(view, 'add_model', self)
|
||||
|
||||
def remove_view(self, view):
|
||||
"""If the given object is currently an observer of this model, it
|
||||
is removed, and if it defines a 'remove_model' method, this method
|
||||
is called with the model as an argument."""
|
||||
views = self.views
|
||||
if view in views:
|
||||
views.remove(view)
|
||||
self._call_if_present(view, 'remove_model', self)
|
||||
|
||||
#
|
||||
# View notification
|
||||
#
|
||||
|
||||
def notify_views(self, message = 'model_changed', *args, **kwds):
|
||||
"""For each observer, if the observer defines a method with the name of the
|
||||
message, call it with the given arguments. Otherwise, if it defines a
|
||||
method called 'model_changed', call it with no arguments. Otherwise,
|
||||
do nothing for that observer."""
|
||||
for view in self.views:
|
||||
if not self._call_if_present(view, message, self, *args, **kwds):
|
||||
self._call_if_present(view, 'model_changed', self)
|
||||
|
||||
def _call_if_present(self, obj, method_name, *args, **kwds):
|
||||
method = getattr(obj, method_name, None)
|
||||
if method:
|
||||
method(*args, **kwds)
|
||||
return 1
|
||||
else:
|
||||
return 0
|
||||
|
||||
#
|
||||
# Marking as changed
|
||||
#
|
||||
|
||||
def changed(self):
|
||||
"Mark the containing Document as changed."
|
||||
parent = self.parent
|
||||
if parent:
|
||||
parent.changed()
|
||||
|
||||
export(Model)
|
||||
@@ -0,0 +1,144 @@
|
||||
#--------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Palette View - Generic
|
||||
#
|
||||
#--------------------------------------------------------------------------
|
||||
|
||||
from GUI import export
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import StdColors, GridView
|
||||
from GUI.GUtils import splitdict
|
||||
|
||||
class PaletteView(GridView):
|
||||
"""A GridView whose cells are identified by a linear index from
|
||||
left to right and top to bottom. Also provides support for
|
||||
highlighting one or more selected cells."""
|
||||
|
||||
num_items = overridable_property('num_items',
|
||||
"Total number of items")
|
||||
|
||||
items_per_row = overridable_property('items_per_row',
|
||||
"Number of items displayed in one row")
|
||||
|
||||
highlight_style = overridable_property('highlight_style',
|
||||
"Style of selection highlighting")
|
||||
|
||||
highlight_color = overridable_property('highlight_color',
|
||||
"Color of selection highlighting")
|
||||
|
||||
highlight_thickness = overridable_property('highlight_thickness',
|
||||
"Width of selection highlighting for 'frame' highlight mode")
|
||||
|
||||
_highlight_style = 'fill'
|
||||
_highlight_color = StdColors.selection_backcolor
|
||||
_highlight_thickness = 4
|
||||
|
||||
def __init__(self, num_items, items_per_row, cell_size,
|
||||
scrolling = '', **kwds):
|
||||
base_kwds = splitdict(kwds, 'border', scrolling = '')
|
||||
GridView.__init__(self, num_rows = 0, num_columns = 0,
|
||||
cell_size = cell_size, **base_kwds)
|
||||
self._num_items = num_items
|
||||
self._items_per_row = items_per_row
|
||||
self._update_num_rows_and_columns()
|
||||
ew, eh = self.extent
|
||||
if not self.hscrolling:
|
||||
self.content_width = ew
|
||||
if not self.vscrolling:
|
||||
self.content_height = eh
|
||||
self.set(**kwds)
|
||||
|
||||
def get_num_items(self):
|
||||
return self._num_items
|
||||
|
||||
def set_num_items(self, n):
|
||||
self._num_items = n
|
||||
self._update_num_rows_and_columns()
|
||||
|
||||
def get_items_per_row(self):
|
||||
return self.num_columns
|
||||
|
||||
def set_items_per_row(self, n):
|
||||
self._items_per_row = n
|
||||
self._update_num_rows_and_columns()
|
||||
|
||||
def _update_num_rows_and_columns(self):
|
||||
nc = self._items_per_row
|
||||
nr = (self._num_items + nc - 1) // nc
|
||||
self._num_columns = nc
|
||||
self._num_rows = nr
|
||||
self._update_extent()
|
||||
|
||||
def get_highlight_style(self):
|
||||
return self._highlight_style
|
||||
|
||||
def set_highlight_style(self, x):
|
||||
self._highlight_style = x
|
||||
|
||||
def get_highlight_color(self):
|
||||
return self._highlight_color
|
||||
|
||||
def set_highlight_color(self, x):
|
||||
self._highlight_color = x
|
||||
|
||||
def get_highlight_color(self):
|
||||
return self._highlight_color
|
||||
|
||||
def set_highlight_color(self, x):
|
||||
self._highlight_color = x
|
||||
|
||||
def item_no_of_cell(self, row, col):
|
||||
i = row * self._items_per_row + col
|
||||
if 0 <= i < self._num_items:
|
||||
return i
|
||||
|
||||
def cell_of_item_no(self, item_no):
|
||||
if 0 <= item_no < self._num_items:
|
||||
return divmod(item_no, self._items_per_row)
|
||||
|
||||
def item_rect(self, item_no):
|
||||
cell = self.cell_of_item_no(item_no)
|
||||
if cell:
|
||||
return self.cell_rect(*cell)
|
||||
|
||||
def draw_cell(self, canvas, row, col, rect):
|
||||
i = self.item_no_of_cell(row, col)
|
||||
if i is not None:
|
||||
highlight = self.item_is_selected(i)
|
||||
self.draw_item_and_highlight(canvas, i, rect, highlight)
|
||||
|
||||
def draw_item_and_highlight(self, canvas, item_no, rect, highlight):
|
||||
"""Draw the specified item, with selection highlighting if highlight
|
||||
is true."""
|
||||
if highlight:
|
||||
style = self.highlight_style
|
||||
if style:
|
||||
canvas.gsave()
|
||||
if style == 'fill':
|
||||
canvas.fillcolor = self.highlight_color
|
||||
canvas.fill_rect(rect)
|
||||
else:
|
||||
canvas.pencolor = self.highlight_color
|
||||
canvas.pensize = self.highlight_thickness
|
||||
canvas.frame_rect(rect)
|
||||
canvas.grestore()
|
||||
self.draw_item(canvas, item_no, rect)
|
||||
|
||||
def draw_item(self, canvas, item_no, rect):
|
||||
"""Should draw the specified item in the given rect."""
|
||||
pass
|
||||
|
||||
def click_cell(self, row, col, event):
|
||||
i = self.item_no_of_cell(row, col)
|
||||
if i is not None:
|
||||
self.click_item(i, event)
|
||||
|
||||
def click_item(self, item_no, event):
|
||||
"""Called when a mouse_down event has occurred in the indicated item."""
|
||||
pass
|
||||
|
||||
def item_is_selected(self, item_no):
|
||||
"""Should return true if the indicated item is to be drawn highlighted."""
|
||||
return False
|
||||
|
||||
export(PaletteView)
|
||||
@@ -0,0 +1,37 @@
|
||||
#
|
||||
# Python GUI - Picture class - Generic
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import View
|
||||
|
||||
class Picture(View):
|
||||
|
||||
image = overridable_property('image', "The image to display")
|
||||
|
||||
_image = None
|
||||
|
||||
def __init__(self, image = None, file = None, **kwds):
|
||||
if file:
|
||||
from Images import Image
|
||||
image = Image(file)
|
||||
View.__init__(self, **kwds)
|
||||
if image:
|
||||
self.size = image.size
|
||||
self._image = image
|
||||
|
||||
def get_image(self):
|
||||
return self._image
|
||||
|
||||
def set_image(self, x):
|
||||
self._image = x
|
||||
self.invalidate()
|
||||
|
||||
def draw(self, canvas, rect):
|
||||
image = self._image
|
||||
if image:
|
||||
w, h = self.size
|
||||
image.draw(canvas, image.bounds, (0, 0, w, h))
|
||||
|
||||
export(Picture)
|
||||
@@ -0,0 +1,42 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Properties - Generic
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Properties(object):
|
||||
"""
|
||||
This class implements the standard interface for initialising
|
||||
properties using keyword arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, **kw):
|
||||
"Properties(name=value, ...) passes the given arguments to the set() method."
|
||||
self.set(**kw)
|
||||
|
||||
def set(self, **kw):
|
||||
"""set(name=value, ...) sets property values according to the given
|
||||
keyword arguments. Will only set attributes for which a descriptor exists."""
|
||||
cls = self.__class__
|
||||
for name, value in kw.iteritems():
|
||||
try:
|
||||
s = getattr(cls, name).__set__
|
||||
except AttributeError:
|
||||
raise TypeError("%s object has no writable property %r" % (
|
||||
self.__class__.__name__, name))
|
||||
s(self, value)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def overridable_property(name, doc = None):
|
||||
"""Creates a property which calls methods get_xxx and set_xxx of
|
||||
the underlying object to get and set the property value, so that
|
||||
the property's behaviour may be easily overridden by subclasses."""
|
||||
|
||||
getter_name = intern('get_' + name)
|
||||
setter_name = intern('set_' + name)
|
||||
return property(
|
||||
lambda self: getattr(self, getter_name)(),
|
||||
lambda self, value: getattr(self, setter_name)(value),
|
||||
None,
|
||||
doc)
|
||||
@@ -0,0 +1,88 @@
|
||||
#
|
||||
# PyGUI - Resources - Generic
|
||||
#
|
||||
|
||||
import os
|
||||
|
||||
resource_path = []
|
||||
resource_cache = {}
|
||||
|
||||
class ResourceNotFoundError(ValueError):
|
||||
|
||||
def __init__(self, name, type, path):
|
||||
name = _append_type(name, type)
|
||||
ValueError.__init__(self, "Resource %r not found in %s" % (name, path))
|
||||
|
||||
def _append_type(name, type):
|
||||
if type:
|
||||
name = "%s.%s" % (os.path.splitext(name)[0], type)
|
||||
return name
|
||||
|
||||
def _add_directory_path(dir, up = 0):
|
||||
# Add the given directory to the resource path if it exists.
|
||||
dir = os.path.abspath(dir)
|
||||
while up > 0:
|
||||
dir = os.path.dirname(dir)
|
||||
up -= 1
|
||||
resdir = os.path.join(dir, "Resources")
|
||||
#print "GUI.Resources: Checking for directory", repr(resdir) ###
|
||||
if os.path.isdir(resdir):
|
||||
resource_path.insert(0, resdir)
|
||||
|
||||
def _add_file_path(file, up = 0):
|
||||
# Add the directory containing the given file to the resource path.
|
||||
#print "GUI.Resources: Adding path for file", repr(file) ###
|
||||
dir = os.path.dirname(os.path.abspath(file))
|
||||
_add_directory_path(dir, up)
|
||||
|
||||
def _add_module_path(module, up = 0):
|
||||
# Add the directory containing the given module to the resource path.
|
||||
if hasattr(module, '__file__'):
|
||||
_add_file_path(module.__file__, up)
|
||||
|
||||
def lookup_resource(name, type = None):
|
||||
"""
|
||||
Return the full pathname of a resource given its relative name
|
||||
using '/' as a directory separator. If a type is specified, any
|
||||
dot-suffix on the name is replaced with '.type'. Returns None if
|
||||
no matching file is found on the resource search path.
|
||||
"""
|
||||
name = _append_type(name, type)
|
||||
relpath = os.path.join(*name.split("/"))
|
||||
for dir in resource_path:
|
||||
path = os.path.join(dir, relpath)
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
def find_resource(name, type = None):
|
||||
"""
|
||||
Returns the full pathname of a resource as per lookup_resource(), but
|
||||
raises ResourceNotFoundError if the resource is not found.
|
||||
"""
|
||||
path = lookup_resource(name, type)
|
||||
if not path:
|
||||
raise ResourceNotFoundError(name, type, resource_path)
|
||||
return path
|
||||
|
||||
def get_resource(loader, name, type = None, default = None, **kwds):
|
||||
"""
|
||||
Find a resource and load it using the specified loader function.
|
||||
The loader is called as: loader(path, **kwds) where path is the full
|
||||
pathname of the resource. The loaded resource is cached, and subsequent
|
||||
calls referencing the same resource will return the cached value.
|
||||
If the resource is not found, the specified default is returned if any,
|
||||
otherwise ResourceNotFoundError is raised.
|
||||
"""
|
||||
path = lookup_resource(name, type)
|
||||
if path:
|
||||
result = resource_cache.get(path)
|
||||
if result is None:
|
||||
result = loader(path, **kwds)
|
||||
resource_cache[path] = result
|
||||
else:
|
||||
if default is not None:
|
||||
result = default
|
||||
else:
|
||||
raise ResourceNotFoundError(name, type, resource_path)
|
||||
return result
|
||||
@@ -0,0 +1,51 @@
|
||||
#---------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Row layout component - Generic
|
||||
#
|
||||
#---------------------------------------------------------------------------
|
||||
|
||||
from LayoutUtils import equalize_components
|
||||
from GUI import Frame, export
|
||||
|
||||
class Row(Frame):
|
||||
|
||||
def __init__(self, items, spacing = 10, align = 'c', equalize = '',
|
||||
expand = None, padding = (0, 0), **kwds):
|
||||
Frame.__init__(self)
|
||||
hpad, vpad = padding
|
||||
if expand is not None and not isinstance(expand, int):
|
||||
expand = items.index(expand)
|
||||
equalize_components(items, equalize)
|
||||
height = 0
|
||||
for item in items:
|
||||
if item:
|
||||
height = max(height, item.height)
|
||||
x = hpad
|
||||
gap = 0
|
||||
hanchor = 'l'
|
||||
vanchor = align
|
||||
for i, item in enumerate(items):
|
||||
x += gap;
|
||||
if item:
|
||||
if 't' in align:
|
||||
y = 0
|
||||
if 'b' in align:
|
||||
item.height = height
|
||||
elif align == 'b':
|
||||
y = height - item.height
|
||||
else:
|
||||
y = (height - item.height) // 2
|
||||
item.position = (x, y + vpad)
|
||||
if i == expand:
|
||||
item.anchor = 'lr' + vanchor
|
||||
else:
|
||||
item.anchor = hanchor + vanchor
|
||||
x += item.width;
|
||||
if i == expand:
|
||||
hanchor = 'r'
|
||||
gap = spacing
|
||||
self.size = (x + hpad, height + 2 * vpad)
|
||||
self.add(items)
|
||||
self.set(**kwds)
|
||||
|
||||
export(Row)
|
||||
@@ -0,0 +1,19 @@
|
||||
#
|
||||
# Python GUI - Standard Buttons
|
||||
#
|
||||
|
||||
from GUI import Button
|
||||
|
||||
class DefaultButton(Button):
|
||||
|
||||
def __init__(self, title = "OK", **kwds):
|
||||
kwds.setdefault('style', 'default')
|
||||
kwds.setdefault('action', 'do_default_action')
|
||||
Button.__init__(self, title = title, **kwds)
|
||||
|
||||
class CancelButton(Button):
|
||||
|
||||
def __init__(self, title = "Cancel", **kwds):
|
||||
kwds.setdefault('style', 'cancel')
|
||||
kwds.setdefault('action', 'do_cancel_action')
|
||||
Button.__init__(self, title = title, **kwds)
|
||||
@@ -0,0 +1,18 @@
|
||||
#
|
||||
# Python GUI - Standard Colors - Generic
|
||||
#
|
||||
|
||||
from GUI.Colors import rgb, selection_forecolor, selection_backcolor
|
||||
|
||||
black = rgb(0, 0, 0)
|
||||
dark_grey = rgb(0.25, 0.25, 0.25)
|
||||
grey = rgb(0.5, 0.5, 0.5)
|
||||
light_grey = rgb(0.75, 0.75, 0.75)
|
||||
white = rgb(1, 1, 1)
|
||||
red = rgb(1, 0, 0)
|
||||
green = rgb(0, 1, 0)
|
||||
blue = rgb(0, 0, 1)
|
||||
yellow = rgb(1, 1, 0)
|
||||
cyan = rgb(0, 1, 1)
|
||||
magenta = rgb(1, 0, 1)
|
||||
clear = rgb(0, 0, 0, 0)
|
||||
@@ -0,0 +1,68 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - TextEditor Printing - Generic
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
import re
|
||||
from GUI import View
|
||||
|
||||
class TextEditorPrintView(View):
|
||||
|
||||
def __init__(self, base_view, page_setup):
|
||||
print "TextEditorPrintView:" ###
|
||||
print "...paper_size =", page_setup.paper_size ###
|
||||
print "...margins =", page_setup.margins ###
|
||||
print "...page_size =", page_setup.page_size ###
|
||||
View.__init__(self)
|
||||
self.base_view = base_view
|
||||
self.width = page_setup.page_width
|
||||
self.page_height = page_setup.page_height
|
||||
self.lay_out_text()
|
||||
lines_per_page = int(page_setup.page_height / base_view.font.line_height)
|
||||
self.lines_per_page = lines_per_page
|
||||
num_lines = len(self.lines)
|
||||
self.num_pages = (num_lines + lines_per_page - 1) // lines_per_page
|
||||
self.height = self.num_pages * self.page_height
|
||||
|
||||
def lay_out_text(self):
|
||||
base_view = self.base_view
|
||||
font = base_view.font
|
||||
space_width = font.width(" ")
|
||||
tab_spacing = base_view.tab_spacing
|
||||
page_width = self.width
|
||||
pat = re.compile(r"[ \t]|[^ \t]+")
|
||||
lines = []
|
||||
line = []
|
||||
x = 0
|
||||
for text_line in base_view.text.splitlines():
|
||||
for match in pat.finditer(text_line):
|
||||
item = match.group()
|
||||
if item == " ":
|
||||
item_width = space_width
|
||||
item = ""
|
||||
elif item == "\t":
|
||||
item_width = tab_spacing - x % tab_spacing
|
||||
item = ""
|
||||
else:
|
||||
item_width = font.width(item)
|
||||
if x + item_width > page_width and x > 0:
|
||||
lines.append(line); line = []; x = 0
|
||||
line.append((x, item))
|
||||
x += item_width
|
||||
lines.append(line); line = []; x = 0
|
||||
self.lines = lines
|
||||
|
||||
def draw(self, canvas, page_rect):
|
||||
l, t, r, b = page_rect
|
||||
page_no = int(t / self.page_height)
|
||||
n = self.lines_per_page
|
||||
i = page_no * n
|
||||
font = self.base_view.font
|
||||
y = t + font.ascent
|
||||
dy = font.line_height
|
||||
for line in self.lines[i : i + n]:
|
||||
for x, item in line:
|
||||
canvas.moveto(x, y)
|
||||
canvas.show_text(item)
|
||||
y += dy
|
||||
Reference in New Issue
Block a user