code
stringlengths
1
1.72M
language
stringclasses
1 value
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for Google App Engine Utilities for making it easier to use the Google API Client for Python on Google App Engine. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' import pickle from google.appengine.ext import db from apiclient.oauth import OAuthCredentials from apiclient.oauth import FlowThreeLegged class FlowThreeLeggedProperty(db.Property): """Utility property that allows easy storage and retreival of an apiclient.oauth.FlowThreeLegged""" # Tell what the user type is. data_type = FlowThreeLegged # For writing to datastore. def get_value_for_datastore(self, model_instance): flow = super(FlowThreeLeggedProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(flow)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, FlowThreeLegged): raise BadValueError('Property %s must be convertible ' 'to a FlowThreeLegged instance (%s)' % (self.name, value)) return super(FlowThreeLeggedProperty, self).validate(value) def empty(self, value): return not value class OAuthCredentialsProperty(db.Property): """Utility property that allows easy storage and retrieval of apiclient.oath.OAuthCredentials """ # Tell what the user type is. data_type = OAuthCredentials # For writing to datastore. def get_value_for_datastore(self, model_instance): cred = super(OAuthCredentialsProperty, self).get_value_for_datastore(model_instance) return db.Blob(pickle.dumps(cred)) # For reading from datastore. def make_value_from_datastore(self, value): if value is None: return None return pickle.loads(value) def validate(self, value): if value is not None and not isinstance(value, OAuthCredentials): raise BadValueError('Property %s must be convertible ' 'to an OAuthCredentials instance (%s)' % (self.name, value)) return super(OAuthCredentialsProperty, self).validate(value) def empty(self, value): return not value class StorageByKeyName(object): """Store and retrieve a single credential to and from the App Engine datastore. This Storage helper presumes the Credentials have been stored as a CredenialsProperty on a datastore model class, and that entities are stored by key_name. """ def __init__(self, model, key_name, property_name): """Constructor for Storage. Args: model: db.Model, model class key_name: string, key name for the entity that has the credentials property_name: string, name of the property that is a CredentialsProperty """ self.model = model self.key_name = key_name self.property_name = property_name def get(self): """Retrieve Credential from datastore. Returns: Credentials """ entity = self.model.get_or_insert(self.key_name) credential = getattr(entity, self.property_name) if credential and hasattr(credential, 'set_store'): credential.set_store(self.put) return credential def put(self, credentials): """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ entity = self.model.get_or_insert(self.key_name) setattr(entity, self.property_name, credentials) entity.put()
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command-line tools for authenticating via OAuth 1.0 Do the OAuth 1.0 Three Legged Dance for a command line application. Stores the generated credentials in a common file that is used by other example apps in the same directory. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' __all__ = ["run"] import BaseHTTPServer import gflags import logging import socket import sys from optparse import OptionParser from apiclient.oauth import RequestError try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl FLAGS = gflags.FLAGS gflags.DEFINE_boolean('auth_local_webserver', True, ('Run a local web server to handle redirects during ' 'OAuth authorization.')) gflags.DEFINE_string('auth_host_name', 'localhost', ('Host name to use when running a local web server to ' 'handle redirects during OAuth authorization.')) gflags.DEFINE_multi_int('auth_host_port', [8080, 8090], ('Port to use when running a local web server to ' 'handle redirects during OAuth authorization.')) class ClientRedirectServer(BaseHTTPServer.HTTPServer): """A server to handle OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into query_params and then stops serving. """ query_params = {} class ClientRedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler): """A handler for OAuth 1.0 redirects back to localhost. Waits for a single request and parses the query parameters into the servers query_params and then stops serving. """ def do_GET(s): """Handle a GET request Parses the query parameters and prints a message if the flow has completed. Note that we can't detect if an error occurred. """ s.send_response(200) s.send_header("Content-type", "text/html") s.end_headers() query = s.path.split('?', 1)[-1] query = dict(parse_qsl(query)) s.server.query_params = query s.wfile.write("<html><head><title>Authentication Status</title></head>") s.wfile.write("<body><p>The authentication flow has completed.</p>") s.wfile.write("</body></html>") def log_message(self, format, *args): """Do not log messages to stdout while running as command line program.""" pass def run(flow, storage): """Core code for a command-line application. Args: flow: Flow, an OAuth 1.0 Flow to step through. storage: Storage, a Storage to store the credential in. Returns: Credentials, the obtained credential. Exceptions: RequestError: if step2 of the flow fails. Args: """ if FLAGS.auth_local_webserver: success = False port_number = 0 for port in FLAGS.auth_host_port: port_number = port try: httpd = BaseHTTPServer.HTTPServer((FLAGS.auth_host_name, port), ClientRedirectHandler) except socket.error, e: pass else: success = True break FLAGS.auth_local_webserver = success if FLAGS.auth_local_webserver: oauth_callback = 'http://%s:%s/' % (FLAGS.auth_host_name, port_number) else: oauth_callback = 'oob' authorize_url = flow.step1_get_authorize_url(oauth_callback) print 'Go to the following link in your browser:' print authorize_url print if FLAGS.auth_local_webserver: print 'If your browser is on a different machine then exit and re-run this' print 'application with the command-line parameter --noauth_local_webserver.' print if FLAGS.auth_local_webserver: httpd.handle_request() if 'error' in httpd.query_params: sys.exit('Authentication request was rejected.') if 'oauth_verifier' in httpd.query_params: code = httpd.query_params['oauth_verifier'] else: accepted = 'n' while accepted.lower() == 'n': accepted = raw_input('Have you authorized me? (y/n) ') code = raw_input('What is the verification code? ').strip() try: credentials = flow.step2_exchange(code) except RequestError: sys.exit('The authentication has failed.') storage.put(credentials) credentials.set_store(storage.put) print "You have successfully authenticated." return credentials
Python
#!/usr/bin/python2.4 # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Errors for the library. All exceptions defined by the library should be defined in this file. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' from oauth2client.anyjson import simplejson class Error(Exception): """Base error for this module.""" pass class HttpError(Error): """HTTP data was invalid or unexpected.""" def __init__(self, resp, content, uri=None): self.resp = resp self.content = content self.uri = uri def _get_reason(self): """Calculate the reason for the error from the response content.""" if self.resp.get('content-type', '').startswith('application/json'): try: data = simplejson.loads(self.content) reason = data['error']['message'] except (ValueError, KeyError): reason = self.content else: reason = self.resp.reason return reason def __repr__(self): if self.uri: return '<HttpError %s when requesting %s returned "%s">' % ( self.resp.status, self.uri, self._get_reason()) else: return '<HttpError %s "%s">' % (self.resp.status, self._get_reason()) __str__ = __repr__ class InvalidJsonError(Error): """The JSON returned could not be parsed.""" pass class UnknownLinkType(Error): """Link type unknown or unexpected.""" pass class UnknownApiNameOrVersion(Error): """No API with that name and version exists.""" pass class UnacceptableMimeTypeError(Error): """That is an unacceptable mimetype for this operation.""" pass class MediaUploadSizeError(Error): """Media is larger than the method can accept.""" pass class ResumableUploadError(Error): """Error occured during resumable upload.""" pass class BatchError(HttpError): """Error occured during batch operations.""" def __init__(self, reason, resp=None, content=None): self.resp = resp self.content = content self.reason = reason def __repr__(self): return '<BatchError %s "%s">' % (self.resp.status, self.reason) __str__ = __repr__ class UnexpectedMethodError(Error): """Exception raised by RequestMockBuilder on unexpected calls.""" def __init__(self, methodId=None): """Constructor for an UnexpectedMethodError.""" super(UnexpectedMethodError, self).__init__( 'Received unexpected call %s' % methodId) class UnexpectedBodyError(Error): """Exception raised by RequestMockBuilder on unexpected bodies.""" def __init__(self, expected, provided): """Constructor for an UnexpectedMethodError.""" super(UnexpectedBodyError, self).__init__( 'Expected: [%s] - Provided: [%s]' % (expected, provided))
Python
__version__ = "1.0c2"
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Schema processing for discovery based APIs Schemas holds an APIs discovery schemas. It can return those schema as deserialized JSON objects, or pretty print them as prototype objects that conform to the schema. For example, given the schema: schema = \"\"\"{ "Foo": { "type": "object", "properties": { "etag": { "type": "string", "description": "ETag of the collection." }, "kind": { "type": "string", "description": "Type of the collection ('calendar#acl').", "default": "calendar#acl" }, "nextPageToken": { "type": "string", "description": "Token used to access the next page of this result. Omitted if no further results are available." } } } }\"\"\" s = Schemas(schema) print s.prettyPrintByName('Foo') Produces the following output: { "nextPageToken": "A String", # Token used to access the # next page of this result. Omitted if no further results are available. "kind": "A String", # Type of the collection ('calendar#acl'). "etag": "A String", # ETag of the collection. }, The constructor takes a discovery document in which to look up named schema. """ # TODO(jcgregorio) support format, enum, minimum, maximum __author__ = 'jcgregorio@google.com (Joe Gregorio)' import copy from oauth2client.anyjson import simplejson class Schemas(object): """Schemas for an API.""" def __init__(self, discovery): """Constructor. Args: discovery: object, Deserialized discovery document from which we pull out the named schema. """ self.schemas = discovery.get('schemas', {}) # Cache of pretty printed schemas. self.pretty = {} def _prettyPrintByName(self, name, seen=None, dent=0): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] if name in seen: # Do not fall into an infinite loop over recursive definitions. return '# Object with schema name: %s' % name seen.append(name) if name not in self.pretty: self.pretty[name] = _SchemaToStruct(self.schemas[name], seen, dent).to_str(self._prettyPrintByName) seen.pop() return self.pretty[name] def prettyPrintByName(self, name): """Get pretty printed object prototype from the schema name. Args: name: string, Name of schema in the discovery document. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintByName(name, seen=[], dent=1)[:-2] def _prettyPrintSchema(self, schema, seen=None, dent=0): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. seen: list of string, Names of schema already seen. Used to handle recursive definitions. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ if seen is None: seen = [] return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName) def prettyPrintSchema(self, schema): """Get pretty printed object prototype of schema. Args: schema: object, Parsed JSON schema. Returns: string, A string that contains a prototype object with comments that conforms to the given schema. """ # Return with trailing comma and newline removed. return self._prettyPrintSchema(schema, dent=1)[:-2] def get(self, name): """Get deserialized JSON schema from the schema name. Args: name: string, Schema name. """ return self.schemas[name] class _SchemaToStruct(object): """Convert schema to a prototype object.""" def __init__(self, schema, seen, dent=0): """Constructor. Args: schema: object, Parsed JSON schema. seen: list, List of names of schema already seen while parsing. Used to handle recursive definitions. dent: int, Initial indentation depth. """ # The result of this parsing kept as list of strings. self.value = [] # The final value of the parsing. self.string = None # The parsed JSON schema. self.schema = schema # Indentation level. self.dent = dent # Method that when called returns a prototype object for the schema with # the given name. self.from_cache = None # List of names of schema already seen while parsing. self.seen = seen def emit(self, text): """Add text as a line to the output. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text, '\n']) def emitBegin(self, text): """Add text to the output, but with no line terminator. Args: text: string, Text to output. """ self.value.extend([" " * self.dent, text]) def emitEnd(self, text, comment): """Add text and comment to the output with line terminator. Args: text: string, Text to output. comment: string, Python comment. """ if comment: divider = '\n' + ' ' * (self.dent + 2) + '# ' lines = comment.splitlines() lines = [x.rstrip() for x in lines] comment = divider.join(lines) self.value.extend([text, ' # ', comment, '\n']) else: self.value.extend([text, '\n']) def indent(self): """Increase indentation level.""" self.dent += 1 def undent(self): """Decrease indentation level.""" self.dent -= 1 def _to_str_impl(self, schema): """Prototype object based on the schema, in Python code with comments. Args: schema: object, Parsed JSON schema file. Returns: Prototype object based on the schema, in Python code with comments. """ stype = schema.get('type') if stype == 'object': self.emitEnd('{', schema.get('description', '')) self.indent() for pname, pschema in schema.get('properties', {}).iteritems(): self.emitBegin('"%s": ' % pname) self._to_str_impl(pschema) self.undent() self.emit('},') elif '$ref' in schema: schemaName = schema['$ref'] description = schema.get('description', '') s = self.from_cache(schemaName, self.seen) parts = s.splitlines() self.emitEnd(parts[0], description) for line in parts[1:]: self.emit(line.rstrip()) elif stype == 'boolean': value = schema.get('default', 'True or False') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'string': value = schema.get('default', 'A String') self.emitEnd('"%s",' % str(value), schema.get('description', '')) elif stype == 'integer': value = schema.get('default', '42') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'number': value = schema.get('default', '3.14') self.emitEnd('%s,' % str(value), schema.get('description', '')) elif stype == 'null': self.emitEnd('None,', schema.get('description', '')) elif stype == 'any': self.emitEnd('"",', schema.get('description', '')) elif stype == 'array': self.emitEnd('[', schema.get('description')) self.indent() self.emitBegin('') self._to_str_impl(schema['items']) self.undent() self.emit('],') else: self.emit('Unknown type! %s' % stype) self.emitEnd('', '') self.string = ''.join(self.value) return self.string def to_str(self, from_cache): """Prototype object based on the schema, in Python code with comments. Args: from_cache: callable(name, seen), Callable that retrieves an object prototype for a schema with the given name. Seen is a list of schema names already seen as we recursively descend the schema definition. Returns: Prototype object based on the schema, in Python code with comments. The lines of the code will all be properly indented. """ self.from_cache = from_cache return self._to_str_impl(self.schema)
Python
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility module to import a JSON module Hides all the messy details of exactly where we get a simplejson module from. """ __author__ = 'jcgregorio@google.com (Joe Gregorio)' try: # pragma: no cover import simplejson except ImportError: # pragma: no cover try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson
Python
# Early, and incomplete implementation of -04. # import re import urllib RESERVED = ":/?#[]@!$&'()*+,;=" OPERATOR = "+./;?|!@" EXPLODE = "*+" MODIFIER = ":^" TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE) VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE) def _tostring(varname, value, explode, operator, safe=""): if type(value) == type([]): if explode == "+": return ",".join([varname + "." + urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) if type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: return urllib.quote(value, safe) def _tostring_path(varname, value, explode, operator, safe=""): joiner = operator if type(value) == type([]): if explode == "+": return joiner.join([varname + "." + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys]) else: return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return urllib.quote(value, safe) else: return "" def _tostring_query(varname, value, explode, operator, safe=""): joiner = operator varprefix = "" if operator == "?": joiner = "&" varprefix = varname + "=" if type(value) == type([]): if 0 == len(value): return "" if explode == "+": return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value]) elif explode == "*": return joiner.join([urllib.quote(x, safe) for x in value]) else: return varprefix + ",".join([urllib.quote(x, safe) for x in value]) elif type(value) == type({}): if 0 == len(value): return "" keys = value.keys() keys.sort() if explode == "+": return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) elif explode == "*": return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys]) else: return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys]) else: if value: return varname + "=" + urllib.quote(value, safe) else: return varname TOSTRING = { "" : _tostring, "+": _tostring, ";": _tostring_query, "?": _tostring_query, "/": _tostring_path, ".": _tostring_path, } def expand(template, vars): def _sub(match): groupdict = match.groupdict() operator = groupdict.get('operator') if operator is None: operator = '' varlist = groupdict.get('varlist') safe = "@" if operator == '+': safe = RESERVED varspecs = varlist.split(",") varnames = [] defaults = {} for varspec in varspecs: m = VAR.search(varspec) groupdict = m.groupdict() varname = groupdict.get('varname') explode = groupdict.get('explode') partial = groupdict.get('partial') default = groupdict.get('default') if default: defaults[varname] = default varnames.append((varname, explode, partial)) retval = [] joiner = operator prefix = operator if operator == "+": prefix = "" joiner = "," if operator == "?": joiner = "&" if operator == "": joiner = "," for varname, explode, partial in varnames: if varname in vars: value = vars[varname] #if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults: if not value and value != "" and varname in defaults: value = defaults[varname] elif varname in defaults: value = defaults[varname] else: continue retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe)) if "".join(retval): return prefix + joiner.join(retval) else: return "" return TEMPLATE.sub(_sub, template)
Python
#!/usr/bin/env python # Copyright (c) 2010, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module to enforce different constraints on flags. A validator represents an invariant, enforced over a one or more flags. See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual. """ __author__ = 'olexiy@google.com (Olexiy Oryeshko)' class Error(Exception): """Thrown If validator constraint is not satisfied.""" class Validator(object): """Base class for flags validators. Users should NOT overload these classes, and use gflags.Register... methods instead. """ # Used to assign each validator an unique insertion_index validators_count = 0 def __init__(self, checker, message): """Constructor to create all validators. Args: checker: function to verify the constraint. Input of this method varies, see SimpleValidator and DictionaryValidator for a detailed description. message: string, error message to be shown to the user """ self.checker = checker self.message = message Validator.validators_count += 1 # Used to assert validators in the order they were registered (CL/18694236) self.insertion_index = Validator.validators_count def Verify(self, flag_values): """Verify that constraint is satisfied. flags library calls this method to verify Validator's constraint. Args: flag_values: gflags.FlagValues, containing all flags Raises: Error: if constraint is not satisfied. """ param = self._GetInputToCheckerFunction(flag_values) if not self.checker(param): raise Error(self.message) def GetFlagsNames(self): """Return the names of the flags checked by this validator. Returns: [string], names of the flags """ raise NotImplementedError('This method should be overloaded') def PrintFlagsWithValues(self, flag_values): raise NotImplementedError('This method should be overloaded') def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues, containing all flags. Returns: Return type depends on the specific validator. """ raise NotImplementedError('This method should be overloaded') class SimpleValidator(Validator): """Validator behind RegisterValidator() method. Validates that a single flag passes its checker function. The checker function takes the flag value and returns True (if value looks fine) or, if flag value is not valid, either returns False or raises an Exception.""" def __init__(self, flag_name, checker, message): """Constructor. Args: flag_name: string, name of the flag. checker: function to verify the validator. input - value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(SimpleValidator, self).__init__(checker, message) self.flag_name = flag_name def GetFlagsNames(self): return [self.flag_name] def PrintFlagsWithValues(self, flag_values): return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value) def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: value of the corresponding flag. """ return flag_values[self.flag_name].value class DictionaryValidator(Validator): """Validator behind RegisterDictionaryValidator method. Validates that flag values pass their common checker function. The checker function takes flag values and returns True (if values look fine) or, if values are not valid, either returns False or raises an Exception. """ def __init__(self, flag_names, checker, message): """Constructor. Args: flag_names: [string], containing names of the flags used by checker. checker: function to verify the validator. input - dictionary, with keys() being flag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise Error. message: string, error message to be shown to the user if validator's condition is not satisfied """ super(DictionaryValidator, self).__init__(checker, message) self.flag_names = flag_names def _GetInputToCheckerFunction(self, flag_values): """Given flag values, construct the input to be given to checker. Args: flag_values: gflags.FlagValues Returns: dictionary, with keys() being self.lag_names, and value for each key being the value of the corresponding flag (string, boolean, etc). """ return dict([key, flag_values[key].value] for key in self.flag_names) def PrintFlagsWithValues(self, flag_values): prefix = 'flags ' flags_with_values = [] for key in self.flag_names: flags_with_values.append('%s=%s' % (key, flag_values[key].value)) return prefix + ', '.join(flags_with_values) def GetFlagsNames(self): return self.flag_names
Python
"""SocksiPy - Python SOCKS module. Version 1.00 Copyright 2006 Dan-Haim. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAN HAIM OR HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. """ """ Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge """ import base64 import socket import struct import sys if getattr(socket, 'socket', None) is None: raise ImportError('socket.socket missing, proxy support unusable') PROXY_TYPE_SOCKS4 = 1 PROXY_TYPE_SOCKS5 = 2 PROXY_TYPE_HTTP = 3 PROXY_TYPE_HTTP_NO_TUNNEL = 4 _defaultproxy = None _orgsocket = socket.socket class ProxyError(Exception): pass class GeneralProxyError(ProxyError): pass class Socks5AuthError(ProxyError): pass class Socks5Error(ProxyError): pass class Socks4Error(ProxyError): pass class HTTPError(ProxyError): pass _generalerrors = ("success", "invalid data", "not connected", "not available", "bad proxy type", "bad input") _socks5errors = ("succeeded", "general SOCKS server failure", "connection not allowed by ruleset", "Network unreachable", "Host unreachable", "Connection refused", "TTL expired", "Command not supported", "Address type not supported", "Unknown error") _socks5autherrors = ("succeeded", "authentication is required", "all offered authentication methods were rejected", "unknown username or invalid password", "unknown error") _socks4errors = ("request granted", "request rejected or failed", "request rejected because SOCKS server cannot connect to identd on the client", "request rejected because the client program and identd report different user-ids", "unknown error") def setdefaultproxy(proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setdefaultproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. """ global _defaultproxy _defaultproxy = (proxytype, addr, port, rdns, username, password) def wrapmodule(module): """wrapmodule(module) Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using setdefaultproxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if _defaultproxy != None: module.socket.socket = socksocket else: raise GeneralProxyError((4, "no proxy specified")) class socksocket(socket.socket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET, type=SOCK_STREAM and proto=0. """ def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): _orgsocket.__init__(self, family, type, proto, _sock) if _defaultproxy != None: self.__proxy = _defaultproxy else: self.__proxy = (None, None, None, None, None, None) self.__proxysockname = None self.__proxypeername = None self.__httptunnel = True def __recvall(self, count): """__recvall(count) -> data Receive EXACTLY the number of bytes requested from the socket. Blocks until the required number of bytes have been received. """ data = self.recv(count) while len(data) < count: d = self.recv(count-len(data)) if not d: raise GeneralProxyError((0, "connection closed unexpectedly")) data = data + d return data def sendall(self, content, *args): """ override socket.socket.sendall method to rewrite the header for non-tunneling proxies if needed """ if not self.__httptunnel: content = self.__rewriteproxy(content) return super(socksocket, self).sendall(content, *args) def __rewriteproxy(self, header): """ rewrite HTTP request headers to support non-tunneling proxies (i.e. those which do not support the CONNECT method). This only works for HTTP (not HTTPS) since HTTPS requires tunneling. """ host, endpt = None, None hdrs = header.split("\r\n") for hdr in hdrs: if hdr.lower().startswith("host:"): host = hdr elif hdr.lower().startswith("get") or hdr.lower().startswith("post"): endpt = hdr if host and endpt: hdrs.remove(host) hdrs.remove(endpt) host = host.split(" ")[1] endpt = endpt.split(" ") if (self.__proxy[4] != None and self.__proxy[5] != None): hdrs.insert(0, self.__getauthheader()) hdrs.insert(0, "Host: %s" % host) hdrs.insert(0, "%s http://%s%s %s" % (endpt[0], host, endpt[1], endpt[2])) return "\r\n".join(hdrs) def __getauthheader(self): auth = self.__proxy[4] + ":" + self.__proxy[5] return "Proxy-Authorization: Basic " + base64.b64encode(auth) def setproxy(self, proxytype=None, addr=None, port=None, rdns=True, username=None, password=None): """setproxy(proxytype, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxytype - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be preformed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.__proxy = (proxytype, addr, port, rdns, username, password) def __negotiatesocks5(self, destaddr, destport): """__negotiatesocks5(self,destaddr,destport) Negotiates a connection through a SOCKS5 server. """ # First we'll send the authentication packages we support. if (self.__proxy[4]!=None) and (self.__proxy[5]!=None): # The username/password details were supplied to the # setproxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). self.sendall(struct.pack('BBBB', 0x05, 0x02, 0x00, 0x02)) else: # No username/password were entered, therefore we # only support connections with no authentication. self.sendall(struct.pack('BBB', 0x05, 0x01, 0x00)) # We'll receive the server's response to determine which # method was selected chosenauth = self.__recvall(2) if chosenauth[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) # Check the chosen authentication method if chosenauth[1:2] == chr(0x00).encode(): # No authentication is required pass elif chosenauth[1:2] == chr(0x02).encode(): # Okay, we need to perform a basic username/password # authentication. self.sendall(chr(0x01).encode() + chr(len(self.__proxy[4])) + self.__proxy[4] + chr(len(self.__proxy[5])) + self.__proxy[5]) authstat = self.__recvall(2) if authstat[0:1] != chr(0x01).encode(): # Bad response self.close() raise GeneralProxyError((1, _generalerrors[1])) if authstat[1:2] != chr(0x00).encode(): # Authentication failed self.close() raise Socks5AuthError((3, _socks5autherrors[3])) # Authentication succeeded else: # Reaching here is always bad self.close() if chosenauth[1] == chr(0xFF).encode(): raise Socks5AuthError((2, _socks5autherrors[2])) else: raise GeneralProxyError((1, _generalerrors[1])) # Now we can request the actual connection req = struct.pack('BBB', 0x05, 0x01, 0x00) # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: ipaddr = socket.inet_aton(destaddr) req = req + chr(0x01).encode() + ipaddr except socket.error: # Well it's not an IP number, so it's probably a DNS name. if self.__proxy[3]: # Resolve remotely ipaddr = None req = req + chr(0x03).encode() + chr(len(destaddr)).encode() + destaddr else: # Resolve locally ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) req = req + chr(0x01).encode() + ipaddr req = req + struct.pack(">H", destport) self.sendall(req) # Get the response resp = self.__recvall(4) if resp[0:1] != chr(0x05).encode(): self.close() raise GeneralProxyError((1, _generalerrors[1])) elif resp[1:2] != chr(0x00).encode(): # Connection failed self.close() if ord(resp[1:2])<=8: raise Socks5Error((ord(resp[1:2]), _socks5errors[ord(resp[1:2])])) else: raise Socks5Error((9, _socks5errors[9])) # Get the bound address/port elif resp[3:4] == chr(0x01).encode(): boundaddr = self.__recvall(4) elif resp[3:4] == chr(0x03).encode(): resp = resp + self.recv(1) boundaddr = self.__recvall(ord(resp[4:5])) else: self.close() raise GeneralProxyError((1,_generalerrors[1])) boundport = struct.unpack(">H", self.__recvall(2))[0] self.__proxysockname = (boundaddr, boundport) if ipaddr != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def getproxysockname(self): """getsockname() -> address info Returns the bound IP address and port number at the proxy. """ return self.__proxysockname def getproxypeername(self): """getproxypeername() -> address info Returns the IP and port number of the proxy. """ return _orgsocket.getpeername(self) def getpeername(self): """getpeername() -> address info Returns the IP address and port number of the destination machine (note: getproxypeername returns the proxy) """ return self.__proxypeername def __negotiatesocks4(self,destaddr,destport): """__negotiatesocks4(self,destaddr,destport) Negotiates a connection through a SOCKS4 server. """ # Check if the destination address provided is an IP address rmtrslv = False try: ipaddr = socket.inet_aton(destaddr) except socket.error: # It's a DNS name. Check where it should be resolved. if self.__proxy[3]: ipaddr = struct.pack("BBBB", 0x00, 0x00, 0x00, 0x01) rmtrslv = True else: ipaddr = socket.inet_aton(socket.gethostbyname(destaddr)) # Construct the request packet req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr # The username parameter is considered userid for SOCKS4 if self.__proxy[4] != None: req = req + self.__proxy[4] req = req + chr(0x00).encode() # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if rmtrslv: req = req + destaddr + chr(0x00).encode() self.sendall(req) # Get the response from the server resp = self.__recvall(8) if resp[0:1] != chr(0x00).encode(): # Bad data self.close() raise GeneralProxyError((1,_generalerrors[1])) if resp[1:2] != chr(0x5A).encode(): # Server returned an error self.close() if ord(resp[1:2]) in (91, 92, 93): self.close() raise Socks4Error((ord(resp[1:2]), _socks4errors[ord(resp[1:2]) - 90])) else: raise Socks4Error((94, _socks4errors[4])) # Get the bound address/port self.__proxysockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if rmtrslv != None: self.__proxypeername = (socket.inet_ntoa(ipaddr), destport) else: self.__proxypeername = (destaddr, destport) def __negotiatehttp(self, destaddr, destport): """__negotiatehttp(self,destaddr,destport) Negotiates a connection through an HTTP server. """ # If we need to resolve locally, we do this now if not self.__proxy[3]: addr = socket.gethostbyname(destaddr) else: addr = destaddr headers = ["CONNECT ", addr, ":", str(destport), " HTTP/1.1\r\n"] headers += ["Host: ", destaddr, "\r\n"] if (self.__proxy[4] != None and self.__proxy[5] != None): headers += [self.__getauthheader(), "\r\n"] headers.append("\r\n") self.sendall("".join(headers).encode()) # We read the response until we get the string "\r\n\r\n" resp = self.recv(1) while resp.find("\r\n\r\n".encode()) == -1: resp = resp + self.recv(1) # We just need the first line to check if the connection # was successful statusline = resp.splitlines()[0].split(" ".encode(), 2) if statusline[0] not in ("HTTP/1.0".encode(), "HTTP/1.1".encode()): self.close() raise GeneralProxyError((1, _generalerrors[1])) try: statuscode = int(statusline[1]) except ValueError: self.close() raise GeneralProxyError((1, _generalerrors[1])) if statuscode != 200: self.close() raise HTTPError((statuscode, statusline[2])) self.__proxysockname = ("0.0.0.0", 0) self.__proxypeername = (addr, destport) def connect(self, destpair): """connect(self, despair) Connects to the specified destination through a proxy. destpar - A tuple of the IP/DNS address and the port number. (identical to socket's connect). To select the proxy server use setproxy(). """ # Do a minimal input check first if (not type(destpair) in (list,tuple)) or (len(destpair) < 2) or (type(destpair[0]) != type('')) or (type(destpair[1]) != int): raise GeneralProxyError((5, _generalerrors[5])) if self.__proxy[0] == PROXY_TYPE_SOCKS5: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self, (self.__proxy[1], portnum)) self.__negotiatesocks5(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_SOCKS4: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 1080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatesocks4(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1], portnum)) self.__negotiatehttp(destpair[0], destpair[1]) elif self.__proxy[0] == PROXY_TYPE_HTTP_NO_TUNNEL: if self.__proxy[2] != None: portnum = self.__proxy[2] else: portnum = 8080 _orgsocket.connect(self,(self.__proxy[1],portnum)) if destpair[1] == 443: self.__negotiatehttp(destpair[0],destpair[1]) else: self.__httptunnel = False elif self.__proxy[0] == None: _orgsocket.connect(self, (destpair[0], destpair[1])) else: raise GeneralProxyError((4, _generalerrors[4]))
Python
""" iri2uri Converts an IRI to a URI. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" __history__ = """ """ import urlparse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF ), (0xE000, 0xF8FF ), (0xF900, 0xFDCF ), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD ), (0x20000, 0x2FFFD ), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD ), (0x50000, 0x5FFFD ), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD ), (0x80000, 0x8FFFD ), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD ), (0xB0000, 0xBFFFD ), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD ), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD ), (0x100000, 0x10FFFD) ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % ord(o) for o in c.encode('utf-8')]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri ,unicode): (scheme, authority, path, query, fragment) = urlparse.urlsplit(uri) authority = authority.encode('idna') # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urlparse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ u"ftp://ftp.is.co.za/rfc/rfc1808.txt", u"http://www.ietf.org/rfc/rfc2396.txt", u"ldap://[2001:db8::7]/c=GB?objectClass?one", u"mailto:John.Doe@example.com", u"news:comp.infosystems.www.servers.unix", u"tel:+1-816-555-1212", u"telnet://192.0.2.16:80/", u"urn:oasis:names:specification:docbook:dtd:xml:4.1.2" ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """ Test that the right type of escaping is done for each part of the URI.""" self.assertEqual("http://xn--o3h.com/%E2%98%84", iri2uri(u"http://\N{COMET}.com/\N{COMET}")) self.assertEqual("http://bitworking.org/?fred=%E2%98%84", iri2uri(u"http://bitworking.org/?fred=\N{COMET}")) self.assertEqual("http://bitworking.org/#%E2%98%84", iri2uri(u"http://bitworking.org/#\N{COMET}")) self.assertEqual("#%E2%98%84", iri2uri(u"#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")) self.assertEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"))) self.assertNotEqual("/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(u"/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode('utf-8'))) unittest.main()
Python
from __future__ import generators """ httplib2 A caching http interface that supports ETags and gzip to conserve bandwidth. Requires Python 2.3 or later Changelog: 2007-08-18, Rick: Modified so it's able to use a socks proxy if needed. """ __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)", "James Antill", "Xavier Verges Farrero", "Jonathan Feinberg", "Blair Zajac", "Sam Ruby", "Louis Nyffenegger"] __license__ = "MIT" __version__ = "0.7.2" import re import sys import email import email.Utils import email.Message import email.FeedParser import StringIO import gzip import zlib import httplib import urlparse import base64 import os import copy import calendar import time import random import errno # remove depracated warning in python2.6 try: from hashlib import sha1 as _sha, md5 as _md5 except ImportError: import sha import md5 _sha = sha.new _md5 = md5.new import hmac from gettext import gettext as _ import socket try: from httplib2 import socks except ImportError: socks = None # Build the appropriate socket wrapper for ssl try: import ssl # python 2.6 ssl_SSLError = ssl.SSLError def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if disable_validation: cert_reqs = ssl.CERT_NONE else: cert_reqs = ssl.CERT_REQUIRED # We should be specifying SSL version 3 or TLS v1, but the ssl module # doesn't expose the necessary knobs. So we need to go with the default # of SSLv23. return ssl.wrap_socket(sock, keyfile=key_file, certfile=cert_file, cert_reqs=cert_reqs, ca_certs=ca_certs) except (AttributeError, ImportError): ssl_SSLError = None def _ssl_wrap_socket(sock, key_file, cert_file, disable_validation, ca_certs): if not disable_validation: raise CertificateValidationUnsupported( "SSL certificate validation is not supported without " "the ssl module installed. To avoid this error, install " "the ssl module, or explicity disable validation.") ssl_sock = socket.ssl(sock, key_file, cert_file) return httplib.FakeSocket(sock, ssl_sock) if sys.version_info >= (2,3): from iri2uri import iri2uri else: def iri2uri(uri): return uri def has_timeout(timeout): # python 2.6 if hasattr(socket, '_GLOBAL_DEFAULT_TIMEOUT'): return (timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT) return (timeout is not None) __all__ = ['Http', 'Response', 'ProxyInfo', 'HttpLib2Error', 'RedirectMissingLocation', 'RedirectLimit', 'FailedToDecompressContent', 'UnimplementedDigestAuthOptionError', 'UnimplementedHmacDigestAuthOptionError', 'debuglevel', 'ProxiesUnavailableError'] # The httplib debug level, set to a non-zero value to get debug output debuglevel = 0 # Python 2.3 support if sys.version_info < (2,4): def sorted(seq): seq.sort() return seq # Python 2.3 support def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items() if not hasattr(httplib.HTTPResponse, 'getheaders'): httplib.HTTPResponse.getheaders = HTTPResponse__getheaders # All exceptions raised here derive from HttpLib2Error class HttpLib2Error(Exception): pass # Some exceptions can be caught and optionally # be turned back into responses. class HttpLib2ErrorWithResponse(HttpLib2Error): def __init__(self, desc, response, content): self.response = response self.content = content HttpLib2Error.__init__(self, desc) class RedirectMissingLocation(HttpLib2ErrorWithResponse): pass class RedirectLimit(HttpLib2ErrorWithResponse): pass class FailedToDecompressContent(HttpLib2ErrorWithResponse): pass class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): pass class MalformedHeader(HttpLib2Error): pass class RelativeURIError(HttpLib2Error): pass class ServerNotFoundError(HttpLib2Error): pass class ProxiesUnavailableError(HttpLib2Error): pass class CertificateValidationUnsupported(HttpLib2Error): pass class SSLHandshakeError(HttpLib2Error): pass class NotSupportedOnThisPlatform(HttpLib2Error): pass class CertificateHostnameMismatch(SSLHandshakeError): def __init__(self, desc, host, cert): HttpLib2Error.__init__(self, desc) self.host = host self.cert = cert # Open Items: # ----------- # Proxy support # Are we removing the cached content too soon on PUT (only delete on 200 Maybe?) # Pluggable cache storage (supports storing the cache in # flat files by default. We need a plug-in architecture # that can support Berkeley DB and Squid) # == Known Issues == # Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator. # Does not handle Cache-Control: max-stale # Does not use Age: headers when calculating cache freshness. # The number of redirections to follow before giving up. # Note that only GET redirects are automatically followed. # Will also honor 301 requests by saving that info and never # requesting that URI again. DEFAULT_MAX_REDIRECTS = 5 # Default CA certificates file bundled with httplib2. CA_CERTS = os.path.join( os.path.dirname(os.path.abspath(__file__ )), "cacerts.txt") # Which headers are hop-by-hop headers by default HOP_BY_HOP = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'] def _get_end2end_headers(response): hopbyhop = list(HOP_BY_HOP) hopbyhop.extend([x.strip() for x in response.get('connection', '').split(',')]) return [header for header in response.keys() if header not in hopbyhop] URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?") def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8]) def urlnorm(uri): (scheme, authority, path, query, fragment) = parse_uri(uri) if not scheme or not authority: raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri) authority = authority.lower() scheme = scheme.lower() if not path: path = "/" # Could do syntax based normalization of the URI before # computing the digest. See Section 6.2.2 of Std 66. request_uri = query and "?".join([path, query]) or path scheme = scheme.lower() defrag_uri = scheme + "://" + authority + request_uri return scheme, authority, request_uri, defrag_uri # Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/) re_url_scheme = re.compile(r'^\w+://') re_slash = re.compile(r'[?/:|]+') def safename(filename): """Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in. """ try: if re_url_scheme.match(filename): if isinstance(filename,str): filename = filename.decode('utf-8') filename = filename.encode('idna') else: filename = filename.encode('idna') except UnicodeError: pass if isinstance(filename,unicode): filename=filename.encode('utf-8') filemd5 = _md5(filename).hexdigest() filename = re_url_scheme.sub("", filename) filename = re_slash.sub(",", filename) # limit length of filename if len(filename)>200: filename=filename[:200] return ",".join((filename, filemd5)) NORMALIZE_SPACE = re.compile(r'(?:\r\n)?[ \t]+') def _normalize_headers(headers): return dict([ (key.lower(), NORMALIZE_SPACE.sub(value, ' ').strip()) for (key, value) in headers.iteritems()]) def _parse_cache_control(headers): retval = {} if headers.has_key('cache-control'): parts = headers['cache-control'].split(',') parts_with_args = [tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=")] parts_wo_args = [(name.strip().lower(), 1) for name in parts if -1 == name.find("=")] retval = dict(parts_with_args + parts_wo_args) return retval # Whether to use a strict mode to parse WWW-Authenticate headers # Might lead to bad results in case of ill-formed header value, # so disabled by default, falling back to relaxed parsing. # Set to true to turn on, usefull for testing servers. USE_WWW_AUTH_STRICT_PARSING = 0 # In regex below: # [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP # "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space # Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both: # \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"? WWW_AUTH_STRICT = re.compile(r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$") WWW_AUTH_RELAXED = re.compile(r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$") UNQUOTE_PAIRS = re.compile(r'\\(.)') def _parse_www_authenticate(headers, headername='www-authenticate'): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headers.has_key(headername): try: authenticate = headers[headername].strip() www_auth = USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED while authenticate: # Break off the scheme at the beginning of the line if headername == 'authentication-info': (auth_scheme, the_rest) = ('digest', authenticate) else: (auth_scheme, the_rest) = authenticate.split(" ", 1) # Now loop over all the key value pairs that come after the scheme, # being careful not to roll into the next scheme match = www_auth.search(the_rest) auth_params = {} while match: if match and len(match.groups()) == 3: (key, value, the_rest) = match.groups() auth_params[key.lower()] = UNQUOTE_PAIRS.sub(r'\1', value) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')]) match = www_auth.search(the_rest) retval[auth_scheme.lower()] = auth_params authenticate = the_rest.strip() except ValueError: raise MalformedHeader("WWW-Authenticate") return retval def _entry_disposition(response_headers, request_headers): """Determine freshness from the Date, Expires and Cache-Control headers. We don't handle the following: 1. Cache-Control: max-stale 2. Age: headers are not used in the calculations. Not that this algorithm is simpler than you might think because we are operating as a private (non-shared) cache. This lets us ignore 's-maxage'. We can also ignore 'proxy-invalidate' since we aren't a proxy. We will never return a stale document as fresh as a design decision, and thus the non-implementation of 'max-stale'. This also lets us safely ignore 'must-revalidate' since we operate as if every server has sent 'must-revalidate'. Since we are private we get to ignore both 'public' and 'private' parameters. We also ignore 'no-transform' since we don't do any transformations. The 'no-store' parameter is handled at a higher level. So the only Cache-Control parameters we look at are: no-cache only-if-cached max-age min-fresh """ retval = "STALE" cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if request_headers.has_key('pragma') and request_headers['pragma'].lower().find('no-cache') != -1: retval = "TRANSPARENT" if 'cache-control' not in request_headers: request_headers['cache-control'] = 'no-cache' elif cc.has_key('no-cache'): retval = "TRANSPARENT" elif cc_response.has_key('no-cache'): retval = "STALE" elif cc.has_key('only-if-cached'): retval = "FRESH" elif response_headers.has_key('date'): date = calendar.timegm(email.Utils.parsedate_tz(response_headers['date'])) now = time.time() current_age = max(0, now - date) if cc_response.has_key('max-age'): try: freshness_lifetime = int(cc_response['max-age']) except ValueError: freshness_lifetime = 0 elif response_headers.has_key('expires'): expires = email.Utils.parsedate_tz(response_headers['expires']) if None == expires: freshness_lifetime = 0 else: freshness_lifetime = max(0, calendar.timegm(expires) - date) else: freshness_lifetime = 0 if cc.has_key('max-age'): try: freshness_lifetime = int(cc['max-age']) except ValueError: freshness_lifetime = 0 if cc.has_key('min-fresh'): try: min_fresh = int(cc['min-fresh']) except ValueError: min_fresh = 0 current_age += min_fresh if freshness_lifetime > current_age: retval = "FRESH" return retval def _decompressContent(response, new_content): content = new_content try: encoding = response.get('content-encoding', None) if encoding in ['gzip', 'deflate']: if encoding == 'gzip': content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read() if encoding == 'deflate': content = zlib.decompress(content) response['content-length'] = str(len(content)) # Record the historical presence of the encoding in a way the won't interfere. response['-content-encoding'] = response['content-encoding'] del response['content-encoding'] except IOError: content = "" raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content) return content def _updateCache(request_headers, response_headers, content, cache, cachekey): if cachekey: cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if cc.has_key('no-store') or cc_response.has_key('no-store'): cache.delete(cachekey) else: info = email.Message.Message() for key, value in response_headers.iteritems(): if key not in ['status','content-encoding','transfer-encoding']: info[key] = value # Add annotations to the cache to indicate what headers # are variant for this request. vary = response_headers.get('vary', None) if vary: vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header try: info[key] = request_headers[header] except KeyError: pass status = response_headers.status if status == 304: status = 200 status_header = 'status: %d\r\n' % status header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = "".join([status_header, header_str, content]) cache.set(cachekey, text) def _cnonce(): dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest() return dig[:16] def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode(_sha("%s%s%s" % (cnonce, iso_now, password)).digest()).strip() # For credentials we need two things, first # a pool of credential to try (not necesarily tied to BAsic, Digest, etc.) # Then we also need a list of URIs that have already demanded authentication # That list is tricky since sub-URIs can take the same auth, or the # auth scheme may change as you descend the tree. # So we also need each Auth instance to be able to tell us # how close to the 'top' it is. class Authentication(object): def __init__(self, credentials, host, request_uri, headers, response, content, http): (scheme, authority, path, query, fragment) = parse_uri(request_uri) self.path = path self.host = host self.credentials = credentials self.http = http def depth(self, request_uri): (scheme, authority, path, query, fragment) = parse_uri(request_uri) return request_uri[len(self.path):].count("/") def inscope(self, host, request_uri): # XXX Should we normalize the request_uri? (scheme, authority, path, query, fragment) = parse_uri(request_uri) return (host == self.host) and path.startswith(self.path) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header. Over-rise this in sub-classes.""" pass def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False class BasicAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'Basic ' + base64.b64encode("%s:%s" % self.credentials).strip() class DigestAuthentication(Authentication): """Only do qop='auth' and MD5, since that is all Apache currently implements""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['digest'] qop = self.challenge.get('qop', 'auth') self.challenge['qop'] = ('auth' in [x.strip() for x in qop.split()]) and 'auth' or None if self.challenge['qop'] is None: raise UnimplementedDigestAuthOptionError( _("Unsupported value for qop: %s." % qop)) self.challenge['algorithm'] = self.challenge.get('algorithm', 'MD5').upper() if self.challenge['algorithm'] != 'MD5': raise UnimplementedDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.A1 = "".join([self.credentials[0], ":", self.challenge['realm'], ":", self.credentials[1]]) self.challenge['nc'] = 1 def request(self, method, request_uri, headers, content, cnonce = None): """Modify the request headers""" H = lambda x: _md5(x).hexdigest() KD = lambda s, d: H("%s:%s" % (s, d)) A2 = "".join([method, ":", request_uri]) self.challenge['cnonce'] = cnonce or _cnonce() request_digest = '"%s"' % KD(H(self.A1), "%s:%s:%s:%s:%s" % (self.challenge['nonce'], '%08x' % self.challenge['nc'], self.challenge['cnonce'], self.challenge['qop'], H(A2) )) headers['authorization'] = 'Digest username="%s", realm="%s", nonce="%s", uri="%s", algorithm=%s, response=%s, qop=%s, nc=%08x, cnonce="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['nonce'], request_uri, self.challenge['algorithm'], request_digest, self.challenge['qop'], self.challenge['nc'], self.challenge['cnonce'], ) if self.challenge.get('opaque'): headers['authorization'] += ', opaque="%s"' % self.challenge['opaque'] self.challenge['nc'] += 1 def response(self, response, content): if not response.has_key('authentication-info'): challenge = _parse_www_authenticate(response, 'www-authenticate').get('digest', {}) if 'true' == challenge.get('stale'): self.challenge['nonce'] = challenge['nonce'] self.challenge['nc'] = 1 return True else: updated_challenge = _parse_www_authenticate(response, 'authentication-info').get('digest', {}) if updated_challenge.has_key('nextnonce'): self.challenge['nonce'] = updated_challenge['nextnonce'] self.challenge['nc'] = 1 return False class HmacDigestAuthentication(Authentication): """Adapted from Robert Sayre's code and DigestAuthentication above.""" __author__ = "Thomas Broyer (t.broyer@ltgt.net)" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['hmacdigest'] # TODO: self.challenge['domain'] self.challenge['reason'] = self.challenge.get('reason', 'unauthorized') if self.challenge['reason'] not in ['unauthorized', 'integrity']: self.challenge['reason'] = 'unauthorized' self.challenge['salt'] = self.challenge.get('salt', '') if not self.challenge.get('snonce'): raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty.")) self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1') if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1') if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm'])) if self.challenge['algorithm'] == 'HMAC-MD5': self.hashmod = _md5 else: self.hashmod = _sha if self.challenge['pw-algorithm'] == 'MD5': self.pwhashmod = _md5 else: self.pwhashmod = _sha self.key = "".join([self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(), ":", self.challenge['realm'] ]) self.key = self.pwhashmod.new(self.key).hexdigest().lower() def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist, ) def response(self, response, content): challenge = _parse_www_authenticate(response, 'www-authenticate').get('hmacdigest', {}) if challenge.get('reason') in ['integrity', 'stale']: return True return False class WsseAuthentication(Authentication): """This is thinly tested and should not be relied upon. At this time there isn't any third party server to test against. Blogger and TypePad implemented this algorithm at one point but Blogger has since switched to Basic over HTTPS and TypePad has implemented it wrong, by never issuing a 401 challenge but instead requiring your client to telepathically know that their endpoint is expecting WSSE profile="UsernameToken".""" def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'WSSE profile="UsernameToken"' iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers['X-WSSE'] = 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( self.credentials[0], password_digest, cnonce, iso_now) class GoogleLoginAuthentication(Authentication): def __init__(self, credentials, host, request_uri, headers, response, content, http): from urllib import urlencode Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') service = challenge['googlelogin'].get('service', 'xapi') # Bloggger actually returns the service in the challenge # For the rest we guess based on the URI if service == 'xapi' and request_uri.find("calendar") > 0: service = "cl" # No point in guessing Base or Spreadsheet #elif request_uri.find("spreadsheets") > 0: # service = "wise" auth = dict(Email=credentials[0], Passwd=credentials[1], service=service, source=headers['user-agent']) resp, content = self.http.request("https://www.google.com/accounts/ClientLogin", method="POST", body=urlencode(auth), headers={'Content-Type': 'application/x-www-form-urlencoded'}) lines = content.split('\n') d = dict([tuple(line.split("=", 1)) for line in lines if line]) if resp.status == 403: self.Auth = "" else: self.Auth = d['Auth'] def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers['authorization'] = 'GoogleLogin Auth=' + self.Auth AUTH_SCHEME_CLASSES = { "basic": BasicAuthentication, "wsse": WsseAuthentication, "digest": DigestAuthentication, "hmacdigest": HmacDigestAuthentication, "googlelogin": GoogleLoginAuthentication } AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"] class FileCache(object): """Uses a local directory as a store for cached files. Not really safe to use if multiple threads or processes are going to be running on the same cache. """ def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache): os.makedirs(self.cache) def get(self, key): retval = None cacheFullPath = os.path.join(self.cache, self.safe(key)) try: f = file(cacheFullPath, "rb") retval = f.read() f.close() except IOError: pass return retval def set(self, key, value): cacheFullPath = os.path.join(self.cache, self.safe(key)) f = file(cacheFullPath, "wb") f.write(value) f.close() def delete(self, key): cacheFullPath = os.path.join(self.cache, self.safe(key)) if os.path.exists(cacheFullPath): os.remove(cacheFullPath) class Credentials(object): def __init__(self): self.credentials = [] def add(self, name, password, domain=""): self.credentials.append((domain.lower(), name, password)) def clear(self): self.credentials = [] def iter(self, domain): for (cdomain, name, password) in self.credentials: if cdomain == "" or domain == cdomain: yield (name, password) class KeyCerts(Credentials): """Identical to Credentials except that name/password are mapped to key/cert.""" pass class ProxyInfo(object): """Collect information required to use a proxy.""" def __init__(self, proxy_type, proxy_host, proxy_port, proxy_rdns=None, proxy_user=None, proxy_pass=None): """The parameter proxy_type must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000) """ self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass = proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass def astuple(self): return (self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass) def isgood(self): return (self.proxy_host != None) and (self.proxy_port != None) class HTTPConnectionWithTimeout(httplib.HTTPConnection): """ HTTPConnection subclass that supports timeouts All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None): httplib.HTTPConnection.__init__(self, host, port, strict) self.timeout = timeout self.proxy_info = proxy_info def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( 'Proxy support missing but proxy use was requested!') msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if self.proxy_info and self.proxy_info.isgood(): self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy(*self.proxy_info.astuple()) else: self.sock = socket.socket(af, socktype, proto) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) self.sock.connect(sa) except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg class HTTPSConnectionWithTimeout(httplib.HTTPSConnection): """ This class allows communication via SSL. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): httplib.HTTPSConnection.__init__(self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict) self.timeout = timeout self.proxy_info = proxy_info if ca_certs is None: ca_certs = CA_CERTS self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # The following two methods were adapted from https_wrapper.py, released # with the Google Appengine SDK at # http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py # under the following license: # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # def _GetValidHostsForCert(self, cert): """Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs. """ if 'subjectAltName' in cert: return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns'] else: return [x[0][1] for x in cert['subject'] if x[0][0].lower() == 'commonname'] def _ValidateCertificateHostname(self, cert, hostname): """Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate. """ hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace('.', '\.').replace('*', '[^.]*') if re.search('^%s$' % (host_re,), hostname, re.I): return True return False def connect(self): "Connect to a host on a given (SSL) port." msg = "getaddrinfo returns an empty list" for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo( self.host, self.port, 0, socket.SOCK_STREAM): try: if self.proxy_info and self.proxy_info.isgood(): sock = socks.socksocket(family, socktype, proto) sock.setproxy(*self.proxy_info.astuple()) else: sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if has_timeout(self.timeout): sock.settimeout(self.timeout) sock.connect((self.host, self.port)) self.sock =_ssl_wrap_socket( sock, self.key_file, self.cert_file, self.disable_ssl_certificate_validation, self.ca_certs) if self.debuglevel > 0: print "connect: (%s, %s)" % (self.host, self.port) if not self.disable_ssl_certificate_validation: cert = self.sock.getpeercert() hostname = self.host.split(':', 0)[0] if not self._ValidateCertificateHostname(cert, hostname): raise CertificateHostnameMismatch( 'Server presented certificate that does not match ' 'host %s: %s' % (hostname, cert), hostname, cert) except ssl_SSLError, e: if sock: sock.close() if self.sock: self.sock.close() self.sock = None # Unfortunately the ssl module doesn't seem to provide any way # to get at more detailed error information, in particular # whether the error is due to certificate validation or # something else (such as SSL protocol mismatch). if e.errno == ssl.SSL_ERROR_SSL: raise SSLHandshakeError(e) else: raise except (socket.timeout, socket.gaierror): raise except socket.error, msg: if self.debuglevel > 0: print 'connect fail:', (self.host, self.port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg SCHEME_TO_CONNECTION = { 'http': HTTPConnectionWithTimeout, 'https': HTTPSConnectionWithTimeout } # Use a different connection object for Google App Engine try: from google.appengine.api import apiproxy_stub_map if apiproxy_stub_map.apiproxy.GetStub('urlfetch') is None: raise ImportError # Bail out; we're not actually running on App Engine. from google.appengine.api.urlfetch import fetch from google.appengine.api.urlfetch import InvalidURLError from google.appengine.api.urlfetch import DownloadError from google.appengine.api.urlfetch import ResponseTooLargeError from google.appengine.api.urlfetch import SSLCertificateError class ResponseDict(dict): """Is a dictionary that also has a read() method, so that it can pass itself off as an httlib.HTTPResponse().""" def read(self): pass class AppEngineHttpConnection(object): """Emulates an httplib.HTTPConnection object, but actually uses the Google App Engine urlfetch library. This allows the timeout to be properly used on Google App Engine, and avoids using httplib, which on Google App Engine is just another wrapper around urlfetch. """ def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None, ca_certs=None, disable_certificate_validation=False): self.host = host self.port = port self.timeout = timeout if key_file or cert_file or proxy_info or ca_certs: raise NotSupportedOnThisPlatform() self.response = None self.scheme = 'http' self.validate_certificate = not disable_certificate_validation self.sock = True def request(self, method, url, body, headers): # Calculate the absolute URI, which fetch requires netloc = self.host if self.port: netloc = '%s:%s' % (self.host, self.port) absolute_uri = '%s://%s%s' % (self.scheme, netloc, url) try: response = fetch(absolute_uri, payload=body, method=method, headers=headers, allow_truncated=False, follow_redirects=False, deadline=self.timeout, validate_certificate=self.validate_certificate) self.response = ResponseDict(response.headers) self.response['status'] = str(response.status_code) self.response.status = response.status_code setattr(self.response, 'read', lambda : response.content) # Make sure the exceptions raised match the exceptions expected. except InvalidURLError: raise socket.gaierror('') except (DownloadError, ResponseTooLargeError, SSLCertificateError): raise httplib.HTTPException() def getresponse(self): if self.response: return self.response else: raise httplib.HTTPException() def set_debuglevel(self, level): pass def connect(self): pass def close(self): pass class AppEngineHttpsConnection(AppEngineHttpConnection): """Same as AppEngineHttpConnection, but for HTTPS URIs.""" def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None, timeout=None, proxy_info=None): AppEngineHttpConnection.__init__(self, host, port, key_file, cert_file, strict, timeout, proxy_info) self.scheme = 'https' # Update the connection classes to use the Googel App Engine specific ones. SCHEME_TO_CONNECTION = { 'http': AppEngineHttpConnection, 'https': AppEngineHttpsConnection } except ImportError: pass class Http(object): """An HTTP client that handles: - all methods - caching - ETags - compression, - HTTPS - Basic - Digest - WSSE and more. """ def __init__(self, cache=None, timeout=None, proxy_info=None, ca_certs=None, disable_ssl_certificate_validation=False): """ The value of proxy_info is a ProxyInfo instance. If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout ca_certs is the path of a file containing root CA certificates for SSL server certificate validation. By default, a CA cert file bundled with httplib2 is used. If disable_ssl_certificate_validation is true, SSL cert validation will not be performed. """ self.proxy_info = proxy_info self.ca_certs = ca_certs self.disable_ssl_certificate_validation = \ disable_ssl_certificate_validation # Map domain name to an httplib connection self.connections = {} # The location of the cache, for now a directory # where cached responses are held. if cache and isinstance(cache, basestring): self.cache = FileCache(cache) else: self.cache = cache # Name/password self.credentials = Credentials() # Key/cert self.certificates = KeyCerts() # authorization objects self.authorizations = [] # If set to False then no redirects are followed, even safe ones. self.follow_redirects = True # Which HTTP methods do we apply optimistic concurrency to, i.e. # which methods get an "if-match:" etag header added to them. self.optimistic_concurrency_methods = ["PUT", "PATCH"] # If 'follow_redirects' is True, and this is set to True then # all redirecs are followed, including unsafe ones. self.follow_all_redirects = False self.ignore_etag = False self.force_exception_to_status_code = False self.timeout = timeout def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, 'www-authenticate') for cred in self.credentials.iter(host): for scheme in AUTH_SCHEME_ORDER: if challenges.has_key(scheme): yield AUTH_SCHEME_CLASSES[scheme](cred, host, request_uri, headers, response, content, self) def add_credentials(self, name, password, domain=""): """Add a name and password that will be used any time a request requires authentication.""" self.credentials.add(name, password, domain) def add_certificate(self, key, cert, domain): """Add a key and cert that will be used any time a request requires authentication.""" self.certificates.add(key, cert, domain) def clear_credentials(self): """Remove all the names and passwords that are used for authentication""" self.credentials.clear() self.authorizations = [] def _conn_request(self, conn, request_uri, method, body, headers): for i in range(2): try: if conn.sock is None: conn.connect() conn.request(method, request_uri, body, headers) except socket.timeout: raise except socket.gaierror: conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except ssl_SSLError: conn.close() raise except socket.error, e: err = 0 if hasattr(e, 'args'): err = getattr(e, 'args')[0] else: err = e.errno if err == errno.ECONNREFUSED: # Connection refused raise except httplib.HTTPException: # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. if conn.sock is None: if i == 0: conn.close() conn.connect() continue else: conn.close() raise if i == 0: conn.close() conn.connect() continue try: response = conn.getresponse() except (socket.error, httplib.HTTPException): if i == 0: conn.close() conn.connect() continue else: raise else: content = "" if method == "HEAD": response.close() else: content = response.read() response = Response(response) if method != "HEAD": content = _decompressContent(response, content) break return (response, content) def _request(self, conn, host, absolute_uri, request_uri, method, body, headers, redirections, cachekey): """Do the actual request using the connection object and also follow one level of redirects if necessary""" auths = [(auth.depth(request_uri), auth) for auth in self.authorizations if auth.inscope(host, request_uri)] auth = auths and sorted(auths)[0][1] or None if auth: auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers) if auth: if auth.response(response, body): auth.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers ) response._stale_digest = 1 if response.status == 401: for authorization in self._auth_from_challenge(host, request_uri, headers, response, content): authorization.request(method, request_uri, headers, body) (response, content) = self._conn_request(conn, request_uri, method, body, headers, ) if response.status != 401: self.authorizations.append(authorization) authorization.response(response, body) break if (self.follow_all_redirects or (method in ["GET", "HEAD"]) or response.status == 303): if self.follow_redirects and response.status in [300, 301, 302, 303, 307]: # Pick out the location header and basically start from the beginning # remembering first to strip the ETag header and decrement our 'depth' if redirections: if not response.has_key('location') and response.status != 300: raise RedirectMissingLocation( _("Redirected but the response is missing a Location: header."), response, content) # Fix-up relative redirects (which violate an RFC 2616 MUST) if response.has_key('location'): location = response['location'] (scheme, authority, path, query, fragment) = parse_uri(location) if authority == None: response['location'] = urlparse.urljoin(absolute_uri, location) if response.status == 301 and method in ["GET", "HEAD"]: response['-x-permanent-redirect-url'] = response['location'] if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) if headers.has_key('if-none-match'): del headers['if-none-match'] if headers.has_key('if-modified-since'): del headers['if-modified-since'] if response.has_key('location'): location = response['location'] old_response = copy.deepcopy(response) if not old_response.has_key('content-location'): old_response['content-location'] = absolute_uri redirect_method = method if response.status in [302, 303]: redirect_method = "GET" body = None (response, content) = self.request(location, redirect_method, body=body, headers = headers, redirections = redirections - 1) response.previous = old_response else: raise RedirectLimit("Redirected more times than rediection_limit allows.", response, content) elif response.status in [200, 203] and method in ["GET", "HEAD"]: # Don't cache 206's since we aren't going to handle byte range requests if not response.has_key('content-location'): response['content-location'] = absolute_uri _updateCache(headers, response, content, self.cache, cachekey) return (response, content) def _normalize_headers(self, headers): return _normalize_headers(headers) # Need to catch and rebrand some exceptions # Then need to optionally turn all exceptions into status codes # including all socket.* and httplib.* exceptions. def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The 'body' is the entity body to be sent with the request. It is a string object. Any extra headers that are to be sent with the request should be provided in the 'headers' dictionary. The maximum number of redirect to follow before raising an exception is 'redirections. The default is 5. The return value is a tuple of (response, content), the first being and instance of the 'Response' class, the second being a string that contains the response entity body. """ try: if headers is None: headers = {} else: headers = self._normalize_headers(headers) if not headers.has_key('user-agent'): headers['user-agent'] = "Python-httplib2/%s (gzip)" % __version__ uri = iri2uri(uri) (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) domain_port = authority.split(":")[0:2] if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http': scheme = 'https' authority = domain_port[0] conn_key = scheme+":"+authority if conn_key in self.connections: conn = self.connections[conn_key] else: if not connection_type: connection_type = SCHEME_TO_CONNECTION[scheme] certs = list(self.certificates.iter(authority)) if issubclass(connection_type, HTTPSConnectionWithTimeout): if certs: conn = self.connections[conn_key] = connection_type( authority, key_file=certs[0][0], cert_file=certs[0][1], timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info, ca_certs=self.ca_certs, disable_ssl_certificate_validation= self.disable_ssl_certificate_validation) else: conn = self.connections[conn_key] = connection_type( authority, timeout=self.timeout, proxy_info=self.proxy_info) conn.set_debuglevel(debuglevel) if 'range' not in headers and 'accept-encoding' not in headers: headers['accept-encoding'] = 'gzip, deflate' info = email.Message.Message() cached_value = None if self.cache: cachekey = defrag_uri cached_value = self.cache.get(cachekey) if cached_value: # info = email.message_from_string(cached_value) # # Need to replace the line above with the kludge below # to fix the non-existent bug not fixed in this # bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html try: info, content = cached_value.split('\r\n\r\n', 1) feedparser = email.FeedParser.FeedParser() feedparser.feed(info) info = feedparser.close() feedparser._parse = None except IndexError: self.cache.delete(cachekey) cachekey = None cached_value = None else: cachekey = None if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers: # http://www.w3.org/1999/04/Editing/ headers['if-match'] = info['etag'] if method not in ["GET", "HEAD"] and self.cache and cachekey: # RFC 2616 Section 13.10 self.cache.delete(cachekey) # Check the vary header in the cache to see if this request # matches what varies in the cache. if method in ['GET', 'HEAD'] and 'vary' in info: vary = info['vary'] vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header value = info[key] if headers.get(header, None) != value: cached_value = None break if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers: if info.has_key('-x-permanent-redirect-url'): # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "") (response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1) response.previous = Response(info) response.previous.fromcache = True else: # Determine our course of action: # Is the cached entry fresh or stale? # Has the client requested a non-cached response? # # There seems to be three possible answers: # 1. [FRESH] Return the cache entry w/o doing a GET # 2. [STALE] Do the GET (but add in cache validators if available) # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request entry_disposition = _entry_disposition(info, headers) if entry_disposition == "FRESH": if not cached_value: info['status'] = '504' content = "" response = Response(info) if cached_value: response.fromcache = True return (response, content) if entry_disposition == "STALE": if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers: headers['if-none-match'] = info['etag'] if info.has_key('last-modified') and not 'last-modified' in headers: headers['if-modified-since'] = info['last-modified'] elif entry_disposition == "TRANSPARENT": pass (response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) if response.status == 304 and method == "GET": # Rewrite the cache entry with the new end-to-end headers # Take all headers that are in response # and overwrite their values in info. # unless they are hop-by-hop, or are listed in the connection header. for key in _get_end2end_headers(response): info[key] = response[key] merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) response = merged_response response.status = 200 response.fromcache = True elif response.status == 200: content = new_content else: self.cache.delete(cachekey) content = new_content else: cc = _parse_cache_control(headers) if cc.has_key('only-if-cached'): info['status'] = '504' response = Response(info) content = "" else: (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) except Exception, e: if self.force_exception_to_status_code: if isinstance(e, HttpLib2ErrorWithResponse): response = e.response content = e.content response.status = 500 response.reason = str(e) elif isinstance(e, socket.timeout): content = "Request Timeout" response = Response( { "content-type": "text/plain", "status": "408", "content-length": len(content) }) response.reason = "Request Timeout" else: content = str(e) response = Response( { "content-type": "text/plain", "status": "400", "content-length": len(content) }) response.reason = "Bad Request" else: raise return (response, content) class Response(dict): """An object more like email.Message than httplib.HTTPResponse.""" """Is this response from our local cache""" fromcache = False """HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. """ version = 11 "Status code returned by server. " status = 200 """Reason phrase returned by server.""" reason = "Ok" previous = None def __init__(self, info): # info is either an email.Message or # an httplib.HTTPResponse object. if isinstance(info, httplib.HTTPResponse): for key, value in info.getheaders(): self[key.lower()] = value self.status = info.status self['status'] = str(self.status) self.reason = info.reason self.version = info.version elif isinstance(info, email.Message.Message): for key, value in info.items(): self[key] = value self.status = int(self['status']) else: for key, value in info.iteritems(): self[key] = value self.status = int(self.get('status', self.status)) def __getattr__(self, name): if name == 'dict': return self else: raise AttributeError, name
Python
#!/usr/bin/env python # # Copyright (c) 2002, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # --- # Author: Chad Lester # Design and style contributions by: # Amit Patel, Bogdan Cocosel, Daniel Dulitz, Eric Tiedemann, # Eric Veach, Laurence Gonsalves, Matthew Springer # Code reorganized a bit by Craig Silverstein """This module is used to define and parse command line flags. This module defines a *distributed* flag-definition policy: rather than an application having to define all flags in or near main(), each python module defines flags that are useful to it. When one python module imports another, it gains access to the other's flags. (This is implemented by having all modules share a common, global registry object containing all the flag information.) Flags are defined through the use of one of the DEFINE_xxx functions. The specific function used determines how the flag is parsed, checked, and optionally type-converted, when it's seen on the command line. IMPLEMENTATION: DEFINE_* creates a 'Flag' object and registers it with a 'FlagValues' object (typically the global FlagValues FLAGS, defined here). The 'FlagValues' object can scan the command line arguments and pass flag arguments to the corresponding 'Flag' objects for value-checking and type conversion. The converted flag values are available as attributes of the 'FlagValues' object. Code can access the flag through a FlagValues object, for instance gflags.FLAGS.myflag. Typically, the __main__ module passes the command line arguments to gflags.FLAGS for parsing. At bottom, this module calls getopt(), so getopt functionality is supported, including short- and long-style flags, and the use of -- to terminate flags. Methods defined by the flag module will throw 'FlagsError' exceptions. The exception argument will be a human-readable string. FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag. DEFINE_string: takes any input, and interprets it as a string. DEFINE_bool or DEFINE_boolean: typically does not take an argument: say --myflag to set FLAGS.myflag to true, or --nomyflag to set FLAGS.myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=1 or --myflag=false or --myflag=f or --myflag=0 DEFINE_float: takes an input and interprets it as a floating point number. Takes optional args lower_bound and upper_bound; if the number specified on the command line is out of range, it will raise a FlagError. DEFINE_integer: takes an input and interprets it as an integer. Takes optional args lower_bound and upper_bound as for floats. DEFINE_enum: takes a list of strings which represents legal values. If the command-line value is not in this list, raise a flag error. Otherwise, assign to FLAGS.flag as a string. DEFINE_list: Takes a comma-separated list of strings on the commandline. Stores them in a python list object. DEFINE_spaceseplist: Takes a space-separated list of strings on the commandline. Stores them in a python list object. Example: --myspacesepflag "foo bar baz" DEFINE_multistring: The same as DEFINE_string, except the flag can be specified more than once on the commandline. The result is a python list object (list of strings), even if the flag is only on the command line once. DEFINE_multi_int: The same as DEFINE_integer, except the flag can be specified more than once on the commandline. The result is a python list object (list of ints), even if the flag is only on the command line once. SPECIAL FLAGS: There are a few flags that have special meaning: --help prints a list of all the flags in a human-readable fashion --helpshort prints a list of all key flags (see below). --helpxml prints a list of all flags, in XML format. DO NOT parse the output of --help and --helpshort. Instead, parse the output of --helpxml. For more info, see "OUTPUT FOR --helpxml" below. --flagfile=foo read flags from file foo. --undefok=f1,f2 ignore unrecognized option errors for f1,f2. For boolean flags, you should use --undefok=boolflag, and --boolflag and --noboolflag will be accepted. Do not use --undefok=noboolflag. -- as in getopt(), terminates flag-processing FLAGS VALIDATORS: If your program: - requires flag X to be specified - needs flag Y to match a regular expression - or requires any more general constraint to be satisfied then validators are for you! Each validator represents a constraint over one flag, which is enforced starting from the initial parsing of the flags and until the program terminates. Also, lower_bound and upper_bound for numerical flags are enforced using flag validators. Howto: If you want to enforce a constraint over one flag, use gflags.RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS) After flag values are initially parsed, and after any change to the specified flag, method checker(flag_value) will be executed. If constraint is not satisfied, an IllegalFlagValue exception will be raised. See RegisterValidator's docstring for a detailed explanation on how to construct your own checker. EXAMPLE USAGE: FLAGS = gflags.FLAGS gflags.DEFINE_integer('my_version', 0, 'Version number.') gflags.DEFINE_string('filename', None, 'Input file name', short_name='f') gflags.RegisterValidator('my_version', lambda value: value % 2 == 0, message='--my_version must be divisible by 2') gflags.MarkFlagAsRequired('filename') NOTE ON --flagfile: Flags may be loaded from text files in addition to being specified on the commandline. Any flags you don't feel like typing, throw them in a file, one flag per line, for instance: --myflag=myvalue --nomyboolean_flag You then specify your file with the special flag '--flagfile=somefile'. You CAN recursively nest flagfile= tokens OR use multiple files on the command line. Lines beginning with a single hash '#' or a double slash '//' are comments in your flagfile. Any flagfile=<file> will be interpreted as having a relative path from the current working directory rather than from the place the file was included from: myPythonScript.py --flagfile=config/somefile.cfg If somefile.cfg includes further --flagfile= directives, these will be referenced relative to the original CWD, not from the directory the including flagfile was found in! The caveat applies to people who are including a series of nested files in a different dir than they are executing out of. Relative path names are always from CWD, not from the directory of the parent include flagfile. We do now support '~' expanded directory names. Absolute path names ALWAYS work! EXAMPLE USAGE: FLAGS = gflags.FLAGS # Flag names are globally defined! So in general, we need to be # careful to pick names that are unlikely to be used by other libraries. # If there is a conflict, we'll get an error at import time. gflags.DEFINE_string('name', 'Mr. President', 'your name') gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0) gflags.DEFINE_boolean('debug', False, 'produces debugging output') gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender') def main(argv): try: argv = FLAGS(argv) # parse flags except gflags.FlagsError, e: print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS) sys.exit(1) if FLAGS.debug: print 'non-flag arguments:', argv print 'Happy Birthday', FLAGS.name if FLAGS.age is not None: print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender) if __name__ == '__main__': main(sys.argv) KEY FLAGS: As we already explained, each module gains access to all flags defined by all the other modules it transitively imports. In the case of non-trivial scripts, this means a lot of flags ... For documentation purposes, it is good to identify the flags that are key (i.e., really important) to a module. Clearly, the concept of "key flag" is a subjective one. When trying to determine whether a flag is key to a module or not, assume that you are trying to explain your module to a potential user: which flags would you really like to mention first? We'll describe shortly how to declare which flags are key to a module. For the moment, assume we know the set of key flags for each module. Then, if you use the app.py module, you can use the --helpshort flag to print only the help for the flags that are key to the main module, in a human-readable format. NOTE: If you need to parse the flag help, do NOT use the output of --help / --helpshort. That output is meant for human consumption, and may be changed in the future. Instead, use --helpxml; flags that are key for the main module are marked there with a <key>yes</key> element. The set of key flags for a module M is composed of: 1. Flags defined by module M by calling a DEFINE_* function. 2. Flags that module M explictly declares as key by using the function DECLARE_key_flag(<flag_name>) 3. Key flags of other modules that M specifies by using the function ADOPT_module_key_flags(<other_module>) This is a "bulk" declaration of key flags: each flag that is key for <other_module> becomes key for the current module too. Notice that if you do not use the functions described at points 2 and 3 above, then --helpshort prints information only about the flags defined by the main module of our script. In many cases, this behavior is good enough. But if you move part of the main module code (together with the related flags) into a different module, then it is nice to use DECLARE_key_flag / ADOPT_module_key_flags and make sure --helpshort lists all relevant flags (otherwise, your code refactoring may confuse your users). Note: each of DECLARE_key_flag / ADOPT_module_key_flags has its own pluses and minuses: DECLARE_key_flag is more targeted and may lead a more focused --helpshort documentation. ADOPT_module_key_flags is good for cases when an entire module is considered key to the current script. Also, it does not require updates to client scripts when a new flag is added to the module. EXAMPLE USAGE 2 (WITH KEY FLAGS): Consider an application that contains the following three files (two auxiliary modules and a main module) File libfoo.py: import gflags gflags.DEFINE_integer('num_replicas', 3, 'Number of replicas to start') gflags.DEFINE_boolean('rpc2', True, 'Turn on the usage of RPC2.') ... some code ... File libbar.py: import gflags gflags.DEFINE_string('bar_gfs_path', '/gfs/path', 'Path to the GFS files for libbar.') gflags.DEFINE_string('email_for_bar_errors', 'bar-team@google.com', 'Email address for bug reports about module libbar.') gflags.DEFINE_boolean('bar_risky_hack', False, 'Turn on an experimental and buggy optimization.') ... some code ... File myscript.py: import gflags import libfoo import libbar gflags.DEFINE_integer('num_iterations', 0, 'Number of iterations.') # Declare that all flags that are key for libfoo are # key for this module too. gflags.ADOPT_module_key_flags(libfoo) # Declare that the flag --bar_gfs_path (defined in libbar) is key # for this module. gflags.DECLARE_key_flag('bar_gfs_path') ... some code ... When myscript is invoked with the flag --helpshort, the resulted help message lists information about all the key flags for myscript: --num_iterations, --num_replicas, --rpc2, and --bar_gfs_path. Of course, myscript uses all the flags declared by it (in this case, just --num_replicas) or by any of the modules it transitively imports (e.g., the modules libfoo, libbar). E.g., it can access the value of FLAGS.bar_risky_hack, even if --bar_risky_hack is not declared as a key flag for myscript. OUTPUT FOR --helpxml: The --helpxml flag generates output with the following structure: <?xml version="1.0"?> <AllFlags> <program>PROGRAM_BASENAME</program> <usage>MAIN_MODULE_DOCSTRING</usage> (<flag> [<key>yes</key>] <file>DECLARING_MODULE</file> <name>FLAG_NAME</name> <meaning>FLAG_HELP_MESSAGE</meaning> <default>DEFAULT_FLAG_VALUE</default> <current>CURRENT_FLAG_VALUE</current> <type>FLAG_TYPE</type> [OPTIONAL_ELEMENTS] </flag>)* </AllFlags> Notes: 1. The output is intentionally similar to the output generated by the C++ command-line flag library. The few differences are due to the Python flags that do not have a C++ equivalent (at least not yet), e.g., DEFINE_list. 2. New XML elements may be added in the future. 3. DEFAULT_FLAG_VALUE is in serialized form, i.e., the string you can pass for this flag on the command-line. E.g., for a flag defined using DEFINE_list, this field may be foo,bar, not ['foo', 'bar']. 4. CURRENT_FLAG_VALUE is produced using str(). This means that the string 'false' will be represented in the same way as the boolean False. Using repr() would have removed this ambiguity and simplified parsing, but would have broken the compatibility with the C++ command-line flags. 5. OPTIONAL_ELEMENTS describe elements relevant for certain kinds of flags: lower_bound, upper_bound (for flags that specify bounds), enum_value (for enum flags), list_separator (for flags that consist of a list of values, separated by a special token). 6. We do not provide any example here: please use --helpxml instead. This module requires at least python 2.2.1 to run. """ import cgi import getopt import os import re import string import struct import sys # pylint: disable-msg=C6204 try: import fcntl except ImportError: fcntl = None try: # Importing termios will fail on non-unix platforms. import termios except ImportError: termios = None import gflags_validators # pylint: enable-msg=C6204 # Are we running under pychecker? _RUNNING_PYCHECKER = 'pychecker.python' in sys.modules def _GetCallingModuleObjectAndName(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. """ # Walk down the stack to find the first globals dict that's not ours. for depth in range(1, sys.getrecursionlimit()): if not sys._getframe(depth).f_globals is globals(): globals_for_frame = sys._getframe(depth).f_globals module, module_name = _GetModuleObjectAndName(globals_for_frame) if module_name is not None: return module, module_name raise AssertionError("No module was found") def _GetCallingModule(): """Returns the name of the module that's calling into this module.""" return _GetCallingModuleObjectAndName()[1] def _GetThisModuleObjectAndName(): """Returns: (module object, module name) for this module.""" return _GetModuleObjectAndName(globals()) # module exceptions: class FlagsError(Exception): """The base class for all flags errors.""" pass class DuplicateFlag(FlagsError): """Raised if there is a flag naming conflict.""" pass class CantOpenFlagFileError(FlagsError): """Raised if flagfile fails to open: doesn't exist, wrong permissions, etc.""" pass class DuplicateFlagCannotPropagateNoneToSwig(DuplicateFlag): """Special case of DuplicateFlag -- SWIG flag value can't be set to None. This can be raised when a duplicate flag is created. Even if allow_override is True, we still abort if the new value is None, because it's currently impossible to pass None default value back to SWIG. See FlagValues.SetDefault for details. """ pass class DuplicateFlagError(DuplicateFlag): """A DuplicateFlag whose message cites the conflicting definitions. A DuplicateFlagError conveys more information than a DuplicateFlag, namely the modules where the conflicting definitions occur. This class was created to avoid breaking external modules which depend on the existing DuplicateFlags interface. """ def __init__(self, flagname, flag_values, other_flag_values=None): """Create a DuplicateFlagError. Args: flagname: Name of the flag being redefined. flag_values: FlagValues object containing the first definition of flagname. other_flag_values: If this argument is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. """ self.flagname = flagname first_module = flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') if other_flag_values is None: second_module = _GetCallingModule() else: second_module = other_flag_values.FindModuleDefiningFlag( flagname, default='<unknown>') msg = "The flag '%s' is defined twice. First from %s, Second from %s" % ( self.flagname, first_module, second_module) DuplicateFlag.__init__(self, msg) class IllegalFlagValue(FlagsError): """The flag command line argument is illegal.""" pass class UnrecognizedFlag(FlagsError): """Raised if a flag is unrecognized.""" pass # An UnrecognizedFlagError conveys more information than an UnrecognizedFlag. # Since there are external modules that create DuplicateFlags, the interface to # DuplicateFlag shouldn't change. The flagvalue will be assigned the full value # of the flag and its argument, if any, allowing handling of unrecognized flags # in an exception handler. # If flagvalue is the empty string, then this exception is an due to a # reference to a flag that was not already defined. class UnrecognizedFlagError(UnrecognizedFlag): def __init__(self, flagname, flagvalue=''): self.flagname = flagname self.flagvalue = flagvalue UnrecognizedFlag.__init__( self, "Unknown command line flag '%s'" % flagname) # Global variable used by expvar _exported_flags = {} _help_width = 80 # width of help output def GetHelpWidth(): """Returns: an integer, the width of help lines that is used in TextWrap.""" if (not sys.stdout.isatty()) or (termios is None) or (fcntl is None): return _help_width try: data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234') columns = struct.unpack('hh', data)[1] # Emacs mode returns 0. # Here we assume that any value below 40 is unreasonable if columns >= 40: return columns # Returning an int as default is fine, int(int) just return the int. return int(os.getenv('COLUMNS', _help_width)) except (TypeError, IOError, struct.error): return _help_width def CutCommonSpacePrefix(text): """Removes a common space prefix from the lines of a multiline text. If the first line does not start with a space, it is left as it is and only in the remaining lines a common space prefix is being searched for. That means the first line will stay untouched. This is especially useful to turn doc strings into help texts. This is because some people prefer to have the doc comment start already after the apostrophe and then align the following lines while others have the apostrophes on a separate line. The function also drops trailing empty lines and ignores empty lines following the initial content line while calculating the initial common whitespace. Args: text: text to work on Returns: the resulting text """ text_lines = text.splitlines() # Drop trailing empty lines while text_lines and not text_lines[-1]: text_lines = text_lines[:-1] if text_lines: # We got some content, is the first line starting with a space? if text_lines[0] and text_lines[0][0].isspace(): text_first_line = [] else: text_first_line = [text_lines.pop(0)] # Calculate length of common leading whitespace (only over content lines) common_prefix = os.path.commonprefix([line for line in text_lines if line]) space_prefix_len = len(common_prefix) - len(common_prefix.lstrip()) # If we have a common space prefix, drop it from all lines if space_prefix_len: for index in xrange(len(text_lines)): if text_lines[index]: text_lines[index] = text_lines[index][space_prefix_len:] return '\n'.join(text_first_line + text_lines) return '' def TextWrap(text, length=None, indent='', firstline_indent=None, tabs=' '): """Wraps a given text to a maximum line length and returns it. We turn lines that only contain whitespace into empty lines. We keep new lines and tabs (e.g., we do not treat tabs as spaces). Args: text: text to wrap length: maximum length of a line, includes indentation if this is None then use GetHelpWidth() indent: indent for all but first line firstline_indent: indent for first line; if None, fall back to indent tabs: replacement for tabs Returns: wrapped text Raises: FlagsError: if indent not shorter than length FlagsError: if firstline_indent not shorter than length """ # Get defaults where callee used None if length is None: length = GetHelpWidth() if indent is None: indent = '' if len(indent) >= length: raise FlagsError('Indent must be shorter than length') # In line we will be holding the current line which is to be started # with indent (or firstline_indent if available) and then appended # with words. if firstline_indent is None: firstline_indent = '' line = indent else: line = firstline_indent if len(firstline_indent) >= length: raise FlagsError('First line indent must be shorter than length') # If the callee does not care about tabs we simply convert them to # spaces If callee wanted tabs to be single space then we do that # already here. if not tabs or tabs == ' ': text = text.replace('\t', ' ') else: tabs_are_whitespace = not tabs.strip() line_regex = re.compile('([ ]*)(\t*)([^ \t]+)', re.MULTILINE) # Split the text into lines and the lines with the regex above. The # resulting lines are collected in result[]. For each split we get the # spaces, the tabs and the next non white space (e.g. next word). result = [] for text_line in text.splitlines(): # Store result length so we can find out whether processing the next # line gave any new content old_result_len = len(result) # Process next line with line_regex. For optimization we do an rstrip(). # - process tabs (changes either line or word, see below) # - process word (first try to squeeze on line, then wrap or force wrap) # Spaces found on the line are ignored, they get added while wrapping as # needed. for spaces, current_tabs, word in line_regex.findall(text_line.rstrip()): # If tabs weren't converted to spaces, handle them now if current_tabs: # If the last thing we added was a space anyway then drop # it. But let's not get rid of the indentation. if (((result and line != indent) or (not result and line != firstline_indent)) and line[-1] == ' '): line = line[:-1] # Add the tabs, if that means adding whitespace, just add it at # the line, the rstrip() code while shorten the line down if # necessary if tabs_are_whitespace: line += tabs * len(current_tabs) else: # if not all tab replacement is whitespace we prepend it to the word word = tabs * len(current_tabs) + word # Handle the case where word cannot be squeezed onto current last line if len(line) + len(word) > length and len(indent) + len(word) <= length: result.append(line.rstrip()) line = indent + word word = '' # No space left on line or can we append a space? if len(line) + 1 >= length: result.append(line.rstrip()) line = indent else: line += ' ' # Add word and shorten it up to allowed line length. Restart next # line with indent and repeat, or add a space if we're done (word # finished) This deals with words that cannot fit on one line # (e.g. indent + word longer than allowed line length). while len(line) + len(word) >= length: line += word result.append(line[:length]) word = line[length:] line = indent # Default case, simply append the word and a space if word: line += word + ' ' # End of input line. If we have content we finish the line. If the # current line is just the indent but we had content in during this # original line then we need to add an empty line. if (result and line != indent) or (not result and line != firstline_indent): result.append(line.rstrip()) elif len(result) == old_result_len: result.append('') line = indent return '\n'.join(result) def DocToHelp(doc): """Takes a __doc__ string and reformats it as help.""" # Get rid of starting and ending white space. Using lstrip() or even # strip() could drop more than maximum of first line and right space # of last line. doc = doc.strip() # Get rid of all empty lines whitespace_only_line = re.compile('^[ \t]+$', re.M) doc = whitespace_only_line.sub('', doc) # Cut out common space at line beginnings doc = CutCommonSpacePrefix(doc) # Just like this module's comment, comments tend to be aligned somehow. # In other words they all start with the same amount of white space # 1) keep double new lines # 2) keep ws after new lines if not empty line # 3) all other new lines shall be changed to a space # Solution: Match new lines between non white space and replace with space. doc = re.sub('(?<=\S)\n(?=\S)', ' ', doc, re.M) return doc def _GetModuleObjectAndName(globals_dict): """Returns the module that defines a global environment, and its name. Args: globals_dict: A dictionary that should correspond to an environment providing the values of the globals. Returns: A pair consisting of (1) module object and (2) module name (a string). Returns (None, None) if the module could not be identified. """ # The use of .items() (instead of .iteritems()) is NOT a mistake: if # a parallel thread imports a module while we iterate over # .iteritems() (not nice, but possible), we get a RuntimeError ... # Hence, we use the slightly slower but safer .items(). for name, module in sys.modules.items(): if getattr(module, '__dict__', None) is globals_dict: if name == '__main__': # Pick a more informative name for the main module. name = sys.argv[0] return (module, name) return (None, None) def _GetMainModule(): """Returns: string, name of the module from which execution started.""" # First, try to use the same logic used by _GetCallingModuleObjectAndName(), # i.e., call _GetModuleObjectAndName(). For that we first need to # find the dictionary that the main module uses to store the # globals. # # That's (normally) the same dictionary object that the deepest # (oldest) stack frame is using for globals. deepest_frame = sys._getframe(0) while deepest_frame.f_back is not None: deepest_frame = deepest_frame.f_back globals_for_main_module = deepest_frame.f_globals main_module_name = _GetModuleObjectAndName(globals_for_main_module)[1] # The above strategy fails in some cases (e.g., tools that compute # code coverage by redefining, among other things, the main module). # If so, just use sys.argv[0]. We can probably always do this, but # it's safest to try to use the same logic as _GetCallingModuleObjectAndName() if main_module_name is None: main_module_name = sys.argv[0] return main_module_name class FlagValues: """Registry of 'Flag' objects. A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: gflags.FLAGS This class is heavily overloaded: 'Flag' objects are registered via __setitem__: FLAGS['longname'] = x # register a new flag The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through __getattr__. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name) Command line arguments are scanned and passed to the registered 'Flag' objects through the __call__ method. Unparsed arguments, including argv[0] (e.g. the program name) are returned. argv = FLAGS(sys.argv) # scan command line arguments The original registered Flag objects can be retrieved through the use of the dictionary-like operator, __getitem__: x = FLAGS['longname'] # access the registered Flag object The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects. """ def __init__(self): # Since everything in this class is so heavily overloaded, the only # way of defining and using fields is to access __dict__ directly. # Dictionary: flag name (string) -> Flag object. self.__dict__['__flags'] = {} # Dictionary: module name (string) -> list of Flag objects that are defined # by that module. self.__dict__['__flags_by_module'] = {} # Dictionary: module id (int) -> list of Flag objects that are defined by # that module. self.__dict__['__flags_by_module_id'] = {} # Dictionary: module name (string) -> list of Flag objects that are # key for that module. self.__dict__['__key_flags_by_module'] = {} # Set if we should use new style gnu_getopt rather than getopt when parsing # the args. Only possible with Python 2.3+ self.UseGnuGetOpt(False) def UseGnuGetOpt(self, use_gnu_getopt=True): """Use GNU-style scanning. Allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt Args: use_gnu_getopt: wether or not to use GNU style scanning. """ self.__dict__['__use_gnu_getopt'] = use_gnu_getopt def IsGnuGetOpt(self): return self.__dict__['__use_gnu_getopt'] def FlagDict(self): return self.__dict__['__flags'] def FlagsByModuleDict(self): """Returns the dictionary of module_name -> list of defined flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module'] def FlagsByModuleIdDict(self): """Returns the dictionary of module_id -> list of defined flags. Returns: A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. """ return self.__dict__['__flags_by_module_id'] def KeyFlagsByModuleDict(self): """Returns the dictionary of module_name -> list of key flags. Returns: A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. """ return self.__dict__['__key_flags_by_module'] def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module = self.FlagsByModuleDict() flags_by_module.setdefault(module_name, []).append(flag) def _RegisterFlagByModuleId(self, module_id, flag): """Records the module that defines a specific flag. Args: module_id: An int, the ID of the Python module. flag: A Flag object, a flag that is key to the module. """ flags_by_module_id = self.FlagsByModuleIdDict() flags_by_module_id.setdefault(module_id, []).append(flag) def _RegisterKeyFlagForModule(self, module_name, flag): """Specifies that a flag is a key flag for a module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a flag that is key to the module. """ key_flags_by_module = self.KeyFlagsByModuleDict() # The list of key flags for the module named module_name. key_flags = key_flags_by_module.setdefault(module_name, []) # Add flag, but avoid duplicates. if flag not in key_flags: key_flags.append(flag) def _GetFlagsDefinedByModule(self, module): """Returns the list of flags defined by a module. Args: module: A module object or a module name (a string). Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ return list(self.FlagsByModuleDict().get(module, [])) def _GetKeyFlagsForModule(self, module): """Returns the list of key flags for a module. Args: module: A module object or a module name (a string) Returns: A new list of Flag objects. Caller may update this list as he wishes: none of those changes will affect the internals of this FlagValue object. """ if not isinstance(module, str): module = module.__name__ # Any flag is a key flag for the module that defined it. NOTE: # key_flags is a fresh list: we can update it without affecting the # internals of this FlagValues object. key_flags = self._GetFlagsDefinedByModule(module) # Take into account flags explicitly declared as key for a module. for flag in self.KeyFlagsByModuleDict().get(module, []): if flag not in key_flags: key_flags.append(flag) return key_flags def FindModuleDefiningFlag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module, flags in self.FlagsByModuleDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module return default def FindModuleIdDefiningFlag(self, flagname, default=None): """Return the ID of the module defining this flag, or default. Args: flagname: Name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ for module_id, flags in self.FlagsByModuleIdDict().iteritems(): for flag in flags: if flag.name == flagname or flag.short_name == flagname: return module_id return default def AppendFlagValues(self, flag_values): """Appends flags registered in another FlagValues instance. Args: flag_values: registry to copy from """ for flag_name, flag in flag_values.FlagDict().iteritems(): # Each flags with shortname appears here twice (once under its # normal name, and again with its short name). To prevent # problems (DuplicateFlagError) with double flag registration, we # perform a check to make sure that the entry we're looking at is # for its normal name. if flag_name == flag.name: try: self[flag_name] = flag except DuplicateFlagError: raise DuplicateFlagError(flag_name, self, other_flag_values=flag_values) def RemoveFlagValues(self, flag_values): """Remove flags that were previously appended from another FlagValues. Args: flag_values: registry containing flags to remove. """ for flag_name in flag_values.FlagDict(): self.__delattr__(flag_name) def __setitem__(self, name, flag): """Registers a new flag variable.""" fl = self.FlagDict() if not isinstance(flag, Flag): raise IllegalFlagValue(flag) if not isinstance(name, type("")): raise FlagsError("Flag name must be a string") if len(name) == 0: raise FlagsError("Flag name cannot be empty") # If running under pychecker, duplicate keys are likely to be # defined. Disable check for duplicate keys when pycheck'ing. if (name in fl and not flag.allow_override and not fl[name].allow_override and not _RUNNING_PYCHECKER): module, module_name = _GetCallingModuleObjectAndName() if (self.FindModuleDefiningFlag(name) == module_name and id(module) != self.FindModuleIdDefiningFlag(name)): # If the flag has already been defined by a module with the same name, # but a different ID, we can stop here because it indicates that the # module is simply being imported a subsequent time. return raise DuplicateFlagError(name, self) short_name = flag.short_name if short_name is not None: if (short_name in fl and not flag.allow_override and not fl[short_name].allow_override and not _RUNNING_PYCHECKER): raise DuplicateFlagError(short_name, self) fl[short_name] = flag fl[name] = flag global _exported_flags _exported_flags[name] = flag def __getitem__(self, name): """Retrieves the Flag object for the flag --name.""" return self.FlagDict()[name] def __getattr__(self, name): """Retrieves the 'value' attribute of the flag --name.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) return fl[name].value def __setattr__(self, name, value): """Sets the 'value' attribute of the flag --name.""" fl = self.FlagDict() fl[name].value = value self._AssertValidators(fl[name].validators) return value def _AssertAllValidators(self): all_validators = set() for flag in self.FlagDict().itervalues(): for validator in flag.validators: all_validators.add(validator) self._AssertValidators(all_validators) def _AssertValidators(self, validators): """Assert if all validators in the list are satisfied. Asserts validators in the order they were created. Args: validators: Iterable(gflags_validators.Validator), validators to be verified Raises: AttributeError: if validators work with a non-existing flag. IllegalFlagValue: if validation fails for at least one validator """ for validator in sorted( validators, key=lambda validator: validator.insertion_index): try: validator.Verify(self) except gflags_validators.Error, e: message = validator.PrintFlagsWithValues(self) raise IllegalFlagValue('%s: %s' % (message, str(e))) def _FlagIsRegistered(self, flag_obj): """Checks whether a Flag object is registered under some name. Note: this is non trivial: in addition to its normal name, a flag may have a short name too. In self.FlagDict(), both the normal and the short name are mapped to the same flag object. E.g., calling only "del FLAGS.short_name" is not unregistering the corresponding Flag object (it is still registered under the longer name). Args: flag_obj: A Flag object. Returns: A boolean: True iff flag_obj is registered under some name. """ flag_dict = self.FlagDict() # Check whether flag_obj is registered under its long name. name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True # Check whether flag_obj is registered under its short name. short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True # The flag cannot be registered under any other name, so we do not # need to do a full search through the values of self.FlagDict(). return False def __delattr__(self, flag_name): """Deletes a previously-defined flag from a flag object. This method makes sure we can delete a flag by using del flag_values_object.<flag_name> E.g., gflags.DEFINE_integer('foo', 1, 'Integer flag.') del gflags.FLAGS.foo Args: flag_name: A string, the name of the flag to be deleted. Raises: AttributeError: When there is no registered flag named flag_name. """ fl = self.FlagDict() if flag_name not in fl: raise AttributeError(flag_name) flag_obj = fl[flag_name] del fl[flag_name] if not self._FlagIsRegistered(flag_obj): # If the Flag object indicated by flag_name is no longer # registered (please see the docstring of _FlagIsRegistered), then # we delete the occurrences of the flag object in all our internal # dictionaries. self.__RemoveFlagFromDictByModule(self.FlagsByModuleDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.FlagsByModuleIdDict(), flag_obj) self.__RemoveFlagFromDictByModule(self.KeyFlagsByModuleDict(), flag_obj) def __RemoveFlagFromDictByModule(self, flags_by_module_dict, flag_obj): """Removes a flag object from a module -> list of flags dictionary. Args: flags_by_module_dict: A dictionary that maps module names to lists of flags. flag_obj: A flag object. """ for unused_module, flags_in_module in flags_by_module_dict.iteritems(): # while (as opposed to if) takes care of multiple occurrences of a # flag in the list for the same module. while flag_obj in flags_in_module: flags_in_module.remove(flag_obj) def SetDefault(self, name, value): """Changes the default value of the named flag object.""" fl = self.FlagDict() if name not in fl: raise AttributeError(name) fl[name].SetDefault(value) self._AssertValidators(fl[name].validators) def __contains__(self, name): """Returns True if name is a value (flag) in the dict.""" return name in self.FlagDict() has_key = __contains__ # a synonym for __contains__() def __iter__(self): return iter(self.FlagDict()) def __call__(self, argv): """Parses flags from argv; stores parsed flags into this FlagValues object. All unparsed arguments are returned. Flags are parsed using the GNU Program Argument Syntax Conventions, using getopt: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Getopt Args: argv: argument list. Can be of any type that may be converted to a list. Returns: The list of arguments not parsed as options, including argv[0] Raises: FlagsError: on any parsing error """ # Support any sequence type that can be converted to a list argv = list(argv) shortopts = "" longopts = [] fl = self.FlagDict() # This pre parses the argv list for --flagfile=<> options. argv = argv[:1] + self.ReadFlagsFromFiles(argv[1:], force_gnu=False) # Correct the argv to support the google style of passing boolean # parameters. Boolean parameters may be passed by using --mybool, # --nomybool, --mybool=(true|false|1|0). getopt does not support # having options that may or may not have a parameter. We replace # instances of the short form --mybool and --nomybool with their # full forms: --mybool=(true|false). original_argv = list(argv) # list() makes a copy shortest_matches = None for name, flag in fl.items(): if not flag.boolean: continue if shortest_matches is None: # Determine the smallest allowable prefix for all flag names shortest_matches = self.ShortestUniquePrefixes(fl) no_name = 'no' + name prefix = shortest_matches[name] no_prefix = shortest_matches[no_name] # Replace all occurrences of this boolean with extended forms for arg_idx in range(1, len(argv)): arg = argv[arg_idx] if arg.find('=') >= 0: continue if arg.startswith('--'+prefix) and ('--'+name).startswith(arg): argv[arg_idx] = ('--%s=true' % name) elif arg.startswith('--'+no_prefix) and ('--'+no_name).startswith(arg): argv[arg_idx] = ('--%s=false' % name) # Loop over all of the flags, building up the lists of short options # and long options that will be passed to getopt. Short options are # specified as a string of letters, each letter followed by a colon # if it takes an argument. Long options are stored in an array of # strings. Each string ends with an '=' if it takes an argument. for name, flag in fl.items(): longopts.append(name + "=") if len(name) == 1: # one-letter option: allow short flag type also shortopts += name if not flag.boolean: shortopts += ":" longopts.append('undefok=') undefok_flags = [] # In case --undefok is specified, loop to pick up unrecognized # options one by one. unrecognized_opts = [] args = argv[1:] while True: try: if self.__dict__['__use_gnu_getopt']: optlist, unparsed_args = getopt.gnu_getopt(args, shortopts, longopts) else: optlist, unparsed_args = getopt.getopt(args, shortopts, longopts) break except getopt.GetoptError, e: if not e.opt or e.opt in fl: # Not an unrecognized option, re-raise the exception as a FlagsError raise FlagsError(e) # Remove offender from args and try again for arg_index in range(len(args)): if ((args[arg_index] == '--' + e.opt) or (args[arg_index] == '-' + e.opt) or (args[arg_index].startswith('--' + e.opt + '='))): unrecognized_opts.append((e.opt, args[arg_index])) args = args[0:arg_index] + args[arg_index+1:] break else: # We should have found the option, so we don't expect to get # here. We could assert, but raising the original exception # might work better. raise FlagsError(e) for name, arg in optlist: if name == '--undefok': flag_names = arg.split(',') undefok_flags.extend(flag_names) # For boolean flags, if --undefok=boolflag is specified, then we should # also accept --noboolflag, in addition to --boolflag. # Since we don't know the type of the undefok'd flag, this will affect # non-boolean flags as well. # NOTE: You shouldn't use --undefok=noboolflag, because then we will # accept --nonoboolflag here. We are choosing not to do the conversion # from noboolflag -> boolflag because of the ambiguity that flag names # can start with 'no'. undefok_flags.extend('no' + name for name in flag_names) continue if name.startswith('--'): # long option name = name[2:] short_option = 0 else: # short option name = name[1:] short_option = 1 if name in fl: flag = fl[name] if flag.boolean and short_option: arg = 1 flag.Parse(arg) # If there were unrecognized options, raise an exception unless # the options were named via --undefok. for opt, value in unrecognized_opts: if opt not in undefok_flags: raise UnrecognizedFlagError(opt, value) if unparsed_args: if self.__dict__['__use_gnu_getopt']: # if using gnu_getopt just return the program name + remainder of argv. ret_val = argv[:1] + unparsed_args else: # unparsed_args becomes the first non-flag detected by getopt to # the end of argv. Because argv may have been modified above, # return original_argv for this region. ret_val = argv[:1] + original_argv[-len(unparsed_args):] else: ret_val = argv[:1] self._AssertAllValidators() return ret_val def Reset(self): """Resets the values to the point before FLAGS(argv) was called.""" for f in self.FlagDict().values(): f.Unparse() def RegisteredFlags(self): """Returns: a list of the names and short names of all registered flags.""" return list(self.FlagDict()) def FlagValuesDict(self): """Returns: a dictionary that maps flag names to flag values.""" flag_values = {} for flag_name in self.RegisteredFlags(): flag = self.FlagDict()[flag_name] flag_values[flag_name] = flag.value return flag_values def __str__(self): """Generates a help string for all known flags.""" return self.GetHelp() def GetHelp(self, prefix=''): """Generates a help string for all known flags.""" helplist = [] flags_by_module = self.FlagsByModuleDict() if flags_by_module: modules = sorted(flags_by_module) # Print the help for the main module first, if possible. main_module = _GetMainModule() if main_module in modules: modules.remove(main_module) modules = [main_module] + modules for module in modules: self.__RenderOurModuleFlags(module, helplist) self.__RenderModuleFlags('gflags', _SPECIAL_FLAGS.FlagDict().values(), helplist) else: # Just print one long list of flags. self.__RenderFlagList( self.FlagDict().values() + _SPECIAL_FLAGS.FlagDict().values(), helplist, prefix) return '\n'.join(helplist) def __RenderModuleFlags(self, module, flags, output_lines, prefix=""): """Generates a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self.__RenderFlagList(flags, output_lines, prefix + " ") def __RenderOurModuleFlags(self, module, output_lines, prefix=""): """Generates a help string for a given module.""" flags = self._GetFlagsDefinedByModule(module) if flags: self.__RenderModuleFlags(module, flags, output_lines, prefix) def __RenderOurModuleKeyFlags(self, module, output_lines, prefix=""): """Generates a help string for the key flags of a given module. Args: module: A module object or a module name (a string). output_lines: A list of strings. The generated help message lines will be appended to this list. prefix: A string that is prepended to each generated help line. """ key_flags = self._GetKeyFlagsForModule(module) if key_flags: self.__RenderModuleFlags(module, key_flags, output_lines, prefix) def ModuleHelp(self, module): """Describe the key flags of a module. Args: module: A module object or a module name (a string). Returns: string describing the key flags of a module. """ helplist = [] self.__RenderOurModuleKeyFlags(module, helplist) return '\n'.join(helplist) def MainModuleHelp(self): """Describe the key flags of the main module. Returns: string describing the key flags of a module. """ return self.ModuleHelp(_GetMainModule()) def __RenderFlagList(self, flaglist, output_lines, prefix=" "): fl = self.FlagDict() special_fl = _SPECIAL_FLAGS.FlagDict() flaglist = [(flag.name, flag) for flag in flaglist] flaglist.sort() flagset = {} for (name, flag) in flaglist: # It's possible this flag got deleted or overridden since being # registered in the per-module flaglist. Check now against the # canonical source of current flag information, the FlagDict. if fl.get(name, None) != flag and special_fl.get(name, None) != flag: # a different flag is using this name now continue # only print help once if flag in flagset: continue flagset[flag] = 1 flaghelp = "" if flag.short_name: flaghelp += "-%s," % flag.short_name if flag.boolean: flaghelp += "--[no]%s" % flag.name + ":" else: flaghelp += "--%s" % flag.name + ":" flaghelp += " " if flag.help: flaghelp += flag.help flaghelp = TextWrap(flaghelp, indent=prefix+" ", firstline_indent=prefix) if flag.default_as_str: flaghelp += "\n" flaghelp += TextWrap("(default: %s)" % flag.default_as_str, indent=prefix+" ") if flag.parser.syntactic_help: flaghelp += "\n" flaghelp += TextWrap("(%s)" % flag.parser.syntactic_help, indent=prefix+" ") output_lines.append(flaghelp) def get(self, name, default): """Returns the value of a flag (if not None) or a default value. Args: name: A string, the name of a flag. default: Default value to use if the flag value is None. """ value = self.__getattr__(name) if value is not None: # Can't do if not value, b/c value might be '0' or "" return value else: return default def ShortestUniquePrefixes(self, fl): """Returns: dictionary; maps flag names to their shortest unique prefix.""" # Sort the list of flag names sorted_flags = [] for name, flag in fl.items(): sorted_flags.append(name) if flag.boolean: sorted_flags.append('no%s' % name) sorted_flags.sort() # For each name in the sorted list, determine the shortest unique # prefix by comparing itself to the next name and to the previous # name (the latter check uses cached info from the previous loop). shortest_matches = {} prev_idx = 0 for flag_idx in range(len(sorted_flags)): curr = sorted_flags[flag_idx] if flag_idx == (len(sorted_flags) - 1): next = None else: next = sorted_flags[flag_idx+1] next_len = len(next) for curr_idx in range(len(curr)): if (next is None or curr_idx >= next_len or curr[curr_idx] != next[curr_idx]): # curr longer than next or no more chars in common shortest_matches[curr] = curr[:max(prev_idx, curr_idx) + 1] prev_idx = curr_idx break else: # curr shorter than (or equal to) next shortest_matches[curr] = curr prev_idx = curr_idx + 1 # next will need at least one more char return shortest_matches def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type("")): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('-flagfile='): return 1 elif flag_string == '-flagfile': return 1 else: return 0 return 0 def ExtractFilename(self, flagfile_str): """Returns filename from a flagfile_str of form -[-]flagfile=filename. The cases of --flagfile foo and -flagfile foo shouldn't be hitting this function, as they are dealt with in the level above this function. """ if flagfile_str.startswith('--flagfile='): return os.path.expanduser((flagfile_str[(len('--flagfile=')):]).strip()) elif flagfile_str.startswith('-flagfile='): return os.path.expanduser((flagfile_str[(len('-flagfile=')):]).strip()) else: raise FlagsError('Hit illegal --flagfile type: %s' % flagfile_str) def __GetFlagFileLines(self, filename, parsed_file_list): """Returns the useful (!=comments, etc) lines from a file with flags. Args: filename: A string, the name of the flag file. parsed_file_list: A list of the names of the files we have already read. MUTATED BY THIS FUNCTION. Returns: List of strings. See the note below. NOTE(springer): This function checks for a nested --flagfile=<foo> tag and handles the lower file recursively. It returns a list of all the lines that _could_ contain command flags. This is EVERYTHING except whitespace lines and comments (lines starting with '#' or '//'). """ line_list = [] # All line from flagfile. flag_line_list = [] # Subset of lines w/o comments, blanks, flagfile= tags. try: file_obj = open(filename, 'r') except IOError, e_msg: raise CantOpenFlagFileError('ERROR:: Unable to open flagfile: %s' % e_msg) line_list = file_obj.readlines() file_obj.close() parsed_file_list.append(filename) # This is where we check each line in the file we just read. for line in line_list: if line.isspace(): pass # Checks for comment (a line that starts with '#'). elif line.startswith('#') or line.startswith('//'): pass # Checks for a nested "--flagfile=<bar>" flag in the current file. # If we find one, recursively parse down into that file. elif self.__IsFlagFileDirective(line): sub_filename = self.ExtractFilename(line) # We do a little safety check for reparsing a file we've already done. if not sub_filename in parsed_file_list: included_flags = self.__GetFlagFileLines(sub_filename, parsed_file_list) flag_line_list.extend(included_flags) else: # Case of hitting a circularly included file. sys.stderr.write('Warning: Hit circular flagfile dependency: %s\n' % (sub_filename,)) else: # Any line that's not a comment or a nested flagfile should get # copied into 2nd position. This leaves earlier arguments # further back in the list, thus giving them higher priority. flag_line_list.append(line.strip()) return flag_line_list def ReadFlagsFromFiles(self, argv, force_gnu=True): """Processes command line args, but also allow args to be read from file. Args: argv: A list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. force_gnu: If False, --flagfile parsing obeys normal flag semantics. If True, --flagfile parsing instead follows gnu_getopt semantics. *** WARNING *** force_gnu=False may become the future default! Returns: A new list which has the original list combined with what we read from any flagfile(s). References: Global gflags.FLAG class instance. This function should be called before the normal FLAGS(argv) call. This function scans the input list for a flag that looks like: --flagfile=<somefile>. Then it opens <somefile>, reads all valid key and value pairs and inserts them into the input list between the first item of the list and any subsequent items in the list. Note that your application's flags are still defined the usual way using gflags DEFINE_flag() type functions. Notes (assuming we're getting a commandline of some sort as our input): --> Flags from the command line argv _should_ always take precedence! --> A further "--flagfile=<otherfile.cfg>" CAN be nested in a flagfile. It will be processed after the parent flag file is done. --> For duplicate flags, first one we hit should "win". --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines _should_ be ignored. """ parsed_file_list = [] rest_of_args = argv new_argv = [] while rest_of_args: current_arg = rest_of_args[0] rest_of_args = rest_of_args[1:] if self.__IsFlagFileDirective(current_arg): # This handles the case of -(-)flagfile foo. In this case the # next arg really is part of this one. if current_arg == '--flagfile' or current_arg == '-flagfile': if not rest_of_args: raise IllegalFlagValue('--flagfile with no argument') flag_filename = os.path.expanduser(rest_of_args[0]) rest_of_args = rest_of_args[1:] else: # This handles the case of (-)-flagfile=foo. flag_filename = self.ExtractFilename(current_arg) new_argv.extend( self.__GetFlagFileLines(flag_filename, parsed_file_list)) else: new_argv.append(current_arg) # Stop parsing after '--', like getopt and gnu_getopt. if current_arg == '--': break # Stop parsing after a non-flag, like getopt. if not current_arg.startswith('-'): if not force_gnu and not self.__dict__['__use_gnu_getopt']: break if rest_of_args: new_argv.extend(rest_of_args) return new_argv def FlagsIntoString(self): """Returns a string with the flags assignments from this FlagValues object. This function ignores flags whose value is None. Each flag assignment is separated by a newline. NOTE: MUST mirror the behavior of the C++ CommandlineFlagsIntoString from http://code.google.com/p/google-gflags """ s = '' for flag in self.FlagDict().values(): if flag.value is not None: s += flag.Serialize() + '\n' return s def AppendFlagsIntoFile(self, filename): """Appends all flags assignments from this FlagInfo object to a file. Output will be in the format of a flagfile. NOTE: MUST mirror the behavior of the C++ AppendFlagsIntoFile from http://code.google.com/p/google-gflags """ out_file = open(filename, 'a') out_file.write(self.FlagsIntoString()) out_file.close() def WriteHelpInXMLFormat(self, outfile=None): """Outputs flag documentation in XML format. NOTE: We use element names that are consistent with those used by the C++ command-line flag library, from http://code.google.com/p/google-gflags We also use a few new elements (e.g., <key>), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency. Args: outfile: File object we write to. Default None means sys.stdout. """ outfile = outfile or sys.stdout outfile.write('<?xml version=\"1.0\"?>\n') outfile.write('<AllFlags>\n') indent = ' ' _WriteSimpleXMLElement(outfile, 'program', os.path.basename(sys.argv[0]), indent) usage_doc = sys.modules['__main__'].__doc__ if not usage_doc: usage_doc = '\nUSAGE: %s [flags]\n' % sys.argv[0] else: usage_doc = usage_doc.replace('%s', sys.argv[0]) _WriteSimpleXMLElement(outfile, 'usage', usage_doc, indent) # Get list of key flags for the main module. key_flags = self._GetKeyFlagsForModule(_GetMainModule()) # Sort flags by declaring module name and next by flag name. flags_by_module = self.FlagsByModuleDict() all_module_names = list(flags_by_module.keys()) all_module_names.sort() for module_name in all_module_names: flag_list = [(f.name, f) for f in flags_by_module[module_name]] flag_list.sort() for unused_flag_name, flag in flag_list: is_key = flag in key_flags flag.WriteInfoInXMLFormat(outfile, module_name, is_key=is_key, indent=indent) outfile.write('</AllFlags>\n') outfile.flush() def AddValidator(self, validator): """Register new flags validator to be checked. Args: validator: gflags_validators.Validator Raises: AttributeError: if validators work with a non-existing flag. """ for flag_name in validator.GetFlagsNames(): flag = self.FlagDict()[flag_name] flag.validators.append(validator) # end of FlagValues definition # The global FlagValues instance FLAGS = FlagValues() def _StrOrUnicode(value): """Converts value to a python string or, if necessary, unicode-string.""" try: return str(value) except UnicodeEncodeError: return unicode(value) def _MakeXMLSafe(s): """Escapes <, >, and & from s, and removes XML 1.0-illegal chars.""" s = cgi.escape(s) # Escape <, >, and & # Remove characters that cannot appear in an XML 1.0 document # (http://www.w3.org/TR/REC-xml/#charsets). # # NOTE: if there are problems with current solution, one may move to # XML 1.1, which allows such chars, if they're entity-escaped (&#xHH;). s = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', s) # Convert non-ascii characters to entities. Note: requires python >=2.3 s = s.encode('ascii', 'xmlcharrefreplace') # u'\xce\x88' -> 'u&#904;' return s def _WriteSimpleXMLElement(outfile, name, value, indent): """Writes a simple XML element. Args: outfile: File object we write the XML element to. name: A string, the name of XML element. value: A Python object, whose string representation will be used as the value of the XML element. indent: A string, prepended to each line of generated output. """ value_str = _StrOrUnicode(value) if isinstance(value, bool): # Display boolean values as the C++ flag library does: no caps. value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)) class Flag: """Information about a command-line flag. 'Flag' objects define the following fields: .name - the name for this flag .default - the default value for this flag .default_as_str - default value as repr'd string, e.g., "'true'" (or None) .value - the most recent parsed value of this flag; set by Parse() .help - a help string or None if no help is available .short_name - the single letter alias for this flag (or None) .boolean - if 'true', this flag does not accept arguments .present - true if this flag was parsed from command line flags. .parser - an ArgumentParser object .serializer - an ArgumentSerializer object .allow_override - the flag may be redefined without raising an error The only public method of a 'Flag' object is Parse(), but it is typically only called by a 'FlagValues' object. The Parse() method is a thin wrapper around the 'ArgumentParser' Parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, a FlagsError is raised. Parse() is also called during __init__ to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the __main__ module neglects to parse the command line arguments. The .present attribute is cleared after __init__ parsing. If the default value is set to None, then the __init__ parsing step is skipped and the .value attribute is initialized to None. Note: The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag. """ def __init__(self, parser, serializer, name, default, help_string, short_name=None, boolean=0, allow_override=0): self.name = name if not help_string: help_string = '(no help available)' self.help = help_string self.short_name = short_name self.boolean = boolean self.present = 0 self.parser = parser self.serializer = serializer self.allow_override = allow_override self.value = None self.validators = [] self.SetDefault(default) def __hash__(self): return hash(id(self)) def __eq__(self, other): return self is other def __lt__(self, other): if isinstance(other, Flag): return id(self) < id(other) return NotImplemented def __GetParsedValueAsString(self, value): if value is None: return None if self.serializer: return repr(self.serializer.Serialize(value)) if self.boolean: if value: return repr('true') else: return repr('false') return repr(_StrOrUnicode(value)) def Parse(self, argument): try: self.value = self.parser.Parse(argument) except ValueError, e: # recast ValueError as IllegalFlagValue raise IllegalFlagValue("flag --%s=%s: %s" % (self.name, argument, e)) self.present += 1 def Unparse(self): if self.default is None: self.value = None else: self.Parse(self.default) self.present = 0 def Serialize(self): if self.value is None: return '' if self.boolean: if self.value: return "--%s" % self.name else: return "--no%s" % self.name else: if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) return "--%s=%s" % (self.name, self.serializer.Serialize(self.value)) def SetDefault(self, value): """Changes the default value (and current value too) for this Flag.""" # We can't allow a None override because it may end up not being # passed to C++ code when we're overriding C++ flags. So we # cowardly bail out until someone fixes the semantics of trying to # pass None to a C++ flag. See swig_flags.Init() for details on # this behavior. # TODO(olexiy): Users can directly call this method, bypassing all flags # validators (we don't have FlagValues here, so we can not check # validators). # The simplest solution I see is to make this method private. # Another approach would be to store reference to the corresponding # FlagValues with each flag, but this seems to be an overkill. if value is None and self.allow_override: raise DuplicateFlagCannotPropagateNoneToSwig(self.name) self.default = value self.Unparse() self.default_as_str = self.__GetParsedValueAsString(self.value) def Type(self): """Returns: a string that describes the type of this Flag.""" # NOTE: we use strings, and not the types.*Type constants because # our flags can have more exotic types, e.g., 'comma separated list # of strings', 'whitespace separated list of strings', etc. return self.parser.Type() def WriteInfoInXMLFormat(self, outfile, module_name, is_key=False, indent=''): """Writes common info about this flag, in XML format. This is information that is relevant to all flags (e.g., name, meaning, etc.). If you defined a flag that has some other pieces of info, then please override _WriteCustomInfoInXMLFormat. Please do NOT override this method. Args: outfile: File object we write to. module_name: A string, the name of the module that defines this flag. is_key: A boolean, True iff this flag is key for main module. indent: A string that is prepended to each generated line. """ outfile.write(indent + '<flag>\n') inner_indent = indent + ' ' if is_key: _WriteSimpleXMLElement(outfile, 'key', 'yes', inner_indent) _WriteSimpleXMLElement(outfile, 'file', module_name, inner_indent) # Print flag features that are relevant for all flags. _WriteSimpleXMLElement(outfile, 'name', self.name, inner_indent) if self.short_name: _WriteSimpleXMLElement(outfile, 'short_name', self.short_name, inner_indent) if self.help: _WriteSimpleXMLElement(outfile, 'meaning', self.help, inner_indent) # The default flag value can either be represented as a string like on the # command line, or as a Python object. We serialize this value in the # latter case in order to remain consistent. if self.serializer and not isinstance(self.default, str): default_serialized = self.serializer.Serialize(self.default) else: default_serialized = self.default _WriteSimpleXMLElement(outfile, 'default', default_serialized, inner_indent) _WriteSimpleXMLElement(outfile, 'current', self.value, inner_indent) _WriteSimpleXMLElement(outfile, 'type', self.Type(), inner_indent) # Print extra flag features this flag may have. self._WriteCustomInfoInXMLFormat(outfile, inner_indent) outfile.write(indent + '</flag>\n') def _WriteCustomInfoInXMLFormat(self, outfile, indent): """Writes extra info about this flag, in XML format. "Extra" means "not already printed by WriteInfoInXMLFormat above." Args: outfile: File object we write to. indent: A string that is prepended to each generated line. """ # Usually, the parser knows the extra details about the flag, so # we just forward the call to it. self.parser.WriteCustomInfoInXMLFormat(outfile, indent) # End of Flag definition class _ArgumentParserCache(type): """Metaclass used to cache and share argument parsers among flags.""" _instances = {} def __call__(mcs, *args, **kwargs): """Returns an instance of the argument parser cls. This method overrides behavior of the __new__ methods in all subclasses of ArgumentParser (inclusive). If an instance for mcs with the same set of arguments exists, this instance is returned, otherwise a new instance is created. If any keyword arguments are defined, or the values in args are not hashable, this method always returns a new instance of cls. Args: args: Positional initializer arguments. kwargs: Initializer keyword arguments. Returns: An instance of cls, shared or new. """ if kwargs: return type.__call__(mcs, *args, **kwargs) else: instances = mcs._instances key = (mcs,) + tuple(args) try: return instances[key] except KeyError: # No cache entry for key exists, create a new one. return instances.setdefault(key, type.__call__(mcs, *args)) except TypeError: # An object in args cannot be hashed, always return # a new instance. return type.__call__(mcs, *args) class ArgumentParser(object): """Base class used to parse and convert arguments. The Parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal. Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values. Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only. """ __metaclass__ = _ArgumentParserCache syntactic_help = "" def Parse(self, argument): """Default implementation: always returns its argument unmodified.""" return argument def Type(self): return 'string' def WriteCustomInfoInXMLFormat(self, outfile, indent): pass class ArgumentSerializer: """Base class for generating string representations of a flag value.""" def Serialize(self, value): return _StrOrUnicode(value) class ListSerializer(ArgumentSerializer): def __init__(self, list_sep): self.list_sep = list_sep def Serialize(self, value): return self.list_sep.join([_StrOrUnicode(x) for x in value]) # Flags validators def RegisterValidator(flag_name, checker, message='Flag validation failed', flag_values=FLAGS): """Adds a constraint, which will be enforced during program execution. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_name: string, name of the flag to be checked. checker: method to validate the flag. input - value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). See file's docstring for examples. output - Boolean. Must return True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise gflags_validators.Error(desired_error_message). message: error text to be shown to the user if checker returns False. If checker raises gflags_validators.Error, message from the raised Error will be shown. flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ flag_values.AddValidator(gflags_validators.SimpleValidator(flag_name, checker, message)) def MarkFlagAsRequired(flag_name, flag_values=FLAGS): """Ensure that flag is not None during program execution. Registers a flag validator, which will follow usual validator rules. Args: flag_name: string, name of the flag flag_values: FlagValues Raises: AttributeError: if flag_name is not registered as a valid flag name. """ RegisterValidator(flag_name, lambda value: value is not None, message='Flag --%s must be specified.' % flag_name, flag_values=flag_values) def _RegisterBoundsValidatorIfNeeded(parser, name, flag_values): """Enforce lower and upper bounds for numeric flags. Args: parser: NumericParser (either FloatParser or IntegerParser). Provides lower and upper bounds, and help text to display. name: string, name of the flag flag_values: FlagValues """ if parser.lower_bound is not None or parser.upper_bound is not None: def Checker(value): if value is not None and parser.IsOutsideBounds(value): message = '%s is not %s' % (value, parser.syntactic_help) raise gflags_validators.Error(message) return True RegisterValidator(name, Checker, flag_values=flag_values) # The DEFINE functions are explained in mode details in the module doc string. def DEFINE(parser, name, default, help, flag_values=FLAGS, serializer=None, **args): """Registers a generic Flag object. NOTE: in the docstrings of all DEFINE* functions, "registers" is short for "creates a new flag and registers it". Auxiliary function: clients should use the specialized DEFINE_<type> function instead. Args: parser: ArgumentParser that is used to parse the flag arguments. name: A string, the flag name. default: The default value of the flag. help: A help string. flag_values: FlagValues object the flag will be registered with. serializer: ArgumentSerializer that serializes the flag value. args: Dictionary with extra keyword args that are passes to the Flag __init__. """ DEFINE_flag(Flag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_flag(flag, flag_values=FLAGS): """Registers a 'Flag' object with a 'FlagValues' object. By default, the global FLAGS 'FlagValue' object is used. Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags. """ # copying the reference to flag_values prevents pychecker warnings fv = flag_values fv[flag.name] = flag # Tell flag_values who's defining the flag. if isinstance(flag_values, FlagValues): # Regarding the above isinstance test: some users pass funny # values of flag_values (e.g., {}) in order to avoid the flag # registration (in the past, there used to be a flag_values == # FLAGS test here) and redefine flags with the same name (e.g., # debug). To avoid breaking their code, we perform the # registration only if flag_values is a real FlagValues object. module, module_name = _GetCallingModuleObjectAndName() flag_values._RegisterFlagByModule(module_name, flag) flag_values._RegisterFlagByModuleId(id(module), flag) def _InternalDeclareKeyFlags(flag_names, flag_values=FLAGS, key_flag_values=None): """Declares a flag as key for the calling module. Internal function. User code should call DECLARE_key_flag or ADOPT_module_key_flags instead. Args: flag_names: A list of strings that are names of already-registered Flag objects. flag_values: A FlagValues object that the flags listed in flag_names have registered with (the value of the flag_values argument from the DEFINE_* calls that defined those flags). This should almost never need to be overridden. key_flag_values: A FlagValues object that (among possibly many other things) keeps track of the key flags for each module. Default None means "same as flag_values". This should almost never need to be overridden. Raises: UnrecognizedFlagError: when we refer to a flag that was not defined yet. """ key_flag_values = key_flag_values or flag_values module = _GetCallingModule() for flag_name in flag_names: if flag_name not in flag_values: raise UnrecognizedFlagError(flag_name) flag = flag_values.FlagDict()[flag_name] key_flag_values._RegisterKeyFlagForModule(module, flag) def DECLARE_key_flag(flag_name, flag_values=FLAGS): """Declares one flag as key to the current module. Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --help). Sample usage: gflags.DECLARED_key_flag('flag_1') Args: flag_name: A string, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) flag_values: A FlagValues object. This should almost never need to be overridden. """ if flag_name in _SPECIAL_FLAGS: # Take care of the special flags, e.g., --flagfile, --undefok. # These flags are defined in _SPECIAL_FLAGS, and are treated # specially during flag parsing, taking precedence over the # user-defined flags. _InternalDeclareKeyFlags([flag_name], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) return _InternalDeclareKeyFlags([flag_name], flag_values=flag_values) def ADOPT_module_key_flags(module, flag_values=FLAGS): """Declares that all flags key to a module are key to the current module. Args: module: A module object. flag_values: A FlagValues object. This should almost never need to be overridden. Raises: FlagsError: When given an argument that is a module name (a string), instead of a module object. """ # NOTE(salcianu): an even better test would be if not # isinstance(module, types.ModuleType) but I didn't want to import # types for such a tiny use. if isinstance(module, str): raise FlagsError('Received module name %s; expected a module object.' % module) _InternalDeclareKeyFlags( [f.name for f in flag_values._GetKeyFlagsForModule(module.__name__)], flag_values=flag_values) # If module is this flag module, take _SPECIAL_FLAGS into account. if module == _GetThisModuleObjectAndName()[0]: _InternalDeclareKeyFlags( # As we associate flags with _GetCallingModuleObjectAndName(), the # special flags defined in this module are incorrectly registered with # a different module. So, we can't use _GetKeyFlagsForModule. # Instead, we take all flags from _SPECIAL_FLAGS (a private # FlagValues, where no other module should register flags). [f.name for f in _SPECIAL_FLAGS.FlagDict().values()], flag_values=_SPECIAL_FLAGS, key_flag_values=flag_values) # # STRING FLAGS # def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) # # BOOLEAN FLAGS # class BooleanParser(ArgumentParser): """Parser of boolean values.""" def Convert(self, argument): """Converts the argument to a boolean; raise ValueError on errors.""" if type(argument) == str: if argument.lower() in ['true', 't', '1']: return True elif argument.lower() in ['false', 'f', '0']: return False bool_argument = bool(argument) if argument == bool_argument: # The argument is a valid boolean (True, False, 0, or 1), and not just # something that always converts to bool (list, string, int, etc.). return bool_argument raise ValueError('Non-boolean argument to boolean flag', argument) def Parse(self, argument): val = self.Convert(argument) return val def Type(self): return 'bool' class BooleanFlag(Flag): """Basic boolean flag. Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name. For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox. """ def __init__(self, name, default, help, short_name=None, **args): p = BooleanParser() Flag.__init__(self, p, None, name, default, help, short_name, 1, **args) if not self.help: self.help = "a boolean value" def DEFINE_boolean(name, default, help, flag_values=FLAGS, **args): """Registers a boolean flag. Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line. """ DEFINE_flag(BooleanFlag(name, default, help, **args), flag_values) # Match C++ API to unconfuse C++ people. DEFINE_bool = DEFINE_boolean class HelpFlag(BooleanFlag): """ HelpFlag is a special boolean flag that prints usage information and raises a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --help flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "help", 0, "show this help", short_name="?", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = str(FLAGS) print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) class HelpXMLFlag(BooleanFlag): """Similar to HelpFlag, but generates output in XML format.""" def __init__(self): BooleanFlag.__init__(self, 'helpxml', False, 'like --help, but generates XML output', allow_override=1) def Parse(self, arg): if arg: FLAGS.WriteHelpInXMLFormat(sys.stdout) sys.exit(1) class HelpshortFlag(BooleanFlag): """ HelpshortFlag is a special boolean flag that prints usage information for the "main" module, and rasies a SystemExit exception if it is ever found in the command line arguments. Note this is called with allow_override=1, so other apps can define their own --helpshort flag, replacing this one, if they want. """ def __init__(self): BooleanFlag.__init__(self, "helpshort", 0, "show usage only for this module", allow_override=1) def Parse(self, arg): if arg: doc = sys.modules["__main__"].__doc__ flags = FLAGS.MainModuleHelp() print doc or ("\nUSAGE: %s [flags]\n" % sys.argv[0]) if flags: print "flags:" print flags sys.exit(1) # # Numeric parser - base class for Integer and Float parsers # class NumericParser(ArgumentParser): """Parser of numeric values. Parsed value may be bounded to a given upper and lower bound. """ def IsOutsideBounds(self, val): return ((self.lower_bound is not None and val < self.lower_bound) or (self.upper_bound is not None and val > self.upper_bound)) def Parse(self, argument): val = self.Convert(argument) if self.IsOutsideBounds(val): raise ValueError("%s is not %s" % (val, self.syntactic_help)) return val def WriteCustomInfoInXMLFormat(self, outfile, indent): if self.lower_bound is not None: _WriteSimpleXMLElement(outfile, 'lower_bound', self.lower_bound, indent) if self.upper_bound is not None: _WriteSimpleXMLElement(outfile, 'upper_bound', self.upper_bound, indent) def Convert(self, argument): """Default implementation: always returns its argument unmodified.""" return argument # End of Numeric Parser # # FLOAT FLAGS # class FloatParser(NumericParser): """Parser of floating point values. Parsed value may be bounded to a given upper and lower bound. """ number_article = "a" number_name = "number" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(FloatParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): """Converts argument to a float; raises ValueError on errors.""" return float(argument) def Type(self): return 'float' # End of FloatParser def DEFINE_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be a float. If lower_bound or upper_bound are set, then this flag must be within the given range. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # INTEGER FLAGS # class IntegerParser(NumericParser): """Parser of an integer value. Parsed value may be bounded to a given upper and lower bound. """ number_article = "an" number_name = "integer" syntactic_help = " ".join((number_article, number_name)) def __init__(self, lower_bound=None, upper_bound=None): super(IntegerParser, self).__init__() self.lower_bound = lower_bound self.upper_bound = upper_bound sh = self.syntactic_help if lower_bound is not None and upper_bound is not None: sh = ("%s in the range [%s, %s]" % (sh, lower_bound, upper_bound)) elif lower_bound == 1: sh = "a positive %s" % self.number_name elif upper_bound == -1: sh = "a negative %s" % self.number_name elif lower_bound == 0: sh = "a non-negative %s" % self.number_name elif upper_bound == 0: sh = "a non-positive %s" % self.number_name elif upper_bound is not None: sh = "%s <= %s" % (self.number_name, upper_bound) elif lower_bound is not None: sh = "%s >= %s" % (self.number_name, lower_bound) self.syntactic_help = sh def Convert(self, argument): __pychecker__ = 'no-returnvalues' if type(argument) == str: base = 10 if len(argument) > 2 and argument[0] == "0" and argument[1] == "x": base = 16 return int(argument, base) else: return int(argument) def Type(self): return 'int' def DEFINE_integer(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value must be an integer. If lower_bound, or upper_bound are set, then this flag must be within the given range. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args) _RegisterBoundsValidatorIfNeeded(parser, name, flag_values=flag_values) # # ENUM FLAGS # class EnumParser(ArgumentParser): """Parser of a string enum value (a string value from a given set). If enum_values (see below) is not specified, any string is allowed. """ def __init__(self, enum_values=None): super(EnumParser, self).__init__() self.enum_values = enum_values def Parse(self, argument): if self.enum_values and argument not in self.enum_values: raise ValueError("value should be one of <%s>" % "|".join(self.enum_values)) return argument def Type(self): return 'string enum' class EnumFlag(Flag): """Basic enum flag; its value can be any string from list of enum_values.""" def __init__(self, name, default, help, enum_values=None, short_name=None, **args): enum_values = enum_values or [] p = EnumParser(enum_values) g = ArgumentSerializer() Flag.__init__(self, p, g, name, default, help, short_name, **args) if not self.help: self.help = "an enum string" self.help = "<%s>: %s" % ("|".join(enum_values), self.help) def _WriteCustomInfoInXMLFormat(self, outfile, indent): for enum_value in self.parser.enum_values: _WriteSimpleXMLElement(outfile, 'enum_value', enum_value, indent) def DEFINE_enum(name, default, enum_values, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string from enum_values.""" DEFINE_flag(EnumFlag(name, default, help, enum_values, ** args), flag_values) # # LIST FLAGS # class BaseListParser(ArgumentParser): """Base class for a parser of lists of strings. To extend, inherit from this class; from the subclass __init__, call BaseListParser.__init__(self, token, name) where token is a character used to tokenize, and name is a description of the separator. """ def __init__(self, token=None, name=None): assert name super(BaseListParser, self).__init__() self._token = token self._name = name self.syntactic_help = "a %s separated list" % self._name def Parse(self, argument): if isinstance(argument, list): return argument elif argument == '': return [] else: return [s.strip() for s in argument.split(self._token)] def Type(self): return '%s separated list of strings' % self._name class ListParser(BaseListParser): """Parser for a comma-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, ',', 'comma') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) _WriteSimpleXMLElement(outfile, 'list_separator', repr(','), indent) class WhitespaceSeparatedListParser(BaseListParser): """Parser for a whitespace-separated list of strings.""" def __init__(self): BaseListParser.__init__(self, None, 'whitespace') def WriteCustomInfoInXMLFormat(self, outfile, indent): BaseListParser.WriteCustomInfoInXMLFormat(self, outfile, indent) separators = list(string.whitespace) separators.sort() for ws_char in string.whitespace: _WriteSimpleXMLElement(outfile, 'list_separator', repr(ws_char), indent) def DEFINE_list(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a comma-separated list of strings.""" parser = ListParser() serializer = ListSerializer(',') DEFINE(parser, name, default, help, flag_values, serializer, **args) def DEFINE_spaceseplist(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value is a whitespace-separated list of strings. Any whitespace can be used as a separator. """ parser = WhitespaceSeparatedListParser() serializer = ListSerializer(' ') DEFINE(parser, name, default, help, flag_values, serializer, **args) # # MULTI FLAGS # class MultiFlag(Flag): """A flag that can appear multiple time on the command-line. The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line. See the __doc__ for Flag for most behavior of this class. Only differences in behavior are described here: * The default value may be either a single value or a list of values. A single value is interpreted as the [value] singleton list. * The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value """ def __init__(self, *args, **kwargs): Flag.__init__(self, *args, **kwargs) self.help += ';\n repeat this option to specify a list of values' def Parse(self, arguments): """Parses one or more arguments with the installed parser. Args: arguments: a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. """ if not isinstance(arguments, list): # Default value may be a list of values. Most other arguments # will not be, so convert them into a single-item list to make # processing simpler below. arguments = [arguments] if self.present: # keep a backup reference to list of previously supplied option values values = self.value else: # "erase" the defaults with an empty list values = [] for item in arguments: # have Flag superclass parse argument, overwriting self.value reference Flag.Parse(self, item) # also increments self.present values.append(self.value) # put list of option values back in the 'value' attribute self.value = values def Serialize(self): if not self.serializer: raise FlagsError("Serializer not present for flag %s" % self.name) if self.value is None: return '' s = '' multi_value = self.value for self.value in multi_value: if s: s += ' ' s += Flag.Serialize(self) self.value = multi_value return s def Type(self): return 'multi ' + self.parser.Type() def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, **args): """Registers a generic MultiFlag that parses its args with a given parser. Auxiliary function. Normal users should NOT use it directly. Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags. """ DEFINE_flag(MultiFlag(parser, serializer, name, default, help, **args), flag_values) def DEFINE_multistring(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of any strings. Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings. """ parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary integers. Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers. """ parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) def DEFINE_multi_float(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): """Registers a flag whose value can be a list of arbitrary floats. Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats. """ parser = FloatParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) # Now register the flags that we want to exist in all applications. # These are all defined with allow_override=1, so user-apps can use # these flagnames for their own purposes, if they want. DEFINE_flag(HelpFlag()) DEFINE_flag(HelpshortFlag()) DEFINE_flag(HelpXMLFlag()) # Define special flags here so that help may be generated for them. # NOTE: Please do NOT use _SPECIAL_FLAGS from outside this module. _SPECIAL_FLAGS = FlagValues() DEFINE_string( 'flagfile', "", "Insert flag definitions from the given file into the command line.", _SPECIAL_FLAGS) DEFINE_string( 'undefok', "", "comma-separated list of flag names that it is okay to specify " "on the command line even if the program does not define a flag " "with that name. IMPORTANT: flags in this list that have " "arguments MUST use the --flag=value format.", _SPECIAL_FLAGS)
Python
import os import sys import django.core.handlers.wsgi path = 'C:/Documents and Settings/Laptop/workspace/flexy/src/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'flexy.settings' application = django.core.handlers.wsgi.WSGIHandler()
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.db import models, IntegrityError from flexy.common.errors import * from django.contrib.auth.models import * SUPPORTED_FIELD_TYPES = ["INT", "FLOAT", "CHAR", "CHAR_UNIQ", "TEXT", "NTO1", "DATE", "TIME", "NTOM", "IMAGES", "FILES"] NTO_SUPPORTED_FIELD_TYPES = ["FLOAT", "CHAR", "DATE"] class FlexyClassManager(models.Manager): def add(self, name, enb) : name = ' '.join(name.upper().split()) if name == '' : #Empty name return err[1][1] if enb == '1' or enb == '0' : pass else : #Invalid value for enabled return err[1][2] flexyClass = self.model(name=name, enb=int(enb)) try : flexyClass.save() except IntegrityError : #already exists return err[1][3] return err[1][0] class FlexyClass(models.Model): name = models.CharField(max_length=255, unique=True, null=False) enb = models.BooleanField() objects = FlexyClassManager() usergroup_perm = models.ManyToManyField(Group, through='UserGroup_FlexyClass') class GroupManager(models.Manager): def add(self, name, class_id) : name = ' '.join(name.upper().split()) if name == '' : #Empty name return err[2][1] flexyclass = FlexyClass.objects.get(id=class_id) if flexyclass.enb == 0 : #Class not enabled return err[2][4] group = self.model(name=name, seq=0, flexyclass=flexyclass) try : group.save() except IntegrityError : #already exists return err[2][3] return err[2][0] class FlexyGroup(models.Model): flexyclass = models.ForeignKey(FlexyClass) name = models.CharField(max_length=255, null=False) seq = models.IntegerField() objects = GroupManager() class Meta: unique_together = (('flexyclass', 'name'),) class FieldManager(models.Manager): def add(self, name, type, group_id, enb, sel_field_id) : name = ' '.join(name.upper().split()) if name == '' : #Empty name return err[3][1] if enb == '1' or enb == '0' : pass else : #Invalid value for enabled return err[3][3] if type not in SUPPORTED_FIELD_TYPES : #Invalid Field type provided return err[3][4] group = FlexyGroup.objects.get(id=group_id) if group.flexyclass.enb == 0 : #Class not enabled return err[3][5] sel_field = None if type == 'NTO1' or type == 'NTOM' : sel_field = Field.objects.get(id=int(sel_field_id)) if sel_field.enb == False : return err[3][7] if sel_field.type != 'CHAR_UNIQ' : return err[3][8] prtn_id = Field.objects.filter(type=type).count() field = self.model(flexyclass = group.flexyclass, group = group, name = name, type = type, seq = 0, enb = enb, sel_field = sel_field, prtn_id = prtn_id, extra_field_parent = None) try : field.save() except IntegrityError : #already exists return err[3][6] return err[3][0] def extra_field_add(self, name, type, enb, parent_field) : name = ' '.join(name.upper().split()) if name == '' : #Empty name return err[8][1] if enb == '1' or enb == '0' : pass else : #Invalid value for enabled return err[8][3] if type not in NTO_SUPPORTED_FIELD_TYPES : #Invalid Field type provided return err[8][4] prtn_id = Field.objects.filter(type=type).exclude(extra_field_parent=None).count() field = self.model(flexyclass = parent_field.group.flexyclass, group = parent_field.group, name = name, type = type, seq = 0, enb = enb, sel_field = None, prtn_id = prtn_id, extra_field_parent = parent_field) try : field.save() except IntegrityError : #already exists return err[8][2] return err[8][0] class Field(models.Model): flexyclass = models.ForeignKey(FlexyClass) group = models.ForeignKey(FlexyGroup) name = models.CharField(max_length=255, null=False) type = models.CharField(max_length=64, null=False) seq = models.IntegerField() enb = models.BooleanField() prtn_id = models.IntegerField() objects = FieldManager() sel_field = models.ForeignKey('self', null=True, related_name="%(app_label)s_%(class)s_sel_field") extra_field_parent = models.ForeignKey('self', null=True, related_name="%(app_label)s_%(class)s_extra_field_parent") display_fields = models.ManyToManyField('self', symmetrical=False) usergroup_perm = models.ManyToManyField(Group, through='UserGroup_Field') class Meta: unique_together = (('flexyclass', 'name'),) class UserGroup_FlexyClassManager(models.Manager): def set_perm(self, ug, class_id, perm) : flexyclass = FlexyClass.objects.get(id = class_id) ugc, created = UserGroup_FlexyClass.objects.get_or_create \ (flexyclass = flexyclass, usergroup = ug) ugc.perm = perm ugc.save() class UserGroup_FlexyClass(models.Model): flexyclass = models.ForeignKey(FlexyClass) usergroup = models.ForeignKey(Group) perm = models.IntegerField(null=True) objects = UserGroup_FlexyClassManager() class Meta: unique_together = (('flexyclass', 'usergroup'),) class UserGroup_FieldManager(models.Manager): def set_perm(self, ug, field_id, perm) : field = Field.objects.get(id = field_id) ugf, created = UserGroup_Field.objects.get_or_create \ (field = field, usergroup = ug) ugf.perm = perm ugf.save() class UserGroup_Field(models.Model): field = models.ForeignKey(Field) usergroup = models.ForeignKey(Group) perm = models.IntegerField(null=True) objects = UserGroup_FieldManager() class Meta: unique_together = (('field', 'usergroup'),)
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import patterns urlpatterns = patterns('', (r'^login/', 'flexy.sysmodel.views.login_view'), (r'^logout/', 'flexy.sysmodel.views.logout_view'), (r'^home/', 'flexy.sysmodel.views.home'), (r'^flexyclass/home/', 'flexy.sysmodel.views.flexyclass_home'), (r'^flexyclass/add/', 'flexy.sysmodel.views.flexyclass_add'), (r'^flexyclass/update/(\d+)/', 'flexy.sysmodel.views.flexyclass_update'), (r'^flexyclass/group/add/(\d+)/', 'flexy.sysmodel.views.group_add'), (r'^flexyclass/group/update/(\d+)/', 'flexy.sysmodel.views.group_update'), (r'^flexyclass/field/add/(\d+)/', 'flexy.sysmodel.views.field_add'), (r'^flexyclass/field/update/(\d+)/', 'flexy.sysmodel.views.field_update'), (r'^flexyclass/field/displayfield/add/(\d+)/', 'flexy.sysmodel.views.display_field_add'), (r'^flexyclass/field/displayfield/remove/(\d+)/(\d+)/', 'flexy.sysmodel.views.display_field_remove'), (r'^flexyclass/field/extrafield/add/(\d+)/', 'flexy.sysmodel.views.extra_field_add'), (r'^flexyclass/field/extrafield/update/(\d+)/', 'flexy.sysmodel.views.extra_field_update'), (r'^user/home/', 'flexy.sysmodel.views.user_home'), (r'^user/add/', 'flexy.sysmodel.views.user_add'), (r'^user/update/(\d+)/', 'flexy.sysmodel.views.user_update'), (r'^usergroup/home/', 'flexy.sysmodel.views.user_group_home'), (r'^usergroup/add/', 'flexy.sysmodel.views.user_group_add'), (r'^usergroup/update/(\d+)/', 'flexy.sysmodel.views.user_group_update'), (r'^usergroup/view/(\d+)/', 'flexy.sysmodel.views.user_group_view'), )
Python
from django.contrib.auth import authenticate, login, logout from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.context_processors import csrf from django.contrib.auth.models import User, Group from django.conf import settings from flexy.sysmodel.models import * from flexy.common.errors import * def is_sysmodel(request): """function invoked by each view function to verify if the logged in user is admin """ if request.user.is_authenticated(): if request.user.username == 'sysmodel' : return True else : logout(request) return False def login_view(request): if request.method == 'GET': c = {} c.update(csrf(request)) return render_to_response('sysmodel/login.html', c) else : username = request.POST['USERNAME'] password = request.POST['PASSWORD'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/sysmodel/home/') return HttpResponseRedirect('/sysmodel/login/') def logout_view(request): logout(request) return HttpResponseRedirect('/sysmodel/login/') def home(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': MEDIA_URL = settings.MEDIA_URL return render_to_response('sysmodel/home.html', locals()) def flexyclass_home(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': flexyclasses = FlexyClass.objects.all().order_by('id') groups = FlexyGroup.objects.all().order_by('seq', 'id') fields = Field.objects.all().order_by('seq', 'id') MEDIA_URL = settings.MEDIA_URL return render_to_response('sysmodel/flexyclass/home.html', locals()) def flexyclass_add(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) return render_to_response('sysmodel/flexyclass/add.html', c) elif request.method == 'POST': d = request.POST rd = FlexyClass.objects.add(d['NAME'], d['ENB']) if rd['rc'] == 0 : return HttpResponseRedirect('/sysmodel/flexyclass/home/') else : c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) c.update(rd) return render_to_response('sysmodel/flexyclass/add.html', c) def flexyclass_update(request, class_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/flexyclass/update.html') def group_add(request, class_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) flexyclass = FlexyClass.objects.get(id=class_id) c.update({'flexyclass':flexyclass}) return render_to_response('sysmodel/flexyclass/group/add.html', c) elif request.method == 'POST': d = request.POST rd = FlexyGroup.objects.add(d['NAME'], class_id) if rd['rc'] == 0 : return HttpResponseRedirect('/sysmodel/flexyclass/home/?#' + str(class_id)) else : c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) flexyclass = FlexyClass.objects.get(id=class_id) c.update({'flexyclass':flexyclass}) c.update(rd) return render_to_response('sysmodel/flexyclass/group/add.html', c) def group_update(request, group_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/flexyclass/group/update.html') def field_add(request, class_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) flexyclass = FlexyClass.objects.get(id = class_id) c.update({'flexyclass' : flexyclass}) c.update({'types' : SUPPORTED_FIELD_TYPES}) c.update({'flexyclasses':FlexyClass.objects.filter(enb=1)}) c.update({'fields':Field.objects.filter(enb=1, type="CHAR_UNIQ")}) c.update({'groups':FlexyGroup.objects.filter(flexyclass=flexyclass)}) if request.method == 'GET': return render_to_response('sysmodel/flexyclass/field/add.html', c) elif request.method == 'POST': d = request.POST rd = err[3][0] sel_field_id = None if d['TYPE'] == 'NTO1' or d['TYPE'] == 'NTOM' : if 'SEL_FIELD_ID' not in d: rd = err[3][9] else : sel_field_id = d['SEL_FIELD_ID'] if 'GROUP_ID' not in d: rd = err[3][10] if rd['rc'] == 0 : rd = Field.objects.add(d['NAME'], d['TYPE'], d['GROUP_ID'], d['ENB'], sel_field_id) if rd['rc'] == 0 : return HttpResponseRedirect('/sysmodel/flexyclass/home/?#' + str(class_id)) else : c.update(rd) return render_to_response('sysmodel/flexyclass/field/add.html', c) def field_update(request, field_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/flexyclass/field/update.html') def display_field_add(request, field_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) parent_field = Field.objects.get(id=field_id) c.update({'field' : parent_field}) c.update({'fields' : Field.objects.filter(enb=1, flexyclass=parent_field.sel_field.flexyclass)}) if request.method == 'GET': return render_to_response('sysmodel/flexyclass/field/display_field/add.html',c) if request.method == 'POST': if 'DISPLAY_FIELD_ID' not in request.POST: c.update(err[7][1]) return render_to_response('sysmodel/flexyclass/field/display_field/add.html',c) display_field_id= request.POST['DISPLAY_FIELD_ID'] display_field = Field.objects.get(id=display_field_id) parent_field.display_fields.add(display_field); return HttpResponseRedirect('/sysmodel/flexyclass/home/') def display_field_remove(request, parent_field_id, field_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') parent_field = Field.objects.get(id=parent_field_id) display_field = Field.objects.get(id=field_id) parent_field.display_fields.remove(display_field); return HttpResponseRedirect('/sysmodel/flexyclass/home/') def extra_field_add(request, field_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) c.update({'field' : Field.objects.get(id=field_id)}) c.update({'types' : NTO_SUPPORTED_FIELD_TYPES}) if request.method == 'GET': return render_to_response('sysmodel/flexyclass/field/extra_field/add.html',c) if request.method == 'POST': d = request.POST parent_field = Field.objects.get(id = field_id) rd = Field.objects.extra_field_add(d['NAME'], d['TYPE'], d['ENB'], parent_field) if rd['rc'] == 0 : return HttpResponseRedirect('/sysmodel/flexyclass/home/?#' + str(parent_field.flexyclass.id)) else : c.update(rd) return render_to_response('sysmodel/flexyclass/field/extra_field/add.html',c) def extra_field_update(request, field_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/flexyclass/field/extra_field/update.html') def user_home(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) users = User.objects.all() c.update({'users' : users}) return render_to_response('sysmodel/user/home.html', c) def user_add(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') c = {} user = None c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) c.update({'user_groups' : Group.objects.all()}) if request.method == 'GET': return render_to_response('sysmodel/user/add.html', c) elif request.method == 'POST': d = request.POST rd = None username = ' '.join(d['USERNAME'].upper().split()) if username == "" : # Empty user name rd = err[5][1] elif d['PASSWORD1'] != d['PASSWORD2'] : #Password do not match rd = err[5][2] else : try : user = User.objects.create_user \ (username, '', d['PASSWORD1']) user.save() rd = err[5][0] except IntegrityError : #user already exists rd = err[5][3] if rd['rc'] == 0 : user.groups.clear() if int(d['GROUP_ID']) != -1 : ug = Group.objects.get(id=int(d['GROUP_ID'])) user.groups.add(ug); return HttpResponseRedirect('/sysmodel/user/home/') else : c.update(rd) return render_to_response('sysmodel/user/add.html', c) def user_update(request, class_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/user/update.html') def user_group_home(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) groups = Group.objects.all() c.update({'groups' : groups}) return render_to_response('sysmodel/usergroup/home.html', c) def user_group_add(request): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') c = {} c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) if request.method == 'GET': return render_to_response('sysmodel/usergroup/add.html', c) elif request.method == 'POST': d = request.POST rd = None name = ' '.join(d['NAME'].upper().split()) if name == "" : # Empty user group name rd = err[9][1] else : try : group = Group(name=name).save() rd = err[9][0] except IntegrityError : #user group already exists rd = err[9][2] if rd['rc'] == 0 : return HttpResponseRedirect('/sysmodel/usergroup/home/') else : c.update(rd) return render_to_response('sysmodel/usergroup/add.html', c) def user_group_update(request, class_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': return render_to_response('sysmodel/usergroup/update.html') def user_group_view(request, user_group_id): if is_sysmodel(request) == False : return HttpResponseRedirect('/sysmodel/login/') if request.method == 'GET': c = {} usergroup = Group.objects.get(id = user_group_id) c.update(csrf(request)) c.update({'MEDIA_URL' : settings.MEDIA_URL}) c.update({'flexyclasses' : FlexyClass.objects.all().order_by('id')}) c.update({'groups' : FlexyGroup.objects.all().order_by('seq', 'id')}) c.update({'fields' : Field.objects.all().order_by('seq', 'id')}) c.update({'ug' : usergroup}) c.update({'usergroup_flexyclass' : UserGroup_FlexyClass.objects.filter(usergroup = usergroup)}) c.update({'usergroup_field' : UserGroup_Field.objects.filter(usergroup = usergroup)}) return render_to_response('sysmodel/usergroup/view.html', c) elif request.method == 'POST': dict = request.POST ug = Group.objects.get(id = user_group_id) for key in dict : if key == 'csrfmiddlewaretoken' : pass elif key[:3] == 'FLD' : UserGroup_Field.objects.set_perm(ug, key[4:], dict[key]) elif key[:3] == 'CLS' : UserGroup_FlexyClass.objects.set_perm(ug, key[4:], dict[key]) return HttpResponseRedirect('/sysmodel/usergroup/home/')
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^flexy/', include('flexy.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: (r'^admin/doc/', include('django.contrib.admindocs.urls')), #Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^sysmodel/', include('flexy.sysmodel.urls')), (r'^objects/', include('flexy.objects.urls')), )
Python
# Django settings for flexy project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'inv_db', # Or path to database file if using sqlite3. 'USER': 'inv_user', # Not used with sqlite3. 'PASSWORD': 'inv_password', # Not used with sqlite3. 'HOST': '/tmp/mysql.sock', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" #MEDIA_URL = 'http://localhost/' MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'gm+#-!g&(_#o8ggsscmhtqfq3d7!bv-1j%5+6!kwlz_6kkn9p(' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'flexy.urls' #FLEXY_INSTALL_PATH="/Users/Gagan/Projects/FlexyClass/server/flexy/src/" FLEXY_INSTALL_PATH="C:/Documents and Settings/Laptop/workspace/flexy/src/" TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. FLEXY_INSTALL_PATH + '/flexy/templates/', ) LOGIN_URL='/objects/login/' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'flexy.sysmodel', 'flexy.objects', )
Python
from django.db import models from flexy.sysmodel.models import * from django.db import transaction from flexy.common.db import * class ObjectManager(models.Manager): @transaction.commit_manually def add(self, dict, flexyclass_id) : ret = err[6][0].copy() try : obj = self.model(flexyclass_id = flexyclass_id) obj.save() for field_id in dict : if ret['rc'] != 0 : break if field_id == 'csrfmiddlewaretoken' : continue field = Field.objects.get(id=field_id) val = None try : val = refine_val(field.type, dict[field_id]) except ValueError : ret = err[6][2].copy() ret['rm'] = ret['rm'] + str(field.name) try : print field.name + " = " + str(val) f = Field_Table_Dict[field.type] \ (field_id = field_id, obj_id = obj.id, val = val) f.save() except IntegrityError : ret = err[6][1].copy() ret['rm'] = str(field.name) + " " + val + ret['rm'] finally : if ret['rc'] == 0 : transaction.commit() else : transaction.rollback() return ret class Object(models.Model): flexyclass_id = models.IntegerField() objects = ObjectManager() class Int(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.IntegerField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Float(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.FloatField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Char(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.CharField(max_length=255, null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Text(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.TextField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Char_Uniq(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.CharField(max_length=255, null=True) class Meta: unique_together = (('field_id', 'obj_id'), ('field_id', 'val'),) class NTO1(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.IntegerField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Date(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.DateField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) class Time(models.Model): field_id = models.IntegerField() obj_id = models.IntegerField() val = models.TimeField(null=True) class Meta: unique_together = (('field_id', 'obj_id'),) Field_Table_Dict = \ { 'INT' : Int, 'FLOAT' : Float, 'CHAR' : Char, 'CHAR_UNIQ' : Char_Uniq, 'TEXT' : Text, 'NTO1' : NTO1, 'DATE' : Date, 'TIME' : Time }
Python
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
Python
from django.conf.urls.defaults import patterns urlpatterns = patterns('', (r'^login/', 'flexy.objects.views.login_view'), (r'^logout/', 'flexy.objects.views.logout_view'), (r'^home/', 'flexy.objects.views.home'), (r'^add/(\d+)/', 'flexy.objects.views.add'), (r'^update/(\d+)/', 'flexy.objects.views.update'), (r'^search/(\d+)/', 'flexy.objects.views.search'), (r'^bulkadd/(\d+)/', 'flexy.objects.views.bulkadd'), (r'^bulkupdate/(\d+)/', 'flexy.objects.views.bulkupdate'), (r'^nto1/(\d+)/', 'flexy.objects.views.get_nto1_list'), )
Python
from django.contrib.auth import authenticate, login, logout from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.context_processors import csrf from django.conf import settings from flexy.sysmodel.models import * from flexy.objects.models import * from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required import time def login_view(request): if request.method == 'GET': c = {} c.update(csrf(request)) return render_to_response('objects/login.html', c) else : username = request.POST['USERNAME'] password = request.POST['PASSWORD'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect('/objects/home/') return HttpResponseRedirect('/objects/login/') def logout_view(request): logout(request) return HttpResponseRedirect('/objects/login/') def get_user_group(request) : user = User.objects.get(id=request.user.id) usergroups = user.groups.all() for usergroup in usergroups : return usergroup return None @login_required def home(request): if request.method == 'GET': MEDIA_URL = settings.MEDIA_URL usergroup = get_user_group(request) usergroup_flexyclass = UserGroup_FlexyClass \ .objects.filter(usergroup = usergroup, perm__gt = 0) return render_to_response('objects/home.html', locals()) @login_required def add(request, class_id): if request.method == 'GET': c = {} c.update(csrf(request)) flexyclass = FlexyClass.objects.get(id=class_id) c.update({'flexyclass' : flexyclass}) usergroup = get_user_group(request) usergroup_field = UserGroup_Field \ .objects.filter(usergroup = usergroup, perm__gt = 0, field__flexyclass__id = flexyclass.id) \ .order_by('field__group__seq', 'field__group__id', 'field__seq', 'field__id') c.update({'usergroup_field' : usergroup_field}) return render_to_response('objects/add.html', c) else : ret = Object.objects.add(request.POST, class_id) return render_to_response('common/ajax_response.json', ret) @login_required def update(request, class_id): if request.method == 'GET': return render_to_response('objects/update.html', locals()) @login_required def bulkadd(request, class_id): if request.method == 'GET': return render_to_response('objects/bulkadd.html', locals()) @login_required def bulkupdate(request, class_id): if request.method == 'GET': return render_to_response('objects/bulkupdate.html', locals()) @login_required def search(request, class_id): if request.method == 'GET': return render_to_response('objects/search.html', locals()) @login_required def get_nto1_list(request, field_id): if request.method == 'GET': print field_id return render_to_response('objects/nto1.json', locals())
Python
from datetime import datetime def refine_val(typ, val) : """ Exceptions : ValueError for float, int, time and date types """ ret_val = None if typ == "TEXT" : if val != "": ret_val = val else : val = ' '.join(val.upper().split()) if val != "" : # Check if user has given all spaces if typ == "INT" : ret_val = int(val) elif typ == "FLOAT" : ret_val = float(val) elif typ == "CHAR" or typ == "CHAR_UNIQ" : ret_val = val elif typ == "DATE" : print val dt = datetime.strptime(val, '%d %b %Y') print dt ret_val = dt.date() return ret_val
Python
err = { #flexyclass_add err codes 1 : { 0 : {'rc' : 0, 'rm' : 'Flexy Class added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Invalid value provided for Enabled' }, 3 : {'rc' : 3, 'rm' : 'Flexy Class already exists' }, }, #group_add err codes 2 : { 0 : {'rc' : 0, 'rm' : 'Group added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Invalid value provided for Sequence' }, 3 : {'rc' : 3, 'rm' : 'Group already exists' }, 4 : {'rc' : 4, 'rm' : 'Class not enabled' }, }, #field_add err codes 3 : { 0 : {'rc' : 0, 'rm' : 'Field added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Invalid value provided for Sequence' }, 3 : {'rc' : 3, 'rm' : 'Invalid value provided for Enabled' }, 4 : {'rc' : 4, 'rm' : 'Invalid Field Type' }, 5 : {'rc' : 5, 'rm' : 'Class not enabled' }, 6 : {'rc' : 6, 'rm' : 'Field already exists under this class' }, 7 : {'rc' : 7, 'rm' : 'Mapping Field not enabled' }, 8 : {'rc' : 8, 'rm' : 'Mapping Field not CHAR_UNIQ' }, 9 : {'rc' : 9, 'rm' : 'Mapping Field not provided' }, 10 : {'rc' : 10, 'rm' : 'Group Name not provided' }, }, #view_add err codes 4 : { 0 : {'rc' : 0, 'rm' : 'View added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Invalid value provided for Permissions' }, 3 : {'rc' : 3, 'rm' : 'View already exists' }, }, #user_add err codes 5 : { 0 : {'rc' : 0, 'rm' : 'User added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Password do not match' }, 3 : {'rc' : 3, 'rm' : 'User already exists' }, }, #object_add err codes 6 : { 0 : {'rc' : 0, 'rm' : 'Added successfully' }, 1 : {'rc' : 1, 'rm' : ' already exists' }, 2 : {'rc' : 2, 'rm' : 'Invalid value provided for ' }, }, #display_field_add err codes 7 : { 0 : {'rc' : 0, 'rm' : 'Added successfully' }, 1 : {'rc' : 1, 'rm' : 'No display field provided'}, }, #extra_field_add err codes 8 : { 0 : {'rc' : 0, 'rm' : 'Added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Field already exists under this class' }, 3 : {'rc' : 2, 'rm' : 'Invalid value provided for Enabled' }, 4 : {'rc' : 2, 'rm' : 'Invalid Field Type' }, }, #user_group_add err codes 9 : { 0 : {'rc' : 0, 'rm' : 'User Group added successfully' }, 1 : {'rc' : 1, 'rm' : 'Name cannot be empty' }, 2 : {'rc' : 2, 'rm' : 'Group already exists' }, }, }
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import ui from copier import PhotoCopier ui.wins.engine = PhotoCopier()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import sys, os, os.path import ui import types import fnmatch import i18n import jpegops import fileops from subprocess import Popen, PIPE class PhotoCopier: def __init__(self): self.jpegtran = None self.exiftool = None # # called at program startup # def init(self): # what external binary to use cmd_j = self.findexe( config.jpegtran ) cmd_e = self.findexe( config.exiftool ) # how to execute the binary if sys.platform == 'win32': # 'call' found in bugs.python.org/issue1524 config.jpegtran = 'call ' + fileops.quotepath( cmd_j ) config.exiftool = 'call ' + fileops.quotepath( cmd_e ) else: config.jpegtran = cmd_j config.exiftool = cmd_e # # find all jpeg-files # fromdir can be a list of directories (all are scanned) # self._frompaths = [] if type(config.fromdir) == types.ListType: for dir in config.fromdir: self.addsourcefiles(dir) else: self.addsourcefiles(config.fromdir) # tell number of found files to the user and the progressbar numitems = len(self._frompaths) ui.status( i18n.name['status_found'] + " " + str( numitems ) + " " + i18n.name['status_files'] ) ui.wins.pb.init( numitems ) # finds all jpegs under 'dir' # definition of a jpeg is config.jpegglob def addsourcefiles(self, dir): for root,dirs,files in os.walk( dir ): if len(files) == 0: continue for filt in config.jpegglob: found = fnmatch.filter( files, filt ) if len(found) > 0: for name in found: self._frompaths.append( os.path.join( root, name ) ) # ---------------------------------------------------------------------- def findexe(self, programname): # if an absolute pathname is configured, use that: if os.path.isabs( programname ): return programname # # if the executable is found in FlickFlecks binary dir, use that # tool = config.installdir + os.sep + config.bindir \ + os.sep + programname if os.access( tool, os.X_OK ): return tool # # if we can execute the program then it's in the path, use that # else: cmd = programname + " NOSUCHFILEEXITS" pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) pipe.wait() # # on Windows only 0 means we could execute the program # (XXX: these test are ad hoc, traversing PATH would be better) if sys.platform == 'win32': if pipe.returncode == 0: return programname # # on UNIX we can execute the program and it can give 1 as error # return code (bad parameter) # elif 0 <= pipe.returncode <= 1: return programname ui.ERR( ("cannot find executable %s" % programname) ) # ---------------------------------------------------------------------- # user started the operations # def start(self): if len( self._frompaths) == 0: ui.ERR("No files to copy") from fileops import copy dst = config.todir if not os.path.exists( dst ): ui.ERR("Target directory (%s) does not exists" % dst) self._newnames = [] # -------- copy files to new location and name --------------- ui.status( i18n.name['status_copying'] ) ui.wins.pb.clear() # reset progressbar for src in self._frompaths: (newdir,newname) = jpegops.newname( src ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # step progressbar targetNOTok = True counter = 0 # if the targetfilename already exists, increase the counter # and add it to the generated filename # loop until unique name is found while targetNOTok: if config.targetdirs == True: to = dst + os.path.sep + newdir + os.path.sep + newname else: to = dst + os.path.sep + newname if counter > 0: to += "-" + str(counter) to += ".jpg" if os.access( to, os.F_OK ): if counter > 999: ui.ERR( "cannot transfer file: %s" % src ) counter = counter + 1 else: targetNOTok = False # end while # make target subdirs if not already made if config.targetdirs == True: path = dst + os.path.sep for dir in newdir.split( os.path.sep ): path += dir + os.path.sep if not os.path.exists( path ): os.mkdir( path ) # save the targetfilename for rotation operations self._newnames.append( to ) copy( src, to ) # ------------ rotate files ------------- ui.status( i18n.name['status_rotating'] ) ui.wins.pb.clear() # reset progressbar for file in self._newnames: jpegops.rotate( file ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # update progressbar ui.status( i18n.name['status_done'] ) ui.Ready()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config name = {} # config.LANGUAGE is used as a module name to import # an object/hash named Text() from that module should contain # localized strings # XXX: should really use gettext and http://translationproject.org # or similar service def init(): global name mod = __import__( config.LANGUAGE, globals(), locals() ) name = mod.Text()
Python
class Text: def __init__(self): self.d = { 'apperror' : 'Application error', 'finished' : 'Files copied successfully.', 'appclose' : 'This application will now close', 'menu_file' : 'File', 'menu_file_exit' : 'Exit', 'menu_about' : 'About...', 'label_copyfrom' : 'Copy files from:', 'label_copyto' : 'To:', 'label_status' : 'Status:', 'button_start' : 'Start', 'button_stop' : 'Cancel', 'status_idle' : 'Idle', 'status_done' : 'Done', 'status_found' : 'Found', 'status_files' : 'files', 'status_copying' : 'Copying files...', 'status_rotating' : 'Rotating files...' } def __getitem__(self, name): if name != None: try: retval = self.d[name] except: retval = 'i18n ERROR (%s)' % name return retval
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys import config import ui import sys # # read a configuration file and set values to config-module # def readconfig( file, mod ): try: f = open( file ) for line in f.readlines(): line = line.strip() if len(line) < 1: continue # skip blank lines if line[0] == '#': continue # comment lines try: name, val = line.split('=', 1) setattr( mod, name.strip(), eval( val.strip() ) ) except ValueError: ui.ERR( "Unknown line in config-file (%s)" % line ) f.close() # any error in processing config datafile is silently ignored # (defaults are used instead) except IOError: pass # # called at program startup to initialize the configuration # def init(): mod = sys.modules['config'] readconfig( 'config.txt', mod ) readconfig( 'config.local', mod ) # executables if not hasattr( mod, 'jpegtran' ): if sys.platform == 'win32': setattr(mod, 'jpegtran', "jpegtran.exe") else: setattr(mod, 'jpegtran', "jpegtran" ) if not hasattr( mod, 'exiftool' ): if sys.platform == 'win32': setattr(mod, 'exiftool', "exiftool.exe" ) else: setattr(mod, 'exiftool', "exiftool" ) # these cannot be set in the configuration file setattr(mod, 'TITLE', 'FlickFleck') setattr(mod, 'VERSION', '1.0 rc1') # if program was started with a parameter, use that as fromdir if len(sys.argv) > 1: setattr(mod, 'fromdir', sys.argv[1]) # try to sanitize the filepath values import os.path setattr(mod, 'fromdir', os.path.normpath( config.fromdir ) ) setattr(mod, 'todir' , os.path.normpath( config.todir ) )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import os, os.path import sys import shutil import ui # ------------------------------------------------------------------------ # in win32 add quotes around path (there can be spaces in names) # XXX: spaces in filepaths should be worked out int UNIX too def quotepath( path ): if sys.platform == 'win32': return '"' + path + '"' else: return path # ------------------------------------------------------------------------ # stops if we cannot access the named file def verify_access( file ): if not os.access( file, os.F_OK ): ui.ERR( "fileops.access: %s: access denied" % file ) # ------------------------------------------------------------------------ # tries to do a safe copy from 'orig_file' to 'new_file' # def copy( orig_file, new_file ): f_from = os.path.normpath( orig_file ) f_to = os.path.normpath( new_file ) # if copying to itself if f_from == f_to: ui.ERR( "fileops.copy: copying a file to itself? (%s)" % f_from ) # we should be able to access fromfile verify_access( f_from ) # target should not exists (caller should make sure of this) if os.path.exists( f_to ): ui.ERR( "fileops.copy: target file exists (%s)" % f_to ) try: shutil.copy2( f_from, f_to ) # preserves attributes except: ui.ERR("fileops.copy: copy2 operation failed (%s)" % f_from) # do some sanity checks to the file we just created verify_access( f_to ) if os.path.getsize( f_to ) < 1: ui.ERR("fileops.copy: target filesize zero (%s)" % f_to ) # # debug/testing # if __name__ == '__main__': import sys import tempfile sys.path.insert("..") filename1 = tempfile.mktemp (".txt") open (filename1, "w").close () filename2 = filename1 + ".copy" print filename1, "=>", filename2 copy( filename1, filename2 )
Python
# # Default configuration for FlickFleck # fromdir = 'tests' todir = '/tmp' # create target subdirs (year/month) targetdirs = True # languages are defined in moduledir: i18n # every language module must also be listed in setup.py LANGUAGE = "english" # what files to process: jpegglob = [ "*.jpg", "*.jpeg" ] # SVN version SVNversion=" $Id: config.py 65 2008-11-27 09:43:11Z jyke.t.jokinen $ " # installdir will be overwritten at startup (flickfleck install location) installdir = "" # bindir can contain external tools (if not in path) bindir = "tools"
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import Tkinter import ui # adhoc widget to make a progressbar # class Widget: def __init__(self, parent): self.w_parent = parent self.w_canvas = Tkinter.Canvas( parent ) self.w_canvas.pack( fill='x', expand='yes') # called when the number of items in the whole operation is known def init(self, num_items): self.max = num_items self.clear() # called if starting again with the same max value def clear(self): self.count = 0 self.w_canvas.delete(Tkinter.ALL) # draw one step forward in the progressbar (previously set max value used) def step(self): self.count = self.count + 1 width = int( self.w_canvas['width'] ) # if one_item_width < 1.0 it would go to zero with ints: one_item = float(width) / float(self.max) draw_width = one_item * self.count self.w_canvas.delete(Tkinter.ALL) self.w_canvas.create_rectangle(0,0, draw_width,ui.wins.PBheight, fill='blue') self.w_parent.update()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import tkMessageBox import sys import wins import mainwin import i18n #----------------------------------------------------------------- # show error message and close the application # def ERR( str ): tkMessageBox.showerror(i18n.name['apperror'], str + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- # all done. this version closes application after this # def Ready(): tkMessageBox.showinfo(config.TITLE, i18n.name['finished'] + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- def status( str ): wins.main.status( str ) #----------------------------------------------------------------- # called at program startup # creates all windows # def init(): wins.root = Pmw.initialise( fontScheme = 'pmw1' ) wins.root.withdraw() wins.root.title( config.TITLE ) if sys.platform == 'win32': wins.root.iconbitmap('flickfleck.ico') else: pass # no X11 bitmap defined right now wins.main = mainwin.FlickFleck(wins.root) wins.root.deiconify() #----------------------------------------------------------------- def start(): wins.root.mainloop() #----------------------------------------------------------------- # engine calls this in file operations loops to check if user # wants to cancel # def checkStop(): wins.root.update() if wins.requestStop: ERR("Stopped by the User")
Python
import PmwColor Color = PmwColor del PmwColor import PmwBlt Blt = PmwBlt del PmwBlt ### Loader functions: _VERSION = '1.3' def setversion(version): if version != _VERSION: raise ValueError, 'Dynamic versioning not available' def setalphaversions(*alpha_versions): if alpha_versions != (): raise ValueError, 'Dynamic versioning not available' def version(alpha = 0): if alpha: return () else: return _VERSION def installedversions(alpha = 0): if alpha: return () else: return (_VERSION,) ###################################################################### ### File: PmwBase.py # Pmw megawidget base classes. # This module provides a foundation for building megawidgets. It # contains the MegaArchetype class which manages component widgets and # configuration options. Also provided are the MegaToplevel and # MegaWidget classes, derived from the MegaArchetype class. The # MegaToplevel class contains a Tkinter Toplevel widget to act as the # container of the megawidget. This is used as the base class of all # megawidgets that are contained in their own top level window, such # as a Dialog window. The MegaWidget class contains a Tkinter Frame # to act as the container of the megawidget. This is used as the base # class of all other megawidgets, such as a ComboBox or ButtonBox. # # Megawidgets are built by creating a class that inherits from either # the MegaToplevel or MegaWidget class. import os import string import sys import traceback import types import Tkinter # Special values used in index() methods of several megawidgets. END = ['end'] SELECT = ['select'] DEFAULT = ['default'] # Constant used to indicate that an option can only be set by a call # to the constructor. INITOPT = ['initopt'] _DEFAULT_OPTION_VALUE = ['default_option_value'] _useTkOptionDb = 0 # Symbolic constants for the indexes into an optionInfo list. _OPT_DEFAULT = 0 _OPT_VALUE = 1 _OPT_FUNCTION = 2 # Stacks _busyStack = [] # Stack which tracks nested calls to show/hidebusycursor (called # either directly or from activate()/deactivate()). Each element # is a dictionary containing: # 'newBusyWindows' : List of windows which had busy_hold called # on them during a call to showbusycursor(). # The corresponding call to hidebusycursor() # will call busy_release on these windows. # 'busyFocus' : The blt _Busy window which showbusycursor() # set the focus to. # 'previousFocus' : The focus as it was when showbusycursor() # was called. The corresponding call to # hidebusycursor() will restore this focus if # the focus has not been changed from busyFocus. _grabStack = [] # Stack of grabbed windows. It tracks calls to push/popgrab() # (called either directly or from activate()/deactivate()). The # window on the top of the stack is the window currently with the # grab. Each element is a dictionary containing: # 'grabWindow' : The window grabbed by pushgrab(). The # corresponding call to popgrab() will release # the grab on this window and restore the grab # on the next window in the stack (if there is one). # 'globalMode' : True if the grabWindow was grabbed with a # global grab, false if the grab was local # and 'nograb' if no grab was performed. # 'previousFocus' : The focus as it was when pushgrab() # was called. The corresponding call to # popgrab() will restore this focus. # 'deactivateFunction' : # The function to call (usually grabWindow.deactivate) if # popgrab() is called (usually from a deactivate() method) # on a window which is not at the top of the stack (that is, # does not have the grab or focus). For example, if a modal # dialog is deleted by the window manager or deactivated by # a timer. In this case, all dialogs above and including # this one are deactivated, starting at the top of the # stack. # Note that when dealing with focus windows, the name of the Tk # widget is used, since it may be the '_Busy' window, which has no # python instance associated with it. #============================================================================= # Functions used to forward methods from a class to a component. # Fill in a flattened method resolution dictionary for a class (attributes are # filtered out). Flattening honours the MI method resolution rules # (depth-first search of bases in order). The dictionary has method names # for keys and functions for values. def __methodDict(cls, dict): # the strategy is to traverse the class in the _reverse_ of the normal # order, and overwrite any duplicates. baseList = list(cls.__bases__) baseList.reverse() # do bases in reverse order, so first base overrides last base for super in baseList: __methodDict(super, dict) # do my methods last to override base classes for key, value in cls.__dict__.items(): # ignore class attributes if type(value) == types.FunctionType: dict[key] = value def __methods(cls): # Return all method names for a class. # Return all method names for a class (attributes are filtered # out). Base classes are searched recursively. dict = {} __methodDict(cls, dict) return dict.keys() # Function body to resolve a forwarding given the target method name and the # attribute name. The resulting lambda requires only self, but will forward # any other parameters. __stringBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(attribute)s.%(method)s, args, kw)') # Get a unique id __counter = 0 def __unique(): global __counter __counter = __counter + 1 return str(__counter) # Function body to resolve a forwarding given the target method name and the # index of the resolution function. The resulting lambda requires only self, # but will forward any other parameters. The target instance is identified # by invoking the resolution function. __funcBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(forwardFunc)s().%(method)s, args, kw)') def forwardmethods(fromClass, toClass, toPart, exclude = ()): # Forward all methods from one class to another. # Forwarders will be created in fromClass to forward method # invocations to toClass. The methods to be forwarded are # identified by flattening the interface of toClass, and excluding # methods identified in the exclude list. Methods already defined # in fromClass, or special methods with one or more leading or # trailing underscores will not be forwarded. # For a given object of class fromClass, the corresponding toClass # object is identified using toPart. This can either be a String # denoting an attribute of fromClass objects, or a function taking # a fromClass object and returning a toClass object. # Example: # class MyClass: # ... # def __init__(self): # ... # self.__target = TargetClass() # ... # def findtarget(self): # return self.__target # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) # # ...or... # forwardmethods(MyClass, TargetClass, MyClass.findtarget, # ['dangerous1', 'dangerous2']) # In both cases, all TargetClass methods will be forwarded from # MyClass except for dangerous1, dangerous2, special methods like # __str__, and pre-existing methods like findtarget. # Allow an attribute name (String) or a function to determine the instance if type(toPart) != types.StringType: # check that it is something like a function if callable(toPart): # If a method is passed, use the function within it if hasattr(toPart, 'im_func'): toPart = toPart.im_func # After this is set up, forwarders in this class will use # the forwarding function. The forwarding function name is # guaranteed to be unique, so that it can't be hidden by subclasses forwardName = '__fwdfunc__' + __unique() fromClass.__dict__[forwardName] = toPart # It's not a valid type else: raise TypeError, 'toPart must be attribute name, function or method' # get the full set of candidate methods dict = {} __methodDict(toClass, dict) # discard special methods for ex in dict.keys(): if ex[:1] == '_' or ex[-1:] == '_': del dict[ex] # discard dangerous methods supplied by the caller for ex in exclude: if dict.has_key(ex): del dict[ex] # discard methods already defined in fromClass for ex in __methods(fromClass): if dict.has_key(ex): del dict[ex] for method, func in dict.items(): d = {'method': method, 'func': func} if type(toPart) == types.StringType: execString = \ __stringBody % {'method' : method, 'attribute' : toPart} else: execString = \ __funcBody % {'forwardFunc' : forwardName, 'method' : method} exec execString in d # this creates a method fromClass.__dict__[method] = d[method] #============================================================================= def setgeometryanddeiconify(window, geom): # To avoid flashes on X and to position the window correctly on NT # (caused by Tk bugs). if os.name == 'nt' or \ (os.name == 'posix' and sys.platform[:6] == 'cygwin'): # Require overrideredirect trick to stop window frame # appearing momentarily. redirect = window.overrideredirect() if not redirect: window.overrideredirect(1) window.deiconify() if geom is not None: window.geometry(geom) # Call update_idletasks to ensure NT moves the window to the # correct position it is raised. window.update_idletasks() window.tkraise() if not redirect: window.overrideredirect(0) else: if geom is not None: window.geometry(geom) # Problem!? Which way around should the following two calls # go? If deiconify() is called first then I get complaints # from people using the enlightenment or sawfish window # managers that when a dialog is activated it takes about 2 # seconds for the contents of the window to appear. But if # tkraise() is called first then I get complaints from people # using the twm window manager that when a dialog is activated # it appears in the top right corner of the screen and also # takes about 2 seconds to appear. #window.tkraise() # Call update_idletasks to ensure certain window managers (eg: # enlightenment and sawfish) do not cause Tk to delay for # about two seconds before displaying window. #window.update_idletasks() #window.deiconify() window.deiconify() if window.overrideredirect(): # The window is not under the control of the window manager # and so we need to raise it ourselves. window.tkraise() #============================================================================= class MegaArchetype: # Megawidget abstract root class. # This class provides methods which are inherited by classes # implementing useful bases (this class doesn't provide a # container widget inside which the megawidget can be built). def __init__(self, parent = None, hullClass = None): # Mapping from each megawidget option to a list of information # about the option # - default value # - current value # - function to call when the option is initialised in the # call to initialiseoptions() in the constructor or # modified via configure(). If this is INITOPT, the # option is an initialisation option (an option that can # be set by the call to the constructor but can not be # used with configure). # This mapping is not initialised here, but in the call to # defineoptions() which precedes construction of this base class. # # self._optionInfo = {} # Mapping from each component name to a tuple of information # about the component. # - component widget instance # - configure function of widget instance # - the class of the widget (Frame, EntryField, etc) # - cget function of widget instance # - the name of the component group of this component, if any self.__componentInfo = {} # Mapping from alias names to the names of components or # sub-components. self.__componentAliases = {} # Contains information about the keywords provided to the # constructor. It is a mapping from the keyword to a tuple # containing: # - value of keyword # - a boolean indicating if the keyword has been used. # A keyword is used if, during the construction of a megawidget, # - it is defined in a call to defineoptions() or addoptions(), or # - it references, by name, a component of the megawidget, or # - it references, by group, at least one component # At the end of megawidget construction, a call is made to # initialiseoptions() which reports an error if there are # unused options given to the constructor. # # After megawidget construction, the dictionary contains # keywords which refer to a dynamic component group, so that # these components can be created after megawidget # construction and still use the group options given to the # constructor. # # self._constructorKeywords = {} # List of dynamic component groups. If a group is included in # this list, then it not an error if a keyword argument for # the group is given to the constructor or to configure(), but # no components with this group have been created. # self._dynamicGroups = () if hullClass is None: self._hull = None else: if parent is None: parent = Tkinter._default_root # Create the hull. self._hull = self.createcomponent('hull', (), None, hullClass, (parent,)) _hullToMegaWidget[self._hull] = self if _useTkOptionDb: # Now that a widget has been created, query the Tk # option database to get the default values for the # options which have not been set in the call to the # constructor. This assumes that defineoptions() is # called before the __init__(). option_get = self.option_get _VALUE = _OPT_VALUE _DEFAULT = _OPT_DEFAULT for name, info in self._optionInfo.items(): value = info[_VALUE] if value is _DEFAULT_OPTION_VALUE: resourceClass = string.upper(name[0]) + name[1:] value = option_get(name, resourceClass) if value != '': try: # Convert the string to int/float/tuple, etc value = eval(value, {'__builtins__': {}}) except: pass info[_VALUE] = value else: info[_VALUE] = info[_DEFAULT] def destroy(self): # Clean up optionInfo in case it contains circular references # in the function field, such as self._settitle in class # MegaToplevel. self._optionInfo = {} if self._hull is not None: del _hullToMegaWidget[self._hull] self._hull.destroy() #====================================================================== # Methods used (mainly) during the construction of the megawidget. def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): # Create options, providing the default value and the method # to call when the value is changed. If any option created by # base classes has the same name as one in <optionDefs>, the # base class's value and function will be overriden. # This should be called before the constructor of the base # class, so that default values defined in the derived class # override those in the base class. if not hasattr(self, '_constructorKeywords'): # First time defineoptions has been called. tmp = {} for option, value in keywords.items(): tmp[option] = [value, 0] self._constructorKeywords = tmp self._optionInfo = {} self._initialiseoptions_counter = 0 self._initialiseoptions_counter = self._initialiseoptions_counter + 1 if not hasattr(self, '_dynamicGroups'): self._dynamicGroups = () self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups) self.addoptions(optionDefs) def addoptions(self, optionDefs): # Add additional options, providing the default value and the # method to call when the value is changed. See # "defineoptions" for more details # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key keywords = self._constructorKeywords keywords_has_key = keywords.has_key FUNCTION = _OPT_FUNCTION for name, default, function in optionDefs: if '_' not in name: # The option will already exist if it has been defined # in a derived class. In this case, do not override the # default value of the option or the callback function # if it is not None. if not optionInfo_has_key(name): if keywords_has_key(name): value = keywords[name][0] optionInfo[name] = [default, value, function] del keywords[name] else: if _useTkOptionDb: optionInfo[name] = \ [default, _DEFAULT_OPTION_VALUE, function] else: optionInfo[name] = [default, default, function] elif optionInfo[name][FUNCTION] is None: optionInfo[name][FUNCTION] = function else: # This option is of the form "component_option". If this is # not already defined in self._constructorKeywords add it. # This allows a derived class to override the default value # of an option of a component of a base class. if not keywords_has_key(name): keywords[name] = [default, 0] def createcomponent(self, componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw): # Create a component (during construction or later). if self.__componentInfo.has_key(componentName): raise ValueError, 'Component "%s" already exists' % componentName if '_' in componentName: raise ValueError, \ 'Component name "%s" must not contain "_"' % componentName if hasattr(self, '_constructorKeywords'): keywords = self._constructorKeywords else: keywords = {} for alias, component in componentAliases: # Create aliases to the component and its sub-components. index = string.find(component, '_') if index < 0: self.__componentAliases[alias] = (component, None) else: mainComponent = component[:index] subComponent = component[(index + 1):] self.__componentAliases[alias] = (mainComponent, subComponent) # Remove aliases from the constructor keyword arguments by # replacing any keyword arguments that begin with *alias* # with corresponding keys beginning with *component*. alias = alias + '_' aliasLen = len(alias) for option in keywords.keys(): if len(option) > aliasLen and option[:aliasLen] == alias: newkey = component + '_' + option[aliasLen:] keywords[newkey] = keywords[option] del keywords[option] componentPrefix = componentName + '_' nameLen = len(componentPrefix) for option in keywords.keys(): if len(option) > nameLen and option[:nameLen] == componentPrefix: # The keyword argument refers to this component, so add # this to the options to use when constructing the widget. kw[option[nameLen:]] = keywords[option][0] del keywords[option] else: # Check if this keyword argument refers to the group # of this component. If so, add this to the options # to use when constructing the widget. Mark the # keyword argument as being used, but do not remove it # since it may be required when creating another # component. index = string.find(option, '_') if index >= 0 and componentGroup == option[:index]: rest = option[(index + 1):] kw[rest] = keywords[option][0] keywords[option][1] = 1 if kw.has_key('pyclass'): widgetClass = kw['pyclass'] del kw['pyclass'] if widgetClass is None: return None if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. widgetArgs = widgetArgs[0] widget = apply(widgetClass, widgetArgs, kw) componentClass = widget.__class__.__name__ self.__componentInfo[componentName] = (widget, widget.configure, componentClass, widget.cget, componentGroup) return widget def destroycomponent(self, name): # Remove a megawidget component. # This command is for use by megawidget designers to destroy a # megawidget component. self.__componentInfo[name][0].destroy() del self.__componentInfo[name] def createlabel(self, parent, childCols = 1, childRows = 1): labelpos = self['labelpos'] labelmargin = self['labelmargin'] if labelpos is None: return label = self.createcomponent('label', (), None, Tkinter.Label, (parent,)) if labelpos[0] in 'ns': # vertical layout if labelpos[0] == 'n': row = 0 margin = 1 else: row = childRows + 3 margin = row - 1 label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos) parent.grid_rowconfigure(margin, minsize=labelmargin) else: # horizontal layout if labelpos[0] == 'w': col = 0 margin = 1 else: col = childCols + 3 margin = col - 1 label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos) parent.grid_columnconfigure(margin, minsize=labelmargin) def initialiseoptions(self, dummy = None): self._initialiseoptions_counter = self._initialiseoptions_counter - 1 if self._initialiseoptions_counter == 0: unusedOptions = [] keywords = self._constructorKeywords for name in keywords.keys(): used = keywords[name][1] if not used: # This keyword argument has not been used. If it # does not refer to a dynamic group, mark it as # unused. index = string.find(name, '_') if index < 0 or name[:index] not in self._dynamicGroups: unusedOptions.append(name) if len(unusedOptions) > 0: if len(unusedOptions) == 1: text = 'Unknown option "' else: text = 'Unknown options "' raise KeyError, text + string.join(unusedOptions, ', ') + \ '" for ' + self.__class__.__name__ # Call the configuration callback function for every option. FUNCTION = _OPT_FUNCTION for info in self._optionInfo.values(): func = info[FUNCTION] if func is not None and func is not INITOPT: func() #====================================================================== # Method used to configure the megawidget. def configure(self, option=None, **kw): # Query or configure the megawidget options. # # If not empty, *kw* is a dictionary giving new # values for some of the options of this megawidget or its # components. For options defined for this megawidget, set # the value of the option to the new value and call the # configuration callback function, if any. For options of the # form <component>_<option>, where <component> is a component # of this megawidget, call the configure method of the # component giving it the new value of the option. The # <component> part may be an alias or a component group name. # # If *option* is None, return all megawidget configuration # options and settings. Options are returned as standard 5 # element tuples # # If *option* is a string, return the 5 element tuple for the # given configuration option. # First, deal with the option queries. if len(kw) == 0: # This configure call is querying the values of one or all options. # Return 5-tuples: # (optionName, resourceName, resourceClass, default, value) if option is None: rtn = {} for option, config in self._optionInfo.items(): resourceClass = string.upper(option[0]) + option[1:] rtn[option] = (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) return rtn else: config = self._optionInfo[option] resourceClass = string.upper(option[0]) + option[1:] return (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key componentInfo = self.__componentInfo componentInfo_has_key = componentInfo.has_key componentAliases = self.__componentAliases componentAliases_has_key = componentAliases.has_key VALUE = _OPT_VALUE FUNCTION = _OPT_FUNCTION # This will contain a list of options in *kw* which # are known to this megawidget. directOptions = [] # This will contain information about the options in # *kw* of the form <component>_<option>, where # <component> is a component of this megawidget. It is a # dictionary whose keys are the configure method of each # component and whose values are a dictionary of options and # values for the component. indirectOptions = {} indirectOptions_has_key = indirectOptions.has_key for option, value in kw.items(): if optionInfo_has_key(option): # This is one of the options of this megawidget. # Make sure it is not an initialisation option. if optionInfo[option][FUNCTION] is INITOPT: raise KeyError, \ 'Cannot configure initialisation option "' \ + option + '" for ' + self.__class__.__name__ optionInfo[option][VALUE] = value directOptions.append(option) else: index = string.find(option, '_') if index >= 0: # This option may be of the form <component>_<option>. component = option[:index] componentOption = option[(index + 1):] # Expand component alias if componentAliases_has_key(component): component, subComponent = componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' \ + componentOption # Expand option string to write on error option = component + '_' + componentOption if componentInfo_has_key(component): # Configure the named component componentConfigFuncs = [componentInfo[component][1]] else: # Check if this is a group name and configure all # components in the group. componentConfigFuncs = [] for info in componentInfo.values(): if info[4] == component: componentConfigFuncs.append(info[1]) if len(componentConfigFuncs) == 0 and \ component not in self._dynamicGroups: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Add the configure method(s) (may be more than # one if this is configuring a component group) # and option/value to dictionary. for componentConfigFunc in componentConfigFuncs: if not indirectOptions_has_key(componentConfigFunc): indirectOptions[componentConfigFunc] = {} indirectOptions[componentConfigFunc][componentOption] \ = value else: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Call the configure methods for any components. map(apply, indirectOptions.keys(), ((),) * len(indirectOptions), indirectOptions.values()) # Call the configuration callback function for each option. for option in directOptions: info = optionInfo[option] func = info[_OPT_FUNCTION] if func is not None: func() def __setitem__(self, key, value): apply(self.configure, (), {key: value}) #====================================================================== # Methods used to query the megawidget. def component(self, name): # Return a component widget of the megawidget given the # component's name # This allows the user of a megawidget to access and configure # widget components directly. # Find the main component and any subcomponents index = string.find(name, '_') if index < 0: component = name remainingComponents = None else: component = name[:index] remainingComponents = name[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: if remainingComponents is None: remainingComponents = subComponent else: remainingComponents = subComponent + '_' \ + remainingComponents widget = self.__componentInfo[component][0] if remainingComponents is None: return widget else: return widget.component(remainingComponents) def interior(self): return self._hull def hulldestroyed(self): return not _hullToMegaWidget.has_key(self._hull) def __str__(self): return str(self._hull) def cget(self, option): # Get current configuration setting. # Return the value of an option, for example myWidget['font']. if self._optionInfo.has_key(option): return self._optionInfo[option][_OPT_VALUE] else: index = string.find(option, '_') if index >= 0: component = option[:index] componentOption = option[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' + componentOption # Expand option string to write on error option = component + '_' + componentOption if self.__componentInfo.has_key(component): # Call cget on the component. componentCget = self.__componentInfo[component][3] return componentCget(componentOption) else: # If this is a group name, call cget for one of # the components in the group. for info in self.__componentInfo.values(): if info[4] == component: componentCget = info[3] return componentCget(componentOption) raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ __getitem__ = cget def isinitoption(self, option): return self._optionInfo[option][_OPT_FUNCTION] is INITOPT def options(self): options = [] if hasattr(self, '_optionInfo'): for option, info in self._optionInfo.items(): isinit = info[_OPT_FUNCTION] is INITOPT default = info[_OPT_DEFAULT] options.append((option, default, isinit)) options.sort() return options def components(self): # Return a list of all components. # This list includes the 'hull' component and all widget subcomponents names = self.__componentInfo.keys() names.sort() return names def componentaliases(self): # Return a list of all component aliases. componentAliases = self.__componentAliases names = componentAliases.keys() names.sort() rtn = [] for alias in names: (mainComponent, subComponent) = componentAliases[alias] if subComponent is None: rtn.append((alias, mainComponent)) else: rtn.append((alias, mainComponent + '_' + subComponent)) return rtn def componentgroup(self, name): return self.__componentInfo[name][4] #============================================================================= # The grab functions are mainly called by the activate() and # deactivate() methods. # # Use pushgrab() to add a new window to the grab stack. This # releases the grab by the window currently on top of the stack (if # there is one) and gives the grab and focus to the new widget. # # To remove the grab from the window on top of the grab stack, call # popgrab(). # # Use releasegrabs() to release the grab and clear the grab stack. def pushgrab(grabWindow, globalMode, deactivateFunction): prevFocus = grabWindow.tk.call('focus') grabInfo = { 'grabWindow' : grabWindow, 'globalMode' : globalMode, 'previousFocus' : prevFocus, 'deactivateFunction' : deactivateFunction, } _grabStack.append(grabInfo) _grabtop() grabWindow.focus_set() def popgrab(window): # Return the grab to the next window in the grab stack, if any. # If this window is not at the top of the grab stack, then it has # just been deleted by the window manager or deactivated by a # timer. Call the deactivate method for the modal dialog above # this one on the stack. if _grabStack[-1]['grabWindow'] != window: for index in range(len(_grabStack)): if _grabStack[index]['grabWindow'] == window: _grabStack[index + 1]['deactivateFunction']() break grabInfo = _grabStack[-1] del _grabStack[-1] topWidget = grabInfo['grabWindow'] prevFocus = grabInfo['previousFocus'] globalMode = grabInfo['globalMode'] if globalMode != 'nograb': topWidget.grab_release() if len(_grabStack) > 0: _grabtop() if prevFocus != '': try: topWidget.tk.call('focus', prevFocus) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to root window. Tkinter._default_root.focus_set() else: # Make sure that focus does not remain on the released widget. if len(_grabStack) > 0: topWidget = _grabStack[-1]['grabWindow'] topWidget.focus_set() else: Tkinter._default_root.focus_set() def grabstacktopwindow(): if len(_grabStack) == 0: return None else: return _grabStack[-1]['grabWindow'] def releasegrabs(): # Release grab and clear the grab stack. current = Tkinter._default_root.grab_current() if current is not None: current.grab_release() _grabStack[:] = [] def _grabtop(): grabInfo = _grabStack[-1] topWidget = grabInfo['grabWindow'] globalMode = grabInfo['globalMode'] if globalMode == 'nograb': return while 1: try: if globalMode: topWidget.grab_set_global() else: topWidget.grab_set() break except Tkinter.TclError: # Another application has grab. Keep trying until # grab can succeed. topWidget.after(100) #============================================================================= class MegaToplevel(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('activatecommand', None, None), ('deactivatecommand', None, None), ('master', None, None), ('title', None, self._settitle), ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Toplevel) # Initialise instance. # Set WM_DELETE_WINDOW protocol, deleting any old callback, so # memory does not leak. if hasattr(self._hull, '_Pmw_WM_DELETE_name'): self._hull.tk.deletecommand(self._hull._Pmw_WM_DELETE_name) self._hull._Pmw_WM_DELETE_name = \ self.register(self._userDeleteWindow, needcleanup = 0) self.protocol('WM_DELETE_WINDOW', self._hull._Pmw_WM_DELETE_name) # Initialise instance variables. self._firstShowing = 1 # Used by show() to ensure window retains previous position on screen. # The IntVar() variable to wait on during a modal dialog. self._wait = None self._active = 0 self._userDeleteFunc = self.destroy self._userModalDeleteFunc = self.deactivate # Check keywords and initialise options. self.initialiseoptions() def _settitle(self): title = self['title'] if title is not None: self.title(title) def userdeletefunc(self, func=None): if func: self._userDeleteFunc = func else: return self._userDeleteFunc def usermodaldeletefunc(self, func=None): if func: self._userModalDeleteFunc = func else: return self._userModalDeleteFunc def _userDeleteWindow(self): if self.active(): self._userModalDeleteFunc() else: self._userDeleteFunc() def destroy(self): # Allow this to be called more than once. if _hullToMegaWidget.has_key(self._hull): self.deactivate() # Remove circular references, so that object can get cleaned up. del self._userDeleteFunc del self._userModalDeleteFunc MegaArchetype.destroy(self) def show(self, master = None): if self.state() != 'normal': if self._firstShowing: # Just let the window manager determine the window # position for the first time. geom = None else: # Position the window at the same place it was last time. geom = self._sameposition() setgeometryanddeiconify(self, geom) if self._firstShowing: self._firstShowing = 0 else: if self.transient() == '': self.tkraise() # Do this last, otherwise get flashing on NT: if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) self.focus() def _centreonscreen(self): # Centre the window on the screen. (Actually halfway across # and one third down.) parent = self.winfo_parent() if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) # Find size of window. self.update_idletasks() width = self.winfo_width() height = self.winfo_height() if width == 1 and height == 1: # If the window has not yet been displayed, its size is # reported as 1x1, so use requested size. width = self.winfo_reqwidth() height = self.winfo_reqheight() # Place in centre of screen: x = (self.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx() y = (self.winfo_screenheight() - height) / 3 - parent.winfo_vrooty() if x < 0: x = 0 if y < 0: y = 0 return '+%d+%d' % (x, y) def _sameposition(self): # Position the window at the same place it was last time. geometry = self.geometry() index = string.find(geometry, '+') if index >= 0: return geometry[index:] else: return None def activate(self, globalMode = 0, geometry = 'centerscreenfirst'): if self._active: raise ValueError, 'Window is already active' if self.state() == 'normal': self.withdraw() self._active = 1 showbusycursor() if self._wait is None: self._wait = Tkinter.IntVar() self._wait.set(0) if geometry == 'centerscreenalways': geom = self._centreonscreen() elif geometry == 'centerscreenfirst': if self._firstShowing: # Centre the window the first time it is displayed. geom = self._centreonscreen() else: # Position the window at the same place it was last time. geom = self._sameposition() elif geometry[:5] == 'first': if self._firstShowing: geom = geometry[5:] else: # Position the window at the same place it was last time. geom = self._sameposition() else: geom = geometry self._firstShowing = 0 setgeometryanddeiconify(self, geom) # Do this last, otherwise get flashing on NT: master = self['master'] if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) pushgrab(self._hull, globalMode, self.deactivate) command = self['activatecommand'] if callable(command): command() self.wait_variable(self._wait) return self._result def deactivate(self, result=None): if not self._active: return self._active = 0 # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._hull) command = self['deactivatecommand'] if callable(command): command() self.withdraw() hidebusycursor(forceFocusRestore = 1) self._result = result self._wait.set(1) def active(self): return self._active forwardmethods(MegaToplevel, Tkinter.Toplevel, '_hull') #============================================================================= class MegaWidget(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Frame) # Check keywords and initialise options. self.initialiseoptions() forwardmethods(MegaWidget, Tkinter.Frame, '_hull') #============================================================================= # Public functions #----------------- _traceTk = 0 def tracetk(root = None, on = 1, withStackTrace = 0, file=None): global _withStackTrace global _traceTkFile global _traceTk if root is None: root = Tkinter._default_root _withStackTrace = withStackTrace _traceTk = on if on: if hasattr(root.tk, '__class__'): # Tracing already on return if file is None: _traceTkFile = sys.stderr else: _traceTkFile = file tk = _TraceTk(root.tk) else: if not hasattr(root.tk, '__class__'): # Tracing already off return tk = root.tk.getTclInterp() _setTkInterps(root, tk) def showbusycursor(): _addRootToToplevelBusyInfo() root = Tkinter._default_root busyInfo = { 'newBusyWindows' : [], 'previousFocus' : None, 'busyFocus' : None, } _busyStack.append(busyInfo) if _disableKeyboardWhileBusy: # Remember the focus as it is now, before it is changed. busyInfo['previousFocus'] = root.tk.call('focus') if not _havebltbusy(root): # No busy command, so don't call busy hold on any windows. return for (window, winInfo) in _toplevelBusyInfo.items(): if (window.state() != 'withdrawn' and not winInfo['isBusy'] and not winInfo['excludeFromBusy']): busyInfo['newBusyWindows'].append(window) winInfo['isBusy'] = 1 _busy_hold(window, winInfo['busyCursorName']) # Make sure that no events for the busy window get # through to Tkinter, otherwise it will crash in # _nametowidget with a 'KeyError: _Busy' if there is # a binding on the toplevel window. window.tk.call('bindtags', winInfo['busyWindow'], 'Pmw_Dummy_Tag') if _disableKeyboardWhileBusy: # Remember previous focus widget for this toplevel window # and set focus to the busy window, which will ignore all # keyboard events. winInfo['windowFocus'] = \ window.tk.call('focus', '-lastfor', window._w) window.tk.call('focus', winInfo['busyWindow']) busyInfo['busyFocus'] = winInfo['busyWindow'] if len(busyInfo['newBusyWindows']) > 0: if os.name == 'nt': # NT needs an "update" before it will change the cursor. window.update() else: window.update_idletasks() def hidebusycursor(forceFocusRestore = 0): # Remember the focus as it is now, before it is changed. root = Tkinter._default_root if _disableKeyboardWhileBusy: currentFocus = root.tk.call('focus') # Pop the busy info off the stack. busyInfo = _busyStack[-1] del _busyStack[-1] for window in busyInfo['newBusyWindows']: # If this window has not been deleted, release the busy cursor. if _toplevelBusyInfo.has_key(window): winInfo = _toplevelBusyInfo[window] winInfo['isBusy'] = 0 _busy_release(window) if _disableKeyboardWhileBusy: # Restore previous focus window for this toplevel window, # but only if is still set to the busy window (it may have # been changed). windowFocusNow = window.tk.call('focus', '-lastfor', window._w) if windowFocusNow == winInfo['busyWindow']: try: window.tk.call('focus', winInfo['windowFocus']) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to toplevel window instead (can't leave focus on # busy window). window.focus_set() if _disableKeyboardWhileBusy: # Restore the focus, depending on whether the focus had changed # between the calls to showbusycursor and hidebusycursor. if forceFocusRestore or busyInfo['busyFocus'] == currentFocus: # The focus had not changed, so restore it to as it was before # the call to showbusycursor, previousFocus = busyInfo['previousFocus'] if previousFocus is not None: try: root.tk.call('focus', previousFocus) except Tkinter.TclError: # Previous focus widget has been deleted; forget it. pass else: # The focus had changed, so restore it to what it had been # changed to before the call to hidebusycursor. root.tk.call('focus', currentFocus) def clearbusycursor(): while len(_busyStack) > 0: hidebusycursor() def setbusycursorattributes(window, **kw): _addRootToToplevelBusyInfo() for name, value in kw.items(): if name == 'exclude': _toplevelBusyInfo[window]['excludeFromBusy'] = value elif name == 'cursorName': _toplevelBusyInfo[window]['busyCursorName'] = value else: raise KeyError, 'Unknown busycursor attribute "' + name + '"' def _addRootToToplevelBusyInfo(): # Include the Tk root window in the list of toplevels. This must # not be called before Tkinter has had a chance to be initialised by # the application. root = Tkinter._default_root if root == None: root = Tkinter.Tk() if not _toplevelBusyInfo.has_key(root): _addToplevelBusyInfo(root) def busycallback(command, updateFunction = None): if not callable(command): raise ValueError, \ 'cannot register non-command busy callback %s %s' % \ (repr(command), type(command)) wrapper = _BusyWrapper(command, updateFunction) return wrapper.callback _errorReportFile = None _errorWindow = None def reporterrorstofile(file = None): global _errorReportFile _errorReportFile = file def displayerror(text): global _errorWindow if _errorReportFile is not None: _errorReportFile.write(text + '\n') else: # Print error on standard error as well as to error window. # Useful if error window fails to be displayed, for example # when exception is triggered in a <Destroy> binding for root # window. sys.stderr.write(text + '\n') if _errorWindow is None: # The error window has not yet been created. _errorWindow = _ErrorWindow() _errorWindow.showerror(text) _root = None _disableKeyboardWhileBusy = 1 def initialise( root = None, size = None, fontScheme = None, useTkOptionDb = 0, noBltBusy = 0, disableKeyboardWhileBusy = None, ): # Remember if show/hidebusycursor should ignore keyboard events. global _disableKeyboardWhileBusy if disableKeyboardWhileBusy is not None: _disableKeyboardWhileBusy = disableKeyboardWhileBusy # Do not use blt busy command if noBltBusy is set. Otherwise, # use blt busy if it is available. global _haveBltBusy if noBltBusy: _haveBltBusy = 0 # Save flag specifying whether the Tk option database should be # queried when setting megawidget option default values. global _useTkOptionDb _useTkOptionDb = useTkOptionDb # If we haven't been given a root window, use the default or # create one. if root is None: if Tkinter._default_root is None: root = Tkinter.Tk() else: root = Tkinter._default_root # If this call is initialising a different Tk interpreter than the # last call, then re-initialise all global variables. Assume the # last interpreter has been destroyed - ie: Pmw does not (yet) # support multiple simultaneous interpreters. global _root if _root is not None and _root != root: global _busyStack global _errorWindow global _grabStack global _hullToMegaWidget global _toplevelBusyInfo _busyStack = [] _errorWindow = None _grabStack = [] _hullToMegaWidget = {} _toplevelBusyInfo = {} _root = root # Trap Tkinter Toplevel constructors so that a list of Toplevels # can be maintained. Tkinter.Toplevel.title = __TkinterToplevelTitle # Trap Tkinter widget destruction so that megawidgets can be # destroyed when their hull widget is destoyed and the list of # Toplevels can be pruned. Tkinter.Toplevel.destroy = __TkinterToplevelDestroy Tkinter.Widget.destroy = __TkinterWidgetDestroy # Modify Tkinter's CallWrapper class to improve the display of # errors which occur in callbacks. Tkinter.CallWrapper = __TkinterCallWrapper # Make sure we get to know when the window manager deletes the # root window. Only do this if the protocol has not yet been set. # This is required if there is a modal dialog displayed and the # window manager deletes the root window. Otherwise the # application will not exit, even though there are no windows. if root.protocol('WM_DELETE_WINDOW') == '': root.protocol('WM_DELETE_WINDOW', root.destroy) # Set the base font size for the application and set the # Tk option database font resources. _font_initialise(root, size, fontScheme) return root def alignlabels(widgets, sticky = None): if len(widgets) == 0: return widgets[0].update_idletasks() # Determine the size of the maximum length label string. maxLabelWidth = 0 for iwid in widgets: labelWidth = iwid.grid_bbox(0, 1)[2] if labelWidth > maxLabelWidth: maxLabelWidth = labelWidth # Adjust the margins for the labels such that the child sites and # labels line up. for iwid in widgets: if sticky is not None: iwid.component('label').grid(sticky=sticky) iwid.grid_columnconfigure(0, minsize = maxLabelWidth) #============================================================================= # Private routines #----------------- _callToTkReturned = 1 _recursionCounter = 1 class _TraceTk: def __init__(self, tclInterp): self.tclInterp = tclInterp def getTclInterp(self): return self.tclInterp # Calling from python into Tk. def call(self, *args, **kw): global _callToTkReturned global _recursionCounter _callToTkReturned = 0 if len(args) == 1 and type(args[0]) == types.TupleType: argStr = str(args[0]) else: argStr = str(args) _traceTkFile.write('CALL TK> %d:%s%s' % (_recursionCounter, ' ' * _recursionCounter, argStr)) _recursionCounter = _recursionCounter + 1 try: result = apply(self.tclInterp.call, args, kw) except Tkinter.TclError, errorString: _callToTkReturned = 1 _recursionCounter = _recursionCounter - 1 _traceTkFile.write('\nTK ERROR> %d:%s-> %s\n' % (_recursionCounter, ' ' * _recursionCounter, repr(errorString))) if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() raise Tkinter.TclError, errorString _recursionCounter = _recursionCounter - 1 if _callToTkReturned: _traceTkFile.write('CALL RTN> %d:%s-> %s' % (_recursionCounter, ' ' * _recursionCounter, repr(result))) else: _callToTkReturned = 1 if result: _traceTkFile.write(' -> %s' % repr(result)) _traceTkFile.write('\n') if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() _traceTkFile.flush() return result def __getattr__(self, key): return getattr(self.tclInterp, key) def _setTkInterps(window, tk): window.tk = tk for child in window.children.values(): _setTkInterps(child, tk) #============================================================================= # Functions to display a busy cursor. Keep a list of all toplevels # and display the busy cursor over them. The list will contain the Tk # root toplevel window as well as all other toplevel windows. # Also keep a list of the widget which last had focus for each # toplevel. # Map from toplevel windows to # {'isBusy', 'windowFocus', 'busyWindow', # 'excludeFromBusy', 'busyCursorName'} _toplevelBusyInfo = {} # Pmw needs to know all toplevel windows, so that it can call blt busy # on them. This is a hack so we get notified when a Tk topevel is # created. Ideally, the __init__ 'method' should be overridden, but # it is a 'read-only special attribute'. Luckily, title() is always # called from the Tkinter Toplevel constructor. def _addToplevelBusyInfo(window): if window._w == '.': busyWindow = '._Busy' else: busyWindow = window._w + '._Busy' _toplevelBusyInfo[window] = { 'isBusy' : 0, 'windowFocus' : None, 'busyWindow' : busyWindow, 'excludeFromBusy' : 0, 'busyCursorName' : None, } def __TkinterToplevelTitle(self, *args): # If this is being called from the constructor, include this # Toplevel in the list of toplevels and set the initial # WM_DELETE_WINDOW protocol to destroy() so that we get to know # about it. if not _toplevelBusyInfo.has_key(self): _addToplevelBusyInfo(self) self._Pmw_WM_DELETE_name = self.register(self.destroy, None, 0) self.protocol('WM_DELETE_WINDOW', self._Pmw_WM_DELETE_name) return apply(Tkinter.Wm.title, (self,) + args) _haveBltBusy = None def _havebltbusy(window): global _busy_hold, _busy_release, _haveBltBusy if _haveBltBusy is None: import PmwBlt _haveBltBusy = PmwBlt.havebltbusy(window) _busy_hold = PmwBlt.busy_hold if os.name == 'nt': # There is a bug in Blt 2.4i on NT where the busy window # does not follow changes in the children of a window. # Using forget works around the problem. _busy_release = PmwBlt.busy_forget else: _busy_release = PmwBlt.busy_release return _haveBltBusy class _BusyWrapper: def __init__(self, command, updateFunction): self._command = command self._updateFunction = updateFunction def callback(self, *args): showbusycursor() rtn = apply(self._command, args) # Call update before hiding the busy windows to clear any # events that may have occurred over the busy windows. if callable(self._updateFunction): self._updateFunction() hidebusycursor() return rtn #============================================================================= def drawarrow(canvas, color, direction, tag, baseOffset = 0.25, edgeOffset = 0.15): canvas.delete(tag) bw = (string.atoi(canvas['borderwidth']) + string.atoi(canvas['highlightthickness'])) width = string.atoi(canvas['width']) height = string.atoi(canvas['height']) if direction in ('up', 'down'): majorDimension = height minorDimension = width else: majorDimension = width minorDimension = height offset = round(baseOffset * majorDimension) if direction in ('down', 'right'): base = bw + offset apex = bw + majorDimension - offset else: base = bw + majorDimension - offset apex = bw + offset if minorDimension > 3 and minorDimension % 2 == 0: minorDimension = minorDimension - 1 half = int(minorDimension * (1 - 2 * edgeOffset)) / 2 low = round(bw + edgeOffset * minorDimension) middle = low + half high = low + 2 * half if direction in ('up', 'down'): coords = (low, base, high, base, middle, apex) else: coords = (base, low, base, high, apex, middle) kw = {'fill' : color, 'outline' : color, 'tag' : tag} apply(canvas.create_polygon, coords, kw) #============================================================================= # Modify the Tkinter destroy methods so that it notifies us when a Tk # toplevel or frame is destroyed. # A map from the 'hull' component of a megawidget to the megawidget. # This is used to clean up a megawidget when its hull is destroyed. _hullToMegaWidget = {} def __TkinterToplevelDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: # Delete the busy info structure for this toplevel (if the # window was created before initialise() was called, it # will not have any. if _toplevelBusyInfo.has_key(tkWidget): del _toplevelBusyInfo[tkWidget] if hasattr(tkWidget, '_Pmw_WM_DELETE_name'): tkWidget.tk.deletecommand(tkWidget._Pmw_WM_DELETE_name) del tkWidget._Pmw_WM_DELETE_name Tkinter.BaseWidget.destroy(tkWidget) def __TkinterWidgetDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: Tkinter.BaseWidget.destroy(tkWidget) #============================================================================= # Add code to Tkinter to improve the display of errors which occur in # callbacks. class __TkinterCallWrapper: def __init__(self, func, subst, widget): self.func = func self.subst = subst self.widget = widget # Calling back from Tk into python. def __call__(self, *args): try: if self.subst: args = apply(self.subst, args) if _traceTk: if not _callToTkReturned: _traceTkFile.write('\n') if hasattr(self.func, 'im_class'): name = self.func.im_class.__name__ + '.' + \ self.func.__name__ else: name = self.func.__name__ if len(args) == 1 and hasattr(args[0], 'type'): # The argument to the callback is an event. eventName = _eventTypeToName[string.atoi(args[0].type)] if eventName in ('KeyPress', 'KeyRelease',): argStr = '(%s %s Event: %s)' % \ (eventName, args[0].keysym, args[0].widget) else: argStr = '(%s Event, %s)' % (eventName, args[0].widget) else: argStr = str(args) _traceTkFile.write('CALLBACK> %d:%s%s%s\n' % (_recursionCounter, ' ' * _recursionCounter, name, argStr)) _traceTkFile.flush() return apply(self.func, args) except SystemExit, msg: raise SystemExit, msg except: _reporterror(self.func, args) _eventTypeToName = { 2 : 'KeyPress', 15 : 'VisibilityNotify', 28 : 'PropertyNotify', 3 : 'KeyRelease', 16 : 'CreateNotify', 29 : 'SelectionClear', 4 : 'ButtonPress', 17 : 'DestroyNotify', 30 : 'SelectionRequest', 5 : 'ButtonRelease', 18 : 'UnmapNotify', 31 : 'SelectionNotify', 6 : 'MotionNotify', 19 : 'MapNotify', 32 : 'ColormapNotify', 7 : 'EnterNotify', 20 : 'MapRequest', 33 : 'ClientMessage', 8 : 'LeaveNotify', 21 : 'ReparentNotify', 34 : 'MappingNotify', 9 : 'FocusIn', 22 : 'ConfigureNotify', 35 : 'VirtualEvents', 10 : 'FocusOut', 23 : 'ConfigureRequest', 36 : 'ActivateNotify', 11 : 'KeymapNotify', 24 : 'GravityNotify', 37 : 'DeactivateNotify', 12 : 'Expose', 25 : 'ResizeRequest', 38 : 'MouseWheelEvent', 13 : 'GraphicsExpose', 26 : 'CirculateNotify', 14 : 'NoExpose', 27 : 'CirculateRequest', } def _reporterror(func, args): # Fetch current exception values. exc_type, exc_value, exc_traceback = sys.exc_info() # Give basic information about the callback exception. if type(exc_type) == types.ClassType: # Handle python 1.5 class exceptions. exc_type = exc_type.__name__ msg = str(exc_type) + ' Exception in Tk callback\n' msg = msg + ' Function: %s (type: %s)\n' % (repr(func), type(func)) msg = msg + ' Args: %s\n' % str(args) if type(args) == types.TupleType and len(args) > 0 and \ hasattr(args[0], 'type'): eventArg = 1 else: eventArg = 0 # If the argument to the callback is an event, add the event type. if eventArg: eventNum = string.atoi(args[0].type) if eventNum in _eventTypeToName.keys(): msg = msg + ' Event type: %s (type num: %d)\n' % \ (_eventTypeToName[eventNum], eventNum) else: msg = msg + ' Unknown event type (type num: %d)\n' % eventNum # Add the traceback. msg = msg + 'Traceback (innermost last):\n' for tr in traceback.extract_tb(exc_traceback): msg = msg + ' File "%s", line %s, in %s\n' % (tr[0], tr[1], tr[2]) msg = msg + ' %s\n' % tr[3] msg = msg + '%s: %s\n' % (exc_type, exc_value) # If the argument to the callback is an event, add the event contents. if eventArg: msg = msg + '\n================================================\n' msg = msg + ' Event contents:\n' keys = args[0].__dict__.keys() keys.sort() for key in keys: msg = msg + ' %s: %s\n' % (key, args[0].__dict__[key]) clearbusycursor() try: displayerror(msg) except: pass class _ErrorWindow: def __init__(self): self._errorQueue = [] self._errorCount = 0 self._open = 0 self._firstShowing = 1 # Create the toplevel window self._top = Tkinter.Toplevel() self._top.protocol('WM_DELETE_WINDOW', self._hide) self._top.title('Error in background function') self._top.iconname('Background error') # Create the text widget and scrollbar in a frame upperframe = Tkinter.Frame(self._top) scrollbar = Tkinter.Scrollbar(upperframe, orient='vertical') scrollbar.pack(side = 'right', fill = 'y') self._text = Tkinter.Text(upperframe, yscrollcommand=scrollbar.set) self._text.pack(fill = 'both', expand = 1) scrollbar.configure(command=self._text.yview) # Create the buttons and label in a frame lowerframe = Tkinter.Frame(self._top) ignore = Tkinter.Button(lowerframe, text = 'Ignore remaining errors', command = self._hide) ignore.pack(side='left') self._nextError = Tkinter.Button(lowerframe, text = 'Show next error', command = self._next) self._nextError.pack(side='left') self._label = Tkinter.Label(lowerframe, relief='ridge') self._label.pack(side='left', fill='x', expand=1) # Pack the lower frame first so that it does not disappear # when the window is resized. lowerframe.pack(side = 'bottom', fill = 'x') upperframe.pack(side = 'bottom', fill = 'both', expand = 1) def showerror(self, text): if self._open: self._errorQueue.append(text) else: self._display(text) self._open = 1 # Display the error window in the same place it was before. if self._top.state() == 'normal': # If update_idletasks is not called here, the window may # be placed partially off the screen. Also, if it is not # called and many errors are generated quickly in # succession, the error window may not display errors # until the last one is generated and the interpreter # becomes idle. # XXX: remove this, since it causes omppython to go into an # infinite loop if an error occurs in an omp callback. # self._top.update_idletasks() pass else: if self._firstShowing: geom = None else: geometry = self._top.geometry() index = string.find(geometry, '+') if index >= 0: geom = geometry[index:] else: geom = None setgeometryanddeiconify(self._top, geom) if self._firstShowing: self._firstShowing = 0 else: self._top.tkraise() self._top.focus() self._updateButtons() # Release any grab, so that buttons in the error window work. releasegrabs() def _hide(self): self._errorCount = self._errorCount + len(self._errorQueue) self._errorQueue = [] self._top.withdraw() self._open = 0 def _next(self): # Display the next error in the queue. text = self._errorQueue[0] del self._errorQueue[0] self._display(text) self._updateButtons() def _display(self, text): self._errorCount = self._errorCount + 1 text = 'Error: %d\n%s' % (self._errorCount, text) self._text.delete('1.0', 'end') self._text.insert('end', text) def _updateButtons(self): numQueued = len(self._errorQueue) if numQueued > 0: self._label.configure(text='%d more errors' % numQueued) self._nextError.configure(state='normal') else: self._label.configure(text='No more errors') self._nextError.configure(state='disabled') ###################################################################### ### File: PmwDialog.py # Based on iwidgets2.2.0/dialog.itk and iwidgets2.2.0/dialogshell.itk code. # Convention: # Each dialog window should have one of these as the rightmost button: # Close Close a window which only displays information. # Cancel Close a window which may be used to change the state of # the application. import sys import types import Tkinter # A Toplevel with a ButtonBox and child site. class Dialog(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttonbox_hull_borderwidth', 1, None), ('buttonbox_hull_relief', 'raised', None), ('buttonboxpos', 's', INITOPT), ('buttons', ('OK',), self._buttons), ('command', None, None), ('dialogchildsite_borderwidth', 1, None), ('dialogchildsite_relief', 'raised', None), ('defaultbutton', None, self._defaultButton), ('master', 'parent', None), ('separatorwidth', 0, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) # Create the components. oldInterior = MegaToplevel.interior(self) # Set up pack options according to the position of the button box. pos = self['buttonboxpos'] if pos not in 'nsew': raise ValueError, \ 'bad buttonboxpos option "%s": should be n, s, e, or w' \ % pos if pos in 'ns': orient = 'horizontal' fill = 'x' if pos == 'n': side = 'top' else: side = 'bottom' else: orient = 'vertical' fill = 'y' if pos == 'w': side = 'left' else: side = 'right' # Create the button box. self._buttonBox = self.createcomponent('buttonbox', (), None, ButtonBox, (oldInterior,), orient = orient) self._buttonBox.pack(side = side, fill = fill) # Create the separating line. width = self['separatorwidth'] if width > 0: self._separator = self.createcomponent('separator', (), None, Tkinter.Frame, (oldInterior,), relief = 'sunken', height = width, width = width, borderwidth = width / 2) self._separator.pack(side = side, fill = fill) # Create the child site. self.__dialogChildSite = self.createcomponent('dialogchildsite', (), None, Tkinter.Frame, (oldInterior,)) self.__dialogChildSite.pack(side=side, fill='both', expand=1) self.oldButtons = () self.oldDefault = None self.bind('<Return>', self._invokeDefault) self.userdeletefunc(self._doCommand) self.usermodaldeletefunc(self._doCommand) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self.__dialogChildSite def invoke(self, index = DEFAULT): return self._buttonBox.invoke(index) def _invokeDefault(self, event): try: self._buttonBox.index(DEFAULT) except ValueError: return self._buttonBox.invoke() def _doCommand(self, name = None): if name is not None and self.active() and \ grabstacktopwindow() != self.component('hull'): # This is a modal dialog but is not on the top of the grab # stack (ie: should not have the grab), so ignore this # event. This seems to be a bug in Tk and may occur in # nested modal dialogs. # # An example is the PromptDialog demonstration. To # trigger the problem, start the demo, then move the mouse # to the main window, hit <TAB> and then <TAB> again. The # highlight border of the "Show prompt dialog" button # should now be displayed. Now hit <SPACE>, <RETURN>, # <RETURN> rapidly several times. Eventually, hitting the # return key invokes the password dialog "OK" button even # though the confirm dialog is active (and therefore # should have the keyboard focus). Observed under Solaris # 2.5.1, python 1.5.2 and Tk8.0. # TODO: Give focus to the window on top of the grabstack. return command = self['command'] if callable(command): return command(name) else: if self.active(): self.deactivate(name) else: self.withdraw() def _buttons(self): buttons = self['buttons'] if type(buttons) != types.TupleType and type(buttons) != types.ListType: raise ValueError, \ 'bad buttons option "%s": should be a tuple' % str(buttons) if self.oldButtons == buttons: return self.oldButtons = buttons for index in range(self._buttonBox.numbuttons()): self._buttonBox.delete(0) for name in buttons: self._buttonBox.add(name, command=lambda self=self, name=name: self._doCommand(name)) if len(buttons) > 0: defaultbutton = self['defaultbutton'] if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) self._buttonBox.alignbuttons() def _defaultButton(self): defaultbutton = self['defaultbutton'] if self.oldDefault == defaultbutton: return self.oldDefault = defaultbutton if len(self['buttons']) > 0: if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) ###################################################################### ### File: PmwTimeFuncs.py # Functions for dealing with dates and times. import re import string def timestringtoseconds(text, separator = ':'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text sign = 1 if len(inputList[0]) > 0 and inputList[0][0] in ('+', '-'): if inputList[0][0] == '-': sign = -1 inputList[0] = inputList[0][1:] if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text hour = string.atoi(inputList[0]) minute = string.atoi(inputList[1]) second = string.atoi(inputList[2]) if minute >= 60 or second >= 60: raise ValueError, 'invalid value: ' + text return sign * (hour * 60 * 60 + minute * 60 + second) _year_pivot = 50 _century = 2000 def setyearpivot(pivot, century = None): global _year_pivot global _century oldvalues = (_year_pivot, _century) _year_pivot = pivot if century is not None: _century = century return oldvalues def datestringtojdn(text, format = 'ymd', separator = '/'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text formatList = list(format) day = string.atoi(inputList[formatList.index('d')]) month = string.atoi(inputList[formatList.index('m')]) year = string.atoi(inputList[formatList.index('y')]) if _year_pivot is not None: if year >= 0 and year < 100: if year <= _year_pivot: year = year + _century else: year = year + _century - 100 jdn = ymdtojdn(year, month, day) if jdntoymd(jdn) != (year, month, day): raise ValueError, 'invalid value: ' + text return jdn def _cdiv(a, b): # Return a / b as calculated by most C language implementations, # assuming both a and b are integers. if a * b > 0: return a / b else: return -(abs(a) / abs(b)) def ymdtojdn(year, month, day, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianDate = 15821004L # last day to use Julian calendar else: # British-American usage lastJulianDate = 17520902L # last day to use Julian calendar julian = ((year * 100L) + month) * 100 + day <= lastJulianDate if year < 0: # Adjust BC year year = year + 1 if julian: return 367L * year - _cdiv(7 * (year + 5001L + _cdiv((month - 9), 7)), 4) + \ _cdiv(275 * month, 9) + day + 1729777L else: return (day - 32076L) + \ _cdiv(1461L * (year + 4800L + _cdiv((month - 14), 12)), 4) + \ _cdiv(367 * (month - 2 - _cdiv((month - 14), 12) * 12), 12) - \ _cdiv((3 * _cdiv((year + 4900L + _cdiv((month - 14), 12)), 100)), 4) + \ 1 # correction by rdg def jdntoymd(jdn, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianJdn = 2299160L # last jdn to use Julian calendar else: # British-American usage lastJulianJdn = 2361221L # last jdn to use Julian calendar julian = (jdn <= lastJulianJdn); x = jdn + 68569L if julian: x = x + 38 daysPer400Years = 146100L fudgedDaysPer4000Years = 1461000L + 1 else: daysPer400Years = 146097L fudgedDaysPer4000Years = 1460970L + 31 z = _cdiv(4 * x, daysPer400Years) x = x - _cdiv((daysPer400Years * z + 3), 4) y = _cdiv(4000 * (x + 1), fudgedDaysPer4000Years) x = x - _cdiv(1461 * y, 4) + 31 m = _cdiv(80 * x, 2447) d = x - _cdiv(2447 * m, 80) x = _cdiv(m, 11) m = m + 2 - 12 * x y = 100 * (z - 49) + y + x # Convert from longs to integers. yy = int(y) mm = int(m) dd = int(d) if yy <= 0: # Adjust BC years. yy = yy - 1 return (yy, mm, dd) def stringtoreal(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: raise ValueError, 'invalid value: ' + text index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] return string.atof(text) ###################################################################### ### File: PmwBalloon.py import os import string import Tkinter class Balloon(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('initwait', 500, None), # milliseconds ('label_background', 'lightyellow', None), ('label_foreground', 'black', None), ('label_justify', 'left', None), ('master', 'parent', None), ('relmouse', 'none', self._relmouse), ('state', 'both', self._state), ('statuscommand', None, None), ('xoffset', 20, None), # pixels ('yoffset', 1, None), # pixels ('hull_highlightthickness', 1, None), ('hull_highlightbackground', 'black', None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) self.withdraw() self.overrideredirect(1) # Create the components. interior = self.interior() self._label = self.createcomponent('label', (), None, Tkinter.Label, (interior,)) self._label.pack() # The default hull configuration options give a black border # around the balloon, but avoids a black 'flash' when the # balloon is deiconified, before the text appears. if not kw.has_key('hull_background'): self.configure(hull_background = \ str(self._label.cget('background'))) # Initialise instance variables. self._timer = None # The widget or item that is currently triggering the balloon. # It is None if the balloon is not being displayed. It is a # one-tuple if the balloon is being displayed in response to a # widget binding (value is the widget). It is a two-tuple if # the balloon is being displayed in response to a canvas or # text item binding (value is the widget and the item). self._currentTrigger = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timer is not None: self.after_cancel(self._timer) self._timer = None MegaToplevel.destroy(self) def bind(self, widget, balloonHelp, statusHelp = None): # If a previous bind for this widget exists, remove it. self.unbind(widget) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.bind('<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 0)) # Set Motion binding so that if the pointer remains at rest # within the widget until the status line removes the help and # then the pointer moves again, then redisplay the help in the # status line. # Note: The Motion binding only works for basic widgets, and # the hull of megawidgets but not for other megawidget components. motionId = widget.bind('<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.bind('<Leave>', self._leave) buttonId = widget.bind('<ButtonPress>', self._buttonpress) # Set Destroy binding so that the balloon can be withdrawn and # the timer can be cancelled if the widget is destroyed. destroyId = widget.bind('<Destroy>', self._destroy) # Use the None item in the widget's private Pmw dictionary to # store the widget's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[None] = \ (enterId, motionId, leaveId, buttonId, destroyId) def unbind(self, widget): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(None): (enterId, motionId, leaveId, buttonId, destroyId) = \ widget._Pmw_BalloonBindIds[None] # Need to pass in old bindings, so that Tkinter can # delete the commands. Otherwise, memory is leaked. widget.unbind('<Enter>', enterId) widget.unbind('<Motion>', motionId) widget.unbind('<Leave>', leaveId) widget.unbind('<ButtonPress>', buttonId) widget.unbind('<Destroy>', destroyId) del widget._Pmw_BalloonBindIds[None] if self._currentTrigger is not None and len(self._currentTrigger) == 1: # The balloon is currently being displayed and the current # trigger is a widget. triggerWidget = self._currentTrigger[0] if triggerWidget == widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def tagbind(self, widget, tagOrItem, balloonHelp, statusHelp = None): # If a previous bind for this widget's tagOrItem exists, remove it. self.tagunbind(widget, tagOrItem) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.tag_bind(tagOrItem, '<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 1)) motionId = widget.tag_bind(tagOrItem, '<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.tag_bind(tagOrItem, '<Leave>', self._leave) buttonId = widget.tag_bind(tagOrItem, '<ButtonPress>', self._buttonpress) # Use the tagOrItem item in the widget's private Pmw dictionary to # store the tagOrItem's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[tagOrItem] = \ (enterId, motionId, leaveId, buttonId) def tagunbind(self, widget, tagOrItem): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(tagOrItem): (enterId, motionId, leaveId, buttonId) = \ widget._Pmw_BalloonBindIds[tagOrItem] widget.tag_unbind(tagOrItem, '<Enter>', enterId) widget.tag_unbind(tagOrItem, '<Motion>', motionId) widget.tag_unbind(tagOrItem, '<Leave>', leaveId) widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId) del widget._Pmw_BalloonBindIds[tagOrItem] if self._currentTrigger is None: # The balloon is not currently being displayed. return if len(self._currentTrigger) == 1: # The current trigger is a widget. return if len(self._currentTrigger) == 2: # The current trigger is a canvas item. (triggerWidget, triggerItem) = self._currentTrigger if triggerWidget == widget and triggerItem == tagOrItem: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None else: # The current trigger is a text item. (triggerWidget, x, y) = self._currentTrigger if triggerWidget == widget: currentPos = widget.index('@%d,%d' % (x, y)) currentTags = widget.tag_names(currentPos) if tagOrItem in currentTags: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def showstatus(self, statusHelp): if self['state'] in ('status', 'both'): cmd = self['statuscommand'] if callable(cmd): cmd(statusHelp) def clearstatus(self): self.showstatus(None) def _state(self): if self['state'] not in ('both', 'balloon', 'status', 'none'): raise ValueError, 'bad state option ' + repr(self['state']) + \ ': should be one of \'both\', \'balloon\', ' + \ '\'status\' or \'none\'' def _relmouse(self): if self['relmouse'] not in ('both', 'x', 'y', 'none'): raise ValueError, 'bad relmouse option ' + repr(self['relmouse'])+ \ ': should be one of \'both\', \'x\', ' + '\'y\' or \'none\'' def _enter(self, event, widget, statusHelp, balloonHelp, isItem): # Do not display balloon if mouse button is pressed. This # will only occur if the button was pressed inside a widget, # then the mouse moved out of and then back into the widget, # with the button still held down. The number 0x1f00 is the # button mask for the 5 possible buttons in X. buttonPressed = (event.state & 0x1f00) != 0 if not buttonPressed and balloonHelp is not None and \ self['state'] in ('balloon', 'both'): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self._timer = self.after(self['initwait'], lambda self = self, widget = widget, help = balloonHelp, isItem = isItem: self._showBalloon(widget, help, isItem)) if isItem: if hasattr(widget, 'canvasx'): # The widget is a canvas. item = widget.find_withtag('current') if len(item) > 0: item = item[0] else: item = None self._currentTrigger = (widget, item) else: # The widget is a text widget. self._currentTrigger = (widget, event.x, event.y) else: self._currentTrigger = (widget,) self.showstatus(statusHelp) def _leave(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _destroy(self, event): # Only withdraw the balloon and cancel the timer if the widget # being destroyed is the widget that triggered the balloon. # Note that in a Tkinter Destroy event, the widget field is a # string and not a widget as usual. if self._currentTrigger is None: # The balloon is not currently being displayed return if len(self._currentTrigger) == 1: # The current trigger is a widget (not an item) triggerWidget = self._currentTrigger[0] if str(triggerWidget) == event.widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _buttonpress(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self._currentTrigger = None def _showBalloon(self, widget, balloonHelp, isItem): self._label.configure(text = balloonHelp) # First, display the balloon offscreen to get dimensions. screenWidth = self.winfo_screenwidth() screenHeight = self.winfo_screenheight() self.geometry('+%d+0' % (screenWidth + 1)) self.update_idletasks() if isItem: # Get the bounding box of the current item. bbox = widget.bbox('current') if bbox is None: # The item that triggered the balloon has disappeared, # perhaps by a user's timer event that occured between # the <Enter> event and the 'initwait' timer calling # this method. return # The widget is either a text or canvas. The meaning of # the values returned by the bbox method is different for # each, so use the existence of the 'canvasx' method to # distinguish between them. if hasattr(widget, 'canvasx'): # The widget is a canvas. Place balloon under canvas # item. The positions returned by bbox are relative # to the entire canvas, not just the visible part, so # need to convert to window coordinates. leftrel = bbox[0] - widget.canvasx(0) toprel = bbox[1] - widget.canvasy(0) bottomrel = bbox[3] - widget.canvasy(0) else: # The widget is a text widget. Place balloon under # the character closest to the mouse. The positions # returned by bbox are relative to the text widget # window (ie the visible part of the text only). leftrel = bbox[0] toprel = bbox[1] bottomrel = bbox[1] + bbox[3] else: leftrel = 0 toprel = 0 bottomrel = widget.winfo_height() xpointer, ypointer = widget.winfo_pointerxy() # -1 if off screen if xpointer >= 0 and self['relmouse'] in ('both', 'x'): x = xpointer else: x = leftrel + widget.winfo_rootx() x = x + self['xoffset'] if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = bottomrel + widget.winfo_rooty() y = y + self['yoffset'] edges = (string.atoi(str(self.cget('hull_highlightthickness'))) + string.atoi(str(self.cget('hull_borderwidth')))) * 2 if x + self._label.winfo_reqwidth() + edges > screenWidth: x = screenWidth - self._label.winfo_reqwidth() - edges if y + self._label.winfo_reqheight() + edges > screenHeight: if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = toprel + widget.winfo_rooty() y = y - self._label.winfo_reqheight() - self['yoffset'] - edges setgeometryanddeiconify(self, '+%d+%d' % (x, y)) ###################################################################### ### File: PmwButtonBox.py # Based on iwidgets2.2.0/buttonbox.itk code. import types import Tkinter class ButtonBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 3, INITOPT), ('pady', 3, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._buttonBoxFrame = self._hull columnOrRow = 0 else: self._buttonBoxFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._buttonBoxFrame.grid(column=2, row=2, sticky='nsew') columnOrRow = 2 self.createlabel(interior) orient = self['orient'] if orient == 'horizontal': interior.grid_columnconfigure(columnOrRow, weight = 1) elif orient == 'vertical': interior.grid_rowconfigure(columnOrRow, weight = 1) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' # Initialise instance variables. # List of tuples describing the buttons: # - name # - button widget self._buttonList = [] # The index of the default button. self._defaultButton = None self._timerId = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timerId: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def numbuttons(self): return len(self._buttonList) def index(self, index, forInsert = 0): listLength = len(self._buttonList) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'ButtonBox has no buttons' elif index is DEFAULT: if self._defaultButton is not None: return self._defaultButton raise ValueError, 'ButtonBox has no default' else: names = map(lambda t: t[0], self._buttonList) if index in names: return names.index(index) validValues = 'a name, a number, END or DEFAULT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def insert(self, componentName, beforeComponent = 0, **kw): if componentName in self.components(): raise ValueError, 'button "%s" already exists' % componentName if not kw.has_key('text'): kw['text'] = componentName kw['default'] = 'normal' button = apply(self.createcomponent, (componentName, (), 'Button', Tkinter.Button, (self._buttonBoxFrame,)), kw) index = self.index(beforeComponent, 1) horizontal = self['orient'] == 'horizontal' numButtons = len(self._buttonList) # Shift buttons up one position. for i in range(numButtons - 1, index - 1, -1): widget = self._buttonList[i][1] pos = i * 2 + 3 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) # Display the new button. if horizontal: button.grid(column = index * 2 + 1, row = 0, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_columnconfigure( numButtons * 2 + 2, weight = 1) else: button.grid(column = 0, row = index * 2 + 1, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_rowconfigure( numButtons * 2 + 2, weight = 1) self._buttonList.insert(index, (componentName, button)) return button def add(self, componentName, **kw): return apply(self.insert, (componentName, len(self._buttonList)), kw) def delete(self, index): index = self.index(index) (name, widget) = self._buttonList[index] widget.grid_forget() self.destroycomponent(name) numButtons = len(self._buttonList) # Shift buttons down one position. horizontal = self['orient'] == 'horizontal' for i in range(index + 1, numButtons): widget = self._buttonList[i][1] pos = i * 2 - 1 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) if horizontal: self._buttonBoxFrame.grid_columnconfigure(numButtons * 2 - 1, minsize = 0) self._buttonBoxFrame.grid_columnconfigure(numButtons * 2, weight = 0) else: self._buttonBoxFrame.grid_rowconfigure(numButtons * 2, weight = 0) del self._buttonList[index] def setdefault(self, index): # Turn off the default ring around the current default button. if self._defaultButton is not None: button = self._buttonList[self._defaultButton][1] button.configure(default = 'normal') self._defaultButton = None # Turn on the default ring around the new default button. if index is not None: index = self.index(index) self._defaultButton = index button = self._buttonList[index][1] button.configure(default = 'active') def invoke(self, index = DEFAULT, noFlash = 0): # Invoke the callback associated with the *index* button. If # *noFlash* is not set, flash the button to indicate to the # user that something happened. button = self._buttonList[self.index(index)][1] if not noFlash: state = button.cget('state') relief = button.cget('relief') button.configure(state = 'active', relief = 'sunken') self.update_idletasks() self.after(100) button.configure(state = state, relief = relief) return button.invoke() def button(self, buttonIndex): return self._buttonList[self.index(buttonIndex)][1] def alignbuttons(self, when = 'later'): if when == 'later': if not self._timerId: self._timerId = self.after_idle(self.alignbuttons, 'now') return self.update_idletasks() self._timerId = None # Determine the width of the maximum length button. max = 0 horizontal = (self['orient'] == 'horizontal') for index in range(len(self._buttonList)): gridIndex = index * 2 + 1 if horizontal: width = self._buttonBoxFrame.grid_bbox(gridIndex, 0)[2] else: width = self._buttonBoxFrame.grid_bbox(0, gridIndex)[2] if width > max: max = width # Set the width of all the buttons to be the same. if horizontal: for index in range(len(self._buttonList)): self._buttonBoxFrame.grid_columnconfigure(index * 2 + 1, minsize = max) else: self._buttonBoxFrame.grid_columnconfigure(0, minsize = max) ###################################################################### ### File: PmwEntryField.py # Based on iwidgets2.2.0/entryfield.itk code. import re import string import types import Tkinter # Possible return values of validation functions. OK = 1 ERROR = 0 PARTIAL = -1 class EntryField(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('errorbackground', 'pink', None), ('invalidcommand', self.bell, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('modifiedcommand', None, None), ('sticky', 'ew', INITOPT), ('validate', None, self._validate), ('extravalidators', {}, None), ('value', '', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) self._entryFieldEntry.grid(column=2, row=2, sticky=self['sticky']) if self['value'] != '': self.__setEntry(self['value']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self.normalBackground = None self._previousText = None # Initialise instance. _registerEntryField(self._entryFieldEntry, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. if EntryField._classBindingsDefinedFor != Tkinter._default_root: tagList = self._entryFieldEntry.bindtags() root = Tkinter._default_root allSequences = {} for tag in tagList: sequences = root.bind_class(tag) if type(sequences) is types.StringType: # In old versions of Tkinter, bind_class returns a string sequences = root.tk.splitlist(sequences) for sequence in sequences: allSequences[sequence] = None for sequence in allSequences.keys(): root.bind_class('EntryFieldPre', sequence, _preProcess) root.bind_class('EntryFieldPost', sequence, _postProcess) EntryField._classBindingsDefinedFor = root self._entryFieldEntry.bindtags(('EntryFieldPre',) + self._entryFieldEntry.bindtags() + ('EntryFieldPost',)) self._entryFieldEntry.bind('<Return>', self._executeCommand) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): _deregisterEntryField(self._entryFieldEntry) MegaWidget.destroy(self) def _getValidatorFunc(self, validator, index): # Search the extra and standard validator lists for the # given 'validator'. If 'validator' is an alias, then # continue the search using the alias. Make sure that # self-referencial aliases do not cause infinite loops. extraValidators = self['extravalidators'] traversedValidators = [] while 1: traversedValidators.append(validator) if extraValidators.has_key(validator): validator = extraValidators[validator][index] elif _standardValidators.has_key(validator): validator = _standardValidators[validator][index] else: return validator if validator in traversedValidators: return validator def _validate(self): dict = { 'validator' : None, 'min' : None, 'max' : None, 'minstrict' : 1, 'maxstrict' : 1, } opt = self['validate'] if type(opt) is types.DictionaryType: dict.update(opt) else: dict['validator'] = opt # Look up validator maps and replace 'validator' field with # the corresponding function. validator = dict['validator'] valFunction = self._getValidatorFunc(validator, 0) self._checkValidateFunction(valFunction, 'validate', validator) dict['validator'] = valFunction # Look up validator maps and replace 'stringtovalue' field # with the corresponding function. if dict.has_key('stringtovalue'): stringtovalue = dict['stringtovalue'] strFunction = self._getValidatorFunc(stringtovalue, 1) self._checkValidateFunction( strFunction, 'stringtovalue', stringtovalue) else: strFunction = self._getValidatorFunc(validator, 1) if strFunction == validator: strFunction = len dict['stringtovalue'] = strFunction self._validationInfo = dict args = dict.copy() del args['validator'] del args['min'] del args['max'] del args['minstrict'] del args['maxstrict'] del args['stringtovalue'] self._validationArgs = args self._previousText = None if type(dict['min']) == types.StringType and strFunction is not None: dict['min'] = apply(strFunction, (dict['min'],), args) if type(dict['max']) == types.StringType and strFunction is not None: dict['max'] = apply(strFunction, (dict['max'],), args) self._checkValidity() def _checkValidateFunction(self, function, option, validator): # Raise an error if 'function' is not a function or None. if function is not None and not callable(function): extraValidators = self['extravalidators'] extra = extraValidators.keys() extra.sort() extra = tuple(extra) standard = _standardValidators.keys() standard.sort() standard = tuple(standard) msg = 'bad %s value "%s": must be a function or one of ' \ 'the standard validators %s or extra validators %s' raise ValueError, msg % (option, validator, standard, extra) def _executeCommand(self, event = None): cmd = self['command'] if callable(cmd): if event is None: # Return result of command for invoke() method. return cmd() else: cmd() def _preProcess(self): self._previousText = self._entryFieldEntry.get() self._previousICursor = self._entryFieldEntry.index('insert') self._previousXview = self._entryFieldEntry.index('@0') if self._entryFieldEntry.selection_present(): self._previousSel= (self._entryFieldEntry.index('sel.first'), self._entryFieldEntry.index('sel.last')) else: self._previousSel = None def _postProcess(self): # No need to check if text has not changed. previousText = self._previousText if previousText == self._entryFieldEntry.get(): return self.valid() valid = self._checkValidity() if self.hulldestroyed(): # The invalidcommand called by _checkValidity() destroyed us. return valid cmd = self['modifiedcommand'] if callable(cmd) and previousText != self._entryFieldEntry.get(): cmd() return valid def checkentry(self): # If there is a variable specified by the entry_textvariable # option, checkentry() should be called after the set() method # of the variable is called. self._previousText = None return self._postProcess() def _getValidity(self): text = self._entryFieldEntry.get() dict = self._validationInfo args = self._validationArgs if dict['validator'] is not None: status = apply(dict['validator'], (text,), args) if status != OK: return status # Check for out of (min, max) range. if dict['stringtovalue'] is not None: min = dict['min'] max = dict['max'] if min is None and max is None: return OK val = apply(dict['stringtovalue'], (text,), args) if min is not None and val < min: if dict['minstrict']: return ERROR else: return PARTIAL if max is not None and val > max: if dict['maxstrict']: return ERROR else: return PARTIAL return OK def _checkValidity(self): valid = self._getValidity() oldValidity = valid if valid == ERROR: # The entry is invalid. cmd = self['invalidcommand'] if callable(cmd): cmd() if self.hulldestroyed(): # The invalidcommand destroyed us. return oldValidity # Restore the entry to its previous value. if self._previousText is not None: self.__setEntry(self._previousText) self._entryFieldEntry.icursor(self._previousICursor) self._entryFieldEntry.xview(self._previousXview) if self._previousSel is not None: self._entryFieldEntry.selection_range(self._previousSel[0], self._previousSel[1]) # Check if the saved text is valid as well. valid = self._getValidity() self._valid = valid if self.hulldestroyed(): # The validator or stringtovalue commands called by # _checkValidity() destroyed us. return oldValidity if valid == OK: if self.normalBackground is not None: self._entryFieldEntry.configure( background = self.normalBackground) self.normalBackground = None else: if self.normalBackground is None: self.normalBackground = self._entryFieldEntry.cget('background') self._entryFieldEntry.configure( background = self['errorbackground']) return oldValidity def invoke(self): return self._executeCommand() def valid(self): return self._valid == OK def clear(self): self.setentry('') def __setEntry(self, text): oldState = str(self._entryFieldEntry.cget('state')) if oldState != 'normal': self._entryFieldEntry.configure(state='normal') self._entryFieldEntry.delete(0, 'end') self._entryFieldEntry.insert(0, text) if oldState != 'normal': self._entryFieldEntry.configure(state=oldState) def setentry(self, text): self._preProcess() self.__setEntry(text) return self._postProcess() def getvalue(self): return self._entryFieldEntry.get() def setvalue(self, text): return self.setentry(text) forwardmethods(EntryField, Tkinter.Entry, '_entryFieldEntry') # ====================================================================== # Entry field validation functions _numericregex = re.compile('^[0-9]*$') _alphabeticregex = re.compile('^[a-z]*$', re.IGNORECASE) _alphanumericregex = re.compile('^[0-9a-z]*$', re.IGNORECASE) def numericvalidator(text): if text == '': return PARTIAL else: if _numericregex.match(text) is None: return ERROR else: return OK def integervalidator(text): if text in ('', '-', '+'): return PARTIAL try: string.atol(text) return OK except ValueError: return ERROR def alphabeticvalidator(text): if _alphabeticregex.match(text) is None: return ERROR else: return OK def alphanumericvalidator(text): if _alphanumericregex.match(text) is None: return ERROR else: return OK def hexadecimalvalidator(text): if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'): return PARTIAL try: string.atol(text, 16) return OK except ValueError: return ERROR def realvalidator(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: return ERROR index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] try: string.atof(text) return OK except ValueError: # Check if the string could be made valid by appending a digit # eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-'). if len(text) == 0: return PARTIAL if text[-1] in string.digits: return ERROR try: string.atof(text + '0') return PARTIAL except ValueError: return ERROR def timevalidator(text, separator = ':'): try: timestringtoseconds(text, separator) return OK except ValueError: if len(text) > 0 and text[0] in ('+', '-'): text = text[1:] if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL def datevalidator(text, format = 'ymd', separator = '/'): try: datestringtojdn(text, format, separator) return OK except ValueError: if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL _standardValidators = { 'numeric' : (numericvalidator, string.atol), 'integer' : (integervalidator, string.atol), 'hexadecimal' : (hexadecimalvalidator, lambda s: string.atol(s, 16)), 'real' : (realvalidator, stringtoreal), 'alphabetic' : (alphabeticvalidator, len), 'alphanumeric' : (alphanumericvalidator, len), 'time' : (timevalidator, timestringtoseconds), 'date' : (datevalidator, datestringtojdn), } _entryCache = {} def _registerEntryField(entry, entryField): # Register an EntryField widget for an Entry widget _entryCache[entry] = entryField def _deregisterEntryField(entry): # Deregister an Entry widget del _entryCache[entry] def _preProcess(event): # Forward preprocess events for an Entry to it's EntryField _entryCache[event.widget]._preProcess() def _postProcess(event): # Forward postprocess events for an Entry to it's EntryField # The function specified by the 'command' option may have destroyed # the megawidget in a binding earlier in bindtags, so need to check. if _entryCache.has_key(event.widget): _entryCache[event.widget]._postProcess() ###################################################################### ### File: PmwGroup.py import string import Tkinter def aligngrouptags(groups): # Adjust the y position of the tags in /groups/ so that they all # have the height of the highest tag. maxTagHeight = 0 for group in groups: if group._tag is None: height = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) else: height = group._tag.winfo_reqheight() if maxTagHeight < height: maxTagHeight = height for group in groups: ringBorder = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) topBorder = maxTagHeight / 2 - ringBorder / 2 group._hull.grid_rowconfigure(0, minsize = topBorder) group._ring.grid_rowconfigure(0, minsize = maxTagHeight - topBorder - ringBorder) if group._tag is not None: group._tag.place(y = maxTagHeight / 2) class Group( MegaWidget ): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('collapsedsize', 6, INITOPT), ('ring_borderwidth', 2, None), ('ring_relief', 'groove', None), ('tagindent', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._ring = self.createcomponent( 'ring', (), None, Tkinter.Frame, (interior,), ) self._groupChildSite = self.createcomponent( 'groupchildsite', (), None, Tkinter.Frame, (self._ring,) ) self._tag = self.createcomponent( 'tag', (), None, Tkinter.Label, (interior,), ) ringBorder = (string.atoi(str(self._ring.cget('borderwidth'))) + string.atoi(str(self._ring.cget('highlightthickness')))) if self._tag is None: tagHeight = ringBorder else: tagHeight = self._tag.winfo_reqheight() self._tag.place( x = ringBorder + self['tagindent'], y = tagHeight / 2, anchor = 'w') topBorder = tagHeight / 2 - ringBorder / 2 self._ring.grid(column = 0, row = 1, sticky = 'nsew') interior.grid_columnconfigure(0, weight = 1) interior.grid_rowconfigure(1, weight = 1) interior.grid_rowconfigure(0, minsize = topBorder) self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') self._ring.grid_columnconfigure(0, weight = 1) self._ring.grid_rowconfigure(1, weight = 1) self._ring.grid_rowconfigure(0, minsize = tagHeight - topBorder - ringBorder) self.showing = 1 # Check keywords and initialise options. self.initialiseoptions() def toggle(self): if self.showing: self.collapse() else: self.expand() self.showing = not self.showing def expand(self): self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') def collapse(self): self._groupChildSite.grid_forget() if self._tag is None: tagHeight = 0 else: tagHeight = self._tag.winfo_reqheight() self._ring.configure(height=(tagHeight / 2) + self['collapsedsize']) def interior(self): return self._groupChildSite ###################################################################### ### File: PmwLabeledWidget.py import Tkinter class LabeledWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'nsew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._labelChildSite = self.createcomponent('labelchildsite', (), None, Tkinter.Frame, (interior,)) self._labelChildSite.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self._labelChildSite ###################################################################### ### File: PmwMainMenuBar.py # Main menubar import string import types import Tkinter class MainMenuBar(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('hull_tearoff', 0, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu',)) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Menu) self._menuInfo = {} self._menuInfo[None] = (None, []) # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The key for the information for the main menubar is None. self._menu = self.interior() self._menu.bind('<Leave>', self._resetHelpmessage) self._menu.bind('<Motion>', lambda event=None, self=self: self._menuHelp(event, None)) # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName).delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ parentName = self._menuInfo[menuName][0] del self._menuInfo[menuName] if parentName is None: parentMenu = self._menu else: parentMenu = self.component(parentName) menu = self.component(menuName) menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName) def disableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'disabled') def enableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, traverseSpec = None, **kw): if statusHelp is None: statusHelp = balloonHelp self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, kw) def addcascademenu(self, parentMenuName, menuName, statusHelp='', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, kw): if (menuName) in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if kw.has_key('name'): menukw['name'] = kw['name'] del kw['name'] if not kw.has_key('label'): kw['label'] = menuName self._addHotkeyToOptions(parentMenuName, kw, traverseSpec) if parentMenuName is None: parentMenu = self._menu balloon = self['balloon'] # Bug in Tk: balloon help not implemented # if balloon is not None: # balloon.mainmenubind(parentMenu, balloonHelp, statusHelp) else: parentMenu = self.component(parentMenuName) apply(parentMenu.add_cascade, (), kw) menu = apply(self.createcomponent, (menuName, (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) parentMenu.entryconfigure('end', menu = menu) self._menuInfo[parentMenuName][1].append(statusHelp) self._menuInfo[menuName] = (parentMenuName, []) menu.bind('<Leave>', self._resetHelpmessage) menu.bind('<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(event, menuName)) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName) if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key('label')): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return if menuName is None: menu = self._menu else: menu = self.component(menuName) hotkeyList = [] end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = \ string.atoi(str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, 'label')) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw['label'] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, event, menuName): if menuName is None: menu = self._menu index = menu.index('@%d'% event.x) else: menu = self.component(menuName) index = menu.index('@%d'% event.y) balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() forwardmethods(MainMenuBar, Tkinter.Menu, '_hull') ###################################################################### ### File: PmwMenuBar.py # Manager widget for menus. import string import types import Tkinter class MenuBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('padx', 0, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu', 'Button')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self._menuInfo = {} # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The third item in the tuple is the id of the binding used # to detect mouse motion to display status help. # Information for the toplevel menubuttons is not stored here. self._mydeletecommand = self.component('hull').tk.deletecommand # Cache this method for use later. # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName + '-menu').delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ # Clean up binding for this menu. parentName = self._menuInfo[menuName][0] bindId = self._menuInfo[menuName][2] _bindtag = 'PmwMenuBar' + str(self) + menuName self.unbind_class(_bindtag, '<Motion>') self._mydeletecommand(bindId) # unbind_class does not clean up del self._menuInfo[menuName] if parentName is None: self.destroycomponent(menuName + '-button') else: parentMenu = self.component(parentName + '-menu') menu = self.component(menuName + '-menu') menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName + '-menu') def disableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'disabled') def enableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, side = 'left', traverseSpec = None, **kw): self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, side, 'text', kw) def addcascademenu(self, parentMenuName, menuName, statusHelp = '', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, None, 'label', kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, side, textKey, kw): if (menuName + '-menu') in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if not kw.has_key(textKey): kw[textKey] = menuName self._addHotkeyToOptions(parentMenuName, kw, textKey, traverseSpec) if parentMenuName is None: button = apply(self.createcomponent, (menuName + '-button', (), 'Button', Tkinter.Menubutton, (self.interior(),)), kw) button.pack(side=side, padx = self['padx']) balloon = self['balloon'] if balloon is not None: balloon.bind(button, balloonHelp, statusHelp) parentMenu = button else: parentMenu = self.component(parentMenuName + '-menu') apply(parentMenu.add_cascade, (), kw) self._menuInfo[parentMenuName][1].append(statusHelp) menu = apply(self.createcomponent, (menuName + '-menu', (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) if parentMenuName is None: button.configure(menu = menu) else: parentMenu.entryconfigure('end', menu = menu) # Need to put this binding after the class bindings so that # menu.index() does not lag behind. _bindtag = 'PmwMenuBar' + str(self) + menuName bindId = self.bind_class(_bindtag, '<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(menuName)) menu.bindtags(menu.bindtags() + (_bindtag,)) menu.bind('<Leave>', self._resetHelpmessage) self._menuInfo[menuName] = (parentMenuName, [], bindId) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName + '-menu') if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, 'label', traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, textKey, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key(textKey)): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return hotkeyList = [] if menuName is None: for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') underline = string.atoi(str(menubutton.cget('underline'))) if underline != -1: label = str(menubutton.cget(textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) else: menu = self.component(menuName + '-menu') end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = string.atoi( str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw[textKey] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, menuName): menu = self.component(menuName + '-menu') index = menu.index('active') balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() ###################################################################### ### File: PmwMessageBar.py # Class to display messages in an information line. import string import Tkinter class MessageBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. defaultMessageTypes = { # (priority, showtime, bells, logmessage) 'systemerror' : (5, 10, 2, 1), 'usererror' : (4, 5, 1, 0), 'busy' : (3, 0, 0, 0), 'systemevent' : (2, 5, 0, 0), 'userevent' : (2, 5, 0, 0), 'help' : (1, 5, 0, 0), 'state' : (0, 0, 0, 0), } optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('messagetypes', defaultMessageTypes, INITOPT), ('silent', 0, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._messageBarEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') self._messageBarEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._numPriorities = 0 for info in self['messagetypes'].values(): if self._numPriorities < info[0]: self._numPriorities = info[0] self._numPriorities = self._numPriorities + 1 self._timer = [None] * self._numPriorities self._messagetext = [''] * self._numPriorities self._activemessage = [0] * self._numPriorities # Check keywords and initialise options. self.initialiseoptions() def destroy(self): for timerId in self._timer: if timerId is not None: self.after_cancel(timerId) self._timer = [None] * self._numPriorities MegaWidget.destroy(self) def message(self, type, text): # Display a message in the message bar. (priority, showtime, bells, logmessage) = self['messagetypes'][type] if not self['silent']: for i in range(bells): if i != 0: self.after(100) self.bell() self._activemessage[priority] = 1 if text is None: text = '' self._messagetext[priority] = string.replace(text, '\n', ' ') self._redisplayInfoMessage() if logmessage: # Should log this text to a text widget. pass if showtime > 0: if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) # Define a callback to clear this message after a time. def _clearmessage(self=self, priority=priority): self._clearActivemessage(priority) mseconds = int(showtime * 1000) self._timer[priority] = self.after(mseconds, _clearmessage) def helpmessage(self, text): if text is None: self.resetmessages('help') else: self.message('help', text) def resetmessages(self, type): priority = self['messagetypes'][type][0] self._clearActivemessage(priority) for messagetype, info in self['messagetypes'].items(): thisPriority = info[0] showtime = info[1] if thisPriority < priority and showtime != 0: self._clearActivemessage(thisPriority) def _clearActivemessage(self, priority): self._activemessage[priority] = 0 if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) self._timer[priority] = None self._redisplayInfoMessage() def _redisplayInfoMessage(self): text = '' for priority in range(self._numPriorities - 1, -1, -1): if self._activemessage[priority]: text = self._messagetext[priority] break self._messageBarEntry.configure(state = 'normal') self._messageBarEntry.delete(0, 'end') self._messageBarEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') forwardmethods(MessageBar, Tkinter.Entry, '_messageBarEntry') ###################################################################### ### File: PmwMessageDialog.py # Based on iwidgets2.2.0/messagedialog.itk code. import Tkinter class MessageDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ('iconmargin', 20, INITOPT), ('iconpos', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() self._message = self.createcomponent('message', (), None, Tkinter.Label, (interior,)) iconpos = self['iconpos'] iconmargin = self['iconmargin'] borderx = self['borderx'] bordery = self['bordery'] border_right = 2 border_bottom = 2 if iconpos is None: self._message.grid(column = 1, row = 1) else: self._icon = self.createcomponent('icon', (), None, Tkinter.Label, (interior,)) if iconpos not in 'nsew': raise ValueError, \ 'bad iconpos option "%s": should be n, s, e, or w' \ % iconpos if iconpos in 'nw': icon = 1 message = 3 else: icon = 3 message = 1 if iconpos in 'ns': # vertical layout self._icon.grid(column = 1, row = icon) self._message.grid(column = 1, row = message) interior.grid_rowconfigure(2, minsize = iconmargin) border_bottom = 4 else: # horizontal layout self._icon.grid(column = icon, row = 1) self._message.grid(column = message, row = 1) interior.grid_columnconfigure(2, minsize = iconmargin) border_right = 4 interior.grid_columnconfigure(0, minsize = borderx) interior.grid_rowconfigure(0, minsize = bordery) interior.grid_columnconfigure(border_right, minsize = borderx) interior.grid_rowconfigure(border_bottom, minsize = bordery) # Check keywords and initialise options. self.initialiseoptions() ###################################################################### ### File: PmwNoteBook.py import string import types import Tkinter class NoteBook(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('hull_highlightthickness', 0, None), ('hull_borderwidth', 0, None), ('arrownavigation', 1, INITOPT), ('borderwidth', 2, INITOPT), ('createcommand', None, None), ('lowercommand', None, None), ('pagemargin', 4, INITOPT), ('raisecommand', None, None), ('tabpos', 'n', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Page', 'Tab')) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Canvas) self.bind('<Map>', self._handleMap) self.bind('<Configure>', self._handleConfigure) tabpos = self['tabpos'] if tabpos is not None and tabpos != 'n': raise ValueError, \ 'bad tabpos option %s: should be n or None' % repr(tabpos) self._withTabs = (tabpos is not None) self._pageMargin = self['pagemargin'] self._borderWidth = self['borderwidth'] # Use a dictionary as a set of bits indicating what needs to # be redisplayed the next time _layout() is called. If # dictionary contains 'topPage' key, the value is the new top # page to be displayed. None indicates that all pages have # been deleted and that _layout() should draw a border under where # the tabs should be. self._pending = {} self._pending['size'] = 1 self._pending['borderColor'] = 1 self._pending['topPage'] = None if self._withTabs: self._pending['tabs'] = 1 self._canvasSize = None # This gets set by <Configure> events # Set initial height of space for tabs if self._withTabs: self.tabBottom = 35 else: self.tabBottom = 0 self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) self._pageNames = [] # List of page names # Map from page name to page info. Each item is itself a # dictionary containing the following items: # page the Tkinter.Frame widget for the page # created set to true the first time the page is raised # tabbutton the Tkinter.Button widget for the button (if any) # tabreqwidth requested width of the tab # tabreqheight requested height of the tab # tabitems the canvas items for the button: the button # window item, the lightshadow and the darkshadow # left the left and right canvas coordinates of the tab # right self._pageAttrs = {} # Name of page currently on top (actually displayed, using # create_window, not pending). Ignored if current top page # has been deleted or new top page is pending. None indicates # no pages in notebook. self._topPageName = None # Canvas items used: # Per tab: # top and left shadow # right shadow # button # Per notebook: # page # top page # left shadow # bottom and right shadow # top (one or two items) # Canvas tags used: # lighttag - top and left shadows of tabs and page # darktag - bottom and right shadows of tabs and page # (if no tabs then these are reversed) # (used to color the borders by recolorborders) # Create page border shadows. if self._withTabs: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageTop1Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') self._pageTop2Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') else: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageTopBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') # Check keywords and initialise options. self.initialiseoptions() def insert(self, pageName, before = 0, **kw): if self._pageAttrs.has_key(pageName): msg = 'Page "%s" already exists.' % pageName raise ValueError, msg # Do this early to catch bad <before> spec before creating any items. beforeIndex = self.index(before, 1) pageOptions = {} if self._withTabs: # Default tab button options. tabOptions = { 'text' : pageName, 'borderwidth' : 0, } # Divide the keyword options into the 'page_' and 'tab_' options. for key in kw.keys(): if key[:5] == 'page_': pageOptions[key[5:]] = kw[key] del kw[key] elif self._withTabs and key[:4] == 'tab_': tabOptions[key[4:]] = kw[key] del kw[key] else: raise KeyError, 'Unknown option "' + key + '"' # Create the frame to contain the page. page = apply(self.createcomponent, (pageName, (), 'Page', Tkinter.Frame, self._hull), pageOptions) attributes = {} attributes['page'] = page attributes['created'] = 0 if self._withTabs: # Create the button for the tab. def raiseThisPage(self = self, pageName = pageName): self.selectpage(pageName) tabOptions['command'] = raiseThisPage tab = apply(self.createcomponent, (pageName + '-tab', (), 'Tab', Tkinter.Button, self._hull), tabOptions) if self['arrownavigation']: # Allow the use of the arrow keys for Tab navigation: def next(event, self = self, pageName = pageName): self.nextpage(pageName) def prev(event, self = self, pageName = pageName): self.previouspage(pageName) tab.bind('<Left>', prev) tab.bind('<Right>', next) attributes['tabbutton'] = tab attributes['tabreqwidth'] = tab.winfo_reqwidth() attributes['tabreqheight'] = tab.winfo_reqheight() # Create the canvas item to manage the tab's button and the items # for the tab's shadow. windowitem = self.create_window(0, 0, window = tab, anchor = 'nw') lightshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'lighttag', fill = self._lightBorderColor) darkshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'darktag', fill = self._darkBorderColor) attributes['tabitems'] = (windowitem, lightshadow, darkshadow) self._pending['tabs'] = 1 self._pageAttrs[pageName] = attributes self._pageNames.insert(beforeIndex, pageName) # If this is the first page added, make it the new top page # and call the create and raise callbacks. if self.getcurselection() is None: self._pending['topPage'] = pageName self._raiseNewTop(pageName) self._layout() return page def add(self, pageName, **kw): return apply(self.insert, (pageName, len(self._pageNames)), kw) def delete(self, *pageNames): newTopPage = 0 for page in pageNames: pageIndex = self.index(page) pageName = self._pageNames[pageIndex] pageInfo = self._pageAttrs[pageName] if self.getcurselection() == pageName: if len(self._pageNames) == 1: newTopPage = 0 self._pending['topPage'] = None elif pageIndex == len(self._pageNames) - 1: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex - 1] else: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex + 1] if self._topPageName == pageName: self._hull.delete(self._topPageItem) self._topPageName = None if self._withTabs: self.destroycomponent(pageName + '-tab') apply(self._hull.delete, pageInfo['tabitems']) self.destroycomponent(pageName) del self._pageAttrs[pageName] del self._pageNames[pageIndex] # If the old top page was deleted and there are still pages # left in the notebook, call the create and raise callbacks. if newTopPage: pageName = self._pending['topPage'] self._raiseNewTop(pageName) if self._withTabs: self._pending['tabs'] = 1 self._layout() def page(self, pageIndex): pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['page'] def pagenames(self): return list(self._pageNames) def getcurselection(self): if self._pending.has_key('topPage'): return self._pending['topPage'] else: return self._topPageName def tab(self, pageIndex): if self._withTabs: pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['tabbutton'] else: return None def index(self, index, forInsert = 0): listLength = len(self._pageNames) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'NoteBook has no pages' elif index is SELECT: if listLength == 0: raise ValueError, 'NoteBook has no pages' return self._pageNames.index(self.getcurselection()) else: if index in self._pageNames: return self._pageNames.index(index) validValues = 'a name, a number, END or SELECT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def selectpage(self, page): pageName = self._pageNames[self.index(page)] oldTopPage = self.getcurselection() if pageName != oldTopPage: self._pending['topPage'] = pageName if oldTopPage == self._topPageName: self._hull.delete(self._topPageItem) cmd = self['lowercommand'] if cmd is not None: cmd(oldTopPage) self._raiseNewTop(pageName) self._layout() # Set focus to the tab of new top page: if self._withTabs and self['arrownavigation']: self._pageAttrs[pageName]['tabbutton'].focus_set() def previouspage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage > 0: self.selectpage(curpage - 1) def nextpage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage < len(self._pageNames) - 1: self.selectpage(curpage + 1) def setnaturalsize(self, pageNames = None): self.update_idletasks() maxPageWidth = 1 maxPageHeight = 1 if pageNames is None: pageNames = self.pagenames() for pageName in pageNames: pageInfo = self._pageAttrs[pageName] page = pageInfo['page'] w = page.winfo_reqwidth() h = page.winfo_reqheight() if maxPageWidth < w: maxPageWidth = w if maxPageHeight < h: maxPageHeight = h pageBorder = self._borderWidth + self._pageMargin width = maxPageWidth + pageBorder * 2 height = maxPageHeight + pageBorder * 2 if self._withTabs: maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] height = height + maxTabHeight + self._borderWidth * 1.5 # Note that, since the hull is a canvas, the width and height # options specify the geometry *inside* the borderwidth and # highlightthickness. self.configure(hull_width = width, hull_height = height) def recolorborders(self): self._pending['borderColor'] = 1 self._layout() def _handleMap(self, event): self._layout() def _handleConfigure(self, event): self._canvasSize = (event.width, event.height) self._pending['size'] = 1 self._layout() def _raiseNewTop(self, pageName): if not self._pageAttrs[pageName]['created']: self._pageAttrs[pageName]['created'] = 1 cmd = self['createcommand'] if cmd is not None: cmd(pageName) cmd = self['raisecommand'] if cmd is not None: cmd(pageName) # This is the vertical layout of the notebook, from top (assuming # tabpos is 'n'): # hull highlightthickness (top) # hull borderwidth (top) # borderwidth (top border of tabs) # borderwidth * 0.5 (space for bevel) # tab button (maximum of requested height of all tab buttons) # borderwidth (border between tabs and page) # pagemargin (top) # the page itself # pagemargin (bottom) # borderwidth (border below page) # hull borderwidth (bottom) # hull highlightthickness (bottom) # # canvasBorder is sum of top two elements. # tabBottom is sum of top five elements. # # Horizontal layout (and also vertical layout when tabpos is None): # hull highlightthickness # hull borderwidth # borderwidth # pagemargin # the page itself # pagemargin # borderwidth # hull borderwidth # hull highlightthickness # def _layout(self): if not self.winfo_ismapped() or self._canvasSize is None: # Don't layout if the window is not displayed, or we # haven't yet received a <Configure> event. return hullWidth, hullHeight = self._canvasSize borderWidth = self._borderWidth canvasBorder = string.atoi(self._hull['borderwidth']) + \ string.atoi(self._hull['highlightthickness']) if not self._withTabs: self.tabBottom = canvasBorder oldTabBottom = self.tabBottom if self._pending.has_key('borderColor'): self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) # Draw all the tabs. if self._withTabs and (self._pending.has_key('tabs') or self._pending.has_key('size')): # Find total requested width and maximum requested height # of tabs. sumTabReqWidth = 0 maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): sumTabReqWidth = sumTabReqWidth + pageInfo['tabreqwidth'] if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] if maxTabHeight != 0: # Add the top tab border plus a bit for the angled corners self.tabBottom = canvasBorder + maxTabHeight + borderWidth * 1.5 # Prepare for drawing the border around each tab button. tabTop = canvasBorder tabTop2 = tabTop + borderWidth tabTop3 = tabTop + borderWidth * 1.5 tabBottom2 = self.tabBottom tabBottom = self.tabBottom + borderWidth numTabs = len(self._pageNames) availableWidth = hullWidth - 2 * canvasBorder - \ numTabs * 2 * borderWidth x = canvasBorder cumTabReqWidth = 0 cumTabWidth = 0 # Position all the tabs. for pageName in self._pageNames: pageInfo = self._pageAttrs[pageName] (windowitem, lightshadow, darkshadow) = pageInfo['tabitems'] if sumTabReqWidth <= availableWidth: tabwidth = pageInfo['tabreqwidth'] else: # This ugly calculation ensures that, when the # notebook is not wide enough for the requested # widths of the tabs, the total width given to # the tabs exactly equals the available width, # without rounding errors. cumTabReqWidth = cumTabReqWidth + pageInfo['tabreqwidth'] tmp = (2*cumTabReqWidth*availableWidth + sumTabReqWidth) \ / (2 * sumTabReqWidth) tabwidth = tmp - cumTabWidth cumTabWidth = tmp # Position the tab's button canvas item. self.coords(windowitem, x + borderWidth, tabTop3) self.itemconfigure(windowitem, width = tabwidth, height = maxTabHeight) # Make a beautiful border around the tab. left = x left2 = left + borderWidth left3 = left + borderWidth * 1.5 right = left + tabwidth + 2 * borderWidth right2 = left + tabwidth + borderWidth right3 = left + tabwidth + borderWidth * 0.5 self.coords(lightshadow, left, tabBottom2, left, tabTop2, left2, tabTop, right2, tabTop, right3, tabTop2, left3, tabTop2, left2, tabTop3, left2, tabBottom, ) self.coords(darkshadow, right2, tabTop, right, tabTop2, right, tabBottom2, right2, tabBottom, right2, tabTop3, right3, tabTop2, ) pageInfo['left'] = left pageInfo['right'] = right x = x + tabwidth + 2 * borderWidth # Redraw shadow under tabs so that it appears that tab for old # top page is lowered and that tab for new top page is raised. if self._withTabs and (self._pending.has_key('topPage') or self._pending.has_key('tabs') or self._pending.has_key('size')): if self.getcurselection() is None: # No pages, so draw line across top of page area. self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Ignore second top border. self.coords(self._pageTop2Border, 0, 0, 0, 0, 0, 0) else: # Draw two lines, one on each side of the tab for the # top page, so that the tab appears to be raised. pageInfo = self._pageAttrs[self.getcurselection()] left = pageInfo['left'] right = pageInfo['right'] self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, left, self.tabBottom, left + borderWidth, self.tabBottom + borderWidth, canvasBorder + borderWidth, self.tabBottom + borderWidth, ) self.coords(self._pageTop2Border, right, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, right - borderWidth, self.tabBottom + borderWidth, ) # Prevent bottom of dark border of tabs appearing over # page top border. self.tag_raise(self._pageTop1Border) self.tag_raise(self._pageTop2Border) # Position the page border shadows. if self._pending.has_key('size') or oldTabBottom != self.tabBottom: self.coords(self._pageLeftBorder, canvasBorder, self.tabBottom, borderWidth + canvasBorder, self.tabBottom + borderWidth, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, canvasBorder, hullHeight - canvasBorder, ) self.coords(self._pageBottomRightBorder, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder, hullHeight - canvasBorder, canvasBorder, hullHeight - canvasBorder, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, ) if not self._withTabs: self.coords(self._pageTopBorder, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Color borders. if self._pending.has_key('borderColor'): self.itemconfigure('lighttag', fill = self._lightBorderColor) self.itemconfigure('darktag', fill = self._darkBorderColor) newTopPage = self._pending.get('topPage') pageBorder = borderWidth + self._pageMargin # Raise new top page. if newTopPage is not None: self._topPageName = newTopPage self._topPageItem = self.create_window( pageBorder + canvasBorder, self.tabBottom + pageBorder, window = self._pageAttrs[newTopPage]['page'], anchor = 'nw', ) # Change position of top page if tab height has changed. if self._topPageName is not None and oldTabBottom != self.tabBottom: self.coords(self._topPageItem, pageBorder + canvasBorder, self.tabBottom + pageBorder) # Change size of top page if, # 1) there is a new top page. # 2) canvas size has changed, but not if there is no top # page (eg: initially or when all pages deleted). # 3) tab height has changed, due to difference in the height of a tab if (newTopPage is not None or \ self._pending.has_key('size') and self._topPageName is not None or oldTabBottom != self.tabBottom): self.itemconfigure(self._topPageItem, width = hullWidth - 2 * canvasBorder - pageBorder * 2, height = hullHeight - 2 * canvasBorder - pageBorder * 2 - (self.tabBottom - canvasBorder), ) self._pending = {} # Need to do forwarding to get the pack, grid, etc methods. # Unfortunately this means that all the other canvas methods are also # forwarded. forwardmethods(NoteBook, Tkinter.Canvas, '_hull') ###################################################################### ### File: PmwOptionMenu.py import types import Tkinter class OptionMenu(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('items', (), INITOPT), ('initialitem', None, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._menubutton = self.createcomponent('menubutton', (), None, Tkinter.Menubutton, (interior,), borderwidth = 2, indicatoron = 1, relief = 'raised', anchor = 'c', highlightthickness = 2, direction = 'flush', takefocus = 1, ) self._menubutton.grid(column = 2, row = 2, sticky = self['sticky']) self._menu = self.createcomponent('menu', (), None, Tkinter.Menu, (self._menubutton,), tearoff=0 ) self._menubutton.configure(menu = self._menu) interior.grid_columnconfigure(2, weight = 1) interior.grid_rowconfigure(2, weight = 1) # Create the label. self.createlabel(interior) # Add the items specified by the initialisation option. self._itemList = [] self.setitems(self['items'], self['initialitem']) # Check keywords and initialise options. self.initialiseoptions() def setitems(self, items, index = None): # Clean up old items and callback commands. for oldIndex in range(len(self._itemList)): tclCommandName = str(self._menu.entrycget(oldIndex, 'command')) if tclCommandName != '': self._menu.deletecommand(tclCommandName) self._menu.delete(0, 'end') self._itemList = list(items) # Set the items in the menu component. for item in items: self._menu.add_command(label = item, command = lambda self = self, item = item: self._invoke(item)) # Set the currently selected value. if index is None: var = str(self._menubutton.cget('textvariable')) if var != '': # None means do not change text variable. return if len(items) == 0: text = '' elif str(self._menubutton.cget('text')) in items: # Do not change selection if it is still valid return else: text = items[0] else: index = self.index(index) text = self._itemList[index] self.setvalue(text) def getcurselection(self): var = str(self._menubutton.cget('textvariable')) if var == '': return str(self._menubutton.cget('text')) else: return self._menu.tk.globalgetvar(var) def getvalue(self): return self.getcurselection() def setvalue(self, text): var = str(self._menubutton.cget('textvariable')) if var == '': self._menubutton.configure(text = text) else: self._menu.tk.globalsetvar(var, text) def index(self, index): listLength = len(self._itemList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'OptionMenu has no items' else: if index is SELECT: if listLength > 0: index = self.getcurselection() else: raise ValueError, 'OptionMenu has no items' if index in self._itemList: return self._itemList.index(index) raise ValueError, \ 'bad index "%s": must be a ' \ 'name, a number, END or SELECT' % (index,) def invoke(self, index = SELECT): index = self.index(index) text = self._itemList[index] return self._invoke(text) def _invoke(self, text): self.setvalue(text) command = self['command'] if callable(command): return command(text) ###################################################################### ### File: PmwPanedWidget.py # PanedWidget # a frame which may contain several resizable sub-frames import string import sys import types import Tkinter class PanedWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('orient', 'vertical', INITOPT), ('separatorrelief', 'sunken', INITOPT), ('separatorthickness', 2, INITOPT), ('handlesize', 8, INITOPT), ('hull_width', 400, None), ('hull_height', 400, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Frame', 'Separator', 'Handle')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.bind('<Configure>', self._handleConfigure) if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' self._separatorThickness = self['separatorthickness'] self._handleSize = self['handlesize'] self._paneNames = [] # List of pane names self._paneAttrs = {} # Map from pane name to pane info self._timerId = None self._frame = {} self._separator = [] self._button = [] self._totalSize = 0 self._movePending = 0 self._relsize = {} self._relmin = {} self._relmax = {} self._size = {} self._min = {} self._max = {} self._rootp = None self._curSize = None self._beforeLimit = None self._afterLimit = None self._buttonIsDown = 0 self._majorSize = 100 self._minorSize = 100 # Check keywords and initialise options. self.initialiseoptions() def insert(self, name, before = 0, **kw): # Parse <kw> for options. self._initPaneOptions(name) self._parsePaneOptions(name, kw) insertPos = self._nameToIndex(before) atEnd = (insertPos == len(self._paneNames)) # Add the frame. self._paneNames[insertPos:insertPos] = [name] self._frame[name] = self.createcomponent(name, (), 'Frame', Tkinter.Frame, (self.interior(),)) # Add separator, if necessary. if len(self._paneNames) > 1: self._addSeparator() else: self._separator.append(None) self._button.append(None) # Add the new frame and adjust the PanedWidget if atEnd: size = self._size[name] if size > 0 or self._relsize[name] is not None: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, height=size, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, width=size, x=self._totalSize) else: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, x=self._totalSize) else: self._updateSizes() self._totalSize = self._totalSize + self._size[name] return self._frame[name] def add(self, name, **kw): return apply(self.insert, (name, len(self._paneNames)), kw) def delete(self, name): deletePos = self._nameToIndex(name) name = self._paneNames[deletePos] self.destroycomponent(name) del self._paneNames[deletePos] del self._frame[name] del self._size[name] del self._min[name] del self._max[name] del self._relsize[name] del self._relmin[name] del self._relmax[name] last = len(self._paneNames) del self._separator[last] del self._button[last] if last > 0: self.destroycomponent(self._sepName(last)) self.destroycomponent(self._buttonName(last)) self._plotHandles() def setnaturalsize(self): self.update_idletasks() totalWidth = 0 totalHeight = 0 maxWidth = 0 maxHeight = 0 for name in self._paneNames: frame = self._frame[name] w = frame.winfo_reqwidth() h = frame.winfo_reqheight() totalWidth = totalWidth + w totalHeight = totalHeight + h if maxWidth < w: maxWidth = w if maxHeight < h: maxHeight = h # Note that, since the hull is a frame, the width and height # options specify the geometry *outside* the borderwidth and # highlightthickness. bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 if str(self.cget('orient')) == 'horizontal': totalWidth = totalWidth + extra maxHeight = maxHeight + extra self.configure(hull_width = totalWidth, hull_height = maxHeight) else: totalHeight = (totalHeight + extra + (len(self._paneNames) - 1) * self._separatorThickness) maxWidth = maxWidth + extra self.configure(hull_width = maxWidth, hull_height = totalHeight) def move(self, name, newPos, newPosOffset = 0): # see if we can spare ourselves some work numPanes = len(self._paneNames) if numPanes < 2: return newPos = self._nameToIndex(newPos) + newPosOffset if newPos < 0 or newPos >=numPanes: return deletePos = self._nameToIndex(name) if deletePos == newPos: # inserting over ourself is a no-op return # delete name from old position in list name = self._paneNames[deletePos] del self._paneNames[deletePos] # place in new position self._paneNames[newPos:newPos] = [name] # force everything to redraw self._plotHandles() self._updateSizes() def _nameToIndex(self, nameOrIndex): try: pos = self._paneNames.index(nameOrIndex) except ValueError: pos = nameOrIndex return pos def _initPaneOptions(self, name): # Set defaults. self._size[name] = 0 self._relsize[name] = None self._min[name] = 0 self._relmin[name] = None self._max[name] = 100000 self._relmax[name] = None def _parsePaneOptions(self, name, args): # Parse <args> for options. for arg, value in args.items(): if type(value) == types.FloatType: relvalue = value value = self._absSize(relvalue) else: relvalue = None if arg == 'size': self._size[name], self._relsize[name] = value, relvalue elif arg == 'min': self._min[name], self._relmin[name] = value, relvalue elif arg == 'max': self._max[name], self._relmax[name] = value, relvalue else: raise ValueError, 'keyword must be "size", "min", or "max"' def _absSize(self, relvalue): return int(round(relvalue * self._majorSize)) def _sepName(self, n): return 'separator-%d' % n def _buttonName(self, n): return 'handle-%d' % n def _addSeparator(self): n = len(self._paneNames) - 1 downFunc = lambda event, s = self, num=n: s._btnDown(event, num) upFunc = lambda event, s = self, num=n: s._btnUp(event, num) moveFunc = lambda event, s = self, num=n: s._btnMove(event, num) # Create the line dividing the panes. sep = self.createcomponent(self._sepName(n), (), 'Separator', Tkinter.Frame, (self.interior(),), borderwidth = 1, relief = self['separatorrelief']) self._separator.append(sep) sep.bind('<ButtonPress-1>', downFunc) sep.bind('<Any-ButtonRelease-1>', upFunc) sep.bind('<B1-Motion>', moveFunc) if self['orient'] == 'vertical': cursor = 'sb_v_double_arrow' sep.configure(height = self._separatorThickness, width = 10000, cursor = cursor) else: cursor = 'sb_h_double_arrow' sep.configure(width = self._separatorThickness, height = 10000, cursor = cursor) self._totalSize = self._totalSize + self._separatorThickness # Create the handle on the dividing line. handle = self.createcomponent(self._buttonName(n), (), 'Handle', Tkinter.Frame, (self.interior(),), relief = 'raised', borderwidth = 1, width = self._handleSize, height = self._handleSize, cursor = cursor, ) self._button.append(handle) handle.bind('<ButtonPress-1>', downFunc) handle.bind('<Any-ButtonRelease-1>', upFunc) handle.bind('<B1-Motion>', moveFunc) self._plotHandles() for i in range(1, len(self._paneNames)): self._separator[i].tkraise() for i in range(1, len(self._paneNames)): self._button[i].tkraise() def _btnUp(self, event, item): self._buttonIsDown = 0 self._updateSizes() try: self._button[item].configure(relief='raised') except: pass def _btnDown(self, event, item): self._button[item].configure(relief='sunken') self._getMotionLimit(item) self._buttonIsDown = 1 self._movePending = 0 def _handleConfigure(self, event = None): self._getNaturalSizes() if self._totalSize == 0: return iterRange = list(self._paneNames) iterRange.reverse() if self._majorSize > self._totalSize: n = self._majorSize - self._totalSize self._iterate(iterRange, self._grow, n) elif self._majorSize < self._totalSize: n = self._totalSize - self._majorSize self._iterate(iterRange, self._shrink, n) self._plotHandles() self._updateSizes() def _getNaturalSizes(self): # Must call this in order to get correct winfo_width, winfo_height self.update_idletasks() self._totalSize = 0 if self['orient'] == 'vertical': self._majorSize = self.winfo_height() self._minorSize = self.winfo_width() majorspec = Tkinter.Frame.winfo_reqheight else: self._majorSize = self.winfo_width() self._minorSize = self.winfo_height() majorspec = Tkinter.Frame.winfo_reqwidth bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 self._majorSize = self._majorSize - extra self._minorSize = self._minorSize - extra if self._majorSize < 0: self._majorSize = 0 if self._minorSize < 0: self._minorSize = 0 for name in self._paneNames: # adjust the absolute sizes first... if self._relsize[name] is None: #special case if self._size[name] == 0: self._size[name] = apply(majorspec, (self._frame[name],)) self._setrel(name) else: self._size[name] = self._absSize(self._relsize[name]) if self._relmin[name] is not None: self._min[name] = self._absSize(self._relmin[name]) if self._relmax[name] is not None: self._max[name] = self._absSize(self._relmax[name]) # now adjust sizes if self._size[name] < self._min[name]: self._size[name] = self._min[name] self._setrel(name) if self._size[name] > self._max[name]: self._size[name] = self._max[name] self._setrel(name) self._totalSize = self._totalSize + self._size[name] # adjust for separators self._totalSize = (self._totalSize + (len(self._paneNames) - 1) * self._separatorThickness) def _setrel(self, name): if self._relsize[name] is not None: if self._majorSize != 0: self._relsize[name] = round(self._size[name]) / self._majorSize def _iterate(self, names, proc, n): for i in names: n = apply(proc, (i, n)) if n == 0: break def _grow(self, name, n): canGrow = self._max[name] - self._size[name] if canGrow > n: self._size[name] = self._size[name] + n self._setrel(name) return 0 elif canGrow > 0: self._size[name] = self._max[name] self._setrel(name) n = n - canGrow return n def _shrink(self, name, n): canShrink = self._size[name] - self._min[name] if canShrink > n: self._size[name] = self._size[name] - n self._setrel(name) return 0 elif canShrink > 0: self._size[name] = self._min[name] self._setrel(name) n = n - canShrink return n def _updateSizes(self): totalSize = 0 for name in self._paneNames: size = self._size[name] if self['orient'] == 'vertical': self._frame[name].place(x = 0, relwidth = 1, y = totalSize, height = size) else: self._frame[name].place(y = 0, relheight = 1, x = totalSize, width = size) totalSize = totalSize + size + self._separatorThickness # Invoke the callback command cmd = self['command'] if callable(cmd): cmd(map(lambda x, s = self: s._size[x], self._paneNames)) def _plotHandles(self): if len(self._paneNames) == 0: return if self['orient'] == 'vertical': btnp = self._minorSize - 13 else: h = self._minorSize if h > 18: btnp = 9 else: btnp = h - 9 firstPane = self._paneNames[0] totalSize = self._size[firstPane] first = 1 last = len(self._paneNames) - 1 # loop from first to last, inclusive for i in range(1, last + 1): handlepos = totalSize - 3 prevSize = self._size[self._paneNames[i - 1]] nextSize = self._size[self._paneNames[i]] offset1 = 0 if i == first: if prevSize < 4: offset1 = 4 - prevSize else: if prevSize < 8: offset1 = (8 - prevSize) / 2 offset2 = 0 if i == last: if nextSize < 4: offset2 = nextSize - 4 else: if nextSize < 8: offset2 = (nextSize - 8) / 2 handlepos = handlepos + offset1 if self['orient'] == 'vertical': height = 8 - offset1 + offset2 if height > 1: self._button[i].configure(height = height) self._button[i].place(x = btnp, y = handlepos) else: self._button[i].place_forget() self._separator[i].place(x = 0, y = totalSize, relwidth = 1) else: width = 8 - offset1 + offset2 if width > 1: self._button[i].configure(width = width) self._button[i].place(y = btnp, x = handlepos) else: self._button[i].place_forget() self._separator[i].place(y = 0, x = totalSize, relheight = 1) totalSize = totalSize + nextSize + self._separatorThickness def pane(self, name): return self._frame[self._paneNames[self._nameToIndex(name)]] # Return the name of all panes def panes(self): return list(self._paneNames) def configurepane(self, name, **kw): name = self._paneNames[self._nameToIndex(name)] self._parsePaneOptions(name, kw) self._handleConfigure() def updatelayout(self): self._handleConfigure() def _getMotionLimit(self, item): curBefore = (item - 1) * self._separatorThickness minBefore, maxBefore = curBefore, curBefore for name in self._paneNames[:item]: curBefore = curBefore + self._size[name] minBefore = minBefore + self._min[name] maxBefore = maxBefore + self._max[name] curAfter = (len(self._paneNames) - item) * self._separatorThickness minAfter, maxAfter = curAfter, curAfter for name in self._paneNames[item:]: curAfter = curAfter + self._size[name] minAfter = minAfter + self._min[name] maxAfter = maxAfter + self._max[name] beforeToGo = min(curBefore - minBefore, maxAfter - curAfter) afterToGo = min(curAfter - minAfter, maxBefore - curBefore) self._beforeLimit = curBefore - beforeToGo self._afterLimit = curBefore + afterToGo self._curSize = curBefore self._plotHandles() # Compress the motion so that update is quick even on slow machines # # theRootp = root position (either rootx or rooty) def _btnMove(self, event, item): self._rootp = event if self._movePending == 0: self._timerId = self.after_idle( lambda s = self, i = item: s._btnMoveCompressed(i)) self._movePending = 1 def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def _btnMoveCompressed(self, item): if not self._buttonIsDown: return if self['orient'] == 'vertical': p = self._rootp.y_root - self.winfo_rooty() else: p = self._rootp.x_root - self.winfo_rootx() if p == self._curSize: self._movePending = 0 return if p < self._beforeLimit: p = self._beforeLimit if p >= self._afterLimit: p = self._afterLimit self._calculateChange(item, p) self.update_idletasks() self._movePending = 0 # Calculate the change in response to mouse motions def _calculateChange(self, item, p): if p < self._curSize: self._moveBefore(item, p) elif p > self._curSize: self._moveAfter(item, p) self._plotHandles() def _moveBefore(self, item, p): n = self._curSize - p # Shrink the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._shrink, n) # Adjust the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._grow, n) self._curSize = p def _moveAfter(self, item, p): n = p - self._curSize # Shrink the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._shrink, n) # Adjust the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._grow, n) self._curSize = p ###################################################################### ### File: PmwPromptDialog.py # Based on iwidgets2.2.0/promptdialog.itk code. # A Dialog with an entryfield class PromptDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('entry', 'entryfield_entry'), ('label', 'entryfield_label'), ) self._promptDialogEntry = self.createcomponent('entryfield', aliases, None, EntryField, (interior,)) self._promptDialogEntry.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # EntryField's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._promptDialogEntry.insert(index, text) def deleteentry(self, first, last=None): self._promptDialogEntry.delete(first, last) def indexentry(self, index): return self._promptDialogEntry.index(index) forwardmethods(PromptDialog, EntryField, '_promptDialogEntry') ###################################################################### ### File: PmwRadioSelect.py import types import Tkinter class RadioSelect(MegaWidget): # A collection of several buttons. In single mode, only one # button may be selected. In multiple mode, any number of buttons # may be selected. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttontype', 'button', INITOPT), ('command', None, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 5, INITOPT), ('pady', 5, INITOPT), ('selectmode', 'single', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._radioSelectFrame = self._hull else: self._radioSelectFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._radioSelectFrame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._buttonList = [] if self['selectmode'] == 'single': self._singleSelect = 1 elif self['selectmode'] == 'multiple': self._singleSelect = 0 else: raise ValueError, 'bad selectmode option "' + \ self['selectmode'] + '": should be single or multiple' if self['buttontype'] == 'button': self.buttonClass = Tkinter.Button elif self['buttontype'] == 'radiobutton': self._singleSelect = 1 self.var = Tkinter.StringVar() self.buttonClass = Tkinter.Radiobutton elif self['buttontype'] == 'checkbutton': self._singleSelect = 0 self.buttonClass = Tkinter.Checkbutton else: raise ValueError, 'bad buttontype option "' + \ self['buttontype'] + \ '": should be button, radiobutton or checkbutton' if self._singleSelect: self.selection = None else: self.selection = [] if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' # Check keywords and initialise options. self.initialiseoptions() def getcurselection(self): if self._singleSelect: return self.selection else: return tuple(self.selection) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): if self._singleSelect: self.__setSingleValue(textOrList) else: # Multiple selections oldselection = self.selection self.selection = textOrList for button in self._buttonList: if button in oldselection: if button not in self.selection: # button is currently selected but should not be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.deselect() else: # Button widget.configure(relief='raised') else: if button in self.selection: # button is not currently selected but should be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.select() else: # Button widget.configure(relief='sunken') def numbuttons(self): return len(self._buttonList) def index(self, index): # Return the integer index of the button with the given index. listLength = len(self._buttonList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'RadioSelect has no buttons' else: for count in range(listLength): name = self._buttonList[count] if index == name: return count validValues = 'a name, a number or END' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def button(self, buttonIndex): name = self._buttonList[self.index(buttonIndex)] return self.component(name) def add(self, componentName, **kw): if componentName in self._buttonList: raise ValueError, 'button "%s" already exists' % componentName kw['command'] = \ lambda self=self, name=componentName: self.invoke(name) if not kw.has_key('text'): kw['text'] = componentName if self['buttontype'] == 'radiobutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' if not kw.has_key('variable'): kw['variable'] = self.var if not kw.has_key('value'): kw['value'] = kw['text'] elif self['buttontype'] == 'checkbutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' button = apply(self.createcomponent, (componentName, (), 'Button', self.buttonClass, (self._radioSelectFrame,)), kw) if self['orient'] == 'horizontal': self._radioSelectFrame.grid_rowconfigure(0, weight=1) col = len(self._buttonList) button.grid(column=col, row=0, padx = self['padx'], pady = self['pady'], sticky='nsew') self._radioSelectFrame.grid_columnconfigure(col, weight=1) else: self._radioSelectFrame.grid_columnconfigure(0, weight=1) row = len(self._buttonList) button.grid(column=0, row=row, padx = self['padx'], pady = self['pady'], sticky='ew') self._radioSelectFrame.grid_rowconfigure(row, weight=1) self._buttonList.append(componentName) return button def deleteall(self): for name in self._buttonList: self.destroycomponent(name) self._buttonList = [] if self._singleSelect: self.selection = None else: self.selection = [] def __setSingleValue(self, value): self.selection = value if self['buttontype'] == 'radiobutton': widget = self.component(value) widget.select() else: # Button for button in self._buttonList: widget = self.component(button) if button == value: widget.configure(relief='sunken') else: widget.configure(relief='raised') def invoke(self, index): index = self.index(index) name = self._buttonList[index] if self._singleSelect: self.__setSingleValue(name) command = self['command'] if callable(command): return command(name) else: # Multiple selections widget = self.component(name) if name in self.selection: if self['buttontype'] == 'checkbutton': widget.deselect() else: widget.configure(relief='raised') self.selection.remove(name) state = 0 else: if self['buttontype'] == 'checkbutton': widget.select() else: widget.configure(relief='sunken') self.selection.append(name) state = 1 command = self['command'] if callable(command): return command(name, state) ###################################################################### ### File: PmwScrolledCanvas.py import Tkinter class ScrolledCanvas(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('canvasmargin', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the canvas. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._canvas.pack(fill = 'both', expand = 1) else: # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._canvas.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self._canvas.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self._canvas.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.setregionTimer = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None if self.setregionTimer is not None: self.after_cancel(self.setregionTimer) self.setregionTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._canvas def resizescrollregion(self): if self.setregionTimer is None: self.setregionTimer = self.after_idle(self._setRegion) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._canvas.cget('xscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) tclCommandName = str(self._canvas.cget('yscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._canvas.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._canvas.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the canvas to set the horizontal or vertical # scrollbar when it has scrolled or changed scrollregion. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._canvas.xview() yview = self._canvas.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _setRegion(self): self.setregionTimer = None region = self._canvas.bbox('all') if region is not None: canvasmargin = self['canvasmargin'] region = (region[0] - canvasmargin, region[1] - canvasmargin, region[2] + canvasmargin, region[3] + canvasmargin) self._canvas.configure(scrollregion = region) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, *args): return apply(self._canvas.bbox, args) forwardmethods(ScrolledCanvas, Tkinter.Canvas, '_canvas') ###################################################################### ### File: PmwScrolledField.py import Tkinter class ScrolledField(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ('text', '', self._text), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._scrolledFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') self._scrolledFieldEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def _text(self): text = self['text'] self._scrolledFieldEntry.configure(state = 'normal') self._scrolledFieldEntry.delete(0, 'end') self._scrolledFieldEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') forwardmethods(ScrolledField, Tkinter.Entry, '_scrolledFieldEntry') ###################################################################### ### File: PmwScrolledFrame.py import string import types import Tkinter class ScrolledFrame(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 1, INITOPT), ('horizflex', 'fixed', self._horizflex), ('horizfraction', 0.05, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vertflex', 'fixed', self._vertflex), ('vertfraction', 0.05, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the clipper. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self._borderframe,), width = 400, height = 300, highlightthickness = 0, borderwidth = 0, ) self._clipper.pack(fill = 'both', expand = 1) else: # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self.origInterior,), width = 400, height = 300, relief = 'sunken', borderwidth = 2, ) self._clipper.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.startX = 0 self.startY = 0 self._flexoptions = ('fixed', 'expand', 'shrink', 'elastic') # Create a frame in the clipper to contain the widgets to be # scrolled. self._frame = self.createcomponent('frame', (), None, Tkinter.Frame, (self._clipper,) ) # Whenever the clipping window or scrolled frame change size, # update the scrollbars. self._frame.bind('<Configure>', self._reposition) self._clipper.bind('<Configure>', self._reposition) # Work around a bug in Tk where the value returned by the # scrollbar get() method is (0.0, 0.0, 0.0, 0.0) rather than # the expected 2-tuple. This occurs if xview() is called soon # after the ScrolledFrame has been created. self._horizScrollbar.set(0.0, 1.0) self._vertScrollbar.set(0.0, 1.0) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._frame # Set timer to call real reposition method, so that it is not # called multiple times when many things are reconfigured at the # same time. def reposition(self): if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) # Called when the user clicks in the horizontal scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def xview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._horizScrollbar.get() elif mode == 'moveto': frameWidth = self._frame.winfo_reqwidth() self.startX = value * float(frameWidth) else: # mode == 'scroll' clipperWidth = self._clipper.winfo_width() if units == 'units': jump = int(clipperWidth * self['horizfraction']) else: jump = clipperWidth self.startX = self.startX + value * jump self.reposition() # Called when the user clicks in the vertical scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def yview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._vertScrollbar.get() elif mode == 'moveto': frameHeight = self._frame.winfo_reqheight() self.startY = value * float(frameHeight) else: # mode == 'scroll' clipperHeight = self._clipper.winfo_height() if units == 'units': jump = int(clipperHeight * self['vertfraction']) else: jump = clipperHeight self.startY = self.startY + value * jump self.reposition() # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _horizflex(self): # The horizontal flex mode has been configured. flex = self['horizflex'] if flex not in self._flexoptions: message = 'bad horizflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() def _vertflex(self): # The vertical flex mode has been configured. flex = self['vertflex'] if flex not in self._flexoptions: message = 'bad vertflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() # ====================================================================== # Private methods. def _reposition(self, event): self.reposition() def _getxview(self): # Horizontal dimension. clipperWidth = self._clipper.winfo_width() frameWidth = self._frame.winfo_reqwidth() if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self.startX = 0 endScrollX = 1.0 if self['horizflex'] in ('expand', 'elastic'): relwidth = 1 else: relwidth = '' else: # The scrolled frame is larger than the clipping window. if self['horizflex'] in ('shrink', 'elastic'): self.startX = 0 endScrollX = 1.0 relwidth = 1 else: if self.startX + clipperWidth > frameWidth: self.startX = frameWidth - clipperWidth endScrollX = 1.0 else: if self.startX < 0: self.startX = 0 endScrollX = (self.startX + clipperWidth) / float(frameWidth) relwidth = '' # Position frame relative to clipper. self._frame.place(x = -self.startX, relwidth = relwidth) return (self.startX / float(frameWidth), endScrollX) def _getyview(self): # Vertical dimension. clipperHeight = self._clipper.winfo_height() frameHeight = self._frame.winfo_reqheight() if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self.startY = 0 endScrollY = 1.0 if self['vertflex'] in ('expand', 'elastic'): relheight = 1 else: relheight = '' else: # The scrolled frame is larger than the clipping window. if self['vertflex'] in ('shrink', 'elastic'): self.startY = 0 endScrollY = 1.0 relheight = 1 else: if self.startY + clipperHeight > frameHeight: self.startY = frameHeight - clipperHeight endScrollY = 1.0 else: if self.startY < 0: self.startY = 0 endScrollY = (self.startY + clipperHeight) / float(frameHeight) relheight = '' # Position frame relative to clipper. self._frame.place(y = -self.startY, relheight = relheight) return (self.startY / float(frameHeight), endScrollY) # According to the relative geometries of the frame and the # clipper, reposition the frame within the clipper and reset the # scrollbars. def _scrollBothNow(self): self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._getxview() yview = self._getyview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) ###################################################################### ### File: PmwScrolledListBox.py # Based on iwidgets2.2.0/scrolledlistbox.itk code. import types import Tkinter class ScrolledListBox(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('dblclickcommand', None, None), ('hscrollmode', 'dynamic', self._hscrollMode), ('items', (), INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('selectioncommand', None, None), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) # Create the listbox widget. self._listbox = self.createcomponent('listbox', (), None, Tkinter.Listbox, (interior,)) self._listbox.grid(row = 2, column = 2, sticky = 'news') interior.grid_rowconfigure(2, weight = 1, minsize = 0) interior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._listbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._listbox.yview ) self.createlabel(interior, childCols = 3, childRows = 3) # Add the items specified by the initialisation option. items = self['items'] if type(items) != types.TupleType: items = tuple(items) if len(items) > 0: apply(self._listbox.insert, ('end',) + items) _registerScrolledList(self._listbox, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. theTag = 'ScrolledListBoxTag' if ScrolledListBox._classBindingsDefinedFor != Tkinter._default_root: root = Tkinter._default_root def doubleEvent(event): _handleEvent(event, 'double') def keyEvent(event): _handleEvent(event, 'key') def releaseEvent(event): _handleEvent(event, 'release') # Bind space and return keys and button 1 to the selectioncommand. root.bind_class(theTag, '<Key-space>', keyEvent) root.bind_class(theTag, '<Key-Return>', keyEvent) root.bind_class(theTag, '<ButtonRelease-1>', releaseEvent) # Bind double button 1 click to the dblclickcommand. root.bind_class(theTag, '<Double-ButtonRelease-1>', doubleEvent) ScrolledListBox._classBindingsDefinedFor = root bindtags = self._listbox.bindtags() self._listbox.bindtags(bindtags + (theTag,)) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None _deregisterScrolledList(self._listbox) MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.setlist(()) def getcurselection(self): rtn = [] for sel in self.curselection(): rtn.append(self._listbox.get(sel)) return tuple(rtn) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): self._listbox.selection_clear(0, 'end') listitems = list(self._listbox.get(0, 'end')) if type(textOrList) == types.StringType: if textOrList in listitems: self._listbox.selection_set(listitems.index(textOrList)) else: raise ValueError, 'no such item "%s"' % textOrList else: for item in textOrList: if item in listitems: self._listbox.selection_set(listitems.index(item)) else: raise ValueError, 'no such item "%s"' % item def setlist(self, items): self._listbox.delete(0, 'end') if len(items) > 0: if type(items) != types.TupleType: items = tuple(items) apply(self._listbox.insert, (0,) + items) # Override Tkinter.Listbox get method, so that if it is called with # no arguments, return all list elements (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._listbox.get(0, 'end') else: return self._listbox.get(first, last) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._listbox.cget('xscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) tclCommandName = str(self._listbox.cget('yscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._listbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._listbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the listbox to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._listbox.xview() yview = self._listbox.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _handleEvent(self, event, eventType): if eventType == 'double': command = self['dblclickcommand'] elif eventType == 'key': command = self['selectioncommand'] else: #eventType == 'release' # Do not execute the command if the mouse was released # outside the listbox. if (event.x < 0 or self._listbox.winfo_width() <= event.x or event.y < 0 or self._listbox.winfo_height() <= event.y): return command = self['selectioncommand'] if callable(command): command() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._listbox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._listbox.bbox(index) forwardmethods(ScrolledListBox, Tkinter.Listbox, '_listbox') # ====================================================================== _listboxCache = {} def _registerScrolledList(listbox, scrolledList): # Register an ScrolledList widget for a Listbox widget _listboxCache[listbox] = scrolledList def _deregisterScrolledList(listbox): # Deregister a Listbox widget del _listboxCache[listbox] def _handleEvent(event, eventType): # Forward events for a Listbox to it's ScrolledListBox # A binding earlier in the bindtags list may have destroyed the # megawidget, so need to check. if _listboxCache.has_key(event.widget): _listboxCache[event.widget]._handleEvent(event, eventType) ###################################################################### ### File: PmwScrolledText.py # Based on iwidgets2.2.0/scrolledtext.itk code. import Tkinter class ScrolledText(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('columnheader', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('rowcolumnheader',0, INITOPT), ('rowheader', 0, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the text # widget. Later, pack the text widget so that it fills # the frame. This avoids a problem in Tk, where window # items in a text widget may overlap the border of the # text widget. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (interior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 4, column = 4, sticky = 'news') # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._textbox.pack(fill = 'both', expand = 1) bw = self._borderframe.cget('borderwidth'), ht = self._borderframe.cget('highlightthickness'), else: # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (interior,), ) self._textbox.grid(row = 4, column = 4, sticky = 'news') bw = self._textbox.cget('borderwidth'), ht = self._textbox.cget('highlightthickness'), # Create the header text widgets if self['columnheader']: self._columnheader = self.createcomponent('columnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._columnheader.grid(row = 2, column = 4, sticky = 'ew') self._columnheader.configure( xscrollcommand = self._columnheaderscrolled) if self['rowheader']: self._rowheader = self.createcomponent('rowheader', (), 'Header', Tkinter.Text, (interior,), wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowheader.grid(row = 4, column = 2, sticky = 'ns') self._rowheader.configure( yscrollcommand = self._rowheaderscrolled) if self['rowcolumnheader']: self._rowcolumnheader = self.createcomponent('rowcolumnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowcolumnheader.grid(row = 2, column = 2, sticky = 'nsew') interior.grid_rowconfigure(4, weight = 1, minsize = 0) interior.grid_columnconfigure(4, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._textbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._textbox.yview ) self.createlabel(interior, childCols = 5, childRows = 5) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self._textWidth = None # These four variables avoid an infinite loop caused by the # row or column header's scrollcommand causing the main text # widget's scrollcommand to be called and vice versa. self._textboxLastX = None self._textboxLastY = None self._columnheaderLastX = None self._rowheaderLastY = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.settext('') def importfile(self, fileName, where = 'end'): file = open(fileName, 'r') self._textbox.insert(where, file.read()) file.close() def exportfile(self, fileName): file = open(fileName, 'w') file.write(self._textbox.get('1.0', 'end')) file.close() def settext(self, text): disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.delete('0.0', 'end') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') # Override Tkinter.Text get method, so that if it is called with # no arguments, return all text (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._textbox.get('1.0', 'end') else: return self._textbox.get(first, last) def getvalue(self): return self.get() def setvalue(self, text): return self.settext(text) def appendtext(self, text): oldTop, oldBottom = self._textbox.yview() disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') if oldBottom == 1.0: self._textbox.yview('moveto', 1.0) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._textbox.cget('xscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) tclCommandName = str(self._textbox.cget('yscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._textbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._textbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) # This code is the same as in _scrollBothNow. Keep it that way. if self['hscrollmode'] == 'dynamic': currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['columnheader']: if self._columnheaderLastX != first: self._columnheaderLastX = first self._columnheader.xview('moveto', first) def _scrollYNow(self, first, last): if first == '0' and last == '0': return self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() if self['rowheader']: if self._rowheaderLastY != first: self._rowheaderLastY = first self._rowheader.yview('moveto', first) def _scrollBothLater(self, first, last): # Called by the text widget to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._textbox.xview() yview = self._textbox.yview() # The text widget returns a yview of (0.0, 0.0) just after it # has been created. Ignore this. if yview == (0.0, 0.0): return if self['columnheader']: if self._columnheaderLastX != xview[0]: self._columnheaderLastX = xview[0] self._columnheader.xview('moveto', xview[0]) if self['rowheader']: if self._rowheaderLastY != yview[0]: self._rowheaderLastY = yview[0] self._rowheader.yview('moveto', yview[0]) self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': # The following test is done to prevent continuous # mapping and unmapping of the horizontal scrollbar. # This may occur when some event (scrolling, resizing # or text changes) modifies the displayed text such # that the bottom line in the window is the longest # line displayed. If this causes the horizontal # scrollbar to be mapped, the scrollbar may "cover up" # the bottom line, which would mean that the scrollbar # is no longer required. If the scrollbar is then # unmapped, the bottom line will then become visible # again, which would cause the scrollbar to be mapped # again, and so on... # # The idea is that, if the width of the text widget # has not changed and the scrollbar is currently # mapped, then do not unmap the scrollbar even if it # is no longer required. This means that, during # normal scrolling of the text, once the horizontal # scrollbar has been mapped it will not be unmapped # (until the width of the text widget changes). currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _columnheaderscrolled(self, first, last): if self._textboxLastX != first: self._textboxLastX = first self._textbox.xview('moveto', first) def _rowheaderscrolled(self, first, last): if self._textboxLastY != first: self._textboxLastY = first self._textbox.yview('moveto', first) def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 6, column = 4, sticky = 'news') interior.grid_rowconfigure(5, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(5, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 4, column = 6, sticky = 'news') interior.grid_columnconfigure(5, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(5, minsize = 0) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._textbox.bbox(index) forwardmethods(ScrolledText, Tkinter.Text, '_textbox') ###################################################################### ### File: PmwHistoryText.py _ORIGINAL = 0 _MODIFIED = 1 _DISPLAY = 2 class HistoryText(ScrolledText): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('compressany', 1, None), ('compresstail', 1, None), ('historycommand', None, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). ScrolledText.__init__(self, parent) # Initialise instance variables. self._list = [] self._currIndex = 0 self._pastIndex = None self._lastIndex = 0 # pointer to end of history list # Check keywords and initialise options. self.initialiseoptions() def addhistory(self): text = self.get() if text[-1] == '\n': text = text[:-1] if len(self._list) == 0: # This is the first history entry. Add it. self._list.append([text, text, _MODIFIED]) return currentEntry = self._list[self._currIndex] if text == currentEntry[_ORIGINAL]: # The current history entry has not been modified. Check if # we need to add it again. if self['compresstail'] and self._currIndex == self._lastIndex: return if self['compressany']: return # Undo any changes for the current history entry, since they # will now be available in the new entry. currentEntry[_MODIFIED] = currentEntry[_ORIGINAL] historycommand = self['historycommand'] if self._currIndex == self._lastIndex: # The last history entry is currently being displayed, # so disable the special meaning of the 'Next' button. self._pastIndex = None nextState = 'disabled' else: # A previous history entry is currently being displayed, # so allow the 'Next' button to go to the entry after this one. self._pastIndex = self._currIndex nextState = 'normal' if callable(historycommand): historycommand('normal', nextState) # Create the new history entry. self._list.append([text, text, _MODIFIED]) # Move the pointer into the history entry list to the end. self._lastIndex = self._lastIndex + 1 self._currIndex = self._lastIndex def next(self): if self._currIndex == self._lastIndex and self._pastIndex is None: self.bell() else: self._modifyDisplay('next') def prev(self): self._pastIndex = None if self._currIndex == 0: self.bell() else: self._modifyDisplay('prev') def undo(self): if len(self._list) != 0: self._modifyDisplay('undo') def redo(self): if len(self._list) != 0: self._modifyDisplay('redo') def gethistory(self): return self._list def _modifyDisplay(self, command): # Modify the display to show either the next or previous # history entry (next, prev) or the original or modified # version of the current history entry (undo, redo). # Save the currently displayed text. currentText = self.get() if currentText[-1] == '\n': currentText = currentText[:-1] currentEntry = self._list[self._currIndex] if currentEntry[_DISPLAY] == _MODIFIED: currentEntry[_MODIFIED] = currentText elif currentEntry[_ORIGINAL] != currentText: currentEntry[_MODIFIED] = currentText if command in ('next', 'prev'): currentEntry[_DISPLAY] = _MODIFIED if command in ('next', 'prev'): prevstate = 'normal' nextstate = 'normal' if command == 'next': if self._pastIndex is not None: self._currIndex = self._pastIndex self._pastIndex = None self._currIndex = self._currIndex + 1 if self._currIndex == self._lastIndex: nextstate = 'disabled' elif command == 'prev': self._currIndex = self._currIndex - 1 if self._currIndex == 0: prevstate = 'disabled' historycommand = self['historycommand'] if callable(historycommand): historycommand(prevstate, nextstate) currentEntry = self._list[self._currIndex] else: if command == 'undo': currentEntry[_DISPLAY] = _ORIGINAL elif command == 'redo': currentEntry[_DISPLAY] = _MODIFIED # Display the new text. self.delete('1.0', 'end') self.insert('end', currentEntry[currentEntry[_DISPLAY]]) ###################################################################### ### File: PmwSelectionDialog.py # Not Based on iwidgets version. class SelectionDialog(Dialog): # Dialog window with selection list. # Dialog window displaying a list and requesting the user to # select one. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'scrolledlist_listbox'), ('label', 'scrolledlist_label'), ) self._list = self.createcomponent('scrolledlist', aliases, None, ScrolledListBox, (interior,), dblclickcommand = self.invoke) self._list.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ScrolledListBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self.component('listbox').size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self.component('listbox').size(index) forwardmethods(SelectionDialog, ScrolledListBox, '_list') ###################################################################### ### File: PmwTextDialog.py # A Dialog with a ScrolledText widget. class TextDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('text', 'scrolledtext_text'), ('label', 'scrolledtext_label'), ) self._text = self.createcomponent('scrolledtext', aliases, None, ScrolledText, (interior,)) self._text.pack(side='top', expand=1, fill='both', padx = self['borderx'], pady = self['bordery']) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._text.bbox(index) forwardmethods(TextDialog, ScrolledText, '_text') ###################################################################### ### File: PmwTimeCounter.py # Authors: Joe VanAndel and Greg McFarlane import string import sys import time import Tkinter class TimeCounter(MegaWidget): """Up-down counter A TimeCounter is a single-line entry widget with Up and Down arrows which increment and decrement the Time value in the entry. """ def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('command', None, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('max', None, self._max), ('min', None, self._min), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('value', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.arrowDirection = {} self._flag = 'stopped' self._timerId = None self._createComponents(kw) value = self['value'] if value is None: now = time.time() value = time.strftime('%H:%M:%S', time.localtime(now)) self.setvalue(value) # Check keywords and initialise options. self.initialiseoptions() def _createComponents(self, kw): # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow buttons. # Create the hour down arrow. self._downHourArrowBtn = self.createcomponent('downhourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downHourArrowBtn] = 'down' self._downHourArrowBtn.grid(column = 0, row = 2) # Create the minute down arrow. self._downMinuteArrowBtn = self.createcomponent('downminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downMinuteArrowBtn] = 'down' self._downMinuteArrowBtn.grid(column = 1, row = 2) # Create the second down arrow. self._downSecondArrowBtn = self.createcomponent('downsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downSecondArrowBtn] = 'down' self._downSecondArrowBtn.grid(column = 2, row = 2) # Create the entry fields. # Create the hour entry field. self._hourCounterEntry = self.createcomponent('hourentryfield', (('hourentry', 'hourentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._hourCounterEntry.grid(column = 0, row = 1, sticky = 'news') # Create the minute entry field. self._minuteCounterEntry = self.createcomponent('minuteentryfield', (('minuteentry', 'minuteentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._minuteCounterEntry.grid(column = 1, row = 1, sticky = 'news') # Create the second entry field. self._secondCounterEntry = self.createcomponent('secondentryfield', (('secondentry', 'secondentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._secondCounterEntry.grid(column = 2, row = 1, sticky = 'news') # Create the up arrow buttons. # Create the hour up arrow. self._upHourArrowBtn = self.createcomponent('uphourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upHourArrowBtn] = 'up' self._upHourArrowBtn.grid(column = 0, row = 0) # Create the minute up arrow. self._upMinuteArrowBtn = self.createcomponent('upminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upMinuteArrowBtn] = 'up' self._upMinuteArrowBtn.grid(column = 1, row = 0) # Create the second up arrow. self._upSecondArrowBtn = self.createcomponent('upsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upSecondArrowBtn] = 'up' self._upSecondArrowBtn.grid(column = 2, row = 0) # Make it resize nicely. padx = self['padx'] pady = self['pady'] for col in range(3): frame.grid_columnconfigure(col, weight = 1, pad = padx) frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_rowconfigure(1, weight = 1) # Create the label. self.createlabel(interior) # Set bindings. # Up hour self._upHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upHourArrowBtn: s._drawArrow(button, 'up')) self._upHourArrowBtn.bind('<1>', lambda event, s=self,button=self._upHourArrowBtn: s._countUp(button, 3600)) self._upHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upHourArrowBtn: s._stopUpDown(button)) # Up minute self._upMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upMinuteArrowBtn: s._drawArrow(button, 'up')) self._upMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._upMinuteArrowBtn: s._countUp(button, 60)) self._upMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upMinuteArrowBtn: s._stopUpDown(button)) # Up second self._upSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upSecondArrowBtn: s._drawArrow(button, 'up')) self._upSecondArrowBtn.bind('<1>', lambda event, s=self,button=self._upSecondArrowBtn: s._countUp(button, 1)) self._upSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upSecondArrowBtn: s._stopUpDown(button)) # Down hour self._downHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downHourArrowBtn: s._drawArrow(button, 'down')) self._downHourArrowBtn.bind('<1>', lambda event, s=self,button=self._downHourArrowBtn: s._countDown(button, 3600)) self._downHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downHourArrowBtn: s._stopUpDown(button)) # Down minute self._downMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downMinuteArrowBtn: s._drawArrow(button, 'down')) self._downMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._downMinuteArrowBtn: s._countDown(button, 60)) self._downMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downMinuteArrowBtn: s._stopUpDown(button)) # Down second self._downSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downSecondArrowBtn: s._drawArrow(button, 'down')) self._downSecondArrowBtn.bind('<1>', lambda event, s=self, button=self._downSecondArrowBtn: s._countDown(button,1)) self._downSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downSecondArrowBtn: s._stopUpDown(button)) self._hourCounterEntry.component('entry').bind( '<Return>', self._invoke) self._minuteCounterEntry.component('entry').bind( '<Return>', self._invoke) self._secondCounterEntry.component('entry').bind( '<Return>', self._invoke) self._hourCounterEntry.bind('<Configure>', self._resizeArrow) self._minuteCounterEntry.bind('<Configure>', self._resizeArrow) self._secondCounterEntry.bind('<Configure>', self._resizeArrow) def _drawArrow(self, arrow, direction): drawarrow(arrow, self['hourentry_foreground'], direction, 'arrow') def _resizeArrow(self, event = None): for btn in (self._upHourArrowBtn, self._upMinuteArrowBtn, self._upSecondArrowBtn, self._downHourArrowBtn, self._downMinuteArrowBtn, self._downSecondArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._hourCounterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn, self.arrowDirection[btn]) def _min(self): min = self['min'] if min is None: self._minVal = 0 else: self._minVal = timestringtoseconds(min) def _max(self): max = self['max'] if max is None: self._maxVal = None else: self._maxVal = timestringtoseconds(max) def getvalue(self): return self.getstring() def setvalue(self, text): list = string.split(text, ':') if len(list) != 3: raise ValueError, 'invalid value: ' + text self._hour = string.atoi(list[0]) self._minute = string.atoi(list[1]) self._second = string.atoi(list[2]) self._setHMS() def getstring(self): return '%02d:%02d:%02d' % (self._hour, self._minute, self._second) def getint(self): return self._hour * 3600 + self._minute * 60 + self._second def _countUp(self, button, increment): self._relief = self._upHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(1, 'start', increment) def _countDown(self, button, increment): self._relief = self._downHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(-1, 'start', increment) def increment(self, seconds = 1): self._count(1, 'force', seconds) def decrement(self, seconds = 1): self._count(-1, 'force', seconds) def _count(self, factor, newFlag = None, increment = 1): if newFlag != 'force': if newFlag is not None: self._flag = newFlag if self._flag == 'stopped': return value = (string.atoi(self._hourCounterEntry.get()) *3600) + \ (string.atoi(self._minuteCounterEntry.get()) *60) + \ string.atoi(self._secondCounterEntry.get()) + \ factor * increment min = self._minVal max = self._maxVal if value < min: value = min if max is not None and value > max: value = max self._hour = value /3600 self._minute = (value - (self._hour*3600)) / 60 self._second = value - (self._hour*3600) - (self._minute*60) self._setHMS() if newFlag != 'force': if self['autorepeat']: if self._flag == 'start': delay = self['initwait'] self._flag = 'running' else: delay = self['repeatrate'] self._timerId = self.after( delay, lambda self=self, factor=factor,increment=increment: self._count(factor,'running', increment)) def _setHMS(self): self._hourCounterEntry.setentry('%02d' % self._hour) self._minuteCounterEntry.setentry('%02d' % self._minute) self._secondCounterEntry.setentry('%02d' % self._second) def _stopUpDown(self, button): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None button.configure(relief=self._relief) self._flag = 'stopped' def _invoke(self, event): cmd = self['command'] if callable(cmd): cmd() def invoke(self): cmd = self['command'] if callable(cmd): return cmd() def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) ###################################################################### ### File: PmwAboutDialog.py class AboutDialog(MessageDialog): # Window to display version and contact information. # Class members containing resettable 'default' values: _version = '' _copyright = '' _contact = '' def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('applicationname', '', INITOPT), ('iconpos', 'w', None), ('icon_bitmap', 'info', None), ('buttons', ('Close',), None), ('defaultbutton', 0, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MessageDialog.__init__(self, parent) applicationname = self['applicationname'] if not kw.has_key('title'): self.configure(title = 'About ' + applicationname) if not kw.has_key('message_text'): text = applicationname + '\n\n' if AboutDialog._version != '': text = text + 'Version ' + AboutDialog._version + '\n' if AboutDialog._copyright != '': text = text + AboutDialog._copyright + '\n\n' if AboutDialog._contact != '': text = text + AboutDialog._contact self.configure(message_text=text) # Check keywords and initialise options. self.initialiseoptions() def aboutversion(value): AboutDialog._version = value def aboutcopyright(value): AboutDialog._copyright = value def aboutcontact(value): AboutDialog._contact = value ###################################################################### ### File: PmwComboBox.py # Based on iwidgets2.2.0/combobox.itk code. import os import string import types import Tkinter class ComboBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autoclear', 0, INITOPT), ('buttonaspect', 1.0, INITOPT), ('dropdown', 1, INITOPT), ('fliparrow', 0, INITOPT), ('history', 1, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('listheight', 200, INITOPT), ('selectioncommand', None, None), ('sticky', 'ew', INITOPT), ('unique', 1, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryfield = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (interior,)) self._entryfield.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight = 1) self._entryWidget = self._entryfield.component('entry') if self['dropdown']: self._isPosted = 0 interior.grid_rowconfigure(2, weight = 1) # Create the arrow button. self._arrowBtn = self.createcomponent('arrowbutton', (), None, Tkinter.Canvas, (interior,), borderwidth = 2, relief = 'raised', width = 16, height = 16) if 'n' in self['sticky']: sticky = 'n' else: sticky = '' if 's' in self['sticky']: sticky = sticky + 's' self._arrowBtn.grid(column=3, row=2, sticky = sticky) self._arrowRelief = self._arrowBtn.cget('relief') # Create the label. self.createlabel(interior, childCols=2) # Create the dropdown window. self._popup = self.createcomponent('popup', (), None, Tkinter.Toplevel, (interior,)) self._popup.withdraw() self._popup.overrideredirect(1) # Create the scrolled listbox inside the dropdown window. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (self._popup,), hull_borderwidth = 2, hull_relief = 'raised', hull_height = self['listheight'], usehullsize = 1, listbox_exportselection = 0) self._list.pack(expand=1, fill='both') self.__listbox = self._list.component('listbox') # Bind events to the arrow button. self._arrowBtn.bind('<1>', self._postList) self._arrowBtn.bind('<Configure>', self._drawArrow) self._arrowBtn.bind('<3>', self._next) self._arrowBtn.bind('<Shift-3>', self._previous) self._arrowBtn.bind('<Down>', self._next) self._arrowBtn.bind('<Up>', self._previous) self._arrowBtn.bind('<Control-n>', self._next) self._arrowBtn.bind('<Control-p>', self._previous) self._arrowBtn.bind('<Shift-Down>', self._postList) self._arrowBtn.bind('<Shift-Up>', self._postList) self._arrowBtn.bind('<F34>', self._postList) self._arrowBtn.bind('<F28>', self._postList) self._arrowBtn.bind('<space>', self._postList) # Bind events to the dropdown window. self._popup.bind('<Escape>', self._unpostList) self._popup.bind('<space>', self._selectUnpost) self._popup.bind('<Return>', self._selectUnpost) self._popup.bind('<ButtonRelease-1>', self._dropdownBtnRelease) self._popup.bind('<ButtonPress-1>', self._unpostOnNextRelease) # Bind events to the Tk listbox. self.__listbox.bind('<Enter>', self._unpostOnNextRelease) # Bind events to the Tk entry widget. self._entryWidget.bind('<Configure>', self._resizeArrow) self._entryWidget.bind('<Shift-Down>', self._postList) self._entryWidget.bind('<Shift-Up>', self._postList) self._entryWidget.bind('<F34>', self._postList) self._entryWidget.bind('<F28>', self._postList) # Need to unpost the popup if the entryfield is unmapped (eg: # its toplevel window is withdrawn) while the popup list is # displayed. self._entryWidget.bind('<Unmap>', self._unpostList) else: # Create the scrolled listbox below the entry field. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (interior,), selectioncommand = self._selectCmd) self._list.grid(column=2, row=3, sticky='nsew') self.__listbox = self._list.component('listbox') # The scrolled listbox should expand vertically. interior.grid_rowconfigure(3, weight = 1) # Create the label. self.createlabel(interior, childRows=2) self._entryWidget.bind('<Down>', self._next) self._entryWidget.bind('<Up>', self._previous) self._entryWidget.bind('<Control-n>', self._next) self._entryWidget.bind('<Control-p>', self._previous) self.__listbox.bind('<Control-n>', self._next) self.__listbox.bind('<Control-p>', self._previous) if self['history']: self._entryfield.configure(command=self._addHistory) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self['dropdown'] and self._isPosted: popgrab(self._popup) MegaWidget.destroy(self) #====================================================================== # Public methods def get(self, first = None, last=None): if first is None: return self._entryWidget.get() else: return self._list.get(first, last) def invoke(self): if self['dropdown']: self._postList() else: return self._selectCmd() def selectitem(self, index, setentry=1): if type(index) == types.StringType: text = index items = self._list.get(0, 'end') if text in items: index = list(items).index(text) else: raise IndexError, 'index "%s" not found' % text elif setentry: text = self._list.get(0, 'end')[index] self._list.select_clear(0, 'end') self._list.select_set(index, index) self._list.activate(index) self.see(index) if setentry: self._entryfield.setentry(text) # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._list.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._list.bbox(index) def clear(self): self._entryfield.clear() self._list.clear() #====================================================================== # Private methods for both dropdown and simple comboboxes. def _addHistory(self): input = self._entryWidget.get() if input != '': index = None if self['unique']: # If item is already in list, select it and return. items = self._list.get(0, 'end') if input in items: index = list(items).index(input) if index is None: index = self._list.index('end') self._list.insert('end', input) self.selectitem(index) if self['autoclear']: self._entryWidget.delete(0, 'end') # Execute the selectioncommand on the new entry. self._selectCmd() def _next(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = 0 else: index = string.atoi(cursels[0]) if index == size - 1: index = 0 else: index = index + 1 self.selectitem(index) def _previous(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = size - 1 else: index = string.atoi(cursels[0]) if index == 0: index = size - 1 else: index = index - 1 self.selectitem(index) def _selectCmd(self, event=None): sels = self.getcurselection() if len(sels) == 0: item = None else: item = sels[0] self._entryfield.setentry(item) cmd = self['selectioncommand'] if callable(cmd): if event is None: # Return result of selectioncommand for invoke() method. return cmd(item) else: cmd(item) #====================================================================== # Private methods for dropdown combobox. def _drawArrow(self, event=None, sunken=0): arrow = self._arrowBtn if sunken: self._arrowRelief = arrow.cget('relief') arrow.configure(relief = 'sunken') else: arrow.configure(relief = self._arrowRelief) if self._isPosted and self['fliparrow']: direction = 'up' else: direction = 'down' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _postList(self, event = None): self._isPosted = 1 self._drawArrow(sunken=1) # Make sure that the arrow is displayed sunken. self.update_idletasks() x = self._entryfield.winfo_rootx() y = self._entryfield.winfo_rooty() + \ self._entryfield.winfo_height() w = self._entryfield.winfo_width() + self._arrowBtn.winfo_width() h = self.__listbox.winfo_height() sh = self.winfo_screenheight() if y + h > sh and y > sh / 2: y = self._entryfield.winfo_rooty() - h self._list.configure(hull_width=w) setgeometryanddeiconify(self._popup, '+%d+%d' % (x, y)) # Grab the popup, so that all events are delivered to it, and # set focus to the listbox, to make keyboard navigation # easier. pushgrab(self._popup, 1, self._unpostList) self.__listbox.focus_set() self._drawArrow() # Ignore the first release of the mouse button after posting the # dropdown list, unless the mouse enters the dropdown list. self._ignoreRelease = 1 def _dropdownBtnRelease(self, event): if (event.widget == self._list.component('vertscrollbar') or event.widget == self._list.component('horizscrollbar')): return if self._ignoreRelease: self._unpostOnNextRelease() return self._unpostList() if (event.x >= 0 and event.x < self.__listbox.winfo_width() and event.y >= 0 and event.y < self.__listbox.winfo_height()): self._selectCmd() def _unpostOnNextRelease(self, event = None): self._ignoreRelease = 0 def _resizeArrow(self, event): bw = (string.atoi(self._arrowBtn['borderwidth']) + string.atoi(self._arrowBtn['highlightthickness'])) newHeight = self._entryfield.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) self._arrowBtn.configure(width=newWidth, height=newHeight) self._drawArrow() def _unpostList(self, event=None): if not self._isPosted: # It is possible to get events on an unposted popup. For # example, by repeatedly pressing the space key to post # and unpost the popup. The <space> event may be # delivered to the popup window even though # popgrab() has set the focus away from the # popup window. (Bug in Tk?) return # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._popup) self._popup.withdraw() self._isPosted = 0 self._drawArrow() def _selectUnpost(self, event): self._unpostList() self._selectCmd() forwardmethods(ComboBox, ScrolledListBox, '_list') forwardmethods(ComboBox, EntryField, '_entryfield') ###################################################################### ### File: PmwComboBoxDialog.py # Not Based on iwidgets version. class ComboBoxDialog(Dialog): # Dialog window with simple combobox. # Dialog window displaying a list and entry field and requesting # the user to make a selection or enter a value def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'combobox_listbox'), ('scrolledlist', 'combobox_scrolledlist'), ('entry', 'combobox_entry'), ('label', 'combobox_label'), ) self._combobox = self.createcomponent('combobox', aliases, None, ComboBox, (interior,), scrolledlist_dblclickcommand = self.invoke, dropdown = 0, ) self._combobox.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ComboBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self._combobox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._combobox.bbox(index) forwardmethods(ComboBoxDialog, ComboBox, '_combobox') ###################################################################### ### File: PmwCounter.py import string import sys import types import Tkinter class Counter(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('datatype', 'numeric', self._datatype), ('increment', 1, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Initialise instance variables. self._timerId = None self._normalRelief = None # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow. self._downArrowBtn = self.createcomponent('downarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) # Create the entry field. self._counterEntry = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (frame,)) # Create the up arrow. self._upArrowBtn = self.createcomponent('uparrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) padx = self['padx'] pady = self['pady'] orient = self['orient'] if orient == 'horizontal': self._downArrowBtn.grid(column = 0, row = 0) self._counterEntry.grid(column = 1, row = 0, sticky = self['sticky']) self._upArrowBtn.grid(column = 2, row = 0) frame.grid_columnconfigure(1, weight = 1) frame.grid_rowconfigure(0, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_columnconfigure(0, pad = padx) frame.grid_columnconfigure(2, pad = padx) frame.grid_rowconfigure(0, pad = pady) elif orient == 'vertical': self._upArrowBtn.grid(column = 0, row = 0, sticky = 's') self._counterEntry.grid(column = 0, row = 1, sticky = self['sticky']) self._downArrowBtn.grid(column = 0, row = 2, sticky = 'n') frame.grid_columnconfigure(0, weight = 1) frame.grid_rowconfigure(0, weight = 1) frame.grid_rowconfigure(2, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_columnconfigure(0, pad = padx) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' self.createlabel(interior) self._upArrowBtn.bind('<Configure>', self._drawUpArrow) self._upArrowBtn.bind('<1>', self._countUp) self._upArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._downArrowBtn.bind('<Configure>', self._drawDownArrow) self._downArrowBtn.bind('<1>', self._countDown) self._downArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._counterEntry.bind('<Configure>', self._resizeArrow) entry = self._counterEntry.component('entry') entry.bind('<Down>', lambda event, s = self: s._key_decrement(event)) entry.bind('<Up>', lambda event, s = self: s._key_increment(event)) # Need to cancel the timer if an arrow button is unmapped (eg: # its toplevel window is withdrawn) while the mouse button is # held down. The canvas will not get the ButtonRelease event # if it is not mapped, since the implicit grab is cancelled. self._upArrowBtn.bind('<Unmap>', self._stopCounting) self._downArrowBtn.bind('<Unmap>', self._stopCounting) # Check keywords and initialise options. self.initialiseoptions() def _resizeArrow(self, event): for btn in (self._upArrowBtn, self._downArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._counterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn) def _drawUpArrow(self, event): self._drawArrow(self._upArrowBtn) def _drawDownArrow(self, event): self._drawArrow(self._downArrowBtn) def _drawArrow(self, arrow): if self['orient'] == 'vertical': if arrow == self._upArrowBtn: direction = 'up' else: direction = 'down' else: if arrow == self._upArrowBtn: direction = 'right' else: direction = 'left' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _stopCounting(self, event = None): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None if self._normalRelief is not None: button, relief = self._normalRelief button.configure(relief=relief) self._normalRelief = None def _countUp(self, event): self._normalRelief = (self._upArrowBtn, self._upArrowBtn.cget('relief')) self._upArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._upArrowBtn.update_idletasks() self._count(1, 1) def _countDown(self, event): self._normalRelief = (self._downArrowBtn, self._downArrowBtn.cget('relief')) self._downArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._downArrowBtn.update_idletasks() self._count(-1, 1) def increment(self): self._forceCount(1) def decrement(self): self._forceCount(-1) def _key_increment(self, event): self._forceCount(1) self.update_idletasks() def _key_decrement(self, event): self._forceCount(-1) self.update_idletasks() def _datatype(self): datatype = self['datatype'] if type(datatype) is types.DictionaryType: self._counterArgs = datatype.copy() if self._counterArgs.has_key('counter'): datatype = self._counterArgs['counter'] del self._counterArgs['counter'] else: datatype = 'numeric' else: self._counterArgs = {} if _counterCommands.has_key(datatype): self._counterCommand = _counterCommands[datatype] elif callable(datatype): self._counterCommand = datatype else: validValues = _counterCommands.keys() validValues.sort() raise ValueError, ('bad datatype value "%s": must be a' + ' function or one of %s') % (datatype, validValues) def _forceCount(self, factor): if not self.valid(): self.bell() return text = self._counterEntry.get() try: value = apply(self._counterCommand, (text, factor, self['increment']), self._counterArgs) except ValueError: self.bell() return previousICursor = self._counterEntry.index('insert') if self._counterEntry.setentry(value) == OK: self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) def _count(self, factor, first): if not self.valid(): self.bell() return self._timerId = None origtext = self._counterEntry.get() try: value = apply(self._counterCommand, (origtext, factor, self['increment']), self._counterArgs) except ValueError: # If text is invalid, stop counting. self._stopCounting() self.bell() return # If incrementing produces an invalid value, restore previous # text and stop counting. previousICursor = self._counterEntry.index('insert') valid = self._counterEntry.setentry(value) if valid != OK: self._stopCounting() self._counterEntry.setentry(origtext) if valid == PARTIAL: self.bell() return self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) if self['autorepeat']: if first: delay = self['initwait'] else: delay = self['repeatrate'] self._timerId = self.after(delay, lambda self=self, factor=factor: self._count(factor, 0)) def destroy(self): self._stopCounting() MegaWidget.destroy(self) forwardmethods(Counter, EntryField, '_counterEntry') def _changeNumber(text, factor, increment): value = string.atol(text) if factor > 0: value = (value / increment) * increment + increment else: value = ((value - 1) / increment) * increment # Get rid of the 'L' at the end of longs (in python up to 1.5.2). rtn = str(value) if rtn[-1] == 'L': return rtn[:-1] else: return rtn def _changeReal(text, factor, increment, separator = '.'): value = stringtoreal(text, separator) div = value / increment # Compare reals using str() to avoid problems caused by binary # numbers being only approximations to decimal numbers. # For example, if value is -0.3 and increment is 0.1, then # int(value/increment) = -2, not -3 as one would expect. if str(div)[-2:] == '.0': # value is an even multiple of increment. div = round(div) + factor else: # value is not an even multiple of increment. div = int(div) * 1.0 if value < 0: div = div - 1 if factor > 0: div = (div + 1) value = div * increment text = str(value) if separator != '.': index = string.find(text, '.') if index >= 0: text = text[:index] + separator + text[index + 1:] return text def _changeDate(value, factor, increment, format = 'ymd', separator = '/', yyyy = 0): jdn = datestringtojdn(value, format, separator) + factor * increment y, m, d = jdntoymd(jdn) result = '' for index in range(3): if index > 0: result = result + separator f = format[index] if f == 'y': if yyyy: result = result + '%02d' % y else: result = result + '%02d' % (y % 100) elif f == 'm': result = result + '%02d' % m elif f == 'd': result = result + '%02d' % d return result _SECSPERDAY = 24 * 60 * 60 def _changeTime(value, factor, increment, separator = ':', time24 = 0): unixTime = timestringtoseconds(value, separator) if factor > 0: chunks = unixTime / increment + 1 else: chunks = (unixTime - 1) / increment unixTime = chunks * increment if time24: while unixTime < 0: unixTime = unixTime + _SECSPERDAY while unixTime >= _SECSPERDAY: unixTime = unixTime - _SECSPERDAY if unixTime < 0: unixTime = -unixTime sign = '-' else: sign = '' secs = unixTime % 60 unixTime = unixTime / 60 mins = unixTime % 60 hours = unixTime / 60 return '%s%02d%s%02d%s%02d' % (sign, hours, separator, mins, separator, secs) # hexadecimal, alphabetic, alphanumeric not implemented _counterCommands = { 'numeric' : _changeNumber, # } integer 'integer' : _changeNumber, # } these two use the same function 'real' : _changeReal, # real number 'time' : _changeTime, 'date' : _changeDate, } ###################################################################### ### File: PmwCounterDialog.py # A Dialog with a counter class CounterDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() # Create the counter. aliases = ( ('entryfield', 'counter_entryfield'), ('entry', 'counter_entryfield_entry'), ('label', 'counter_label') ) self._cdCounter = self.createcomponent('counter', aliases, None, Counter, (interior,)) self._cdCounter.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # Counter's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._cdCounter.insert(index, text) def deleteentry(self, first, last=None): self._cdCounter.delete(first, last) def indexentry(self, index): return self._cdCounter.index(index) forwardmethods(CounterDialog, Counter, '_cdCounter') ###################################################################### ### File: PmwLogicalFont.py import os import string def _font_initialise(root, size=None, fontScheme = None): global _fontSize if size is not None: _fontSize = size if fontScheme in ('pmw1', 'pmw2'): if os.name == 'posix': defaultFont = logicalfont('Helvetica') menuFont = logicalfont('Helvetica', weight='bold', slant='italic') scaleFont = logicalfont('Helvetica', slant='italic') root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Menu*Font', menuFont, 'userDefault') root.option_add('*Menubutton*Font', menuFont, 'userDefault') root.option_add('*Scale.*Font', scaleFont, 'userDefault') if fontScheme == 'pmw1': balloonFont = logicalfont('Helvetica', -6, pixel = '12') else: # fontScheme == 'pmw2' balloonFont = logicalfont('Helvetica', -2) root.option_add('*Balloon.*Font', balloonFont, 'userDefault') else: defaultFont = logicalfont('Helvetica') root.option_add('*Font', defaultFont, 'userDefault') elif fontScheme == 'default': defaultFont = ('Helvetica', '-%d' % (_fontSize,), 'bold') entryFont = ('Helvetica', '-%d' % (_fontSize,)) textFont = ('Courier', '-%d' % (_fontSize,)) root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Entry*Font', entryFont, 'userDefault') root.option_add('*Text*Font', textFont, 'userDefault') def logicalfont(name='Helvetica', sizeIncr = 0, **kw): if not _fontInfo.has_key(name): raise ValueError, 'font %s does not exist' % name rtn = [] for field in _fontFields: if kw.has_key(field): logicalValue = kw[field] elif _fontInfo[name].has_key(field): logicalValue = _fontInfo[name][field] else: logicalValue = '*' if _propertyAliases[name].has_key((field, logicalValue)): realValue = _propertyAliases[name][(field, logicalValue)] elif _propertyAliases[name].has_key((field, None)): realValue = _propertyAliases[name][(field, None)] elif _propertyAliases[None].has_key((field, logicalValue)): realValue = _propertyAliases[None][(field, logicalValue)] elif _propertyAliases[None].has_key((field, None)): realValue = _propertyAliases[None][(field, None)] else: realValue = logicalValue if field == 'size': if realValue == '*': realValue = _fontSize realValue = str((realValue + sizeIncr) * 10) rtn.append(realValue) return string.join(rtn, '-') def logicalfontnames(): return _fontInfo.keys() if os.name == 'nt': _fontSize = 16 else: _fontSize = 14 _fontFields = ( 'registry', 'foundry', 'family', 'weight', 'slant', 'width', 'style', 'pixel', 'size', 'xres', 'yres', 'spacing', 'avgwidth', 'charset', 'encoding') # <_propertyAliases> defines other names for which property values may # be known by. This is required because italics in adobe-helvetica # are specified by 'o', while other fonts use 'i'. _propertyAliases = {} _propertyAliases[None] = { ('slant', 'italic') : 'i', ('slant', 'normal') : 'r', ('weight', 'light') : 'normal', ('width', 'wide') : 'normal', ('width', 'condensed') : 'normal', } # <_fontInfo> describes a 'logical' font, giving the default values of # some of its properties. _fontInfo = {} _fontInfo['Helvetica'] = { 'foundry' : 'adobe', 'family' : 'helvetica', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Helvetica'] = { ('slant', 'italic') : 'o', ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Times'] = { 'foundry' : 'adobe', 'family' : 'times', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Times'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Fixed'] = { 'foundry' : 'misc', 'family' : 'fixed', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'c', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Fixed'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', ('width', 'condensed') : 'semicondensed', } _fontInfo['Courier'] = { 'foundry' : 'adobe', 'family' : 'courier', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Courier'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', } _fontInfo['Typewriter'] = { 'foundry' : 'b&h', 'family' : 'lucidatypewriter', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Typewriter'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } if os.name == 'nt': # For some reason 'fixed' fonts on NT aren't. _fontInfo['Fixed'] = _fontInfo['Courier'] _propertyAliases['Fixed'] = _propertyAliases['Courier']
Python
# Functions for converting colors and modifying the color scheme of # an application. import math import string import sys import Tkinter _PI = math.pi _TWO_PI = _PI * 2 _THIRD_PI = _PI / 3 _SIXTH_PI = _PI / 6 _MAX_RGB = float(256 * 256 - 1) # max size of rgb values returned from Tk def setscheme(root, background=None, **kw): root = root._root() palette = apply(_calcPalette, (root, background,), kw) for option, value in palette.items(): root.option_add('*' + option, value, 'widgetDefault') def getdefaultpalette(root): # Return the default values of all options, using the defaults # from a few widgets. ckbtn = Tkinter.Checkbutton(root) entry = Tkinter.Entry(root) scbar = Tkinter.Scrollbar(root) orig = {} orig['activeBackground'] = str(ckbtn.configure('activebackground')[4]) orig['activeForeground'] = str(ckbtn.configure('activeforeground')[4]) orig['background'] = str(ckbtn.configure('background')[4]) orig['disabledForeground'] = str(ckbtn.configure('disabledforeground')[4]) orig['foreground'] = str(ckbtn.configure('foreground')[4]) orig['highlightBackground'] = str(ckbtn.configure('highlightbackground')[4]) orig['highlightColor'] = str(ckbtn.configure('highlightcolor')[4]) orig['insertBackground'] = str(entry.configure('insertbackground')[4]) orig['selectColor'] = str(ckbtn.configure('selectcolor')[4]) orig['selectBackground'] = str(entry.configure('selectbackground')[4]) orig['selectForeground'] = str(entry.configure('selectforeground')[4]) orig['troughColor'] = str(scbar.configure('troughcolor')[4]) ckbtn.destroy() entry.destroy() scbar.destroy() return orig #====================================================================== # Functions dealing with brightness, hue, saturation and intensity of colors. def changebrightness(root, colorName, brightness): # Convert the color name into its hue and back into a color of the # required brightness. rgb = name2rgb(root, colorName) hue, saturation, intensity = rgb2hsi(rgb) if saturation == 0.0: hue = None return hue2name(hue, brightness) def hue2name(hue, brightness = None): # Convert the requested hue and brightness into a color name. If # hue is None, return a grey of the requested brightness. if hue is None: rgb = hsi2rgb(0.0, 0.0, brightness) else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI rgb = hsi2rgb(hue, 1.0, 1.0) if brightness is not None: b = rgb2brightness(rgb) i = 1.0 - (1.0 - brightness) * b s = bhi2saturation(brightness, hue, i) rgb = hsi2rgb(hue, s, i) return rgb2name(rgb) def bhi2saturation(brightness, hue, intensity): while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) pp = intensity pq = intensity * f pt = intensity - intensity * f pv = 0 hue = int(hue) if hue == 0: rgb = (pv, pt, pp) elif hue == 1: rgb = (pq, pv, pp) elif hue == 2: rgb = (pp, pv, pt) elif hue == 3: rgb = (pp, pq, pv) elif hue == 4: rgb = (pt, pp, pv) elif hue == 5: rgb = (pv, pp, pq) return (intensity - brightness) / rgb2brightness(rgb) def hsi2rgb(hue, saturation, intensity): i = intensity if saturation == 0: rgb = [i, i, i] else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) p = i * (1.0 - saturation) q = i * (1.0 - saturation * f) t = i * (1.0 - saturation * (1.0 - f)) hue = int(hue) if hue == 0: rgb = [i, t, p] elif hue == 1: rgb = [q, i, p] elif hue == 2: rgb = [p, i, t] elif hue == 3: rgb = [p, q, i] elif hue == 4: rgb = [t, p, i] elif hue == 5: rgb = [i, p, q] for index in range(3): val = rgb[index] if val < 0.0: val = 0.0 if val > 1.0: val = 1.0 rgb[index] = val return rgb def average(rgb1, rgb2, fraction): return ( rgb2[0] * fraction + rgb1[0] * (1.0 - fraction), rgb2[1] * fraction + rgb1[1] * (1.0 - fraction), rgb2[2] * fraction + rgb1[2] * (1.0 - fraction) ) def rgb2name(rgb): return '#%02x%02x%02x' % \ (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)) def rgb2brightness(rgb): # Return the perceived grey level of the color # (0.0 == black, 1.0 == white). rf = 0.299 gf = 0.587 bf = 0.114 return rf * rgb[0] + gf * rgb[1] + bf * rgb[2] def rgb2hsi(rgb): maxc = max(rgb[0], rgb[1], rgb[2]) minc = min(rgb[0], rgb[1], rgb[2]) intensity = maxc if maxc != 0: saturation = (maxc - minc) / maxc else: saturation = 0.0 hue = 0.0 if saturation != 0.0: c = [] for index in range(3): c.append((maxc - rgb[index]) / (maxc - minc)) if rgb[0] == maxc: hue = c[2] - c[1] elif rgb[1] == maxc: hue = 2 + c[0] - c[2] elif rgb[2] == maxc: hue = 4 + c[1] - c[0] hue = hue * _THIRD_PI if hue < 0.0: hue = hue + _TWO_PI return (hue, saturation, intensity) def name2rgb(root, colorName, asInt = 0): if colorName[0] == '#': # Extract rgb information from the color name itself, assuming # it is either #rgb, #rrggbb, #rrrgggbbb, or #rrrrggggbbbb # This is useful, since tk may return incorrect rgb values if # the colormap is full - it will return the rbg values of the # closest color available. colorName = colorName[1:] digits = len(colorName) / 3 factor = 16 ** (4 - digits) rgb = ( string.atoi(colorName[0:digits], 16) * factor, string.atoi(colorName[digits:digits * 2], 16) * factor, string.atoi(colorName[digits * 2:digits * 3], 16) * factor, ) else: # We have no choice but to ask Tk what the rgb values are. rgb = root.winfo_rgb(colorName) if not asInt: rgb = (rgb[0] / _MAX_RGB, rgb[1] / _MAX_RGB, rgb[2] / _MAX_RGB) return rgb def _calcPalette(root, background=None, **kw): # Create a map that has the complete new palette. If some colors # aren't specified, compute them from other colors that are specified. new = {} for key, value in kw.items(): new[key] = value if background is not None: new['background'] = background if not new.has_key('background'): raise ValueError, 'must specify a background color' if not new.has_key('foreground'): new['foreground'] = 'black' bg = name2rgb(root, new['background']) fg = name2rgb(root, new['foreground']) for i in ('activeForeground', 'insertBackground', 'selectForeground', 'highlightColor'): if not new.has_key(i): new[i] = new['foreground'] if not new.has_key('disabledForeground'): newCol = average(bg, fg, 0.3) new['disabledForeground'] = rgb2name(newCol) if not new.has_key('highlightBackground'): new['highlightBackground'] = new['background'] # Set <lighterBg> to a color that is a little lighter that the # normal background. To do this, round each color component up by # 9% or 1/3 of the way to full white, whichever is greater. lighterBg = [] for i in range(3): lighterBg.append(bg[i]) inc1 = lighterBg[i] * 0.09 inc2 = (1.0 - lighterBg[i]) / 3 if inc1 > inc2: lighterBg[i] = lighterBg[i] + inc1 else: lighterBg[i] = lighterBg[i] + inc2 if lighterBg[i] > 1.0: lighterBg[i] = 1.0 # Set <darkerBg> to a color that is a little darker that the # normal background. darkerBg = (bg[0] * 0.9, bg[1] * 0.9, bg[2] * 0.9) if not new.has_key('activeBackground'): # If the foreground is dark, pick a light active background. # If the foreground is light, pick a dark active background. # XXX This has been disabled, since it does not look very # good with dark backgrounds. If this is ever fixed, the # selectBackground and troughColor options should also be fixed. if rgb2brightness(fg) < 0.5: new['activeBackground'] = rgb2name(lighterBg) else: new['activeBackground'] = rgb2name(lighterBg) if not new.has_key('selectBackground'): new['selectBackground'] = rgb2name(darkerBg) if not new.has_key('troughColor'): new['troughColor'] = rgb2name(darkerBg) if not new.has_key('selectColor'): new['selectColor'] = 'yellow' return new def spectrum(numColors, correction = 1.0, saturation = 1.0, intensity = 1.0, extraOrange = 1, returnHues = 0): colorList = [] division = numColors / 7.0 for index in range(numColors): if extraOrange: if index < 2 * division: hue = index / division else: hue = 2 + 2 * (index - 2 * division) / division hue = hue * _SIXTH_PI else: hue = index * _TWO_PI / numColors if returnHues: colorList.append(hue) else: rgb = hsi2rgb(hue, saturation, intensity) if correction != 1.0: rgb = correct(rgb, correction) name = rgb2name(rgb) colorList.append(name) return colorList def correct(rgb, correction): correction = float(correction) rtn = [] for index in range(3): rtn.append((1 - (1 - rgb[index]) ** correction) ** (1 / correction)) return rtn #============================================================================== def _recolorTree(widget, oldpalette, newcolors): # Change the colors in a widget and its descendants. # Change the colors in <widget> and all of its descendants, # according to the <newcolors> dictionary. It only modifies # colors that have their default values as specified by the # <oldpalette> variable. The keys of the <newcolors> dictionary # are named after widget configuration options and the values are # the new value for that option. for dbOption in newcolors.keys(): option = string.lower(dbOption) try: value = str(widget.cget(option)) except: continue if oldpalette is None or value == oldpalette[dbOption]: apply(widget.configure, (), {option : newcolors[dbOption]}) for child in widget.winfo_children(): _recolorTree(child, oldpalette, newcolors) def changecolor(widget, background=None, **kw): root = widget._root() if not hasattr(widget, '_Pmw_oldpalette'): widget._Pmw_oldpalette = getdefaultpalette(root) newpalette = apply(_calcPalette, (root, background,), kw) _recolorTree(widget, widget._Pmw_oldpalette, newpalette) widget._Pmw_oldpalette = newpalette def bordercolors(root, colorName): # This is the same method that Tk uses for shadows, in TkpGetShadows. lightRGB = [] darkRGB = [] for value in name2rgb(root, colorName, 1): value40pc = (14 * value) / 10 if value40pc > _MAX_RGB: value40pc = _MAX_RGB valueHalfWhite = (_MAX_RGB + value) / 2; lightRGB.append(max(value40pc, valueHalfWhite)) darkValue = (60 * value) / 100 darkRGB.append(darkValue) return ( '#%04x%04x%04x' % (lightRGB[0], lightRGB[1], lightRGB[2]), '#%04x%04x%04x' % (darkRGB[0], darkRGB[1], darkRGB[2]) )
Python
# This file is part of FlickFleck. # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import i18n import Tkinter import Pmw import wins import sys # simple window to display about and copyright information class About: def __init__(self, parent): self.parent = parent infotext = config.TITLE + ' version: ' + config.VERSION + \ '\n\nA tool to copy, rotate and rename' + \ '\ndigital camera jpeg files.' + \ '\n\nPython version: ' + sys.version + \ '\nPmw version: ' + Pmw.version() + \ '\nRunning on: ' + sys.platform + \ '\n\nhttp://flickfleck.googlecode.com/' self.w_dialog = Pmw.Dialog( parent, buttons = ('OK',), defaultbutton = 'OK', title = i18n.name['menu_about'] + ' ' + config.TITLE, command = self.button ) self.w_dialog.withdraw() self.w_notebook = Pmw.NoteBook( self.w_dialog.interior() ) self.w_notebook.pack( fill = 'both', expand = 1, padx = 2, pady = 2 ) self.addtab( 'Info', infotext ) self.addtab( 'Copyright', wins.COPYRIGHT ) self.addtab( 'Disclaimer', wins.DISCLAIMER ) self.addtab( 'Tools', wins.TOOLS ) self.addtab( 'Pmw', wins.PMW ) gpltab = self.w_notebook.add( 'GPLv3' ) gpl = Pmw.ScrolledText( gpltab, hscrollmode = 'none' ) gpl.importfile( 'GPL.txt' ) gpl.component('text').config( state = Tkinter.DISABLED ) gpl.pack( padx = 5, pady = 5, expand = 1 ) self.w_notebook.tab('Info').focus_set() self.w_notebook.setnaturalsize() def addtab( self, name, text ): tab = self.w_notebook.add( name ) label = Tkinter.Label( tab, text = text, pady = 10 ) label.pack( expand = 1, fill = 'both', padx = 2, pady = 2 ) def show(self): self.w_dialog.activate(geometry = 'centerscreenalways') def button(self, result): self.w_dialog.deactivate( result )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import Tkinter import Pmw import aboutwin import config import ui import i18n import progressbar class FlickFleck: # create all windows when object is made def __init__(self, parent): self.parent = parent self.w_about = aboutwin.About(parent) self.balloon = Pmw.Balloon( parent ) self.menubar = Pmw.MenuBar( parent, hull_relief = 'raised', hull_borderwidth = 1, balloon = self.balloon ) self.menubar.pack( fill = 'x' ) self.menubar.addmenu('File', None, text = i18n.name['menu_file'] ) self.menubar.addmenuitem('File', 'command', None, command = self.doquit, label =i18n.name['menu_file_exit'] ) self.button_about = Tkinter.Button( self.menubar.component('hull'), text = i18n.name['menu_about'] + '...', relief = 'flat', command = self.about ) self.button_about.pack(side='right') # self.balloon.bind( self.button_about, 'About') self.w_from = Pmw.Group( parent, tag_text = i18n.name['label_copyfrom'] ) self.w_from.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.w_fromlabel = Tkinter.Label( self.w_from.interior(), text = config.fromdir, pady = 10 ) self.w_fromlabel.pack( side = 'left', padx = 5, pady = 2 ) self.w_to = Pmw.Group( parent, tag_text = i18n.name['label_copyto'] ) self.w_to.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.w_tolabel = Tkinter.Label( self.w_to.interior(), text = config.todir ) self.w_tolabel.pack( side = 'left', padx = 5, pady = 2 ) # --- start n stop buttons --- self.w_buttons = Pmw.ButtonBox( parent ) # frame_borderwidth = 2, # frame_relief = 'groove' ) self.w_buttons.pack( fill = 'both', expand = 1, padx = 10, pady = 10 ) self.w_buttons.add( 'Start', command = self.start, text = i18n.name['button_start'] ) self.w_buttons.add( 'Stop', command = self.stop, text = i18n.name['button_stop'] ) self.w_buttons.setdefault('Start') parent.bind('<Return>', self._processReturnKey) self.w_buttons.alignbuttons() self.w_buttons.button('Stop').config(state = Tkinter.DISABLED) # --- progressbar --- # self.w_pb = Pmw.LabeledWidget( parent, labelpos = "nw", # label_text = "" ) self.w_pb = Pmw.ScrolledCanvas( parent, borderframe = 0, usehullsize = 1, hscrollmode = 'none', vscrollmode = 'none', hull_height = ui.wins.PBheight ) self.w_pb.component('hull').configure(relief='sunken', borderwidth=2) self.w_pb.pack( padx=5, pady=5, expand='yes', fill = 'x') self.w_pbw = progressbar.Widget( self.w_pb.interior() ) ui.wins.pb = self.w_pbw self.w_status = Pmw.MessageBar( parent, entry_relief = 'groove', labelpos = 'w', label_text = i18n.name['label_status'] + ' ') self.w_status.silent = True self.w_status.message('state', i18n.name['status_idle'] ) self.w_status.pack( fill = 'x', padx = 2, pady = 1, side = 'bottom' ) # self.balloon.configure( statuscommand = self.w_status.helpmessage ) #-- set message in the statusrow def status(self, msg_str, type = 'state'): self.w_status.message(type, msg_str) ui.wins.root.update() #-- user pressed 'start' def start(self): self.w_buttons.button(1).config(state = Tkinter.NORMAL) self.w_buttons.button(0).config(state = Tkinter.DISABLED) ui.wins.requestStop = False ui.wins.engine.start() #-- user pressed 'cancel' def stop(self): # self.w_buttons.button(0).config(state = Tkinter.NORMAL) self.w_buttons.button(1).config(state = Tkinter.DISABLED) # stopping is only noted, engine will stop when it notices value change ui.wins.requestStop = True #-- user pressed Enter def _processReturnKey(self, event): self.w_buttons.invoke() #-- quit selected in file-menu def doquit(self): self.parent.quit() #-- about button pressed def about(self): return self.w_about.show()
Python
# -*- coding: latin-1 -*- root = None main = None # Progressbar graphics height PBheight = 30 requestStop = False DISCLAIMER = """ THIS SOFTWARE IS PROVIDED BY Jyke Jokinen ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Jyke Jokinen BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ COPYRIGHT = """ Copyright (C) 2008 Jyke Tapani Jokinen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may not use this software except in compliance with the License. Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ PMW = """ Pmw copyright Copyright 1997-1999 Telstra Corporation Limited, Australia Copyright 2000-2002 Really Good Software Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ TOOLS = """ FlickFleck uses these external programs: Python megawidgets (http://pmw.sourceforge.net/) Jpegtran (http://sylvana.net/jpegcrop/jpegtran/) ExifTool (http://www.sno.phy.queensu.ca/~phil/exiftool/) """
Python
# Python interface to some of the commands of the 2.4 version of the # BLT extension to tcl. import string import types import Tkinter # Supported commands: _busyCommand = '::blt::busy' _vectorCommand = '::blt::vector' _graphCommand = '::blt::graph' _testCommand = '::blt::*' _chartCommand = '::blt::stripchart' _tabsetCommand = '::blt::tabset' _haveBlt = None _haveBltBusy = None def _checkForBlt(window): global _haveBlt global _haveBltBusy # Blt may be a package which has not yet been loaded. Try to load it. try: window.tk.call('package', 'require', 'BLT') except Tkinter.TclError: # Another way to try to dynamically load blt: try: window.tk.call('load', '', 'Blt') except Tkinter.TclError: pass _haveBlt= (window.tk.call('info', 'commands', _testCommand) != '') _haveBltBusy = (window.tk.call('info', 'commands', _busyCommand) != '') def haveblt(window): if _haveBlt is None: _checkForBlt(window) return _haveBlt def havebltbusy(window): if _haveBlt is None: _checkForBlt(window) return _haveBltBusy def _loadBlt(window): if _haveBlt is None: if window is None: window = Tkinter._default_root if window is None: window = Tkinter.Tk() _checkForBlt(window) def busy_hold(window, cursor = None): _loadBlt(window) if cursor is None: window.tk.call(_busyCommand, 'hold', window._w) else: window.tk.call(_busyCommand, 'hold', window._w, '-cursor', cursor) def busy_release(window): _loadBlt(window) window.tk.call(_busyCommand, 'release', window._w) def busy_forget(window): _loadBlt(window) window.tk.call(_busyCommand, 'forget', window._w) #============================================================================= # Interface to the blt vector command which makes it look like the # builtin python list type. # The -variable, -command, -watchunset creation options are not supported. # The dup, merge, notify, offset, populate, seq and variable methods # and the +, -, * and / operations are not supported. # Blt vector functions: def vector_expr(expression): tk = Tkinter._default_root.tk strList = tk.splitlist(tk.call(_vectorCommand, 'expr', expression)) return tuple(map(string.atof, strList)) def vector_names(pattern = None): tk = Tkinter._default_root.tk return tk.splitlist(tk.call(_vectorCommand, 'names', pattern)) class Vector: _varnum = 0 def __init__(self, size=None, master=None): # <size> can be either an integer size, or a string "first:last". _loadBlt(master) if master: self._master = master else: self._master = Tkinter._default_root self.tk = self._master.tk self._name = 'PY_VEC' + str(Vector._varnum) Vector._varnum = Vector._varnum + 1 if size is None: self.tk.call(_vectorCommand, 'create', self._name) else: self.tk.call(_vectorCommand, 'create', '%s(%s)' % (self._name, size)) def __del__(self): self.tk.call(_vectorCommand, 'destroy', self._name) def __str__(self): return self._name def __repr__(self): return '[' + string.join(map(str, self), ', ') + ']' def __cmp__(self, list): return cmp(self[:], list) def __len__(self): return self.tk.getint(self.tk.call(self._name, 'length')) def __getitem__(self, key): oldkey = key if key < 0: key = key + len(self) try: return self.tk.getdouble(self.tk.globalgetvar(self._name, str(key))) except Tkinter.TclError: raise IndexError, oldkey def __setitem__(self, key, value): if key < 0: key = key + len(self) return self.tk.globalsetvar(self._name, str(key), float(value)) def __delitem__(self, key): if key < 0: key = key + len(self) return self.tk.globalunsetvar(self._name, str(key)) def __getslice__(self, start, end): length = len(self) if start < 0: start = 0 if end > length: end = length if start >= end: return [] end = end - 1 # Blt vector slices include end point. text = self.tk.globalgetvar(self._name, str(start) + ':' + str(end)) return map(self.tk.getdouble, self.tk.splitlist(text)) def __setslice__(self, start, end, list): if start > end: end = start self.set(self[:start] + list + self[end:]) def __delslice__(self, start, end): if start < end: self.set(self[:start] + self[end:]) def __add__(self, list): return self[:] + list def __radd__(self, list): return list + self[:] def __mul__(self, n): return self[:] * n __rmul__ = __mul__ # Python builtin list methods: def append(self, *args): self.tk.call(self._name, 'append', args) def count(self, obj): return self[:].count(obj) def index(self, value): return self[:].index(value) def insert(self, index, value): self[index:index] = [value] def remove(self, value): del self[self.index(value)] def reverse(self): s = self[:] s.reverse() self.set(s) def sort(self, *args): s = self[:] s.sort() self.set(s) # Blt vector instance methods: # append - same as list method above def clear(self): self.tk.call(self._name, 'clear') def delete(self, *args): self.tk.call((self._name, 'delete') + args) def expr(self, expression): self.tk.call(self._name, 'expr', expression) def length(self, newSize=None): return self.tk.getint(self.tk.call(self._name, 'length', newSize)) def range(self, first, last=None): # Note that, unlike self[first:last], this includes the last # item in the returned range. text = self.tk.call(self._name, 'range', first, last) return map(self.tk.getdouble, self.tk.splitlist(text)) def search(self, start, end=None): return self._master._getints(self.tk.call( self._name, 'search', start, end)) def set(self, list): if type(list) != types.TupleType: list = tuple(list) self.tk.call(self._name, 'set', list) # The blt vector sort method has different semantics to the python # list sort method. Call these blt_sort: def blt_sort(self, *args): self.tk.call((self._name, 'sort') + args) def blt_sort_reverse(self, *args): self.tk.call((self._name, 'sort', '-reverse') + args) # Special blt vector indexes: def min(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'min')) def max(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'max')) # Method borrowed from Tkinter.Var class: def get(self): return self[:] #============================================================================= # This is a general purpose configure routine which can handle the # configuration of widgets, items within widgets, etc. Supports the # forms configure() and configure('font') for querying and # configure(font = 'fixed', text = 'hello') for setting. def _doConfigure(widget, subcommand, option, kw): if not option and not kw: # Return a description of all options. ret = {} options = widget.tk.splitlist(widget.tk.call(subcommand)) for optionString in options: optionInfo = widget.tk.splitlist(optionString) option = optionInfo[0][1:] ret[option] = (option,) + optionInfo[1:] return ret if option: # Return a description of the option given by <option>. if kw: # Having keywords implies setting configuration options. # Can't set and get in one command! raise ValueError, 'cannot have option argument with keywords' option = '-' + option optionInfo = widget.tk.splitlist(widget.tk.call(subcommand + (option,))) return (optionInfo[0][1:],) + optionInfo[1:] # Otherwise, set the given configuration options. widget.tk.call(subcommand + widget._options(kw)) #============================================================================= class Graph(Tkinter.Widget): # Wrapper for the blt graph widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _graphCommand, cnf, kw) def bar_create(self, name, **kw): self.tk.call((self._w, 'bar', 'create', name) + self._options(kw)) def line_create(self, name, **kw): self.tk.call((self._w, 'line', 'create', name) + self._options(kw)) def extents(self, item): return self.tk.getint(self.tk.call(self._w, 'extents', item)) def invtransform(self, winX, winY): return self._getdoubles( self.tk.call(self._w, 'invtransform', winX, winY)) def inside(self, x, y): return self.tk.getint(self.tk.call(self._w, 'inside', x, y)) def snap(self, photoName): self.tk.call(self._w, 'snap', photoName) def transform(self, x, y): return self._getdoubles(self.tk.call(self._w, 'transform', x, y)) def axis_cget(self, axisName, key): return self.tk.call(self._w, 'axis', 'cget', axisName, '-' + key) def axis_configure(self, axes, option=None, **kw): # <axes> may be a list of axisNames. if type(axes) == types.StringType: axes = [axes] subcommand = (self._w, 'axis', 'configure') + tuple(axes) return _doConfigure(self, subcommand, option, kw) def axis_create(self, axisName, **kw): self.tk.call((self._w, 'axis', 'create', axisName) + self._options(kw)) def axis_delete(self, *args): self.tk.call((self._w, 'axis', 'delete') + args) def axis_invtransform(self, axisName, value): return self.tk.getdouble(self.tk.call( self._w, 'axis', 'invtransform', axisName, value)) def axis_limits(self, axisName): return self._getdoubles(self.tk.call( self._w, 'axis', 'limits', axisName)) def axis_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'axis', 'names') + args)) def axis_transform(self, axisName, value): return self.tk.getint(self.tk.call( self._w, 'axis', 'transform', axisName, value)) def xaxis_cget(self, key): return self.tk.call(self._w, 'xaxis', 'cget', '-' + key) def xaxis_configure(self, option=None, **kw): subcommand = (self._w, 'xaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def xaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'xaxis', 'invtransform', value)) def xaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'xaxis', 'limits')) def xaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'xaxis', 'transform', value)) def xaxis_use(self, axisName = None): return self.tk.call(self._w, 'xaxis', 'use', axisName) def x2axis_cget(self, key): return self.tk.call(self._w, 'x2axis', 'cget', '-' + key) def x2axis_configure(self, option=None, **kw): subcommand = (self._w, 'x2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def x2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'x2axis', 'invtransform', value)) def x2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'x2axis', 'limits')) def x2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'x2axis', 'transform', value)) def x2axis_use(self, axisName = None): return self.tk.call(self._w, 'x2axis', 'use', axisName) def yaxis_cget(self, key): return self.tk.call(self._w, 'yaxis', 'cget', '-' + key) def yaxis_configure(self, option=None, **kw): subcommand = (self._w, 'yaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def yaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'yaxis', 'invtransform', value)) def yaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'yaxis', 'limits')) def yaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'yaxis', 'transform', value)) def yaxis_use(self, axisName = None): return self.tk.call(self._w, 'yaxis', 'use', axisName) def y2axis_cget(self, key): return self.tk.call(self._w, 'y2axis', 'cget', '-' + key) def y2axis_configure(self, option=None, **kw): subcommand = (self._w, 'y2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def y2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'y2axis', 'invtransform', value)) def y2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'y2axis', 'limits')) def y2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'y2axis', 'transform', value)) def y2axis_use(self, axisName = None): return self.tk.call(self._w, 'y2axis', 'use', axisName) def crosshairs_cget(self, key): return self.tk.call(self._w, 'crosshairs', 'cget', '-' + key) def crosshairs_configure(self, option=None, **kw): subcommand = (self._w, 'crosshairs', 'configure') return _doConfigure(self, subcommand, option, kw) def crosshairs_off(self): self.tk.call(self._w, 'crosshairs', 'off') def crosshairs_on(self): self.tk.call(self._w, 'crosshairs', 'on') def crosshairs_toggle(self): self.tk.call(self._w, 'crosshairs', 'toggle') def element_activate(self, name, *args): self.tk.call((self._w, 'element', 'activate', name) + args) def element_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'element', 'bind', tagName), sequence, func, add) def element_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'element', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def element_cget(self, name, key): return self.tk.call(self._w, 'element', 'cget', name, '-' + key) def element_closest(self, x, y, *args, **kw): var = 'python_private_1' success = self.tk.getint(self.tk.call( (self._w, 'element', 'closest', x, y, var) + self._options(kw) + args)) if success: rtn = {} rtn['dist'] = self.tk.getdouble(self.tk.globalgetvar(var, 'dist')) rtn['x'] = self.tk.getdouble(self.tk.globalgetvar(var, 'x')) rtn['y'] = self.tk.getdouble(self.tk.globalgetvar(var, 'y')) rtn['index'] = self.tk.getint(self.tk.globalgetvar(var, 'index')) rtn['name'] = self.tk.globalgetvar(var, 'name') return rtn else: return None def element_configure(self, names, option=None, **kw): # <names> may be a list of elemNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'element', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def element_deactivate(self, *args): self.tk.call((self._w, 'element', 'deactivate') + args) def element_delete(self, *args): self.tk.call((self._w, 'element', 'delete') + args) def element_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'element', 'exists', name)) def element_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'element', 'names') + args)) def element_show(self, nameList=None): if nameList is not None: nameList = tuple(nameList) return self.tk.splitlist( self.tk.call(self._w, 'element', 'show', nameList)) def element_type(self, name): return self.tk.call(self._w, 'element', 'type', name) def grid_cget(self, key): return self.tk.call(self._w, 'grid', 'cget', '-' + key) def grid_configure(self, option=None, **kw): subcommand = (self._w, 'grid', 'configure') return _doConfigure(self, subcommand, option, kw) def grid_off(self): self.tk.call(self._w, 'grid', 'off') def grid_on(self): self.tk.call(self._w, 'grid', 'on') def grid_toggle(self): self.tk.call(self._w, 'grid', 'toggle') def legend_activate(self, *args): self.tk.call((self._w, 'legend', 'activate') + args) def legend_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'legend', 'bind', tagName), sequence, func, add) def legend_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'legend', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def legend_cget(self, key): return self.tk.call(self._w, 'legend', 'cget', '-' + key) def legend_configure(self, option=None, **kw): subcommand = (self._w, 'legend', 'configure') return _doConfigure(self, subcommand, option, kw) def legend_deactivate(self, *args): self.tk.call((self._w, 'legend', 'deactivate') + args) def legend_get(self, pos): return self.tk.call(self._w, 'legend', 'get', pos) def pen_cget(self, name, key): return self.tk.call(self._w, 'pen', 'cget', name, '-' + key) def pen_configure(self, names, option=None, **kw): # <names> may be a list of penNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'pen', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def pen_create(self, name, **kw): self.tk.call((self._w, 'pen', 'create', name) + self._options(kw)) def pen_delete(self, *args): self.tk.call((self._w, 'pen', 'delete') + args) def pen_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'pen', 'names') + args)) def postscript_cget(self, key): return self.tk.call(self._w, 'postscript', 'cget', '-' + key) def postscript_configure(self, option=None, **kw): subcommand = (self._w, 'postscript', 'configure') return _doConfigure(self, subcommand, option, kw) def postscript_output(self, fileName=None, **kw): prefix = (self._w, 'postscript', 'output') if fileName is None: return self.tk.call(prefix + self._options(kw)) else: self.tk.call(prefix + (fileName,) + self._options(kw)) def marker_after(self, first, second=None): self.tk.call(self._w, 'marker', 'after', first, second) def marker_before(self, first, second=None): self.tk.call(self._w, 'marker', 'before', first, second) def marker_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'marker', 'bind', tagName), sequence, func, add) def marker_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'marker', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def marker_cget(self, name, key): return self.tk.call(self._w, 'marker', 'cget', name, '-' + key) def marker_configure(self, names, option=None, **kw): # <names> may be a list of markerIds. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'marker', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def marker_create(self, type, **kw): return self.tk.call( (self._w, 'marker', 'create', type) + self._options(kw)) def marker_delete(self, *args): self.tk.call((self._w, 'marker', 'delete') + args) def marker_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'marker', 'exists', name)) def marker_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'marker', 'names') + args)) def marker_type(self, name): type = self.tk.call(self._w, 'marker', 'type', name) if type == '': type = None return type #============================================================================= class Stripchart(Graph): # Wrapper for the blt stripchart widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _chartCommand, cnf, kw) #============================================================================= class Tabset(Tkinter.Widget): # Wrapper for the blt TabSet widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _tabsetCommand, cnf, kw) def activate(self, tabIndex): self.tk.call(self._w, 'activate', tabIndex) # This is the 'bind' sub-command: def tag_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'bind', tagName), sequence, func, add) def tag_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def delete(self, first, last = None): self.tk.call(self._w, 'delete', first, last) # This is the 'focus' sub-command: def tab_focus(self, tabIndex): self.tk.call(self._w, 'focus', tabIndex) def get(self, tabIndex): return self.tk.call(self._w, 'get', tabIndex) def index(self, tabIndex): index = self.tk.call(self._w, 'index', tabIndex) if index == '': return None else: return self.tk.getint(self.tk.call(self._w, 'index', tabIndex)) def insert(self, position, name1, *names, **kw): self.tk.call( (self._w, 'insert', position, name1) + names + self._options(kw)) def invoke(self, tabIndex): return self.tk.call(self._w, 'invoke', tabIndex) def move(self, tabIndex1, beforeOrAfter, tabIndex2): self.tk.call(self._w, 'move', tabIndex1, beforeOrAfter, tabIndex2) def nearest(self, x, y): return self.tk.call(self._w, 'nearest', x, y) def scan_mark(self, x, y): self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): self.tk.call(self._w, 'see', index) def see(self, tabIndex): self.tk.call(self._w,'see',tabIndex) def size(self): return self.tk.getint(self.tk.call(self._w, 'size')) def tab_cget(self, tabIndex, option): if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tab', 'cget', tabIndex, option) def tab_configure(self, tabIndexes, option=None, **kw): # <tabIndexes> may be a list of tabs. if type(tabIndexes) in (types.StringType, types.IntType): tabIndexes = [tabIndexes] subcommand = (self._w, 'tab', 'configure') + tuple(tabIndexes) return _doConfigure(self, subcommand, option, kw) def tab_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'tab', 'names') + args)) def tab_tearoff(self, tabIndex, newName = None): if newName is None: name = self.tk.call(self._w, 'tab', 'tearoff', tabIndex) return self.nametowidget(name) else: self.tk.call(self._w, 'tab', 'tearoff', tabIndex, newName) def view(self): s = self.tk.call(self._w, 'view') return tuple(map(self.tk.getint, self.tk.splitlist(s))) def view_moveto(self, fraction): self.tk.call(self._w, 'view', 'moveto', fraction) def view_scroll(self, number, what): self.tk.call(self._w, 'view', 'scroll', number, what)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # # import exifrotate import exifdatename # # rotates the file using jpegtran if orientation is not horizontal # def rotate( filename ): exifrotate.rotate( filename ) # # return (newdir, newname) tuple based on the EXIF createdate infromation # def newname( filename ): return exifdatename.newname( filename )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os.path from subprocess import Popen, PIPE from fileops import quotepath def eqlen( str ): if len(str) == 1: str = "0" + str return str # ----------------------------------------------------------------------- # return ('<year>/<month>', <datename>') tuple based on files EXIF date # def newname( filename ): # --a no duplicate tags # -f force printing of tags even if values are not found # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -CreateDate " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() # parse createdate values (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "problem running exiftool (%s)" % filename ) if str.strip().lower() != "create date": ui.ERR( "exiftool: createdate not found (%s)" % filename ) try: (date,time) = data.strip().split(' ') (year,mon,day) = date.split(':') mon = eqlen( mon ) day = eqlen( day ) (hour,min,sec) = time.split(':') hour = eqlen( hour ) min = eqlen( min ) sec = eqlen( sec ) except: ui.ERR( "problem parsing EXIF date (%s)" % data) newdir = year + os.path.sep + mon newname = "%s%s%s-%s%s%s" % (year,mon,day,hour,min,sec) return (newdir, newname)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os, os.path import tempfile from subprocess import Popen, PIPE from fileops import copy, quotepath # # map orientation values to jpegtran commands to make the pic right # data is from # http://sylvana.net/jpegcrop/exif_orientation.html TRANS = [ [ "" ], # not in use [ "" ], [ "-flip horizontal" ], [ "-rotate 180 -trim" ], [ "-flip vertical" ], [ "-transpose" ], [ "-rotate 90 -trim" ], [ "-transverse" ], [ "-rotate 90 -trim", "-rotate 180 -trim" ] ] # -------------------------------------------------------------------- def rotate( filename ): dir = os.path.dirname( filename ) file = os.path.basename( filename ) # --a no duplicate tags # -f force printing of tags even if values are not found (0 is unknown) # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -Orientation " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (read orientation1) (%s)" % filename ) # parse orientation (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "exception in exiftool (read orientation2) (%s)" % filename ) if str.strip().lower() != "orientation": ui.ERR( "exiftool: orientation not found (%s)" % str ) orientation = int( data.strip() ) if orientation > 8: ui.ERR( "orientation out of range (%d,%s)" % (orientation, filename) ) # 0 : unknown orientation -> do not touch # 1 : horizontal orientation -> no need to rotate if orientation == 0 or orientation == 1: return # # execute rotation operations defined in table 'TRANS' # rotations are written to a new file which is copied to the # original file in the last step # fromfile = filename tmpfiles = [] for op in TRANS[ orientation ]: (fd, tmp) = tempfile.mkstemp( '', '', dir ) os.close(fd) # XXX: closing tmpfile and using the filename creates a race condition # but target is usually in users subdirectory and this program is usually # run in a personal computer, so risk should be minimal/acceptable tmpfiles.append( tmp ) # record name for cleanup later # -copy all preserves original EXIF information rot_cmd = config.jpegtran + " -copy all -outfile " \ + quotepath(tmp) + " " + op + " " + quotepath(fromfile) try: pipe = Popen( rot_cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running jpegtran (%s)" % fromfile ) except: ui.ERR("exception in jpegtran (%s)" % rot_cmd ) fromfile = tmp # endfor # move the last resultfile into original name if fromfile != filename: try: os.remove( filename ) os.rename( fromfile, filename ) except: ui.ERR("error finalizing jpegtran (%s)" % filename ) # rotation should have made the picture into 'horizontal' orientation so # change the orientation EXIF info to match that cmd = config.exiftool + " -overwrite_original_in_place -n -Orientation=1 " \ + quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (set orientation) (%s)" % filename ) except: ui.ERR( "exception in exiftool (set orientation) (%s)" % filename ) # remove any tempfiles still present in the filesystem for f in tmpfiles: if os.path.exists( f ): try: os.remove( f ) except: ui.ERR("cannot remove tempfile (%s)" % f )
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
from distutils.core import setup import py2exe opts = { "py2exe": { # i18n languages are loaded at runtime so py2exe won't find em "includes": "i18n.finnish, i18n.english", "optimize" : 2, # "bundle_files" : 1, # does not seem to work in my env "dist_dir": "packaging/windows", } } setup(name = "flickfleck", version = "0.9.1", author = "Jyke Tapani Jokinen", author_email = "jyke.t.jokinen(at)gmail.com", # packages = ["ui", "jpegops"], data_files =[('', ['GPL.txt', 'config.txt', 'flickfleck.ico']), ('tools', ['tools/jpegtran.exe', 'tools/exiftool.exe']) ], url = 'http://flickfleck.googlecode.com/', download_url = 'http://flickfleck.googlecode.com/', options = opts, windows=[{"script": 'flickfleck.py', "icon_resources" : [(1, "flickfleck.ico")], }])
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import i18n if __name__=='__main__': print i18n.name['Start']
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import ui import engine if __name__=='__main__': ui.wins.engine.init() print ui.wins.engine.jpegtran print ui.wins.engine.exiftool
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import jpegops if __name__=='__main__': if len(sys.argv) < 2: print "Usage: %s <jpg files>" % sys.argv[0] else: for file in sys.argv[1:]: jpegops.rotate( file )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import ui from copier import PhotoCopier ui.wins.engine = PhotoCopier()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import sys, os, os.path import ui import types import fnmatch import i18n import jpegops import fileops from subprocess import Popen, PIPE class PhotoCopier: def __init__(self): pass def init(self): # what external binary to use cmd_j = self.findexe( config.jpegtran ) cmd_e = self.findexe( config.exiftool ) # how to execute the binary if sys.platform == 'win32': # 'call' found in bugs.python.org/issue1524 config.jpegtran = 'call ' + fileops.quotepath( cmd_j ) config.exiftool = 'call ' + fileops.quotepath( cmd_e ) else: config.jpegtran = cmd_j config.exiftool = cmd_e self.init_filelist() # # called at program startup # def init_filelist(self): # # find all jpeg-files # fromdir can be a list of directories (all are scanned) # self._frompaths = [] if type(config.fromdir) == types.ListType: for dir in config.fromdir: self.addsourcefiles(dir) else: self.addsourcefiles(config.fromdir) # tell number of found files to the user and the progressbar numitems = len(self._frompaths) ui.status( i18n.name['status_found'] + " " + str( numitems ) + " " + i18n.name['status_files'] ) ui.wins.pb.init( numitems ) # finds all jpegs under 'dir' # definition of a jpeg is config.jpegglob def addsourcefiles(self, dir): for root,dirs,files in os.walk( dir ): if len(files) == 0: continue for filt in config.jpegglob: found = fnmatch.filter( files, filt ) if len(found) > 0: for name in found: self._frompaths.append( os.path.join( root, name ) ) # ---------------------------------------------------------------------- def findexe(self, programname): # if an absolute pathname is configured, use that: if os.path.isabs( programname ): return programname # # if the executable is found in FlickFlecks binary dir, use that # tool = config.installdir + os.sep + config.bindir \ + os.sep + programname if os.access( tool, os.X_OK ): return tool # # if we can execute the program then it's in the path, use that # else: cmd = programname + " NOSUCHFILEEXITS" pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) pipe.wait() # # on Windows only 0 means we could execute the program # (XXX: these test are ad hoc, traversing PATH would be better) if sys.platform == 'win32': if pipe.returncode == 0: return programname # # on UNIX we can execute the program and it can give 1 as error # return code (bad parameter) # elif 0 <= pipe.returncode <= 1: return programname ui.ERR( ("cannot find executable %s" % programname) ) # ---------------------------------------------------------------------- # user started the operations # def start(self): if len( self._frompaths) == 0: ui.ERR("No files to copy") from fileops import copy dst = config.todir if not os.path.exists( dst ): ui.ERR("Target directory (%s) does not exists" % dst) self._newnames = [] # -------- copy files to new location and name --------------- ui.status( i18n.name['status_copying'] ) ui.wins.pb.clear() # reset progressbar for src in self._frompaths: (newdir,newname) = jpegops.newname( src ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # step progressbar targetNOTok = True silentskip = False counter = 0 # if the targetfilename already exists, increase the counter # and add it to the generated filename # loop until unique name is found while targetNOTok: if config.targetdirs == True: to = dst + os.path.sep + newdir + os.path.sep + newname else: to = dst + os.path.sep + newname if counter > 0: to += "-" + str(counter) to += ".jpg" if os.access( to, os.F_OK ): if hasattr(config, 'silentskip'): silentskip = True targetNOTok = False if counter > 999: ui.ERR( "cannot transfer file: %s" % src ) counter = counter + 1 else: targetNOTok = False # end while if silentskip: continue # make target subdirs if not already made if config.targetdirs == True: path = dst + os.path.sep for dir in newdir.split( os.path.sep ): path += dir + os.path.sep if not os.path.exists( path ): os.mkdir( path ) # save the targetfilename for rotation operations self._newnames.append( to ) copy( src, to ) # ------------ rotate files ------------- ui.status( i18n.name['status_rotating'] ) ui.wins.pb.clear() # reset progressbar for file in self._newnames: jpegops.rotate( file ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # update progressbar ui.status( i18n.name['status_done'] ) ui.Ready()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config name = {} # config.LANGUAGE is used as a module name to import # an object/hash named Text() from that module should contain # localized strings # XXX: should really use gettext and http://translationproject.org # or similar service def init(): global name mod = __import__( config.LANGUAGE, globals(), locals() ) name = mod.Text()
Python
class Text: def __init__(self): self.d = { 'apperror' : 'Application error', 'finished' : 'Files copied successfully.', 'appclose' : 'This application will now close', 'menu_file' : 'File', 'menu_file_fromdir' : 'Select picture folder (fromdir)', 'menu_file_todir' : 'Select target folder (todir)', 'menu_file_config' : 'Edit configuration', 'menu_file_exit' : 'Exit', 'menu_about' : 'About...', 'label_copyfrom' : 'Copy files from:', 'label_copyto' : 'To:', 'label_status' : 'Status:', 'button_start' : 'Start', 'button_stop' : 'Cancel', 'status_idle' : 'Idle', 'status_done' : 'Done', 'status_found' : 'Found', 'status_files' : 'files', 'status_copying' : 'Copying files...', 'status_rotating' : 'Rotating files...' } def __getitem__(self, name): if name != None: try: retval = self.d[name] except: retval = 'i18n ERROR (%s)' % name return retval
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys import config import ui import os, os.path import sys # # read a configuration file and set values to config-module # def readconfig( file, mod ): try: f = open( file ) for line in f.readlines(): line = line.strip() if len(line) < 1: continue # skip blank lines if line[0] == '#': continue # comment lines try: name, val = line.split('=', 1) setattr( mod, name.strip(), eval( val.strip() ) ) except ValueError: ui.ERR( "Unknown line in config-file (%s)" % line ) f.close() # any error in processing config datafile is silently ignored # (defaults are used instead) except IOError: pass # # called at program startup to initialize the configuration # def init(): mod = sys.modules['config'] readconfig( 'config.txt', mod ) readconfig( 'config.local', mod ) if sys.platform == 'darwin': readconfig( _mac_confpath(), mod ) # executables if not hasattr( mod, 'jpegtran' ): if sys.platform == 'win32': setattr(mod, 'jpegtran', "jpegtran.exe") else: setattr(mod, 'jpegtran', "jpegtran" ) if not hasattr( mod, 'exiftool' ): if sys.platform == 'win32': setattr(mod, 'exiftool', "exiftool.exe" ) else: setattr(mod, 'exiftool', "exiftool" ) # these cannot be set in the configuration file setattr(mod, 'TITLE', 'FlickFleck') setattr(mod, 'VERSION', '1.0') # if program was started with a parameter, use that as fromdir if len(sys.argv) > 1: setattr(mod, 'fromdir', sys.argv[1]) # try to sanitize the filepath values import os.path setattr(mod, 'fromdir', os.path.normpath( config.fromdir ) ) setattr(mod, 'todir' , os.path.normpath( config.todir ) ) if sys.platform == 'darwin': mac_initconfig() # location where we want to store config in macosX def _mac_confpath(): if sys.platform == 'darwin': return os.environ["HOME"] + "/Library/Preferences/FlickFleck.txt" else: return "NOSUCHFILE" # should not happen, but wont raise error here # if we don't have a config in Preferences (macosX) go and create it def mac_initconfig(): if sys.platform == 'darwin': if not os.path.exists( _mac_confpath() ): import shutil shutil.copy( config.installdir + "/config.txt", _mac_confpath() ) # simple way to allow user to edit the config (macosX) def mac_editconfig(): if sys.platform == 'darwin': # I'm real happy that macosX will find the editor for me os.system( "open " + _mac_confpath() )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import os, os.path import sys import shutil import ui # ------------------------------------------------------------------------ # in win32 add quotes around path (there can be spaces in names) # XXX: spaces in filepaths should be worked out int UNIX too def quotepath( path ): if sys.platform == 'win32': return '"' + path + '"' else: return path # ------------------------------------------------------------------------ # stops if we cannot access the named file def verify_access( file ): if not os.access( file, os.F_OK ): ui.ERR( "fileops.access: %s: access denied" % file ) # ------------------------------------------------------------------------ # tries to do a safe copy from 'orig_file' to 'new_file' # def copy( orig_file, new_file ): f_from = os.path.normpath( orig_file ) f_to = os.path.normpath( new_file ) # if copying to itself if f_from == f_to: ui.ERR( "fileops.copy: copying a file to itself? (%s)" % f_from ) # we should be able to access fromfile verify_access( f_from ) # target should not exists (caller should make sure of this) if os.path.exists( f_to ): ui.ERR( "fileops.copy: target file exists (%s)" % f_to ) try: shutil.copy2( f_from, f_to ) # preserves attributes except: ui.ERR("fileops.copy: copy2 operation failed (%s)" % f_from) # do some sanity checks to the file we just created verify_access( f_to ) if os.path.getsize( f_to ) < 1: ui.ERR("fileops.copy: target filesize zero (%s)" % f_to ) # # debug/testing # if __name__ == '__main__': import sys import tempfile sys.path.insert("..") filename1 = tempfile.mktemp (".txt") open (filename1, "w").close () filename2 = filename1 + ".copy" print filename1, "=>", filename2 copy( filename1, filename2 )
Python
# # Default configuration for FlickFleck # fromdir = 'tests' todir = '/tmp' # create target subdirs (year/month) targetdirs = True # languages are defined in moduledir: i18n # every language module must also be listed in setup.py LANGUAGE = "english" # what files to process: jpegglob = [ "*.jpg", "*.jpeg" ] # SVN version SVNversion=" $Id: config.py 65 2008-11-27 09:43:11Z jyke.t.jokinen $ " # installdir will be overwritten at startup (flickfleck install location) installdir = "" # bindir can contain external tools (if not in path) bindir = "tools"
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import Tkinter import ui # adhoc widget to make a progressbar # class Widget: def __init__(self, parent): self.w_parent = parent self.w_canvas = Tkinter.Canvas( parent ) self.w_canvas.pack( fill='x', expand='yes') # called when the number of items in the whole operation is known def init(self, num_items): self.max = num_items self.clear() # called if starting again with the same max value def clear(self): self.count = 0 self.w_canvas.delete(Tkinter.ALL) # draw one step forward in the progressbar (previously set max value used) def step(self): self.count = self.count + 1 width = int( self.w_canvas['width'] ) # if one_item_width < 1.0 it would go to zero with ints: one_item = float(width) / float(self.max) draw_width = one_item * self.count self.w_canvas.delete(Tkinter.ALL) self.w_canvas.create_rectangle(0,0, draw_width,ui.wins.PBheight, fill='blue') self.w_parent.update()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import tkMessageBox import sys import wins import mainwin import i18n #----------------------------------------------------------------- # show error message and close the application # def ERR( str ): tkMessageBox.showerror(i18n.name['apperror'], str + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- # all done. this version closes application after this # def Ready(): tkMessageBox.showinfo(config.TITLE, i18n.name['finished'] + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- def status( str ): wins.main.status( str ) #----------------------------------------------------------------- # called at program startup # creates all windows # def init(): wins.root = Pmw.initialise( fontScheme = 'pmw1' ) wins.root.withdraw() if sys.platform == 'darwin' and hasattr(sys, 'frozen'): wins.root.tk.call('console', 'hide') wins.root.title( config.TITLE ) if sys.platform == 'win32': wins.root.iconbitmap('flickfleck.ico') elif sys.platform == 'darwin': grey="#CCCCCC" wins.root.config(background=grey, highlightbackground=grey) # wins.root.option_add( "*background", grey ) # wins.root.option_add( "*activebackground", grey ) # wins.root.option_add( "*highlightbackground", grey ) # wins.root.option_add( "*insertBackground", grey ) # wins.root.option_add( "*selectBackground", grey ) wins.root.tk_setPalette( grey ) else: pass #wins.root.iconbitmap('flickfleck.xbm') wins.main = mainwin.FlickFleck(wins.root) wins.root.deiconify() #----------------------------------------------------------------- def start(): wins.root.mainloop() #----------------------------------------------------------------- # engine calls this in file operations loops to check if user # wants to cancel # def checkStop(): wins.root.update() if wins.requestStop: ERR("Stopped by the User")
Python
import PmwColor Color = PmwColor del PmwColor import PmwBlt Blt = PmwBlt del PmwBlt ### Loader functions: _VERSION = '1.3' def setversion(version): if version != _VERSION: raise ValueError, 'Dynamic versioning not available' def setalphaversions(*alpha_versions): if alpha_versions != (): raise ValueError, 'Dynamic versioning not available' def version(alpha = 0): if alpha: return () else: return _VERSION def installedversions(alpha = 0): if alpha: return () else: return (_VERSION,) ###################################################################### ### File: PmwBase.py # Pmw megawidget base classes. # This module provides a foundation for building megawidgets. It # contains the MegaArchetype class which manages component widgets and # configuration options. Also provided are the MegaToplevel and # MegaWidget classes, derived from the MegaArchetype class. The # MegaToplevel class contains a Tkinter Toplevel widget to act as the # container of the megawidget. This is used as the base class of all # megawidgets that are contained in their own top level window, such # as a Dialog window. The MegaWidget class contains a Tkinter Frame # to act as the container of the megawidget. This is used as the base # class of all other megawidgets, such as a ComboBox or ButtonBox. # # Megawidgets are built by creating a class that inherits from either # the MegaToplevel or MegaWidget class. import os import string import sys import traceback import types import Tkinter # Special values used in index() methods of several megawidgets. END = ['end'] SELECT = ['select'] DEFAULT = ['default'] # Constant used to indicate that an option can only be set by a call # to the constructor. INITOPT = ['initopt'] _DEFAULT_OPTION_VALUE = ['default_option_value'] _useTkOptionDb = 0 # Symbolic constants for the indexes into an optionInfo list. _OPT_DEFAULT = 0 _OPT_VALUE = 1 _OPT_FUNCTION = 2 # Stacks _busyStack = [] # Stack which tracks nested calls to show/hidebusycursor (called # either directly or from activate()/deactivate()). Each element # is a dictionary containing: # 'newBusyWindows' : List of windows which had busy_hold called # on them during a call to showbusycursor(). # The corresponding call to hidebusycursor() # will call busy_release on these windows. # 'busyFocus' : The blt _Busy window which showbusycursor() # set the focus to. # 'previousFocus' : The focus as it was when showbusycursor() # was called. The corresponding call to # hidebusycursor() will restore this focus if # the focus has not been changed from busyFocus. _grabStack = [] # Stack of grabbed windows. It tracks calls to push/popgrab() # (called either directly or from activate()/deactivate()). The # window on the top of the stack is the window currently with the # grab. Each element is a dictionary containing: # 'grabWindow' : The window grabbed by pushgrab(). The # corresponding call to popgrab() will release # the grab on this window and restore the grab # on the next window in the stack (if there is one). # 'globalMode' : True if the grabWindow was grabbed with a # global grab, false if the grab was local # and 'nograb' if no grab was performed. # 'previousFocus' : The focus as it was when pushgrab() # was called. The corresponding call to # popgrab() will restore this focus. # 'deactivateFunction' : # The function to call (usually grabWindow.deactivate) if # popgrab() is called (usually from a deactivate() method) # on a window which is not at the top of the stack (that is, # does not have the grab or focus). For example, if a modal # dialog is deleted by the window manager or deactivated by # a timer. In this case, all dialogs above and including # this one are deactivated, starting at the top of the # stack. # Note that when dealing with focus windows, the name of the Tk # widget is used, since it may be the '_Busy' window, which has no # python instance associated with it. #============================================================================= # Functions used to forward methods from a class to a component. # Fill in a flattened method resolution dictionary for a class (attributes are # filtered out). Flattening honours the MI method resolution rules # (depth-first search of bases in order). The dictionary has method names # for keys and functions for values. def __methodDict(cls, dict): # the strategy is to traverse the class in the _reverse_ of the normal # order, and overwrite any duplicates. baseList = list(cls.__bases__) baseList.reverse() # do bases in reverse order, so first base overrides last base for super in baseList: __methodDict(super, dict) # do my methods last to override base classes for key, value in cls.__dict__.items(): # ignore class attributes if type(value) == types.FunctionType: dict[key] = value def __methods(cls): # Return all method names for a class. # Return all method names for a class (attributes are filtered # out). Base classes are searched recursively. dict = {} __methodDict(cls, dict) return dict.keys() # Function body to resolve a forwarding given the target method name and the # attribute name. The resulting lambda requires only self, but will forward # any other parameters. __stringBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(attribute)s.%(method)s, args, kw)') # Get a unique id __counter = 0 def __unique(): global __counter __counter = __counter + 1 return str(__counter) # Function body to resolve a forwarding given the target method name and the # index of the resolution function. The resulting lambda requires only self, # but will forward any other parameters. The target instance is identified # by invoking the resolution function. __funcBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(forwardFunc)s().%(method)s, args, kw)') def forwardmethods(fromClass, toClass, toPart, exclude = ()): # Forward all methods from one class to another. # Forwarders will be created in fromClass to forward method # invocations to toClass. The methods to be forwarded are # identified by flattening the interface of toClass, and excluding # methods identified in the exclude list. Methods already defined # in fromClass, or special methods with one or more leading or # trailing underscores will not be forwarded. # For a given object of class fromClass, the corresponding toClass # object is identified using toPart. This can either be a String # denoting an attribute of fromClass objects, or a function taking # a fromClass object and returning a toClass object. # Example: # class MyClass: # ... # def __init__(self): # ... # self.__target = TargetClass() # ... # def findtarget(self): # return self.__target # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) # # ...or... # forwardmethods(MyClass, TargetClass, MyClass.findtarget, # ['dangerous1', 'dangerous2']) # In both cases, all TargetClass methods will be forwarded from # MyClass except for dangerous1, dangerous2, special methods like # __str__, and pre-existing methods like findtarget. # Allow an attribute name (String) or a function to determine the instance if type(toPart) != types.StringType: # check that it is something like a function if callable(toPart): # If a method is passed, use the function within it if hasattr(toPart, 'im_func'): toPart = toPart.im_func # After this is set up, forwarders in this class will use # the forwarding function. The forwarding function name is # guaranteed to be unique, so that it can't be hidden by subclasses forwardName = '__fwdfunc__' + __unique() fromClass.__dict__[forwardName] = toPart # It's not a valid type else: raise TypeError, 'toPart must be attribute name, function or method' # get the full set of candidate methods dict = {} __methodDict(toClass, dict) # discard special methods for ex in dict.keys(): if ex[:1] == '_' or ex[-1:] == '_': del dict[ex] # discard dangerous methods supplied by the caller for ex in exclude: if dict.has_key(ex): del dict[ex] # discard methods already defined in fromClass for ex in __methods(fromClass): if dict.has_key(ex): del dict[ex] for method, func in dict.items(): d = {'method': method, 'func': func} if type(toPart) == types.StringType: execString = \ __stringBody % {'method' : method, 'attribute' : toPart} else: execString = \ __funcBody % {'forwardFunc' : forwardName, 'method' : method} exec execString in d # this creates a method fromClass.__dict__[method] = d[method] #============================================================================= def setgeometryanddeiconify(window, geom): # To avoid flashes on X and to position the window correctly on NT # (caused by Tk bugs). if os.name == 'nt' or \ (os.name == 'posix' and sys.platform[:6] == 'cygwin'): # Require overrideredirect trick to stop window frame # appearing momentarily. redirect = window.overrideredirect() if not redirect: window.overrideredirect(1) window.deiconify() if geom is not None: window.geometry(geom) # Call update_idletasks to ensure NT moves the window to the # correct position it is raised. window.update_idletasks() window.tkraise() if not redirect: window.overrideredirect(0) else: if geom is not None: window.geometry(geom) # Problem!? Which way around should the following two calls # go? If deiconify() is called first then I get complaints # from people using the enlightenment or sawfish window # managers that when a dialog is activated it takes about 2 # seconds for the contents of the window to appear. But if # tkraise() is called first then I get complaints from people # using the twm window manager that when a dialog is activated # it appears in the top right corner of the screen and also # takes about 2 seconds to appear. #window.tkraise() # Call update_idletasks to ensure certain window managers (eg: # enlightenment and sawfish) do not cause Tk to delay for # about two seconds before displaying window. #window.update_idletasks() #window.deiconify() window.deiconify() if window.overrideredirect(): # The window is not under the control of the window manager # and so we need to raise it ourselves. window.tkraise() #============================================================================= class MegaArchetype: # Megawidget abstract root class. # This class provides methods which are inherited by classes # implementing useful bases (this class doesn't provide a # container widget inside which the megawidget can be built). def __init__(self, parent = None, hullClass = None): # Mapping from each megawidget option to a list of information # about the option # - default value # - current value # - function to call when the option is initialised in the # call to initialiseoptions() in the constructor or # modified via configure(). If this is INITOPT, the # option is an initialisation option (an option that can # be set by the call to the constructor but can not be # used with configure). # This mapping is not initialised here, but in the call to # defineoptions() which precedes construction of this base class. # # self._optionInfo = {} # Mapping from each component name to a tuple of information # about the component. # - component widget instance # - configure function of widget instance # - the class of the widget (Frame, EntryField, etc) # - cget function of widget instance # - the name of the component group of this component, if any self.__componentInfo = {} # Mapping from alias names to the names of components or # sub-components. self.__componentAliases = {} # Contains information about the keywords provided to the # constructor. It is a mapping from the keyword to a tuple # containing: # - value of keyword # - a boolean indicating if the keyword has been used. # A keyword is used if, during the construction of a megawidget, # - it is defined in a call to defineoptions() or addoptions(), or # - it references, by name, a component of the megawidget, or # - it references, by group, at least one component # At the end of megawidget construction, a call is made to # initialiseoptions() which reports an error if there are # unused options given to the constructor. # # After megawidget construction, the dictionary contains # keywords which refer to a dynamic component group, so that # these components can be created after megawidget # construction and still use the group options given to the # constructor. # # self._constructorKeywords = {} # List of dynamic component groups. If a group is included in # this list, then it not an error if a keyword argument for # the group is given to the constructor or to configure(), but # no components with this group have been created. # self._dynamicGroups = () if hullClass is None: self._hull = None else: if parent is None: parent = Tkinter._default_root # Create the hull. self._hull = self.createcomponent('hull', (), None, hullClass, (parent,)) _hullToMegaWidget[self._hull] = self if _useTkOptionDb: # Now that a widget has been created, query the Tk # option database to get the default values for the # options which have not been set in the call to the # constructor. This assumes that defineoptions() is # called before the __init__(). option_get = self.option_get _VALUE = _OPT_VALUE _DEFAULT = _OPT_DEFAULT for name, info in self._optionInfo.items(): value = info[_VALUE] if value is _DEFAULT_OPTION_VALUE: resourceClass = string.upper(name[0]) + name[1:] value = option_get(name, resourceClass) if value != '': try: # Convert the string to int/float/tuple, etc value = eval(value, {'__builtins__': {}}) except: pass info[_VALUE] = value else: info[_VALUE] = info[_DEFAULT] def destroy(self): # Clean up optionInfo in case it contains circular references # in the function field, such as self._settitle in class # MegaToplevel. self._optionInfo = {} if self._hull is not None: del _hullToMegaWidget[self._hull] self._hull.destroy() #====================================================================== # Methods used (mainly) during the construction of the megawidget. def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): # Create options, providing the default value and the method # to call when the value is changed. If any option created by # base classes has the same name as one in <optionDefs>, the # base class's value and function will be overriden. # This should be called before the constructor of the base # class, so that default values defined in the derived class # override those in the base class. if not hasattr(self, '_constructorKeywords'): # First time defineoptions has been called. tmp = {} for option, value in keywords.items(): tmp[option] = [value, 0] self._constructorKeywords = tmp self._optionInfo = {} self._initialiseoptions_counter = 0 self._initialiseoptions_counter = self._initialiseoptions_counter + 1 if not hasattr(self, '_dynamicGroups'): self._dynamicGroups = () self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups) self.addoptions(optionDefs) def addoptions(self, optionDefs): # Add additional options, providing the default value and the # method to call when the value is changed. See # "defineoptions" for more details # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key keywords = self._constructorKeywords keywords_has_key = keywords.has_key FUNCTION = _OPT_FUNCTION for name, default, function in optionDefs: if '_' not in name: # The option will already exist if it has been defined # in a derived class. In this case, do not override the # default value of the option or the callback function # if it is not None. if not optionInfo_has_key(name): if keywords_has_key(name): value = keywords[name][0] optionInfo[name] = [default, value, function] del keywords[name] else: if _useTkOptionDb: optionInfo[name] = \ [default, _DEFAULT_OPTION_VALUE, function] else: optionInfo[name] = [default, default, function] elif optionInfo[name][FUNCTION] is None: optionInfo[name][FUNCTION] = function else: # This option is of the form "component_option". If this is # not already defined in self._constructorKeywords add it. # This allows a derived class to override the default value # of an option of a component of a base class. if not keywords_has_key(name): keywords[name] = [default, 0] def createcomponent(self, componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw): # Create a component (during construction or later). if self.__componentInfo.has_key(componentName): raise ValueError, 'Component "%s" already exists' % componentName if '_' in componentName: raise ValueError, \ 'Component name "%s" must not contain "_"' % componentName if hasattr(self, '_constructorKeywords'): keywords = self._constructorKeywords else: keywords = {} for alias, component in componentAliases: # Create aliases to the component and its sub-components. index = string.find(component, '_') if index < 0: self.__componentAliases[alias] = (component, None) else: mainComponent = component[:index] subComponent = component[(index + 1):] self.__componentAliases[alias] = (mainComponent, subComponent) # Remove aliases from the constructor keyword arguments by # replacing any keyword arguments that begin with *alias* # with corresponding keys beginning with *component*. alias = alias + '_' aliasLen = len(alias) for option in keywords.keys(): if len(option) > aliasLen and option[:aliasLen] == alias: newkey = component + '_' + option[aliasLen:] keywords[newkey] = keywords[option] del keywords[option] componentPrefix = componentName + '_' nameLen = len(componentPrefix) for option in keywords.keys(): if len(option) > nameLen and option[:nameLen] == componentPrefix: # The keyword argument refers to this component, so add # this to the options to use when constructing the widget. kw[option[nameLen:]] = keywords[option][0] del keywords[option] else: # Check if this keyword argument refers to the group # of this component. If so, add this to the options # to use when constructing the widget. Mark the # keyword argument as being used, but do not remove it # since it may be required when creating another # component. index = string.find(option, '_') if index >= 0 and componentGroup == option[:index]: rest = option[(index + 1):] kw[rest] = keywords[option][0] keywords[option][1] = 1 if kw.has_key('pyclass'): widgetClass = kw['pyclass'] del kw['pyclass'] if widgetClass is None: return None if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. widgetArgs = widgetArgs[0] widget = apply(widgetClass, widgetArgs, kw) componentClass = widget.__class__.__name__ self.__componentInfo[componentName] = (widget, widget.configure, componentClass, widget.cget, componentGroup) return widget def destroycomponent(self, name): # Remove a megawidget component. # This command is for use by megawidget designers to destroy a # megawidget component. self.__componentInfo[name][0].destroy() del self.__componentInfo[name] def createlabel(self, parent, childCols = 1, childRows = 1): labelpos = self['labelpos'] labelmargin = self['labelmargin'] if labelpos is None: return label = self.createcomponent('label', (), None, Tkinter.Label, (parent,)) if labelpos[0] in 'ns': # vertical layout if labelpos[0] == 'n': row = 0 margin = 1 else: row = childRows + 3 margin = row - 1 label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos) parent.grid_rowconfigure(margin, minsize=labelmargin) else: # horizontal layout if labelpos[0] == 'w': col = 0 margin = 1 else: col = childCols + 3 margin = col - 1 label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos) parent.grid_columnconfigure(margin, minsize=labelmargin) def initialiseoptions(self, dummy = None): self._initialiseoptions_counter = self._initialiseoptions_counter - 1 if self._initialiseoptions_counter == 0: unusedOptions = [] keywords = self._constructorKeywords for name in keywords.keys(): used = keywords[name][1] if not used: # This keyword argument has not been used. If it # does not refer to a dynamic group, mark it as # unused. index = string.find(name, '_') if index < 0 or name[:index] not in self._dynamicGroups: unusedOptions.append(name) if len(unusedOptions) > 0: if len(unusedOptions) == 1: text = 'Unknown option "' else: text = 'Unknown options "' raise KeyError, text + string.join(unusedOptions, ', ') + \ '" for ' + self.__class__.__name__ # Call the configuration callback function for every option. FUNCTION = _OPT_FUNCTION for info in self._optionInfo.values(): func = info[FUNCTION] if func is not None and func is not INITOPT: func() #====================================================================== # Method used to configure the megawidget. def configure(self, option=None, **kw): # Query or configure the megawidget options. # # If not empty, *kw* is a dictionary giving new # values for some of the options of this megawidget or its # components. For options defined for this megawidget, set # the value of the option to the new value and call the # configuration callback function, if any. For options of the # form <component>_<option>, where <component> is a component # of this megawidget, call the configure method of the # component giving it the new value of the option. The # <component> part may be an alias or a component group name. # # If *option* is None, return all megawidget configuration # options and settings. Options are returned as standard 5 # element tuples # # If *option* is a string, return the 5 element tuple for the # given configuration option. # First, deal with the option queries. if len(kw) == 0: # This configure call is querying the values of one or all options. # Return 5-tuples: # (optionName, resourceName, resourceClass, default, value) if option is None: rtn = {} for option, config in self._optionInfo.items(): resourceClass = string.upper(option[0]) + option[1:] rtn[option] = (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) return rtn else: config = self._optionInfo[option] resourceClass = string.upper(option[0]) + option[1:] return (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key componentInfo = self.__componentInfo componentInfo_has_key = componentInfo.has_key componentAliases = self.__componentAliases componentAliases_has_key = componentAliases.has_key VALUE = _OPT_VALUE FUNCTION = _OPT_FUNCTION # This will contain a list of options in *kw* which # are known to this megawidget. directOptions = [] # This will contain information about the options in # *kw* of the form <component>_<option>, where # <component> is a component of this megawidget. It is a # dictionary whose keys are the configure method of each # component and whose values are a dictionary of options and # values for the component. indirectOptions = {} indirectOptions_has_key = indirectOptions.has_key for option, value in kw.items(): if optionInfo_has_key(option): # This is one of the options of this megawidget. # Make sure it is not an initialisation option. if optionInfo[option][FUNCTION] is INITOPT: raise KeyError, \ 'Cannot configure initialisation option "' \ + option + '" for ' + self.__class__.__name__ optionInfo[option][VALUE] = value directOptions.append(option) else: index = string.find(option, '_') if index >= 0: # This option may be of the form <component>_<option>. component = option[:index] componentOption = option[(index + 1):] # Expand component alias if componentAliases_has_key(component): component, subComponent = componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' \ + componentOption # Expand option string to write on error option = component + '_' + componentOption if componentInfo_has_key(component): # Configure the named component componentConfigFuncs = [componentInfo[component][1]] else: # Check if this is a group name and configure all # components in the group. componentConfigFuncs = [] for info in componentInfo.values(): if info[4] == component: componentConfigFuncs.append(info[1]) if len(componentConfigFuncs) == 0 and \ component not in self._dynamicGroups: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Add the configure method(s) (may be more than # one if this is configuring a component group) # and option/value to dictionary. for componentConfigFunc in componentConfigFuncs: if not indirectOptions_has_key(componentConfigFunc): indirectOptions[componentConfigFunc] = {} indirectOptions[componentConfigFunc][componentOption] \ = value else: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Call the configure methods for any components. map(apply, indirectOptions.keys(), ((),) * len(indirectOptions), indirectOptions.values()) # Call the configuration callback function for each option. for option in directOptions: info = optionInfo[option] func = info[_OPT_FUNCTION] if func is not None: func() def __setitem__(self, key, value): apply(self.configure, (), {key: value}) #====================================================================== # Methods used to query the megawidget. def component(self, name): # Return a component widget of the megawidget given the # component's name # This allows the user of a megawidget to access and configure # widget components directly. # Find the main component and any subcomponents index = string.find(name, '_') if index < 0: component = name remainingComponents = None else: component = name[:index] remainingComponents = name[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: if remainingComponents is None: remainingComponents = subComponent else: remainingComponents = subComponent + '_' \ + remainingComponents widget = self.__componentInfo[component][0] if remainingComponents is None: return widget else: return widget.component(remainingComponents) def interior(self): return self._hull def hulldestroyed(self): return not _hullToMegaWidget.has_key(self._hull) def __str__(self): return str(self._hull) def cget(self, option): # Get current configuration setting. # Return the value of an option, for example myWidget['font']. if self._optionInfo.has_key(option): return self._optionInfo[option][_OPT_VALUE] else: index = string.find(option, '_') if index >= 0: component = option[:index] componentOption = option[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' + componentOption # Expand option string to write on error option = component + '_' + componentOption if self.__componentInfo.has_key(component): # Call cget on the component. componentCget = self.__componentInfo[component][3] return componentCget(componentOption) else: # If this is a group name, call cget for one of # the components in the group. for info in self.__componentInfo.values(): if info[4] == component: componentCget = info[3] return componentCget(componentOption) raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ __getitem__ = cget def isinitoption(self, option): return self._optionInfo[option][_OPT_FUNCTION] is INITOPT def options(self): options = [] if hasattr(self, '_optionInfo'): for option, info in self._optionInfo.items(): isinit = info[_OPT_FUNCTION] is INITOPT default = info[_OPT_DEFAULT] options.append((option, default, isinit)) options.sort() return options def components(self): # Return a list of all components. # This list includes the 'hull' component and all widget subcomponents names = self.__componentInfo.keys() names.sort() return names def componentaliases(self): # Return a list of all component aliases. componentAliases = self.__componentAliases names = componentAliases.keys() names.sort() rtn = [] for alias in names: (mainComponent, subComponent) = componentAliases[alias] if subComponent is None: rtn.append((alias, mainComponent)) else: rtn.append((alias, mainComponent + '_' + subComponent)) return rtn def componentgroup(self, name): return self.__componentInfo[name][4] #============================================================================= # The grab functions are mainly called by the activate() and # deactivate() methods. # # Use pushgrab() to add a new window to the grab stack. This # releases the grab by the window currently on top of the stack (if # there is one) and gives the grab and focus to the new widget. # # To remove the grab from the window on top of the grab stack, call # popgrab(). # # Use releasegrabs() to release the grab and clear the grab stack. def pushgrab(grabWindow, globalMode, deactivateFunction): prevFocus = grabWindow.tk.call('focus') grabInfo = { 'grabWindow' : grabWindow, 'globalMode' : globalMode, 'previousFocus' : prevFocus, 'deactivateFunction' : deactivateFunction, } _grabStack.append(grabInfo) _grabtop() grabWindow.focus_set() def popgrab(window): # Return the grab to the next window in the grab stack, if any. # If this window is not at the top of the grab stack, then it has # just been deleted by the window manager or deactivated by a # timer. Call the deactivate method for the modal dialog above # this one on the stack. if _grabStack[-1]['grabWindow'] != window: for index in range(len(_grabStack)): if _grabStack[index]['grabWindow'] == window: _grabStack[index + 1]['deactivateFunction']() break grabInfo = _grabStack[-1] del _grabStack[-1] topWidget = grabInfo['grabWindow'] prevFocus = grabInfo['previousFocus'] globalMode = grabInfo['globalMode'] if globalMode != 'nograb': topWidget.grab_release() if len(_grabStack) > 0: _grabtop() if prevFocus != '': try: topWidget.tk.call('focus', prevFocus) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to root window. Tkinter._default_root.focus_set() else: # Make sure that focus does not remain on the released widget. if len(_grabStack) > 0: topWidget = _grabStack[-1]['grabWindow'] topWidget.focus_set() else: Tkinter._default_root.focus_set() def grabstacktopwindow(): if len(_grabStack) == 0: return None else: return _grabStack[-1]['grabWindow'] def releasegrabs(): # Release grab and clear the grab stack. current = Tkinter._default_root.grab_current() if current is not None: current.grab_release() _grabStack[:] = [] def _grabtop(): grabInfo = _grabStack[-1] topWidget = grabInfo['grabWindow'] globalMode = grabInfo['globalMode'] if globalMode == 'nograb': return while 1: try: if globalMode: topWidget.grab_set_global() else: topWidget.grab_set() break except Tkinter.TclError: # Another application has grab. Keep trying until # grab can succeed. topWidget.after(100) #============================================================================= class MegaToplevel(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('activatecommand', None, None), ('deactivatecommand', None, None), ('master', None, None), ('title', None, self._settitle), ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Toplevel) # Initialise instance. # Set WM_DELETE_WINDOW protocol, deleting any old callback, so # memory does not leak. if hasattr(self._hull, '_Pmw_WM_DELETE_name'): self._hull.tk.deletecommand(self._hull._Pmw_WM_DELETE_name) self._hull._Pmw_WM_DELETE_name = \ self.register(self._userDeleteWindow, needcleanup = 0) self.protocol('WM_DELETE_WINDOW', self._hull._Pmw_WM_DELETE_name) # Initialise instance variables. self._firstShowing = 1 # Used by show() to ensure window retains previous position on screen. # The IntVar() variable to wait on during a modal dialog. self._wait = None self._active = 0 self._userDeleteFunc = self.destroy self._userModalDeleteFunc = self.deactivate # Check keywords and initialise options. self.initialiseoptions() def _settitle(self): title = self['title'] if title is not None: self.title(title) def userdeletefunc(self, func=None): if func: self._userDeleteFunc = func else: return self._userDeleteFunc def usermodaldeletefunc(self, func=None): if func: self._userModalDeleteFunc = func else: return self._userModalDeleteFunc def _userDeleteWindow(self): if self.active(): self._userModalDeleteFunc() else: self._userDeleteFunc() def destroy(self): # Allow this to be called more than once. if _hullToMegaWidget.has_key(self._hull): self.deactivate() # Remove circular references, so that object can get cleaned up. del self._userDeleteFunc del self._userModalDeleteFunc MegaArchetype.destroy(self) def show(self, master = None): if self.state() != 'normal': if self._firstShowing: # Just let the window manager determine the window # position for the first time. geom = None else: # Position the window at the same place it was last time. geom = self._sameposition() setgeometryanddeiconify(self, geom) if self._firstShowing: self._firstShowing = 0 else: if self.transient() == '': self.tkraise() # Do this last, otherwise get flashing on NT: if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) self.focus() def _centreonscreen(self): # Centre the window on the screen. (Actually halfway across # and one third down.) parent = self.winfo_parent() if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) # Find size of window. self.update_idletasks() width = self.winfo_width() height = self.winfo_height() if width == 1 and height == 1: # If the window has not yet been displayed, its size is # reported as 1x1, so use requested size. width = self.winfo_reqwidth() height = self.winfo_reqheight() # Place in centre of screen: x = (self.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx() y = (self.winfo_screenheight() - height) / 3 - parent.winfo_vrooty() if x < 0: x = 0 if y < 0: y = 0 return '+%d+%d' % (x, y) def _sameposition(self): # Position the window at the same place it was last time. geometry = self.geometry() index = string.find(geometry, '+') if index >= 0: return geometry[index:] else: return None def activate(self, globalMode = 0, geometry = 'centerscreenfirst'): if self._active: raise ValueError, 'Window is already active' if self.state() == 'normal': self.withdraw() self._active = 1 showbusycursor() if self._wait is None: self._wait = Tkinter.IntVar() self._wait.set(0) if geometry == 'centerscreenalways': geom = self._centreonscreen() elif geometry == 'centerscreenfirst': if self._firstShowing: # Centre the window the first time it is displayed. geom = self._centreonscreen() else: # Position the window at the same place it was last time. geom = self._sameposition() elif geometry[:5] == 'first': if self._firstShowing: geom = geometry[5:] else: # Position the window at the same place it was last time. geom = self._sameposition() else: geom = geometry self._firstShowing = 0 setgeometryanddeiconify(self, geom) # Do this last, otherwise get flashing on NT: master = self['master'] if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) pushgrab(self._hull, globalMode, self.deactivate) command = self['activatecommand'] if callable(command): command() self.wait_variable(self._wait) return self._result def deactivate(self, result=None): if not self._active: return self._active = 0 # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._hull) command = self['deactivatecommand'] if callable(command): command() self.withdraw() hidebusycursor(forceFocusRestore = 1) self._result = result self._wait.set(1) def active(self): return self._active forwardmethods(MegaToplevel, Tkinter.Toplevel, '_hull') #============================================================================= class MegaWidget(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Frame) # Check keywords and initialise options. self.initialiseoptions() forwardmethods(MegaWidget, Tkinter.Frame, '_hull') #============================================================================= # Public functions #----------------- _traceTk = 0 def tracetk(root = None, on = 1, withStackTrace = 0, file=None): global _withStackTrace global _traceTkFile global _traceTk if root is None: root = Tkinter._default_root _withStackTrace = withStackTrace _traceTk = on if on: if hasattr(root.tk, '__class__'): # Tracing already on return if file is None: _traceTkFile = sys.stderr else: _traceTkFile = file tk = _TraceTk(root.tk) else: if not hasattr(root.tk, '__class__'): # Tracing already off return tk = root.tk.getTclInterp() _setTkInterps(root, tk) def showbusycursor(): _addRootToToplevelBusyInfo() root = Tkinter._default_root busyInfo = { 'newBusyWindows' : [], 'previousFocus' : None, 'busyFocus' : None, } _busyStack.append(busyInfo) if _disableKeyboardWhileBusy: # Remember the focus as it is now, before it is changed. busyInfo['previousFocus'] = root.tk.call('focus') if not _havebltbusy(root): # No busy command, so don't call busy hold on any windows. return for (window, winInfo) in _toplevelBusyInfo.items(): if (window.state() != 'withdrawn' and not winInfo['isBusy'] and not winInfo['excludeFromBusy']): busyInfo['newBusyWindows'].append(window) winInfo['isBusy'] = 1 _busy_hold(window, winInfo['busyCursorName']) # Make sure that no events for the busy window get # through to Tkinter, otherwise it will crash in # _nametowidget with a 'KeyError: _Busy' if there is # a binding on the toplevel window. window.tk.call('bindtags', winInfo['busyWindow'], 'Pmw_Dummy_Tag') if _disableKeyboardWhileBusy: # Remember previous focus widget for this toplevel window # and set focus to the busy window, which will ignore all # keyboard events. winInfo['windowFocus'] = \ window.tk.call('focus', '-lastfor', window._w) window.tk.call('focus', winInfo['busyWindow']) busyInfo['busyFocus'] = winInfo['busyWindow'] if len(busyInfo['newBusyWindows']) > 0: if os.name == 'nt': # NT needs an "update" before it will change the cursor. window.update() else: window.update_idletasks() def hidebusycursor(forceFocusRestore = 0): # Remember the focus as it is now, before it is changed. root = Tkinter._default_root if _disableKeyboardWhileBusy: currentFocus = root.tk.call('focus') # Pop the busy info off the stack. busyInfo = _busyStack[-1] del _busyStack[-1] for window in busyInfo['newBusyWindows']: # If this window has not been deleted, release the busy cursor. if _toplevelBusyInfo.has_key(window): winInfo = _toplevelBusyInfo[window] winInfo['isBusy'] = 0 _busy_release(window) if _disableKeyboardWhileBusy: # Restore previous focus window for this toplevel window, # but only if is still set to the busy window (it may have # been changed). windowFocusNow = window.tk.call('focus', '-lastfor', window._w) if windowFocusNow == winInfo['busyWindow']: try: window.tk.call('focus', winInfo['windowFocus']) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to toplevel window instead (can't leave focus on # busy window). window.focus_set() if _disableKeyboardWhileBusy: # Restore the focus, depending on whether the focus had changed # between the calls to showbusycursor and hidebusycursor. if forceFocusRestore or busyInfo['busyFocus'] == currentFocus: # The focus had not changed, so restore it to as it was before # the call to showbusycursor, previousFocus = busyInfo['previousFocus'] if previousFocus is not None: try: root.tk.call('focus', previousFocus) except Tkinter.TclError: # Previous focus widget has been deleted; forget it. pass else: # The focus had changed, so restore it to what it had been # changed to before the call to hidebusycursor. root.tk.call('focus', currentFocus) def clearbusycursor(): while len(_busyStack) > 0: hidebusycursor() def setbusycursorattributes(window, **kw): _addRootToToplevelBusyInfo() for name, value in kw.items(): if name == 'exclude': _toplevelBusyInfo[window]['excludeFromBusy'] = value elif name == 'cursorName': _toplevelBusyInfo[window]['busyCursorName'] = value else: raise KeyError, 'Unknown busycursor attribute "' + name + '"' def _addRootToToplevelBusyInfo(): # Include the Tk root window in the list of toplevels. This must # not be called before Tkinter has had a chance to be initialised by # the application. root = Tkinter._default_root if root == None: root = Tkinter.Tk() if not _toplevelBusyInfo.has_key(root): _addToplevelBusyInfo(root) def busycallback(command, updateFunction = None): if not callable(command): raise ValueError, \ 'cannot register non-command busy callback %s %s' % \ (repr(command), type(command)) wrapper = _BusyWrapper(command, updateFunction) return wrapper.callback _errorReportFile = None _errorWindow = None def reporterrorstofile(file = None): global _errorReportFile _errorReportFile = file def displayerror(text): global _errorWindow if _errorReportFile is not None: _errorReportFile.write(text + '\n') else: # Print error on standard error as well as to error window. # Useful if error window fails to be displayed, for example # when exception is triggered in a <Destroy> binding for root # window. sys.stderr.write(text + '\n') if _errorWindow is None: # The error window has not yet been created. _errorWindow = _ErrorWindow() _errorWindow.showerror(text) _root = None _disableKeyboardWhileBusy = 1 def initialise( root = None, size = None, fontScheme = None, useTkOptionDb = 0, noBltBusy = 0, disableKeyboardWhileBusy = None, ): # Remember if show/hidebusycursor should ignore keyboard events. global _disableKeyboardWhileBusy if disableKeyboardWhileBusy is not None: _disableKeyboardWhileBusy = disableKeyboardWhileBusy # Do not use blt busy command if noBltBusy is set. Otherwise, # use blt busy if it is available. global _haveBltBusy if noBltBusy: _haveBltBusy = 0 # Save flag specifying whether the Tk option database should be # queried when setting megawidget option default values. global _useTkOptionDb _useTkOptionDb = useTkOptionDb # If we haven't been given a root window, use the default or # create one. if root is None: if Tkinter._default_root is None: root = Tkinter.Tk() else: root = Tkinter._default_root # If this call is initialising a different Tk interpreter than the # last call, then re-initialise all global variables. Assume the # last interpreter has been destroyed - ie: Pmw does not (yet) # support multiple simultaneous interpreters. global _root if _root is not None and _root != root: global _busyStack global _errorWindow global _grabStack global _hullToMegaWidget global _toplevelBusyInfo _busyStack = [] _errorWindow = None _grabStack = [] _hullToMegaWidget = {} _toplevelBusyInfo = {} _root = root # Trap Tkinter Toplevel constructors so that a list of Toplevels # can be maintained. Tkinter.Toplevel.title = __TkinterToplevelTitle # Trap Tkinter widget destruction so that megawidgets can be # destroyed when their hull widget is destoyed and the list of # Toplevels can be pruned. Tkinter.Toplevel.destroy = __TkinterToplevelDestroy Tkinter.Widget.destroy = __TkinterWidgetDestroy # Modify Tkinter's CallWrapper class to improve the display of # errors which occur in callbacks. Tkinter.CallWrapper = __TkinterCallWrapper # Make sure we get to know when the window manager deletes the # root window. Only do this if the protocol has not yet been set. # This is required if there is a modal dialog displayed and the # window manager deletes the root window. Otherwise the # application will not exit, even though there are no windows. if root.protocol('WM_DELETE_WINDOW') == '': root.protocol('WM_DELETE_WINDOW', root.destroy) # Set the base font size for the application and set the # Tk option database font resources. _font_initialise(root, size, fontScheme) return root def alignlabels(widgets, sticky = None): if len(widgets) == 0: return widgets[0].update_idletasks() # Determine the size of the maximum length label string. maxLabelWidth = 0 for iwid in widgets: labelWidth = iwid.grid_bbox(0, 1)[2] if labelWidth > maxLabelWidth: maxLabelWidth = labelWidth # Adjust the margins for the labels such that the child sites and # labels line up. for iwid in widgets: if sticky is not None: iwid.component('label').grid(sticky=sticky) iwid.grid_columnconfigure(0, minsize = maxLabelWidth) #============================================================================= # Private routines #----------------- _callToTkReturned = 1 _recursionCounter = 1 class _TraceTk: def __init__(self, tclInterp): self.tclInterp = tclInterp def getTclInterp(self): return self.tclInterp # Calling from python into Tk. def call(self, *args, **kw): global _callToTkReturned global _recursionCounter _callToTkReturned = 0 if len(args) == 1 and type(args[0]) == types.TupleType: argStr = str(args[0]) else: argStr = str(args) _traceTkFile.write('CALL TK> %d:%s%s' % (_recursionCounter, ' ' * _recursionCounter, argStr)) _recursionCounter = _recursionCounter + 1 try: result = apply(self.tclInterp.call, args, kw) except Tkinter.TclError, errorString: _callToTkReturned = 1 _recursionCounter = _recursionCounter - 1 _traceTkFile.write('\nTK ERROR> %d:%s-> %s\n' % (_recursionCounter, ' ' * _recursionCounter, repr(errorString))) if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() raise Tkinter.TclError, errorString _recursionCounter = _recursionCounter - 1 if _callToTkReturned: _traceTkFile.write('CALL RTN> %d:%s-> %s' % (_recursionCounter, ' ' * _recursionCounter, repr(result))) else: _callToTkReturned = 1 if result: _traceTkFile.write(' -> %s' % repr(result)) _traceTkFile.write('\n') if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() _traceTkFile.flush() return result def __getattr__(self, key): return getattr(self.tclInterp, key) def _setTkInterps(window, tk): window.tk = tk for child in window.children.values(): _setTkInterps(child, tk) #============================================================================= # Functions to display a busy cursor. Keep a list of all toplevels # and display the busy cursor over them. The list will contain the Tk # root toplevel window as well as all other toplevel windows. # Also keep a list of the widget which last had focus for each # toplevel. # Map from toplevel windows to # {'isBusy', 'windowFocus', 'busyWindow', # 'excludeFromBusy', 'busyCursorName'} _toplevelBusyInfo = {} # Pmw needs to know all toplevel windows, so that it can call blt busy # on them. This is a hack so we get notified when a Tk topevel is # created. Ideally, the __init__ 'method' should be overridden, but # it is a 'read-only special attribute'. Luckily, title() is always # called from the Tkinter Toplevel constructor. def _addToplevelBusyInfo(window): if window._w == '.': busyWindow = '._Busy' else: busyWindow = window._w + '._Busy' _toplevelBusyInfo[window] = { 'isBusy' : 0, 'windowFocus' : None, 'busyWindow' : busyWindow, 'excludeFromBusy' : 0, 'busyCursorName' : None, } def __TkinterToplevelTitle(self, *args): # If this is being called from the constructor, include this # Toplevel in the list of toplevels and set the initial # WM_DELETE_WINDOW protocol to destroy() so that we get to know # about it. if not _toplevelBusyInfo.has_key(self): _addToplevelBusyInfo(self) self._Pmw_WM_DELETE_name = self.register(self.destroy, None, 0) self.protocol('WM_DELETE_WINDOW', self._Pmw_WM_DELETE_name) return apply(Tkinter.Wm.title, (self,) + args) _haveBltBusy = None def _havebltbusy(window): global _busy_hold, _busy_release, _haveBltBusy if _haveBltBusy is None: import PmwBlt _haveBltBusy = PmwBlt.havebltbusy(window) _busy_hold = PmwBlt.busy_hold if os.name == 'nt': # There is a bug in Blt 2.4i on NT where the busy window # does not follow changes in the children of a window. # Using forget works around the problem. _busy_release = PmwBlt.busy_forget else: _busy_release = PmwBlt.busy_release return _haveBltBusy class _BusyWrapper: def __init__(self, command, updateFunction): self._command = command self._updateFunction = updateFunction def callback(self, *args): showbusycursor() rtn = apply(self._command, args) # Call update before hiding the busy windows to clear any # events that may have occurred over the busy windows. if callable(self._updateFunction): self._updateFunction() hidebusycursor() return rtn #============================================================================= def drawarrow(canvas, color, direction, tag, baseOffset = 0.25, edgeOffset = 0.15): canvas.delete(tag) bw = (string.atoi(canvas['borderwidth']) + string.atoi(canvas['highlightthickness'])) width = string.atoi(canvas['width']) height = string.atoi(canvas['height']) if direction in ('up', 'down'): majorDimension = height minorDimension = width else: majorDimension = width minorDimension = height offset = round(baseOffset * majorDimension) if direction in ('down', 'right'): base = bw + offset apex = bw + majorDimension - offset else: base = bw + majorDimension - offset apex = bw + offset if minorDimension > 3 and minorDimension % 2 == 0: minorDimension = minorDimension - 1 half = int(minorDimension * (1 - 2 * edgeOffset)) / 2 low = round(bw + edgeOffset * minorDimension) middle = low + half high = low + 2 * half if direction in ('up', 'down'): coords = (low, base, high, base, middle, apex) else: coords = (base, low, base, high, apex, middle) kw = {'fill' : color, 'outline' : color, 'tag' : tag} apply(canvas.create_polygon, coords, kw) #============================================================================= # Modify the Tkinter destroy methods so that it notifies us when a Tk # toplevel or frame is destroyed. # A map from the 'hull' component of a megawidget to the megawidget. # This is used to clean up a megawidget when its hull is destroyed. _hullToMegaWidget = {} def __TkinterToplevelDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: # Delete the busy info structure for this toplevel (if the # window was created before initialise() was called, it # will not have any. if _toplevelBusyInfo.has_key(tkWidget): del _toplevelBusyInfo[tkWidget] if hasattr(tkWidget, '_Pmw_WM_DELETE_name'): tkWidget.tk.deletecommand(tkWidget._Pmw_WM_DELETE_name) del tkWidget._Pmw_WM_DELETE_name Tkinter.BaseWidget.destroy(tkWidget) def __TkinterWidgetDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: Tkinter.BaseWidget.destroy(tkWidget) #============================================================================= # Add code to Tkinter to improve the display of errors which occur in # callbacks. class __TkinterCallWrapper: def __init__(self, func, subst, widget): self.func = func self.subst = subst self.widget = widget # Calling back from Tk into python. def __call__(self, *args): try: if self.subst: args = apply(self.subst, args) if _traceTk: if not _callToTkReturned: _traceTkFile.write('\n') if hasattr(self.func, 'im_class'): name = self.func.im_class.__name__ + '.' + \ self.func.__name__ else: name = self.func.__name__ if len(args) == 1 and hasattr(args[0], 'type'): # The argument to the callback is an event. eventName = _eventTypeToName[string.atoi(args[0].type)] if eventName in ('KeyPress', 'KeyRelease',): argStr = '(%s %s Event: %s)' % \ (eventName, args[0].keysym, args[0].widget) else: argStr = '(%s Event, %s)' % (eventName, args[0].widget) else: argStr = str(args) _traceTkFile.write('CALLBACK> %d:%s%s%s\n' % (_recursionCounter, ' ' * _recursionCounter, name, argStr)) _traceTkFile.flush() return apply(self.func, args) except SystemExit, msg: raise SystemExit, msg except: _reporterror(self.func, args) _eventTypeToName = { 2 : 'KeyPress', 15 : 'VisibilityNotify', 28 : 'PropertyNotify', 3 : 'KeyRelease', 16 : 'CreateNotify', 29 : 'SelectionClear', 4 : 'ButtonPress', 17 : 'DestroyNotify', 30 : 'SelectionRequest', 5 : 'ButtonRelease', 18 : 'UnmapNotify', 31 : 'SelectionNotify', 6 : 'MotionNotify', 19 : 'MapNotify', 32 : 'ColormapNotify', 7 : 'EnterNotify', 20 : 'MapRequest', 33 : 'ClientMessage', 8 : 'LeaveNotify', 21 : 'ReparentNotify', 34 : 'MappingNotify', 9 : 'FocusIn', 22 : 'ConfigureNotify', 35 : 'VirtualEvents', 10 : 'FocusOut', 23 : 'ConfigureRequest', 36 : 'ActivateNotify', 11 : 'KeymapNotify', 24 : 'GravityNotify', 37 : 'DeactivateNotify', 12 : 'Expose', 25 : 'ResizeRequest', 38 : 'MouseWheelEvent', 13 : 'GraphicsExpose', 26 : 'CirculateNotify', 14 : 'NoExpose', 27 : 'CirculateRequest', } def _reporterror(func, args): # Fetch current exception values. exc_type, exc_value, exc_traceback = sys.exc_info() # Give basic information about the callback exception. if type(exc_type) == types.ClassType: # Handle python 1.5 class exceptions. exc_type = exc_type.__name__ msg = str(exc_type) + ' Exception in Tk callback\n' msg = msg + ' Function: %s (type: %s)\n' % (repr(func), type(func)) msg = msg + ' Args: %s\n' % str(args) if type(args) == types.TupleType and len(args) > 0 and \ hasattr(args[0], 'type'): eventArg = 1 else: eventArg = 0 # If the argument to the callback is an event, add the event type. if eventArg: eventNum = string.atoi(args[0].type) if eventNum in _eventTypeToName.keys(): msg = msg + ' Event type: %s (type num: %d)\n' % \ (_eventTypeToName[eventNum], eventNum) else: msg = msg + ' Unknown event type (type num: %d)\n' % eventNum # Add the traceback. msg = msg + 'Traceback (innermost last):\n' for tr in traceback.extract_tb(exc_traceback): msg = msg + ' File "%s", line %s, in %s\n' % (tr[0], tr[1], tr[2]) msg = msg + ' %s\n' % tr[3] msg = msg + '%s: %s\n' % (exc_type, exc_value) # If the argument to the callback is an event, add the event contents. if eventArg: msg = msg + '\n================================================\n' msg = msg + ' Event contents:\n' keys = args[0].__dict__.keys() keys.sort() for key in keys: msg = msg + ' %s: %s\n' % (key, args[0].__dict__[key]) clearbusycursor() try: displayerror(msg) except: pass class _ErrorWindow: def __init__(self): self._errorQueue = [] self._errorCount = 0 self._open = 0 self._firstShowing = 1 # Create the toplevel window self._top = Tkinter.Toplevel() self._top.protocol('WM_DELETE_WINDOW', self._hide) self._top.title('Error in background function') self._top.iconname('Background error') # Create the text widget and scrollbar in a frame upperframe = Tkinter.Frame(self._top) scrollbar = Tkinter.Scrollbar(upperframe, orient='vertical') scrollbar.pack(side = 'right', fill = 'y') self._text = Tkinter.Text(upperframe, yscrollcommand=scrollbar.set) self._text.pack(fill = 'both', expand = 1) scrollbar.configure(command=self._text.yview) # Create the buttons and label in a frame lowerframe = Tkinter.Frame(self._top) ignore = Tkinter.Button(lowerframe, text = 'Ignore remaining errors', command = self._hide) ignore.pack(side='left') self._nextError = Tkinter.Button(lowerframe, text = 'Show next error', command = self._next) self._nextError.pack(side='left') self._label = Tkinter.Label(lowerframe, relief='ridge') self._label.pack(side='left', fill='x', expand=1) # Pack the lower frame first so that it does not disappear # when the window is resized. lowerframe.pack(side = 'bottom', fill = 'x') upperframe.pack(side = 'bottom', fill = 'both', expand = 1) def showerror(self, text): if self._open: self._errorQueue.append(text) else: self._display(text) self._open = 1 # Display the error window in the same place it was before. if self._top.state() == 'normal': # If update_idletasks is not called here, the window may # be placed partially off the screen. Also, if it is not # called and many errors are generated quickly in # succession, the error window may not display errors # until the last one is generated and the interpreter # becomes idle. # XXX: remove this, since it causes omppython to go into an # infinite loop if an error occurs in an omp callback. # self._top.update_idletasks() pass else: if self._firstShowing: geom = None else: geometry = self._top.geometry() index = string.find(geometry, '+') if index >= 0: geom = geometry[index:] else: geom = None setgeometryanddeiconify(self._top, geom) if self._firstShowing: self._firstShowing = 0 else: self._top.tkraise() self._top.focus() self._updateButtons() # Release any grab, so that buttons in the error window work. releasegrabs() def _hide(self): self._errorCount = self._errorCount + len(self._errorQueue) self._errorQueue = [] self._top.withdraw() self._open = 0 def _next(self): # Display the next error in the queue. text = self._errorQueue[0] del self._errorQueue[0] self._display(text) self._updateButtons() def _display(self, text): self._errorCount = self._errorCount + 1 text = 'Error: %d\n%s' % (self._errorCount, text) self._text.delete('1.0', 'end') self._text.insert('end', text) def _updateButtons(self): numQueued = len(self._errorQueue) if numQueued > 0: self._label.configure(text='%d more errors' % numQueued) self._nextError.configure(state='normal') else: self._label.configure(text='No more errors') self._nextError.configure(state='disabled') ###################################################################### ### File: PmwDialog.py # Based on iwidgets2.2.0/dialog.itk and iwidgets2.2.0/dialogshell.itk code. # Convention: # Each dialog window should have one of these as the rightmost button: # Close Close a window which only displays information. # Cancel Close a window which may be used to change the state of # the application. import sys import types import Tkinter # A Toplevel with a ButtonBox and child site. class Dialog(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttonbox_hull_borderwidth', 1, None), ('buttonbox_hull_relief', 'raised', None), ('buttonboxpos', 's', INITOPT), ('buttons', ('OK',), self._buttons), ('command', None, None), ('dialogchildsite_borderwidth', 1, None), ('dialogchildsite_relief', 'raised', None), ('defaultbutton', None, self._defaultButton), ('master', 'parent', None), ('separatorwidth', 0, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) # Create the components. oldInterior = MegaToplevel.interior(self) # Set up pack options according to the position of the button box. pos = self['buttonboxpos'] if pos not in 'nsew': raise ValueError, \ 'bad buttonboxpos option "%s": should be n, s, e, or w' \ % pos if pos in 'ns': orient = 'horizontal' fill = 'x' if pos == 'n': side = 'top' else: side = 'bottom' else: orient = 'vertical' fill = 'y' if pos == 'w': side = 'left' else: side = 'right' # Create the button box. self._buttonBox = self.createcomponent('buttonbox', (), None, ButtonBox, (oldInterior,), orient = orient) self._buttonBox.pack(side = side, fill = fill) # Create the separating line. width = self['separatorwidth'] if width > 0: self._separator = self.createcomponent('separator', (), None, Tkinter.Frame, (oldInterior,), relief = 'sunken', height = width, width = width, borderwidth = width / 2) self._separator.pack(side = side, fill = fill) # Create the child site. self.__dialogChildSite = self.createcomponent('dialogchildsite', (), None, Tkinter.Frame, (oldInterior,)) self.__dialogChildSite.pack(side=side, fill='both', expand=1) self.oldButtons = () self.oldDefault = None self.bind('<Return>', self._invokeDefault) self.userdeletefunc(self._doCommand) self.usermodaldeletefunc(self._doCommand) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self.__dialogChildSite def invoke(self, index = DEFAULT): return self._buttonBox.invoke(index) def _invokeDefault(self, event): try: self._buttonBox.index(DEFAULT) except ValueError: return self._buttonBox.invoke() def _doCommand(self, name = None): if name is not None and self.active() and \ grabstacktopwindow() != self.component('hull'): # This is a modal dialog but is not on the top of the grab # stack (ie: should not have the grab), so ignore this # event. This seems to be a bug in Tk and may occur in # nested modal dialogs. # # An example is the PromptDialog demonstration. To # trigger the problem, start the demo, then move the mouse # to the main window, hit <TAB> and then <TAB> again. The # highlight border of the "Show prompt dialog" button # should now be displayed. Now hit <SPACE>, <RETURN>, # <RETURN> rapidly several times. Eventually, hitting the # return key invokes the password dialog "OK" button even # though the confirm dialog is active (and therefore # should have the keyboard focus). Observed under Solaris # 2.5.1, python 1.5.2 and Tk8.0. # TODO: Give focus to the window on top of the grabstack. return command = self['command'] if callable(command): return command(name) else: if self.active(): self.deactivate(name) else: self.withdraw() def _buttons(self): buttons = self['buttons'] if type(buttons) != types.TupleType and type(buttons) != types.ListType: raise ValueError, \ 'bad buttons option "%s": should be a tuple' % str(buttons) if self.oldButtons == buttons: return self.oldButtons = buttons for index in range(self._buttonBox.numbuttons()): self._buttonBox.delete(0) for name in buttons: self._buttonBox.add(name, command=lambda self=self, name=name: self._doCommand(name)) if len(buttons) > 0: defaultbutton = self['defaultbutton'] if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) self._buttonBox.alignbuttons() def _defaultButton(self): defaultbutton = self['defaultbutton'] if self.oldDefault == defaultbutton: return self.oldDefault = defaultbutton if len(self['buttons']) > 0: if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) ###################################################################### ### File: PmwTimeFuncs.py # Functions for dealing with dates and times. import re import string def timestringtoseconds(text, separator = ':'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text sign = 1 if len(inputList[0]) > 0 and inputList[0][0] in ('+', '-'): if inputList[0][0] == '-': sign = -1 inputList[0] = inputList[0][1:] if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text hour = string.atoi(inputList[0]) minute = string.atoi(inputList[1]) second = string.atoi(inputList[2]) if minute >= 60 or second >= 60: raise ValueError, 'invalid value: ' + text return sign * (hour * 60 * 60 + minute * 60 + second) _year_pivot = 50 _century = 2000 def setyearpivot(pivot, century = None): global _year_pivot global _century oldvalues = (_year_pivot, _century) _year_pivot = pivot if century is not None: _century = century return oldvalues def datestringtojdn(text, format = 'ymd', separator = '/'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text formatList = list(format) day = string.atoi(inputList[formatList.index('d')]) month = string.atoi(inputList[formatList.index('m')]) year = string.atoi(inputList[formatList.index('y')]) if _year_pivot is not None: if year >= 0 and year < 100: if year <= _year_pivot: year = year + _century else: year = year + _century - 100 jdn = ymdtojdn(year, month, day) if jdntoymd(jdn) != (year, month, day): raise ValueError, 'invalid value: ' + text return jdn def _cdiv(a, b): # Return a / b as calculated by most C language implementations, # assuming both a and b are integers. if a * b > 0: return a / b else: return -(abs(a) / abs(b)) def ymdtojdn(year, month, day, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianDate = 15821004L # last day to use Julian calendar else: # British-American usage lastJulianDate = 17520902L # last day to use Julian calendar julian = ((year * 100L) + month) * 100 + day <= lastJulianDate if year < 0: # Adjust BC year year = year + 1 if julian: return 367L * year - _cdiv(7 * (year + 5001L + _cdiv((month - 9), 7)), 4) + \ _cdiv(275 * month, 9) + day + 1729777L else: return (day - 32076L) + \ _cdiv(1461L * (year + 4800L + _cdiv((month - 14), 12)), 4) + \ _cdiv(367 * (month - 2 - _cdiv((month - 14), 12) * 12), 12) - \ _cdiv((3 * _cdiv((year + 4900L + _cdiv((month - 14), 12)), 100)), 4) + \ 1 # correction by rdg def jdntoymd(jdn, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianJdn = 2299160L # last jdn to use Julian calendar else: # British-American usage lastJulianJdn = 2361221L # last jdn to use Julian calendar julian = (jdn <= lastJulianJdn); x = jdn + 68569L if julian: x = x + 38 daysPer400Years = 146100L fudgedDaysPer4000Years = 1461000L + 1 else: daysPer400Years = 146097L fudgedDaysPer4000Years = 1460970L + 31 z = _cdiv(4 * x, daysPer400Years) x = x - _cdiv((daysPer400Years * z + 3), 4) y = _cdiv(4000 * (x + 1), fudgedDaysPer4000Years) x = x - _cdiv(1461 * y, 4) + 31 m = _cdiv(80 * x, 2447) d = x - _cdiv(2447 * m, 80) x = _cdiv(m, 11) m = m + 2 - 12 * x y = 100 * (z - 49) + y + x # Convert from longs to integers. yy = int(y) mm = int(m) dd = int(d) if yy <= 0: # Adjust BC years. yy = yy - 1 return (yy, mm, dd) def stringtoreal(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: raise ValueError, 'invalid value: ' + text index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] return string.atof(text) ###################################################################### ### File: PmwBalloon.py import os import string import Tkinter class Balloon(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('initwait', 500, None), # milliseconds ('label_background', 'lightyellow', None), ('label_foreground', 'black', None), ('label_justify', 'left', None), ('master', 'parent', None), ('relmouse', 'none', self._relmouse), ('state', 'both', self._state), ('statuscommand', None, None), ('xoffset', 20, None), # pixels ('yoffset', 1, None), # pixels ('hull_highlightthickness', 1, None), ('hull_highlightbackground', 'black', None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) self.withdraw() self.overrideredirect(1) # Create the components. interior = self.interior() self._label = self.createcomponent('label', (), None, Tkinter.Label, (interior,)) self._label.pack() # The default hull configuration options give a black border # around the balloon, but avoids a black 'flash' when the # balloon is deiconified, before the text appears. if not kw.has_key('hull_background'): self.configure(hull_background = \ str(self._label.cget('background'))) # Initialise instance variables. self._timer = None # The widget or item that is currently triggering the balloon. # It is None if the balloon is not being displayed. It is a # one-tuple if the balloon is being displayed in response to a # widget binding (value is the widget). It is a two-tuple if # the balloon is being displayed in response to a canvas or # text item binding (value is the widget and the item). self._currentTrigger = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timer is not None: self.after_cancel(self._timer) self._timer = None MegaToplevel.destroy(self) def bind(self, widget, balloonHelp, statusHelp = None): # If a previous bind for this widget exists, remove it. self.unbind(widget) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.bind('<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 0)) # Set Motion binding so that if the pointer remains at rest # within the widget until the status line removes the help and # then the pointer moves again, then redisplay the help in the # status line. # Note: The Motion binding only works for basic widgets, and # the hull of megawidgets but not for other megawidget components. motionId = widget.bind('<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.bind('<Leave>', self._leave) buttonId = widget.bind('<ButtonPress>', self._buttonpress) # Set Destroy binding so that the balloon can be withdrawn and # the timer can be cancelled if the widget is destroyed. destroyId = widget.bind('<Destroy>', self._destroy) # Use the None item in the widget's private Pmw dictionary to # store the widget's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[None] = \ (enterId, motionId, leaveId, buttonId, destroyId) def unbind(self, widget): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(None): (enterId, motionId, leaveId, buttonId, destroyId) = \ widget._Pmw_BalloonBindIds[None] # Need to pass in old bindings, so that Tkinter can # delete the commands. Otherwise, memory is leaked. widget.unbind('<Enter>', enterId) widget.unbind('<Motion>', motionId) widget.unbind('<Leave>', leaveId) widget.unbind('<ButtonPress>', buttonId) widget.unbind('<Destroy>', destroyId) del widget._Pmw_BalloonBindIds[None] if self._currentTrigger is not None and len(self._currentTrigger) == 1: # The balloon is currently being displayed and the current # trigger is a widget. triggerWidget = self._currentTrigger[0] if triggerWidget == widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def tagbind(self, widget, tagOrItem, balloonHelp, statusHelp = None): # If a previous bind for this widget's tagOrItem exists, remove it. self.tagunbind(widget, tagOrItem) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.tag_bind(tagOrItem, '<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 1)) motionId = widget.tag_bind(tagOrItem, '<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.tag_bind(tagOrItem, '<Leave>', self._leave) buttonId = widget.tag_bind(tagOrItem, '<ButtonPress>', self._buttonpress) # Use the tagOrItem item in the widget's private Pmw dictionary to # store the tagOrItem's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[tagOrItem] = \ (enterId, motionId, leaveId, buttonId) def tagunbind(self, widget, tagOrItem): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(tagOrItem): (enterId, motionId, leaveId, buttonId) = \ widget._Pmw_BalloonBindIds[tagOrItem] widget.tag_unbind(tagOrItem, '<Enter>', enterId) widget.tag_unbind(tagOrItem, '<Motion>', motionId) widget.tag_unbind(tagOrItem, '<Leave>', leaveId) widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId) del widget._Pmw_BalloonBindIds[tagOrItem] if self._currentTrigger is None: # The balloon is not currently being displayed. return if len(self._currentTrigger) == 1: # The current trigger is a widget. return if len(self._currentTrigger) == 2: # The current trigger is a canvas item. (triggerWidget, triggerItem) = self._currentTrigger if triggerWidget == widget and triggerItem == tagOrItem: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None else: # The current trigger is a text item. (triggerWidget, x, y) = self._currentTrigger if triggerWidget == widget: currentPos = widget.index('@%d,%d' % (x, y)) currentTags = widget.tag_names(currentPos) if tagOrItem in currentTags: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def showstatus(self, statusHelp): if self['state'] in ('status', 'both'): cmd = self['statuscommand'] if callable(cmd): cmd(statusHelp) def clearstatus(self): self.showstatus(None) def _state(self): if self['state'] not in ('both', 'balloon', 'status', 'none'): raise ValueError, 'bad state option ' + repr(self['state']) + \ ': should be one of \'both\', \'balloon\', ' + \ '\'status\' or \'none\'' def _relmouse(self): if self['relmouse'] not in ('both', 'x', 'y', 'none'): raise ValueError, 'bad relmouse option ' + repr(self['relmouse'])+ \ ': should be one of \'both\', \'x\', ' + '\'y\' or \'none\'' def _enter(self, event, widget, statusHelp, balloonHelp, isItem): # Do not display balloon if mouse button is pressed. This # will only occur if the button was pressed inside a widget, # then the mouse moved out of and then back into the widget, # with the button still held down. The number 0x1f00 is the # button mask for the 5 possible buttons in X. buttonPressed = (event.state & 0x1f00) != 0 if not buttonPressed and balloonHelp is not None and \ self['state'] in ('balloon', 'both'): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self._timer = self.after(self['initwait'], lambda self = self, widget = widget, help = balloonHelp, isItem = isItem: self._showBalloon(widget, help, isItem)) if isItem: if hasattr(widget, 'canvasx'): # The widget is a canvas. item = widget.find_withtag('current') if len(item) > 0: item = item[0] else: item = None self._currentTrigger = (widget, item) else: # The widget is a text widget. self._currentTrigger = (widget, event.x, event.y) else: self._currentTrigger = (widget,) self.showstatus(statusHelp) def _leave(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _destroy(self, event): # Only withdraw the balloon and cancel the timer if the widget # being destroyed is the widget that triggered the balloon. # Note that in a Tkinter Destroy event, the widget field is a # string and not a widget as usual. if self._currentTrigger is None: # The balloon is not currently being displayed return if len(self._currentTrigger) == 1: # The current trigger is a widget (not an item) triggerWidget = self._currentTrigger[0] if str(triggerWidget) == event.widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _buttonpress(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self._currentTrigger = None def _showBalloon(self, widget, balloonHelp, isItem): self._label.configure(text = balloonHelp) # First, display the balloon offscreen to get dimensions. screenWidth = self.winfo_screenwidth() screenHeight = self.winfo_screenheight() self.geometry('+%d+0' % (screenWidth + 1)) self.update_idletasks() if isItem: # Get the bounding box of the current item. bbox = widget.bbox('current') if bbox is None: # The item that triggered the balloon has disappeared, # perhaps by a user's timer event that occured between # the <Enter> event and the 'initwait' timer calling # this method. return # The widget is either a text or canvas. The meaning of # the values returned by the bbox method is different for # each, so use the existence of the 'canvasx' method to # distinguish between them. if hasattr(widget, 'canvasx'): # The widget is a canvas. Place balloon under canvas # item. The positions returned by bbox are relative # to the entire canvas, not just the visible part, so # need to convert to window coordinates. leftrel = bbox[0] - widget.canvasx(0) toprel = bbox[1] - widget.canvasy(0) bottomrel = bbox[3] - widget.canvasy(0) else: # The widget is a text widget. Place balloon under # the character closest to the mouse. The positions # returned by bbox are relative to the text widget # window (ie the visible part of the text only). leftrel = bbox[0] toprel = bbox[1] bottomrel = bbox[1] + bbox[3] else: leftrel = 0 toprel = 0 bottomrel = widget.winfo_height() xpointer, ypointer = widget.winfo_pointerxy() # -1 if off screen if xpointer >= 0 and self['relmouse'] in ('both', 'x'): x = xpointer else: x = leftrel + widget.winfo_rootx() x = x + self['xoffset'] if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = bottomrel + widget.winfo_rooty() y = y + self['yoffset'] edges = (string.atoi(str(self.cget('hull_highlightthickness'))) + string.atoi(str(self.cget('hull_borderwidth')))) * 2 if x + self._label.winfo_reqwidth() + edges > screenWidth: x = screenWidth - self._label.winfo_reqwidth() - edges if y + self._label.winfo_reqheight() + edges > screenHeight: if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = toprel + widget.winfo_rooty() y = y - self._label.winfo_reqheight() - self['yoffset'] - edges setgeometryanddeiconify(self, '+%d+%d' % (x, y)) ###################################################################### ### File: PmwButtonBox.py # Based on iwidgets2.2.0/buttonbox.itk code. import types import Tkinter class ButtonBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 3, INITOPT), ('pady', 3, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._buttonBoxFrame = self._hull columnOrRow = 0 else: self._buttonBoxFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._buttonBoxFrame.grid(column=2, row=2, sticky='nsew') columnOrRow = 2 self.createlabel(interior) orient = self['orient'] if orient == 'horizontal': interior.grid_columnconfigure(columnOrRow, weight = 1) elif orient == 'vertical': interior.grid_rowconfigure(columnOrRow, weight = 1) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' # Initialise instance variables. # List of tuples describing the buttons: # - name # - button widget self._buttonList = [] # The index of the default button. self._defaultButton = None self._timerId = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timerId: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def numbuttons(self): return len(self._buttonList) def index(self, index, forInsert = 0): listLength = len(self._buttonList) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'ButtonBox has no buttons' elif index is DEFAULT: if self._defaultButton is not None: return self._defaultButton raise ValueError, 'ButtonBox has no default' else: names = map(lambda t: t[0], self._buttonList) if index in names: return names.index(index) validValues = 'a name, a number, END or DEFAULT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def insert(self, componentName, beforeComponent = 0, **kw): if componentName in self.components(): raise ValueError, 'button "%s" already exists' % componentName if not kw.has_key('text'): kw['text'] = componentName kw['default'] = 'normal' button = apply(self.createcomponent, (componentName, (), 'Button', Tkinter.Button, (self._buttonBoxFrame,)), kw) index = self.index(beforeComponent, 1) horizontal = self['orient'] == 'horizontal' numButtons = len(self._buttonList) # Shift buttons up one position. for i in range(numButtons - 1, index - 1, -1): widget = self._buttonList[i][1] pos = i * 2 + 3 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) # Display the new button. if horizontal: button.grid(column = index * 2 + 1, row = 0, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_columnconfigure( numButtons * 2 + 2, weight = 1) else: button.grid(column = 0, row = index * 2 + 1, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_rowconfigure( numButtons * 2 + 2, weight = 1) self._buttonList.insert(index, (componentName, button)) return button def add(self, componentName, **kw): return apply(self.insert, (componentName, len(self._buttonList)), kw) def delete(self, index): index = self.index(index) (name, widget) = self._buttonList[index] widget.grid_forget() self.destroycomponent(name) numButtons = len(self._buttonList) # Shift buttons down one position. horizontal = self['orient'] == 'horizontal' for i in range(index + 1, numButtons): widget = self._buttonList[i][1] pos = i * 2 - 1 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) if horizontal: self._buttonBoxFrame.grid_columnconfigure(numButtons * 2 - 1, minsize = 0) self._buttonBoxFrame.grid_columnconfigure(numButtons * 2, weight = 0) else: self._buttonBoxFrame.grid_rowconfigure(numButtons * 2, weight = 0) del self._buttonList[index] def setdefault(self, index): # Turn off the default ring around the current default button. if self._defaultButton is not None: button = self._buttonList[self._defaultButton][1] button.configure(default = 'normal') self._defaultButton = None # Turn on the default ring around the new default button. if index is not None: index = self.index(index) self._defaultButton = index button = self._buttonList[index][1] button.configure(default = 'active') def invoke(self, index = DEFAULT, noFlash = 0): # Invoke the callback associated with the *index* button. If # *noFlash* is not set, flash the button to indicate to the # user that something happened. button = self._buttonList[self.index(index)][1] if not noFlash: state = button.cget('state') relief = button.cget('relief') button.configure(state = 'active', relief = 'sunken') self.update_idletasks() self.after(100) button.configure(state = state, relief = relief) return button.invoke() def button(self, buttonIndex): return self._buttonList[self.index(buttonIndex)][1] def alignbuttons(self, when = 'later'): if when == 'later': if not self._timerId: self._timerId = self.after_idle(self.alignbuttons, 'now') return self.update_idletasks() self._timerId = None # Determine the width of the maximum length button. max = 0 horizontal = (self['orient'] == 'horizontal') for index in range(len(self._buttonList)): gridIndex = index * 2 + 1 if horizontal: width = self._buttonBoxFrame.grid_bbox(gridIndex, 0)[2] else: width = self._buttonBoxFrame.grid_bbox(0, gridIndex)[2] if width > max: max = width # Set the width of all the buttons to be the same. if horizontal: for index in range(len(self._buttonList)): self._buttonBoxFrame.grid_columnconfigure(index * 2 + 1, minsize = max) else: self._buttonBoxFrame.grid_columnconfigure(0, minsize = max) ###################################################################### ### File: PmwEntryField.py # Based on iwidgets2.2.0/entryfield.itk code. import re import string import types import Tkinter # Possible return values of validation functions. OK = 1 ERROR = 0 PARTIAL = -1 class EntryField(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('errorbackground', 'pink', None), ('invalidcommand', self.bell, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('modifiedcommand', None, None), ('sticky', 'ew', INITOPT), ('validate', None, self._validate), ('extravalidators', {}, None), ('value', '', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) self._entryFieldEntry.grid(column=2, row=2, sticky=self['sticky']) if self['value'] != '': self.__setEntry(self['value']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self.normalBackground = None self._previousText = None # Initialise instance. _registerEntryField(self._entryFieldEntry, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. if EntryField._classBindingsDefinedFor != Tkinter._default_root: tagList = self._entryFieldEntry.bindtags() root = Tkinter._default_root allSequences = {} for tag in tagList: sequences = root.bind_class(tag) if type(sequences) is types.StringType: # In old versions of Tkinter, bind_class returns a string sequences = root.tk.splitlist(sequences) for sequence in sequences: allSequences[sequence] = None for sequence in allSequences.keys(): root.bind_class('EntryFieldPre', sequence, _preProcess) root.bind_class('EntryFieldPost', sequence, _postProcess) EntryField._classBindingsDefinedFor = root self._entryFieldEntry.bindtags(('EntryFieldPre',) + self._entryFieldEntry.bindtags() + ('EntryFieldPost',)) self._entryFieldEntry.bind('<Return>', self._executeCommand) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): _deregisterEntryField(self._entryFieldEntry) MegaWidget.destroy(self) def _getValidatorFunc(self, validator, index): # Search the extra and standard validator lists for the # given 'validator'. If 'validator' is an alias, then # continue the search using the alias. Make sure that # self-referencial aliases do not cause infinite loops. extraValidators = self['extravalidators'] traversedValidators = [] while 1: traversedValidators.append(validator) if extraValidators.has_key(validator): validator = extraValidators[validator][index] elif _standardValidators.has_key(validator): validator = _standardValidators[validator][index] else: return validator if validator in traversedValidators: return validator def _validate(self): dict = { 'validator' : None, 'min' : None, 'max' : None, 'minstrict' : 1, 'maxstrict' : 1, } opt = self['validate'] if type(opt) is types.DictionaryType: dict.update(opt) else: dict['validator'] = opt # Look up validator maps and replace 'validator' field with # the corresponding function. validator = dict['validator'] valFunction = self._getValidatorFunc(validator, 0) self._checkValidateFunction(valFunction, 'validate', validator) dict['validator'] = valFunction # Look up validator maps and replace 'stringtovalue' field # with the corresponding function. if dict.has_key('stringtovalue'): stringtovalue = dict['stringtovalue'] strFunction = self._getValidatorFunc(stringtovalue, 1) self._checkValidateFunction( strFunction, 'stringtovalue', stringtovalue) else: strFunction = self._getValidatorFunc(validator, 1) if strFunction == validator: strFunction = len dict['stringtovalue'] = strFunction self._validationInfo = dict args = dict.copy() del args['validator'] del args['min'] del args['max'] del args['minstrict'] del args['maxstrict'] del args['stringtovalue'] self._validationArgs = args self._previousText = None if type(dict['min']) == types.StringType and strFunction is not None: dict['min'] = apply(strFunction, (dict['min'],), args) if type(dict['max']) == types.StringType and strFunction is not None: dict['max'] = apply(strFunction, (dict['max'],), args) self._checkValidity() def _checkValidateFunction(self, function, option, validator): # Raise an error if 'function' is not a function or None. if function is not None and not callable(function): extraValidators = self['extravalidators'] extra = extraValidators.keys() extra.sort() extra = tuple(extra) standard = _standardValidators.keys() standard.sort() standard = tuple(standard) msg = 'bad %s value "%s": must be a function or one of ' \ 'the standard validators %s or extra validators %s' raise ValueError, msg % (option, validator, standard, extra) def _executeCommand(self, event = None): cmd = self['command'] if callable(cmd): if event is None: # Return result of command for invoke() method. return cmd() else: cmd() def _preProcess(self): self._previousText = self._entryFieldEntry.get() self._previousICursor = self._entryFieldEntry.index('insert') self._previousXview = self._entryFieldEntry.index('@0') if self._entryFieldEntry.selection_present(): self._previousSel= (self._entryFieldEntry.index('sel.first'), self._entryFieldEntry.index('sel.last')) else: self._previousSel = None def _postProcess(self): # No need to check if text has not changed. previousText = self._previousText if previousText == self._entryFieldEntry.get(): return self.valid() valid = self._checkValidity() if self.hulldestroyed(): # The invalidcommand called by _checkValidity() destroyed us. return valid cmd = self['modifiedcommand'] if callable(cmd) and previousText != self._entryFieldEntry.get(): cmd() return valid def checkentry(self): # If there is a variable specified by the entry_textvariable # option, checkentry() should be called after the set() method # of the variable is called. self._previousText = None return self._postProcess() def _getValidity(self): text = self._entryFieldEntry.get() dict = self._validationInfo args = self._validationArgs if dict['validator'] is not None: status = apply(dict['validator'], (text,), args) if status != OK: return status # Check for out of (min, max) range. if dict['stringtovalue'] is not None: min = dict['min'] max = dict['max'] if min is None and max is None: return OK val = apply(dict['stringtovalue'], (text,), args) if min is not None and val < min: if dict['minstrict']: return ERROR else: return PARTIAL if max is not None and val > max: if dict['maxstrict']: return ERROR else: return PARTIAL return OK def _checkValidity(self): valid = self._getValidity() oldValidity = valid if valid == ERROR: # The entry is invalid. cmd = self['invalidcommand'] if callable(cmd): cmd() if self.hulldestroyed(): # The invalidcommand destroyed us. return oldValidity # Restore the entry to its previous value. if self._previousText is not None: self.__setEntry(self._previousText) self._entryFieldEntry.icursor(self._previousICursor) self._entryFieldEntry.xview(self._previousXview) if self._previousSel is not None: self._entryFieldEntry.selection_range(self._previousSel[0], self._previousSel[1]) # Check if the saved text is valid as well. valid = self._getValidity() self._valid = valid if self.hulldestroyed(): # The validator or stringtovalue commands called by # _checkValidity() destroyed us. return oldValidity if valid == OK: if self.normalBackground is not None: self._entryFieldEntry.configure( background = self.normalBackground) self.normalBackground = None else: if self.normalBackground is None: self.normalBackground = self._entryFieldEntry.cget('background') self._entryFieldEntry.configure( background = self['errorbackground']) return oldValidity def invoke(self): return self._executeCommand() def valid(self): return self._valid == OK def clear(self): self.setentry('') def __setEntry(self, text): oldState = str(self._entryFieldEntry.cget('state')) if oldState != 'normal': self._entryFieldEntry.configure(state='normal') self._entryFieldEntry.delete(0, 'end') self._entryFieldEntry.insert(0, text) if oldState != 'normal': self._entryFieldEntry.configure(state=oldState) def setentry(self, text): self._preProcess() self.__setEntry(text) return self._postProcess() def getvalue(self): return self._entryFieldEntry.get() def setvalue(self, text): return self.setentry(text) forwardmethods(EntryField, Tkinter.Entry, '_entryFieldEntry') # ====================================================================== # Entry field validation functions _numericregex = re.compile('^[0-9]*$') _alphabeticregex = re.compile('^[a-z]*$', re.IGNORECASE) _alphanumericregex = re.compile('^[0-9a-z]*$', re.IGNORECASE) def numericvalidator(text): if text == '': return PARTIAL else: if _numericregex.match(text) is None: return ERROR else: return OK def integervalidator(text): if text in ('', '-', '+'): return PARTIAL try: string.atol(text) return OK except ValueError: return ERROR def alphabeticvalidator(text): if _alphabeticregex.match(text) is None: return ERROR else: return OK def alphanumericvalidator(text): if _alphanumericregex.match(text) is None: return ERROR else: return OK def hexadecimalvalidator(text): if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'): return PARTIAL try: string.atol(text, 16) return OK except ValueError: return ERROR def realvalidator(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: return ERROR index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] try: string.atof(text) return OK except ValueError: # Check if the string could be made valid by appending a digit # eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-'). if len(text) == 0: return PARTIAL if text[-1] in string.digits: return ERROR try: string.atof(text + '0') return PARTIAL except ValueError: return ERROR def timevalidator(text, separator = ':'): try: timestringtoseconds(text, separator) return OK except ValueError: if len(text) > 0 and text[0] in ('+', '-'): text = text[1:] if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL def datevalidator(text, format = 'ymd', separator = '/'): try: datestringtojdn(text, format, separator) return OK except ValueError: if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL _standardValidators = { 'numeric' : (numericvalidator, string.atol), 'integer' : (integervalidator, string.atol), 'hexadecimal' : (hexadecimalvalidator, lambda s: string.atol(s, 16)), 'real' : (realvalidator, stringtoreal), 'alphabetic' : (alphabeticvalidator, len), 'alphanumeric' : (alphanumericvalidator, len), 'time' : (timevalidator, timestringtoseconds), 'date' : (datevalidator, datestringtojdn), } _entryCache = {} def _registerEntryField(entry, entryField): # Register an EntryField widget for an Entry widget _entryCache[entry] = entryField def _deregisterEntryField(entry): # Deregister an Entry widget del _entryCache[entry] def _preProcess(event): # Forward preprocess events for an Entry to it's EntryField _entryCache[event.widget]._preProcess() def _postProcess(event): # Forward postprocess events for an Entry to it's EntryField # The function specified by the 'command' option may have destroyed # the megawidget in a binding earlier in bindtags, so need to check. if _entryCache.has_key(event.widget): _entryCache[event.widget]._postProcess() ###################################################################### ### File: PmwGroup.py import string import Tkinter def aligngrouptags(groups): # Adjust the y position of the tags in /groups/ so that they all # have the height of the highest tag. maxTagHeight = 0 for group in groups: if group._tag is None: height = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) else: height = group._tag.winfo_reqheight() if maxTagHeight < height: maxTagHeight = height for group in groups: ringBorder = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) topBorder = maxTagHeight / 2 - ringBorder / 2 group._hull.grid_rowconfigure(0, minsize = topBorder) group._ring.grid_rowconfigure(0, minsize = maxTagHeight - topBorder - ringBorder) if group._tag is not None: group._tag.place(y = maxTagHeight / 2) class Group( MegaWidget ): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('collapsedsize', 6, INITOPT), ('ring_borderwidth', 2, None), ('ring_relief', 'groove', None), ('tagindent', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._ring = self.createcomponent( 'ring', (), None, Tkinter.Frame, (interior,), ) self._groupChildSite = self.createcomponent( 'groupchildsite', (), None, Tkinter.Frame, (self._ring,) ) self._tag = self.createcomponent( 'tag', (), None, Tkinter.Label, (interior,), ) ringBorder = (string.atoi(str(self._ring.cget('borderwidth'))) + string.atoi(str(self._ring.cget('highlightthickness')))) if self._tag is None: tagHeight = ringBorder else: tagHeight = self._tag.winfo_reqheight() self._tag.place( x = ringBorder + self['tagindent'], y = tagHeight / 2, anchor = 'w') topBorder = tagHeight / 2 - ringBorder / 2 self._ring.grid(column = 0, row = 1, sticky = 'nsew') interior.grid_columnconfigure(0, weight = 1) interior.grid_rowconfigure(1, weight = 1) interior.grid_rowconfigure(0, minsize = topBorder) self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') self._ring.grid_columnconfigure(0, weight = 1) self._ring.grid_rowconfigure(1, weight = 1) self._ring.grid_rowconfigure(0, minsize = tagHeight - topBorder - ringBorder) self.showing = 1 # Check keywords and initialise options. self.initialiseoptions() def toggle(self): if self.showing: self.collapse() else: self.expand() self.showing = not self.showing def expand(self): self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') def collapse(self): self._groupChildSite.grid_forget() if self._tag is None: tagHeight = 0 else: tagHeight = self._tag.winfo_reqheight() self._ring.configure(height=(tagHeight / 2) + self['collapsedsize']) def interior(self): return self._groupChildSite ###################################################################### ### File: PmwLabeledWidget.py import Tkinter class LabeledWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'nsew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._labelChildSite = self.createcomponent('labelchildsite', (), None, Tkinter.Frame, (interior,)) self._labelChildSite.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self._labelChildSite ###################################################################### ### File: PmwMainMenuBar.py # Main menubar import string import types import Tkinter class MainMenuBar(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('hull_tearoff', 0, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu',)) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Menu) self._menuInfo = {} self._menuInfo[None] = (None, []) # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The key for the information for the main menubar is None. self._menu = self.interior() self._menu.bind('<Leave>', self._resetHelpmessage) self._menu.bind('<Motion>', lambda event=None, self=self: self._menuHelp(event, None)) # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName).delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ parentName = self._menuInfo[menuName][0] del self._menuInfo[menuName] if parentName is None: parentMenu = self._menu else: parentMenu = self.component(parentName) menu = self.component(menuName) menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName) def disableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'disabled') def enableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, traverseSpec = None, **kw): if statusHelp is None: statusHelp = balloonHelp self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, kw) def addcascademenu(self, parentMenuName, menuName, statusHelp='', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, kw): if (menuName) in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if kw.has_key('name'): menukw['name'] = kw['name'] del kw['name'] if not kw.has_key('label'): kw['label'] = menuName self._addHotkeyToOptions(parentMenuName, kw, traverseSpec) if parentMenuName is None: parentMenu = self._menu balloon = self['balloon'] # Bug in Tk: balloon help not implemented # if balloon is not None: # balloon.mainmenubind(parentMenu, balloonHelp, statusHelp) else: parentMenu = self.component(parentMenuName) apply(parentMenu.add_cascade, (), kw) menu = apply(self.createcomponent, (menuName, (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) parentMenu.entryconfigure('end', menu = menu) self._menuInfo[parentMenuName][1].append(statusHelp) self._menuInfo[menuName] = (parentMenuName, []) menu.bind('<Leave>', self._resetHelpmessage) menu.bind('<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(event, menuName)) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName) if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key('label')): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return if menuName is None: menu = self._menu else: menu = self.component(menuName) hotkeyList = [] end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = \ string.atoi(str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, 'label')) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw['label'] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, event, menuName): if menuName is None: menu = self._menu index = menu.index('@%d'% event.x) else: menu = self.component(menuName) index = menu.index('@%d'% event.y) balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() forwardmethods(MainMenuBar, Tkinter.Menu, '_hull') ###################################################################### ### File: PmwMenuBar.py # Manager widget for menus. import string import types import Tkinter class MenuBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('padx', 0, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu', 'Button')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self._menuInfo = {} # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The third item in the tuple is the id of the binding used # to detect mouse motion to display status help. # Information for the toplevel menubuttons is not stored here. self._mydeletecommand = self.component('hull').tk.deletecommand # Cache this method for use later. # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName + '-menu').delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ # Clean up binding for this menu. parentName = self._menuInfo[menuName][0] bindId = self._menuInfo[menuName][2] _bindtag = 'PmwMenuBar' + str(self) + menuName self.unbind_class(_bindtag, '<Motion>') self._mydeletecommand(bindId) # unbind_class does not clean up del self._menuInfo[menuName] if parentName is None: self.destroycomponent(menuName + '-button') else: parentMenu = self.component(parentName + '-menu') menu = self.component(menuName + '-menu') menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName + '-menu') def disableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'disabled') def enableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, side = 'left', traverseSpec = None, **kw): self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, side, 'text', kw) def addcascademenu(self, parentMenuName, menuName, statusHelp = '', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, None, 'label', kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, side, textKey, kw): if (menuName + '-menu') in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if not kw.has_key(textKey): kw[textKey] = menuName self._addHotkeyToOptions(parentMenuName, kw, textKey, traverseSpec) if parentMenuName is None: button = apply(self.createcomponent, (menuName + '-button', (), 'Button', Tkinter.Menubutton, (self.interior(),)), kw) button.pack(side=side, padx = self['padx']) balloon = self['balloon'] if balloon is not None: balloon.bind(button, balloonHelp, statusHelp) parentMenu = button else: parentMenu = self.component(parentMenuName + '-menu') apply(parentMenu.add_cascade, (), kw) self._menuInfo[parentMenuName][1].append(statusHelp) menu = apply(self.createcomponent, (menuName + '-menu', (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) if parentMenuName is None: button.configure(menu = menu) else: parentMenu.entryconfigure('end', menu = menu) # Need to put this binding after the class bindings so that # menu.index() does not lag behind. _bindtag = 'PmwMenuBar' + str(self) + menuName bindId = self.bind_class(_bindtag, '<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(menuName)) menu.bindtags(menu.bindtags() + (_bindtag,)) menu.bind('<Leave>', self._resetHelpmessage) self._menuInfo[menuName] = (parentMenuName, [], bindId) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName + '-menu') if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, 'label', traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, textKey, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key(textKey)): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return hotkeyList = [] if menuName is None: for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') underline = string.atoi(str(menubutton.cget('underline'))) if underline != -1: label = str(menubutton.cget(textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) else: menu = self.component(menuName + '-menu') end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = string.atoi( str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw[textKey] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, menuName): menu = self.component(menuName + '-menu') index = menu.index('active') balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() ###################################################################### ### File: PmwMessageBar.py # Class to display messages in an information line. import string import Tkinter class MessageBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. defaultMessageTypes = { # (priority, showtime, bells, logmessage) 'systemerror' : (5, 10, 2, 1), 'usererror' : (4, 5, 1, 0), 'busy' : (3, 0, 0, 0), 'systemevent' : (2, 5, 0, 0), 'userevent' : (2, 5, 0, 0), 'help' : (1, 5, 0, 0), 'state' : (0, 0, 0, 0), } optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('messagetypes', defaultMessageTypes, INITOPT), ('silent', 0, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._messageBarEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') self._messageBarEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._numPriorities = 0 for info in self['messagetypes'].values(): if self._numPriorities < info[0]: self._numPriorities = info[0] self._numPriorities = self._numPriorities + 1 self._timer = [None] * self._numPriorities self._messagetext = [''] * self._numPriorities self._activemessage = [0] * self._numPriorities # Check keywords and initialise options. self.initialiseoptions() def destroy(self): for timerId in self._timer: if timerId is not None: self.after_cancel(timerId) self._timer = [None] * self._numPriorities MegaWidget.destroy(self) def message(self, type, text): # Display a message in the message bar. (priority, showtime, bells, logmessage) = self['messagetypes'][type] if not self['silent']: for i in range(bells): if i != 0: self.after(100) self.bell() self._activemessage[priority] = 1 if text is None: text = '' self._messagetext[priority] = string.replace(text, '\n', ' ') self._redisplayInfoMessage() if logmessage: # Should log this text to a text widget. pass if showtime > 0: if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) # Define a callback to clear this message after a time. def _clearmessage(self=self, priority=priority): self._clearActivemessage(priority) mseconds = int(showtime * 1000) self._timer[priority] = self.after(mseconds, _clearmessage) def helpmessage(self, text): if text is None: self.resetmessages('help') else: self.message('help', text) def resetmessages(self, type): priority = self['messagetypes'][type][0] self._clearActivemessage(priority) for messagetype, info in self['messagetypes'].items(): thisPriority = info[0] showtime = info[1] if thisPriority < priority and showtime != 0: self._clearActivemessage(thisPriority) def _clearActivemessage(self, priority): self._activemessage[priority] = 0 if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) self._timer[priority] = None self._redisplayInfoMessage() def _redisplayInfoMessage(self): text = '' for priority in range(self._numPriorities - 1, -1, -1): if self._activemessage[priority]: text = self._messagetext[priority] break self._messageBarEntry.configure(state = 'normal') self._messageBarEntry.delete(0, 'end') self._messageBarEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') forwardmethods(MessageBar, Tkinter.Entry, '_messageBarEntry') ###################################################################### ### File: PmwMessageDialog.py # Based on iwidgets2.2.0/messagedialog.itk code. import Tkinter class MessageDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ('iconmargin', 20, INITOPT), ('iconpos', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() self._message = self.createcomponent('message', (), None, Tkinter.Label, (interior,)) iconpos = self['iconpos'] iconmargin = self['iconmargin'] borderx = self['borderx'] bordery = self['bordery'] border_right = 2 border_bottom = 2 if iconpos is None: self._message.grid(column = 1, row = 1) else: self._icon = self.createcomponent('icon', (), None, Tkinter.Label, (interior,)) if iconpos not in 'nsew': raise ValueError, \ 'bad iconpos option "%s": should be n, s, e, or w' \ % iconpos if iconpos in 'nw': icon = 1 message = 3 else: icon = 3 message = 1 if iconpos in 'ns': # vertical layout self._icon.grid(column = 1, row = icon) self._message.grid(column = 1, row = message) interior.grid_rowconfigure(2, minsize = iconmargin) border_bottom = 4 else: # horizontal layout self._icon.grid(column = icon, row = 1) self._message.grid(column = message, row = 1) interior.grid_columnconfigure(2, minsize = iconmargin) border_right = 4 interior.grid_columnconfigure(0, minsize = borderx) interior.grid_rowconfigure(0, minsize = bordery) interior.grid_columnconfigure(border_right, minsize = borderx) interior.grid_rowconfigure(border_bottom, minsize = bordery) # Check keywords and initialise options. self.initialiseoptions() ###################################################################### ### File: PmwNoteBook.py import string import types import Tkinter class NoteBook(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('hull_highlightthickness', 0, None), ('hull_borderwidth', 0, None), ('arrownavigation', 1, INITOPT), ('borderwidth', 2, INITOPT), ('createcommand', None, None), ('lowercommand', None, None), ('pagemargin', 4, INITOPT), ('raisecommand', None, None), ('tabpos', 'n', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Page', 'Tab')) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Canvas) self.bind('<Map>', self._handleMap) self.bind('<Configure>', self._handleConfigure) tabpos = self['tabpos'] if tabpos is not None and tabpos != 'n': raise ValueError, \ 'bad tabpos option %s: should be n or None' % repr(tabpos) self._withTabs = (tabpos is not None) self._pageMargin = self['pagemargin'] self._borderWidth = self['borderwidth'] # Use a dictionary as a set of bits indicating what needs to # be redisplayed the next time _layout() is called. If # dictionary contains 'topPage' key, the value is the new top # page to be displayed. None indicates that all pages have # been deleted and that _layout() should draw a border under where # the tabs should be. self._pending = {} self._pending['size'] = 1 self._pending['borderColor'] = 1 self._pending['topPage'] = None if self._withTabs: self._pending['tabs'] = 1 self._canvasSize = None # This gets set by <Configure> events # Set initial height of space for tabs if self._withTabs: self.tabBottom = 35 else: self.tabBottom = 0 self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) self._pageNames = [] # List of page names # Map from page name to page info. Each item is itself a # dictionary containing the following items: # page the Tkinter.Frame widget for the page # created set to true the first time the page is raised # tabbutton the Tkinter.Button widget for the button (if any) # tabreqwidth requested width of the tab # tabreqheight requested height of the tab # tabitems the canvas items for the button: the button # window item, the lightshadow and the darkshadow # left the left and right canvas coordinates of the tab # right self._pageAttrs = {} # Name of page currently on top (actually displayed, using # create_window, not pending). Ignored if current top page # has been deleted or new top page is pending. None indicates # no pages in notebook. self._topPageName = None # Canvas items used: # Per tab: # top and left shadow # right shadow # button # Per notebook: # page # top page # left shadow # bottom and right shadow # top (one or two items) # Canvas tags used: # lighttag - top and left shadows of tabs and page # darktag - bottom and right shadows of tabs and page # (if no tabs then these are reversed) # (used to color the borders by recolorborders) # Create page border shadows. if self._withTabs: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageTop1Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') self._pageTop2Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') else: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageTopBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') # Check keywords and initialise options. self.initialiseoptions() def insert(self, pageName, before = 0, **kw): if self._pageAttrs.has_key(pageName): msg = 'Page "%s" already exists.' % pageName raise ValueError, msg # Do this early to catch bad <before> spec before creating any items. beforeIndex = self.index(before, 1) pageOptions = {} if self._withTabs: # Default tab button options. tabOptions = { 'text' : pageName, 'borderwidth' : 0, } # Divide the keyword options into the 'page_' and 'tab_' options. for key in kw.keys(): if key[:5] == 'page_': pageOptions[key[5:]] = kw[key] del kw[key] elif self._withTabs and key[:4] == 'tab_': tabOptions[key[4:]] = kw[key] del kw[key] else: raise KeyError, 'Unknown option "' + key + '"' # Create the frame to contain the page. page = apply(self.createcomponent, (pageName, (), 'Page', Tkinter.Frame, self._hull), pageOptions) attributes = {} attributes['page'] = page attributes['created'] = 0 if self._withTabs: # Create the button for the tab. def raiseThisPage(self = self, pageName = pageName): self.selectpage(pageName) tabOptions['command'] = raiseThisPage tab = apply(self.createcomponent, (pageName + '-tab', (), 'Tab', Tkinter.Button, self._hull), tabOptions) if self['arrownavigation']: # Allow the use of the arrow keys for Tab navigation: def next(event, self = self, pageName = pageName): self.nextpage(pageName) def prev(event, self = self, pageName = pageName): self.previouspage(pageName) tab.bind('<Left>', prev) tab.bind('<Right>', next) attributes['tabbutton'] = tab attributes['tabreqwidth'] = tab.winfo_reqwidth() attributes['tabreqheight'] = tab.winfo_reqheight() # Create the canvas item to manage the tab's button and the items # for the tab's shadow. windowitem = self.create_window(0, 0, window = tab, anchor = 'nw') lightshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'lighttag', fill = self._lightBorderColor) darkshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'darktag', fill = self._darkBorderColor) attributes['tabitems'] = (windowitem, lightshadow, darkshadow) self._pending['tabs'] = 1 self._pageAttrs[pageName] = attributes self._pageNames.insert(beforeIndex, pageName) # If this is the first page added, make it the new top page # and call the create and raise callbacks. if self.getcurselection() is None: self._pending['topPage'] = pageName self._raiseNewTop(pageName) self._layout() return page def add(self, pageName, **kw): return apply(self.insert, (pageName, len(self._pageNames)), kw) def delete(self, *pageNames): newTopPage = 0 for page in pageNames: pageIndex = self.index(page) pageName = self._pageNames[pageIndex] pageInfo = self._pageAttrs[pageName] if self.getcurselection() == pageName: if len(self._pageNames) == 1: newTopPage = 0 self._pending['topPage'] = None elif pageIndex == len(self._pageNames) - 1: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex - 1] else: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex + 1] if self._topPageName == pageName: self._hull.delete(self._topPageItem) self._topPageName = None if self._withTabs: self.destroycomponent(pageName + '-tab') apply(self._hull.delete, pageInfo['tabitems']) self.destroycomponent(pageName) del self._pageAttrs[pageName] del self._pageNames[pageIndex] # If the old top page was deleted and there are still pages # left in the notebook, call the create and raise callbacks. if newTopPage: pageName = self._pending['topPage'] self._raiseNewTop(pageName) if self._withTabs: self._pending['tabs'] = 1 self._layout() def page(self, pageIndex): pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['page'] def pagenames(self): return list(self._pageNames) def getcurselection(self): if self._pending.has_key('topPage'): return self._pending['topPage'] else: return self._topPageName def tab(self, pageIndex): if self._withTabs: pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['tabbutton'] else: return None def index(self, index, forInsert = 0): listLength = len(self._pageNames) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'NoteBook has no pages' elif index is SELECT: if listLength == 0: raise ValueError, 'NoteBook has no pages' return self._pageNames.index(self.getcurselection()) else: if index in self._pageNames: return self._pageNames.index(index) validValues = 'a name, a number, END or SELECT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def selectpage(self, page): pageName = self._pageNames[self.index(page)] oldTopPage = self.getcurselection() if pageName != oldTopPage: self._pending['topPage'] = pageName if oldTopPage == self._topPageName: self._hull.delete(self._topPageItem) cmd = self['lowercommand'] if cmd is not None: cmd(oldTopPage) self._raiseNewTop(pageName) self._layout() # Set focus to the tab of new top page: if self._withTabs and self['arrownavigation']: self._pageAttrs[pageName]['tabbutton'].focus_set() def previouspage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage > 0: self.selectpage(curpage - 1) def nextpage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage < len(self._pageNames) - 1: self.selectpage(curpage + 1) def setnaturalsize(self, pageNames = None): self.update_idletasks() maxPageWidth = 1 maxPageHeight = 1 if pageNames is None: pageNames = self.pagenames() for pageName in pageNames: pageInfo = self._pageAttrs[pageName] page = pageInfo['page'] w = page.winfo_reqwidth() h = page.winfo_reqheight() if maxPageWidth < w: maxPageWidth = w if maxPageHeight < h: maxPageHeight = h pageBorder = self._borderWidth + self._pageMargin width = maxPageWidth + pageBorder * 2 height = maxPageHeight + pageBorder * 2 if self._withTabs: maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] height = height + maxTabHeight + self._borderWidth * 1.5 # Note that, since the hull is a canvas, the width and height # options specify the geometry *inside* the borderwidth and # highlightthickness. self.configure(hull_width = width, hull_height = height) def recolorborders(self): self._pending['borderColor'] = 1 self._layout() def _handleMap(self, event): self._layout() def _handleConfigure(self, event): self._canvasSize = (event.width, event.height) self._pending['size'] = 1 self._layout() def _raiseNewTop(self, pageName): if not self._pageAttrs[pageName]['created']: self._pageAttrs[pageName]['created'] = 1 cmd = self['createcommand'] if cmd is not None: cmd(pageName) cmd = self['raisecommand'] if cmd is not None: cmd(pageName) # This is the vertical layout of the notebook, from top (assuming # tabpos is 'n'): # hull highlightthickness (top) # hull borderwidth (top) # borderwidth (top border of tabs) # borderwidth * 0.5 (space for bevel) # tab button (maximum of requested height of all tab buttons) # borderwidth (border between tabs and page) # pagemargin (top) # the page itself # pagemargin (bottom) # borderwidth (border below page) # hull borderwidth (bottom) # hull highlightthickness (bottom) # # canvasBorder is sum of top two elements. # tabBottom is sum of top five elements. # # Horizontal layout (and also vertical layout when tabpos is None): # hull highlightthickness # hull borderwidth # borderwidth # pagemargin # the page itself # pagemargin # borderwidth # hull borderwidth # hull highlightthickness # def _layout(self): if not self.winfo_ismapped() or self._canvasSize is None: # Don't layout if the window is not displayed, or we # haven't yet received a <Configure> event. return hullWidth, hullHeight = self._canvasSize borderWidth = self._borderWidth canvasBorder = string.atoi(self._hull['borderwidth']) + \ string.atoi(self._hull['highlightthickness']) if not self._withTabs: self.tabBottom = canvasBorder oldTabBottom = self.tabBottom if self._pending.has_key('borderColor'): self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) # Draw all the tabs. if self._withTabs and (self._pending.has_key('tabs') or self._pending.has_key('size')): # Find total requested width and maximum requested height # of tabs. sumTabReqWidth = 0 maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): sumTabReqWidth = sumTabReqWidth + pageInfo['tabreqwidth'] if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] if maxTabHeight != 0: # Add the top tab border plus a bit for the angled corners self.tabBottom = canvasBorder + maxTabHeight + borderWidth * 1.5 # Prepare for drawing the border around each tab button. tabTop = canvasBorder tabTop2 = tabTop + borderWidth tabTop3 = tabTop + borderWidth * 1.5 tabBottom2 = self.tabBottom tabBottom = self.tabBottom + borderWidth numTabs = len(self._pageNames) availableWidth = hullWidth - 2 * canvasBorder - \ numTabs * 2 * borderWidth x = canvasBorder cumTabReqWidth = 0 cumTabWidth = 0 # Position all the tabs. for pageName in self._pageNames: pageInfo = self._pageAttrs[pageName] (windowitem, lightshadow, darkshadow) = pageInfo['tabitems'] if sumTabReqWidth <= availableWidth: tabwidth = pageInfo['tabreqwidth'] else: # This ugly calculation ensures that, when the # notebook is not wide enough for the requested # widths of the tabs, the total width given to # the tabs exactly equals the available width, # without rounding errors. cumTabReqWidth = cumTabReqWidth + pageInfo['tabreqwidth'] tmp = (2*cumTabReqWidth*availableWidth + sumTabReqWidth) \ / (2 * sumTabReqWidth) tabwidth = tmp - cumTabWidth cumTabWidth = tmp # Position the tab's button canvas item. self.coords(windowitem, x + borderWidth, tabTop3) self.itemconfigure(windowitem, width = tabwidth, height = maxTabHeight) # Make a beautiful border around the tab. left = x left2 = left + borderWidth left3 = left + borderWidth * 1.5 right = left + tabwidth + 2 * borderWidth right2 = left + tabwidth + borderWidth right3 = left + tabwidth + borderWidth * 0.5 self.coords(lightshadow, left, tabBottom2, left, tabTop2, left2, tabTop, right2, tabTop, right3, tabTop2, left3, tabTop2, left2, tabTop3, left2, tabBottom, ) self.coords(darkshadow, right2, tabTop, right, tabTop2, right, tabBottom2, right2, tabBottom, right2, tabTop3, right3, tabTop2, ) pageInfo['left'] = left pageInfo['right'] = right x = x + tabwidth + 2 * borderWidth # Redraw shadow under tabs so that it appears that tab for old # top page is lowered and that tab for new top page is raised. if self._withTabs and (self._pending.has_key('topPage') or self._pending.has_key('tabs') or self._pending.has_key('size')): if self.getcurselection() is None: # No pages, so draw line across top of page area. self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Ignore second top border. self.coords(self._pageTop2Border, 0, 0, 0, 0, 0, 0) else: # Draw two lines, one on each side of the tab for the # top page, so that the tab appears to be raised. pageInfo = self._pageAttrs[self.getcurselection()] left = pageInfo['left'] right = pageInfo['right'] self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, left, self.tabBottom, left + borderWidth, self.tabBottom + borderWidth, canvasBorder + borderWidth, self.tabBottom + borderWidth, ) self.coords(self._pageTop2Border, right, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, right - borderWidth, self.tabBottom + borderWidth, ) # Prevent bottom of dark border of tabs appearing over # page top border. self.tag_raise(self._pageTop1Border) self.tag_raise(self._pageTop2Border) # Position the page border shadows. if self._pending.has_key('size') or oldTabBottom != self.tabBottom: self.coords(self._pageLeftBorder, canvasBorder, self.tabBottom, borderWidth + canvasBorder, self.tabBottom + borderWidth, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, canvasBorder, hullHeight - canvasBorder, ) self.coords(self._pageBottomRightBorder, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder, hullHeight - canvasBorder, canvasBorder, hullHeight - canvasBorder, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, ) if not self._withTabs: self.coords(self._pageTopBorder, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Color borders. if self._pending.has_key('borderColor'): self.itemconfigure('lighttag', fill = self._lightBorderColor) self.itemconfigure('darktag', fill = self._darkBorderColor) newTopPage = self._pending.get('topPage') pageBorder = borderWidth + self._pageMargin # Raise new top page. if newTopPage is not None: self._topPageName = newTopPage self._topPageItem = self.create_window( pageBorder + canvasBorder, self.tabBottom + pageBorder, window = self._pageAttrs[newTopPage]['page'], anchor = 'nw', ) # Change position of top page if tab height has changed. if self._topPageName is not None and oldTabBottom != self.tabBottom: self.coords(self._topPageItem, pageBorder + canvasBorder, self.tabBottom + pageBorder) # Change size of top page if, # 1) there is a new top page. # 2) canvas size has changed, but not if there is no top # page (eg: initially or when all pages deleted). # 3) tab height has changed, due to difference in the height of a tab if (newTopPage is not None or \ self._pending.has_key('size') and self._topPageName is not None or oldTabBottom != self.tabBottom): self.itemconfigure(self._topPageItem, width = hullWidth - 2 * canvasBorder - pageBorder * 2, height = hullHeight - 2 * canvasBorder - pageBorder * 2 - (self.tabBottom - canvasBorder), ) self._pending = {} # Need to do forwarding to get the pack, grid, etc methods. # Unfortunately this means that all the other canvas methods are also # forwarded. forwardmethods(NoteBook, Tkinter.Canvas, '_hull') ###################################################################### ### File: PmwOptionMenu.py import types import Tkinter class OptionMenu(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('items', (), INITOPT), ('initialitem', None, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._menubutton = self.createcomponent('menubutton', (), None, Tkinter.Menubutton, (interior,), borderwidth = 2, indicatoron = 1, relief = 'raised', anchor = 'c', highlightthickness = 2, direction = 'flush', takefocus = 1, ) self._menubutton.grid(column = 2, row = 2, sticky = self['sticky']) self._menu = self.createcomponent('menu', (), None, Tkinter.Menu, (self._menubutton,), tearoff=0 ) self._menubutton.configure(menu = self._menu) interior.grid_columnconfigure(2, weight = 1) interior.grid_rowconfigure(2, weight = 1) # Create the label. self.createlabel(interior) # Add the items specified by the initialisation option. self._itemList = [] self.setitems(self['items'], self['initialitem']) # Check keywords and initialise options. self.initialiseoptions() def setitems(self, items, index = None): # Clean up old items and callback commands. for oldIndex in range(len(self._itemList)): tclCommandName = str(self._menu.entrycget(oldIndex, 'command')) if tclCommandName != '': self._menu.deletecommand(tclCommandName) self._menu.delete(0, 'end') self._itemList = list(items) # Set the items in the menu component. for item in items: self._menu.add_command(label = item, command = lambda self = self, item = item: self._invoke(item)) # Set the currently selected value. if index is None: var = str(self._menubutton.cget('textvariable')) if var != '': # None means do not change text variable. return if len(items) == 0: text = '' elif str(self._menubutton.cget('text')) in items: # Do not change selection if it is still valid return else: text = items[0] else: index = self.index(index) text = self._itemList[index] self.setvalue(text) def getcurselection(self): var = str(self._menubutton.cget('textvariable')) if var == '': return str(self._menubutton.cget('text')) else: return self._menu.tk.globalgetvar(var) def getvalue(self): return self.getcurselection() def setvalue(self, text): var = str(self._menubutton.cget('textvariable')) if var == '': self._menubutton.configure(text = text) else: self._menu.tk.globalsetvar(var, text) def index(self, index): listLength = len(self._itemList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'OptionMenu has no items' else: if index is SELECT: if listLength > 0: index = self.getcurselection() else: raise ValueError, 'OptionMenu has no items' if index in self._itemList: return self._itemList.index(index) raise ValueError, \ 'bad index "%s": must be a ' \ 'name, a number, END or SELECT' % (index,) def invoke(self, index = SELECT): index = self.index(index) text = self._itemList[index] return self._invoke(text) def _invoke(self, text): self.setvalue(text) command = self['command'] if callable(command): return command(text) ###################################################################### ### File: PmwPanedWidget.py # PanedWidget # a frame which may contain several resizable sub-frames import string import sys import types import Tkinter class PanedWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('orient', 'vertical', INITOPT), ('separatorrelief', 'sunken', INITOPT), ('separatorthickness', 2, INITOPT), ('handlesize', 8, INITOPT), ('hull_width', 400, None), ('hull_height', 400, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Frame', 'Separator', 'Handle')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.bind('<Configure>', self._handleConfigure) if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' self._separatorThickness = self['separatorthickness'] self._handleSize = self['handlesize'] self._paneNames = [] # List of pane names self._paneAttrs = {} # Map from pane name to pane info self._timerId = None self._frame = {} self._separator = [] self._button = [] self._totalSize = 0 self._movePending = 0 self._relsize = {} self._relmin = {} self._relmax = {} self._size = {} self._min = {} self._max = {} self._rootp = None self._curSize = None self._beforeLimit = None self._afterLimit = None self._buttonIsDown = 0 self._majorSize = 100 self._minorSize = 100 # Check keywords and initialise options. self.initialiseoptions() def insert(self, name, before = 0, **kw): # Parse <kw> for options. self._initPaneOptions(name) self._parsePaneOptions(name, kw) insertPos = self._nameToIndex(before) atEnd = (insertPos == len(self._paneNames)) # Add the frame. self._paneNames[insertPos:insertPos] = [name] self._frame[name] = self.createcomponent(name, (), 'Frame', Tkinter.Frame, (self.interior(),)) # Add separator, if necessary. if len(self._paneNames) > 1: self._addSeparator() else: self._separator.append(None) self._button.append(None) # Add the new frame and adjust the PanedWidget if atEnd: size = self._size[name] if size > 0 or self._relsize[name] is not None: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, height=size, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, width=size, x=self._totalSize) else: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, x=self._totalSize) else: self._updateSizes() self._totalSize = self._totalSize + self._size[name] return self._frame[name] def add(self, name, **kw): return apply(self.insert, (name, len(self._paneNames)), kw) def delete(self, name): deletePos = self._nameToIndex(name) name = self._paneNames[deletePos] self.destroycomponent(name) del self._paneNames[deletePos] del self._frame[name] del self._size[name] del self._min[name] del self._max[name] del self._relsize[name] del self._relmin[name] del self._relmax[name] last = len(self._paneNames) del self._separator[last] del self._button[last] if last > 0: self.destroycomponent(self._sepName(last)) self.destroycomponent(self._buttonName(last)) self._plotHandles() def setnaturalsize(self): self.update_idletasks() totalWidth = 0 totalHeight = 0 maxWidth = 0 maxHeight = 0 for name in self._paneNames: frame = self._frame[name] w = frame.winfo_reqwidth() h = frame.winfo_reqheight() totalWidth = totalWidth + w totalHeight = totalHeight + h if maxWidth < w: maxWidth = w if maxHeight < h: maxHeight = h # Note that, since the hull is a frame, the width and height # options specify the geometry *outside* the borderwidth and # highlightthickness. bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 if str(self.cget('orient')) == 'horizontal': totalWidth = totalWidth + extra maxHeight = maxHeight + extra self.configure(hull_width = totalWidth, hull_height = maxHeight) else: totalHeight = (totalHeight + extra + (len(self._paneNames) - 1) * self._separatorThickness) maxWidth = maxWidth + extra self.configure(hull_width = maxWidth, hull_height = totalHeight) def move(self, name, newPos, newPosOffset = 0): # see if we can spare ourselves some work numPanes = len(self._paneNames) if numPanes < 2: return newPos = self._nameToIndex(newPos) + newPosOffset if newPos < 0 or newPos >=numPanes: return deletePos = self._nameToIndex(name) if deletePos == newPos: # inserting over ourself is a no-op return # delete name from old position in list name = self._paneNames[deletePos] del self._paneNames[deletePos] # place in new position self._paneNames[newPos:newPos] = [name] # force everything to redraw self._plotHandles() self._updateSizes() def _nameToIndex(self, nameOrIndex): try: pos = self._paneNames.index(nameOrIndex) except ValueError: pos = nameOrIndex return pos def _initPaneOptions(self, name): # Set defaults. self._size[name] = 0 self._relsize[name] = None self._min[name] = 0 self._relmin[name] = None self._max[name] = 100000 self._relmax[name] = None def _parsePaneOptions(self, name, args): # Parse <args> for options. for arg, value in args.items(): if type(value) == types.FloatType: relvalue = value value = self._absSize(relvalue) else: relvalue = None if arg == 'size': self._size[name], self._relsize[name] = value, relvalue elif arg == 'min': self._min[name], self._relmin[name] = value, relvalue elif arg == 'max': self._max[name], self._relmax[name] = value, relvalue else: raise ValueError, 'keyword must be "size", "min", or "max"' def _absSize(self, relvalue): return int(round(relvalue * self._majorSize)) def _sepName(self, n): return 'separator-%d' % n def _buttonName(self, n): return 'handle-%d' % n def _addSeparator(self): n = len(self._paneNames) - 1 downFunc = lambda event, s = self, num=n: s._btnDown(event, num) upFunc = lambda event, s = self, num=n: s._btnUp(event, num) moveFunc = lambda event, s = self, num=n: s._btnMove(event, num) # Create the line dividing the panes. sep = self.createcomponent(self._sepName(n), (), 'Separator', Tkinter.Frame, (self.interior(),), borderwidth = 1, relief = self['separatorrelief']) self._separator.append(sep) sep.bind('<ButtonPress-1>', downFunc) sep.bind('<Any-ButtonRelease-1>', upFunc) sep.bind('<B1-Motion>', moveFunc) if self['orient'] == 'vertical': cursor = 'sb_v_double_arrow' sep.configure(height = self._separatorThickness, width = 10000, cursor = cursor) else: cursor = 'sb_h_double_arrow' sep.configure(width = self._separatorThickness, height = 10000, cursor = cursor) self._totalSize = self._totalSize + self._separatorThickness # Create the handle on the dividing line. handle = self.createcomponent(self._buttonName(n), (), 'Handle', Tkinter.Frame, (self.interior(),), relief = 'raised', borderwidth = 1, width = self._handleSize, height = self._handleSize, cursor = cursor, ) self._button.append(handle) handle.bind('<ButtonPress-1>', downFunc) handle.bind('<Any-ButtonRelease-1>', upFunc) handle.bind('<B1-Motion>', moveFunc) self._plotHandles() for i in range(1, len(self._paneNames)): self._separator[i].tkraise() for i in range(1, len(self._paneNames)): self._button[i].tkraise() def _btnUp(self, event, item): self._buttonIsDown = 0 self._updateSizes() try: self._button[item].configure(relief='raised') except: pass def _btnDown(self, event, item): self._button[item].configure(relief='sunken') self._getMotionLimit(item) self._buttonIsDown = 1 self._movePending = 0 def _handleConfigure(self, event = None): self._getNaturalSizes() if self._totalSize == 0: return iterRange = list(self._paneNames) iterRange.reverse() if self._majorSize > self._totalSize: n = self._majorSize - self._totalSize self._iterate(iterRange, self._grow, n) elif self._majorSize < self._totalSize: n = self._totalSize - self._majorSize self._iterate(iterRange, self._shrink, n) self._plotHandles() self._updateSizes() def _getNaturalSizes(self): # Must call this in order to get correct winfo_width, winfo_height self.update_idletasks() self._totalSize = 0 if self['orient'] == 'vertical': self._majorSize = self.winfo_height() self._minorSize = self.winfo_width() majorspec = Tkinter.Frame.winfo_reqheight else: self._majorSize = self.winfo_width() self._minorSize = self.winfo_height() majorspec = Tkinter.Frame.winfo_reqwidth bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 self._majorSize = self._majorSize - extra self._minorSize = self._minorSize - extra if self._majorSize < 0: self._majorSize = 0 if self._minorSize < 0: self._minorSize = 0 for name in self._paneNames: # adjust the absolute sizes first... if self._relsize[name] is None: #special case if self._size[name] == 0: self._size[name] = apply(majorspec, (self._frame[name],)) self._setrel(name) else: self._size[name] = self._absSize(self._relsize[name]) if self._relmin[name] is not None: self._min[name] = self._absSize(self._relmin[name]) if self._relmax[name] is not None: self._max[name] = self._absSize(self._relmax[name]) # now adjust sizes if self._size[name] < self._min[name]: self._size[name] = self._min[name] self._setrel(name) if self._size[name] > self._max[name]: self._size[name] = self._max[name] self._setrel(name) self._totalSize = self._totalSize + self._size[name] # adjust for separators self._totalSize = (self._totalSize + (len(self._paneNames) - 1) * self._separatorThickness) def _setrel(self, name): if self._relsize[name] is not None: if self._majorSize != 0: self._relsize[name] = round(self._size[name]) / self._majorSize def _iterate(self, names, proc, n): for i in names: n = apply(proc, (i, n)) if n == 0: break def _grow(self, name, n): canGrow = self._max[name] - self._size[name] if canGrow > n: self._size[name] = self._size[name] + n self._setrel(name) return 0 elif canGrow > 0: self._size[name] = self._max[name] self._setrel(name) n = n - canGrow return n def _shrink(self, name, n): canShrink = self._size[name] - self._min[name] if canShrink > n: self._size[name] = self._size[name] - n self._setrel(name) return 0 elif canShrink > 0: self._size[name] = self._min[name] self._setrel(name) n = n - canShrink return n def _updateSizes(self): totalSize = 0 for name in self._paneNames: size = self._size[name] if self['orient'] == 'vertical': self._frame[name].place(x = 0, relwidth = 1, y = totalSize, height = size) else: self._frame[name].place(y = 0, relheight = 1, x = totalSize, width = size) totalSize = totalSize + size + self._separatorThickness # Invoke the callback command cmd = self['command'] if callable(cmd): cmd(map(lambda x, s = self: s._size[x], self._paneNames)) def _plotHandles(self): if len(self._paneNames) == 0: return if self['orient'] == 'vertical': btnp = self._minorSize - 13 else: h = self._minorSize if h > 18: btnp = 9 else: btnp = h - 9 firstPane = self._paneNames[0] totalSize = self._size[firstPane] first = 1 last = len(self._paneNames) - 1 # loop from first to last, inclusive for i in range(1, last + 1): handlepos = totalSize - 3 prevSize = self._size[self._paneNames[i - 1]] nextSize = self._size[self._paneNames[i]] offset1 = 0 if i == first: if prevSize < 4: offset1 = 4 - prevSize else: if prevSize < 8: offset1 = (8 - prevSize) / 2 offset2 = 0 if i == last: if nextSize < 4: offset2 = nextSize - 4 else: if nextSize < 8: offset2 = (nextSize - 8) / 2 handlepos = handlepos + offset1 if self['orient'] == 'vertical': height = 8 - offset1 + offset2 if height > 1: self._button[i].configure(height = height) self._button[i].place(x = btnp, y = handlepos) else: self._button[i].place_forget() self._separator[i].place(x = 0, y = totalSize, relwidth = 1) else: width = 8 - offset1 + offset2 if width > 1: self._button[i].configure(width = width) self._button[i].place(y = btnp, x = handlepos) else: self._button[i].place_forget() self._separator[i].place(y = 0, x = totalSize, relheight = 1) totalSize = totalSize + nextSize + self._separatorThickness def pane(self, name): return self._frame[self._paneNames[self._nameToIndex(name)]] # Return the name of all panes def panes(self): return list(self._paneNames) def configurepane(self, name, **kw): name = self._paneNames[self._nameToIndex(name)] self._parsePaneOptions(name, kw) self._handleConfigure() def updatelayout(self): self._handleConfigure() def _getMotionLimit(self, item): curBefore = (item - 1) * self._separatorThickness minBefore, maxBefore = curBefore, curBefore for name in self._paneNames[:item]: curBefore = curBefore + self._size[name] minBefore = minBefore + self._min[name] maxBefore = maxBefore + self._max[name] curAfter = (len(self._paneNames) - item) * self._separatorThickness minAfter, maxAfter = curAfter, curAfter for name in self._paneNames[item:]: curAfter = curAfter + self._size[name] minAfter = minAfter + self._min[name] maxAfter = maxAfter + self._max[name] beforeToGo = min(curBefore - minBefore, maxAfter - curAfter) afterToGo = min(curAfter - minAfter, maxBefore - curBefore) self._beforeLimit = curBefore - beforeToGo self._afterLimit = curBefore + afterToGo self._curSize = curBefore self._plotHandles() # Compress the motion so that update is quick even on slow machines # # theRootp = root position (either rootx or rooty) def _btnMove(self, event, item): self._rootp = event if self._movePending == 0: self._timerId = self.after_idle( lambda s = self, i = item: s._btnMoveCompressed(i)) self._movePending = 1 def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def _btnMoveCompressed(self, item): if not self._buttonIsDown: return if self['orient'] == 'vertical': p = self._rootp.y_root - self.winfo_rooty() else: p = self._rootp.x_root - self.winfo_rootx() if p == self._curSize: self._movePending = 0 return if p < self._beforeLimit: p = self._beforeLimit if p >= self._afterLimit: p = self._afterLimit self._calculateChange(item, p) self.update_idletasks() self._movePending = 0 # Calculate the change in response to mouse motions def _calculateChange(self, item, p): if p < self._curSize: self._moveBefore(item, p) elif p > self._curSize: self._moveAfter(item, p) self._plotHandles() def _moveBefore(self, item, p): n = self._curSize - p # Shrink the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._shrink, n) # Adjust the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._grow, n) self._curSize = p def _moveAfter(self, item, p): n = p - self._curSize # Shrink the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._shrink, n) # Adjust the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._grow, n) self._curSize = p ###################################################################### ### File: PmwPromptDialog.py # Based on iwidgets2.2.0/promptdialog.itk code. # A Dialog with an entryfield class PromptDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('entry', 'entryfield_entry'), ('label', 'entryfield_label'), ) self._promptDialogEntry = self.createcomponent('entryfield', aliases, None, EntryField, (interior,)) self._promptDialogEntry.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # EntryField's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._promptDialogEntry.insert(index, text) def deleteentry(self, first, last=None): self._promptDialogEntry.delete(first, last) def indexentry(self, index): return self._promptDialogEntry.index(index) forwardmethods(PromptDialog, EntryField, '_promptDialogEntry') ###################################################################### ### File: PmwRadioSelect.py import types import Tkinter class RadioSelect(MegaWidget): # A collection of several buttons. In single mode, only one # button may be selected. In multiple mode, any number of buttons # may be selected. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttontype', 'button', INITOPT), ('command', None, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 5, INITOPT), ('pady', 5, INITOPT), ('selectmode', 'single', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._radioSelectFrame = self._hull else: self._radioSelectFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._radioSelectFrame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._buttonList = [] if self['selectmode'] == 'single': self._singleSelect = 1 elif self['selectmode'] == 'multiple': self._singleSelect = 0 else: raise ValueError, 'bad selectmode option "' + \ self['selectmode'] + '": should be single or multiple' if self['buttontype'] == 'button': self.buttonClass = Tkinter.Button elif self['buttontype'] == 'radiobutton': self._singleSelect = 1 self.var = Tkinter.StringVar() self.buttonClass = Tkinter.Radiobutton elif self['buttontype'] == 'checkbutton': self._singleSelect = 0 self.buttonClass = Tkinter.Checkbutton else: raise ValueError, 'bad buttontype option "' + \ self['buttontype'] + \ '": should be button, radiobutton or checkbutton' if self._singleSelect: self.selection = None else: self.selection = [] if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' # Check keywords and initialise options. self.initialiseoptions() def getcurselection(self): if self._singleSelect: return self.selection else: return tuple(self.selection) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): if self._singleSelect: self.__setSingleValue(textOrList) else: # Multiple selections oldselection = self.selection self.selection = textOrList for button in self._buttonList: if button in oldselection: if button not in self.selection: # button is currently selected but should not be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.deselect() else: # Button widget.configure(relief='raised') else: if button in self.selection: # button is not currently selected but should be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.select() else: # Button widget.configure(relief='sunken') def numbuttons(self): return len(self._buttonList) def index(self, index): # Return the integer index of the button with the given index. listLength = len(self._buttonList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'RadioSelect has no buttons' else: for count in range(listLength): name = self._buttonList[count] if index == name: return count validValues = 'a name, a number or END' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def button(self, buttonIndex): name = self._buttonList[self.index(buttonIndex)] return self.component(name) def add(self, componentName, **kw): if componentName in self._buttonList: raise ValueError, 'button "%s" already exists' % componentName kw['command'] = \ lambda self=self, name=componentName: self.invoke(name) if not kw.has_key('text'): kw['text'] = componentName if self['buttontype'] == 'radiobutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' if not kw.has_key('variable'): kw['variable'] = self.var if not kw.has_key('value'): kw['value'] = kw['text'] elif self['buttontype'] == 'checkbutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' button = apply(self.createcomponent, (componentName, (), 'Button', self.buttonClass, (self._radioSelectFrame,)), kw) if self['orient'] == 'horizontal': self._radioSelectFrame.grid_rowconfigure(0, weight=1) col = len(self._buttonList) button.grid(column=col, row=0, padx = self['padx'], pady = self['pady'], sticky='nsew') self._radioSelectFrame.grid_columnconfigure(col, weight=1) else: self._radioSelectFrame.grid_columnconfigure(0, weight=1) row = len(self._buttonList) button.grid(column=0, row=row, padx = self['padx'], pady = self['pady'], sticky='ew') self._radioSelectFrame.grid_rowconfigure(row, weight=1) self._buttonList.append(componentName) return button def deleteall(self): for name in self._buttonList: self.destroycomponent(name) self._buttonList = [] if self._singleSelect: self.selection = None else: self.selection = [] def __setSingleValue(self, value): self.selection = value if self['buttontype'] == 'radiobutton': widget = self.component(value) widget.select() else: # Button for button in self._buttonList: widget = self.component(button) if button == value: widget.configure(relief='sunken') else: widget.configure(relief='raised') def invoke(self, index): index = self.index(index) name = self._buttonList[index] if self._singleSelect: self.__setSingleValue(name) command = self['command'] if callable(command): return command(name) else: # Multiple selections widget = self.component(name) if name in self.selection: if self['buttontype'] == 'checkbutton': widget.deselect() else: widget.configure(relief='raised') self.selection.remove(name) state = 0 else: if self['buttontype'] == 'checkbutton': widget.select() else: widget.configure(relief='sunken') self.selection.append(name) state = 1 command = self['command'] if callable(command): return command(name, state) ###################################################################### ### File: PmwScrolledCanvas.py import Tkinter class ScrolledCanvas(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('canvasmargin', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the canvas. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._canvas.pack(fill = 'both', expand = 1) else: # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._canvas.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self._canvas.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self._canvas.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.setregionTimer = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None if self.setregionTimer is not None: self.after_cancel(self.setregionTimer) self.setregionTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._canvas def resizescrollregion(self): if self.setregionTimer is None: self.setregionTimer = self.after_idle(self._setRegion) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._canvas.cget('xscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) tclCommandName = str(self._canvas.cget('yscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._canvas.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._canvas.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the canvas to set the horizontal or vertical # scrollbar when it has scrolled or changed scrollregion. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._canvas.xview() yview = self._canvas.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _setRegion(self): self.setregionTimer = None region = self._canvas.bbox('all') if region is not None: canvasmargin = self['canvasmargin'] region = (region[0] - canvasmargin, region[1] - canvasmargin, region[2] + canvasmargin, region[3] + canvasmargin) self._canvas.configure(scrollregion = region) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, *args): return apply(self._canvas.bbox, args) forwardmethods(ScrolledCanvas, Tkinter.Canvas, '_canvas') ###################################################################### ### File: PmwScrolledField.py import Tkinter class ScrolledField(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ('text', '', self._text), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._scrolledFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') self._scrolledFieldEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def _text(self): text = self['text'] self._scrolledFieldEntry.configure(state = 'normal') self._scrolledFieldEntry.delete(0, 'end') self._scrolledFieldEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') forwardmethods(ScrolledField, Tkinter.Entry, '_scrolledFieldEntry') ###################################################################### ### File: PmwScrolledFrame.py import string import types import Tkinter class ScrolledFrame(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 1, INITOPT), ('horizflex', 'fixed', self._horizflex), ('horizfraction', 0.05, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vertflex', 'fixed', self._vertflex), ('vertfraction', 0.05, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the clipper. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self._borderframe,), width = 400, height = 300, highlightthickness = 0, borderwidth = 0, ) self._clipper.pack(fill = 'both', expand = 1) else: # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self.origInterior,), width = 400, height = 300, relief = 'sunken', borderwidth = 2, ) self._clipper.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.startX = 0 self.startY = 0 self._flexoptions = ('fixed', 'expand', 'shrink', 'elastic') # Create a frame in the clipper to contain the widgets to be # scrolled. self._frame = self.createcomponent('frame', (), None, Tkinter.Frame, (self._clipper,) ) # Whenever the clipping window or scrolled frame change size, # update the scrollbars. self._frame.bind('<Configure>', self._reposition) self._clipper.bind('<Configure>', self._reposition) # Work around a bug in Tk where the value returned by the # scrollbar get() method is (0.0, 0.0, 0.0, 0.0) rather than # the expected 2-tuple. This occurs if xview() is called soon # after the ScrolledFrame has been created. self._horizScrollbar.set(0.0, 1.0) self._vertScrollbar.set(0.0, 1.0) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._frame # Set timer to call real reposition method, so that it is not # called multiple times when many things are reconfigured at the # same time. def reposition(self): if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) # Called when the user clicks in the horizontal scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def xview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._horizScrollbar.get() elif mode == 'moveto': frameWidth = self._frame.winfo_reqwidth() self.startX = value * float(frameWidth) else: # mode == 'scroll' clipperWidth = self._clipper.winfo_width() if units == 'units': jump = int(clipperWidth * self['horizfraction']) else: jump = clipperWidth self.startX = self.startX + value * jump self.reposition() # Called when the user clicks in the vertical scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def yview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._vertScrollbar.get() elif mode == 'moveto': frameHeight = self._frame.winfo_reqheight() self.startY = value * float(frameHeight) else: # mode == 'scroll' clipperHeight = self._clipper.winfo_height() if units == 'units': jump = int(clipperHeight * self['vertfraction']) else: jump = clipperHeight self.startY = self.startY + value * jump self.reposition() # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _horizflex(self): # The horizontal flex mode has been configured. flex = self['horizflex'] if flex not in self._flexoptions: message = 'bad horizflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() def _vertflex(self): # The vertical flex mode has been configured. flex = self['vertflex'] if flex not in self._flexoptions: message = 'bad vertflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() # ====================================================================== # Private methods. def _reposition(self, event): self.reposition() def _getxview(self): # Horizontal dimension. clipperWidth = self._clipper.winfo_width() frameWidth = self._frame.winfo_reqwidth() if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self.startX = 0 endScrollX = 1.0 if self['horizflex'] in ('expand', 'elastic'): relwidth = 1 else: relwidth = '' else: # The scrolled frame is larger than the clipping window. if self['horizflex'] in ('shrink', 'elastic'): self.startX = 0 endScrollX = 1.0 relwidth = 1 else: if self.startX + clipperWidth > frameWidth: self.startX = frameWidth - clipperWidth endScrollX = 1.0 else: if self.startX < 0: self.startX = 0 endScrollX = (self.startX + clipperWidth) / float(frameWidth) relwidth = '' # Position frame relative to clipper. self._frame.place(x = -self.startX, relwidth = relwidth) return (self.startX / float(frameWidth), endScrollX) def _getyview(self): # Vertical dimension. clipperHeight = self._clipper.winfo_height() frameHeight = self._frame.winfo_reqheight() if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self.startY = 0 endScrollY = 1.0 if self['vertflex'] in ('expand', 'elastic'): relheight = 1 else: relheight = '' else: # The scrolled frame is larger than the clipping window. if self['vertflex'] in ('shrink', 'elastic'): self.startY = 0 endScrollY = 1.0 relheight = 1 else: if self.startY + clipperHeight > frameHeight: self.startY = frameHeight - clipperHeight endScrollY = 1.0 else: if self.startY < 0: self.startY = 0 endScrollY = (self.startY + clipperHeight) / float(frameHeight) relheight = '' # Position frame relative to clipper. self._frame.place(y = -self.startY, relheight = relheight) return (self.startY / float(frameHeight), endScrollY) # According to the relative geometries of the frame and the # clipper, reposition the frame within the clipper and reset the # scrollbars. def _scrollBothNow(self): self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._getxview() yview = self._getyview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) ###################################################################### ### File: PmwScrolledListBox.py # Based on iwidgets2.2.0/scrolledlistbox.itk code. import types import Tkinter class ScrolledListBox(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('dblclickcommand', None, None), ('hscrollmode', 'dynamic', self._hscrollMode), ('items', (), INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('selectioncommand', None, None), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) # Create the listbox widget. self._listbox = self.createcomponent('listbox', (), None, Tkinter.Listbox, (interior,)) self._listbox.grid(row = 2, column = 2, sticky = 'news') interior.grid_rowconfigure(2, weight = 1, minsize = 0) interior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._listbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._listbox.yview ) self.createlabel(interior, childCols = 3, childRows = 3) # Add the items specified by the initialisation option. items = self['items'] if type(items) != types.TupleType: items = tuple(items) if len(items) > 0: apply(self._listbox.insert, ('end',) + items) _registerScrolledList(self._listbox, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. theTag = 'ScrolledListBoxTag' if ScrolledListBox._classBindingsDefinedFor != Tkinter._default_root: root = Tkinter._default_root def doubleEvent(event): _handleEvent(event, 'double') def keyEvent(event): _handleEvent(event, 'key') def releaseEvent(event): _handleEvent(event, 'release') # Bind space and return keys and button 1 to the selectioncommand. root.bind_class(theTag, '<Key-space>', keyEvent) root.bind_class(theTag, '<Key-Return>', keyEvent) root.bind_class(theTag, '<ButtonRelease-1>', releaseEvent) # Bind double button 1 click to the dblclickcommand. root.bind_class(theTag, '<Double-ButtonRelease-1>', doubleEvent) ScrolledListBox._classBindingsDefinedFor = root bindtags = self._listbox.bindtags() self._listbox.bindtags(bindtags + (theTag,)) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None _deregisterScrolledList(self._listbox) MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.setlist(()) def getcurselection(self): rtn = [] for sel in self.curselection(): rtn.append(self._listbox.get(sel)) return tuple(rtn) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): self._listbox.selection_clear(0, 'end') listitems = list(self._listbox.get(0, 'end')) if type(textOrList) == types.StringType: if textOrList in listitems: self._listbox.selection_set(listitems.index(textOrList)) else: raise ValueError, 'no such item "%s"' % textOrList else: for item in textOrList: if item in listitems: self._listbox.selection_set(listitems.index(item)) else: raise ValueError, 'no such item "%s"' % item def setlist(self, items): self._listbox.delete(0, 'end') if len(items) > 0: if type(items) != types.TupleType: items = tuple(items) apply(self._listbox.insert, (0,) + items) # Override Tkinter.Listbox get method, so that if it is called with # no arguments, return all list elements (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._listbox.get(0, 'end') else: return self._listbox.get(first, last) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._listbox.cget('xscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) tclCommandName = str(self._listbox.cget('yscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._listbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._listbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the listbox to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._listbox.xview() yview = self._listbox.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _handleEvent(self, event, eventType): if eventType == 'double': command = self['dblclickcommand'] elif eventType == 'key': command = self['selectioncommand'] else: #eventType == 'release' # Do not execute the command if the mouse was released # outside the listbox. if (event.x < 0 or self._listbox.winfo_width() <= event.x or event.y < 0 or self._listbox.winfo_height() <= event.y): return command = self['selectioncommand'] if callable(command): command() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._listbox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._listbox.bbox(index) forwardmethods(ScrolledListBox, Tkinter.Listbox, '_listbox') # ====================================================================== _listboxCache = {} def _registerScrolledList(listbox, scrolledList): # Register an ScrolledList widget for a Listbox widget _listboxCache[listbox] = scrolledList def _deregisterScrolledList(listbox): # Deregister a Listbox widget del _listboxCache[listbox] def _handleEvent(event, eventType): # Forward events for a Listbox to it's ScrolledListBox # A binding earlier in the bindtags list may have destroyed the # megawidget, so need to check. if _listboxCache.has_key(event.widget): _listboxCache[event.widget]._handleEvent(event, eventType) ###################################################################### ### File: PmwScrolledText.py # Based on iwidgets2.2.0/scrolledtext.itk code. import Tkinter class ScrolledText(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('columnheader', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('rowcolumnheader',0, INITOPT), ('rowheader', 0, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the text # widget. Later, pack the text widget so that it fills # the frame. This avoids a problem in Tk, where window # items in a text widget may overlap the border of the # text widget. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (interior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 4, column = 4, sticky = 'news') # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._textbox.pack(fill = 'both', expand = 1) bw = self._borderframe.cget('borderwidth'), ht = self._borderframe.cget('highlightthickness'), else: # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (interior,), ) self._textbox.grid(row = 4, column = 4, sticky = 'news') bw = self._textbox.cget('borderwidth'), ht = self._textbox.cget('highlightthickness'), # Create the header text widgets if self['columnheader']: self._columnheader = self.createcomponent('columnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._columnheader.grid(row = 2, column = 4, sticky = 'ew') self._columnheader.configure( xscrollcommand = self._columnheaderscrolled) if self['rowheader']: self._rowheader = self.createcomponent('rowheader', (), 'Header', Tkinter.Text, (interior,), wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowheader.grid(row = 4, column = 2, sticky = 'ns') self._rowheader.configure( yscrollcommand = self._rowheaderscrolled) if self['rowcolumnheader']: self._rowcolumnheader = self.createcomponent('rowcolumnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowcolumnheader.grid(row = 2, column = 2, sticky = 'nsew') interior.grid_rowconfigure(4, weight = 1, minsize = 0) interior.grid_columnconfigure(4, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._textbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._textbox.yview ) self.createlabel(interior, childCols = 5, childRows = 5) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self._textWidth = None # These four variables avoid an infinite loop caused by the # row or column header's scrollcommand causing the main text # widget's scrollcommand to be called and vice versa. self._textboxLastX = None self._textboxLastY = None self._columnheaderLastX = None self._rowheaderLastY = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.settext('') def importfile(self, fileName, where = 'end'): file = open(fileName, 'r') self._textbox.insert(where, file.read()) file.close() def exportfile(self, fileName): file = open(fileName, 'w') file.write(self._textbox.get('1.0', 'end')) file.close() def settext(self, text): disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.delete('0.0', 'end') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') # Override Tkinter.Text get method, so that if it is called with # no arguments, return all text (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._textbox.get('1.0', 'end') else: return self._textbox.get(first, last) def getvalue(self): return self.get() def setvalue(self, text): return self.settext(text) def appendtext(self, text): oldTop, oldBottom = self._textbox.yview() disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') if oldBottom == 1.0: self._textbox.yview('moveto', 1.0) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._textbox.cget('xscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) tclCommandName = str(self._textbox.cget('yscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._textbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._textbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) # This code is the same as in _scrollBothNow. Keep it that way. if self['hscrollmode'] == 'dynamic': currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['columnheader']: if self._columnheaderLastX != first: self._columnheaderLastX = first self._columnheader.xview('moveto', first) def _scrollYNow(self, first, last): if first == '0' and last == '0': return self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() if self['rowheader']: if self._rowheaderLastY != first: self._rowheaderLastY = first self._rowheader.yview('moveto', first) def _scrollBothLater(self, first, last): # Called by the text widget to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._textbox.xview() yview = self._textbox.yview() # The text widget returns a yview of (0.0, 0.0) just after it # has been created. Ignore this. if yview == (0.0, 0.0): return if self['columnheader']: if self._columnheaderLastX != xview[0]: self._columnheaderLastX = xview[0] self._columnheader.xview('moveto', xview[0]) if self['rowheader']: if self._rowheaderLastY != yview[0]: self._rowheaderLastY = yview[0] self._rowheader.yview('moveto', yview[0]) self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': # The following test is done to prevent continuous # mapping and unmapping of the horizontal scrollbar. # This may occur when some event (scrolling, resizing # or text changes) modifies the displayed text such # that the bottom line in the window is the longest # line displayed. If this causes the horizontal # scrollbar to be mapped, the scrollbar may "cover up" # the bottom line, which would mean that the scrollbar # is no longer required. If the scrollbar is then # unmapped, the bottom line will then become visible # again, which would cause the scrollbar to be mapped # again, and so on... # # The idea is that, if the width of the text widget # has not changed and the scrollbar is currently # mapped, then do not unmap the scrollbar even if it # is no longer required. This means that, during # normal scrolling of the text, once the horizontal # scrollbar has been mapped it will not be unmapped # (until the width of the text widget changes). currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _columnheaderscrolled(self, first, last): if self._textboxLastX != first: self._textboxLastX = first self._textbox.xview('moveto', first) def _rowheaderscrolled(self, first, last): if self._textboxLastY != first: self._textboxLastY = first self._textbox.yview('moveto', first) def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 6, column = 4, sticky = 'news') interior.grid_rowconfigure(5, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(5, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 4, column = 6, sticky = 'news') interior.grid_columnconfigure(5, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(5, minsize = 0) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._textbox.bbox(index) forwardmethods(ScrolledText, Tkinter.Text, '_textbox') ###################################################################### ### File: PmwHistoryText.py _ORIGINAL = 0 _MODIFIED = 1 _DISPLAY = 2 class HistoryText(ScrolledText): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('compressany', 1, None), ('compresstail', 1, None), ('historycommand', None, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). ScrolledText.__init__(self, parent) # Initialise instance variables. self._list = [] self._currIndex = 0 self._pastIndex = None self._lastIndex = 0 # pointer to end of history list # Check keywords and initialise options. self.initialiseoptions() def addhistory(self): text = self.get() if text[-1] == '\n': text = text[:-1] if len(self._list) == 0: # This is the first history entry. Add it. self._list.append([text, text, _MODIFIED]) return currentEntry = self._list[self._currIndex] if text == currentEntry[_ORIGINAL]: # The current history entry has not been modified. Check if # we need to add it again. if self['compresstail'] and self._currIndex == self._lastIndex: return if self['compressany']: return # Undo any changes for the current history entry, since they # will now be available in the new entry. currentEntry[_MODIFIED] = currentEntry[_ORIGINAL] historycommand = self['historycommand'] if self._currIndex == self._lastIndex: # The last history entry is currently being displayed, # so disable the special meaning of the 'Next' button. self._pastIndex = None nextState = 'disabled' else: # A previous history entry is currently being displayed, # so allow the 'Next' button to go to the entry after this one. self._pastIndex = self._currIndex nextState = 'normal' if callable(historycommand): historycommand('normal', nextState) # Create the new history entry. self._list.append([text, text, _MODIFIED]) # Move the pointer into the history entry list to the end. self._lastIndex = self._lastIndex + 1 self._currIndex = self._lastIndex def next(self): if self._currIndex == self._lastIndex and self._pastIndex is None: self.bell() else: self._modifyDisplay('next') def prev(self): self._pastIndex = None if self._currIndex == 0: self.bell() else: self._modifyDisplay('prev') def undo(self): if len(self._list) != 0: self._modifyDisplay('undo') def redo(self): if len(self._list) != 0: self._modifyDisplay('redo') def gethistory(self): return self._list def _modifyDisplay(self, command): # Modify the display to show either the next or previous # history entry (next, prev) or the original or modified # version of the current history entry (undo, redo). # Save the currently displayed text. currentText = self.get() if currentText[-1] == '\n': currentText = currentText[:-1] currentEntry = self._list[self._currIndex] if currentEntry[_DISPLAY] == _MODIFIED: currentEntry[_MODIFIED] = currentText elif currentEntry[_ORIGINAL] != currentText: currentEntry[_MODIFIED] = currentText if command in ('next', 'prev'): currentEntry[_DISPLAY] = _MODIFIED if command in ('next', 'prev'): prevstate = 'normal' nextstate = 'normal' if command == 'next': if self._pastIndex is not None: self._currIndex = self._pastIndex self._pastIndex = None self._currIndex = self._currIndex + 1 if self._currIndex == self._lastIndex: nextstate = 'disabled' elif command == 'prev': self._currIndex = self._currIndex - 1 if self._currIndex == 0: prevstate = 'disabled' historycommand = self['historycommand'] if callable(historycommand): historycommand(prevstate, nextstate) currentEntry = self._list[self._currIndex] else: if command == 'undo': currentEntry[_DISPLAY] = _ORIGINAL elif command == 'redo': currentEntry[_DISPLAY] = _MODIFIED # Display the new text. self.delete('1.0', 'end') self.insert('end', currentEntry[currentEntry[_DISPLAY]]) ###################################################################### ### File: PmwSelectionDialog.py # Not Based on iwidgets version. class SelectionDialog(Dialog): # Dialog window with selection list. # Dialog window displaying a list and requesting the user to # select one. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'scrolledlist_listbox'), ('label', 'scrolledlist_label'), ) self._list = self.createcomponent('scrolledlist', aliases, None, ScrolledListBox, (interior,), dblclickcommand = self.invoke) self._list.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ScrolledListBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self.component('listbox').size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self.component('listbox').size(index) forwardmethods(SelectionDialog, ScrolledListBox, '_list') ###################################################################### ### File: PmwTextDialog.py # A Dialog with a ScrolledText widget. class TextDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('text', 'scrolledtext_text'), ('label', 'scrolledtext_label'), ) self._text = self.createcomponent('scrolledtext', aliases, None, ScrolledText, (interior,)) self._text.pack(side='top', expand=1, fill='both', padx = self['borderx'], pady = self['bordery']) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._text.bbox(index) forwardmethods(TextDialog, ScrolledText, '_text') ###################################################################### ### File: PmwTimeCounter.py # Authors: Joe VanAndel and Greg McFarlane import string import sys import time import Tkinter class TimeCounter(MegaWidget): """Up-down counter A TimeCounter is a single-line entry widget with Up and Down arrows which increment and decrement the Time value in the entry. """ def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('command', None, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('max', None, self._max), ('min', None, self._min), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('value', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.arrowDirection = {} self._flag = 'stopped' self._timerId = None self._createComponents(kw) value = self['value'] if value is None: now = time.time() value = time.strftime('%H:%M:%S', time.localtime(now)) self.setvalue(value) # Check keywords and initialise options. self.initialiseoptions() def _createComponents(self, kw): # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow buttons. # Create the hour down arrow. self._downHourArrowBtn = self.createcomponent('downhourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downHourArrowBtn] = 'down' self._downHourArrowBtn.grid(column = 0, row = 2) # Create the minute down arrow. self._downMinuteArrowBtn = self.createcomponent('downminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downMinuteArrowBtn] = 'down' self._downMinuteArrowBtn.grid(column = 1, row = 2) # Create the second down arrow. self._downSecondArrowBtn = self.createcomponent('downsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downSecondArrowBtn] = 'down' self._downSecondArrowBtn.grid(column = 2, row = 2) # Create the entry fields. # Create the hour entry field. self._hourCounterEntry = self.createcomponent('hourentryfield', (('hourentry', 'hourentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._hourCounterEntry.grid(column = 0, row = 1, sticky = 'news') # Create the minute entry field. self._minuteCounterEntry = self.createcomponent('minuteentryfield', (('minuteentry', 'minuteentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._minuteCounterEntry.grid(column = 1, row = 1, sticky = 'news') # Create the second entry field. self._secondCounterEntry = self.createcomponent('secondentryfield', (('secondentry', 'secondentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._secondCounterEntry.grid(column = 2, row = 1, sticky = 'news') # Create the up arrow buttons. # Create the hour up arrow. self._upHourArrowBtn = self.createcomponent('uphourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upHourArrowBtn] = 'up' self._upHourArrowBtn.grid(column = 0, row = 0) # Create the minute up arrow. self._upMinuteArrowBtn = self.createcomponent('upminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upMinuteArrowBtn] = 'up' self._upMinuteArrowBtn.grid(column = 1, row = 0) # Create the second up arrow. self._upSecondArrowBtn = self.createcomponent('upsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upSecondArrowBtn] = 'up' self._upSecondArrowBtn.grid(column = 2, row = 0) # Make it resize nicely. padx = self['padx'] pady = self['pady'] for col in range(3): frame.grid_columnconfigure(col, weight = 1, pad = padx) frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_rowconfigure(1, weight = 1) # Create the label. self.createlabel(interior) # Set bindings. # Up hour self._upHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upHourArrowBtn: s._drawArrow(button, 'up')) self._upHourArrowBtn.bind('<1>', lambda event, s=self,button=self._upHourArrowBtn: s._countUp(button, 3600)) self._upHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upHourArrowBtn: s._stopUpDown(button)) # Up minute self._upMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upMinuteArrowBtn: s._drawArrow(button, 'up')) self._upMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._upMinuteArrowBtn: s._countUp(button, 60)) self._upMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upMinuteArrowBtn: s._stopUpDown(button)) # Up second self._upSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upSecondArrowBtn: s._drawArrow(button, 'up')) self._upSecondArrowBtn.bind('<1>', lambda event, s=self,button=self._upSecondArrowBtn: s._countUp(button, 1)) self._upSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upSecondArrowBtn: s._stopUpDown(button)) # Down hour self._downHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downHourArrowBtn: s._drawArrow(button, 'down')) self._downHourArrowBtn.bind('<1>', lambda event, s=self,button=self._downHourArrowBtn: s._countDown(button, 3600)) self._downHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downHourArrowBtn: s._stopUpDown(button)) # Down minute self._downMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downMinuteArrowBtn: s._drawArrow(button, 'down')) self._downMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._downMinuteArrowBtn: s._countDown(button, 60)) self._downMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downMinuteArrowBtn: s._stopUpDown(button)) # Down second self._downSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downSecondArrowBtn: s._drawArrow(button, 'down')) self._downSecondArrowBtn.bind('<1>', lambda event, s=self, button=self._downSecondArrowBtn: s._countDown(button,1)) self._downSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downSecondArrowBtn: s._stopUpDown(button)) self._hourCounterEntry.component('entry').bind( '<Return>', self._invoke) self._minuteCounterEntry.component('entry').bind( '<Return>', self._invoke) self._secondCounterEntry.component('entry').bind( '<Return>', self._invoke) self._hourCounterEntry.bind('<Configure>', self._resizeArrow) self._minuteCounterEntry.bind('<Configure>', self._resizeArrow) self._secondCounterEntry.bind('<Configure>', self._resizeArrow) def _drawArrow(self, arrow, direction): drawarrow(arrow, self['hourentry_foreground'], direction, 'arrow') def _resizeArrow(self, event = None): for btn in (self._upHourArrowBtn, self._upMinuteArrowBtn, self._upSecondArrowBtn, self._downHourArrowBtn, self._downMinuteArrowBtn, self._downSecondArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._hourCounterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn, self.arrowDirection[btn]) def _min(self): min = self['min'] if min is None: self._minVal = 0 else: self._minVal = timestringtoseconds(min) def _max(self): max = self['max'] if max is None: self._maxVal = None else: self._maxVal = timestringtoseconds(max) def getvalue(self): return self.getstring() def setvalue(self, text): list = string.split(text, ':') if len(list) != 3: raise ValueError, 'invalid value: ' + text self._hour = string.atoi(list[0]) self._minute = string.atoi(list[1]) self._second = string.atoi(list[2]) self._setHMS() def getstring(self): return '%02d:%02d:%02d' % (self._hour, self._minute, self._second) def getint(self): return self._hour * 3600 + self._minute * 60 + self._second def _countUp(self, button, increment): self._relief = self._upHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(1, 'start', increment) def _countDown(self, button, increment): self._relief = self._downHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(-1, 'start', increment) def increment(self, seconds = 1): self._count(1, 'force', seconds) def decrement(self, seconds = 1): self._count(-1, 'force', seconds) def _count(self, factor, newFlag = None, increment = 1): if newFlag != 'force': if newFlag is not None: self._flag = newFlag if self._flag == 'stopped': return value = (string.atoi(self._hourCounterEntry.get()) *3600) + \ (string.atoi(self._minuteCounterEntry.get()) *60) + \ string.atoi(self._secondCounterEntry.get()) + \ factor * increment min = self._minVal max = self._maxVal if value < min: value = min if max is not None and value > max: value = max self._hour = value /3600 self._minute = (value - (self._hour*3600)) / 60 self._second = value - (self._hour*3600) - (self._minute*60) self._setHMS() if newFlag != 'force': if self['autorepeat']: if self._flag == 'start': delay = self['initwait'] self._flag = 'running' else: delay = self['repeatrate'] self._timerId = self.after( delay, lambda self=self, factor=factor,increment=increment: self._count(factor,'running', increment)) def _setHMS(self): self._hourCounterEntry.setentry('%02d' % self._hour) self._minuteCounterEntry.setentry('%02d' % self._minute) self._secondCounterEntry.setentry('%02d' % self._second) def _stopUpDown(self, button): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None button.configure(relief=self._relief) self._flag = 'stopped' def _invoke(self, event): cmd = self['command'] if callable(cmd): cmd() def invoke(self): cmd = self['command'] if callable(cmd): return cmd() def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) ###################################################################### ### File: PmwAboutDialog.py class AboutDialog(MessageDialog): # Window to display version and contact information. # Class members containing resettable 'default' values: _version = '' _copyright = '' _contact = '' def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('applicationname', '', INITOPT), ('iconpos', 'w', None), ('icon_bitmap', 'info', None), ('buttons', ('Close',), None), ('defaultbutton', 0, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MessageDialog.__init__(self, parent) applicationname = self['applicationname'] if not kw.has_key('title'): self.configure(title = 'About ' + applicationname) if not kw.has_key('message_text'): text = applicationname + '\n\n' if AboutDialog._version != '': text = text + 'Version ' + AboutDialog._version + '\n' if AboutDialog._copyright != '': text = text + AboutDialog._copyright + '\n\n' if AboutDialog._contact != '': text = text + AboutDialog._contact self.configure(message_text=text) # Check keywords and initialise options. self.initialiseoptions() def aboutversion(value): AboutDialog._version = value def aboutcopyright(value): AboutDialog._copyright = value def aboutcontact(value): AboutDialog._contact = value ###################################################################### ### File: PmwComboBox.py # Based on iwidgets2.2.0/combobox.itk code. import os import string import types import Tkinter class ComboBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autoclear', 0, INITOPT), ('buttonaspect', 1.0, INITOPT), ('dropdown', 1, INITOPT), ('fliparrow', 0, INITOPT), ('history', 1, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('listheight', 200, INITOPT), ('selectioncommand', None, None), ('sticky', 'ew', INITOPT), ('unique', 1, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryfield = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (interior,)) self._entryfield.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight = 1) self._entryWidget = self._entryfield.component('entry') if self['dropdown']: self._isPosted = 0 interior.grid_rowconfigure(2, weight = 1) # Create the arrow button. self._arrowBtn = self.createcomponent('arrowbutton', (), None, Tkinter.Canvas, (interior,), borderwidth = 2, relief = 'raised', width = 16, height = 16) if 'n' in self['sticky']: sticky = 'n' else: sticky = '' if 's' in self['sticky']: sticky = sticky + 's' self._arrowBtn.grid(column=3, row=2, sticky = sticky) self._arrowRelief = self._arrowBtn.cget('relief') # Create the label. self.createlabel(interior, childCols=2) # Create the dropdown window. self._popup = self.createcomponent('popup', (), None, Tkinter.Toplevel, (interior,)) self._popup.withdraw() self._popup.overrideredirect(1) # Create the scrolled listbox inside the dropdown window. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (self._popup,), hull_borderwidth = 2, hull_relief = 'raised', hull_height = self['listheight'], usehullsize = 1, listbox_exportselection = 0) self._list.pack(expand=1, fill='both') self.__listbox = self._list.component('listbox') # Bind events to the arrow button. self._arrowBtn.bind('<1>', self._postList) self._arrowBtn.bind('<Configure>', self._drawArrow) self._arrowBtn.bind('<3>', self._next) self._arrowBtn.bind('<Shift-3>', self._previous) self._arrowBtn.bind('<Down>', self._next) self._arrowBtn.bind('<Up>', self._previous) self._arrowBtn.bind('<Control-n>', self._next) self._arrowBtn.bind('<Control-p>', self._previous) self._arrowBtn.bind('<Shift-Down>', self._postList) self._arrowBtn.bind('<Shift-Up>', self._postList) self._arrowBtn.bind('<F34>', self._postList) self._arrowBtn.bind('<F28>', self._postList) self._arrowBtn.bind('<space>', self._postList) # Bind events to the dropdown window. self._popup.bind('<Escape>', self._unpostList) self._popup.bind('<space>', self._selectUnpost) self._popup.bind('<Return>', self._selectUnpost) self._popup.bind('<ButtonRelease-1>', self._dropdownBtnRelease) self._popup.bind('<ButtonPress-1>', self._unpostOnNextRelease) # Bind events to the Tk listbox. self.__listbox.bind('<Enter>', self._unpostOnNextRelease) # Bind events to the Tk entry widget. self._entryWidget.bind('<Configure>', self._resizeArrow) self._entryWidget.bind('<Shift-Down>', self._postList) self._entryWidget.bind('<Shift-Up>', self._postList) self._entryWidget.bind('<F34>', self._postList) self._entryWidget.bind('<F28>', self._postList) # Need to unpost the popup if the entryfield is unmapped (eg: # its toplevel window is withdrawn) while the popup list is # displayed. self._entryWidget.bind('<Unmap>', self._unpostList) else: # Create the scrolled listbox below the entry field. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (interior,), selectioncommand = self._selectCmd) self._list.grid(column=2, row=3, sticky='nsew') self.__listbox = self._list.component('listbox') # The scrolled listbox should expand vertically. interior.grid_rowconfigure(3, weight = 1) # Create the label. self.createlabel(interior, childRows=2) self._entryWidget.bind('<Down>', self._next) self._entryWidget.bind('<Up>', self._previous) self._entryWidget.bind('<Control-n>', self._next) self._entryWidget.bind('<Control-p>', self._previous) self.__listbox.bind('<Control-n>', self._next) self.__listbox.bind('<Control-p>', self._previous) if self['history']: self._entryfield.configure(command=self._addHistory) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self['dropdown'] and self._isPosted: popgrab(self._popup) MegaWidget.destroy(self) #====================================================================== # Public methods def get(self, first = None, last=None): if first is None: return self._entryWidget.get() else: return self._list.get(first, last) def invoke(self): if self['dropdown']: self._postList() else: return self._selectCmd() def selectitem(self, index, setentry=1): if type(index) == types.StringType: text = index items = self._list.get(0, 'end') if text in items: index = list(items).index(text) else: raise IndexError, 'index "%s" not found' % text elif setentry: text = self._list.get(0, 'end')[index] self._list.select_clear(0, 'end') self._list.select_set(index, index) self._list.activate(index) self.see(index) if setentry: self._entryfield.setentry(text) # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._list.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._list.bbox(index) def clear(self): self._entryfield.clear() self._list.clear() #====================================================================== # Private methods for both dropdown and simple comboboxes. def _addHistory(self): input = self._entryWidget.get() if input != '': index = None if self['unique']: # If item is already in list, select it and return. items = self._list.get(0, 'end') if input in items: index = list(items).index(input) if index is None: index = self._list.index('end') self._list.insert('end', input) self.selectitem(index) if self['autoclear']: self._entryWidget.delete(0, 'end') # Execute the selectioncommand on the new entry. self._selectCmd() def _next(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = 0 else: index = string.atoi(cursels[0]) if index == size - 1: index = 0 else: index = index + 1 self.selectitem(index) def _previous(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = size - 1 else: index = string.atoi(cursels[0]) if index == 0: index = size - 1 else: index = index - 1 self.selectitem(index) def _selectCmd(self, event=None): sels = self.getcurselection() if len(sels) == 0: item = None else: item = sels[0] self._entryfield.setentry(item) cmd = self['selectioncommand'] if callable(cmd): if event is None: # Return result of selectioncommand for invoke() method. return cmd(item) else: cmd(item) #====================================================================== # Private methods for dropdown combobox. def _drawArrow(self, event=None, sunken=0): arrow = self._arrowBtn if sunken: self._arrowRelief = arrow.cget('relief') arrow.configure(relief = 'sunken') else: arrow.configure(relief = self._arrowRelief) if self._isPosted and self['fliparrow']: direction = 'up' else: direction = 'down' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _postList(self, event = None): self._isPosted = 1 self._drawArrow(sunken=1) # Make sure that the arrow is displayed sunken. self.update_idletasks() x = self._entryfield.winfo_rootx() y = self._entryfield.winfo_rooty() + \ self._entryfield.winfo_height() w = self._entryfield.winfo_width() + self._arrowBtn.winfo_width() h = self.__listbox.winfo_height() sh = self.winfo_screenheight() if y + h > sh and y > sh / 2: y = self._entryfield.winfo_rooty() - h self._list.configure(hull_width=w) setgeometryanddeiconify(self._popup, '+%d+%d' % (x, y)) # Grab the popup, so that all events are delivered to it, and # set focus to the listbox, to make keyboard navigation # easier. pushgrab(self._popup, 1, self._unpostList) self.__listbox.focus_set() self._drawArrow() # Ignore the first release of the mouse button after posting the # dropdown list, unless the mouse enters the dropdown list. self._ignoreRelease = 1 def _dropdownBtnRelease(self, event): if (event.widget == self._list.component('vertscrollbar') or event.widget == self._list.component('horizscrollbar')): return if self._ignoreRelease: self._unpostOnNextRelease() return self._unpostList() if (event.x >= 0 and event.x < self.__listbox.winfo_width() and event.y >= 0 and event.y < self.__listbox.winfo_height()): self._selectCmd() def _unpostOnNextRelease(self, event = None): self._ignoreRelease = 0 def _resizeArrow(self, event): bw = (string.atoi(self._arrowBtn['borderwidth']) + string.atoi(self._arrowBtn['highlightthickness'])) newHeight = self._entryfield.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) self._arrowBtn.configure(width=newWidth, height=newHeight) self._drawArrow() def _unpostList(self, event=None): if not self._isPosted: # It is possible to get events on an unposted popup. For # example, by repeatedly pressing the space key to post # and unpost the popup. The <space> event may be # delivered to the popup window even though # popgrab() has set the focus away from the # popup window. (Bug in Tk?) return # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._popup) self._popup.withdraw() self._isPosted = 0 self._drawArrow() def _selectUnpost(self, event): self._unpostList() self._selectCmd() forwardmethods(ComboBox, ScrolledListBox, '_list') forwardmethods(ComboBox, EntryField, '_entryfield') ###################################################################### ### File: PmwComboBoxDialog.py # Not Based on iwidgets version. class ComboBoxDialog(Dialog): # Dialog window with simple combobox. # Dialog window displaying a list and entry field and requesting # the user to make a selection or enter a value def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'combobox_listbox'), ('scrolledlist', 'combobox_scrolledlist'), ('entry', 'combobox_entry'), ('label', 'combobox_label'), ) self._combobox = self.createcomponent('combobox', aliases, None, ComboBox, (interior,), scrolledlist_dblclickcommand = self.invoke, dropdown = 0, ) self._combobox.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ComboBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self._combobox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._combobox.bbox(index) forwardmethods(ComboBoxDialog, ComboBox, '_combobox') ###################################################################### ### File: PmwCounter.py import string import sys import types import Tkinter class Counter(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('datatype', 'numeric', self._datatype), ('increment', 1, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Initialise instance variables. self._timerId = None self._normalRelief = None # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow. self._downArrowBtn = self.createcomponent('downarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) # Create the entry field. self._counterEntry = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (frame,)) # Create the up arrow. self._upArrowBtn = self.createcomponent('uparrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) padx = self['padx'] pady = self['pady'] orient = self['orient'] if orient == 'horizontal': self._downArrowBtn.grid(column = 0, row = 0) self._counterEntry.grid(column = 1, row = 0, sticky = self['sticky']) self._upArrowBtn.grid(column = 2, row = 0) frame.grid_columnconfigure(1, weight = 1) frame.grid_rowconfigure(0, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_columnconfigure(0, pad = padx) frame.grid_columnconfigure(2, pad = padx) frame.grid_rowconfigure(0, pad = pady) elif orient == 'vertical': self._upArrowBtn.grid(column = 0, row = 0, sticky = 's') self._counterEntry.grid(column = 0, row = 1, sticky = self['sticky']) self._downArrowBtn.grid(column = 0, row = 2, sticky = 'n') frame.grid_columnconfigure(0, weight = 1) frame.grid_rowconfigure(0, weight = 1) frame.grid_rowconfigure(2, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_columnconfigure(0, pad = padx) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' self.createlabel(interior) self._upArrowBtn.bind('<Configure>', self._drawUpArrow) self._upArrowBtn.bind('<1>', self._countUp) self._upArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._downArrowBtn.bind('<Configure>', self._drawDownArrow) self._downArrowBtn.bind('<1>', self._countDown) self._downArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._counterEntry.bind('<Configure>', self._resizeArrow) entry = self._counterEntry.component('entry') entry.bind('<Down>', lambda event, s = self: s._key_decrement(event)) entry.bind('<Up>', lambda event, s = self: s._key_increment(event)) # Need to cancel the timer if an arrow button is unmapped (eg: # its toplevel window is withdrawn) while the mouse button is # held down. The canvas will not get the ButtonRelease event # if it is not mapped, since the implicit grab is cancelled. self._upArrowBtn.bind('<Unmap>', self._stopCounting) self._downArrowBtn.bind('<Unmap>', self._stopCounting) # Check keywords and initialise options. self.initialiseoptions() def _resizeArrow(self, event): for btn in (self._upArrowBtn, self._downArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._counterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn) def _drawUpArrow(self, event): self._drawArrow(self._upArrowBtn) def _drawDownArrow(self, event): self._drawArrow(self._downArrowBtn) def _drawArrow(self, arrow): if self['orient'] == 'vertical': if arrow == self._upArrowBtn: direction = 'up' else: direction = 'down' else: if arrow == self._upArrowBtn: direction = 'right' else: direction = 'left' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _stopCounting(self, event = None): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None if self._normalRelief is not None: button, relief = self._normalRelief button.configure(relief=relief) self._normalRelief = None def _countUp(self, event): self._normalRelief = (self._upArrowBtn, self._upArrowBtn.cget('relief')) self._upArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._upArrowBtn.update_idletasks() self._count(1, 1) def _countDown(self, event): self._normalRelief = (self._downArrowBtn, self._downArrowBtn.cget('relief')) self._downArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._downArrowBtn.update_idletasks() self._count(-1, 1) def increment(self): self._forceCount(1) def decrement(self): self._forceCount(-1) def _key_increment(self, event): self._forceCount(1) self.update_idletasks() def _key_decrement(self, event): self._forceCount(-1) self.update_idletasks() def _datatype(self): datatype = self['datatype'] if type(datatype) is types.DictionaryType: self._counterArgs = datatype.copy() if self._counterArgs.has_key('counter'): datatype = self._counterArgs['counter'] del self._counterArgs['counter'] else: datatype = 'numeric' else: self._counterArgs = {} if _counterCommands.has_key(datatype): self._counterCommand = _counterCommands[datatype] elif callable(datatype): self._counterCommand = datatype else: validValues = _counterCommands.keys() validValues.sort() raise ValueError, ('bad datatype value "%s": must be a' + ' function or one of %s') % (datatype, validValues) def _forceCount(self, factor): if not self.valid(): self.bell() return text = self._counterEntry.get() try: value = apply(self._counterCommand, (text, factor, self['increment']), self._counterArgs) except ValueError: self.bell() return previousICursor = self._counterEntry.index('insert') if self._counterEntry.setentry(value) == OK: self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) def _count(self, factor, first): if not self.valid(): self.bell() return self._timerId = None origtext = self._counterEntry.get() try: value = apply(self._counterCommand, (origtext, factor, self['increment']), self._counterArgs) except ValueError: # If text is invalid, stop counting. self._stopCounting() self.bell() return # If incrementing produces an invalid value, restore previous # text and stop counting. previousICursor = self._counterEntry.index('insert') valid = self._counterEntry.setentry(value) if valid != OK: self._stopCounting() self._counterEntry.setentry(origtext) if valid == PARTIAL: self.bell() return self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) if self['autorepeat']: if first: delay = self['initwait'] else: delay = self['repeatrate'] self._timerId = self.after(delay, lambda self=self, factor=factor: self._count(factor, 0)) def destroy(self): self._stopCounting() MegaWidget.destroy(self) forwardmethods(Counter, EntryField, '_counterEntry') def _changeNumber(text, factor, increment): value = string.atol(text) if factor > 0: value = (value / increment) * increment + increment else: value = ((value - 1) / increment) * increment # Get rid of the 'L' at the end of longs (in python up to 1.5.2). rtn = str(value) if rtn[-1] == 'L': return rtn[:-1] else: return rtn def _changeReal(text, factor, increment, separator = '.'): value = stringtoreal(text, separator) div = value / increment # Compare reals using str() to avoid problems caused by binary # numbers being only approximations to decimal numbers. # For example, if value is -0.3 and increment is 0.1, then # int(value/increment) = -2, not -3 as one would expect. if str(div)[-2:] == '.0': # value is an even multiple of increment. div = round(div) + factor else: # value is not an even multiple of increment. div = int(div) * 1.0 if value < 0: div = div - 1 if factor > 0: div = (div + 1) value = div * increment text = str(value) if separator != '.': index = string.find(text, '.') if index >= 0: text = text[:index] + separator + text[index + 1:] return text def _changeDate(value, factor, increment, format = 'ymd', separator = '/', yyyy = 0): jdn = datestringtojdn(value, format, separator) + factor * increment y, m, d = jdntoymd(jdn) result = '' for index in range(3): if index > 0: result = result + separator f = format[index] if f == 'y': if yyyy: result = result + '%02d' % y else: result = result + '%02d' % (y % 100) elif f == 'm': result = result + '%02d' % m elif f == 'd': result = result + '%02d' % d return result _SECSPERDAY = 24 * 60 * 60 def _changeTime(value, factor, increment, separator = ':', time24 = 0): unixTime = timestringtoseconds(value, separator) if factor > 0: chunks = unixTime / increment + 1 else: chunks = (unixTime - 1) / increment unixTime = chunks * increment if time24: while unixTime < 0: unixTime = unixTime + _SECSPERDAY while unixTime >= _SECSPERDAY: unixTime = unixTime - _SECSPERDAY if unixTime < 0: unixTime = -unixTime sign = '-' else: sign = '' secs = unixTime % 60 unixTime = unixTime / 60 mins = unixTime % 60 hours = unixTime / 60 return '%s%02d%s%02d%s%02d' % (sign, hours, separator, mins, separator, secs) # hexadecimal, alphabetic, alphanumeric not implemented _counterCommands = { 'numeric' : _changeNumber, # } integer 'integer' : _changeNumber, # } these two use the same function 'real' : _changeReal, # real number 'time' : _changeTime, 'date' : _changeDate, } ###################################################################### ### File: PmwCounterDialog.py # A Dialog with a counter class CounterDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() # Create the counter. aliases = ( ('entryfield', 'counter_entryfield'), ('entry', 'counter_entryfield_entry'), ('label', 'counter_label') ) self._cdCounter = self.createcomponent('counter', aliases, None, Counter, (interior,)) self._cdCounter.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # Counter's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._cdCounter.insert(index, text) def deleteentry(self, first, last=None): self._cdCounter.delete(first, last) def indexentry(self, index): return self._cdCounter.index(index) forwardmethods(CounterDialog, Counter, '_cdCounter') ###################################################################### ### File: PmwLogicalFont.py import os import string def _font_initialise(root, size=None, fontScheme = None): global _fontSize if size is not None: _fontSize = size if fontScheme in ('pmw1', 'pmw2'): if os.name == 'posix': defaultFont = logicalfont('Helvetica') menuFont = logicalfont('Helvetica', weight='bold', slant='italic') scaleFont = logicalfont('Helvetica', slant='italic') root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Menu*Font', menuFont, 'userDefault') root.option_add('*Menubutton*Font', menuFont, 'userDefault') root.option_add('*Scale.*Font', scaleFont, 'userDefault') if fontScheme == 'pmw1': balloonFont = logicalfont('Helvetica', -6, pixel = '12') else: # fontScheme == 'pmw2' balloonFont = logicalfont('Helvetica', -2) root.option_add('*Balloon.*Font', balloonFont, 'userDefault') else: defaultFont = logicalfont('Helvetica') root.option_add('*Font', defaultFont, 'userDefault') elif fontScheme == 'default': defaultFont = ('Helvetica', '-%d' % (_fontSize,), 'bold') entryFont = ('Helvetica', '-%d' % (_fontSize,)) textFont = ('Courier', '-%d' % (_fontSize,)) root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Entry*Font', entryFont, 'userDefault') root.option_add('*Text*Font', textFont, 'userDefault') def logicalfont(name='Helvetica', sizeIncr = 0, **kw): if not _fontInfo.has_key(name): raise ValueError, 'font %s does not exist' % name rtn = [] for field in _fontFields: if kw.has_key(field): logicalValue = kw[field] elif _fontInfo[name].has_key(field): logicalValue = _fontInfo[name][field] else: logicalValue = '*' if _propertyAliases[name].has_key((field, logicalValue)): realValue = _propertyAliases[name][(field, logicalValue)] elif _propertyAliases[name].has_key((field, None)): realValue = _propertyAliases[name][(field, None)] elif _propertyAliases[None].has_key((field, logicalValue)): realValue = _propertyAliases[None][(field, logicalValue)] elif _propertyAliases[None].has_key((field, None)): realValue = _propertyAliases[None][(field, None)] else: realValue = logicalValue if field == 'size': if realValue == '*': realValue = _fontSize realValue = str((realValue + sizeIncr) * 10) rtn.append(realValue) return string.join(rtn, '-') def logicalfontnames(): return _fontInfo.keys() if os.name == 'nt': _fontSize = 16 else: _fontSize = 14 _fontFields = ( 'registry', 'foundry', 'family', 'weight', 'slant', 'width', 'style', 'pixel', 'size', 'xres', 'yres', 'spacing', 'avgwidth', 'charset', 'encoding') # <_propertyAliases> defines other names for which property values may # be known by. This is required because italics in adobe-helvetica # are specified by 'o', while other fonts use 'i'. _propertyAliases = {} _propertyAliases[None] = { ('slant', 'italic') : 'i', ('slant', 'normal') : 'r', ('weight', 'light') : 'normal', ('width', 'wide') : 'normal', ('width', 'condensed') : 'normal', } # <_fontInfo> describes a 'logical' font, giving the default values of # some of its properties. _fontInfo = {} _fontInfo['Helvetica'] = { 'foundry' : 'adobe', 'family' : 'helvetica', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Helvetica'] = { ('slant', 'italic') : 'o', ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Times'] = { 'foundry' : 'adobe', 'family' : 'times', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Times'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Fixed'] = { 'foundry' : 'misc', 'family' : 'fixed', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'c', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Fixed'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', ('width', 'condensed') : 'semicondensed', } _fontInfo['Courier'] = { 'foundry' : 'adobe', 'family' : 'courier', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Courier'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', } _fontInfo['Typewriter'] = { 'foundry' : 'b&h', 'family' : 'lucidatypewriter', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Typewriter'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } if os.name == 'nt': # For some reason 'fixed' fonts on NT aren't. _fontInfo['Fixed'] = _fontInfo['Courier'] _propertyAliases['Fixed'] = _propertyAliases['Courier']
Python
# Functions for converting colors and modifying the color scheme of # an application. import math import string import sys import Tkinter _PI = math.pi _TWO_PI = _PI * 2 _THIRD_PI = _PI / 3 _SIXTH_PI = _PI / 6 _MAX_RGB = float(256 * 256 - 1) # max size of rgb values returned from Tk def setscheme(root, background=None, **kw): root = root._root() palette = apply(_calcPalette, (root, background,), kw) for option, value in palette.items(): root.option_add('*' + option, value, 'widgetDefault') def getdefaultpalette(root): # Return the default values of all options, using the defaults # from a few widgets. ckbtn = Tkinter.Checkbutton(root) entry = Tkinter.Entry(root) scbar = Tkinter.Scrollbar(root) orig = {} orig['activeBackground'] = str(ckbtn.configure('activebackground')[4]) orig['activeForeground'] = str(ckbtn.configure('activeforeground')[4]) orig['background'] = str(ckbtn.configure('background')[4]) orig['disabledForeground'] = str(ckbtn.configure('disabledforeground')[4]) orig['foreground'] = str(ckbtn.configure('foreground')[4]) orig['highlightBackground'] = str(ckbtn.configure('highlightbackground')[4]) orig['highlightColor'] = str(ckbtn.configure('highlightcolor')[4]) orig['insertBackground'] = str(entry.configure('insertbackground')[4]) orig['selectColor'] = str(ckbtn.configure('selectcolor')[4]) orig['selectBackground'] = str(entry.configure('selectbackground')[4]) orig['selectForeground'] = str(entry.configure('selectforeground')[4]) orig['troughColor'] = str(scbar.configure('troughcolor')[4]) ckbtn.destroy() entry.destroy() scbar.destroy() return orig #====================================================================== # Functions dealing with brightness, hue, saturation and intensity of colors. def changebrightness(root, colorName, brightness): # Convert the color name into its hue and back into a color of the # required brightness. rgb = name2rgb(root, colorName) hue, saturation, intensity = rgb2hsi(rgb) if saturation == 0.0: hue = None return hue2name(hue, brightness) def hue2name(hue, brightness = None): # Convert the requested hue and brightness into a color name. If # hue is None, return a grey of the requested brightness. if hue is None: rgb = hsi2rgb(0.0, 0.0, brightness) else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI rgb = hsi2rgb(hue, 1.0, 1.0) if brightness is not None: b = rgb2brightness(rgb) i = 1.0 - (1.0 - brightness) * b s = bhi2saturation(brightness, hue, i) rgb = hsi2rgb(hue, s, i) return rgb2name(rgb) def bhi2saturation(brightness, hue, intensity): while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) pp = intensity pq = intensity * f pt = intensity - intensity * f pv = 0 hue = int(hue) if hue == 0: rgb = (pv, pt, pp) elif hue == 1: rgb = (pq, pv, pp) elif hue == 2: rgb = (pp, pv, pt) elif hue == 3: rgb = (pp, pq, pv) elif hue == 4: rgb = (pt, pp, pv) elif hue == 5: rgb = (pv, pp, pq) return (intensity - brightness) / rgb2brightness(rgb) def hsi2rgb(hue, saturation, intensity): i = intensity if saturation == 0: rgb = [i, i, i] else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) p = i * (1.0 - saturation) q = i * (1.0 - saturation * f) t = i * (1.0 - saturation * (1.0 - f)) hue = int(hue) if hue == 0: rgb = [i, t, p] elif hue == 1: rgb = [q, i, p] elif hue == 2: rgb = [p, i, t] elif hue == 3: rgb = [p, q, i] elif hue == 4: rgb = [t, p, i] elif hue == 5: rgb = [i, p, q] for index in range(3): val = rgb[index] if val < 0.0: val = 0.0 if val > 1.0: val = 1.0 rgb[index] = val return rgb def average(rgb1, rgb2, fraction): return ( rgb2[0] * fraction + rgb1[0] * (1.0 - fraction), rgb2[1] * fraction + rgb1[1] * (1.0 - fraction), rgb2[2] * fraction + rgb1[2] * (1.0 - fraction) ) def rgb2name(rgb): return '#%02x%02x%02x' % \ (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)) def rgb2brightness(rgb): # Return the perceived grey level of the color # (0.0 == black, 1.0 == white). rf = 0.299 gf = 0.587 bf = 0.114 return rf * rgb[0] + gf * rgb[1] + bf * rgb[2] def rgb2hsi(rgb): maxc = max(rgb[0], rgb[1], rgb[2]) minc = min(rgb[0], rgb[1], rgb[2]) intensity = maxc if maxc != 0: saturation = (maxc - minc) / maxc else: saturation = 0.0 hue = 0.0 if saturation != 0.0: c = [] for index in range(3): c.append((maxc - rgb[index]) / (maxc - minc)) if rgb[0] == maxc: hue = c[2] - c[1] elif rgb[1] == maxc: hue = 2 + c[0] - c[2] elif rgb[2] == maxc: hue = 4 + c[1] - c[0] hue = hue * _THIRD_PI if hue < 0.0: hue = hue + _TWO_PI return (hue, saturation, intensity) def name2rgb(root, colorName, asInt = 0): if colorName[0] == '#': # Extract rgb information from the color name itself, assuming # it is either #rgb, #rrggbb, #rrrgggbbb, or #rrrrggggbbbb # This is useful, since tk may return incorrect rgb values if # the colormap is full - it will return the rbg values of the # closest color available. colorName = colorName[1:] digits = len(colorName) / 3 factor = 16 ** (4 - digits) rgb = ( string.atoi(colorName[0:digits], 16) * factor, string.atoi(colorName[digits:digits * 2], 16) * factor, string.atoi(colorName[digits * 2:digits * 3], 16) * factor, ) else: # We have no choice but to ask Tk what the rgb values are. rgb = root.winfo_rgb(colorName) if not asInt: rgb = (rgb[0] / _MAX_RGB, rgb[1] / _MAX_RGB, rgb[2] / _MAX_RGB) return rgb def _calcPalette(root, background=None, **kw): # Create a map that has the complete new palette. If some colors # aren't specified, compute them from other colors that are specified. new = {} for key, value in kw.items(): new[key] = value if background is not None: new['background'] = background if not new.has_key('background'): raise ValueError, 'must specify a background color' if not new.has_key('foreground'): new['foreground'] = 'black' bg = name2rgb(root, new['background']) fg = name2rgb(root, new['foreground']) for i in ('activeForeground', 'insertBackground', 'selectForeground', 'highlightColor'): if not new.has_key(i): new[i] = new['foreground'] if not new.has_key('disabledForeground'): newCol = average(bg, fg, 0.3) new['disabledForeground'] = rgb2name(newCol) if not new.has_key('highlightBackground'): new['highlightBackground'] = new['background'] # Set <lighterBg> to a color that is a little lighter that the # normal background. To do this, round each color component up by # 9% or 1/3 of the way to full white, whichever is greater. lighterBg = [] for i in range(3): lighterBg.append(bg[i]) inc1 = lighterBg[i] * 0.09 inc2 = (1.0 - lighterBg[i]) / 3 if inc1 > inc2: lighterBg[i] = lighterBg[i] + inc1 else: lighterBg[i] = lighterBg[i] + inc2 if lighterBg[i] > 1.0: lighterBg[i] = 1.0 # Set <darkerBg> to a color that is a little darker that the # normal background. darkerBg = (bg[0] * 0.9, bg[1] * 0.9, bg[2] * 0.9) if not new.has_key('activeBackground'): # If the foreground is dark, pick a light active background. # If the foreground is light, pick a dark active background. # XXX This has been disabled, since it does not look very # good with dark backgrounds. If this is ever fixed, the # selectBackground and troughColor options should also be fixed. if rgb2brightness(fg) < 0.5: new['activeBackground'] = rgb2name(lighterBg) else: new['activeBackground'] = rgb2name(lighterBg) if not new.has_key('selectBackground'): new['selectBackground'] = rgb2name(darkerBg) if not new.has_key('troughColor'): new['troughColor'] = rgb2name(darkerBg) if not new.has_key('selectColor'): new['selectColor'] = 'yellow' return new def spectrum(numColors, correction = 1.0, saturation = 1.0, intensity = 1.0, extraOrange = 1, returnHues = 0): colorList = [] division = numColors / 7.0 for index in range(numColors): if extraOrange: if index < 2 * division: hue = index / division else: hue = 2 + 2 * (index - 2 * division) / division hue = hue * _SIXTH_PI else: hue = index * _TWO_PI / numColors if returnHues: colorList.append(hue) else: rgb = hsi2rgb(hue, saturation, intensity) if correction != 1.0: rgb = correct(rgb, correction) name = rgb2name(rgb) colorList.append(name) return colorList def correct(rgb, correction): correction = float(correction) rtn = [] for index in range(3): rtn.append((1 - (1 - rgb[index]) ** correction) ** (1 / correction)) return rtn #============================================================================== def _recolorTree(widget, oldpalette, newcolors): # Change the colors in a widget and its descendants. # Change the colors in <widget> and all of its descendants, # according to the <newcolors> dictionary. It only modifies # colors that have their default values as specified by the # <oldpalette> variable. The keys of the <newcolors> dictionary # are named after widget configuration options and the values are # the new value for that option. for dbOption in newcolors.keys(): option = string.lower(dbOption) try: value = str(widget.cget(option)) except: continue if oldpalette is None or value == oldpalette[dbOption]: apply(widget.configure, (), {option : newcolors[dbOption]}) for child in widget.winfo_children(): _recolorTree(child, oldpalette, newcolors) def changecolor(widget, background=None, **kw): root = widget._root() if not hasattr(widget, '_Pmw_oldpalette'): widget._Pmw_oldpalette = getdefaultpalette(root) newpalette = apply(_calcPalette, (root, background,), kw) _recolorTree(widget, widget._Pmw_oldpalette, newpalette) widget._Pmw_oldpalette = newpalette def bordercolors(root, colorName): # This is the same method that Tk uses for shadows, in TkpGetShadows. lightRGB = [] darkRGB = [] for value in name2rgb(root, colorName, 1): value40pc = (14 * value) / 10 if value40pc > _MAX_RGB: value40pc = _MAX_RGB valueHalfWhite = (_MAX_RGB + value) / 2; lightRGB.append(max(value40pc, valueHalfWhite)) darkValue = (60 * value) / 100 darkRGB.append(darkValue) return ( '#%04x%04x%04x' % (lightRGB[0], lightRGB[1], lightRGB[2]), '#%04x%04x%04x' % (darkRGB[0], darkRGB[1], darkRGB[2]) )
Python
# This file is part of FlickFleck. # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import i18n import Tkinter import Pmw import wins import sys # simple window to display about and copyright information class About: def __init__(self, parent): self.parent = parent infotext = config.TITLE + ' version: ' + config.VERSION + \ '\n\nA tool to copy, rotate and rename' + \ '\ndigital camera jpeg files.' + \ '\n\nPython version: ' + sys.version + \ '\nPmw version: ' + Pmw.version() + \ '\nRunning on: ' + sys.platform + \ '\n\nhttp://flickfleck.googlecode.com/' self.w_dialog = Pmw.Dialog( parent, buttons = ('OK',), defaultbutton = 'OK', title = i18n.name['menu_about'] + ' ' + config.TITLE, command = self.button ) self.w_dialog.withdraw() self.w_notebook = Pmw.NoteBook( self.w_dialog.interior() ) self.w_notebook.pack( fill = 'both', expand = 1, padx = 2, pady = 2 ) self.addtab( 'Info', infotext ) self.addtab( 'Copyright', wins.COPYRIGHT ) self.addtab( 'Disclaimer', wins.DISCLAIMER ) self.addtab( 'Tools', wins.TOOLS ) self.addtab( 'Pmw', wins.PMW ) gpltab = self.w_notebook.add( 'GPLv3' ) gpl = Pmw.ScrolledText( gpltab, hscrollmode = 'none' ) gpl.importfile( 'GPL.txt' ) gpl.component('text').config( state = Tkinter.DISABLED ) gpl.pack( padx = 5, pady = 5, expand = 1 ) self.w_notebook.tab('Info').focus_set() self.w_notebook.setnaturalsize() def addtab( self, name, text ): tab = self.w_notebook.add( name ) label = Tkinter.Label( tab, text = text, pady = 10 ) label.pack( expand = 1, fill = 'both', padx = 2, pady = 2 ) def show(self): self.w_dialog.activate(geometry = 'centerscreenalways') def button(self, result): self.w_dialog.deactivate( result )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys import Tkinter, tkFileDialog import Pmw import aboutwin import config import configuration import ui import i18n import progressbar class FlickFleck: # create all windows when object is made def __init__(self, parent): self.parent = parent self.parent.protocol("WM_DELETE_WINDOW",self.doquit) self.parent.bind('<Return>', self._processReturnKey) self.parent.focus_set() self.w_about = aboutwin.About(parent) self.balloon = Pmw.Balloon( parent ) # --- top menubar --- self.menubar = Pmw.MenuBar( parent, hull_relief = 'raised', hull_borderwidth = 1, balloon = self.balloon ) self.menubar.pack( fill = 'x' ) self.menubar.addmenu('File', None, text = i18n.name['menu_file'] ) self.menubar.addmenuitem('File', 'command', None, command = self.doSelFromdir, label = i18n.name['menu_file_fromdir'] ) self.menubar.addmenuitem('File', 'command', None, command = self.doSelTodir, label = i18n.name['menu_file_todir'] ) if sys.platform == 'darwin': self.menubar.addmenuitem('File', 'separator') self.menubar.addmenuitem('File', 'command', None, command = configuration.mac_editconfig, label = i18n.name['menu_file_config'] ) self.menubar.addmenuitem('File', 'separator') self.menubar.addmenuitem('File', 'command', None, command = self.doquit, label =i18n.name['menu_file_exit'] ) self.button_about = Tkinter.Button( self.menubar.component('hull'), text = i18n.name['menu_about'] + '...', relief = 'flat', command = self.about ) self.button_about.pack(side='right') # self.balloon.bind( self.button_about, 'About') # --- from directory --- self.w_from = Pmw.Group( parent, tag_text = i18n.name['label_copyfrom'] ) self.w_from.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.var_fromlabel = Tkinter.StringVar( value = config.fromdir ) self.w_fromlabel = Tkinter.Label( self.w_from.interior(), textvariable = self.var_fromlabel, pady = 10 ) self.w_fromlabel.pack( side = 'left', padx = 5, pady = 2 ) # --- to directory --- self.w_to = Pmw.Group( parent, tag_text = i18n.name['label_copyto'] ) self.w_to.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.var_tolabel = Tkinter.StringVar( value = config.todir ) self.w_tolabel = Tkinter.Label( self.w_to.interior(), textvariable = self.var_tolabel ) self.w_tolabel.pack( side = 'left', padx = 5, pady = 2 ) # --- start n stop buttons --- self.w_buttons = Pmw.ButtonBox( parent ) # frame_borderwidth = 2, # frame_relief = 'groove' ) self.w_buttons.pack( fill = 'both', expand = 1, padx = 10, pady = 10 ) self.w_buttons.add( 'Start', command = self.start, text = i18n.name['button_start'] ) self.w_buttons.add( 'Stop', command = self.stop, text = i18n.name['button_stop'] ) self.w_buttons.setdefault('Start') self.w_buttons.alignbuttons() self.w_buttons.button('Stop').config(state = Tkinter.DISABLED) self.w_buttons.setdefault('Start') # --- progressbar --- # self.w_pb = Pmw.LabeledWidget( parent, labelpos = "nw", # label_text = "" ) self.w_pb = Pmw.ScrolledCanvas( parent, borderframe = 0, usehullsize = 1, hscrollmode = 'none', vscrollmode = 'none', hull_height = ui.wins.PBheight ) self.w_pb.component('hull').configure(relief='sunken', borderwidth=2) self.w_pb.pack( padx=5, pady=5, expand='yes', fill = 'x') self.w_pbw = progressbar.Widget( self.w_pb.interior() ) ui.wins.pb = self.w_pbw # --- status area at the bottom --- self.w_status = Pmw.MessageBar( parent, entry_relief = 'groove', labelpos = 'w', label_text = i18n.name['label_status'] + ' ') self.w_status.silent = True self.w_status.message('state', i18n.name['status_idle'] ) self.w_status.pack( fill = 'x', padx = 2, pady = 1, side = 'bottom' ) # self.balloon.configure( statuscommand = self.w_status.helpmessage ) #-- set message in the statusrow def status(self, msg_str, type = 'state'): self.w_status.message(type, msg_str) ui.wins.root.update() #-- user pressed 'start' def start(self): self.w_buttons.button(1).config(state = Tkinter.NORMAL) self.w_buttons.button(0).config(state = Tkinter.DISABLED) ui.wins.requestStop = False ui.wins.engine.start() #-- user pressed 'cancel' def stop(self): # self.w_buttons.button(0).config(state = Tkinter.NORMAL) self.w_buttons.button(1).config(state = Tkinter.DISABLED) # stopping is only noted, engine will stop when it notices value change ui.wins.requestStop = True #-- user pressed Enter def _processReturnKey(self, event): self.w_buttons.invoke() #-- quit selected in file-menu def doquit(self): self.parent.quit() #-- about button pressed def about(self): return self.w_about.show() #-- select fromdir def doSelFromdir(self): dir = tkFileDialog.askdirectory() if len(dir) > 0: config.fromdir = dir self.var_fromlabel.set( dir ) ui.wins.engine.init_filelist() # refind jpgs to copy #-- select todir def doSelTodir(self): dir = tkFileDialog.askdirectory() if len(dir) > 0: config.todir = dir self.var_tolabel.set( dir )
Python
# -*- coding: latin-1 -*- root = None main = None # Progressbar graphics height PBheight = 30 requestStop = False DISCLAIMER = """ THIS SOFTWARE IS PROVIDED BY Jyke Jokinen ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Jyke Jokinen BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ COPYRIGHT = """ Copyright (C) 2008 Jyke Tapani Jokinen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may not use this software except in compliance with the License. Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ PMW = """ Pmw copyright Copyright 1997-1999 Telstra Corporation Limited, Australia Copyright 2000-2002 Really Good Software Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ TOOLS = """ FlickFleck uses these external programs: Python megawidgets (http://pmw.sourceforge.net/) Jpegtran (http://sylvana.net/jpegcrop/jpegtran/) ExifTool (http://www.sno.phy.queensu.ca/~phil/exiftool/) """
Python
# Python interface to some of the commands of the 2.4 version of the # BLT extension to tcl. import string import types import Tkinter # Supported commands: _busyCommand = '::blt::busy' _vectorCommand = '::blt::vector' _graphCommand = '::blt::graph' _testCommand = '::blt::*' _chartCommand = '::blt::stripchart' _tabsetCommand = '::blt::tabset' _haveBlt = None _haveBltBusy = None def _checkForBlt(window): global _haveBlt global _haveBltBusy # Blt may be a package which has not yet been loaded. Try to load it. try: window.tk.call('package', 'require', 'BLT') except Tkinter.TclError: # Another way to try to dynamically load blt: try: window.tk.call('load', '', 'Blt') except Tkinter.TclError: pass _haveBlt= (window.tk.call('info', 'commands', _testCommand) != '') _haveBltBusy = (window.tk.call('info', 'commands', _busyCommand) != '') def haveblt(window): if _haveBlt is None: _checkForBlt(window) return _haveBlt def havebltbusy(window): if _haveBlt is None: _checkForBlt(window) return _haveBltBusy def _loadBlt(window): if _haveBlt is None: if window is None: window = Tkinter._default_root if window is None: window = Tkinter.Tk() _checkForBlt(window) def busy_hold(window, cursor = None): _loadBlt(window) if cursor is None: window.tk.call(_busyCommand, 'hold', window._w) else: window.tk.call(_busyCommand, 'hold', window._w, '-cursor', cursor) def busy_release(window): _loadBlt(window) window.tk.call(_busyCommand, 'release', window._w) def busy_forget(window): _loadBlt(window) window.tk.call(_busyCommand, 'forget', window._w) #============================================================================= # Interface to the blt vector command which makes it look like the # builtin python list type. # The -variable, -command, -watchunset creation options are not supported. # The dup, merge, notify, offset, populate, seq and variable methods # and the +, -, * and / operations are not supported. # Blt vector functions: def vector_expr(expression): tk = Tkinter._default_root.tk strList = tk.splitlist(tk.call(_vectorCommand, 'expr', expression)) return tuple(map(string.atof, strList)) def vector_names(pattern = None): tk = Tkinter._default_root.tk return tk.splitlist(tk.call(_vectorCommand, 'names', pattern)) class Vector: _varnum = 0 def __init__(self, size=None, master=None): # <size> can be either an integer size, or a string "first:last". _loadBlt(master) if master: self._master = master else: self._master = Tkinter._default_root self.tk = self._master.tk self._name = 'PY_VEC' + str(Vector._varnum) Vector._varnum = Vector._varnum + 1 if size is None: self.tk.call(_vectorCommand, 'create', self._name) else: self.tk.call(_vectorCommand, 'create', '%s(%s)' % (self._name, size)) def __del__(self): self.tk.call(_vectorCommand, 'destroy', self._name) def __str__(self): return self._name def __repr__(self): return '[' + string.join(map(str, self), ', ') + ']' def __cmp__(self, list): return cmp(self[:], list) def __len__(self): return self.tk.getint(self.tk.call(self._name, 'length')) def __getitem__(self, key): oldkey = key if key < 0: key = key + len(self) try: return self.tk.getdouble(self.tk.globalgetvar(self._name, str(key))) except Tkinter.TclError: raise IndexError, oldkey def __setitem__(self, key, value): if key < 0: key = key + len(self) return self.tk.globalsetvar(self._name, str(key), float(value)) def __delitem__(self, key): if key < 0: key = key + len(self) return self.tk.globalunsetvar(self._name, str(key)) def __getslice__(self, start, end): length = len(self) if start < 0: start = 0 if end > length: end = length if start >= end: return [] end = end - 1 # Blt vector slices include end point. text = self.tk.globalgetvar(self._name, str(start) + ':' + str(end)) return map(self.tk.getdouble, self.tk.splitlist(text)) def __setslice__(self, start, end, list): if start > end: end = start self.set(self[:start] + list + self[end:]) def __delslice__(self, start, end): if start < end: self.set(self[:start] + self[end:]) def __add__(self, list): return self[:] + list def __radd__(self, list): return list + self[:] def __mul__(self, n): return self[:] * n __rmul__ = __mul__ # Python builtin list methods: def append(self, *args): self.tk.call(self._name, 'append', args) def count(self, obj): return self[:].count(obj) def index(self, value): return self[:].index(value) def insert(self, index, value): self[index:index] = [value] def remove(self, value): del self[self.index(value)] def reverse(self): s = self[:] s.reverse() self.set(s) def sort(self, *args): s = self[:] s.sort() self.set(s) # Blt vector instance methods: # append - same as list method above def clear(self): self.tk.call(self._name, 'clear') def delete(self, *args): self.tk.call((self._name, 'delete') + args) def expr(self, expression): self.tk.call(self._name, 'expr', expression) def length(self, newSize=None): return self.tk.getint(self.tk.call(self._name, 'length', newSize)) def range(self, first, last=None): # Note that, unlike self[first:last], this includes the last # item in the returned range. text = self.tk.call(self._name, 'range', first, last) return map(self.tk.getdouble, self.tk.splitlist(text)) def search(self, start, end=None): return self._master._getints(self.tk.call( self._name, 'search', start, end)) def set(self, list): if type(list) != types.TupleType: list = tuple(list) self.tk.call(self._name, 'set', list) # The blt vector sort method has different semantics to the python # list sort method. Call these blt_sort: def blt_sort(self, *args): self.tk.call((self._name, 'sort') + args) def blt_sort_reverse(self, *args): self.tk.call((self._name, 'sort', '-reverse') + args) # Special blt vector indexes: def min(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'min')) def max(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'max')) # Method borrowed from Tkinter.Var class: def get(self): return self[:] #============================================================================= # This is a general purpose configure routine which can handle the # configuration of widgets, items within widgets, etc. Supports the # forms configure() and configure('font') for querying and # configure(font = 'fixed', text = 'hello') for setting. def _doConfigure(widget, subcommand, option, kw): if not option and not kw: # Return a description of all options. ret = {} options = widget.tk.splitlist(widget.tk.call(subcommand)) for optionString in options: optionInfo = widget.tk.splitlist(optionString) option = optionInfo[0][1:] ret[option] = (option,) + optionInfo[1:] return ret if option: # Return a description of the option given by <option>. if kw: # Having keywords implies setting configuration options. # Can't set and get in one command! raise ValueError, 'cannot have option argument with keywords' option = '-' + option optionInfo = widget.tk.splitlist(widget.tk.call(subcommand + (option,))) return (optionInfo[0][1:],) + optionInfo[1:] # Otherwise, set the given configuration options. widget.tk.call(subcommand + widget._options(kw)) #============================================================================= class Graph(Tkinter.Widget): # Wrapper for the blt graph widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _graphCommand, cnf, kw) def bar_create(self, name, **kw): self.tk.call((self._w, 'bar', 'create', name) + self._options(kw)) def line_create(self, name, **kw): self.tk.call((self._w, 'line', 'create', name) + self._options(kw)) def extents(self, item): return self.tk.getint(self.tk.call(self._w, 'extents', item)) def invtransform(self, winX, winY): return self._getdoubles( self.tk.call(self._w, 'invtransform', winX, winY)) def inside(self, x, y): return self.tk.getint(self.tk.call(self._w, 'inside', x, y)) def snap(self, photoName): self.tk.call(self._w, 'snap', photoName) def transform(self, x, y): return self._getdoubles(self.tk.call(self._w, 'transform', x, y)) def axis_cget(self, axisName, key): return self.tk.call(self._w, 'axis', 'cget', axisName, '-' + key) def axis_configure(self, axes, option=None, **kw): # <axes> may be a list of axisNames. if type(axes) == types.StringType: axes = [axes] subcommand = (self._w, 'axis', 'configure') + tuple(axes) return _doConfigure(self, subcommand, option, kw) def axis_create(self, axisName, **kw): self.tk.call((self._w, 'axis', 'create', axisName) + self._options(kw)) def axis_delete(self, *args): self.tk.call((self._w, 'axis', 'delete') + args) def axis_invtransform(self, axisName, value): return self.tk.getdouble(self.tk.call( self._w, 'axis', 'invtransform', axisName, value)) def axis_limits(self, axisName): return self._getdoubles(self.tk.call( self._w, 'axis', 'limits', axisName)) def axis_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'axis', 'names') + args)) def axis_transform(self, axisName, value): return self.tk.getint(self.tk.call( self._w, 'axis', 'transform', axisName, value)) def xaxis_cget(self, key): return self.tk.call(self._w, 'xaxis', 'cget', '-' + key) def xaxis_configure(self, option=None, **kw): subcommand = (self._w, 'xaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def xaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'xaxis', 'invtransform', value)) def xaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'xaxis', 'limits')) def xaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'xaxis', 'transform', value)) def xaxis_use(self, axisName = None): return self.tk.call(self._w, 'xaxis', 'use', axisName) def x2axis_cget(self, key): return self.tk.call(self._w, 'x2axis', 'cget', '-' + key) def x2axis_configure(self, option=None, **kw): subcommand = (self._w, 'x2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def x2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'x2axis', 'invtransform', value)) def x2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'x2axis', 'limits')) def x2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'x2axis', 'transform', value)) def x2axis_use(self, axisName = None): return self.tk.call(self._w, 'x2axis', 'use', axisName) def yaxis_cget(self, key): return self.tk.call(self._w, 'yaxis', 'cget', '-' + key) def yaxis_configure(self, option=None, **kw): subcommand = (self._w, 'yaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def yaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'yaxis', 'invtransform', value)) def yaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'yaxis', 'limits')) def yaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'yaxis', 'transform', value)) def yaxis_use(self, axisName = None): return self.tk.call(self._w, 'yaxis', 'use', axisName) def y2axis_cget(self, key): return self.tk.call(self._w, 'y2axis', 'cget', '-' + key) def y2axis_configure(self, option=None, **kw): subcommand = (self._w, 'y2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def y2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'y2axis', 'invtransform', value)) def y2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'y2axis', 'limits')) def y2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'y2axis', 'transform', value)) def y2axis_use(self, axisName = None): return self.tk.call(self._w, 'y2axis', 'use', axisName) def crosshairs_cget(self, key): return self.tk.call(self._w, 'crosshairs', 'cget', '-' + key) def crosshairs_configure(self, option=None, **kw): subcommand = (self._w, 'crosshairs', 'configure') return _doConfigure(self, subcommand, option, kw) def crosshairs_off(self): self.tk.call(self._w, 'crosshairs', 'off') def crosshairs_on(self): self.tk.call(self._w, 'crosshairs', 'on') def crosshairs_toggle(self): self.tk.call(self._w, 'crosshairs', 'toggle') def element_activate(self, name, *args): self.tk.call((self._w, 'element', 'activate', name) + args) def element_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'element', 'bind', tagName), sequence, func, add) def element_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'element', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def element_cget(self, name, key): return self.tk.call(self._w, 'element', 'cget', name, '-' + key) def element_closest(self, x, y, *args, **kw): var = 'python_private_1' success = self.tk.getint(self.tk.call( (self._w, 'element', 'closest', x, y, var) + self._options(kw) + args)) if success: rtn = {} rtn['dist'] = self.tk.getdouble(self.tk.globalgetvar(var, 'dist')) rtn['x'] = self.tk.getdouble(self.tk.globalgetvar(var, 'x')) rtn['y'] = self.tk.getdouble(self.tk.globalgetvar(var, 'y')) rtn['index'] = self.tk.getint(self.tk.globalgetvar(var, 'index')) rtn['name'] = self.tk.globalgetvar(var, 'name') return rtn else: return None def element_configure(self, names, option=None, **kw): # <names> may be a list of elemNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'element', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def element_deactivate(self, *args): self.tk.call((self._w, 'element', 'deactivate') + args) def element_delete(self, *args): self.tk.call((self._w, 'element', 'delete') + args) def element_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'element', 'exists', name)) def element_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'element', 'names') + args)) def element_show(self, nameList=None): if nameList is not None: nameList = tuple(nameList) return self.tk.splitlist( self.tk.call(self._w, 'element', 'show', nameList)) def element_type(self, name): return self.tk.call(self._w, 'element', 'type', name) def grid_cget(self, key): return self.tk.call(self._w, 'grid', 'cget', '-' + key) def grid_configure(self, option=None, **kw): subcommand = (self._w, 'grid', 'configure') return _doConfigure(self, subcommand, option, kw) def grid_off(self): self.tk.call(self._w, 'grid', 'off') def grid_on(self): self.tk.call(self._w, 'grid', 'on') def grid_toggle(self): self.tk.call(self._w, 'grid', 'toggle') def legend_activate(self, *args): self.tk.call((self._w, 'legend', 'activate') + args) def legend_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'legend', 'bind', tagName), sequence, func, add) def legend_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'legend', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def legend_cget(self, key): return self.tk.call(self._w, 'legend', 'cget', '-' + key) def legend_configure(self, option=None, **kw): subcommand = (self._w, 'legend', 'configure') return _doConfigure(self, subcommand, option, kw) def legend_deactivate(self, *args): self.tk.call((self._w, 'legend', 'deactivate') + args) def legend_get(self, pos): return self.tk.call(self._w, 'legend', 'get', pos) def pen_cget(self, name, key): return self.tk.call(self._w, 'pen', 'cget', name, '-' + key) def pen_configure(self, names, option=None, **kw): # <names> may be a list of penNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'pen', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def pen_create(self, name, **kw): self.tk.call((self._w, 'pen', 'create', name) + self._options(kw)) def pen_delete(self, *args): self.tk.call((self._w, 'pen', 'delete') + args) def pen_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'pen', 'names') + args)) def postscript_cget(self, key): return self.tk.call(self._w, 'postscript', 'cget', '-' + key) def postscript_configure(self, option=None, **kw): subcommand = (self._w, 'postscript', 'configure') return _doConfigure(self, subcommand, option, kw) def postscript_output(self, fileName=None, **kw): prefix = (self._w, 'postscript', 'output') if fileName is None: return self.tk.call(prefix + self._options(kw)) else: self.tk.call(prefix + (fileName,) + self._options(kw)) def marker_after(self, first, second=None): self.tk.call(self._w, 'marker', 'after', first, second) def marker_before(self, first, second=None): self.tk.call(self._w, 'marker', 'before', first, second) def marker_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'marker', 'bind', tagName), sequence, func, add) def marker_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'marker', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def marker_cget(self, name, key): return self.tk.call(self._w, 'marker', 'cget', name, '-' + key) def marker_configure(self, names, option=None, **kw): # <names> may be a list of markerIds. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'marker', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def marker_create(self, type, **kw): return self.tk.call( (self._w, 'marker', 'create', type) + self._options(kw)) def marker_delete(self, *args): self.tk.call((self._w, 'marker', 'delete') + args) def marker_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'marker', 'exists', name)) def marker_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'marker', 'names') + args)) def marker_type(self, name): type = self.tk.call(self._w, 'marker', 'type', name) if type == '': type = None return type #============================================================================= class Stripchart(Graph): # Wrapper for the blt stripchart widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _chartCommand, cnf, kw) #============================================================================= class Tabset(Tkinter.Widget): # Wrapper for the blt TabSet widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _tabsetCommand, cnf, kw) def activate(self, tabIndex): self.tk.call(self._w, 'activate', tabIndex) # This is the 'bind' sub-command: def tag_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'bind', tagName), sequence, func, add) def tag_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def delete(self, first, last = None): self.tk.call(self._w, 'delete', first, last) # This is the 'focus' sub-command: def tab_focus(self, tabIndex): self.tk.call(self._w, 'focus', tabIndex) def get(self, tabIndex): return self.tk.call(self._w, 'get', tabIndex) def index(self, tabIndex): index = self.tk.call(self._w, 'index', tabIndex) if index == '': return None else: return self.tk.getint(self.tk.call(self._w, 'index', tabIndex)) def insert(self, position, name1, *names, **kw): self.tk.call( (self._w, 'insert', position, name1) + names + self._options(kw)) def invoke(self, tabIndex): return self.tk.call(self._w, 'invoke', tabIndex) def move(self, tabIndex1, beforeOrAfter, tabIndex2): self.tk.call(self._w, 'move', tabIndex1, beforeOrAfter, tabIndex2) def nearest(self, x, y): return self.tk.call(self._w, 'nearest', x, y) def scan_mark(self, x, y): self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): self.tk.call(self._w, 'see', index) def see(self, tabIndex): self.tk.call(self._w,'see',tabIndex) def size(self): return self.tk.getint(self.tk.call(self._w, 'size')) def tab_cget(self, tabIndex, option): if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tab', 'cget', tabIndex, option) def tab_configure(self, tabIndexes, option=None, **kw): # <tabIndexes> may be a list of tabs. if type(tabIndexes) in (types.StringType, types.IntType): tabIndexes = [tabIndexes] subcommand = (self._w, 'tab', 'configure') + tuple(tabIndexes) return _doConfigure(self, subcommand, option, kw) def tab_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'tab', 'names') + args)) def tab_tearoff(self, tabIndex, newName = None): if newName is None: name = self.tk.call(self._w, 'tab', 'tearoff', tabIndex) return self.nametowidget(name) else: self.tk.call(self._w, 'tab', 'tearoff', tabIndex, newName) def view(self): s = self.tk.call(self._w, 'view') return tuple(map(self.tk.getint, self.tk.splitlist(s))) def view_moveto(self, fraction): self.tk.call(self._w, 'view', 'moveto', fraction) def view_scroll(self, number, what): self.tk.call(self._w, 'view', 'scroll', number, what)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # # import exifrotate import exifdatename # # rotates the file using jpegtran if orientation is not horizontal # def rotate( filename ): exifrotate.rotate( filename ) # # return (newdir, newname) tuple based on the EXIF createdate infromation # def newname( filename ): return exifdatename.newname( filename )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os.path from subprocess import Popen, PIPE from fileops import quotepath def eqlen( str ): if len(str) == 1: str = "0" + str return str # ----------------------------------------------------------------------- # return ('<year>/<month>', <datename>') tuple based on files EXIF date # def newname( filename ): # --a no duplicate tags # -f force printing of tags even if values are not found # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -CreateDate " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() # parse createdate values (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "problem running exiftool (%s)" % filename ) if str.strip().lower() != "create date": ui.ERR( "exiftool: createdate not found (%s)" % filename ) try: (date,time) = data.strip().split(' ') (year,mon,day) = date.split(':') mon = eqlen( mon ) day = eqlen( day ) (hour,min,sec) = time.split(':') hour = eqlen( hour ) min = eqlen( min ) sec = eqlen( sec ) except: ui.ERR( "problem parsing EXIF date (%s)" % data) newdir = year + os.path.sep + mon newname = "%s%s%s-%s%s%s" % (year,mon,day,hour,min,sec) return (newdir, newname)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os, os.path import tempfile from subprocess import Popen, PIPE from fileops import copy, quotepath # # map orientation values to jpegtran commands to make the pic right # data is from # http://sylvana.net/jpegcrop/exif_orientation.html TRANS = [ [ "" ], # not in use [ "" ], [ "-flip horizontal" ], [ "-rotate 180 -trim" ], [ "-flip vertical" ], [ "-transpose" ], [ "-rotate 90 -trim" ], [ "-transverse" ], [ "-rotate 90 -trim", "-rotate 180 -trim" ] ] # -------------------------------------------------------------------- def rotate( filename ): dir = os.path.dirname( filename ) file = os.path.basename( filename ) # --a no duplicate tags # -f force printing of tags even if values are not found (0 is unknown) # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -Orientation " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (read orientation1) (%s)" % filename ) # parse orientation (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "exception in exiftool (read orientation2) (%s)" % filename ) if str.strip().lower() != "orientation": ui.ERR( "exiftool: orientation not found (%s)" % str ) orientation = int( data.strip() ) if orientation > 8: ui.ERR( "orientation out of range (%d,%s)" % (orientation, filename) ) # 0 : unknown orientation -> do not touch # 1 : horizontal orientation -> no need to rotate if orientation == 0 or orientation == 1: return # # execute rotation operations defined in table 'TRANS' # rotations are written to a new file which is copied to the # original file in the last step # fromfile = filename tmpfiles = [] for op in TRANS[ orientation ]: (fd, tmp) = tempfile.mkstemp( '', '', dir ) os.close(fd) # XXX: closing tmpfile and using the filename creates a race condition # but target is usually in users subdirectory and this program is usually # run in a personal computer, so risk should be minimal/acceptable tmpfiles.append( tmp ) # record name for cleanup later # -copy all preserves original EXIF information rot_cmd = config.jpegtran + " -copy all -outfile " \ + quotepath(tmp) + " " + op + " " + quotepath(fromfile) try: pipe = Popen( rot_cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running jpegtran (%s)" % fromfile ) except: ui.ERR("exception in jpegtran (%s)" % rot_cmd ) fromfile = tmp # endfor # move the last resultfile into original name if fromfile != filename: try: os.remove( filename ) os.rename( fromfile, filename ) except: ui.ERR("error finalizing jpegtran (%s)" % filename ) # rotation should have made the picture into 'horizontal' orientation so # change the orientation EXIF info to match that cmd = config.exiftool + " -overwrite_original_in_place -n -Orientation=1 " \ + quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (set orientation) (%s)" % filename ) except: ui.ERR( "exception in exiftool (set orientation) (%s)" % filename ) # remove any tempfiles still present in the filesystem for f in tmpfiles: if os.path.exists( f ): try: os.remove( f ) except: ui.ERR("cannot remove tempfile (%s)" % f )
Python
from distutils.core import setup import py2app opts = { "py2app": { # i18n languages are loaded at runtime so py2exe won't find em "includes": "i18n.finnish, i18n.english", "optimize" : 2, "argv_emulation":True, "iconfile" : "flickfleck.icns", # "semi_standalone":True, # "bundle_files" : 1, # does not seem to work in my env "dist_dir": "packaging/macos", } } setup(name = "flickfleck", version = "1.0.0", author = "Jyke Tapani Jokinen", author_email = "jyke.t.jokinen(at)gmail.com", # packages = ["ui", "jpegops"], data_files =[('', ['GPL.txt', 'README.txt', 'config.txt', 'flickfleck.ico']) # ('tools', ['tools/jpegtran', 'tools/exiftool']) ], url = 'http://flickfleck.googlecode.com/', download_url = 'http://flickfleck.googlecode.com/', options = opts, app=[{"script": 'flickfleck.py', "icon_resources" : [(1, "flickfleck.icns")], }])
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
from distutils.core import setup import py2exe opts = { "py2exe": { # i18n languages are loaded at runtime so py2exe won't find em "includes": "i18n.finnish, i18n.english", "optimize" : 2, # "bundle_files" : 1, # does not seem to work in my env "dist_dir": "packaging/windows", } } setup(name = "flickfleck", version = "1.0.0", author = "Jyke Tapani Jokinen", author_email = "jyke.t.jokinen(at)gmail.com", # packages = ["ui", "jpegops"], data_files =[('', ['GPL.txt', 'README.txt', 'config.txt', 'flickfleck.ico']), ('tools', ['tools/jpegtran.exe', 'tools/exiftool.exe']) ], url = 'http://flickfleck.googlecode.com/', download_url = 'http://flickfleck.googlecode.com/', options = opts, windows=[{"script": 'flickfleck.py', "icon_resources" : [(1, "flickfleck.ico")], }])
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import i18n if __name__=='__main__': print i18n.name['Start']
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import ui import engine if __name__=='__main__': ui.wins.engine.init() print ui.wins.engine.jpegtran print ui.wins.engine.exiftool
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import jpegops if __name__=='__main__': if len(sys.argv) < 2: print "Usage: %s <jpg files>" % sys.argv[0] else: for file in sys.argv[1:]: jpegops.rotate( file )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import ui from copier import PhotoCopier ui.wins.engine = PhotoCopier()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import sys, os, os.path import ui import types import fnmatch import i18n import jpegops import fileops from subprocess import Popen, PIPE class PhotoCopier: def __init__(self): pass def init(self): # what external binary to use cmd_j = self.findexe( config.jpegtran ) cmd_e = self.findexe( config.exiftool ) # how to execute the binary if sys.platform == 'win32': # 'call' found in bugs.python.org/issue1524 config.jpegtran = 'call ' + fileops.quotepath( cmd_j ) config.exiftool = 'call ' + fileops.quotepath( cmd_e ) else: config.jpegtran = cmd_j config.exiftool = cmd_e self.init_filelist() # # called at program startup # def init_filelist(self): # # find all jpeg-files # fromdir can be a list of directories (all are scanned) # self._frompaths = [] if type(config.fromdir) == types.ListType: for dir in config.fromdir: self.addsourcefiles(dir) else: self.addsourcefiles(config.fromdir) # tell number of found files to the user and the progressbar numitems = len(self._frompaths) ui.status( i18n.name['status_found'] + " " + str( numitems ) + " " + i18n.name['status_files'] ) ui.wins.pb.init( numitems ) # finds all jpegs under 'dir' # definition of a jpeg is config.jpegglob def addsourcefiles(self, dir): for root,dirs,files in os.walk( dir ): if len(files) == 0: continue for filt in config.jpegglob: found = fnmatch.filter( files, filt ) if len(found) > 0: for name in found: self._frompaths.append( os.path.join( root, name ) ) # ---------------------------------------------------------------------- def findexe(self, programname): # if an absolute pathname is configured, use that: if os.path.isabs( programname ): return programname # # if the executable is found in FlickFlecks binary dir, use that # tool = config.installdir + os.sep + config.bindir \ + os.sep + programname if os.access( tool, os.X_OK ): return tool # # if we can execute the program then it's in the path, use that # else: cmd = programname + " NOSUCHFILEEXITS" pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) pipe.wait() # # on Windows only 0 means we could execute the program # (XXX: these test are ad hoc, traversing PATH would be better) if sys.platform == 'win32': if pipe.returncode == 0: return programname # # on UNIX we can execute the program and it can give 1 as error # return code (bad parameter) # elif 0 <= pipe.returncode <= 1: return programname ui.ERR( ("cannot find executable %s" % programname) ) # ---------------------------------------------------------------------- # user started the operations # def start(self): if len( self._frompaths) == 0: ui.ERR("No files to copy") from fileops import copy dst = config.todir if not os.path.exists( dst ): ui.ERR("Target directory (%s) does not exists" % dst) self._newnames = [] # -------- copy files to new location and name --------------- ui.status( i18n.name['status_copying'] ) ui.wins.pb.clear() # reset progressbar for src in self._frompaths: (newdir,newname) = jpegops.newname( src ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # step progressbar targetNOTok = True silentskip = False counter = 0 # if the targetfilename already exists, increase the counter # and add it to the generated filename # loop until unique name is found while targetNOTok: if config.targetdirs == True: to = dst + os.path.sep + newdir + os.path.sep + newname else: to = dst + os.path.sep + newname if counter > 0: to += "-" + str(counter) to += ".jpg" if os.access( to, os.F_OK ): if hasattr(config, 'silentskip'): silentskip = True targetNOTok = False if counter > 999: ui.ERR( "cannot transfer file: %s" % src ) counter = counter + 1 else: targetNOTok = False # end while if silentskip: continue # make target subdirs if not already made if config.targetdirs == True: path = dst + os.path.sep for dir in newdir.split( os.path.sep ): path += dir + os.path.sep if not os.path.exists( path ): os.mkdir( path ) # save the targetfilename for rotation operations self._newnames.append( to ) copy( src, to ) # ------------ rotate files ------------- ui.status( i18n.name['status_rotating'] ) ui.wins.pb.clear() # reset progressbar for file in self._newnames: jpegops.rotate( file ) ui.checkStop() # was operation cancelled by user ui.wins.pb.step() # update progressbar ui.status( i18n.name['status_done'] ) ui.Ready()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config name = {} # config.LANGUAGE is used as a module name to import # an object/hash named Text() from that module should contain # localized strings # XXX: should really use gettext and http://translationproject.org # or similar service def init(): global name mod = __import__( config.LANGUAGE, globals(), locals() ) name = mod.Text()
Python
class Text: def __init__(self): self.d = { 'apperror' : 'Application error', 'finished' : 'Files copied successfully.', 'appclose' : 'This application will now close', 'menu_file' : 'File', 'menu_file_fromdir' : 'Select picture folder (fromdir)', 'menu_file_todir' : 'Select target folder (todir)', 'menu_file_config' : 'Edit configuration', 'menu_file_exit' : 'Exit', 'menu_about' : 'About...', 'label_copyfrom' : 'Copy files from:', 'label_copyto' : 'To:', 'label_status' : 'Status:', 'button_start' : 'Start', 'button_stop' : 'Cancel', 'status_idle' : 'Idle', 'status_done' : 'Done', 'status_found' : 'Found', 'status_files' : 'files', 'status_copying' : 'Copying files...', 'status_rotating' : 'Rotating files...' } def __getitem__(self, name): if name != None: try: retval = self.d[name] except: retval = 'i18n ERROR (%s)' % name return retval
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys import config import ui import os, os.path import sys # # read a configuration file and set values to config-module # def readconfig( file, mod ): try: f = open( file ) for line in f.readlines(): line = line.strip() if len(line) < 1: continue # skip blank lines if line[0] == '#': continue # comment lines try: name, val = line.split('=', 1) setattr( mod, name.strip(), eval( val.strip() ) ) except ValueError: ui.ERR( "Unknown line in config-file (%s)" % line ) f.close() # any error in processing config datafile is silently ignored # (defaults are used instead) except IOError: pass # # called at program startup to initialize the configuration # def init(): mod = sys.modules['config'] readconfig( 'config.txt', mod ) readconfig( 'config.local', mod ) if sys.platform == 'darwin': readconfig( _mac_confpath(), mod ) # executables if not hasattr( mod, 'jpegtran' ): if sys.platform == 'win32': setattr(mod, 'jpegtran', "jpegtran.exe") else: setattr(mod, 'jpegtran', "jpegtran" ) if not hasattr( mod, 'exiftool' ): if sys.platform == 'win32': setattr(mod, 'exiftool', "exiftool.exe" ) else: setattr(mod, 'exiftool', "exiftool" ) # these cannot be set in the configuration file setattr(mod, 'TITLE', 'FlickFleck') setattr(mod, 'VERSION', '1.0') # if program was started with a parameter, use that as fromdir if len(sys.argv) > 1: setattr(mod, 'fromdir', sys.argv[1]) # try to sanitize the filepath values import os.path setattr(mod, 'fromdir', os.path.normpath( config.fromdir ) ) setattr(mod, 'todir' , os.path.normpath( config.todir ) ) if sys.platform == 'darwin': mac_initconfig() # location where we want to store config in macosX def _mac_confpath(): if sys.platform == 'darwin': return os.environ["HOME"] + "/Library/Preferences/FlickFleck.txt" else: return "NOSUCHFILE" # should not happen, but wont raise error here # if we don't have a config in Preferences (macosX) go and create it def mac_initconfig(): if sys.platform == 'darwin': if not os.path.exists( _mac_confpath() ): import shutil shutil.copy( config.installdir + "/config.txt", _mac_confpath() ) # simple way to allow user to edit the config (macosX) def mac_editconfig(): if sys.platform == 'darwin': # I'm real happy that macosX will find the editor for me os.system( "open " + _mac_confpath() )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import os, os.path import sys import shutil import ui # ------------------------------------------------------------------------ # in win32 add quotes around path (there can be spaces in names) # XXX: spaces in filepaths should be worked out int UNIX too def quotepath( path ): if sys.platform == 'win32': return '"' + path + '"' else: return path # ------------------------------------------------------------------------ # stops if we cannot access the named file def verify_access( file ): if not os.access( file, os.F_OK ): ui.ERR( "fileops.access: %s: access denied" % file ) # ------------------------------------------------------------------------ # tries to do a safe copy from 'orig_file' to 'new_file' # def copy( orig_file, new_file ): f_from = os.path.normpath( orig_file ) f_to = os.path.normpath( new_file ) # if copying to itself if f_from == f_to: ui.ERR( "fileops.copy: copying a file to itself? (%s)" % f_from ) # we should be able to access fromfile verify_access( f_from ) # target should not exists (caller should make sure of this) if os.path.exists( f_to ): ui.ERR( "fileops.copy: target file exists (%s)" % f_to ) try: shutil.copy2( f_from, f_to ) # preserves attributes except: ui.ERR("fileops.copy: copy2 operation failed (%s)" % f_from) # do some sanity checks to the file we just created verify_access( f_to ) if os.path.getsize( f_to ) < 1: ui.ERR("fileops.copy: target filesize zero (%s)" % f_to ) # # debug/testing # if __name__ == '__main__': import sys import tempfile sys.path.insert("..") filename1 = tempfile.mktemp (".txt") open (filename1, "w").close () filename2 = filename1 + ".copy" print filename1, "=>", filename2 copy( filename1, filename2 )
Python
# # Default configuration for FlickFleck # fromdir = 'tests' todir = '/tmp' # create target subdirs (year/month) targetdirs = True # languages are defined in moduledir: i18n # every language module must also be listed in setup.py LANGUAGE = "english" # what files to process: jpegglob = [ "*.jpg", "*.jpeg" ] # SVN version SVNversion=" $Id: config.py 65 2008-11-27 09:43:11Z jyke.t.jokinen $ " # installdir will be overwritten at startup (flickfleck install location) installdir = "" # bindir can contain external tools (if not in path) bindir = "tools"
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import Tkinter import ui # adhoc widget to make a progressbar # class Widget: def __init__(self, parent): self.w_parent = parent self.w_canvas = Tkinter.Canvas( parent ) self.w_canvas.pack( fill='x', expand='yes') # called when the number of items in the whole operation is known def init(self, num_items): self.max = num_items self.clear() # called if starting again with the same max value def clear(self): self.count = 0 self.w_canvas.delete(Tkinter.ALL) # draw one step forward in the progressbar (previously set max value used) def step(self): self.count = self.count + 1 width = int( self.w_canvas['width'] ) # if one_item_width < 1.0 it would go to zero with ints: one_item = float(width) / float(self.max) draw_width = one_item * self.count self.w_canvas.delete(Tkinter.ALL) self.w_canvas.create_rectangle(0,0, draw_width,ui.wins.PBheight, fill='blue') self.w_parent.update()
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import tkMessageBox import sys import wins import mainwin import i18n #----------------------------------------------------------------- # show error message and close the application # def ERR( str ): tkMessageBox.showerror(i18n.name['apperror'], str + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- # all done. this version closes application after this # def Ready(): tkMessageBox.showinfo(config.TITLE, i18n.name['finished'] + '\n' + i18n.name['appclose'] ) sys.exit() #----------------------------------------------------------------- def status( str ): wins.main.status( str ) #----------------------------------------------------------------- # called at program startup # creates all windows # def init(): wins.root = Pmw.initialise( fontScheme = 'pmw1' ) wins.root.withdraw() if sys.platform == 'darwin' and hasattr(sys, 'frozen'): wins.root.tk.call('console', 'hide') wins.root.title( config.TITLE ) if sys.platform == 'win32': wins.root.iconbitmap('flickfleck.ico') elif sys.platform == 'darwin': grey="#CCCCCC" wins.root.config(background=grey, highlightbackground=grey) # wins.root.option_add( "*background", grey ) # wins.root.option_add( "*activebackground", grey ) # wins.root.option_add( "*highlightbackground", grey ) # wins.root.option_add( "*insertBackground", grey ) # wins.root.option_add( "*selectBackground", grey ) wins.root.tk_setPalette( grey ) else: pass #wins.root.iconbitmap('flickfleck.xbm') wins.main = mainwin.FlickFleck(wins.root) wins.root.deiconify() #----------------------------------------------------------------- def start(): wins.root.mainloop() #----------------------------------------------------------------- # engine calls this in file operations loops to check if user # wants to cancel # def checkStop(): wins.root.update() if wins.requestStop: ERR("Stopped by the User")
Python
import PmwColor Color = PmwColor del PmwColor import PmwBlt Blt = PmwBlt del PmwBlt ### Loader functions: _VERSION = '1.3' def setversion(version): if version != _VERSION: raise ValueError, 'Dynamic versioning not available' def setalphaversions(*alpha_versions): if alpha_versions != (): raise ValueError, 'Dynamic versioning not available' def version(alpha = 0): if alpha: return () else: return _VERSION def installedversions(alpha = 0): if alpha: return () else: return (_VERSION,) ###################################################################### ### File: PmwBase.py # Pmw megawidget base classes. # This module provides a foundation for building megawidgets. It # contains the MegaArchetype class which manages component widgets and # configuration options. Also provided are the MegaToplevel and # MegaWidget classes, derived from the MegaArchetype class. The # MegaToplevel class contains a Tkinter Toplevel widget to act as the # container of the megawidget. This is used as the base class of all # megawidgets that are contained in their own top level window, such # as a Dialog window. The MegaWidget class contains a Tkinter Frame # to act as the container of the megawidget. This is used as the base # class of all other megawidgets, such as a ComboBox or ButtonBox. # # Megawidgets are built by creating a class that inherits from either # the MegaToplevel or MegaWidget class. import os import string import sys import traceback import types import Tkinter # Special values used in index() methods of several megawidgets. END = ['end'] SELECT = ['select'] DEFAULT = ['default'] # Constant used to indicate that an option can only be set by a call # to the constructor. INITOPT = ['initopt'] _DEFAULT_OPTION_VALUE = ['default_option_value'] _useTkOptionDb = 0 # Symbolic constants for the indexes into an optionInfo list. _OPT_DEFAULT = 0 _OPT_VALUE = 1 _OPT_FUNCTION = 2 # Stacks _busyStack = [] # Stack which tracks nested calls to show/hidebusycursor (called # either directly or from activate()/deactivate()). Each element # is a dictionary containing: # 'newBusyWindows' : List of windows which had busy_hold called # on them during a call to showbusycursor(). # The corresponding call to hidebusycursor() # will call busy_release on these windows. # 'busyFocus' : The blt _Busy window which showbusycursor() # set the focus to. # 'previousFocus' : The focus as it was when showbusycursor() # was called. The corresponding call to # hidebusycursor() will restore this focus if # the focus has not been changed from busyFocus. _grabStack = [] # Stack of grabbed windows. It tracks calls to push/popgrab() # (called either directly or from activate()/deactivate()). The # window on the top of the stack is the window currently with the # grab. Each element is a dictionary containing: # 'grabWindow' : The window grabbed by pushgrab(). The # corresponding call to popgrab() will release # the grab on this window and restore the grab # on the next window in the stack (if there is one). # 'globalMode' : True if the grabWindow was grabbed with a # global grab, false if the grab was local # and 'nograb' if no grab was performed. # 'previousFocus' : The focus as it was when pushgrab() # was called. The corresponding call to # popgrab() will restore this focus. # 'deactivateFunction' : # The function to call (usually grabWindow.deactivate) if # popgrab() is called (usually from a deactivate() method) # on a window which is not at the top of the stack (that is, # does not have the grab or focus). For example, if a modal # dialog is deleted by the window manager or deactivated by # a timer. In this case, all dialogs above and including # this one are deactivated, starting at the top of the # stack. # Note that when dealing with focus windows, the name of the Tk # widget is used, since it may be the '_Busy' window, which has no # python instance associated with it. #============================================================================= # Functions used to forward methods from a class to a component. # Fill in a flattened method resolution dictionary for a class (attributes are # filtered out). Flattening honours the MI method resolution rules # (depth-first search of bases in order). The dictionary has method names # for keys and functions for values. def __methodDict(cls, dict): # the strategy is to traverse the class in the _reverse_ of the normal # order, and overwrite any duplicates. baseList = list(cls.__bases__) baseList.reverse() # do bases in reverse order, so first base overrides last base for super in baseList: __methodDict(super, dict) # do my methods last to override base classes for key, value in cls.__dict__.items(): # ignore class attributes if type(value) == types.FunctionType: dict[key] = value def __methods(cls): # Return all method names for a class. # Return all method names for a class (attributes are filtered # out). Base classes are searched recursively. dict = {} __methodDict(cls, dict) return dict.keys() # Function body to resolve a forwarding given the target method name and the # attribute name. The resulting lambda requires only self, but will forward # any other parameters. __stringBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(attribute)s.%(method)s, args, kw)') # Get a unique id __counter = 0 def __unique(): global __counter __counter = __counter + 1 return str(__counter) # Function body to resolve a forwarding given the target method name and the # index of the resolution function. The resulting lambda requires only self, # but will forward any other parameters. The target instance is identified # by invoking the resolution function. __funcBody = ( 'def %(method)s(this, *args, **kw): return ' + 'apply(this.%(forwardFunc)s().%(method)s, args, kw)') def forwardmethods(fromClass, toClass, toPart, exclude = ()): # Forward all methods from one class to another. # Forwarders will be created in fromClass to forward method # invocations to toClass. The methods to be forwarded are # identified by flattening the interface of toClass, and excluding # methods identified in the exclude list. Methods already defined # in fromClass, or special methods with one or more leading or # trailing underscores will not be forwarded. # For a given object of class fromClass, the corresponding toClass # object is identified using toPart. This can either be a String # denoting an attribute of fromClass objects, or a function taking # a fromClass object and returning a toClass object. # Example: # class MyClass: # ... # def __init__(self): # ... # self.__target = TargetClass() # ... # def findtarget(self): # return self.__target # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2']) # # ...or... # forwardmethods(MyClass, TargetClass, MyClass.findtarget, # ['dangerous1', 'dangerous2']) # In both cases, all TargetClass methods will be forwarded from # MyClass except for dangerous1, dangerous2, special methods like # __str__, and pre-existing methods like findtarget. # Allow an attribute name (String) or a function to determine the instance if type(toPart) != types.StringType: # check that it is something like a function if callable(toPart): # If a method is passed, use the function within it if hasattr(toPart, 'im_func'): toPart = toPart.im_func # After this is set up, forwarders in this class will use # the forwarding function. The forwarding function name is # guaranteed to be unique, so that it can't be hidden by subclasses forwardName = '__fwdfunc__' + __unique() fromClass.__dict__[forwardName] = toPart # It's not a valid type else: raise TypeError, 'toPart must be attribute name, function or method' # get the full set of candidate methods dict = {} __methodDict(toClass, dict) # discard special methods for ex in dict.keys(): if ex[:1] == '_' or ex[-1:] == '_': del dict[ex] # discard dangerous methods supplied by the caller for ex in exclude: if dict.has_key(ex): del dict[ex] # discard methods already defined in fromClass for ex in __methods(fromClass): if dict.has_key(ex): del dict[ex] for method, func in dict.items(): d = {'method': method, 'func': func} if type(toPart) == types.StringType: execString = \ __stringBody % {'method' : method, 'attribute' : toPart} else: execString = \ __funcBody % {'forwardFunc' : forwardName, 'method' : method} exec execString in d # this creates a method fromClass.__dict__[method] = d[method] #============================================================================= def setgeometryanddeiconify(window, geom): # To avoid flashes on X and to position the window correctly on NT # (caused by Tk bugs). if os.name == 'nt' or \ (os.name == 'posix' and sys.platform[:6] == 'cygwin'): # Require overrideredirect trick to stop window frame # appearing momentarily. redirect = window.overrideredirect() if not redirect: window.overrideredirect(1) window.deiconify() if geom is not None: window.geometry(geom) # Call update_idletasks to ensure NT moves the window to the # correct position it is raised. window.update_idletasks() window.tkraise() if not redirect: window.overrideredirect(0) else: if geom is not None: window.geometry(geom) # Problem!? Which way around should the following two calls # go? If deiconify() is called first then I get complaints # from people using the enlightenment or sawfish window # managers that when a dialog is activated it takes about 2 # seconds for the contents of the window to appear. But if # tkraise() is called first then I get complaints from people # using the twm window manager that when a dialog is activated # it appears in the top right corner of the screen and also # takes about 2 seconds to appear. #window.tkraise() # Call update_idletasks to ensure certain window managers (eg: # enlightenment and sawfish) do not cause Tk to delay for # about two seconds before displaying window. #window.update_idletasks() #window.deiconify() window.deiconify() if window.overrideredirect(): # The window is not under the control of the window manager # and so we need to raise it ourselves. window.tkraise() #============================================================================= class MegaArchetype: # Megawidget abstract root class. # This class provides methods which are inherited by classes # implementing useful bases (this class doesn't provide a # container widget inside which the megawidget can be built). def __init__(self, parent = None, hullClass = None): # Mapping from each megawidget option to a list of information # about the option # - default value # - current value # - function to call when the option is initialised in the # call to initialiseoptions() in the constructor or # modified via configure(). If this is INITOPT, the # option is an initialisation option (an option that can # be set by the call to the constructor but can not be # used with configure). # This mapping is not initialised here, but in the call to # defineoptions() which precedes construction of this base class. # # self._optionInfo = {} # Mapping from each component name to a tuple of information # about the component. # - component widget instance # - configure function of widget instance # - the class of the widget (Frame, EntryField, etc) # - cget function of widget instance # - the name of the component group of this component, if any self.__componentInfo = {} # Mapping from alias names to the names of components or # sub-components. self.__componentAliases = {} # Contains information about the keywords provided to the # constructor. It is a mapping from the keyword to a tuple # containing: # - value of keyword # - a boolean indicating if the keyword has been used. # A keyword is used if, during the construction of a megawidget, # - it is defined in a call to defineoptions() or addoptions(), or # - it references, by name, a component of the megawidget, or # - it references, by group, at least one component # At the end of megawidget construction, a call is made to # initialiseoptions() which reports an error if there are # unused options given to the constructor. # # After megawidget construction, the dictionary contains # keywords which refer to a dynamic component group, so that # these components can be created after megawidget # construction and still use the group options given to the # constructor. # # self._constructorKeywords = {} # List of dynamic component groups. If a group is included in # this list, then it not an error if a keyword argument for # the group is given to the constructor or to configure(), but # no components with this group have been created. # self._dynamicGroups = () if hullClass is None: self._hull = None else: if parent is None: parent = Tkinter._default_root # Create the hull. self._hull = self.createcomponent('hull', (), None, hullClass, (parent,)) _hullToMegaWidget[self._hull] = self if _useTkOptionDb: # Now that a widget has been created, query the Tk # option database to get the default values for the # options which have not been set in the call to the # constructor. This assumes that defineoptions() is # called before the __init__(). option_get = self.option_get _VALUE = _OPT_VALUE _DEFAULT = _OPT_DEFAULT for name, info in self._optionInfo.items(): value = info[_VALUE] if value is _DEFAULT_OPTION_VALUE: resourceClass = string.upper(name[0]) + name[1:] value = option_get(name, resourceClass) if value != '': try: # Convert the string to int/float/tuple, etc value = eval(value, {'__builtins__': {}}) except: pass info[_VALUE] = value else: info[_VALUE] = info[_DEFAULT] def destroy(self): # Clean up optionInfo in case it contains circular references # in the function field, such as self._settitle in class # MegaToplevel. self._optionInfo = {} if self._hull is not None: del _hullToMegaWidget[self._hull] self._hull.destroy() #====================================================================== # Methods used (mainly) during the construction of the megawidget. def defineoptions(self, keywords, optionDefs, dynamicGroups = ()): # Create options, providing the default value and the method # to call when the value is changed. If any option created by # base classes has the same name as one in <optionDefs>, the # base class's value and function will be overriden. # This should be called before the constructor of the base # class, so that default values defined in the derived class # override those in the base class. if not hasattr(self, '_constructorKeywords'): # First time defineoptions has been called. tmp = {} for option, value in keywords.items(): tmp[option] = [value, 0] self._constructorKeywords = tmp self._optionInfo = {} self._initialiseoptions_counter = 0 self._initialiseoptions_counter = self._initialiseoptions_counter + 1 if not hasattr(self, '_dynamicGroups'): self._dynamicGroups = () self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups) self.addoptions(optionDefs) def addoptions(self, optionDefs): # Add additional options, providing the default value and the # method to call when the value is changed. See # "defineoptions" for more details # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key keywords = self._constructorKeywords keywords_has_key = keywords.has_key FUNCTION = _OPT_FUNCTION for name, default, function in optionDefs: if '_' not in name: # The option will already exist if it has been defined # in a derived class. In this case, do not override the # default value of the option or the callback function # if it is not None. if not optionInfo_has_key(name): if keywords_has_key(name): value = keywords[name][0] optionInfo[name] = [default, value, function] del keywords[name] else: if _useTkOptionDb: optionInfo[name] = \ [default, _DEFAULT_OPTION_VALUE, function] else: optionInfo[name] = [default, default, function] elif optionInfo[name][FUNCTION] is None: optionInfo[name][FUNCTION] = function else: # This option is of the form "component_option". If this is # not already defined in self._constructorKeywords add it. # This allows a derived class to override the default value # of an option of a component of a base class. if not keywords_has_key(name): keywords[name] = [default, 0] def createcomponent(self, componentName, componentAliases, componentGroup, widgetClass, *widgetArgs, **kw): # Create a component (during construction or later). if self.__componentInfo.has_key(componentName): raise ValueError, 'Component "%s" already exists' % componentName if '_' in componentName: raise ValueError, \ 'Component name "%s" must not contain "_"' % componentName if hasattr(self, '_constructorKeywords'): keywords = self._constructorKeywords else: keywords = {} for alias, component in componentAliases: # Create aliases to the component and its sub-components. index = string.find(component, '_') if index < 0: self.__componentAliases[alias] = (component, None) else: mainComponent = component[:index] subComponent = component[(index + 1):] self.__componentAliases[alias] = (mainComponent, subComponent) # Remove aliases from the constructor keyword arguments by # replacing any keyword arguments that begin with *alias* # with corresponding keys beginning with *component*. alias = alias + '_' aliasLen = len(alias) for option in keywords.keys(): if len(option) > aliasLen and option[:aliasLen] == alias: newkey = component + '_' + option[aliasLen:] keywords[newkey] = keywords[option] del keywords[option] componentPrefix = componentName + '_' nameLen = len(componentPrefix) for option in keywords.keys(): if len(option) > nameLen and option[:nameLen] == componentPrefix: # The keyword argument refers to this component, so add # this to the options to use when constructing the widget. kw[option[nameLen:]] = keywords[option][0] del keywords[option] else: # Check if this keyword argument refers to the group # of this component. If so, add this to the options # to use when constructing the widget. Mark the # keyword argument as being used, but do not remove it # since it may be required when creating another # component. index = string.find(option, '_') if index >= 0 and componentGroup == option[:index]: rest = option[(index + 1):] kw[rest] = keywords[option][0] keywords[option][1] = 1 if kw.has_key('pyclass'): widgetClass = kw['pyclass'] del kw['pyclass'] if widgetClass is None: return None if len(widgetArgs) == 1 and type(widgetArgs[0]) == types.TupleType: # Arguments to the constructor can be specified as either # multiple trailing arguments to createcomponent() or as a # single tuple argument. widgetArgs = widgetArgs[0] widget = apply(widgetClass, widgetArgs, kw) componentClass = widget.__class__.__name__ self.__componentInfo[componentName] = (widget, widget.configure, componentClass, widget.cget, componentGroup) return widget def destroycomponent(self, name): # Remove a megawidget component. # This command is for use by megawidget designers to destroy a # megawidget component. self.__componentInfo[name][0].destroy() del self.__componentInfo[name] def createlabel(self, parent, childCols = 1, childRows = 1): labelpos = self['labelpos'] labelmargin = self['labelmargin'] if labelpos is None: return label = self.createcomponent('label', (), None, Tkinter.Label, (parent,)) if labelpos[0] in 'ns': # vertical layout if labelpos[0] == 'n': row = 0 margin = 1 else: row = childRows + 3 margin = row - 1 label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos) parent.grid_rowconfigure(margin, minsize=labelmargin) else: # horizontal layout if labelpos[0] == 'w': col = 0 margin = 1 else: col = childCols + 3 margin = col - 1 label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos) parent.grid_columnconfigure(margin, minsize=labelmargin) def initialiseoptions(self, dummy = None): self._initialiseoptions_counter = self._initialiseoptions_counter - 1 if self._initialiseoptions_counter == 0: unusedOptions = [] keywords = self._constructorKeywords for name in keywords.keys(): used = keywords[name][1] if not used: # This keyword argument has not been used. If it # does not refer to a dynamic group, mark it as # unused. index = string.find(name, '_') if index < 0 or name[:index] not in self._dynamicGroups: unusedOptions.append(name) if len(unusedOptions) > 0: if len(unusedOptions) == 1: text = 'Unknown option "' else: text = 'Unknown options "' raise KeyError, text + string.join(unusedOptions, ', ') + \ '" for ' + self.__class__.__name__ # Call the configuration callback function for every option. FUNCTION = _OPT_FUNCTION for info in self._optionInfo.values(): func = info[FUNCTION] if func is not None and func is not INITOPT: func() #====================================================================== # Method used to configure the megawidget. def configure(self, option=None, **kw): # Query or configure the megawidget options. # # If not empty, *kw* is a dictionary giving new # values for some of the options of this megawidget or its # components. For options defined for this megawidget, set # the value of the option to the new value and call the # configuration callback function, if any. For options of the # form <component>_<option>, where <component> is a component # of this megawidget, call the configure method of the # component giving it the new value of the option. The # <component> part may be an alias or a component group name. # # If *option* is None, return all megawidget configuration # options and settings. Options are returned as standard 5 # element tuples # # If *option* is a string, return the 5 element tuple for the # given configuration option. # First, deal with the option queries. if len(kw) == 0: # This configure call is querying the values of one or all options. # Return 5-tuples: # (optionName, resourceName, resourceClass, default, value) if option is None: rtn = {} for option, config in self._optionInfo.items(): resourceClass = string.upper(option[0]) + option[1:] rtn[option] = (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) return rtn else: config = self._optionInfo[option] resourceClass = string.upper(option[0]) + option[1:] return (option, option, resourceClass, config[_OPT_DEFAULT], config[_OPT_VALUE]) # optimisations: optionInfo = self._optionInfo optionInfo_has_key = optionInfo.has_key componentInfo = self.__componentInfo componentInfo_has_key = componentInfo.has_key componentAliases = self.__componentAliases componentAliases_has_key = componentAliases.has_key VALUE = _OPT_VALUE FUNCTION = _OPT_FUNCTION # This will contain a list of options in *kw* which # are known to this megawidget. directOptions = [] # This will contain information about the options in # *kw* of the form <component>_<option>, where # <component> is a component of this megawidget. It is a # dictionary whose keys are the configure method of each # component and whose values are a dictionary of options and # values for the component. indirectOptions = {} indirectOptions_has_key = indirectOptions.has_key for option, value in kw.items(): if optionInfo_has_key(option): # This is one of the options of this megawidget. # Make sure it is not an initialisation option. if optionInfo[option][FUNCTION] is INITOPT: raise KeyError, \ 'Cannot configure initialisation option "' \ + option + '" for ' + self.__class__.__name__ optionInfo[option][VALUE] = value directOptions.append(option) else: index = string.find(option, '_') if index >= 0: # This option may be of the form <component>_<option>. component = option[:index] componentOption = option[(index + 1):] # Expand component alias if componentAliases_has_key(component): component, subComponent = componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' \ + componentOption # Expand option string to write on error option = component + '_' + componentOption if componentInfo_has_key(component): # Configure the named component componentConfigFuncs = [componentInfo[component][1]] else: # Check if this is a group name and configure all # components in the group. componentConfigFuncs = [] for info in componentInfo.values(): if info[4] == component: componentConfigFuncs.append(info[1]) if len(componentConfigFuncs) == 0 and \ component not in self._dynamicGroups: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Add the configure method(s) (may be more than # one if this is configuring a component group) # and option/value to dictionary. for componentConfigFunc in componentConfigFuncs: if not indirectOptions_has_key(componentConfigFunc): indirectOptions[componentConfigFunc] = {} indirectOptions[componentConfigFunc][componentOption] \ = value else: raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ # Call the configure methods for any components. map(apply, indirectOptions.keys(), ((),) * len(indirectOptions), indirectOptions.values()) # Call the configuration callback function for each option. for option in directOptions: info = optionInfo[option] func = info[_OPT_FUNCTION] if func is not None: func() def __setitem__(self, key, value): apply(self.configure, (), {key: value}) #====================================================================== # Methods used to query the megawidget. def component(self, name): # Return a component widget of the megawidget given the # component's name # This allows the user of a megawidget to access and configure # widget components directly. # Find the main component and any subcomponents index = string.find(name, '_') if index < 0: component = name remainingComponents = None else: component = name[:index] remainingComponents = name[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: if remainingComponents is None: remainingComponents = subComponent else: remainingComponents = subComponent + '_' \ + remainingComponents widget = self.__componentInfo[component][0] if remainingComponents is None: return widget else: return widget.component(remainingComponents) def interior(self): return self._hull def hulldestroyed(self): return not _hullToMegaWidget.has_key(self._hull) def __str__(self): return str(self._hull) def cget(self, option): # Get current configuration setting. # Return the value of an option, for example myWidget['font']. if self._optionInfo.has_key(option): return self._optionInfo[option][_OPT_VALUE] else: index = string.find(option, '_') if index >= 0: component = option[:index] componentOption = option[(index + 1):] # Expand component alias if self.__componentAliases.has_key(component): component, subComponent = self.__componentAliases[component] if subComponent is not None: componentOption = subComponent + '_' + componentOption # Expand option string to write on error option = component + '_' + componentOption if self.__componentInfo.has_key(component): # Call cget on the component. componentCget = self.__componentInfo[component][3] return componentCget(componentOption) else: # If this is a group name, call cget for one of # the components in the group. for info in self.__componentInfo.values(): if info[4] == component: componentCget = info[3] return componentCget(componentOption) raise KeyError, 'Unknown option "' + option + \ '" for ' + self.__class__.__name__ __getitem__ = cget def isinitoption(self, option): return self._optionInfo[option][_OPT_FUNCTION] is INITOPT def options(self): options = [] if hasattr(self, '_optionInfo'): for option, info in self._optionInfo.items(): isinit = info[_OPT_FUNCTION] is INITOPT default = info[_OPT_DEFAULT] options.append((option, default, isinit)) options.sort() return options def components(self): # Return a list of all components. # This list includes the 'hull' component and all widget subcomponents names = self.__componentInfo.keys() names.sort() return names def componentaliases(self): # Return a list of all component aliases. componentAliases = self.__componentAliases names = componentAliases.keys() names.sort() rtn = [] for alias in names: (mainComponent, subComponent) = componentAliases[alias] if subComponent is None: rtn.append((alias, mainComponent)) else: rtn.append((alias, mainComponent + '_' + subComponent)) return rtn def componentgroup(self, name): return self.__componentInfo[name][4] #============================================================================= # The grab functions are mainly called by the activate() and # deactivate() methods. # # Use pushgrab() to add a new window to the grab stack. This # releases the grab by the window currently on top of the stack (if # there is one) and gives the grab and focus to the new widget. # # To remove the grab from the window on top of the grab stack, call # popgrab(). # # Use releasegrabs() to release the grab and clear the grab stack. def pushgrab(grabWindow, globalMode, deactivateFunction): prevFocus = grabWindow.tk.call('focus') grabInfo = { 'grabWindow' : grabWindow, 'globalMode' : globalMode, 'previousFocus' : prevFocus, 'deactivateFunction' : deactivateFunction, } _grabStack.append(grabInfo) _grabtop() grabWindow.focus_set() def popgrab(window): # Return the grab to the next window in the grab stack, if any. # If this window is not at the top of the grab stack, then it has # just been deleted by the window manager or deactivated by a # timer. Call the deactivate method for the modal dialog above # this one on the stack. if _grabStack[-1]['grabWindow'] != window: for index in range(len(_grabStack)): if _grabStack[index]['grabWindow'] == window: _grabStack[index + 1]['deactivateFunction']() break grabInfo = _grabStack[-1] del _grabStack[-1] topWidget = grabInfo['grabWindow'] prevFocus = grabInfo['previousFocus'] globalMode = grabInfo['globalMode'] if globalMode != 'nograb': topWidget.grab_release() if len(_grabStack) > 0: _grabtop() if prevFocus != '': try: topWidget.tk.call('focus', prevFocus) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to root window. Tkinter._default_root.focus_set() else: # Make sure that focus does not remain on the released widget. if len(_grabStack) > 0: topWidget = _grabStack[-1]['grabWindow'] topWidget.focus_set() else: Tkinter._default_root.focus_set() def grabstacktopwindow(): if len(_grabStack) == 0: return None else: return _grabStack[-1]['grabWindow'] def releasegrabs(): # Release grab and clear the grab stack. current = Tkinter._default_root.grab_current() if current is not None: current.grab_release() _grabStack[:] = [] def _grabtop(): grabInfo = _grabStack[-1] topWidget = grabInfo['grabWindow'] globalMode = grabInfo['globalMode'] if globalMode == 'nograb': return while 1: try: if globalMode: topWidget.grab_set_global() else: topWidget.grab_set() break except Tkinter.TclError: # Another application has grab. Keep trying until # grab can succeed. topWidget.after(100) #============================================================================= class MegaToplevel(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('activatecommand', None, None), ('deactivatecommand', None, None), ('master', None, None), ('title', None, self._settitle), ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Toplevel) # Initialise instance. # Set WM_DELETE_WINDOW protocol, deleting any old callback, so # memory does not leak. if hasattr(self._hull, '_Pmw_WM_DELETE_name'): self._hull.tk.deletecommand(self._hull._Pmw_WM_DELETE_name) self._hull._Pmw_WM_DELETE_name = \ self.register(self._userDeleteWindow, needcleanup = 0) self.protocol('WM_DELETE_WINDOW', self._hull._Pmw_WM_DELETE_name) # Initialise instance variables. self._firstShowing = 1 # Used by show() to ensure window retains previous position on screen. # The IntVar() variable to wait on during a modal dialog. self._wait = None self._active = 0 self._userDeleteFunc = self.destroy self._userModalDeleteFunc = self.deactivate # Check keywords and initialise options. self.initialiseoptions() def _settitle(self): title = self['title'] if title is not None: self.title(title) def userdeletefunc(self, func=None): if func: self._userDeleteFunc = func else: return self._userDeleteFunc def usermodaldeletefunc(self, func=None): if func: self._userModalDeleteFunc = func else: return self._userModalDeleteFunc def _userDeleteWindow(self): if self.active(): self._userModalDeleteFunc() else: self._userDeleteFunc() def destroy(self): # Allow this to be called more than once. if _hullToMegaWidget.has_key(self._hull): self.deactivate() # Remove circular references, so that object can get cleaned up. del self._userDeleteFunc del self._userModalDeleteFunc MegaArchetype.destroy(self) def show(self, master = None): if self.state() != 'normal': if self._firstShowing: # Just let the window manager determine the window # position for the first time. geom = None else: # Position the window at the same place it was last time. geom = self._sameposition() setgeometryanddeiconify(self, geom) if self._firstShowing: self._firstShowing = 0 else: if self.transient() == '': self.tkraise() # Do this last, otherwise get flashing on NT: if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) self.focus() def _centreonscreen(self): # Centre the window on the screen. (Actually halfway across # and one third down.) parent = self.winfo_parent() if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) # Find size of window. self.update_idletasks() width = self.winfo_width() height = self.winfo_height() if width == 1 and height == 1: # If the window has not yet been displayed, its size is # reported as 1x1, so use requested size. width = self.winfo_reqwidth() height = self.winfo_reqheight() # Place in centre of screen: x = (self.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx() y = (self.winfo_screenheight() - height) / 3 - parent.winfo_vrooty() if x < 0: x = 0 if y < 0: y = 0 return '+%d+%d' % (x, y) def _sameposition(self): # Position the window at the same place it was last time. geometry = self.geometry() index = string.find(geometry, '+') if index >= 0: return geometry[index:] else: return None def activate(self, globalMode = 0, geometry = 'centerscreenfirst'): if self._active: raise ValueError, 'Window is already active' if self.state() == 'normal': self.withdraw() self._active = 1 showbusycursor() if self._wait is None: self._wait = Tkinter.IntVar() self._wait.set(0) if geometry == 'centerscreenalways': geom = self._centreonscreen() elif geometry == 'centerscreenfirst': if self._firstShowing: # Centre the window the first time it is displayed. geom = self._centreonscreen() else: # Position the window at the same place it was last time. geom = self._sameposition() elif geometry[:5] == 'first': if self._firstShowing: geom = geometry[5:] else: # Position the window at the same place it was last time. geom = self._sameposition() else: geom = geometry self._firstShowing = 0 setgeometryanddeiconify(self, geom) # Do this last, otherwise get flashing on NT: master = self['master'] if master is not None: if master == 'parent': parent = self.winfo_parent() # winfo_parent() should return the parent widget, but the # the current version of Tkinter returns a string. if type(parent) == types.StringType: parent = self._hull._nametowidget(parent) master = parent.winfo_toplevel() self.transient(master) pushgrab(self._hull, globalMode, self.deactivate) command = self['activatecommand'] if callable(command): command() self.wait_variable(self._wait) return self._result def deactivate(self, result=None): if not self._active: return self._active = 0 # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._hull) command = self['deactivatecommand'] if callable(command): command() self.withdraw() hidebusycursor(forceFocusRestore = 1) self._result = result self._wait.set(1) def active(self): return self._active forwardmethods(MegaToplevel, Tkinter.Toplevel, '_hull') #============================================================================= class MegaWidget(MegaArchetype): def __init__(self, parent = None, **kw): # Define the options for this megawidget. optiondefs = ( ('hull_class', self.__class__.__name__, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Frame) # Check keywords and initialise options. self.initialiseoptions() forwardmethods(MegaWidget, Tkinter.Frame, '_hull') #============================================================================= # Public functions #----------------- _traceTk = 0 def tracetk(root = None, on = 1, withStackTrace = 0, file=None): global _withStackTrace global _traceTkFile global _traceTk if root is None: root = Tkinter._default_root _withStackTrace = withStackTrace _traceTk = on if on: if hasattr(root.tk, '__class__'): # Tracing already on return if file is None: _traceTkFile = sys.stderr else: _traceTkFile = file tk = _TraceTk(root.tk) else: if not hasattr(root.tk, '__class__'): # Tracing already off return tk = root.tk.getTclInterp() _setTkInterps(root, tk) def showbusycursor(): _addRootToToplevelBusyInfo() root = Tkinter._default_root busyInfo = { 'newBusyWindows' : [], 'previousFocus' : None, 'busyFocus' : None, } _busyStack.append(busyInfo) if _disableKeyboardWhileBusy: # Remember the focus as it is now, before it is changed. busyInfo['previousFocus'] = root.tk.call('focus') if not _havebltbusy(root): # No busy command, so don't call busy hold on any windows. return for (window, winInfo) in _toplevelBusyInfo.items(): if (window.state() != 'withdrawn' and not winInfo['isBusy'] and not winInfo['excludeFromBusy']): busyInfo['newBusyWindows'].append(window) winInfo['isBusy'] = 1 _busy_hold(window, winInfo['busyCursorName']) # Make sure that no events for the busy window get # through to Tkinter, otherwise it will crash in # _nametowidget with a 'KeyError: _Busy' if there is # a binding on the toplevel window. window.tk.call('bindtags', winInfo['busyWindow'], 'Pmw_Dummy_Tag') if _disableKeyboardWhileBusy: # Remember previous focus widget for this toplevel window # and set focus to the busy window, which will ignore all # keyboard events. winInfo['windowFocus'] = \ window.tk.call('focus', '-lastfor', window._w) window.tk.call('focus', winInfo['busyWindow']) busyInfo['busyFocus'] = winInfo['busyWindow'] if len(busyInfo['newBusyWindows']) > 0: if os.name == 'nt': # NT needs an "update" before it will change the cursor. window.update() else: window.update_idletasks() def hidebusycursor(forceFocusRestore = 0): # Remember the focus as it is now, before it is changed. root = Tkinter._default_root if _disableKeyboardWhileBusy: currentFocus = root.tk.call('focus') # Pop the busy info off the stack. busyInfo = _busyStack[-1] del _busyStack[-1] for window in busyInfo['newBusyWindows']: # If this window has not been deleted, release the busy cursor. if _toplevelBusyInfo.has_key(window): winInfo = _toplevelBusyInfo[window] winInfo['isBusy'] = 0 _busy_release(window) if _disableKeyboardWhileBusy: # Restore previous focus window for this toplevel window, # but only if is still set to the busy window (it may have # been changed). windowFocusNow = window.tk.call('focus', '-lastfor', window._w) if windowFocusNow == winInfo['busyWindow']: try: window.tk.call('focus', winInfo['windowFocus']) except Tkinter.TclError: # Previous focus widget has been deleted. Set focus # to toplevel window instead (can't leave focus on # busy window). window.focus_set() if _disableKeyboardWhileBusy: # Restore the focus, depending on whether the focus had changed # between the calls to showbusycursor and hidebusycursor. if forceFocusRestore or busyInfo['busyFocus'] == currentFocus: # The focus had not changed, so restore it to as it was before # the call to showbusycursor, previousFocus = busyInfo['previousFocus'] if previousFocus is not None: try: root.tk.call('focus', previousFocus) except Tkinter.TclError: # Previous focus widget has been deleted; forget it. pass else: # The focus had changed, so restore it to what it had been # changed to before the call to hidebusycursor. root.tk.call('focus', currentFocus) def clearbusycursor(): while len(_busyStack) > 0: hidebusycursor() def setbusycursorattributes(window, **kw): _addRootToToplevelBusyInfo() for name, value in kw.items(): if name == 'exclude': _toplevelBusyInfo[window]['excludeFromBusy'] = value elif name == 'cursorName': _toplevelBusyInfo[window]['busyCursorName'] = value else: raise KeyError, 'Unknown busycursor attribute "' + name + '"' def _addRootToToplevelBusyInfo(): # Include the Tk root window in the list of toplevels. This must # not be called before Tkinter has had a chance to be initialised by # the application. root = Tkinter._default_root if root == None: root = Tkinter.Tk() if not _toplevelBusyInfo.has_key(root): _addToplevelBusyInfo(root) def busycallback(command, updateFunction = None): if not callable(command): raise ValueError, \ 'cannot register non-command busy callback %s %s' % \ (repr(command), type(command)) wrapper = _BusyWrapper(command, updateFunction) return wrapper.callback _errorReportFile = None _errorWindow = None def reporterrorstofile(file = None): global _errorReportFile _errorReportFile = file def displayerror(text): global _errorWindow if _errorReportFile is not None: _errorReportFile.write(text + '\n') else: # Print error on standard error as well as to error window. # Useful if error window fails to be displayed, for example # when exception is triggered in a <Destroy> binding for root # window. sys.stderr.write(text + '\n') if _errorWindow is None: # The error window has not yet been created. _errorWindow = _ErrorWindow() _errorWindow.showerror(text) _root = None _disableKeyboardWhileBusy = 1 def initialise( root = None, size = None, fontScheme = None, useTkOptionDb = 0, noBltBusy = 0, disableKeyboardWhileBusy = None, ): # Remember if show/hidebusycursor should ignore keyboard events. global _disableKeyboardWhileBusy if disableKeyboardWhileBusy is not None: _disableKeyboardWhileBusy = disableKeyboardWhileBusy # Do not use blt busy command if noBltBusy is set. Otherwise, # use blt busy if it is available. global _haveBltBusy if noBltBusy: _haveBltBusy = 0 # Save flag specifying whether the Tk option database should be # queried when setting megawidget option default values. global _useTkOptionDb _useTkOptionDb = useTkOptionDb # If we haven't been given a root window, use the default or # create one. if root is None: if Tkinter._default_root is None: root = Tkinter.Tk() else: root = Tkinter._default_root # If this call is initialising a different Tk interpreter than the # last call, then re-initialise all global variables. Assume the # last interpreter has been destroyed - ie: Pmw does not (yet) # support multiple simultaneous interpreters. global _root if _root is not None and _root != root: global _busyStack global _errorWindow global _grabStack global _hullToMegaWidget global _toplevelBusyInfo _busyStack = [] _errorWindow = None _grabStack = [] _hullToMegaWidget = {} _toplevelBusyInfo = {} _root = root # Trap Tkinter Toplevel constructors so that a list of Toplevels # can be maintained. Tkinter.Toplevel.title = __TkinterToplevelTitle # Trap Tkinter widget destruction so that megawidgets can be # destroyed when their hull widget is destoyed and the list of # Toplevels can be pruned. Tkinter.Toplevel.destroy = __TkinterToplevelDestroy Tkinter.Widget.destroy = __TkinterWidgetDestroy # Modify Tkinter's CallWrapper class to improve the display of # errors which occur in callbacks. Tkinter.CallWrapper = __TkinterCallWrapper # Make sure we get to know when the window manager deletes the # root window. Only do this if the protocol has not yet been set. # This is required if there is a modal dialog displayed and the # window manager deletes the root window. Otherwise the # application will not exit, even though there are no windows. if root.protocol('WM_DELETE_WINDOW') == '': root.protocol('WM_DELETE_WINDOW', root.destroy) # Set the base font size for the application and set the # Tk option database font resources. _font_initialise(root, size, fontScheme) return root def alignlabels(widgets, sticky = None): if len(widgets) == 0: return widgets[0].update_idletasks() # Determine the size of the maximum length label string. maxLabelWidth = 0 for iwid in widgets: labelWidth = iwid.grid_bbox(0, 1)[2] if labelWidth > maxLabelWidth: maxLabelWidth = labelWidth # Adjust the margins for the labels such that the child sites and # labels line up. for iwid in widgets: if sticky is not None: iwid.component('label').grid(sticky=sticky) iwid.grid_columnconfigure(0, minsize = maxLabelWidth) #============================================================================= # Private routines #----------------- _callToTkReturned = 1 _recursionCounter = 1 class _TraceTk: def __init__(self, tclInterp): self.tclInterp = tclInterp def getTclInterp(self): return self.tclInterp # Calling from python into Tk. def call(self, *args, **kw): global _callToTkReturned global _recursionCounter _callToTkReturned = 0 if len(args) == 1 and type(args[0]) == types.TupleType: argStr = str(args[0]) else: argStr = str(args) _traceTkFile.write('CALL TK> %d:%s%s' % (_recursionCounter, ' ' * _recursionCounter, argStr)) _recursionCounter = _recursionCounter + 1 try: result = apply(self.tclInterp.call, args, kw) except Tkinter.TclError, errorString: _callToTkReturned = 1 _recursionCounter = _recursionCounter - 1 _traceTkFile.write('\nTK ERROR> %d:%s-> %s\n' % (_recursionCounter, ' ' * _recursionCounter, repr(errorString))) if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() raise Tkinter.TclError, errorString _recursionCounter = _recursionCounter - 1 if _callToTkReturned: _traceTkFile.write('CALL RTN> %d:%s-> %s' % (_recursionCounter, ' ' * _recursionCounter, repr(result))) else: _callToTkReturned = 1 if result: _traceTkFile.write(' -> %s' % repr(result)) _traceTkFile.write('\n') if _withStackTrace: _traceTkFile.write('CALL TK> stack:\n') traceback.print_stack() _traceTkFile.flush() return result def __getattr__(self, key): return getattr(self.tclInterp, key) def _setTkInterps(window, tk): window.tk = tk for child in window.children.values(): _setTkInterps(child, tk) #============================================================================= # Functions to display a busy cursor. Keep a list of all toplevels # and display the busy cursor over them. The list will contain the Tk # root toplevel window as well as all other toplevel windows. # Also keep a list of the widget which last had focus for each # toplevel. # Map from toplevel windows to # {'isBusy', 'windowFocus', 'busyWindow', # 'excludeFromBusy', 'busyCursorName'} _toplevelBusyInfo = {} # Pmw needs to know all toplevel windows, so that it can call blt busy # on them. This is a hack so we get notified when a Tk topevel is # created. Ideally, the __init__ 'method' should be overridden, but # it is a 'read-only special attribute'. Luckily, title() is always # called from the Tkinter Toplevel constructor. def _addToplevelBusyInfo(window): if window._w == '.': busyWindow = '._Busy' else: busyWindow = window._w + '._Busy' _toplevelBusyInfo[window] = { 'isBusy' : 0, 'windowFocus' : None, 'busyWindow' : busyWindow, 'excludeFromBusy' : 0, 'busyCursorName' : None, } def __TkinterToplevelTitle(self, *args): # If this is being called from the constructor, include this # Toplevel in the list of toplevels and set the initial # WM_DELETE_WINDOW protocol to destroy() so that we get to know # about it. if not _toplevelBusyInfo.has_key(self): _addToplevelBusyInfo(self) self._Pmw_WM_DELETE_name = self.register(self.destroy, None, 0) self.protocol('WM_DELETE_WINDOW', self._Pmw_WM_DELETE_name) return apply(Tkinter.Wm.title, (self,) + args) _haveBltBusy = None def _havebltbusy(window): global _busy_hold, _busy_release, _haveBltBusy if _haveBltBusy is None: import PmwBlt _haveBltBusy = PmwBlt.havebltbusy(window) _busy_hold = PmwBlt.busy_hold if os.name == 'nt': # There is a bug in Blt 2.4i on NT where the busy window # does not follow changes in the children of a window. # Using forget works around the problem. _busy_release = PmwBlt.busy_forget else: _busy_release = PmwBlt.busy_release return _haveBltBusy class _BusyWrapper: def __init__(self, command, updateFunction): self._command = command self._updateFunction = updateFunction def callback(self, *args): showbusycursor() rtn = apply(self._command, args) # Call update before hiding the busy windows to clear any # events that may have occurred over the busy windows. if callable(self._updateFunction): self._updateFunction() hidebusycursor() return rtn #============================================================================= def drawarrow(canvas, color, direction, tag, baseOffset = 0.25, edgeOffset = 0.15): canvas.delete(tag) bw = (string.atoi(canvas['borderwidth']) + string.atoi(canvas['highlightthickness'])) width = string.atoi(canvas['width']) height = string.atoi(canvas['height']) if direction in ('up', 'down'): majorDimension = height minorDimension = width else: majorDimension = width minorDimension = height offset = round(baseOffset * majorDimension) if direction in ('down', 'right'): base = bw + offset apex = bw + majorDimension - offset else: base = bw + majorDimension - offset apex = bw + offset if minorDimension > 3 and minorDimension % 2 == 0: minorDimension = minorDimension - 1 half = int(minorDimension * (1 - 2 * edgeOffset)) / 2 low = round(bw + edgeOffset * minorDimension) middle = low + half high = low + 2 * half if direction in ('up', 'down'): coords = (low, base, high, base, middle, apex) else: coords = (base, low, base, high, apex, middle) kw = {'fill' : color, 'outline' : color, 'tag' : tag} apply(canvas.create_polygon, coords, kw) #============================================================================= # Modify the Tkinter destroy methods so that it notifies us when a Tk # toplevel or frame is destroyed. # A map from the 'hull' component of a megawidget to the megawidget. # This is used to clean up a megawidget when its hull is destroyed. _hullToMegaWidget = {} def __TkinterToplevelDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: # Delete the busy info structure for this toplevel (if the # window was created before initialise() was called, it # will not have any. if _toplevelBusyInfo.has_key(tkWidget): del _toplevelBusyInfo[tkWidget] if hasattr(tkWidget, '_Pmw_WM_DELETE_name'): tkWidget.tk.deletecommand(tkWidget._Pmw_WM_DELETE_name) del tkWidget._Pmw_WM_DELETE_name Tkinter.BaseWidget.destroy(tkWidget) def __TkinterWidgetDestroy(tkWidget): if _hullToMegaWidget.has_key(tkWidget): mega = _hullToMegaWidget[tkWidget] try: mega.destroy() except: _reporterror(mega.destroy, ()) else: Tkinter.BaseWidget.destroy(tkWidget) #============================================================================= # Add code to Tkinter to improve the display of errors which occur in # callbacks. class __TkinterCallWrapper: def __init__(self, func, subst, widget): self.func = func self.subst = subst self.widget = widget # Calling back from Tk into python. def __call__(self, *args): try: if self.subst: args = apply(self.subst, args) if _traceTk: if not _callToTkReturned: _traceTkFile.write('\n') if hasattr(self.func, 'im_class'): name = self.func.im_class.__name__ + '.' + \ self.func.__name__ else: name = self.func.__name__ if len(args) == 1 and hasattr(args[0], 'type'): # The argument to the callback is an event. eventName = _eventTypeToName[string.atoi(args[0].type)] if eventName in ('KeyPress', 'KeyRelease',): argStr = '(%s %s Event: %s)' % \ (eventName, args[0].keysym, args[0].widget) else: argStr = '(%s Event, %s)' % (eventName, args[0].widget) else: argStr = str(args) _traceTkFile.write('CALLBACK> %d:%s%s%s\n' % (_recursionCounter, ' ' * _recursionCounter, name, argStr)) _traceTkFile.flush() return apply(self.func, args) except SystemExit, msg: raise SystemExit, msg except: _reporterror(self.func, args) _eventTypeToName = { 2 : 'KeyPress', 15 : 'VisibilityNotify', 28 : 'PropertyNotify', 3 : 'KeyRelease', 16 : 'CreateNotify', 29 : 'SelectionClear', 4 : 'ButtonPress', 17 : 'DestroyNotify', 30 : 'SelectionRequest', 5 : 'ButtonRelease', 18 : 'UnmapNotify', 31 : 'SelectionNotify', 6 : 'MotionNotify', 19 : 'MapNotify', 32 : 'ColormapNotify', 7 : 'EnterNotify', 20 : 'MapRequest', 33 : 'ClientMessage', 8 : 'LeaveNotify', 21 : 'ReparentNotify', 34 : 'MappingNotify', 9 : 'FocusIn', 22 : 'ConfigureNotify', 35 : 'VirtualEvents', 10 : 'FocusOut', 23 : 'ConfigureRequest', 36 : 'ActivateNotify', 11 : 'KeymapNotify', 24 : 'GravityNotify', 37 : 'DeactivateNotify', 12 : 'Expose', 25 : 'ResizeRequest', 38 : 'MouseWheelEvent', 13 : 'GraphicsExpose', 26 : 'CirculateNotify', 14 : 'NoExpose', 27 : 'CirculateRequest', } def _reporterror(func, args): # Fetch current exception values. exc_type, exc_value, exc_traceback = sys.exc_info() # Give basic information about the callback exception. if type(exc_type) == types.ClassType: # Handle python 1.5 class exceptions. exc_type = exc_type.__name__ msg = str(exc_type) + ' Exception in Tk callback\n' msg = msg + ' Function: %s (type: %s)\n' % (repr(func), type(func)) msg = msg + ' Args: %s\n' % str(args) if type(args) == types.TupleType and len(args) > 0 and \ hasattr(args[0], 'type'): eventArg = 1 else: eventArg = 0 # If the argument to the callback is an event, add the event type. if eventArg: eventNum = string.atoi(args[0].type) if eventNum in _eventTypeToName.keys(): msg = msg + ' Event type: %s (type num: %d)\n' % \ (_eventTypeToName[eventNum], eventNum) else: msg = msg + ' Unknown event type (type num: %d)\n' % eventNum # Add the traceback. msg = msg + 'Traceback (innermost last):\n' for tr in traceback.extract_tb(exc_traceback): msg = msg + ' File "%s", line %s, in %s\n' % (tr[0], tr[1], tr[2]) msg = msg + ' %s\n' % tr[3] msg = msg + '%s: %s\n' % (exc_type, exc_value) # If the argument to the callback is an event, add the event contents. if eventArg: msg = msg + '\n================================================\n' msg = msg + ' Event contents:\n' keys = args[0].__dict__.keys() keys.sort() for key in keys: msg = msg + ' %s: %s\n' % (key, args[0].__dict__[key]) clearbusycursor() try: displayerror(msg) except: pass class _ErrorWindow: def __init__(self): self._errorQueue = [] self._errorCount = 0 self._open = 0 self._firstShowing = 1 # Create the toplevel window self._top = Tkinter.Toplevel() self._top.protocol('WM_DELETE_WINDOW', self._hide) self._top.title('Error in background function') self._top.iconname('Background error') # Create the text widget and scrollbar in a frame upperframe = Tkinter.Frame(self._top) scrollbar = Tkinter.Scrollbar(upperframe, orient='vertical') scrollbar.pack(side = 'right', fill = 'y') self._text = Tkinter.Text(upperframe, yscrollcommand=scrollbar.set) self._text.pack(fill = 'both', expand = 1) scrollbar.configure(command=self._text.yview) # Create the buttons and label in a frame lowerframe = Tkinter.Frame(self._top) ignore = Tkinter.Button(lowerframe, text = 'Ignore remaining errors', command = self._hide) ignore.pack(side='left') self._nextError = Tkinter.Button(lowerframe, text = 'Show next error', command = self._next) self._nextError.pack(side='left') self._label = Tkinter.Label(lowerframe, relief='ridge') self._label.pack(side='left', fill='x', expand=1) # Pack the lower frame first so that it does not disappear # when the window is resized. lowerframe.pack(side = 'bottom', fill = 'x') upperframe.pack(side = 'bottom', fill = 'both', expand = 1) def showerror(self, text): if self._open: self._errorQueue.append(text) else: self._display(text) self._open = 1 # Display the error window in the same place it was before. if self._top.state() == 'normal': # If update_idletasks is not called here, the window may # be placed partially off the screen. Also, if it is not # called and many errors are generated quickly in # succession, the error window may not display errors # until the last one is generated and the interpreter # becomes idle. # XXX: remove this, since it causes omppython to go into an # infinite loop if an error occurs in an omp callback. # self._top.update_idletasks() pass else: if self._firstShowing: geom = None else: geometry = self._top.geometry() index = string.find(geometry, '+') if index >= 0: geom = geometry[index:] else: geom = None setgeometryanddeiconify(self._top, geom) if self._firstShowing: self._firstShowing = 0 else: self._top.tkraise() self._top.focus() self._updateButtons() # Release any grab, so that buttons in the error window work. releasegrabs() def _hide(self): self._errorCount = self._errorCount + len(self._errorQueue) self._errorQueue = [] self._top.withdraw() self._open = 0 def _next(self): # Display the next error in the queue. text = self._errorQueue[0] del self._errorQueue[0] self._display(text) self._updateButtons() def _display(self, text): self._errorCount = self._errorCount + 1 text = 'Error: %d\n%s' % (self._errorCount, text) self._text.delete('1.0', 'end') self._text.insert('end', text) def _updateButtons(self): numQueued = len(self._errorQueue) if numQueued > 0: self._label.configure(text='%d more errors' % numQueued) self._nextError.configure(state='normal') else: self._label.configure(text='No more errors') self._nextError.configure(state='disabled') ###################################################################### ### File: PmwDialog.py # Based on iwidgets2.2.0/dialog.itk and iwidgets2.2.0/dialogshell.itk code. # Convention: # Each dialog window should have one of these as the rightmost button: # Close Close a window which only displays information. # Cancel Close a window which may be used to change the state of # the application. import sys import types import Tkinter # A Toplevel with a ButtonBox and child site. class Dialog(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttonbox_hull_borderwidth', 1, None), ('buttonbox_hull_relief', 'raised', None), ('buttonboxpos', 's', INITOPT), ('buttons', ('OK',), self._buttons), ('command', None, None), ('dialogchildsite_borderwidth', 1, None), ('dialogchildsite_relief', 'raised', None), ('defaultbutton', None, self._defaultButton), ('master', 'parent', None), ('separatorwidth', 0, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) # Create the components. oldInterior = MegaToplevel.interior(self) # Set up pack options according to the position of the button box. pos = self['buttonboxpos'] if pos not in 'nsew': raise ValueError, \ 'bad buttonboxpos option "%s": should be n, s, e, or w' \ % pos if pos in 'ns': orient = 'horizontal' fill = 'x' if pos == 'n': side = 'top' else: side = 'bottom' else: orient = 'vertical' fill = 'y' if pos == 'w': side = 'left' else: side = 'right' # Create the button box. self._buttonBox = self.createcomponent('buttonbox', (), None, ButtonBox, (oldInterior,), orient = orient) self._buttonBox.pack(side = side, fill = fill) # Create the separating line. width = self['separatorwidth'] if width > 0: self._separator = self.createcomponent('separator', (), None, Tkinter.Frame, (oldInterior,), relief = 'sunken', height = width, width = width, borderwidth = width / 2) self._separator.pack(side = side, fill = fill) # Create the child site. self.__dialogChildSite = self.createcomponent('dialogchildsite', (), None, Tkinter.Frame, (oldInterior,)) self.__dialogChildSite.pack(side=side, fill='both', expand=1) self.oldButtons = () self.oldDefault = None self.bind('<Return>', self._invokeDefault) self.userdeletefunc(self._doCommand) self.usermodaldeletefunc(self._doCommand) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self.__dialogChildSite def invoke(self, index = DEFAULT): return self._buttonBox.invoke(index) def _invokeDefault(self, event): try: self._buttonBox.index(DEFAULT) except ValueError: return self._buttonBox.invoke() def _doCommand(self, name = None): if name is not None and self.active() and \ grabstacktopwindow() != self.component('hull'): # This is a modal dialog but is not on the top of the grab # stack (ie: should not have the grab), so ignore this # event. This seems to be a bug in Tk and may occur in # nested modal dialogs. # # An example is the PromptDialog demonstration. To # trigger the problem, start the demo, then move the mouse # to the main window, hit <TAB> and then <TAB> again. The # highlight border of the "Show prompt dialog" button # should now be displayed. Now hit <SPACE>, <RETURN>, # <RETURN> rapidly several times. Eventually, hitting the # return key invokes the password dialog "OK" button even # though the confirm dialog is active (and therefore # should have the keyboard focus). Observed under Solaris # 2.5.1, python 1.5.2 and Tk8.0. # TODO: Give focus to the window on top of the grabstack. return command = self['command'] if callable(command): return command(name) else: if self.active(): self.deactivate(name) else: self.withdraw() def _buttons(self): buttons = self['buttons'] if type(buttons) != types.TupleType and type(buttons) != types.ListType: raise ValueError, \ 'bad buttons option "%s": should be a tuple' % str(buttons) if self.oldButtons == buttons: return self.oldButtons = buttons for index in range(self._buttonBox.numbuttons()): self._buttonBox.delete(0) for name in buttons: self._buttonBox.add(name, command=lambda self=self, name=name: self._doCommand(name)) if len(buttons) > 0: defaultbutton = self['defaultbutton'] if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) self._buttonBox.alignbuttons() def _defaultButton(self): defaultbutton = self['defaultbutton'] if self.oldDefault == defaultbutton: return self.oldDefault = defaultbutton if len(self['buttons']) > 0: if defaultbutton is None: self._buttonBox.setdefault(None) else: try: self._buttonBox.index(defaultbutton) except ValueError: pass else: self._buttonBox.setdefault(defaultbutton) ###################################################################### ### File: PmwTimeFuncs.py # Functions for dealing with dates and times. import re import string def timestringtoseconds(text, separator = ':'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text sign = 1 if len(inputList[0]) > 0 and inputList[0][0] in ('+', '-'): if inputList[0][0] == '-': sign = -1 inputList[0] = inputList[0][1:] if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text hour = string.atoi(inputList[0]) minute = string.atoi(inputList[1]) second = string.atoi(inputList[2]) if minute >= 60 or second >= 60: raise ValueError, 'invalid value: ' + text return sign * (hour * 60 * 60 + minute * 60 + second) _year_pivot = 50 _century = 2000 def setyearpivot(pivot, century = None): global _year_pivot global _century oldvalues = (_year_pivot, _century) _year_pivot = pivot if century is not None: _century = century return oldvalues def datestringtojdn(text, format = 'ymd', separator = '/'): inputList = string.split(string.strip(text), separator) if len(inputList) != 3: raise ValueError, 'invalid value: ' + text if re.search('[^0-9]', string.join(inputList, '')) is not None: raise ValueError, 'invalid value: ' + text formatList = list(format) day = string.atoi(inputList[formatList.index('d')]) month = string.atoi(inputList[formatList.index('m')]) year = string.atoi(inputList[formatList.index('y')]) if _year_pivot is not None: if year >= 0 and year < 100: if year <= _year_pivot: year = year + _century else: year = year + _century - 100 jdn = ymdtojdn(year, month, day) if jdntoymd(jdn) != (year, month, day): raise ValueError, 'invalid value: ' + text return jdn def _cdiv(a, b): # Return a / b as calculated by most C language implementations, # assuming both a and b are integers. if a * b > 0: return a / b else: return -(abs(a) / abs(b)) def ymdtojdn(year, month, day, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianDate = 15821004L # last day to use Julian calendar else: # British-American usage lastJulianDate = 17520902L # last day to use Julian calendar julian = ((year * 100L) + month) * 100 + day <= lastJulianDate if year < 0: # Adjust BC year year = year + 1 if julian: return 367L * year - _cdiv(7 * (year + 5001L + _cdiv((month - 9), 7)), 4) + \ _cdiv(275 * month, 9) + day + 1729777L else: return (day - 32076L) + \ _cdiv(1461L * (year + 4800L + _cdiv((month - 14), 12)), 4) + \ _cdiv(367 * (month - 2 - _cdiv((month - 14), 12) * 12), 12) - \ _cdiv((3 * _cdiv((year + 4900L + _cdiv((month - 14), 12)), 100)), 4) + \ 1 # correction by rdg def jdntoymd(jdn, julian = -1, papal = 1): # set Julian flag if auto set if julian < 0: if papal: # Pope Gregory XIII's decree lastJulianJdn = 2299160L # last jdn to use Julian calendar else: # British-American usage lastJulianJdn = 2361221L # last jdn to use Julian calendar julian = (jdn <= lastJulianJdn); x = jdn + 68569L if julian: x = x + 38 daysPer400Years = 146100L fudgedDaysPer4000Years = 1461000L + 1 else: daysPer400Years = 146097L fudgedDaysPer4000Years = 1460970L + 31 z = _cdiv(4 * x, daysPer400Years) x = x - _cdiv((daysPer400Years * z + 3), 4) y = _cdiv(4000 * (x + 1), fudgedDaysPer4000Years) x = x - _cdiv(1461 * y, 4) + 31 m = _cdiv(80 * x, 2447) d = x - _cdiv(2447 * m, 80) x = _cdiv(m, 11) m = m + 2 - 12 * x y = 100 * (z - 49) + y + x # Convert from longs to integers. yy = int(y) mm = int(m) dd = int(d) if yy <= 0: # Adjust BC years. yy = yy - 1 return (yy, mm, dd) def stringtoreal(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: raise ValueError, 'invalid value: ' + text index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] return string.atof(text) ###################################################################### ### File: PmwBalloon.py import os import string import Tkinter class Balloon(MegaToplevel): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('initwait', 500, None), # milliseconds ('label_background', 'lightyellow', None), ('label_foreground', 'black', None), ('label_justify', 'left', None), ('master', 'parent', None), ('relmouse', 'none', self._relmouse), ('state', 'both', self._state), ('statuscommand', None, None), ('xoffset', 20, None), # pixels ('yoffset', 1, None), # pixels ('hull_highlightthickness', 1, None), ('hull_highlightbackground', 'black', None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaToplevel.__init__(self, parent) self.withdraw() self.overrideredirect(1) # Create the components. interior = self.interior() self._label = self.createcomponent('label', (), None, Tkinter.Label, (interior,)) self._label.pack() # The default hull configuration options give a black border # around the balloon, but avoids a black 'flash' when the # balloon is deiconified, before the text appears. if not kw.has_key('hull_background'): self.configure(hull_background = \ str(self._label.cget('background'))) # Initialise instance variables. self._timer = None # The widget or item that is currently triggering the balloon. # It is None if the balloon is not being displayed. It is a # one-tuple if the balloon is being displayed in response to a # widget binding (value is the widget). It is a two-tuple if # the balloon is being displayed in response to a canvas or # text item binding (value is the widget and the item). self._currentTrigger = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timer is not None: self.after_cancel(self._timer) self._timer = None MegaToplevel.destroy(self) def bind(self, widget, balloonHelp, statusHelp = None): # If a previous bind for this widget exists, remove it. self.unbind(widget) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.bind('<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 0)) # Set Motion binding so that if the pointer remains at rest # within the widget until the status line removes the help and # then the pointer moves again, then redisplay the help in the # status line. # Note: The Motion binding only works for basic widgets, and # the hull of megawidgets but not for other megawidget components. motionId = widget.bind('<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.bind('<Leave>', self._leave) buttonId = widget.bind('<ButtonPress>', self._buttonpress) # Set Destroy binding so that the balloon can be withdrawn and # the timer can be cancelled if the widget is destroyed. destroyId = widget.bind('<Destroy>', self._destroy) # Use the None item in the widget's private Pmw dictionary to # store the widget's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[None] = \ (enterId, motionId, leaveId, buttonId, destroyId) def unbind(self, widget): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(None): (enterId, motionId, leaveId, buttonId, destroyId) = \ widget._Pmw_BalloonBindIds[None] # Need to pass in old bindings, so that Tkinter can # delete the commands. Otherwise, memory is leaked. widget.unbind('<Enter>', enterId) widget.unbind('<Motion>', motionId) widget.unbind('<Leave>', leaveId) widget.unbind('<ButtonPress>', buttonId) widget.unbind('<Destroy>', destroyId) del widget._Pmw_BalloonBindIds[None] if self._currentTrigger is not None and len(self._currentTrigger) == 1: # The balloon is currently being displayed and the current # trigger is a widget. triggerWidget = self._currentTrigger[0] if triggerWidget == widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def tagbind(self, widget, tagOrItem, balloonHelp, statusHelp = None): # If a previous bind for this widget's tagOrItem exists, remove it. self.tagunbind(widget, tagOrItem) if balloonHelp is None and statusHelp is None: return if statusHelp is None: statusHelp = balloonHelp enterId = widget.tag_bind(tagOrItem, '<Enter>', lambda event, self = self, w = widget, sHelp = statusHelp, bHelp = balloonHelp: self._enter(event, w, sHelp, bHelp, 1)) motionId = widget.tag_bind(tagOrItem, '<Motion>', lambda event = None, self = self, statusHelp = statusHelp: self.showstatus(statusHelp)) leaveId = widget.tag_bind(tagOrItem, '<Leave>', self._leave) buttonId = widget.tag_bind(tagOrItem, '<ButtonPress>', self._buttonpress) # Use the tagOrItem item in the widget's private Pmw dictionary to # store the tagOrItem's bind callbacks, for later clean up. if not hasattr(widget, '_Pmw_BalloonBindIds'): widget._Pmw_BalloonBindIds = {} widget._Pmw_BalloonBindIds[tagOrItem] = \ (enterId, motionId, leaveId, buttonId) def tagunbind(self, widget, tagOrItem): if hasattr(widget, '_Pmw_BalloonBindIds'): if widget._Pmw_BalloonBindIds.has_key(tagOrItem): (enterId, motionId, leaveId, buttonId) = \ widget._Pmw_BalloonBindIds[tagOrItem] widget.tag_unbind(tagOrItem, '<Enter>', enterId) widget.tag_unbind(tagOrItem, '<Motion>', motionId) widget.tag_unbind(tagOrItem, '<Leave>', leaveId) widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId) del widget._Pmw_BalloonBindIds[tagOrItem] if self._currentTrigger is None: # The balloon is not currently being displayed. return if len(self._currentTrigger) == 1: # The current trigger is a widget. return if len(self._currentTrigger) == 2: # The current trigger is a canvas item. (triggerWidget, triggerItem) = self._currentTrigger if triggerWidget == widget and triggerItem == tagOrItem: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None else: # The current trigger is a text item. (triggerWidget, x, y) = self._currentTrigger if triggerWidget == widget: currentPos = widget.index('@%d,%d' % (x, y)) currentTags = widget.tag_names(currentPos) if tagOrItem in currentTags: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def showstatus(self, statusHelp): if self['state'] in ('status', 'both'): cmd = self['statuscommand'] if callable(cmd): cmd(statusHelp) def clearstatus(self): self.showstatus(None) def _state(self): if self['state'] not in ('both', 'balloon', 'status', 'none'): raise ValueError, 'bad state option ' + repr(self['state']) + \ ': should be one of \'both\', \'balloon\', ' + \ '\'status\' or \'none\'' def _relmouse(self): if self['relmouse'] not in ('both', 'x', 'y', 'none'): raise ValueError, 'bad relmouse option ' + repr(self['relmouse'])+ \ ': should be one of \'both\', \'x\', ' + '\'y\' or \'none\'' def _enter(self, event, widget, statusHelp, balloonHelp, isItem): # Do not display balloon if mouse button is pressed. This # will only occur if the button was pressed inside a widget, # then the mouse moved out of and then back into the widget, # with the button still held down. The number 0x1f00 is the # button mask for the 5 possible buttons in X. buttonPressed = (event.state & 0x1f00) != 0 if not buttonPressed and balloonHelp is not None and \ self['state'] in ('balloon', 'both'): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self._timer = self.after(self['initwait'], lambda self = self, widget = widget, help = balloonHelp, isItem = isItem: self._showBalloon(widget, help, isItem)) if isItem: if hasattr(widget, 'canvasx'): # The widget is a canvas. item = widget.find_withtag('current') if len(item) > 0: item = item[0] else: item = None self._currentTrigger = (widget, item) else: # The widget is a text widget. self._currentTrigger = (widget, event.x, event.y) else: self._currentTrigger = (widget,) self.showstatus(statusHelp) def _leave(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _destroy(self, event): # Only withdraw the balloon and cancel the timer if the widget # being destroyed is the widget that triggered the balloon. # Note that in a Tkinter Destroy event, the widget field is a # string and not a widget as usual. if self._currentTrigger is None: # The balloon is not currently being displayed return if len(self._currentTrigger) == 1: # The current trigger is a widget (not an item) triggerWidget = self._currentTrigger[0] if str(triggerWidget) == event.widget: if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self.clearstatus() self._currentTrigger = None def _buttonpress(self, event): if self._timer is not None: self.after_cancel(self._timer) self._timer = None self.withdraw() self._currentTrigger = None def _showBalloon(self, widget, balloonHelp, isItem): self._label.configure(text = balloonHelp) # First, display the balloon offscreen to get dimensions. screenWidth = self.winfo_screenwidth() screenHeight = self.winfo_screenheight() self.geometry('+%d+0' % (screenWidth + 1)) self.update_idletasks() if isItem: # Get the bounding box of the current item. bbox = widget.bbox('current') if bbox is None: # The item that triggered the balloon has disappeared, # perhaps by a user's timer event that occured between # the <Enter> event and the 'initwait' timer calling # this method. return # The widget is either a text or canvas. The meaning of # the values returned by the bbox method is different for # each, so use the existence of the 'canvasx' method to # distinguish between them. if hasattr(widget, 'canvasx'): # The widget is a canvas. Place balloon under canvas # item. The positions returned by bbox are relative # to the entire canvas, not just the visible part, so # need to convert to window coordinates. leftrel = bbox[0] - widget.canvasx(0) toprel = bbox[1] - widget.canvasy(0) bottomrel = bbox[3] - widget.canvasy(0) else: # The widget is a text widget. Place balloon under # the character closest to the mouse. The positions # returned by bbox are relative to the text widget # window (ie the visible part of the text only). leftrel = bbox[0] toprel = bbox[1] bottomrel = bbox[1] + bbox[3] else: leftrel = 0 toprel = 0 bottomrel = widget.winfo_height() xpointer, ypointer = widget.winfo_pointerxy() # -1 if off screen if xpointer >= 0 and self['relmouse'] in ('both', 'x'): x = xpointer else: x = leftrel + widget.winfo_rootx() x = x + self['xoffset'] if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = bottomrel + widget.winfo_rooty() y = y + self['yoffset'] edges = (string.atoi(str(self.cget('hull_highlightthickness'))) + string.atoi(str(self.cget('hull_borderwidth')))) * 2 if x + self._label.winfo_reqwidth() + edges > screenWidth: x = screenWidth - self._label.winfo_reqwidth() - edges if y + self._label.winfo_reqheight() + edges > screenHeight: if ypointer >= 0 and self['relmouse'] in ('both', 'y'): y = ypointer else: y = toprel + widget.winfo_rooty() y = y - self._label.winfo_reqheight() - self['yoffset'] - edges setgeometryanddeiconify(self, '+%d+%d' % (x, y)) ###################################################################### ### File: PmwButtonBox.py # Based on iwidgets2.2.0/buttonbox.itk code. import types import Tkinter class ButtonBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 3, INITOPT), ('pady', 3, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._buttonBoxFrame = self._hull columnOrRow = 0 else: self._buttonBoxFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._buttonBoxFrame.grid(column=2, row=2, sticky='nsew') columnOrRow = 2 self.createlabel(interior) orient = self['orient'] if orient == 'horizontal': interior.grid_columnconfigure(columnOrRow, weight = 1) elif orient == 'vertical': interior.grid_rowconfigure(columnOrRow, weight = 1) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' # Initialise instance variables. # List of tuples describing the buttons: # - name # - button widget self._buttonList = [] # The index of the default button. self._defaultButton = None self._timerId = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self._timerId: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def numbuttons(self): return len(self._buttonList) def index(self, index, forInsert = 0): listLength = len(self._buttonList) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'ButtonBox has no buttons' elif index is DEFAULT: if self._defaultButton is not None: return self._defaultButton raise ValueError, 'ButtonBox has no default' else: names = map(lambda t: t[0], self._buttonList) if index in names: return names.index(index) validValues = 'a name, a number, END or DEFAULT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def insert(self, componentName, beforeComponent = 0, **kw): if componentName in self.components(): raise ValueError, 'button "%s" already exists' % componentName if not kw.has_key('text'): kw['text'] = componentName kw['default'] = 'normal' button = apply(self.createcomponent, (componentName, (), 'Button', Tkinter.Button, (self._buttonBoxFrame,)), kw) index = self.index(beforeComponent, 1) horizontal = self['orient'] == 'horizontal' numButtons = len(self._buttonList) # Shift buttons up one position. for i in range(numButtons - 1, index - 1, -1): widget = self._buttonList[i][1] pos = i * 2 + 3 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) # Display the new button. if horizontal: button.grid(column = index * 2 + 1, row = 0, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_columnconfigure( numButtons * 2 + 2, weight = 1) else: button.grid(column = 0, row = index * 2 + 1, sticky = 'ew', padx = self['padx'], pady = self['pady']) self._buttonBoxFrame.grid_rowconfigure( numButtons * 2 + 2, weight = 1) self._buttonList.insert(index, (componentName, button)) return button def add(self, componentName, **kw): return apply(self.insert, (componentName, len(self._buttonList)), kw) def delete(self, index): index = self.index(index) (name, widget) = self._buttonList[index] widget.grid_forget() self.destroycomponent(name) numButtons = len(self._buttonList) # Shift buttons down one position. horizontal = self['orient'] == 'horizontal' for i in range(index + 1, numButtons): widget = self._buttonList[i][1] pos = i * 2 - 1 if horizontal: widget.grid(column = pos, row = 0) else: widget.grid(column = 0, row = pos) if horizontal: self._buttonBoxFrame.grid_columnconfigure(numButtons * 2 - 1, minsize = 0) self._buttonBoxFrame.grid_columnconfigure(numButtons * 2, weight = 0) else: self._buttonBoxFrame.grid_rowconfigure(numButtons * 2, weight = 0) del self._buttonList[index] def setdefault(self, index): # Turn off the default ring around the current default button. if self._defaultButton is not None: button = self._buttonList[self._defaultButton][1] button.configure(default = 'normal') self._defaultButton = None # Turn on the default ring around the new default button. if index is not None: index = self.index(index) self._defaultButton = index button = self._buttonList[index][1] button.configure(default = 'active') def invoke(self, index = DEFAULT, noFlash = 0): # Invoke the callback associated with the *index* button. If # *noFlash* is not set, flash the button to indicate to the # user that something happened. button = self._buttonList[self.index(index)][1] if not noFlash: state = button.cget('state') relief = button.cget('relief') button.configure(state = 'active', relief = 'sunken') self.update_idletasks() self.after(100) button.configure(state = state, relief = relief) return button.invoke() def button(self, buttonIndex): return self._buttonList[self.index(buttonIndex)][1] def alignbuttons(self, when = 'later'): if when == 'later': if not self._timerId: self._timerId = self.after_idle(self.alignbuttons, 'now') return self.update_idletasks() self._timerId = None # Determine the width of the maximum length button. max = 0 horizontal = (self['orient'] == 'horizontal') for index in range(len(self._buttonList)): gridIndex = index * 2 + 1 if horizontal: width = self._buttonBoxFrame.grid_bbox(gridIndex, 0)[2] else: width = self._buttonBoxFrame.grid_bbox(0, gridIndex)[2] if width > max: max = width # Set the width of all the buttons to be the same. if horizontal: for index in range(len(self._buttonList)): self._buttonBoxFrame.grid_columnconfigure(index * 2 + 1, minsize = max) else: self._buttonBoxFrame.grid_columnconfigure(0, minsize = max) ###################################################################### ### File: PmwEntryField.py # Based on iwidgets2.2.0/entryfield.itk code. import re import string import types import Tkinter # Possible return values of validation functions. OK = 1 ERROR = 0 PARTIAL = -1 class EntryField(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('errorbackground', 'pink', None), ('invalidcommand', self.bell, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('modifiedcommand', None, None), ('sticky', 'ew', INITOPT), ('validate', None, self._validate), ('extravalidators', {}, None), ('value', '', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) self._entryFieldEntry.grid(column=2, row=2, sticky=self['sticky']) if self['value'] != '': self.__setEntry(self['value']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self.normalBackground = None self._previousText = None # Initialise instance. _registerEntryField(self._entryFieldEntry, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. if EntryField._classBindingsDefinedFor != Tkinter._default_root: tagList = self._entryFieldEntry.bindtags() root = Tkinter._default_root allSequences = {} for tag in tagList: sequences = root.bind_class(tag) if type(sequences) is types.StringType: # In old versions of Tkinter, bind_class returns a string sequences = root.tk.splitlist(sequences) for sequence in sequences: allSequences[sequence] = None for sequence in allSequences.keys(): root.bind_class('EntryFieldPre', sequence, _preProcess) root.bind_class('EntryFieldPost', sequence, _postProcess) EntryField._classBindingsDefinedFor = root self._entryFieldEntry.bindtags(('EntryFieldPre',) + self._entryFieldEntry.bindtags() + ('EntryFieldPost',)) self._entryFieldEntry.bind('<Return>', self._executeCommand) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): _deregisterEntryField(self._entryFieldEntry) MegaWidget.destroy(self) def _getValidatorFunc(self, validator, index): # Search the extra and standard validator lists for the # given 'validator'. If 'validator' is an alias, then # continue the search using the alias. Make sure that # self-referencial aliases do not cause infinite loops. extraValidators = self['extravalidators'] traversedValidators = [] while 1: traversedValidators.append(validator) if extraValidators.has_key(validator): validator = extraValidators[validator][index] elif _standardValidators.has_key(validator): validator = _standardValidators[validator][index] else: return validator if validator in traversedValidators: return validator def _validate(self): dict = { 'validator' : None, 'min' : None, 'max' : None, 'minstrict' : 1, 'maxstrict' : 1, } opt = self['validate'] if type(opt) is types.DictionaryType: dict.update(opt) else: dict['validator'] = opt # Look up validator maps and replace 'validator' field with # the corresponding function. validator = dict['validator'] valFunction = self._getValidatorFunc(validator, 0) self._checkValidateFunction(valFunction, 'validate', validator) dict['validator'] = valFunction # Look up validator maps and replace 'stringtovalue' field # with the corresponding function. if dict.has_key('stringtovalue'): stringtovalue = dict['stringtovalue'] strFunction = self._getValidatorFunc(stringtovalue, 1) self._checkValidateFunction( strFunction, 'stringtovalue', stringtovalue) else: strFunction = self._getValidatorFunc(validator, 1) if strFunction == validator: strFunction = len dict['stringtovalue'] = strFunction self._validationInfo = dict args = dict.copy() del args['validator'] del args['min'] del args['max'] del args['minstrict'] del args['maxstrict'] del args['stringtovalue'] self._validationArgs = args self._previousText = None if type(dict['min']) == types.StringType and strFunction is not None: dict['min'] = apply(strFunction, (dict['min'],), args) if type(dict['max']) == types.StringType and strFunction is not None: dict['max'] = apply(strFunction, (dict['max'],), args) self._checkValidity() def _checkValidateFunction(self, function, option, validator): # Raise an error if 'function' is not a function or None. if function is not None and not callable(function): extraValidators = self['extravalidators'] extra = extraValidators.keys() extra.sort() extra = tuple(extra) standard = _standardValidators.keys() standard.sort() standard = tuple(standard) msg = 'bad %s value "%s": must be a function or one of ' \ 'the standard validators %s or extra validators %s' raise ValueError, msg % (option, validator, standard, extra) def _executeCommand(self, event = None): cmd = self['command'] if callable(cmd): if event is None: # Return result of command for invoke() method. return cmd() else: cmd() def _preProcess(self): self._previousText = self._entryFieldEntry.get() self._previousICursor = self._entryFieldEntry.index('insert') self._previousXview = self._entryFieldEntry.index('@0') if self._entryFieldEntry.selection_present(): self._previousSel= (self._entryFieldEntry.index('sel.first'), self._entryFieldEntry.index('sel.last')) else: self._previousSel = None def _postProcess(self): # No need to check if text has not changed. previousText = self._previousText if previousText == self._entryFieldEntry.get(): return self.valid() valid = self._checkValidity() if self.hulldestroyed(): # The invalidcommand called by _checkValidity() destroyed us. return valid cmd = self['modifiedcommand'] if callable(cmd) and previousText != self._entryFieldEntry.get(): cmd() return valid def checkentry(self): # If there is a variable specified by the entry_textvariable # option, checkentry() should be called after the set() method # of the variable is called. self._previousText = None return self._postProcess() def _getValidity(self): text = self._entryFieldEntry.get() dict = self._validationInfo args = self._validationArgs if dict['validator'] is not None: status = apply(dict['validator'], (text,), args) if status != OK: return status # Check for out of (min, max) range. if dict['stringtovalue'] is not None: min = dict['min'] max = dict['max'] if min is None and max is None: return OK val = apply(dict['stringtovalue'], (text,), args) if min is not None and val < min: if dict['minstrict']: return ERROR else: return PARTIAL if max is not None and val > max: if dict['maxstrict']: return ERROR else: return PARTIAL return OK def _checkValidity(self): valid = self._getValidity() oldValidity = valid if valid == ERROR: # The entry is invalid. cmd = self['invalidcommand'] if callable(cmd): cmd() if self.hulldestroyed(): # The invalidcommand destroyed us. return oldValidity # Restore the entry to its previous value. if self._previousText is not None: self.__setEntry(self._previousText) self._entryFieldEntry.icursor(self._previousICursor) self._entryFieldEntry.xview(self._previousXview) if self._previousSel is not None: self._entryFieldEntry.selection_range(self._previousSel[0], self._previousSel[1]) # Check if the saved text is valid as well. valid = self._getValidity() self._valid = valid if self.hulldestroyed(): # The validator or stringtovalue commands called by # _checkValidity() destroyed us. return oldValidity if valid == OK: if self.normalBackground is not None: self._entryFieldEntry.configure( background = self.normalBackground) self.normalBackground = None else: if self.normalBackground is None: self.normalBackground = self._entryFieldEntry.cget('background') self._entryFieldEntry.configure( background = self['errorbackground']) return oldValidity def invoke(self): return self._executeCommand() def valid(self): return self._valid == OK def clear(self): self.setentry('') def __setEntry(self, text): oldState = str(self._entryFieldEntry.cget('state')) if oldState != 'normal': self._entryFieldEntry.configure(state='normal') self._entryFieldEntry.delete(0, 'end') self._entryFieldEntry.insert(0, text) if oldState != 'normal': self._entryFieldEntry.configure(state=oldState) def setentry(self, text): self._preProcess() self.__setEntry(text) return self._postProcess() def getvalue(self): return self._entryFieldEntry.get() def setvalue(self, text): return self.setentry(text) forwardmethods(EntryField, Tkinter.Entry, '_entryFieldEntry') # ====================================================================== # Entry field validation functions _numericregex = re.compile('^[0-9]*$') _alphabeticregex = re.compile('^[a-z]*$', re.IGNORECASE) _alphanumericregex = re.compile('^[0-9a-z]*$', re.IGNORECASE) def numericvalidator(text): if text == '': return PARTIAL else: if _numericregex.match(text) is None: return ERROR else: return OK def integervalidator(text): if text in ('', '-', '+'): return PARTIAL try: string.atol(text) return OK except ValueError: return ERROR def alphabeticvalidator(text): if _alphabeticregex.match(text) is None: return ERROR else: return OK def alphanumericvalidator(text): if _alphanumericregex.match(text) is None: return ERROR else: return OK def hexadecimalvalidator(text): if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'): return PARTIAL try: string.atol(text, 16) return OK except ValueError: return ERROR def realvalidator(text, separator = '.'): if separator != '.': if string.find(text, '.') >= 0: return ERROR index = string.find(text, separator) if index >= 0: text = text[:index] + '.' + text[index + 1:] try: string.atof(text) return OK except ValueError: # Check if the string could be made valid by appending a digit # eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-'). if len(text) == 0: return PARTIAL if text[-1] in string.digits: return ERROR try: string.atof(text + '0') return PARTIAL except ValueError: return ERROR def timevalidator(text, separator = ':'): try: timestringtoseconds(text, separator) return OK except ValueError: if len(text) > 0 and text[0] in ('+', '-'): text = text[1:] if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL def datevalidator(text, format = 'ymd', separator = '/'): try: datestringtojdn(text, format, separator) return OK except ValueError: if re.search('[^0-9' + separator + ']', text) is not None: return ERROR return PARTIAL _standardValidators = { 'numeric' : (numericvalidator, string.atol), 'integer' : (integervalidator, string.atol), 'hexadecimal' : (hexadecimalvalidator, lambda s: string.atol(s, 16)), 'real' : (realvalidator, stringtoreal), 'alphabetic' : (alphabeticvalidator, len), 'alphanumeric' : (alphanumericvalidator, len), 'time' : (timevalidator, timestringtoseconds), 'date' : (datevalidator, datestringtojdn), } _entryCache = {} def _registerEntryField(entry, entryField): # Register an EntryField widget for an Entry widget _entryCache[entry] = entryField def _deregisterEntryField(entry): # Deregister an Entry widget del _entryCache[entry] def _preProcess(event): # Forward preprocess events for an Entry to it's EntryField _entryCache[event.widget]._preProcess() def _postProcess(event): # Forward postprocess events for an Entry to it's EntryField # The function specified by the 'command' option may have destroyed # the megawidget in a binding earlier in bindtags, so need to check. if _entryCache.has_key(event.widget): _entryCache[event.widget]._postProcess() ###################################################################### ### File: PmwGroup.py import string import Tkinter def aligngrouptags(groups): # Adjust the y position of the tags in /groups/ so that they all # have the height of the highest tag. maxTagHeight = 0 for group in groups: if group._tag is None: height = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) else: height = group._tag.winfo_reqheight() if maxTagHeight < height: maxTagHeight = height for group in groups: ringBorder = (string.atoi(str(group._ring.cget('borderwidth'))) + string.atoi(str(group._ring.cget('highlightthickness')))) topBorder = maxTagHeight / 2 - ringBorder / 2 group._hull.grid_rowconfigure(0, minsize = topBorder) group._ring.grid_rowconfigure(0, minsize = maxTagHeight - topBorder - ringBorder) if group._tag is not None: group._tag.place(y = maxTagHeight / 2) class Group( MegaWidget ): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('collapsedsize', 6, INITOPT), ('ring_borderwidth', 2, None), ('ring_relief', 'groove', None), ('tagindent', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._ring = self.createcomponent( 'ring', (), None, Tkinter.Frame, (interior,), ) self._groupChildSite = self.createcomponent( 'groupchildsite', (), None, Tkinter.Frame, (self._ring,) ) self._tag = self.createcomponent( 'tag', (), None, Tkinter.Label, (interior,), ) ringBorder = (string.atoi(str(self._ring.cget('borderwidth'))) + string.atoi(str(self._ring.cget('highlightthickness')))) if self._tag is None: tagHeight = ringBorder else: tagHeight = self._tag.winfo_reqheight() self._tag.place( x = ringBorder + self['tagindent'], y = tagHeight / 2, anchor = 'w') topBorder = tagHeight / 2 - ringBorder / 2 self._ring.grid(column = 0, row = 1, sticky = 'nsew') interior.grid_columnconfigure(0, weight = 1) interior.grid_rowconfigure(1, weight = 1) interior.grid_rowconfigure(0, minsize = topBorder) self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') self._ring.grid_columnconfigure(0, weight = 1) self._ring.grid_rowconfigure(1, weight = 1) self._ring.grid_rowconfigure(0, minsize = tagHeight - topBorder - ringBorder) self.showing = 1 # Check keywords and initialise options. self.initialiseoptions() def toggle(self): if self.showing: self.collapse() else: self.expand() self.showing = not self.showing def expand(self): self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew') def collapse(self): self._groupChildSite.grid_forget() if self._tag is None: tagHeight = 0 else: tagHeight = self._tag.winfo_reqheight() self._ring.configure(height=(tagHeight / 2) + self['collapsedsize']) def interior(self): return self._groupChildSite ###################################################################### ### File: PmwLabeledWidget.py import Tkinter class LabeledWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'nsew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = MegaWidget.interior(self) self._labelChildSite = self.createcomponent('labelchildsite', (), None, Tkinter.Frame, (interior,)) self._labelChildSite.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def interior(self): return self._labelChildSite ###################################################################### ### File: PmwMainMenuBar.py # Main menubar import string import types import Tkinter class MainMenuBar(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('hull_tearoff', 0, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu',)) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Menu) self._menuInfo = {} self._menuInfo[None] = (None, []) # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The key for the information for the main menubar is None. self._menu = self.interior() self._menu.bind('<Leave>', self._resetHelpmessage) self._menu.bind('<Motion>', lambda event=None, self=self: self._menuHelp(event, None)) # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName).delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ parentName = self._menuInfo[menuName][0] del self._menuInfo[menuName] if parentName is None: parentMenu = self._menu else: parentMenu = self.component(parentName) menu = self.component(menuName) menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName) def disableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'disabled') def enableall(self): for index in range(len(self._menuInfo[None][1])): self.entryconfigure(index, state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, traverseSpec = None, **kw): if statusHelp is None: statusHelp = balloonHelp self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, kw) def addcascademenu(self, parentMenuName, menuName, statusHelp='', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, kw): if (menuName) in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if kw.has_key('name'): menukw['name'] = kw['name'] del kw['name'] if not kw.has_key('label'): kw['label'] = menuName self._addHotkeyToOptions(parentMenuName, kw, traverseSpec) if parentMenuName is None: parentMenu = self._menu balloon = self['balloon'] # Bug in Tk: balloon help not implemented # if balloon is not None: # balloon.mainmenubind(parentMenu, balloonHelp, statusHelp) else: parentMenu = self.component(parentMenuName) apply(parentMenu.add_cascade, (), kw) menu = apply(self.createcomponent, (menuName, (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) parentMenu.entryconfigure('end', menu = menu) self._menuInfo[parentMenuName][1].append(statusHelp) self._menuInfo[menuName] = (parentMenuName, []) menu.bind('<Leave>', self._resetHelpmessage) menu.bind('<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(event, menuName)) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName) if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key('label')): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return if menuName is None: menu = self._menu else: menu = self.component(menuName) hotkeyList = [] end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = \ string.atoi(str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, 'label')) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw['label'] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, event, menuName): if menuName is None: menu = self._menu index = menu.index('@%d'% event.x) else: menu = self.component(menuName) index = menu.index('@%d'% event.y) balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() forwardmethods(MainMenuBar, Tkinter.Menu, '_hull') ###################################################################### ### File: PmwMenuBar.py # Manager widget for menus. import string import types import Tkinter class MenuBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('balloon', None, None), ('hotkeys', 1, INITOPT), ('padx', 0, INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu', 'Button')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self._menuInfo = {} # Map from a menu name to a tuple of information about the menu. # The first item in the tuple is the name of the parent menu (for # toplevel menus this is None). The second item in the tuple is # a list of status help messages for each item in the menu. # The third item in the tuple is the id of the binding used # to detect mouse motion to display status help. # Information for the toplevel menubuttons is not stored here. self._mydeletecommand = self.component('hull').tk.deletecommand # Cache this method for use later. # Check keywords and initialise options. self.initialiseoptions() def deletemenuitems(self, menuName, start, end = None): self.component(menuName + '-menu').delete(start, end) if end is None: del self._menuInfo[menuName][1][start] else: self._menuInfo[menuName][1][start:end+1] = [] def deletemenu(self, menuName): """Delete should be called for cascaded menus before main menus. """ # Clean up binding for this menu. parentName = self._menuInfo[menuName][0] bindId = self._menuInfo[menuName][2] _bindtag = 'PmwMenuBar' + str(self) + menuName self.unbind_class(_bindtag, '<Motion>') self._mydeletecommand(bindId) # unbind_class does not clean up del self._menuInfo[menuName] if parentName is None: self.destroycomponent(menuName + '-button') else: parentMenu = self.component(parentName + '-menu') menu = self.component(menuName + '-menu') menuId = str(menu) for item in range(parentMenu.index('end') + 1): if parentMenu.type(item) == 'cascade': itemMenu = str(parentMenu.entrycget(item, 'menu')) if itemMenu == menuId: parentMenu.delete(item) del self._menuInfo[parentName][1][item] break self.destroycomponent(menuName + '-menu') def disableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'disabled') def enableall(self): for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') menubutton.configure(state = 'normal') def addmenu(self, menuName, balloonHelp, statusHelp = None, side = 'left', traverseSpec = None, **kw): self._addmenu(None, menuName, balloonHelp, statusHelp, traverseSpec, side, 'text', kw) def addcascademenu(self, parentMenuName, menuName, statusHelp = '', traverseSpec = None, **kw): self._addmenu(parentMenuName, menuName, None, statusHelp, traverseSpec, None, 'label', kw) def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp, traverseSpec, side, textKey, kw): if (menuName + '-menu') in self.components(): raise ValueError, 'menu "%s" already exists' % menuName menukw = {} if kw.has_key('tearoff'): menukw['tearoff'] = kw['tearoff'] del kw['tearoff'] else: menukw['tearoff'] = 0 if not kw.has_key(textKey): kw[textKey] = menuName self._addHotkeyToOptions(parentMenuName, kw, textKey, traverseSpec) if parentMenuName is None: button = apply(self.createcomponent, (menuName + '-button', (), 'Button', Tkinter.Menubutton, (self.interior(),)), kw) button.pack(side=side, padx = self['padx']) balloon = self['balloon'] if balloon is not None: balloon.bind(button, balloonHelp, statusHelp) parentMenu = button else: parentMenu = self.component(parentMenuName + '-menu') apply(parentMenu.add_cascade, (), kw) self._menuInfo[parentMenuName][1].append(statusHelp) menu = apply(self.createcomponent, (menuName + '-menu', (), 'Menu', Tkinter.Menu, (parentMenu,)), menukw) if parentMenuName is None: button.configure(menu = menu) else: parentMenu.entryconfigure('end', menu = menu) # Need to put this binding after the class bindings so that # menu.index() does not lag behind. _bindtag = 'PmwMenuBar' + str(self) + menuName bindId = self.bind_class(_bindtag, '<Motion>', lambda event=None, self=self, menuName=menuName: self._menuHelp(menuName)) menu.bindtags(menu.bindtags() + (_bindtag,)) menu.bind('<Leave>', self._resetHelpmessage) self._menuInfo[menuName] = (parentMenuName, [], bindId) def addmenuitem(self, menuName, itemType, statusHelp = '', traverseSpec = None, **kw): menu = self.component(menuName + '-menu') if itemType != 'separator': self._addHotkeyToOptions(menuName, kw, 'label', traverseSpec) if itemType == 'command': command = menu.add_command elif itemType == 'separator': command = menu.add_separator elif itemType == 'checkbutton': command = menu.add_checkbutton elif itemType == 'radiobutton': command = menu.add_radiobutton elif itemType == 'cascade': command = menu.add_cascade else: raise ValueError, 'unknown menuitem type "%s"' % itemType self._menuInfo[menuName][1].append(statusHelp) apply(command, (), kw) def _addHotkeyToOptions(self, menuName, kw, textKey, traverseSpec): if (not self['hotkeys'] or kw.has_key('underline') or not kw.has_key(textKey)): return if type(traverseSpec) == types.IntType: kw['underline'] = traverseSpec return hotkeyList = [] if menuName is None: for menuName in self._menuInfo.keys(): if self._menuInfo[menuName][0] is None: menubutton = self.component(menuName + '-button') underline = string.atoi(str(menubutton.cget('underline'))) if underline != -1: label = str(menubutton.cget(textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) else: menu = self.component(menuName + '-menu') end = menu.index('end') if end is not None: for item in range(end + 1): if menu.type(item) not in ('separator', 'tearoff'): underline = string.atoi( str(menu.entrycget(item, 'underline'))) if underline != -1: label = str(menu.entrycget(item, textKey)) if underline < len(label): hotkey = string.lower(label[underline]) if hotkey not in hotkeyList: hotkeyList.append(hotkey) name = kw[textKey] if type(traverseSpec) == types.StringType: lowerLetter = string.lower(traverseSpec) if traverseSpec in name and lowerLetter not in hotkeyList: kw['underline'] = string.index(name, traverseSpec) else: targets = string.digits + string.letters lowerName = string.lower(name) for letter_index in range(len(name)): letter = lowerName[letter_index] if letter in targets and letter not in hotkeyList: kw['underline'] = letter_index break def _menuHelp(self, menuName): menu = self.component(menuName + '-menu') index = menu.index('active') balloon = self['balloon'] if balloon is not None: if index is None: balloon.showstatus('') else: if str(menu.cget('tearoff')) == '1': index = index - 1 if index >= 0: help = self._menuInfo[menuName][1][index] balloon.showstatus(help) def _resetHelpmessage(self, event=None): balloon = self['balloon'] if balloon is not None: balloon.clearstatus() ###################################################################### ### File: PmwMessageBar.py # Class to display messages in an information line. import string import Tkinter class MessageBar(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. defaultMessageTypes = { # (priority, showtime, bells, logmessage) 'systemerror' : (5, 10, 2, 1), 'usererror' : (4, 5, 1, 0), 'busy' : (3, 0, 0, 0), 'systemevent' : (2, 5, 0, 0), 'userevent' : (2, 5, 0, 0), 'help' : (1, 5, 0, 0), 'state' : (0, 0, 0, 0), } optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('messagetypes', defaultMessageTypes, INITOPT), ('silent', 0, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._messageBarEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') self._messageBarEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._numPriorities = 0 for info in self['messagetypes'].values(): if self._numPriorities < info[0]: self._numPriorities = info[0] self._numPriorities = self._numPriorities + 1 self._timer = [None] * self._numPriorities self._messagetext = [''] * self._numPriorities self._activemessage = [0] * self._numPriorities # Check keywords and initialise options. self.initialiseoptions() def destroy(self): for timerId in self._timer: if timerId is not None: self.after_cancel(timerId) self._timer = [None] * self._numPriorities MegaWidget.destroy(self) def message(self, type, text): # Display a message in the message bar. (priority, showtime, bells, logmessage) = self['messagetypes'][type] if not self['silent']: for i in range(bells): if i != 0: self.after(100) self.bell() self._activemessage[priority] = 1 if text is None: text = '' self._messagetext[priority] = string.replace(text, '\n', ' ') self._redisplayInfoMessage() if logmessage: # Should log this text to a text widget. pass if showtime > 0: if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) # Define a callback to clear this message after a time. def _clearmessage(self=self, priority=priority): self._clearActivemessage(priority) mseconds = int(showtime * 1000) self._timer[priority] = self.after(mseconds, _clearmessage) def helpmessage(self, text): if text is None: self.resetmessages('help') else: self.message('help', text) def resetmessages(self, type): priority = self['messagetypes'][type][0] self._clearActivemessage(priority) for messagetype, info in self['messagetypes'].items(): thisPriority = info[0] showtime = info[1] if thisPriority < priority and showtime != 0: self._clearActivemessage(thisPriority) def _clearActivemessage(self, priority): self._activemessage[priority] = 0 if self._timer[priority] is not None: self.after_cancel(self._timer[priority]) self._timer[priority] = None self._redisplayInfoMessage() def _redisplayInfoMessage(self): text = '' for priority in range(self._numPriorities - 1, -1, -1): if self._activemessage[priority]: text = self._messagetext[priority] break self._messageBarEntry.configure(state = 'normal') self._messageBarEntry.delete(0, 'end') self._messageBarEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._messageBarEntry.configure(state = 'readonly') except Tkinter.TclError: self._messageBarEntry.configure(state = 'disabled') forwardmethods(MessageBar, Tkinter.Entry, '_messageBarEntry') ###################################################################### ### File: PmwMessageDialog.py # Based on iwidgets2.2.0/messagedialog.itk code. import Tkinter class MessageDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ('iconmargin', 20, INITOPT), ('iconpos', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() self._message = self.createcomponent('message', (), None, Tkinter.Label, (interior,)) iconpos = self['iconpos'] iconmargin = self['iconmargin'] borderx = self['borderx'] bordery = self['bordery'] border_right = 2 border_bottom = 2 if iconpos is None: self._message.grid(column = 1, row = 1) else: self._icon = self.createcomponent('icon', (), None, Tkinter.Label, (interior,)) if iconpos not in 'nsew': raise ValueError, \ 'bad iconpos option "%s": should be n, s, e, or w' \ % iconpos if iconpos in 'nw': icon = 1 message = 3 else: icon = 3 message = 1 if iconpos in 'ns': # vertical layout self._icon.grid(column = 1, row = icon) self._message.grid(column = 1, row = message) interior.grid_rowconfigure(2, minsize = iconmargin) border_bottom = 4 else: # horizontal layout self._icon.grid(column = icon, row = 1) self._message.grid(column = message, row = 1) interior.grid_columnconfigure(2, minsize = iconmargin) border_right = 4 interior.grid_columnconfigure(0, minsize = borderx) interior.grid_rowconfigure(0, minsize = bordery) interior.grid_columnconfigure(border_right, minsize = borderx) interior.grid_rowconfigure(border_bottom, minsize = bordery) # Check keywords and initialise options. self.initialiseoptions() ###################################################################### ### File: PmwNoteBook.py import string import types import Tkinter class NoteBook(MegaArchetype): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('hull_highlightthickness', 0, None), ('hull_borderwidth', 0, None), ('arrownavigation', 1, INITOPT), ('borderwidth', 2, INITOPT), ('createcommand', None, None), ('lowercommand', None, None), ('pagemargin', 4, INITOPT), ('raisecommand', None, None), ('tabpos', 'n', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Page', 'Tab')) # Initialise the base class (after defining the options). MegaArchetype.__init__(self, parent, Tkinter.Canvas) self.bind('<Map>', self._handleMap) self.bind('<Configure>', self._handleConfigure) tabpos = self['tabpos'] if tabpos is not None and tabpos != 'n': raise ValueError, \ 'bad tabpos option %s: should be n or None' % repr(tabpos) self._withTabs = (tabpos is not None) self._pageMargin = self['pagemargin'] self._borderWidth = self['borderwidth'] # Use a dictionary as a set of bits indicating what needs to # be redisplayed the next time _layout() is called. If # dictionary contains 'topPage' key, the value is the new top # page to be displayed. None indicates that all pages have # been deleted and that _layout() should draw a border under where # the tabs should be. self._pending = {} self._pending['size'] = 1 self._pending['borderColor'] = 1 self._pending['topPage'] = None if self._withTabs: self._pending['tabs'] = 1 self._canvasSize = None # This gets set by <Configure> events # Set initial height of space for tabs if self._withTabs: self.tabBottom = 35 else: self.tabBottom = 0 self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) self._pageNames = [] # List of page names # Map from page name to page info. Each item is itself a # dictionary containing the following items: # page the Tkinter.Frame widget for the page # created set to true the first time the page is raised # tabbutton the Tkinter.Button widget for the button (if any) # tabreqwidth requested width of the tab # tabreqheight requested height of the tab # tabitems the canvas items for the button: the button # window item, the lightshadow and the darkshadow # left the left and right canvas coordinates of the tab # right self._pageAttrs = {} # Name of page currently on top (actually displayed, using # create_window, not pending). Ignored if current top page # has been deleted or new top page is pending. None indicates # no pages in notebook. self._topPageName = None # Canvas items used: # Per tab: # top and left shadow # right shadow # button # Per notebook: # page # top page # left shadow # bottom and right shadow # top (one or two items) # Canvas tags used: # lighttag - top and left shadows of tabs and page # darktag - bottom and right shadows of tabs and page # (if no tabs then these are reversed) # (used to color the borders by recolorborders) # Create page border shadows. if self._withTabs: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageTop1Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') self._pageTop2Border = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'lighttag') else: self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._lightBorderColor, tags = 'lighttag') self._pageTopBorder = self.create_polygon(0, 0, 0, 0, 0, 0, fill = self._darkBorderColor, tags = 'darktag') # Check keywords and initialise options. self.initialiseoptions() def insert(self, pageName, before = 0, **kw): if self._pageAttrs.has_key(pageName): msg = 'Page "%s" already exists.' % pageName raise ValueError, msg # Do this early to catch bad <before> spec before creating any items. beforeIndex = self.index(before, 1) pageOptions = {} if self._withTabs: # Default tab button options. tabOptions = { 'text' : pageName, 'borderwidth' : 0, } # Divide the keyword options into the 'page_' and 'tab_' options. for key in kw.keys(): if key[:5] == 'page_': pageOptions[key[5:]] = kw[key] del kw[key] elif self._withTabs and key[:4] == 'tab_': tabOptions[key[4:]] = kw[key] del kw[key] else: raise KeyError, 'Unknown option "' + key + '"' # Create the frame to contain the page. page = apply(self.createcomponent, (pageName, (), 'Page', Tkinter.Frame, self._hull), pageOptions) attributes = {} attributes['page'] = page attributes['created'] = 0 if self._withTabs: # Create the button for the tab. def raiseThisPage(self = self, pageName = pageName): self.selectpage(pageName) tabOptions['command'] = raiseThisPage tab = apply(self.createcomponent, (pageName + '-tab', (), 'Tab', Tkinter.Button, self._hull), tabOptions) if self['arrownavigation']: # Allow the use of the arrow keys for Tab navigation: def next(event, self = self, pageName = pageName): self.nextpage(pageName) def prev(event, self = self, pageName = pageName): self.previouspage(pageName) tab.bind('<Left>', prev) tab.bind('<Right>', next) attributes['tabbutton'] = tab attributes['tabreqwidth'] = tab.winfo_reqwidth() attributes['tabreqheight'] = tab.winfo_reqheight() # Create the canvas item to manage the tab's button and the items # for the tab's shadow. windowitem = self.create_window(0, 0, window = tab, anchor = 'nw') lightshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'lighttag', fill = self._lightBorderColor) darkshadow = self.create_polygon(0, 0, 0, 0, 0, 0, tags = 'darktag', fill = self._darkBorderColor) attributes['tabitems'] = (windowitem, lightshadow, darkshadow) self._pending['tabs'] = 1 self._pageAttrs[pageName] = attributes self._pageNames.insert(beforeIndex, pageName) # If this is the first page added, make it the new top page # and call the create and raise callbacks. if self.getcurselection() is None: self._pending['topPage'] = pageName self._raiseNewTop(pageName) self._layout() return page def add(self, pageName, **kw): return apply(self.insert, (pageName, len(self._pageNames)), kw) def delete(self, *pageNames): newTopPage = 0 for page in pageNames: pageIndex = self.index(page) pageName = self._pageNames[pageIndex] pageInfo = self._pageAttrs[pageName] if self.getcurselection() == pageName: if len(self._pageNames) == 1: newTopPage = 0 self._pending['topPage'] = None elif pageIndex == len(self._pageNames) - 1: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex - 1] else: newTopPage = 1 self._pending['topPage'] = self._pageNames[pageIndex + 1] if self._topPageName == pageName: self._hull.delete(self._topPageItem) self._topPageName = None if self._withTabs: self.destroycomponent(pageName + '-tab') apply(self._hull.delete, pageInfo['tabitems']) self.destroycomponent(pageName) del self._pageAttrs[pageName] del self._pageNames[pageIndex] # If the old top page was deleted and there are still pages # left in the notebook, call the create and raise callbacks. if newTopPage: pageName = self._pending['topPage'] self._raiseNewTop(pageName) if self._withTabs: self._pending['tabs'] = 1 self._layout() def page(self, pageIndex): pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['page'] def pagenames(self): return list(self._pageNames) def getcurselection(self): if self._pending.has_key('topPage'): return self._pending['topPage'] else: return self._topPageName def tab(self, pageIndex): if self._withTabs: pageName = self._pageNames[self.index(pageIndex)] return self._pageAttrs[pageName]['tabbutton'] else: return None def index(self, index, forInsert = 0): listLength = len(self._pageNames) if type(index) == types.IntType: if forInsert and index <= listLength: return index elif not forInsert and index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if forInsert: return listLength elif listLength > 0: return listLength - 1 else: raise ValueError, 'NoteBook has no pages' elif index is SELECT: if listLength == 0: raise ValueError, 'NoteBook has no pages' return self._pageNames.index(self.getcurselection()) else: if index in self._pageNames: return self._pageNames.index(index) validValues = 'a name, a number, END or SELECT' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def selectpage(self, page): pageName = self._pageNames[self.index(page)] oldTopPage = self.getcurselection() if pageName != oldTopPage: self._pending['topPage'] = pageName if oldTopPage == self._topPageName: self._hull.delete(self._topPageItem) cmd = self['lowercommand'] if cmd is not None: cmd(oldTopPage) self._raiseNewTop(pageName) self._layout() # Set focus to the tab of new top page: if self._withTabs and self['arrownavigation']: self._pageAttrs[pageName]['tabbutton'].focus_set() def previouspage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage > 0: self.selectpage(curpage - 1) def nextpage(self, pageIndex = None): if pageIndex is None: curpage = self.index(SELECT) else: curpage = self.index(pageIndex) if curpage < len(self._pageNames) - 1: self.selectpage(curpage + 1) def setnaturalsize(self, pageNames = None): self.update_idletasks() maxPageWidth = 1 maxPageHeight = 1 if pageNames is None: pageNames = self.pagenames() for pageName in pageNames: pageInfo = self._pageAttrs[pageName] page = pageInfo['page'] w = page.winfo_reqwidth() h = page.winfo_reqheight() if maxPageWidth < w: maxPageWidth = w if maxPageHeight < h: maxPageHeight = h pageBorder = self._borderWidth + self._pageMargin width = maxPageWidth + pageBorder * 2 height = maxPageHeight + pageBorder * 2 if self._withTabs: maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] height = height + maxTabHeight + self._borderWidth * 1.5 # Note that, since the hull is a canvas, the width and height # options specify the geometry *inside* the borderwidth and # highlightthickness. self.configure(hull_width = width, hull_height = height) def recolorborders(self): self._pending['borderColor'] = 1 self._layout() def _handleMap(self, event): self._layout() def _handleConfigure(self, event): self._canvasSize = (event.width, event.height) self._pending['size'] = 1 self._layout() def _raiseNewTop(self, pageName): if not self._pageAttrs[pageName]['created']: self._pageAttrs[pageName]['created'] = 1 cmd = self['createcommand'] if cmd is not None: cmd(pageName) cmd = self['raisecommand'] if cmd is not None: cmd(pageName) # This is the vertical layout of the notebook, from top (assuming # tabpos is 'n'): # hull highlightthickness (top) # hull borderwidth (top) # borderwidth (top border of tabs) # borderwidth * 0.5 (space for bevel) # tab button (maximum of requested height of all tab buttons) # borderwidth (border between tabs and page) # pagemargin (top) # the page itself # pagemargin (bottom) # borderwidth (border below page) # hull borderwidth (bottom) # hull highlightthickness (bottom) # # canvasBorder is sum of top two elements. # tabBottom is sum of top five elements. # # Horizontal layout (and also vertical layout when tabpos is None): # hull highlightthickness # hull borderwidth # borderwidth # pagemargin # the page itself # pagemargin # borderwidth # hull borderwidth # hull highlightthickness # def _layout(self): if not self.winfo_ismapped() or self._canvasSize is None: # Don't layout if the window is not displayed, or we # haven't yet received a <Configure> event. return hullWidth, hullHeight = self._canvasSize borderWidth = self._borderWidth canvasBorder = string.atoi(self._hull['borderwidth']) + \ string.atoi(self._hull['highlightthickness']) if not self._withTabs: self.tabBottom = canvasBorder oldTabBottom = self.tabBottom if self._pending.has_key('borderColor'): self._lightBorderColor, self._darkBorderColor = \ Color.bordercolors(self, self['hull_background']) # Draw all the tabs. if self._withTabs and (self._pending.has_key('tabs') or self._pending.has_key('size')): # Find total requested width and maximum requested height # of tabs. sumTabReqWidth = 0 maxTabHeight = 0 for pageInfo in self._pageAttrs.values(): sumTabReqWidth = sumTabReqWidth + pageInfo['tabreqwidth'] if maxTabHeight < pageInfo['tabreqheight']: maxTabHeight = pageInfo['tabreqheight'] if maxTabHeight != 0: # Add the top tab border plus a bit for the angled corners self.tabBottom = canvasBorder + maxTabHeight + borderWidth * 1.5 # Prepare for drawing the border around each tab button. tabTop = canvasBorder tabTop2 = tabTop + borderWidth tabTop3 = tabTop + borderWidth * 1.5 tabBottom2 = self.tabBottom tabBottom = self.tabBottom + borderWidth numTabs = len(self._pageNames) availableWidth = hullWidth - 2 * canvasBorder - \ numTabs * 2 * borderWidth x = canvasBorder cumTabReqWidth = 0 cumTabWidth = 0 # Position all the tabs. for pageName in self._pageNames: pageInfo = self._pageAttrs[pageName] (windowitem, lightshadow, darkshadow) = pageInfo['tabitems'] if sumTabReqWidth <= availableWidth: tabwidth = pageInfo['tabreqwidth'] else: # This ugly calculation ensures that, when the # notebook is not wide enough for the requested # widths of the tabs, the total width given to # the tabs exactly equals the available width, # without rounding errors. cumTabReqWidth = cumTabReqWidth + pageInfo['tabreqwidth'] tmp = (2*cumTabReqWidth*availableWidth + sumTabReqWidth) \ / (2 * sumTabReqWidth) tabwidth = tmp - cumTabWidth cumTabWidth = tmp # Position the tab's button canvas item. self.coords(windowitem, x + borderWidth, tabTop3) self.itemconfigure(windowitem, width = tabwidth, height = maxTabHeight) # Make a beautiful border around the tab. left = x left2 = left + borderWidth left3 = left + borderWidth * 1.5 right = left + tabwidth + 2 * borderWidth right2 = left + tabwidth + borderWidth right3 = left + tabwidth + borderWidth * 0.5 self.coords(lightshadow, left, tabBottom2, left, tabTop2, left2, tabTop, right2, tabTop, right3, tabTop2, left3, tabTop2, left2, tabTop3, left2, tabBottom, ) self.coords(darkshadow, right2, tabTop, right, tabTop2, right, tabBottom2, right2, tabBottom, right2, tabTop3, right3, tabTop2, ) pageInfo['left'] = left pageInfo['right'] = right x = x + tabwidth + 2 * borderWidth # Redraw shadow under tabs so that it appears that tab for old # top page is lowered and that tab for new top page is raised. if self._withTabs and (self._pending.has_key('topPage') or self._pending.has_key('tabs') or self._pending.has_key('size')): if self.getcurselection() is None: # No pages, so draw line across top of page area. self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Ignore second top border. self.coords(self._pageTop2Border, 0, 0, 0, 0, 0, 0) else: # Draw two lines, one on each side of the tab for the # top page, so that the tab appears to be raised. pageInfo = self._pageAttrs[self.getcurselection()] left = pageInfo['left'] right = pageInfo['right'] self.coords(self._pageTop1Border, canvasBorder, self.tabBottom, left, self.tabBottom, left + borderWidth, self.tabBottom + borderWidth, canvasBorder + borderWidth, self.tabBottom + borderWidth, ) self.coords(self._pageTop2Border, right, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, right - borderWidth, self.tabBottom + borderWidth, ) # Prevent bottom of dark border of tabs appearing over # page top border. self.tag_raise(self._pageTop1Border) self.tag_raise(self._pageTop2Border) # Position the page border shadows. if self._pending.has_key('size') or oldTabBottom != self.tabBottom: self.coords(self._pageLeftBorder, canvasBorder, self.tabBottom, borderWidth + canvasBorder, self.tabBottom + borderWidth, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, canvasBorder, hullHeight - canvasBorder, ) self.coords(self._pageBottomRightBorder, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder, hullHeight - canvasBorder, canvasBorder, hullHeight - canvasBorder, borderWidth + canvasBorder, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, hullHeight - canvasBorder - borderWidth, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, ) if not self._withTabs: self.coords(self._pageTopBorder, canvasBorder, self.tabBottom, hullWidth - canvasBorder, self.tabBottom, hullWidth - canvasBorder - borderWidth, self.tabBottom + borderWidth, borderWidth + canvasBorder, self.tabBottom + borderWidth, ) # Color borders. if self._pending.has_key('borderColor'): self.itemconfigure('lighttag', fill = self._lightBorderColor) self.itemconfigure('darktag', fill = self._darkBorderColor) newTopPage = self._pending.get('topPage') pageBorder = borderWidth + self._pageMargin # Raise new top page. if newTopPage is not None: self._topPageName = newTopPage self._topPageItem = self.create_window( pageBorder + canvasBorder, self.tabBottom + pageBorder, window = self._pageAttrs[newTopPage]['page'], anchor = 'nw', ) # Change position of top page if tab height has changed. if self._topPageName is not None and oldTabBottom != self.tabBottom: self.coords(self._topPageItem, pageBorder + canvasBorder, self.tabBottom + pageBorder) # Change size of top page if, # 1) there is a new top page. # 2) canvas size has changed, but not if there is no top # page (eg: initially or when all pages deleted). # 3) tab height has changed, due to difference in the height of a tab if (newTopPage is not None or \ self._pending.has_key('size') and self._topPageName is not None or oldTabBottom != self.tabBottom): self.itemconfigure(self._topPageItem, width = hullWidth - 2 * canvasBorder - pageBorder * 2, height = hullHeight - 2 * canvasBorder - pageBorder * 2 - (self.tabBottom - canvasBorder), ) self._pending = {} # Need to do forwarding to get the pack, grid, etc methods. # Unfortunately this means that all the other canvas methods are also # forwarded. forwardmethods(NoteBook, Tkinter.Canvas, '_hull') ###################################################################### ### File: PmwOptionMenu.py import types import Tkinter class OptionMenu(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('items', (), INITOPT), ('initialitem', None, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._menubutton = self.createcomponent('menubutton', (), None, Tkinter.Menubutton, (interior,), borderwidth = 2, indicatoron = 1, relief = 'raised', anchor = 'c', highlightthickness = 2, direction = 'flush', takefocus = 1, ) self._menubutton.grid(column = 2, row = 2, sticky = self['sticky']) self._menu = self.createcomponent('menu', (), None, Tkinter.Menu, (self._menubutton,), tearoff=0 ) self._menubutton.configure(menu = self._menu) interior.grid_columnconfigure(2, weight = 1) interior.grid_rowconfigure(2, weight = 1) # Create the label. self.createlabel(interior) # Add the items specified by the initialisation option. self._itemList = [] self.setitems(self['items'], self['initialitem']) # Check keywords and initialise options. self.initialiseoptions() def setitems(self, items, index = None): # Clean up old items and callback commands. for oldIndex in range(len(self._itemList)): tclCommandName = str(self._menu.entrycget(oldIndex, 'command')) if tclCommandName != '': self._menu.deletecommand(tclCommandName) self._menu.delete(0, 'end') self._itemList = list(items) # Set the items in the menu component. for item in items: self._menu.add_command(label = item, command = lambda self = self, item = item: self._invoke(item)) # Set the currently selected value. if index is None: var = str(self._menubutton.cget('textvariable')) if var != '': # None means do not change text variable. return if len(items) == 0: text = '' elif str(self._menubutton.cget('text')) in items: # Do not change selection if it is still valid return else: text = items[0] else: index = self.index(index) text = self._itemList[index] self.setvalue(text) def getcurselection(self): var = str(self._menubutton.cget('textvariable')) if var == '': return str(self._menubutton.cget('text')) else: return self._menu.tk.globalgetvar(var) def getvalue(self): return self.getcurselection() def setvalue(self, text): var = str(self._menubutton.cget('textvariable')) if var == '': self._menubutton.configure(text = text) else: self._menu.tk.globalsetvar(var, text) def index(self, index): listLength = len(self._itemList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'OptionMenu has no items' else: if index is SELECT: if listLength > 0: index = self.getcurselection() else: raise ValueError, 'OptionMenu has no items' if index in self._itemList: return self._itemList.index(index) raise ValueError, \ 'bad index "%s": must be a ' \ 'name, a number, END or SELECT' % (index,) def invoke(self, index = SELECT): index = self.index(index) text = self._itemList[index] return self._invoke(text) def _invoke(self, text): self.setvalue(text) command = self['command'] if callable(command): return command(text) ###################################################################### ### File: PmwPanedWidget.py # PanedWidget # a frame which may contain several resizable sub-frames import string import sys import types import Tkinter class PanedWidget(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('command', None, None), ('orient', 'vertical', INITOPT), ('separatorrelief', 'sunken', INITOPT), ('separatorthickness', 2, INITOPT), ('handlesize', 8, INITOPT), ('hull_width', 400, None), ('hull_height', 400, None), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Frame', 'Separator', 'Handle')) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.bind('<Configure>', self._handleConfigure) if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' self._separatorThickness = self['separatorthickness'] self._handleSize = self['handlesize'] self._paneNames = [] # List of pane names self._paneAttrs = {} # Map from pane name to pane info self._timerId = None self._frame = {} self._separator = [] self._button = [] self._totalSize = 0 self._movePending = 0 self._relsize = {} self._relmin = {} self._relmax = {} self._size = {} self._min = {} self._max = {} self._rootp = None self._curSize = None self._beforeLimit = None self._afterLimit = None self._buttonIsDown = 0 self._majorSize = 100 self._minorSize = 100 # Check keywords and initialise options. self.initialiseoptions() def insert(self, name, before = 0, **kw): # Parse <kw> for options. self._initPaneOptions(name) self._parsePaneOptions(name, kw) insertPos = self._nameToIndex(before) atEnd = (insertPos == len(self._paneNames)) # Add the frame. self._paneNames[insertPos:insertPos] = [name] self._frame[name] = self.createcomponent(name, (), 'Frame', Tkinter.Frame, (self.interior(),)) # Add separator, if necessary. if len(self._paneNames) > 1: self._addSeparator() else: self._separator.append(None) self._button.append(None) # Add the new frame and adjust the PanedWidget if atEnd: size = self._size[name] if size > 0 or self._relsize[name] is not None: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, height=size, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, width=size, x=self._totalSize) else: if self['orient'] == 'vertical': self._frame[name].place(x=0, relwidth=1, y=self._totalSize) else: self._frame[name].place(y=0, relheight=1, x=self._totalSize) else: self._updateSizes() self._totalSize = self._totalSize + self._size[name] return self._frame[name] def add(self, name, **kw): return apply(self.insert, (name, len(self._paneNames)), kw) def delete(self, name): deletePos = self._nameToIndex(name) name = self._paneNames[deletePos] self.destroycomponent(name) del self._paneNames[deletePos] del self._frame[name] del self._size[name] del self._min[name] del self._max[name] del self._relsize[name] del self._relmin[name] del self._relmax[name] last = len(self._paneNames) del self._separator[last] del self._button[last] if last > 0: self.destroycomponent(self._sepName(last)) self.destroycomponent(self._buttonName(last)) self._plotHandles() def setnaturalsize(self): self.update_idletasks() totalWidth = 0 totalHeight = 0 maxWidth = 0 maxHeight = 0 for name in self._paneNames: frame = self._frame[name] w = frame.winfo_reqwidth() h = frame.winfo_reqheight() totalWidth = totalWidth + w totalHeight = totalHeight + h if maxWidth < w: maxWidth = w if maxHeight < h: maxHeight = h # Note that, since the hull is a frame, the width and height # options specify the geometry *outside* the borderwidth and # highlightthickness. bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 if str(self.cget('orient')) == 'horizontal': totalWidth = totalWidth + extra maxHeight = maxHeight + extra self.configure(hull_width = totalWidth, hull_height = maxHeight) else: totalHeight = (totalHeight + extra + (len(self._paneNames) - 1) * self._separatorThickness) maxWidth = maxWidth + extra self.configure(hull_width = maxWidth, hull_height = totalHeight) def move(self, name, newPos, newPosOffset = 0): # see if we can spare ourselves some work numPanes = len(self._paneNames) if numPanes < 2: return newPos = self._nameToIndex(newPos) + newPosOffset if newPos < 0 or newPos >=numPanes: return deletePos = self._nameToIndex(name) if deletePos == newPos: # inserting over ourself is a no-op return # delete name from old position in list name = self._paneNames[deletePos] del self._paneNames[deletePos] # place in new position self._paneNames[newPos:newPos] = [name] # force everything to redraw self._plotHandles() self._updateSizes() def _nameToIndex(self, nameOrIndex): try: pos = self._paneNames.index(nameOrIndex) except ValueError: pos = nameOrIndex return pos def _initPaneOptions(self, name): # Set defaults. self._size[name] = 0 self._relsize[name] = None self._min[name] = 0 self._relmin[name] = None self._max[name] = 100000 self._relmax[name] = None def _parsePaneOptions(self, name, args): # Parse <args> for options. for arg, value in args.items(): if type(value) == types.FloatType: relvalue = value value = self._absSize(relvalue) else: relvalue = None if arg == 'size': self._size[name], self._relsize[name] = value, relvalue elif arg == 'min': self._min[name], self._relmin[name] = value, relvalue elif arg == 'max': self._max[name], self._relmax[name] = value, relvalue else: raise ValueError, 'keyword must be "size", "min", or "max"' def _absSize(self, relvalue): return int(round(relvalue * self._majorSize)) def _sepName(self, n): return 'separator-%d' % n def _buttonName(self, n): return 'handle-%d' % n def _addSeparator(self): n = len(self._paneNames) - 1 downFunc = lambda event, s = self, num=n: s._btnDown(event, num) upFunc = lambda event, s = self, num=n: s._btnUp(event, num) moveFunc = lambda event, s = self, num=n: s._btnMove(event, num) # Create the line dividing the panes. sep = self.createcomponent(self._sepName(n), (), 'Separator', Tkinter.Frame, (self.interior(),), borderwidth = 1, relief = self['separatorrelief']) self._separator.append(sep) sep.bind('<ButtonPress-1>', downFunc) sep.bind('<Any-ButtonRelease-1>', upFunc) sep.bind('<B1-Motion>', moveFunc) if self['orient'] == 'vertical': cursor = 'sb_v_double_arrow' sep.configure(height = self._separatorThickness, width = 10000, cursor = cursor) else: cursor = 'sb_h_double_arrow' sep.configure(width = self._separatorThickness, height = 10000, cursor = cursor) self._totalSize = self._totalSize + self._separatorThickness # Create the handle on the dividing line. handle = self.createcomponent(self._buttonName(n), (), 'Handle', Tkinter.Frame, (self.interior(),), relief = 'raised', borderwidth = 1, width = self._handleSize, height = self._handleSize, cursor = cursor, ) self._button.append(handle) handle.bind('<ButtonPress-1>', downFunc) handle.bind('<Any-ButtonRelease-1>', upFunc) handle.bind('<B1-Motion>', moveFunc) self._plotHandles() for i in range(1, len(self._paneNames)): self._separator[i].tkraise() for i in range(1, len(self._paneNames)): self._button[i].tkraise() def _btnUp(self, event, item): self._buttonIsDown = 0 self._updateSizes() try: self._button[item].configure(relief='raised') except: pass def _btnDown(self, event, item): self._button[item].configure(relief='sunken') self._getMotionLimit(item) self._buttonIsDown = 1 self._movePending = 0 def _handleConfigure(self, event = None): self._getNaturalSizes() if self._totalSize == 0: return iterRange = list(self._paneNames) iterRange.reverse() if self._majorSize > self._totalSize: n = self._majorSize - self._totalSize self._iterate(iterRange, self._grow, n) elif self._majorSize < self._totalSize: n = self._totalSize - self._majorSize self._iterate(iterRange, self._shrink, n) self._plotHandles() self._updateSizes() def _getNaturalSizes(self): # Must call this in order to get correct winfo_width, winfo_height self.update_idletasks() self._totalSize = 0 if self['orient'] == 'vertical': self._majorSize = self.winfo_height() self._minorSize = self.winfo_width() majorspec = Tkinter.Frame.winfo_reqheight else: self._majorSize = self.winfo_width() self._minorSize = self.winfo_height() majorspec = Tkinter.Frame.winfo_reqwidth bw = string.atoi(str(self.cget('hull_borderwidth'))) hl = string.atoi(str(self.cget('hull_highlightthickness'))) extra = (bw + hl) * 2 self._majorSize = self._majorSize - extra self._minorSize = self._minorSize - extra if self._majorSize < 0: self._majorSize = 0 if self._minorSize < 0: self._minorSize = 0 for name in self._paneNames: # adjust the absolute sizes first... if self._relsize[name] is None: #special case if self._size[name] == 0: self._size[name] = apply(majorspec, (self._frame[name],)) self._setrel(name) else: self._size[name] = self._absSize(self._relsize[name]) if self._relmin[name] is not None: self._min[name] = self._absSize(self._relmin[name]) if self._relmax[name] is not None: self._max[name] = self._absSize(self._relmax[name]) # now adjust sizes if self._size[name] < self._min[name]: self._size[name] = self._min[name] self._setrel(name) if self._size[name] > self._max[name]: self._size[name] = self._max[name] self._setrel(name) self._totalSize = self._totalSize + self._size[name] # adjust for separators self._totalSize = (self._totalSize + (len(self._paneNames) - 1) * self._separatorThickness) def _setrel(self, name): if self._relsize[name] is not None: if self._majorSize != 0: self._relsize[name] = round(self._size[name]) / self._majorSize def _iterate(self, names, proc, n): for i in names: n = apply(proc, (i, n)) if n == 0: break def _grow(self, name, n): canGrow = self._max[name] - self._size[name] if canGrow > n: self._size[name] = self._size[name] + n self._setrel(name) return 0 elif canGrow > 0: self._size[name] = self._max[name] self._setrel(name) n = n - canGrow return n def _shrink(self, name, n): canShrink = self._size[name] - self._min[name] if canShrink > n: self._size[name] = self._size[name] - n self._setrel(name) return 0 elif canShrink > 0: self._size[name] = self._min[name] self._setrel(name) n = n - canShrink return n def _updateSizes(self): totalSize = 0 for name in self._paneNames: size = self._size[name] if self['orient'] == 'vertical': self._frame[name].place(x = 0, relwidth = 1, y = totalSize, height = size) else: self._frame[name].place(y = 0, relheight = 1, x = totalSize, width = size) totalSize = totalSize + size + self._separatorThickness # Invoke the callback command cmd = self['command'] if callable(cmd): cmd(map(lambda x, s = self: s._size[x], self._paneNames)) def _plotHandles(self): if len(self._paneNames) == 0: return if self['orient'] == 'vertical': btnp = self._minorSize - 13 else: h = self._minorSize if h > 18: btnp = 9 else: btnp = h - 9 firstPane = self._paneNames[0] totalSize = self._size[firstPane] first = 1 last = len(self._paneNames) - 1 # loop from first to last, inclusive for i in range(1, last + 1): handlepos = totalSize - 3 prevSize = self._size[self._paneNames[i - 1]] nextSize = self._size[self._paneNames[i]] offset1 = 0 if i == first: if prevSize < 4: offset1 = 4 - prevSize else: if prevSize < 8: offset1 = (8 - prevSize) / 2 offset2 = 0 if i == last: if nextSize < 4: offset2 = nextSize - 4 else: if nextSize < 8: offset2 = (nextSize - 8) / 2 handlepos = handlepos + offset1 if self['orient'] == 'vertical': height = 8 - offset1 + offset2 if height > 1: self._button[i].configure(height = height) self._button[i].place(x = btnp, y = handlepos) else: self._button[i].place_forget() self._separator[i].place(x = 0, y = totalSize, relwidth = 1) else: width = 8 - offset1 + offset2 if width > 1: self._button[i].configure(width = width) self._button[i].place(y = btnp, x = handlepos) else: self._button[i].place_forget() self._separator[i].place(y = 0, x = totalSize, relheight = 1) totalSize = totalSize + nextSize + self._separatorThickness def pane(self, name): return self._frame[self._paneNames[self._nameToIndex(name)]] # Return the name of all panes def panes(self): return list(self._paneNames) def configurepane(self, name, **kw): name = self._paneNames[self._nameToIndex(name)] self._parsePaneOptions(name, kw) self._handleConfigure() def updatelayout(self): self._handleConfigure() def _getMotionLimit(self, item): curBefore = (item - 1) * self._separatorThickness minBefore, maxBefore = curBefore, curBefore for name in self._paneNames[:item]: curBefore = curBefore + self._size[name] minBefore = minBefore + self._min[name] maxBefore = maxBefore + self._max[name] curAfter = (len(self._paneNames) - item) * self._separatorThickness minAfter, maxAfter = curAfter, curAfter for name in self._paneNames[item:]: curAfter = curAfter + self._size[name] minAfter = minAfter + self._min[name] maxAfter = maxAfter + self._max[name] beforeToGo = min(curBefore - minBefore, maxAfter - curAfter) afterToGo = min(curAfter - minAfter, maxBefore - curBefore) self._beforeLimit = curBefore - beforeToGo self._afterLimit = curBefore + afterToGo self._curSize = curBefore self._plotHandles() # Compress the motion so that update is quick even on slow machines # # theRootp = root position (either rootx or rooty) def _btnMove(self, event, item): self._rootp = event if self._movePending == 0: self._timerId = self.after_idle( lambda s = self, i = item: s._btnMoveCompressed(i)) self._movePending = 1 def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) def _btnMoveCompressed(self, item): if not self._buttonIsDown: return if self['orient'] == 'vertical': p = self._rootp.y_root - self.winfo_rooty() else: p = self._rootp.x_root - self.winfo_rootx() if p == self._curSize: self._movePending = 0 return if p < self._beforeLimit: p = self._beforeLimit if p >= self._afterLimit: p = self._afterLimit self._calculateChange(item, p) self.update_idletasks() self._movePending = 0 # Calculate the change in response to mouse motions def _calculateChange(self, item, p): if p < self._curSize: self._moveBefore(item, p) elif p > self._curSize: self._moveAfter(item, p) self._plotHandles() def _moveBefore(self, item, p): n = self._curSize - p # Shrink the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._shrink, n) # Adjust the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._grow, n) self._curSize = p def _moveAfter(self, item, p): n = p - self._curSize # Shrink the frames after iterRange = self._paneNames[item:] self._iterate(iterRange, self._shrink, n) # Adjust the frames before iterRange = list(self._paneNames[:item]) iterRange.reverse() self._iterate(iterRange, self._grow, n) self._curSize = p ###################################################################### ### File: PmwPromptDialog.py # Based on iwidgets2.2.0/promptdialog.itk code. # A Dialog with an entryfield class PromptDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('entry', 'entryfield_entry'), ('label', 'entryfield_label'), ) self._promptDialogEntry = self.createcomponent('entryfield', aliases, None, EntryField, (interior,)) self._promptDialogEntry.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # EntryField's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._promptDialogEntry.insert(index, text) def deleteentry(self, first, last=None): self._promptDialogEntry.delete(first, last) def indexentry(self, index): return self._promptDialogEntry.index(index) forwardmethods(PromptDialog, EntryField, '_promptDialogEntry') ###################################################################### ### File: PmwRadioSelect.py import types import Tkinter class RadioSelect(MegaWidget): # A collection of several buttons. In single mode, only one # button may be selected. In multiple mode, any number of buttons # may be selected. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('buttontype', 'button', INITOPT), ('command', None, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 5, INITOPT), ('pady', 5, INITOPT), ('selectmode', 'single', INITOPT), ) self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',)) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['labelpos'] is None: self._radioSelectFrame = self._hull else: self._radioSelectFrame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,)) self._radioSelectFrame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Initialise instance variables. self._buttonList = [] if self['selectmode'] == 'single': self._singleSelect = 1 elif self['selectmode'] == 'multiple': self._singleSelect = 0 else: raise ValueError, 'bad selectmode option "' + \ self['selectmode'] + '": should be single or multiple' if self['buttontype'] == 'button': self.buttonClass = Tkinter.Button elif self['buttontype'] == 'radiobutton': self._singleSelect = 1 self.var = Tkinter.StringVar() self.buttonClass = Tkinter.Radiobutton elif self['buttontype'] == 'checkbutton': self._singleSelect = 0 self.buttonClass = Tkinter.Checkbutton else: raise ValueError, 'bad buttontype option "' + \ self['buttontype'] + \ '": should be button, radiobutton or checkbutton' if self._singleSelect: self.selection = None else: self.selection = [] if self['orient'] not in ('horizontal', 'vertical'): raise ValueError, 'bad orient option ' + repr(self['orient']) + \ ': must be either \'horizontal\' or \'vertical\'' # Check keywords and initialise options. self.initialiseoptions() def getcurselection(self): if self._singleSelect: return self.selection else: return tuple(self.selection) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): if self._singleSelect: self.__setSingleValue(textOrList) else: # Multiple selections oldselection = self.selection self.selection = textOrList for button in self._buttonList: if button in oldselection: if button not in self.selection: # button is currently selected but should not be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.deselect() else: # Button widget.configure(relief='raised') else: if button in self.selection: # button is not currently selected but should be widget = self.component(button) if self['buttontype'] == 'checkbutton': widget.select() else: # Button widget.configure(relief='sunken') def numbuttons(self): return len(self._buttonList) def index(self, index): # Return the integer index of the button with the given index. listLength = len(self._buttonList) if type(index) == types.IntType: if index < listLength: return index else: raise ValueError, 'index "%s" is out of range' % index elif index is END: if listLength > 0: return listLength - 1 else: raise ValueError, 'RadioSelect has no buttons' else: for count in range(listLength): name = self._buttonList[count] if index == name: return count validValues = 'a name, a number or END' raise ValueError, \ 'bad index "%s": must be %s' % (index, validValues) def button(self, buttonIndex): name = self._buttonList[self.index(buttonIndex)] return self.component(name) def add(self, componentName, **kw): if componentName in self._buttonList: raise ValueError, 'button "%s" already exists' % componentName kw['command'] = \ lambda self=self, name=componentName: self.invoke(name) if not kw.has_key('text'): kw['text'] = componentName if self['buttontype'] == 'radiobutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' if not kw.has_key('variable'): kw['variable'] = self.var if not kw.has_key('value'): kw['value'] = kw['text'] elif self['buttontype'] == 'checkbutton': if not kw.has_key('anchor'): kw['anchor'] = 'w' button = apply(self.createcomponent, (componentName, (), 'Button', self.buttonClass, (self._radioSelectFrame,)), kw) if self['orient'] == 'horizontal': self._radioSelectFrame.grid_rowconfigure(0, weight=1) col = len(self._buttonList) button.grid(column=col, row=0, padx = self['padx'], pady = self['pady'], sticky='nsew') self._radioSelectFrame.grid_columnconfigure(col, weight=1) else: self._radioSelectFrame.grid_columnconfigure(0, weight=1) row = len(self._buttonList) button.grid(column=0, row=row, padx = self['padx'], pady = self['pady'], sticky='ew') self._radioSelectFrame.grid_rowconfigure(row, weight=1) self._buttonList.append(componentName) return button def deleteall(self): for name in self._buttonList: self.destroycomponent(name) self._buttonList = [] if self._singleSelect: self.selection = None else: self.selection = [] def __setSingleValue(self, value): self.selection = value if self['buttontype'] == 'radiobutton': widget = self.component(value) widget.select() else: # Button for button in self._buttonList: widget = self.component(button) if button == value: widget.configure(relief='sunken') else: widget.configure(relief='raised') def invoke(self, index): index = self.index(index) name = self._buttonList[index] if self._singleSelect: self.__setSingleValue(name) command = self['command'] if callable(command): return command(name) else: # Multiple selections widget = self.component(name) if name in self.selection: if self['buttontype'] == 'checkbutton': widget.deselect() else: widget.configure(relief='raised') self.selection.remove(name) state = 0 else: if self['buttontype'] == 'checkbutton': widget.select() else: widget.configure(relief='sunken') self.selection.append(name) state = 1 command = self['command'] if callable(command): return command(name, state) ###################################################################### ### File: PmwScrolledCanvas.py import Tkinter class ScrolledCanvas(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('canvasmargin', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the canvas. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._canvas.pack(fill = 'both', expand = 1) else: # Create the canvas widget. self._canvas = self.createcomponent('canvas', (), None, Tkinter.Canvas, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._canvas.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self._canvas.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self._canvas.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.setregionTimer = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None if self.setregionTimer is not None: self.after_cancel(self.setregionTimer) self.setregionTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._canvas def resizescrollregion(self): if self.setregionTimer is None: self.setregionTimer = self.after_idle(self._setRegion) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._canvas.cget('xscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) tclCommandName = str(self._canvas.cget('yscrollcommand')) if tclCommandName != '': self._canvas.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._canvas.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._canvas.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the canvas to set the horizontal or vertical # scrollbar when it has scrolled or changed scrollregion. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._canvas.xview() yview = self._canvas.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _setRegion(self): self.setregionTimer = None region = self._canvas.bbox('all') if region is not None: canvasmargin = self['canvasmargin'] region = (region[0] - canvasmargin, region[1] - canvasmargin, region[2] + canvasmargin, region[3] + canvasmargin) self._canvas.configure(scrollregion = region) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, *args): return apply(self._canvas.bbox, args) forwardmethods(ScrolledCanvas, Tkinter.Canvas, '_canvas') ###################################################################### ### File: PmwScrolledField.py import Tkinter class ScrolledField(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('sticky', 'ew', INITOPT), ('text', '', self._text), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._scrolledFieldEntry = self.createcomponent('entry', (), None, Tkinter.Entry, (interior,)) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') self._scrolledFieldEntry.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) self.createlabel(interior) # Check keywords and initialise options. self.initialiseoptions() def _text(self): text = self['text'] self._scrolledFieldEntry.configure(state = 'normal') self._scrolledFieldEntry.delete(0, 'end') self._scrolledFieldEntry.insert('end', text) # Can't always use 'disabled', since this greys out text in Tk 8.4.2 try: self._scrolledFieldEntry.configure(state = 'readonly') except Tkinter.TclError: self._scrolledFieldEntry.configure(state = 'disabled') forwardmethods(ScrolledField, Tkinter.Entry, '_scrolledFieldEntry') ###################################################################### ### File: PmwScrolledFrame.py import string import types import Tkinter class ScrolledFrame(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 1, INITOPT), ('horizflex', 'fixed', self._horizflex), ('horizfraction', 0.05, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vertflex', 'fixed', self._vertflex), ('vertfraction', 0.05, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. self.origInterior = MegaWidget.interior(self) if self['usehullsize']: self.origInterior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the clipper. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (self.origInterior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 2, column = 2, sticky = 'news') # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self._borderframe,), width = 400, height = 300, highlightthickness = 0, borderwidth = 0, ) self._clipper.pack(fill = 'both', expand = 1) else: # Create the clipping window. self._clipper = self.createcomponent('clipper', (), None, Tkinter.Frame, (self.origInterior,), width = 400, height = 300, relief = 'sunken', borderwidth = 2, ) self._clipper.grid(row = 2, column = 2, sticky = 'news') self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0) self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='horizontal', command=self.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (self.origInterior,), orient='vertical', command=self.yview ) self.createlabel(self.origInterior, childCols = 3, childRows = 3) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self.startX = 0 self.startY = 0 self._flexoptions = ('fixed', 'expand', 'shrink', 'elastic') # Create a frame in the clipper to contain the widgets to be # scrolled. self._frame = self.createcomponent('frame', (), None, Tkinter.Frame, (self._clipper,) ) # Whenever the clipping window or scrolled frame change size, # update the scrollbars. self._frame.bind('<Configure>', self._reposition) self._clipper.bind('<Configure>', self._reposition) # Work around a bug in Tk where the value returned by the # scrollbar get() method is (0.0, 0.0, 0.0, 0.0) rather than # the expected 2-tuple. This occurs if xview() is called soon # after the ScrolledFrame has been created. self._horizScrollbar.set(0.0, 1.0) self._vertScrollbar.set(0.0, 1.0) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def interior(self): return self._frame # Set timer to call real reposition method, so that it is not # called multiple times when many things are reconfigured at the # same time. def reposition(self): if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) # Called when the user clicks in the horizontal scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def xview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._horizScrollbar.get() elif mode == 'moveto': frameWidth = self._frame.winfo_reqwidth() self.startX = value * float(frameWidth) else: # mode == 'scroll' clipperWidth = self._clipper.winfo_width() if units == 'units': jump = int(clipperWidth * self['horizfraction']) else: jump = clipperWidth self.startX = self.startX + value * jump self.reposition() # Called when the user clicks in the vertical scrollbar. # Calculates new position of frame then calls reposition() to # update the frame and the scrollbar. def yview(self, mode = None, value = None, units = None): if type(value) == types.StringType: value = string.atof(value) if mode is None: return self._vertScrollbar.get() elif mode == 'moveto': frameHeight = self._frame.winfo_reqheight() self.startY = value * float(frameHeight) else: # mode == 'scroll' clipperHeight = self._clipper.winfo_height() if units == 'units': jump = int(clipperHeight * self['vertfraction']) else: jump = clipperHeight self.startY = self.startY + value * jump self.reposition() # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message def _horizflex(self): # The horizontal flex mode has been configured. flex = self['horizflex'] if flex not in self._flexoptions: message = 'bad horizflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() def _vertflex(self): # The vertical flex mode has been configured. flex = self['vertflex'] if flex not in self._flexoptions: message = 'bad vertflex option "%s": should be one of %s' % \ (flex, str(self._flexoptions)) raise ValueError, message self.reposition() # ====================================================================== # Private methods. def _reposition(self, event): self.reposition() def _getxview(self): # Horizontal dimension. clipperWidth = self._clipper.winfo_width() frameWidth = self._frame.winfo_reqwidth() if frameWidth <= clipperWidth: # The scrolled frame is smaller than the clipping window. self.startX = 0 endScrollX = 1.0 if self['horizflex'] in ('expand', 'elastic'): relwidth = 1 else: relwidth = '' else: # The scrolled frame is larger than the clipping window. if self['horizflex'] in ('shrink', 'elastic'): self.startX = 0 endScrollX = 1.0 relwidth = 1 else: if self.startX + clipperWidth > frameWidth: self.startX = frameWidth - clipperWidth endScrollX = 1.0 else: if self.startX < 0: self.startX = 0 endScrollX = (self.startX + clipperWidth) / float(frameWidth) relwidth = '' # Position frame relative to clipper. self._frame.place(x = -self.startX, relwidth = relwidth) return (self.startX / float(frameWidth), endScrollX) def _getyview(self): # Vertical dimension. clipperHeight = self._clipper.winfo_height() frameHeight = self._frame.winfo_reqheight() if frameHeight <= clipperHeight: # The scrolled frame is smaller than the clipping window. self.startY = 0 endScrollY = 1.0 if self['vertflex'] in ('expand', 'elastic'): relheight = 1 else: relheight = '' else: # The scrolled frame is larger than the clipping window. if self['vertflex'] in ('shrink', 'elastic'): self.startY = 0 endScrollY = 1.0 relheight = 1 else: if self.startY + clipperHeight > frameHeight: self.startY = frameHeight - clipperHeight endScrollY = 1.0 else: if self.startY < 0: self.startY = 0 endScrollY = (self.startY + clipperHeight) / float(frameHeight) relheight = '' # Position frame relative to clipper. self._frame.place(y = -self.startY, relheight = relheight) return (self.startY / float(frameHeight), endScrollY) # According to the relative geometries of the frame and the # clipper, reposition the frame within the clipper and reset the # scrollbars. def _scrollBothNow(self): self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._getxview() yview = self._getyview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.origInterior if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.origInterior if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) ###################################################################### ### File: PmwScrolledListBox.py # Based on iwidgets2.2.0/scrolledlistbox.itk code. import types import Tkinter class ScrolledListBox(MegaWidget): _classBindingsDefinedFor = 0 def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('dblclickcommand', None, None), ('hscrollmode', 'dynamic', self._hscrollMode), ('items', (), INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('scrollmargin', 2, INITOPT), ('selectioncommand', None, None), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) # Create the listbox widget. self._listbox = self.createcomponent('listbox', (), None, Tkinter.Listbox, (interior,)) self._listbox.grid(row = 2, column = 2, sticky = 'news') interior.grid_rowconfigure(2, weight = 1, minsize = 0) interior.grid_columnconfigure(2, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._listbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._listbox.yview ) self.createlabel(interior, childCols = 3, childRows = 3) # Add the items specified by the initialisation option. items = self['items'] if type(items) != types.TupleType: items = tuple(items) if len(items) > 0: apply(self._listbox.insert, ('end',) + items) _registerScrolledList(self._listbox, self) # Establish the special class bindings if not already done. # Also create bindings if the Tkinter default interpreter has # changed. Use Tkinter._default_root to create class # bindings, so that a reference to root is created by # bind_class rather than a reference to self, which would # prevent object cleanup. theTag = 'ScrolledListBoxTag' if ScrolledListBox._classBindingsDefinedFor != Tkinter._default_root: root = Tkinter._default_root def doubleEvent(event): _handleEvent(event, 'double') def keyEvent(event): _handleEvent(event, 'key') def releaseEvent(event): _handleEvent(event, 'release') # Bind space and return keys and button 1 to the selectioncommand. root.bind_class(theTag, '<Key-space>', keyEvent) root.bind_class(theTag, '<Key-Return>', keyEvent) root.bind_class(theTag, '<ButtonRelease-1>', releaseEvent) # Bind double button 1 click to the dblclickcommand. root.bind_class(theTag, '<Double-ButtonRelease-1>', doubleEvent) ScrolledListBox._classBindingsDefinedFor = root bindtags = self._listbox.bindtags() self._listbox.bindtags(bindtags + (theTag,)) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None _deregisterScrolledList(self._listbox) MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.setlist(()) def getcurselection(self): rtn = [] for sel in self.curselection(): rtn.append(self._listbox.get(sel)) return tuple(rtn) def getvalue(self): return self.getcurselection() def setvalue(self, textOrList): self._listbox.selection_clear(0, 'end') listitems = list(self._listbox.get(0, 'end')) if type(textOrList) == types.StringType: if textOrList in listitems: self._listbox.selection_set(listitems.index(textOrList)) else: raise ValueError, 'no such item "%s"' % textOrList else: for item in textOrList: if item in listitems: self._listbox.selection_set(listitems.index(item)) else: raise ValueError, 'no such item "%s"' % item def setlist(self, items): self._listbox.delete(0, 'end') if len(items) > 0: if type(items) != types.TupleType: items = tuple(items) apply(self._listbox.insert, (0,) + items) # Override Tkinter.Listbox get method, so that if it is called with # no arguments, return all list elements (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._listbox.get(0, 'end') else: return self._listbox.get(first, last) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._listbox.cget('xscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) tclCommandName = str(self._listbox.cget('yscrollcommand')) if tclCommandName != '': self._listbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._listbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._listbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() def _scrollYNow(self, first, last): self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _scrollBothLater(self, first, last): # Called by the listbox to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._listbox.xview() yview = self._listbox.yview() self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news') interior.grid_rowconfigure(3, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(3, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news') interior.grid_columnconfigure(3, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(3, minsize = 0) def _handleEvent(self, event, eventType): if eventType == 'double': command = self['dblclickcommand'] elif eventType == 'key': command = self['selectioncommand'] else: #eventType == 'release' # Do not execute the command if the mouse was released # outside the listbox. if (event.x < 0 or self._listbox.winfo_width() <= event.x or event.y < 0 or self._listbox.winfo_height() <= event.y): return command = self['selectioncommand'] if callable(command): command() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._listbox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._listbox.bbox(index) forwardmethods(ScrolledListBox, Tkinter.Listbox, '_listbox') # ====================================================================== _listboxCache = {} def _registerScrolledList(listbox, scrolledList): # Register an ScrolledList widget for a Listbox widget _listboxCache[listbox] = scrolledList def _deregisterScrolledList(listbox): # Deregister a Listbox widget del _listboxCache[listbox] def _handleEvent(event, eventType): # Forward events for a Listbox to it's ScrolledListBox # A binding earlier in the bindtags list may have destroyed the # megawidget, so need to check. if _listboxCache.has_key(event.widget): _listboxCache[event.widget]._handleEvent(event, eventType) ###################################################################### ### File: PmwScrolledText.py # Based on iwidgets2.2.0/scrolledtext.itk code. import Tkinter class ScrolledText(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderframe', 0, INITOPT), ('columnheader', 0, INITOPT), ('hscrollmode', 'dynamic', self._hscrollMode), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('rowcolumnheader',0, INITOPT), ('rowheader', 0, INITOPT), ('scrollmargin', 2, INITOPT), ('usehullsize', 0, INITOPT), ('vscrollmode', 'dynamic', self._vscrollMode), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() if self['usehullsize']: interior.grid_propagate(0) if self['borderframe']: # Create a frame widget to act as the border of the text # widget. Later, pack the text widget so that it fills # the frame. This avoids a problem in Tk, where window # items in a text widget may overlap the border of the # text widget. self._borderframe = self.createcomponent('borderframe', (), None, Tkinter.Frame, (interior,), relief = 'sunken', borderwidth = 2, ) self._borderframe.grid(row = 4, column = 4, sticky = 'news') # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (self._borderframe,), highlightthickness = 0, borderwidth = 0, ) self._textbox.pack(fill = 'both', expand = 1) bw = self._borderframe.cget('borderwidth'), ht = self._borderframe.cget('highlightthickness'), else: # Create the text widget. self._textbox = self.createcomponent('text', (), None, Tkinter.Text, (interior,), ) self._textbox.grid(row = 4, column = 4, sticky = 'news') bw = self._textbox.cget('borderwidth'), ht = self._textbox.cget('highlightthickness'), # Create the header text widgets if self['columnheader']: self._columnheader = self.createcomponent('columnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._columnheader.grid(row = 2, column = 4, sticky = 'ew') self._columnheader.configure( xscrollcommand = self._columnheaderscrolled) if self['rowheader']: self._rowheader = self.createcomponent('rowheader', (), 'Header', Tkinter.Text, (interior,), wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowheader.grid(row = 4, column = 2, sticky = 'ns') self._rowheader.configure( yscrollcommand = self._rowheaderscrolled) if self['rowcolumnheader']: self._rowcolumnheader = self.createcomponent('rowcolumnheader', (), 'Header', Tkinter.Text, (interior,), height=1, wrap='none', borderwidth = bw, highlightthickness = ht, ) self._rowcolumnheader.grid(row = 2, column = 2, sticky = 'nsew') interior.grid_rowconfigure(4, weight = 1, minsize = 0) interior.grid_columnconfigure(4, weight = 1, minsize = 0) # Create the horizontal scrollbar self._horizScrollbar = self.createcomponent('horizscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='horizontal', command=self._textbox.xview ) # Create the vertical scrollbar self._vertScrollbar = self.createcomponent('vertscrollbar', (), 'Scrollbar', Tkinter.Scrollbar, (interior,), orient='vertical', command=self._textbox.yview ) self.createlabel(interior, childCols = 5, childRows = 5) # Initialise instance variables. self._horizScrollbarOn = 0 self._vertScrollbarOn = 0 self.scrollTimer = None self._scrollRecurse = 0 self._horizScrollbarNeeded = 0 self._vertScrollbarNeeded = 0 self._textWidth = None # These four variables avoid an infinite loop caused by the # row or column header's scrollcommand causing the main text # widget's scrollcommand to be called and vice versa. self._textboxLastX = None self._textboxLastY = None self._columnheaderLastX = None self._rowheaderLastY = None # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self.scrollTimer is not None: self.after_cancel(self.scrollTimer) self.scrollTimer = None MegaWidget.destroy(self) # ====================================================================== # Public methods. def clear(self): self.settext('') def importfile(self, fileName, where = 'end'): file = open(fileName, 'r') self._textbox.insert(where, file.read()) file.close() def exportfile(self, fileName): file = open(fileName, 'w') file.write(self._textbox.get('1.0', 'end')) file.close() def settext(self, text): disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.delete('0.0', 'end') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') # Override Tkinter.Text get method, so that if it is called with # no arguments, return all text (consistent with other widgets). def get(self, first=None, last=None): if first is None: return self._textbox.get('1.0', 'end') else: return self._textbox.get(first, last) def getvalue(self): return self.get() def setvalue(self, text): return self.settext(text) def appendtext(self, text): oldTop, oldBottom = self._textbox.yview() disabled = (str(self._textbox.cget('state')) == 'disabled') if disabled: self._textbox.configure(state='normal') self._textbox.insert('end', text) if disabled: self._textbox.configure(state='disabled') if oldBottom == 1.0: self._textbox.yview('moveto', 1.0) # ====================================================================== # Configuration methods. def _hscrollMode(self): # The horizontal scroll mode has been configured. mode = self['hscrollmode'] if mode == 'static': if not self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'dynamic': if self._horizScrollbarNeeded != self._horizScrollbarOn: self._toggleHorizScrollbar() elif mode == 'none': if self._horizScrollbarOn: self._toggleHorizScrollbar() else: message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() def _vscrollMode(self): # The vertical scroll mode has been configured. mode = self['vscrollmode'] if mode == 'static': if not self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() elif mode == 'none': if self._vertScrollbarOn: self._toggleVertScrollbar() else: message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode raise ValueError, message self._configureScrollCommands() # ====================================================================== # Private methods. def _configureScrollCommands(self): # If both scrollmodes are not dynamic we can save a lot of # time by not having to create an idle job to handle the # scroll commands. # Clean up previous scroll commands to prevent memory leak. tclCommandName = str(self._textbox.cget('xscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) tclCommandName = str(self._textbox.cget('yscrollcommand')) if tclCommandName != '': self._textbox.deletecommand(tclCommandName) if self['hscrollmode'] == self['vscrollmode'] == 'dynamic': self._textbox.configure( xscrollcommand=self._scrollBothLater, yscrollcommand=self._scrollBothLater ) else: self._textbox.configure( xscrollcommand=self._scrollXNow, yscrollcommand=self._scrollYNow ) def _scrollXNow(self, first, last): self._horizScrollbar.set(first, last) self._horizScrollbarNeeded = ((first, last) != ('0', '1')) # This code is the same as in _scrollBothNow. Keep it that way. if self['hscrollmode'] == 'dynamic': currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['columnheader']: if self._columnheaderLastX != first: self._columnheaderLastX = first self._columnheader.xview('moveto', first) def _scrollYNow(self, first, last): if first == '0' and last == '0': return self._vertScrollbar.set(first, last) self._vertScrollbarNeeded = ((first, last) != ('0', '1')) if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() if self['rowheader']: if self._rowheaderLastY != first: self._rowheaderLastY = first self._rowheader.yview('moveto', first) def _scrollBothLater(self, first, last): # Called by the text widget to set the horizontal or vertical # scrollbar when it has scrolled or changed size or contents. if self.scrollTimer is None: self.scrollTimer = self.after_idle(self._scrollBothNow) def _scrollBothNow(self): # This performs the function of _scrollXNow and _scrollYNow. # If one is changed, the other should be updated to match. self.scrollTimer = None # Call update_idletasks to make sure that the containing frame # has been resized before we attempt to set the scrollbars. # Otherwise the scrollbars may be mapped/unmapped continuously. self._scrollRecurse = self._scrollRecurse + 1 self.update_idletasks() self._scrollRecurse = self._scrollRecurse - 1 if self._scrollRecurse != 0: return xview = self._textbox.xview() yview = self._textbox.yview() # The text widget returns a yview of (0.0, 0.0) just after it # has been created. Ignore this. if yview == (0.0, 0.0): return if self['columnheader']: if self._columnheaderLastX != xview[0]: self._columnheaderLastX = xview[0] self._columnheader.xview('moveto', xview[0]) if self['rowheader']: if self._rowheaderLastY != yview[0]: self._rowheaderLastY = yview[0] self._rowheader.yview('moveto', yview[0]) self._horizScrollbar.set(xview[0], xview[1]) self._vertScrollbar.set(yview[0], yview[1]) self._horizScrollbarNeeded = (xview != (0.0, 1.0)) self._vertScrollbarNeeded = (yview != (0.0, 1.0)) # If both horizontal and vertical scrollmodes are dynamic and # currently only one scrollbar is mapped and both should be # toggled, then unmap the mapped scrollbar. This prevents a # continuous mapping and unmapping of the scrollbars. if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and self._horizScrollbarNeeded != self._horizScrollbarOn and self._vertScrollbarNeeded != self._vertScrollbarOn and self._vertScrollbarOn != self._horizScrollbarOn): if self._horizScrollbarOn: self._toggleHorizScrollbar() else: self._toggleVertScrollbar() return if self['hscrollmode'] == 'dynamic': # The following test is done to prevent continuous # mapping and unmapping of the horizontal scrollbar. # This may occur when some event (scrolling, resizing # or text changes) modifies the displayed text such # that the bottom line in the window is the longest # line displayed. If this causes the horizontal # scrollbar to be mapped, the scrollbar may "cover up" # the bottom line, which would mean that the scrollbar # is no longer required. If the scrollbar is then # unmapped, the bottom line will then become visible # again, which would cause the scrollbar to be mapped # again, and so on... # # The idea is that, if the width of the text widget # has not changed and the scrollbar is currently # mapped, then do not unmap the scrollbar even if it # is no longer required. This means that, during # normal scrolling of the text, once the horizontal # scrollbar has been mapped it will not be unmapped # (until the width of the text widget changes). currentWidth = self._textbox.winfo_width() if self._horizScrollbarNeeded != self._horizScrollbarOn: if self._horizScrollbarNeeded or \ self._textWidth != currentWidth: self._toggleHorizScrollbar() self._textWidth = currentWidth if self['vscrollmode'] == 'dynamic': if self._vertScrollbarNeeded != self._vertScrollbarOn: self._toggleVertScrollbar() def _columnheaderscrolled(self, first, last): if self._textboxLastX != first: self._textboxLastX = first self._textbox.xview('moveto', first) def _rowheaderscrolled(self, first, last): if self._textboxLastY != first: self._textboxLastY = first self._textbox.yview('moveto', first) def _toggleHorizScrollbar(self): self._horizScrollbarOn = not self._horizScrollbarOn interior = self.interior() if self._horizScrollbarOn: self._horizScrollbar.grid(row = 6, column = 4, sticky = 'news') interior.grid_rowconfigure(5, minsize = self['scrollmargin']) else: self._horizScrollbar.grid_forget() interior.grid_rowconfigure(5, minsize = 0) def _toggleVertScrollbar(self): self._vertScrollbarOn = not self._vertScrollbarOn interior = self.interior() if self._vertScrollbarOn: self._vertScrollbar.grid(row = 4, column = 6, sticky = 'news') interior.grid_columnconfigure(5, minsize = self['scrollmargin']) else: self._vertScrollbar.grid_forget() interior.grid_columnconfigure(5, minsize = 0) # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._textbox.bbox(index) forwardmethods(ScrolledText, Tkinter.Text, '_textbox') ###################################################################### ### File: PmwHistoryText.py _ORIGINAL = 0 _MODIFIED = 1 _DISPLAY = 2 class HistoryText(ScrolledText): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('compressany', 1, None), ('compresstail', 1, None), ('historycommand', None, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). ScrolledText.__init__(self, parent) # Initialise instance variables. self._list = [] self._currIndex = 0 self._pastIndex = None self._lastIndex = 0 # pointer to end of history list # Check keywords and initialise options. self.initialiseoptions() def addhistory(self): text = self.get() if text[-1] == '\n': text = text[:-1] if len(self._list) == 0: # This is the first history entry. Add it. self._list.append([text, text, _MODIFIED]) return currentEntry = self._list[self._currIndex] if text == currentEntry[_ORIGINAL]: # The current history entry has not been modified. Check if # we need to add it again. if self['compresstail'] and self._currIndex == self._lastIndex: return if self['compressany']: return # Undo any changes for the current history entry, since they # will now be available in the new entry. currentEntry[_MODIFIED] = currentEntry[_ORIGINAL] historycommand = self['historycommand'] if self._currIndex == self._lastIndex: # The last history entry is currently being displayed, # so disable the special meaning of the 'Next' button. self._pastIndex = None nextState = 'disabled' else: # A previous history entry is currently being displayed, # so allow the 'Next' button to go to the entry after this one. self._pastIndex = self._currIndex nextState = 'normal' if callable(historycommand): historycommand('normal', nextState) # Create the new history entry. self._list.append([text, text, _MODIFIED]) # Move the pointer into the history entry list to the end. self._lastIndex = self._lastIndex + 1 self._currIndex = self._lastIndex def next(self): if self._currIndex == self._lastIndex and self._pastIndex is None: self.bell() else: self._modifyDisplay('next') def prev(self): self._pastIndex = None if self._currIndex == 0: self.bell() else: self._modifyDisplay('prev') def undo(self): if len(self._list) != 0: self._modifyDisplay('undo') def redo(self): if len(self._list) != 0: self._modifyDisplay('redo') def gethistory(self): return self._list def _modifyDisplay(self, command): # Modify the display to show either the next or previous # history entry (next, prev) or the original or modified # version of the current history entry (undo, redo). # Save the currently displayed text. currentText = self.get() if currentText[-1] == '\n': currentText = currentText[:-1] currentEntry = self._list[self._currIndex] if currentEntry[_DISPLAY] == _MODIFIED: currentEntry[_MODIFIED] = currentText elif currentEntry[_ORIGINAL] != currentText: currentEntry[_MODIFIED] = currentText if command in ('next', 'prev'): currentEntry[_DISPLAY] = _MODIFIED if command in ('next', 'prev'): prevstate = 'normal' nextstate = 'normal' if command == 'next': if self._pastIndex is not None: self._currIndex = self._pastIndex self._pastIndex = None self._currIndex = self._currIndex + 1 if self._currIndex == self._lastIndex: nextstate = 'disabled' elif command == 'prev': self._currIndex = self._currIndex - 1 if self._currIndex == 0: prevstate = 'disabled' historycommand = self['historycommand'] if callable(historycommand): historycommand(prevstate, nextstate) currentEntry = self._list[self._currIndex] else: if command == 'undo': currentEntry[_DISPLAY] = _ORIGINAL elif command == 'redo': currentEntry[_DISPLAY] = _MODIFIED # Display the new text. self.delete('1.0', 'end') self.insert('end', currentEntry[currentEntry[_DISPLAY]]) ###################################################################### ### File: PmwSelectionDialog.py # Not Based on iwidgets version. class SelectionDialog(Dialog): # Dialog window with selection list. # Dialog window displaying a list and requesting the user to # select one. def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'scrolledlist_listbox'), ('label', 'scrolledlist_label'), ) self._list = self.createcomponent('scrolledlist', aliases, None, ScrolledListBox, (interior,), dblclickcommand = self.invoke) self._list.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ScrolledListBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self.component('listbox').size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self.component('listbox').size(index) forwardmethods(SelectionDialog, ScrolledListBox, '_list') ###################################################################### ### File: PmwTextDialog.py # A Dialog with a ScrolledText widget. class TextDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('text', 'scrolledtext_text'), ('label', 'scrolledtext_label'), ) self._text = self.createcomponent('scrolledtext', aliases, None, ScrolledText, (interior,)) self._text.pack(side='top', expand=1, fill='both', padx = self['borderx'], pady = self['bordery']) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._text.bbox(index) forwardmethods(TextDialog, ScrolledText, '_text') ###################################################################### ### File: PmwTimeCounter.py # Authors: Joe VanAndel and Greg McFarlane import string import sys import time import Tkinter class TimeCounter(MegaWidget): """Up-down counter A TimeCounter is a single-line entry widget with Up and Down arrows which increment and decrement the Time value in the entry. """ def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('command', None, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('max', None, self._max), ('min', None, self._min), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('value', None, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) self.arrowDirection = {} self._flag = 'stopped' self._timerId = None self._createComponents(kw) value = self['value'] if value is None: now = time.time() value = time.strftime('%H:%M:%S', time.localtime(now)) self.setvalue(value) # Check keywords and initialise options. self.initialiseoptions() def _createComponents(self, kw): # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky='nsew') interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow buttons. # Create the hour down arrow. self._downHourArrowBtn = self.createcomponent('downhourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downHourArrowBtn] = 'down' self._downHourArrowBtn.grid(column = 0, row = 2) # Create the minute down arrow. self._downMinuteArrowBtn = self.createcomponent('downminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downMinuteArrowBtn] = 'down' self._downMinuteArrowBtn.grid(column = 1, row = 2) # Create the second down arrow. self._downSecondArrowBtn = self.createcomponent('downsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._downSecondArrowBtn] = 'down' self._downSecondArrowBtn.grid(column = 2, row = 2) # Create the entry fields. # Create the hour entry field. self._hourCounterEntry = self.createcomponent('hourentryfield', (('hourentry', 'hourentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._hourCounterEntry.grid(column = 0, row = 1, sticky = 'news') # Create the minute entry field. self._minuteCounterEntry = self.createcomponent('minuteentryfield', (('minuteentry', 'minuteentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._minuteCounterEntry.grid(column = 1, row = 1, sticky = 'news') # Create the second entry field. self._secondCounterEntry = self.createcomponent('secondentryfield', (('secondentry', 'secondentryfield_entry'),), None, EntryField, (frame,), validate='integer', entry_width = 2) self._secondCounterEntry.grid(column = 2, row = 1, sticky = 'news') # Create the up arrow buttons. # Create the hour up arrow. self._upHourArrowBtn = self.createcomponent('uphourarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upHourArrowBtn] = 'up' self._upHourArrowBtn.grid(column = 0, row = 0) # Create the minute up arrow. self._upMinuteArrowBtn = self.createcomponent('upminutearrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upMinuteArrowBtn] = 'up' self._upMinuteArrowBtn.grid(column = 1, row = 0) # Create the second up arrow. self._upSecondArrowBtn = self.createcomponent('upsecondarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) self.arrowDirection[self._upSecondArrowBtn] = 'up' self._upSecondArrowBtn.grid(column = 2, row = 0) # Make it resize nicely. padx = self['padx'] pady = self['pady'] for col in range(3): frame.grid_columnconfigure(col, weight = 1, pad = padx) frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_rowconfigure(1, weight = 1) # Create the label. self.createlabel(interior) # Set bindings. # Up hour self._upHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upHourArrowBtn: s._drawArrow(button, 'up')) self._upHourArrowBtn.bind('<1>', lambda event, s=self,button=self._upHourArrowBtn: s._countUp(button, 3600)) self._upHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upHourArrowBtn: s._stopUpDown(button)) # Up minute self._upMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upMinuteArrowBtn: s._drawArrow(button, 'up')) self._upMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._upMinuteArrowBtn: s._countUp(button, 60)) self._upMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upMinuteArrowBtn: s._stopUpDown(button)) # Up second self._upSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._upSecondArrowBtn: s._drawArrow(button, 'up')) self._upSecondArrowBtn.bind('<1>', lambda event, s=self,button=self._upSecondArrowBtn: s._countUp(button, 1)) self._upSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._upSecondArrowBtn: s._stopUpDown(button)) # Down hour self._downHourArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downHourArrowBtn: s._drawArrow(button, 'down')) self._downHourArrowBtn.bind('<1>', lambda event, s=self,button=self._downHourArrowBtn: s._countDown(button, 3600)) self._downHourArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downHourArrowBtn: s._stopUpDown(button)) # Down minute self._downMinuteArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downMinuteArrowBtn: s._drawArrow(button, 'down')) self._downMinuteArrowBtn.bind('<1>', lambda event, s=self,button=self._downMinuteArrowBtn: s._countDown(button, 60)) self._downMinuteArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downMinuteArrowBtn: s._stopUpDown(button)) # Down second self._downSecondArrowBtn.bind('<Configure>', lambda event, s=self,button=self._downSecondArrowBtn: s._drawArrow(button, 'down')) self._downSecondArrowBtn.bind('<1>', lambda event, s=self, button=self._downSecondArrowBtn: s._countDown(button,1)) self._downSecondArrowBtn.bind('<Any-ButtonRelease-1>', lambda event, s=self, button=self._downSecondArrowBtn: s._stopUpDown(button)) self._hourCounterEntry.component('entry').bind( '<Return>', self._invoke) self._minuteCounterEntry.component('entry').bind( '<Return>', self._invoke) self._secondCounterEntry.component('entry').bind( '<Return>', self._invoke) self._hourCounterEntry.bind('<Configure>', self._resizeArrow) self._minuteCounterEntry.bind('<Configure>', self._resizeArrow) self._secondCounterEntry.bind('<Configure>', self._resizeArrow) def _drawArrow(self, arrow, direction): drawarrow(arrow, self['hourentry_foreground'], direction, 'arrow') def _resizeArrow(self, event = None): for btn in (self._upHourArrowBtn, self._upMinuteArrowBtn, self._upSecondArrowBtn, self._downHourArrowBtn, self._downMinuteArrowBtn, self._downSecondArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._hourCounterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn, self.arrowDirection[btn]) def _min(self): min = self['min'] if min is None: self._minVal = 0 else: self._minVal = timestringtoseconds(min) def _max(self): max = self['max'] if max is None: self._maxVal = None else: self._maxVal = timestringtoseconds(max) def getvalue(self): return self.getstring() def setvalue(self, text): list = string.split(text, ':') if len(list) != 3: raise ValueError, 'invalid value: ' + text self._hour = string.atoi(list[0]) self._minute = string.atoi(list[1]) self._second = string.atoi(list[2]) self._setHMS() def getstring(self): return '%02d:%02d:%02d' % (self._hour, self._minute, self._second) def getint(self): return self._hour * 3600 + self._minute * 60 + self._second def _countUp(self, button, increment): self._relief = self._upHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(1, 'start', increment) def _countDown(self, button, increment): self._relief = self._downHourArrowBtn.cget('relief') button.configure(relief='sunken') self._count(-1, 'start', increment) def increment(self, seconds = 1): self._count(1, 'force', seconds) def decrement(self, seconds = 1): self._count(-1, 'force', seconds) def _count(self, factor, newFlag = None, increment = 1): if newFlag != 'force': if newFlag is not None: self._flag = newFlag if self._flag == 'stopped': return value = (string.atoi(self._hourCounterEntry.get()) *3600) + \ (string.atoi(self._minuteCounterEntry.get()) *60) + \ string.atoi(self._secondCounterEntry.get()) + \ factor * increment min = self._minVal max = self._maxVal if value < min: value = min if max is not None and value > max: value = max self._hour = value /3600 self._minute = (value - (self._hour*3600)) / 60 self._second = value - (self._hour*3600) - (self._minute*60) self._setHMS() if newFlag != 'force': if self['autorepeat']: if self._flag == 'start': delay = self['initwait'] self._flag = 'running' else: delay = self['repeatrate'] self._timerId = self.after( delay, lambda self=self, factor=factor,increment=increment: self._count(factor,'running', increment)) def _setHMS(self): self._hourCounterEntry.setentry('%02d' % self._hour) self._minuteCounterEntry.setentry('%02d' % self._minute) self._secondCounterEntry.setentry('%02d' % self._second) def _stopUpDown(self, button): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None button.configure(relief=self._relief) self._flag = 'stopped' def _invoke(self, event): cmd = self['command'] if callable(cmd): cmd() def invoke(self): cmd = self['command'] if callable(cmd): return cmd() def destroy(self): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None MegaWidget.destroy(self) ###################################################################### ### File: PmwAboutDialog.py class AboutDialog(MessageDialog): # Window to display version and contact information. # Class members containing resettable 'default' values: _version = '' _copyright = '' _contact = '' def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('applicationname', '', INITOPT), ('iconpos', 'w', None), ('icon_bitmap', 'info', None), ('buttons', ('Close',), None), ('defaultbutton', 0, None), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MessageDialog.__init__(self, parent) applicationname = self['applicationname'] if not kw.has_key('title'): self.configure(title = 'About ' + applicationname) if not kw.has_key('message_text'): text = applicationname + '\n\n' if AboutDialog._version != '': text = text + 'Version ' + AboutDialog._version + '\n' if AboutDialog._copyright != '': text = text + AboutDialog._copyright + '\n\n' if AboutDialog._contact != '': text = text + AboutDialog._contact self.configure(message_text=text) # Check keywords and initialise options. self.initialiseoptions() def aboutversion(value): AboutDialog._version = value def aboutcopyright(value): AboutDialog._copyright = value def aboutcontact(value): AboutDialog._contact = value ###################################################################### ### File: PmwComboBox.py # Based on iwidgets2.2.0/combobox.itk code. import os import string import types import Tkinter class ComboBox(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autoclear', 0, INITOPT), ('buttonaspect', 1.0, INITOPT), ('dropdown', 1, INITOPT), ('fliparrow', 0, INITOPT), ('history', 1, INITOPT), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('listheight', 200, INITOPT), ('selectioncommand', None, None), ('sticky', 'ew', INITOPT), ('unique', 1, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Create the components. interior = self.interior() self._entryfield = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (interior,)) self._entryfield.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight = 1) self._entryWidget = self._entryfield.component('entry') if self['dropdown']: self._isPosted = 0 interior.grid_rowconfigure(2, weight = 1) # Create the arrow button. self._arrowBtn = self.createcomponent('arrowbutton', (), None, Tkinter.Canvas, (interior,), borderwidth = 2, relief = 'raised', width = 16, height = 16) if 'n' in self['sticky']: sticky = 'n' else: sticky = '' if 's' in self['sticky']: sticky = sticky + 's' self._arrowBtn.grid(column=3, row=2, sticky = sticky) self._arrowRelief = self._arrowBtn.cget('relief') # Create the label. self.createlabel(interior, childCols=2) # Create the dropdown window. self._popup = self.createcomponent('popup', (), None, Tkinter.Toplevel, (interior,)) self._popup.withdraw() self._popup.overrideredirect(1) # Create the scrolled listbox inside the dropdown window. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (self._popup,), hull_borderwidth = 2, hull_relief = 'raised', hull_height = self['listheight'], usehullsize = 1, listbox_exportselection = 0) self._list.pack(expand=1, fill='both') self.__listbox = self._list.component('listbox') # Bind events to the arrow button. self._arrowBtn.bind('<1>', self._postList) self._arrowBtn.bind('<Configure>', self._drawArrow) self._arrowBtn.bind('<3>', self._next) self._arrowBtn.bind('<Shift-3>', self._previous) self._arrowBtn.bind('<Down>', self._next) self._arrowBtn.bind('<Up>', self._previous) self._arrowBtn.bind('<Control-n>', self._next) self._arrowBtn.bind('<Control-p>', self._previous) self._arrowBtn.bind('<Shift-Down>', self._postList) self._arrowBtn.bind('<Shift-Up>', self._postList) self._arrowBtn.bind('<F34>', self._postList) self._arrowBtn.bind('<F28>', self._postList) self._arrowBtn.bind('<space>', self._postList) # Bind events to the dropdown window. self._popup.bind('<Escape>', self._unpostList) self._popup.bind('<space>', self._selectUnpost) self._popup.bind('<Return>', self._selectUnpost) self._popup.bind('<ButtonRelease-1>', self._dropdownBtnRelease) self._popup.bind('<ButtonPress-1>', self._unpostOnNextRelease) # Bind events to the Tk listbox. self.__listbox.bind('<Enter>', self._unpostOnNextRelease) # Bind events to the Tk entry widget. self._entryWidget.bind('<Configure>', self._resizeArrow) self._entryWidget.bind('<Shift-Down>', self._postList) self._entryWidget.bind('<Shift-Up>', self._postList) self._entryWidget.bind('<F34>', self._postList) self._entryWidget.bind('<F28>', self._postList) # Need to unpost the popup if the entryfield is unmapped (eg: # its toplevel window is withdrawn) while the popup list is # displayed. self._entryWidget.bind('<Unmap>', self._unpostList) else: # Create the scrolled listbox below the entry field. self._list = self.createcomponent('scrolledlist', (('listbox', 'scrolledlist_listbox'),), None, ScrolledListBox, (interior,), selectioncommand = self._selectCmd) self._list.grid(column=2, row=3, sticky='nsew') self.__listbox = self._list.component('listbox') # The scrolled listbox should expand vertically. interior.grid_rowconfigure(3, weight = 1) # Create the label. self.createlabel(interior, childRows=2) self._entryWidget.bind('<Down>', self._next) self._entryWidget.bind('<Up>', self._previous) self._entryWidget.bind('<Control-n>', self._next) self._entryWidget.bind('<Control-p>', self._previous) self.__listbox.bind('<Control-n>', self._next) self.__listbox.bind('<Control-p>', self._previous) if self['history']: self._entryfield.configure(command=self._addHistory) # Check keywords and initialise options. self.initialiseoptions() def destroy(self): if self['dropdown'] and self._isPosted: popgrab(self._popup) MegaWidget.destroy(self) #====================================================================== # Public methods def get(self, first = None, last=None): if first is None: return self._entryWidget.get() else: return self._list.get(first, last) def invoke(self): if self['dropdown']: self._postList() else: return self._selectCmd() def selectitem(self, index, setentry=1): if type(index) == types.StringType: text = index items = self._list.get(0, 'end') if text in items: index = list(items).index(text) else: raise IndexError, 'index "%s" not found' % text elif setentry: text = self._list.get(0, 'end')[index] self._list.select_clear(0, 'end') self._list.select_set(index, index) self._list.activate(index) self.see(index) if setentry: self._entryfield.setentry(text) # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Frame.Grid. def size(self): return self._list.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Frame.Grid. def bbox(self, index): return self._list.bbox(index) def clear(self): self._entryfield.clear() self._list.clear() #====================================================================== # Private methods for both dropdown and simple comboboxes. def _addHistory(self): input = self._entryWidget.get() if input != '': index = None if self['unique']: # If item is already in list, select it and return. items = self._list.get(0, 'end') if input in items: index = list(items).index(input) if index is None: index = self._list.index('end') self._list.insert('end', input) self.selectitem(index) if self['autoclear']: self._entryWidget.delete(0, 'end') # Execute the selectioncommand on the new entry. self._selectCmd() def _next(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = 0 else: index = string.atoi(cursels[0]) if index == size - 1: index = 0 else: index = index + 1 self.selectitem(index) def _previous(self, event): size = self.size() if size <= 1: return cursels = self.curselection() if len(cursels) == 0: index = size - 1 else: index = string.atoi(cursels[0]) if index == 0: index = size - 1 else: index = index - 1 self.selectitem(index) def _selectCmd(self, event=None): sels = self.getcurselection() if len(sels) == 0: item = None else: item = sels[0] self._entryfield.setentry(item) cmd = self['selectioncommand'] if callable(cmd): if event is None: # Return result of selectioncommand for invoke() method. return cmd(item) else: cmd(item) #====================================================================== # Private methods for dropdown combobox. def _drawArrow(self, event=None, sunken=0): arrow = self._arrowBtn if sunken: self._arrowRelief = arrow.cget('relief') arrow.configure(relief = 'sunken') else: arrow.configure(relief = self._arrowRelief) if self._isPosted and self['fliparrow']: direction = 'up' else: direction = 'down' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _postList(self, event = None): self._isPosted = 1 self._drawArrow(sunken=1) # Make sure that the arrow is displayed sunken. self.update_idletasks() x = self._entryfield.winfo_rootx() y = self._entryfield.winfo_rooty() + \ self._entryfield.winfo_height() w = self._entryfield.winfo_width() + self._arrowBtn.winfo_width() h = self.__listbox.winfo_height() sh = self.winfo_screenheight() if y + h > sh and y > sh / 2: y = self._entryfield.winfo_rooty() - h self._list.configure(hull_width=w) setgeometryanddeiconify(self._popup, '+%d+%d' % (x, y)) # Grab the popup, so that all events are delivered to it, and # set focus to the listbox, to make keyboard navigation # easier. pushgrab(self._popup, 1, self._unpostList) self.__listbox.focus_set() self._drawArrow() # Ignore the first release of the mouse button after posting the # dropdown list, unless the mouse enters the dropdown list. self._ignoreRelease = 1 def _dropdownBtnRelease(self, event): if (event.widget == self._list.component('vertscrollbar') or event.widget == self._list.component('horizscrollbar')): return if self._ignoreRelease: self._unpostOnNextRelease() return self._unpostList() if (event.x >= 0 and event.x < self.__listbox.winfo_width() and event.y >= 0 and event.y < self.__listbox.winfo_height()): self._selectCmd() def _unpostOnNextRelease(self, event = None): self._ignoreRelease = 0 def _resizeArrow(self, event): bw = (string.atoi(self._arrowBtn['borderwidth']) + string.atoi(self._arrowBtn['highlightthickness'])) newHeight = self._entryfield.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) self._arrowBtn.configure(width=newWidth, height=newHeight) self._drawArrow() def _unpostList(self, event=None): if not self._isPosted: # It is possible to get events on an unposted popup. For # example, by repeatedly pressing the space key to post # and unpost the popup. The <space> event may be # delivered to the popup window even though # popgrab() has set the focus away from the # popup window. (Bug in Tk?) return # Restore the focus before withdrawing the window, since # otherwise the window manager may take the focus away so we # can't redirect it. Also, return the grab to the next active # window in the stack, if any. popgrab(self._popup) self._popup.withdraw() self._isPosted = 0 self._drawArrow() def _selectUnpost(self, event): self._unpostList() self._selectCmd() forwardmethods(ComboBox, ScrolledListBox, '_list') forwardmethods(ComboBox, EntryField, '_entryfield') ###################################################################### ### File: PmwComboBoxDialog.py # Not Based on iwidgets version. class ComboBoxDialog(Dialog): # Dialog window with simple combobox. # Dialog window displaying a list and entry field and requesting # the user to make a selection or enter a value def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 10, INITOPT), ('bordery', 10, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() aliases = ( ('listbox', 'combobox_listbox'), ('scrolledlist', 'combobox_scrolledlist'), ('entry', 'combobox_entry'), ('label', 'combobox_label'), ) self._combobox = self.createcomponent('combobox', aliases, None, ComboBox, (interior,), scrolledlist_dblclickcommand = self.invoke, dropdown = 0, ) self._combobox.pack(side='top', expand='true', fill='both', padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # ComboBox's listbox widget. listbox = self.component('listbox') self.configure(activatecommand = listbox.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Need to explicitly forward this to override the stupid # (grid_)size method inherited from Tkinter.Toplevel.Grid. def size(self): return self._combobox.size() # Need to explicitly forward this to override the stupid # (grid_)bbox method inherited from Tkinter.Toplevel.Grid. def bbox(self, index): return self._combobox.bbox(index) forwardmethods(ComboBoxDialog, ComboBox, '_combobox') ###################################################################### ### File: PmwCounter.py import string import sys import types import Tkinter class Counter(MegaWidget): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('autorepeat', 1, None), ('buttonaspect', 1.0, INITOPT), ('datatype', 'numeric', self._datatype), ('increment', 1, None), ('initwait', 300, None), ('labelmargin', 0, INITOPT), ('labelpos', None, INITOPT), ('orient', 'horizontal', INITOPT), ('padx', 0, INITOPT), ('pady', 0, INITOPT), ('repeatrate', 50, None), ('sticky', 'ew', INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). MegaWidget.__init__(self, parent) # Initialise instance variables. self._timerId = None self._normalRelief = None # Create the components. interior = self.interior() # If there is no label, put the arrows and the entry directly # into the interior, otherwise create a frame for them. In # either case the border around the arrows and the entry will # be raised (but not around the label). if self['labelpos'] is None: frame = interior if not kw.has_key('hull_relief'): frame.configure(relief = 'raised') if not kw.has_key('hull_borderwidth'): frame.configure(borderwidth = 1) else: frame = self.createcomponent('frame', (), None, Tkinter.Frame, (interior,), relief = 'raised', borderwidth = 1) frame.grid(column=2, row=2, sticky=self['sticky']) interior.grid_columnconfigure(2, weight=1) interior.grid_rowconfigure(2, weight=1) # Create the down arrow. self._downArrowBtn = self.createcomponent('downarrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) # Create the entry field. self._counterEntry = self.createcomponent('entryfield', (('entry', 'entryfield_entry'),), None, EntryField, (frame,)) # Create the up arrow. self._upArrowBtn = self.createcomponent('uparrow', (), 'Arrow', Tkinter.Canvas, (frame,), width = 16, height = 16, relief = 'raised', borderwidth = 2) padx = self['padx'] pady = self['pady'] orient = self['orient'] if orient == 'horizontal': self._downArrowBtn.grid(column = 0, row = 0) self._counterEntry.grid(column = 1, row = 0, sticky = self['sticky']) self._upArrowBtn.grid(column = 2, row = 0) frame.grid_columnconfigure(1, weight = 1) frame.grid_rowconfigure(0, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_columnconfigure(0, pad = padx) frame.grid_columnconfigure(2, pad = padx) frame.grid_rowconfigure(0, pad = pady) elif orient == 'vertical': self._upArrowBtn.grid(column = 0, row = 0, sticky = 's') self._counterEntry.grid(column = 0, row = 1, sticky = self['sticky']) self._downArrowBtn.grid(column = 0, row = 2, sticky = 'n') frame.grid_columnconfigure(0, weight = 1) frame.grid_rowconfigure(0, weight = 1) frame.grid_rowconfigure(2, weight = 1) if Tkinter.TkVersion >= 4.2: frame.grid_rowconfigure(0, pad = pady) frame.grid_rowconfigure(2, pad = pady) frame.grid_columnconfigure(0, pad = padx) else: raise ValueError, 'bad orient option ' + repr(orient) + \ ': must be either \'horizontal\' or \'vertical\'' self.createlabel(interior) self._upArrowBtn.bind('<Configure>', self._drawUpArrow) self._upArrowBtn.bind('<1>', self._countUp) self._upArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._downArrowBtn.bind('<Configure>', self._drawDownArrow) self._downArrowBtn.bind('<1>', self._countDown) self._downArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting) self._counterEntry.bind('<Configure>', self._resizeArrow) entry = self._counterEntry.component('entry') entry.bind('<Down>', lambda event, s = self: s._key_decrement(event)) entry.bind('<Up>', lambda event, s = self: s._key_increment(event)) # Need to cancel the timer if an arrow button is unmapped (eg: # its toplevel window is withdrawn) while the mouse button is # held down. The canvas will not get the ButtonRelease event # if it is not mapped, since the implicit grab is cancelled. self._upArrowBtn.bind('<Unmap>', self._stopCounting) self._downArrowBtn.bind('<Unmap>', self._stopCounting) # Check keywords and initialise options. self.initialiseoptions() def _resizeArrow(self, event): for btn in (self._upArrowBtn, self._downArrowBtn): bw = (string.atoi(btn['borderwidth']) + string.atoi(btn['highlightthickness'])) newHeight = self._counterEntry.winfo_reqheight() - 2 * bw newWidth = int(newHeight * self['buttonaspect']) btn.configure(width=newWidth, height=newHeight) self._drawArrow(btn) def _drawUpArrow(self, event): self._drawArrow(self._upArrowBtn) def _drawDownArrow(self, event): self._drawArrow(self._downArrowBtn) def _drawArrow(self, arrow): if self['orient'] == 'vertical': if arrow == self._upArrowBtn: direction = 'up' else: direction = 'down' else: if arrow == self._upArrowBtn: direction = 'right' else: direction = 'left' drawarrow(arrow, self['entry_foreground'], direction, 'arrow') def _stopCounting(self, event = None): if self._timerId is not None: self.after_cancel(self._timerId) self._timerId = None if self._normalRelief is not None: button, relief = self._normalRelief button.configure(relief=relief) self._normalRelief = None def _countUp(self, event): self._normalRelief = (self._upArrowBtn, self._upArrowBtn.cget('relief')) self._upArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._upArrowBtn.update_idletasks() self._count(1, 1) def _countDown(self, event): self._normalRelief = (self._downArrowBtn, self._downArrowBtn.cget('relief')) self._downArrowBtn.configure(relief='sunken') # Force arrow down (it may come up immediately, if increment fails). self._downArrowBtn.update_idletasks() self._count(-1, 1) def increment(self): self._forceCount(1) def decrement(self): self._forceCount(-1) def _key_increment(self, event): self._forceCount(1) self.update_idletasks() def _key_decrement(self, event): self._forceCount(-1) self.update_idletasks() def _datatype(self): datatype = self['datatype'] if type(datatype) is types.DictionaryType: self._counterArgs = datatype.copy() if self._counterArgs.has_key('counter'): datatype = self._counterArgs['counter'] del self._counterArgs['counter'] else: datatype = 'numeric' else: self._counterArgs = {} if _counterCommands.has_key(datatype): self._counterCommand = _counterCommands[datatype] elif callable(datatype): self._counterCommand = datatype else: validValues = _counterCommands.keys() validValues.sort() raise ValueError, ('bad datatype value "%s": must be a' + ' function or one of %s') % (datatype, validValues) def _forceCount(self, factor): if not self.valid(): self.bell() return text = self._counterEntry.get() try: value = apply(self._counterCommand, (text, factor, self['increment']), self._counterArgs) except ValueError: self.bell() return previousICursor = self._counterEntry.index('insert') if self._counterEntry.setentry(value) == OK: self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) def _count(self, factor, first): if not self.valid(): self.bell() return self._timerId = None origtext = self._counterEntry.get() try: value = apply(self._counterCommand, (origtext, factor, self['increment']), self._counterArgs) except ValueError: # If text is invalid, stop counting. self._stopCounting() self.bell() return # If incrementing produces an invalid value, restore previous # text and stop counting. previousICursor = self._counterEntry.index('insert') valid = self._counterEntry.setentry(value) if valid != OK: self._stopCounting() self._counterEntry.setentry(origtext) if valid == PARTIAL: self.bell() return self._counterEntry.xview('end') self._counterEntry.icursor(previousICursor) if self['autorepeat']: if first: delay = self['initwait'] else: delay = self['repeatrate'] self._timerId = self.after(delay, lambda self=self, factor=factor: self._count(factor, 0)) def destroy(self): self._stopCounting() MegaWidget.destroy(self) forwardmethods(Counter, EntryField, '_counterEntry') def _changeNumber(text, factor, increment): value = string.atol(text) if factor > 0: value = (value / increment) * increment + increment else: value = ((value - 1) / increment) * increment # Get rid of the 'L' at the end of longs (in python up to 1.5.2). rtn = str(value) if rtn[-1] == 'L': return rtn[:-1] else: return rtn def _changeReal(text, factor, increment, separator = '.'): value = stringtoreal(text, separator) div = value / increment # Compare reals using str() to avoid problems caused by binary # numbers being only approximations to decimal numbers. # For example, if value is -0.3 and increment is 0.1, then # int(value/increment) = -2, not -3 as one would expect. if str(div)[-2:] == '.0': # value is an even multiple of increment. div = round(div) + factor else: # value is not an even multiple of increment. div = int(div) * 1.0 if value < 0: div = div - 1 if factor > 0: div = (div + 1) value = div * increment text = str(value) if separator != '.': index = string.find(text, '.') if index >= 0: text = text[:index] + separator + text[index + 1:] return text def _changeDate(value, factor, increment, format = 'ymd', separator = '/', yyyy = 0): jdn = datestringtojdn(value, format, separator) + factor * increment y, m, d = jdntoymd(jdn) result = '' for index in range(3): if index > 0: result = result + separator f = format[index] if f == 'y': if yyyy: result = result + '%02d' % y else: result = result + '%02d' % (y % 100) elif f == 'm': result = result + '%02d' % m elif f == 'd': result = result + '%02d' % d return result _SECSPERDAY = 24 * 60 * 60 def _changeTime(value, factor, increment, separator = ':', time24 = 0): unixTime = timestringtoseconds(value, separator) if factor > 0: chunks = unixTime / increment + 1 else: chunks = (unixTime - 1) / increment unixTime = chunks * increment if time24: while unixTime < 0: unixTime = unixTime + _SECSPERDAY while unixTime >= _SECSPERDAY: unixTime = unixTime - _SECSPERDAY if unixTime < 0: unixTime = -unixTime sign = '-' else: sign = '' secs = unixTime % 60 unixTime = unixTime / 60 mins = unixTime % 60 hours = unixTime / 60 return '%s%02d%s%02d%s%02d' % (sign, hours, separator, mins, separator, secs) # hexadecimal, alphabetic, alphanumeric not implemented _counterCommands = { 'numeric' : _changeNumber, # } integer 'integer' : _changeNumber, # } these two use the same function 'real' : _changeReal, # real number 'time' : _changeTime, 'date' : _changeDate, } ###################################################################### ### File: PmwCounterDialog.py # A Dialog with a counter class CounterDialog(Dialog): def __init__(self, parent = None, **kw): # Define the megawidget options. optiondefs = ( ('borderx', 20, INITOPT), ('bordery', 20, INITOPT), ) self.defineoptions(kw, optiondefs) # Initialise the base class (after defining the options). Dialog.__init__(self, parent) # Create the components. interior = self.interior() # Create the counter. aliases = ( ('entryfield', 'counter_entryfield'), ('entry', 'counter_entryfield_entry'), ('label', 'counter_label') ) self._cdCounter = self.createcomponent('counter', aliases, None, Counter, (interior,)) self._cdCounter.pack(fill='x', expand=1, padx = self['borderx'], pady = self['bordery']) if not kw.has_key('activatecommand'): # Whenever this dialog is activated, set the focus to the # Counter's entry widget. tkentry = self.component('entry') self.configure(activatecommand = tkentry.focus_set) # Check keywords and initialise options. self.initialiseoptions() # Supply aliases to some of the entry component methods. def insertentry(self, index, text): self._cdCounter.insert(index, text) def deleteentry(self, first, last=None): self._cdCounter.delete(first, last) def indexentry(self, index): return self._cdCounter.index(index) forwardmethods(CounterDialog, Counter, '_cdCounter') ###################################################################### ### File: PmwLogicalFont.py import os import string def _font_initialise(root, size=None, fontScheme = None): global _fontSize if size is not None: _fontSize = size if fontScheme in ('pmw1', 'pmw2'): if os.name == 'posix': defaultFont = logicalfont('Helvetica') menuFont = logicalfont('Helvetica', weight='bold', slant='italic') scaleFont = logicalfont('Helvetica', slant='italic') root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Menu*Font', menuFont, 'userDefault') root.option_add('*Menubutton*Font', menuFont, 'userDefault') root.option_add('*Scale.*Font', scaleFont, 'userDefault') if fontScheme == 'pmw1': balloonFont = logicalfont('Helvetica', -6, pixel = '12') else: # fontScheme == 'pmw2' balloonFont = logicalfont('Helvetica', -2) root.option_add('*Balloon.*Font', balloonFont, 'userDefault') else: defaultFont = logicalfont('Helvetica') root.option_add('*Font', defaultFont, 'userDefault') elif fontScheme == 'default': defaultFont = ('Helvetica', '-%d' % (_fontSize,), 'bold') entryFont = ('Helvetica', '-%d' % (_fontSize,)) textFont = ('Courier', '-%d' % (_fontSize,)) root.option_add('*Font', defaultFont, 'userDefault') root.option_add('*Entry*Font', entryFont, 'userDefault') root.option_add('*Text*Font', textFont, 'userDefault') def logicalfont(name='Helvetica', sizeIncr = 0, **kw): if not _fontInfo.has_key(name): raise ValueError, 'font %s does not exist' % name rtn = [] for field in _fontFields: if kw.has_key(field): logicalValue = kw[field] elif _fontInfo[name].has_key(field): logicalValue = _fontInfo[name][field] else: logicalValue = '*' if _propertyAliases[name].has_key((field, logicalValue)): realValue = _propertyAliases[name][(field, logicalValue)] elif _propertyAliases[name].has_key((field, None)): realValue = _propertyAliases[name][(field, None)] elif _propertyAliases[None].has_key((field, logicalValue)): realValue = _propertyAliases[None][(field, logicalValue)] elif _propertyAliases[None].has_key((field, None)): realValue = _propertyAliases[None][(field, None)] else: realValue = logicalValue if field == 'size': if realValue == '*': realValue = _fontSize realValue = str((realValue + sizeIncr) * 10) rtn.append(realValue) return string.join(rtn, '-') def logicalfontnames(): return _fontInfo.keys() if os.name == 'nt': _fontSize = 16 else: _fontSize = 14 _fontFields = ( 'registry', 'foundry', 'family', 'weight', 'slant', 'width', 'style', 'pixel', 'size', 'xres', 'yres', 'spacing', 'avgwidth', 'charset', 'encoding') # <_propertyAliases> defines other names for which property values may # be known by. This is required because italics in adobe-helvetica # are specified by 'o', while other fonts use 'i'. _propertyAliases = {} _propertyAliases[None] = { ('slant', 'italic') : 'i', ('slant', 'normal') : 'r', ('weight', 'light') : 'normal', ('width', 'wide') : 'normal', ('width', 'condensed') : 'normal', } # <_fontInfo> describes a 'logical' font, giving the default values of # some of its properties. _fontInfo = {} _fontInfo['Helvetica'] = { 'foundry' : 'adobe', 'family' : 'helvetica', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Helvetica'] = { ('slant', 'italic') : 'o', ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Times'] = { 'foundry' : 'adobe', 'family' : 'times', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'p', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Times'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } _fontInfo['Fixed'] = { 'foundry' : 'misc', 'family' : 'fixed', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'c', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Fixed'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', ('width', 'condensed') : 'semicondensed', } _fontInfo['Courier'] = { 'foundry' : 'adobe', 'family' : 'courier', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Courier'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', ('style', None) : '', } _fontInfo['Typewriter'] = { 'foundry' : 'b&h', 'family' : 'lucidatypewriter', 'registry' : '', 'charset' : 'iso8859', 'encoding' : '1', 'spacing' : 'm', 'slant' : 'normal', 'width' : 'normal', 'weight' : 'normal', } _propertyAliases['Typewriter'] = { ('weight', 'normal') : 'medium', ('weight', 'light') : 'medium', } if os.name == 'nt': # For some reason 'fixed' fonts on NT aren't. _fontInfo['Fixed'] = _fontInfo['Courier'] _propertyAliases['Fixed'] = _propertyAliases['Courier']
Python
# Functions for converting colors and modifying the color scheme of # an application. import math import string import sys import Tkinter _PI = math.pi _TWO_PI = _PI * 2 _THIRD_PI = _PI / 3 _SIXTH_PI = _PI / 6 _MAX_RGB = float(256 * 256 - 1) # max size of rgb values returned from Tk def setscheme(root, background=None, **kw): root = root._root() palette = apply(_calcPalette, (root, background,), kw) for option, value in palette.items(): root.option_add('*' + option, value, 'widgetDefault') def getdefaultpalette(root): # Return the default values of all options, using the defaults # from a few widgets. ckbtn = Tkinter.Checkbutton(root) entry = Tkinter.Entry(root) scbar = Tkinter.Scrollbar(root) orig = {} orig['activeBackground'] = str(ckbtn.configure('activebackground')[4]) orig['activeForeground'] = str(ckbtn.configure('activeforeground')[4]) orig['background'] = str(ckbtn.configure('background')[4]) orig['disabledForeground'] = str(ckbtn.configure('disabledforeground')[4]) orig['foreground'] = str(ckbtn.configure('foreground')[4]) orig['highlightBackground'] = str(ckbtn.configure('highlightbackground')[4]) orig['highlightColor'] = str(ckbtn.configure('highlightcolor')[4]) orig['insertBackground'] = str(entry.configure('insertbackground')[4]) orig['selectColor'] = str(ckbtn.configure('selectcolor')[4]) orig['selectBackground'] = str(entry.configure('selectbackground')[4]) orig['selectForeground'] = str(entry.configure('selectforeground')[4]) orig['troughColor'] = str(scbar.configure('troughcolor')[4]) ckbtn.destroy() entry.destroy() scbar.destroy() return orig #====================================================================== # Functions dealing with brightness, hue, saturation and intensity of colors. def changebrightness(root, colorName, brightness): # Convert the color name into its hue and back into a color of the # required brightness. rgb = name2rgb(root, colorName) hue, saturation, intensity = rgb2hsi(rgb) if saturation == 0.0: hue = None return hue2name(hue, brightness) def hue2name(hue, brightness = None): # Convert the requested hue and brightness into a color name. If # hue is None, return a grey of the requested brightness. if hue is None: rgb = hsi2rgb(0.0, 0.0, brightness) else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI rgb = hsi2rgb(hue, 1.0, 1.0) if brightness is not None: b = rgb2brightness(rgb) i = 1.0 - (1.0 - brightness) * b s = bhi2saturation(brightness, hue, i) rgb = hsi2rgb(hue, s, i) return rgb2name(rgb) def bhi2saturation(brightness, hue, intensity): while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) pp = intensity pq = intensity * f pt = intensity - intensity * f pv = 0 hue = int(hue) if hue == 0: rgb = (pv, pt, pp) elif hue == 1: rgb = (pq, pv, pp) elif hue == 2: rgb = (pp, pv, pt) elif hue == 3: rgb = (pp, pq, pv) elif hue == 4: rgb = (pt, pp, pv) elif hue == 5: rgb = (pv, pp, pq) return (intensity - brightness) / rgb2brightness(rgb) def hsi2rgb(hue, saturation, intensity): i = intensity if saturation == 0: rgb = [i, i, i] else: while hue < 0: hue = hue + _TWO_PI while hue >= _TWO_PI: hue = hue - _TWO_PI hue = hue / _THIRD_PI f = hue - math.floor(hue) p = i * (1.0 - saturation) q = i * (1.0 - saturation * f) t = i * (1.0 - saturation * (1.0 - f)) hue = int(hue) if hue == 0: rgb = [i, t, p] elif hue == 1: rgb = [q, i, p] elif hue == 2: rgb = [p, i, t] elif hue == 3: rgb = [p, q, i] elif hue == 4: rgb = [t, p, i] elif hue == 5: rgb = [i, p, q] for index in range(3): val = rgb[index] if val < 0.0: val = 0.0 if val > 1.0: val = 1.0 rgb[index] = val return rgb def average(rgb1, rgb2, fraction): return ( rgb2[0] * fraction + rgb1[0] * (1.0 - fraction), rgb2[1] * fraction + rgb1[1] * (1.0 - fraction), rgb2[2] * fraction + rgb1[2] * (1.0 - fraction) ) def rgb2name(rgb): return '#%02x%02x%02x' % \ (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)) def rgb2brightness(rgb): # Return the perceived grey level of the color # (0.0 == black, 1.0 == white). rf = 0.299 gf = 0.587 bf = 0.114 return rf * rgb[0] + gf * rgb[1] + bf * rgb[2] def rgb2hsi(rgb): maxc = max(rgb[0], rgb[1], rgb[2]) minc = min(rgb[0], rgb[1], rgb[2]) intensity = maxc if maxc != 0: saturation = (maxc - minc) / maxc else: saturation = 0.0 hue = 0.0 if saturation != 0.0: c = [] for index in range(3): c.append((maxc - rgb[index]) / (maxc - minc)) if rgb[0] == maxc: hue = c[2] - c[1] elif rgb[1] == maxc: hue = 2 + c[0] - c[2] elif rgb[2] == maxc: hue = 4 + c[1] - c[0] hue = hue * _THIRD_PI if hue < 0.0: hue = hue + _TWO_PI return (hue, saturation, intensity) def name2rgb(root, colorName, asInt = 0): if colorName[0] == '#': # Extract rgb information from the color name itself, assuming # it is either #rgb, #rrggbb, #rrrgggbbb, or #rrrrggggbbbb # This is useful, since tk may return incorrect rgb values if # the colormap is full - it will return the rbg values of the # closest color available. colorName = colorName[1:] digits = len(colorName) / 3 factor = 16 ** (4 - digits) rgb = ( string.atoi(colorName[0:digits], 16) * factor, string.atoi(colorName[digits:digits * 2], 16) * factor, string.atoi(colorName[digits * 2:digits * 3], 16) * factor, ) else: # We have no choice but to ask Tk what the rgb values are. rgb = root.winfo_rgb(colorName) if not asInt: rgb = (rgb[0] / _MAX_RGB, rgb[1] / _MAX_RGB, rgb[2] / _MAX_RGB) return rgb def _calcPalette(root, background=None, **kw): # Create a map that has the complete new palette. If some colors # aren't specified, compute them from other colors that are specified. new = {} for key, value in kw.items(): new[key] = value if background is not None: new['background'] = background if not new.has_key('background'): raise ValueError, 'must specify a background color' if not new.has_key('foreground'): new['foreground'] = 'black' bg = name2rgb(root, new['background']) fg = name2rgb(root, new['foreground']) for i in ('activeForeground', 'insertBackground', 'selectForeground', 'highlightColor'): if not new.has_key(i): new[i] = new['foreground'] if not new.has_key('disabledForeground'): newCol = average(bg, fg, 0.3) new['disabledForeground'] = rgb2name(newCol) if not new.has_key('highlightBackground'): new['highlightBackground'] = new['background'] # Set <lighterBg> to a color that is a little lighter that the # normal background. To do this, round each color component up by # 9% or 1/3 of the way to full white, whichever is greater. lighterBg = [] for i in range(3): lighterBg.append(bg[i]) inc1 = lighterBg[i] * 0.09 inc2 = (1.0 - lighterBg[i]) / 3 if inc1 > inc2: lighterBg[i] = lighterBg[i] + inc1 else: lighterBg[i] = lighterBg[i] + inc2 if lighterBg[i] > 1.0: lighterBg[i] = 1.0 # Set <darkerBg> to a color that is a little darker that the # normal background. darkerBg = (bg[0] * 0.9, bg[1] * 0.9, bg[2] * 0.9) if not new.has_key('activeBackground'): # If the foreground is dark, pick a light active background. # If the foreground is light, pick a dark active background. # XXX This has been disabled, since it does not look very # good with dark backgrounds. If this is ever fixed, the # selectBackground and troughColor options should also be fixed. if rgb2brightness(fg) < 0.5: new['activeBackground'] = rgb2name(lighterBg) else: new['activeBackground'] = rgb2name(lighterBg) if not new.has_key('selectBackground'): new['selectBackground'] = rgb2name(darkerBg) if not new.has_key('troughColor'): new['troughColor'] = rgb2name(darkerBg) if not new.has_key('selectColor'): new['selectColor'] = 'yellow' return new def spectrum(numColors, correction = 1.0, saturation = 1.0, intensity = 1.0, extraOrange = 1, returnHues = 0): colorList = [] division = numColors / 7.0 for index in range(numColors): if extraOrange: if index < 2 * division: hue = index / division else: hue = 2 + 2 * (index - 2 * division) / division hue = hue * _SIXTH_PI else: hue = index * _TWO_PI / numColors if returnHues: colorList.append(hue) else: rgb = hsi2rgb(hue, saturation, intensity) if correction != 1.0: rgb = correct(rgb, correction) name = rgb2name(rgb) colorList.append(name) return colorList def correct(rgb, correction): correction = float(correction) rtn = [] for index in range(3): rtn.append((1 - (1 - rgb[index]) ** correction) ** (1 / correction)) return rtn #============================================================================== def _recolorTree(widget, oldpalette, newcolors): # Change the colors in a widget and its descendants. # Change the colors in <widget> and all of its descendants, # according to the <newcolors> dictionary. It only modifies # colors that have their default values as specified by the # <oldpalette> variable. The keys of the <newcolors> dictionary # are named after widget configuration options and the values are # the new value for that option. for dbOption in newcolors.keys(): option = string.lower(dbOption) try: value = str(widget.cget(option)) except: continue if oldpalette is None or value == oldpalette[dbOption]: apply(widget.configure, (), {option : newcolors[dbOption]}) for child in widget.winfo_children(): _recolorTree(child, oldpalette, newcolors) def changecolor(widget, background=None, **kw): root = widget._root() if not hasattr(widget, '_Pmw_oldpalette'): widget._Pmw_oldpalette = getdefaultpalette(root) newpalette = apply(_calcPalette, (root, background,), kw) _recolorTree(widget, widget._Pmw_oldpalette, newpalette) widget._Pmw_oldpalette = newpalette def bordercolors(root, colorName): # This is the same method that Tk uses for shadows, in TkpGetShadows. lightRGB = [] darkRGB = [] for value in name2rgb(root, colorName, 1): value40pc = (14 * value) / 10 if value40pc > _MAX_RGB: value40pc = _MAX_RGB valueHalfWhite = (_MAX_RGB + value) / 2; lightRGB.append(max(value40pc, valueHalfWhite)) darkValue = (60 * value) / 100 darkRGB.append(darkValue) return ( '#%04x%04x%04x' % (lightRGB[0], lightRGB[1], lightRGB[2]), '#%04x%04x%04x' % (darkRGB[0], darkRGB[1], darkRGB[2]) )
Python
# This file is part of FlickFleck. # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import i18n import Tkinter import Pmw import wins import sys # simple window to display about and copyright information class About: def __init__(self, parent): self.parent = parent infotext = config.TITLE + ' version: ' + config.VERSION + \ '\n\nA tool to copy, rotate and rename' + \ '\ndigital camera jpeg files.' + \ '\n\nPython version: ' + sys.version + \ '\nPmw version: ' + Pmw.version() + \ '\nRunning on: ' + sys.platform + \ '\n\nhttp://flickfleck.googlecode.com/' self.w_dialog = Pmw.Dialog( parent, buttons = ('OK',), defaultbutton = 'OK', title = i18n.name['menu_about'] + ' ' + config.TITLE, command = self.button ) self.w_dialog.withdraw() self.w_notebook = Pmw.NoteBook( self.w_dialog.interior() ) self.w_notebook.pack( fill = 'both', expand = 1, padx = 2, pady = 2 ) self.addtab( 'Info', infotext ) self.addtab( 'Copyright', wins.COPYRIGHT ) self.addtab( 'Disclaimer', wins.DISCLAIMER ) self.addtab( 'Tools', wins.TOOLS ) self.addtab( 'Pmw', wins.PMW ) gpltab = self.w_notebook.add( 'GPLv3' ) gpl = Pmw.ScrolledText( gpltab, hscrollmode = 'none' ) gpl.importfile( 'GPL.txt' ) gpl.component('text').config( state = Tkinter.DISABLED ) gpl.pack( padx = 5, pady = 5, expand = 1 ) self.w_notebook.tab('Info').focus_set() self.w_notebook.setnaturalsize() def addtab( self, name, text ): tab = self.w_notebook.add( name ) label = Tkinter.Label( tab, text = text, pady = 10 ) label.pack( expand = 1, fill = 'both', padx = 2, pady = 2 ) def show(self): self.w_dialog.activate(geometry = 'centerscreenalways') def button(self, result): self.w_dialog.deactivate( result )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys import Tkinter, tkFileDialog import Pmw import aboutwin import config import configuration import ui import i18n import progressbar class FlickFleck: # create all windows when object is made def __init__(self, parent): self.parent = parent self.parent.protocol("WM_DELETE_WINDOW",self.doquit) self.parent.bind('<Return>', self._processReturnKey) self.parent.focus_set() self.w_about = aboutwin.About(parent) self.balloon = Pmw.Balloon( parent ) # --- top menubar --- self.menubar = Pmw.MenuBar( parent, hull_relief = 'raised', hull_borderwidth = 1, balloon = self.balloon ) self.menubar.pack( fill = 'x' ) self.menubar.addmenu('File', None, text = i18n.name['menu_file'] ) self.menubar.addmenuitem('File', 'command', None, command = self.doSelFromdir, label = i18n.name['menu_file_fromdir'] ) self.menubar.addmenuitem('File', 'command', None, command = self.doSelTodir, label = i18n.name['menu_file_todir'] ) if sys.platform == 'darwin': self.menubar.addmenuitem('File', 'separator') self.menubar.addmenuitem('File', 'command', None, command = configuration.mac_editconfig, label = i18n.name['menu_file_config'] ) self.menubar.addmenuitem('File', 'separator') self.menubar.addmenuitem('File', 'command', None, command = self.doquit, label =i18n.name['menu_file_exit'] ) self.button_about = Tkinter.Button( self.menubar.component('hull'), text = i18n.name['menu_about'] + '...', relief = 'flat', command = self.about ) self.button_about.pack(side='right') # self.balloon.bind( self.button_about, 'About') # --- from directory --- self.w_from = Pmw.Group( parent, tag_text = i18n.name['label_copyfrom'] ) self.w_from.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.var_fromlabel = Tkinter.StringVar( value = config.fromdir ) self.w_fromlabel = Tkinter.Label( self.w_from.interior(), textvariable = self.var_fromlabel, pady = 10 ) self.w_fromlabel.pack( side = 'left', padx = 5, pady = 2 ) # --- to directory --- self.w_to = Pmw.Group( parent, tag_text = i18n.name['label_copyto'] ) self.w_to.pack( fill = 'both', expand = 1, padx = 6, pady = 6 ) self.var_tolabel = Tkinter.StringVar( value = config.todir ) self.w_tolabel = Tkinter.Label( self.w_to.interior(), textvariable = self.var_tolabel ) self.w_tolabel.pack( side = 'left', padx = 5, pady = 2 ) # --- start n stop buttons --- self.w_buttons = Pmw.ButtonBox( parent ) # frame_borderwidth = 2, # frame_relief = 'groove' ) self.w_buttons.pack( fill = 'both', expand = 1, padx = 10, pady = 10 ) self.w_buttons.add( 'Start', command = self.start, text = i18n.name['button_start'] ) self.w_buttons.add( 'Stop', command = self.stop, text = i18n.name['button_stop'] ) self.w_buttons.setdefault('Start') self.w_buttons.alignbuttons() self.w_buttons.button('Stop').config(state = Tkinter.DISABLED) self.w_buttons.setdefault('Start') # --- progressbar --- # self.w_pb = Pmw.LabeledWidget( parent, labelpos = "nw", # label_text = "" ) self.w_pb = Pmw.ScrolledCanvas( parent, borderframe = 0, usehullsize = 1, hscrollmode = 'none', vscrollmode = 'none', hull_height = ui.wins.PBheight ) self.w_pb.component('hull').configure(relief='sunken', borderwidth=2) self.w_pb.pack( padx=5, pady=5, expand='yes', fill = 'x') self.w_pbw = progressbar.Widget( self.w_pb.interior() ) ui.wins.pb = self.w_pbw # --- status area at the bottom --- self.w_status = Pmw.MessageBar( parent, entry_relief = 'groove', labelpos = 'w', label_text = i18n.name['label_status'] + ' ') self.w_status.silent = True self.w_status.message('state', i18n.name['status_idle'] ) self.w_status.pack( fill = 'x', padx = 2, pady = 1, side = 'bottom' ) # self.balloon.configure( statuscommand = self.w_status.helpmessage ) #-- set message in the statusrow def status(self, msg_str, type = 'state'): self.w_status.message(type, msg_str) ui.wins.root.update() #-- user pressed 'start' def start(self): self.w_buttons.button(1).config(state = Tkinter.NORMAL) self.w_buttons.button(0).config(state = Tkinter.DISABLED) ui.wins.requestStop = False ui.wins.engine.start() #-- user pressed 'cancel' def stop(self): # self.w_buttons.button(0).config(state = Tkinter.NORMAL) self.w_buttons.button(1).config(state = Tkinter.DISABLED) # stopping is only noted, engine will stop when it notices value change ui.wins.requestStop = True #-- user pressed Enter def _processReturnKey(self, event): self.w_buttons.invoke() #-- quit selected in file-menu def doquit(self): self.parent.quit() #-- about button pressed def about(self): return self.w_about.show() #-- select fromdir def doSelFromdir(self): dir = tkFileDialog.askdirectory() if len(dir) > 0: config.fromdir = dir self.var_fromlabel.set( dir ) ui.wins.engine.init_filelist() # refind jpgs to copy #-- select todir def doSelTodir(self): dir = tkFileDialog.askdirectory() if len(dir) > 0: config.todir = dir self.var_tolabel.set( dir )
Python
# -*- coding: latin-1 -*- root = None main = None # Progressbar graphics height PBheight = 30 requestStop = False DISCLAIMER = """ THIS SOFTWARE IS PROVIDED BY Jyke Jokinen ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Jyke Jokinen BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ COPYRIGHT = """ Copyright (C) 2008 Jyke Tapani Jokinen This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. You may not use this software except in compliance with the License. Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ PMW = """ Pmw copyright Copyright 1997-1999 Telstra Corporation Limited, Australia Copyright 2000-2002 Really Good Software Pty Ltd, Australia Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ TOOLS = """ FlickFleck uses these external programs: Python megawidgets (http://pmw.sourceforge.net/) Jpegtran (http://sylvana.net/jpegcrop/jpegtran/) ExifTool (http://www.sno.phy.queensu.ca/~phil/exiftool/) """
Python
# Python interface to some of the commands of the 2.4 version of the # BLT extension to tcl. import string import types import Tkinter # Supported commands: _busyCommand = '::blt::busy' _vectorCommand = '::blt::vector' _graphCommand = '::blt::graph' _testCommand = '::blt::*' _chartCommand = '::blt::stripchart' _tabsetCommand = '::blt::tabset' _haveBlt = None _haveBltBusy = None def _checkForBlt(window): global _haveBlt global _haveBltBusy # Blt may be a package which has not yet been loaded. Try to load it. try: window.tk.call('package', 'require', 'BLT') except Tkinter.TclError: # Another way to try to dynamically load blt: try: window.tk.call('load', '', 'Blt') except Tkinter.TclError: pass _haveBlt= (window.tk.call('info', 'commands', _testCommand) != '') _haveBltBusy = (window.tk.call('info', 'commands', _busyCommand) != '') def haveblt(window): if _haveBlt is None: _checkForBlt(window) return _haveBlt def havebltbusy(window): if _haveBlt is None: _checkForBlt(window) return _haveBltBusy def _loadBlt(window): if _haveBlt is None: if window is None: window = Tkinter._default_root if window is None: window = Tkinter.Tk() _checkForBlt(window) def busy_hold(window, cursor = None): _loadBlt(window) if cursor is None: window.tk.call(_busyCommand, 'hold', window._w) else: window.tk.call(_busyCommand, 'hold', window._w, '-cursor', cursor) def busy_release(window): _loadBlt(window) window.tk.call(_busyCommand, 'release', window._w) def busy_forget(window): _loadBlt(window) window.tk.call(_busyCommand, 'forget', window._w) #============================================================================= # Interface to the blt vector command which makes it look like the # builtin python list type. # The -variable, -command, -watchunset creation options are not supported. # The dup, merge, notify, offset, populate, seq and variable methods # and the +, -, * and / operations are not supported. # Blt vector functions: def vector_expr(expression): tk = Tkinter._default_root.tk strList = tk.splitlist(tk.call(_vectorCommand, 'expr', expression)) return tuple(map(string.atof, strList)) def vector_names(pattern = None): tk = Tkinter._default_root.tk return tk.splitlist(tk.call(_vectorCommand, 'names', pattern)) class Vector: _varnum = 0 def __init__(self, size=None, master=None): # <size> can be either an integer size, or a string "first:last". _loadBlt(master) if master: self._master = master else: self._master = Tkinter._default_root self.tk = self._master.tk self._name = 'PY_VEC' + str(Vector._varnum) Vector._varnum = Vector._varnum + 1 if size is None: self.tk.call(_vectorCommand, 'create', self._name) else: self.tk.call(_vectorCommand, 'create', '%s(%s)' % (self._name, size)) def __del__(self): self.tk.call(_vectorCommand, 'destroy', self._name) def __str__(self): return self._name def __repr__(self): return '[' + string.join(map(str, self), ', ') + ']' def __cmp__(self, list): return cmp(self[:], list) def __len__(self): return self.tk.getint(self.tk.call(self._name, 'length')) def __getitem__(self, key): oldkey = key if key < 0: key = key + len(self) try: return self.tk.getdouble(self.tk.globalgetvar(self._name, str(key))) except Tkinter.TclError: raise IndexError, oldkey def __setitem__(self, key, value): if key < 0: key = key + len(self) return self.tk.globalsetvar(self._name, str(key), float(value)) def __delitem__(self, key): if key < 0: key = key + len(self) return self.tk.globalunsetvar(self._name, str(key)) def __getslice__(self, start, end): length = len(self) if start < 0: start = 0 if end > length: end = length if start >= end: return [] end = end - 1 # Blt vector slices include end point. text = self.tk.globalgetvar(self._name, str(start) + ':' + str(end)) return map(self.tk.getdouble, self.tk.splitlist(text)) def __setslice__(self, start, end, list): if start > end: end = start self.set(self[:start] + list + self[end:]) def __delslice__(self, start, end): if start < end: self.set(self[:start] + self[end:]) def __add__(self, list): return self[:] + list def __radd__(self, list): return list + self[:] def __mul__(self, n): return self[:] * n __rmul__ = __mul__ # Python builtin list methods: def append(self, *args): self.tk.call(self._name, 'append', args) def count(self, obj): return self[:].count(obj) def index(self, value): return self[:].index(value) def insert(self, index, value): self[index:index] = [value] def remove(self, value): del self[self.index(value)] def reverse(self): s = self[:] s.reverse() self.set(s) def sort(self, *args): s = self[:] s.sort() self.set(s) # Blt vector instance methods: # append - same as list method above def clear(self): self.tk.call(self._name, 'clear') def delete(self, *args): self.tk.call((self._name, 'delete') + args) def expr(self, expression): self.tk.call(self._name, 'expr', expression) def length(self, newSize=None): return self.tk.getint(self.tk.call(self._name, 'length', newSize)) def range(self, first, last=None): # Note that, unlike self[first:last], this includes the last # item in the returned range. text = self.tk.call(self._name, 'range', first, last) return map(self.tk.getdouble, self.tk.splitlist(text)) def search(self, start, end=None): return self._master._getints(self.tk.call( self._name, 'search', start, end)) def set(self, list): if type(list) != types.TupleType: list = tuple(list) self.tk.call(self._name, 'set', list) # The blt vector sort method has different semantics to the python # list sort method. Call these blt_sort: def blt_sort(self, *args): self.tk.call((self._name, 'sort') + args) def blt_sort_reverse(self, *args): self.tk.call((self._name, 'sort', '-reverse') + args) # Special blt vector indexes: def min(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'min')) def max(self): return self.tk.getdouble(self.tk.globalgetvar(self._name, 'max')) # Method borrowed from Tkinter.Var class: def get(self): return self[:] #============================================================================= # This is a general purpose configure routine which can handle the # configuration of widgets, items within widgets, etc. Supports the # forms configure() and configure('font') for querying and # configure(font = 'fixed', text = 'hello') for setting. def _doConfigure(widget, subcommand, option, kw): if not option and not kw: # Return a description of all options. ret = {} options = widget.tk.splitlist(widget.tk.call(subcommand)) for optionString in options: optionInfo = widget.tk.splitlist(optionString) option = optionInfo[0][1:] ret[option] = (option,) + optionInfo[1:] return ret if option: # Return a description of the option given by <option>. if kw: # Having keywords implies setting configuration options. # Can't set and get in one command! raise ValueError, 'cannot have option argument with keywords' option = '-' + option optionInfo = widget.tk.splitlist(widget.tk.call(subcommand + (option,))) return (optionInfo[0][1:],) + optionInfo[1:] # Otherwise, set the given configuration options. widget.tk.call(subcommand + widget._options(kw)) #============================================================================= class Graph(Tkinter.Widget): # Wrapper for the blt graph widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _graphCommand, cnf, kw) def bar_create(self, name, **kw): self.tk.call((self._w, 'bar', 'create', name) + self._options(kw)) def line_create(self, name, **kw): self.tk.call((self._w, 'line', 'create', name) + self._options(kw)) def extents(self, item): return self.tk.getint(self.tk.call(self._w, 'extents', item)) def invtransform(self, winX, winY): return self._getdoubles( self.tk.call(self._w, 'invtransform', winX, winY)) def inside(self, x, y): return self.tk.getint(self.tk.call(self._w, 'inside', x, y)) def snap(self, photoName): self.tk.call(self._w, 'snap', photoName) def transform(self, x, y): return self._getdoubles(self.tk.call(self._w, 'transform', x, y)) def axis_cget(self, axisName, key): return self.tk.call(self._w, 'axis', 'cget', axisName, '-' + key) def axis_configure(self, axes, option=None, **kw): # <axes> may be a list of axisNames. if type(axes) == types.StringType: axes = [axes] subcommand = (self._w, 'axis', 'configure') + tuple(axes) return _doConfigure(self, subcommand, option, kw) def axis_create(self, axisName, **kw): self.tk.call((self._w, 'axis', 'create', axisName) + self._options(kw)) def axis_delete(self, *args): self.tk.call((self._w, 'axis', 'delete') + args) def axis_invtransform(self, axisName, value): return self.tk.getdouble(self.tk.call( self._w, 'axis', 'invtransform', axisName, value)) def axis_limits(self, axisName): return self._getdoubles(self.tk.call( self._w, 'axis', 'limits', axisName)) def axis_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'axis', 'names') + args)) def axis_transform(self, axisName, value): return self.tk.getint(self.tk.call( self._w, 'axis', 'transform', axisName, value)) def xaxis_cget(self, key): return self.tk.call(self._w, 'xaxis', 'cget', '-' + key) def xaxis_configure(self, option=None, **kw): subcommand = (self._w, 'xaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def xaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'xaxis', 'invtransform', value)) def xaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'xaxis', 'limits')) def xaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'xaxis', 'transform', value)) def xaxis_use(self, axisName = None): return self.tk.call(self._w, 'xaxis', 'use', axisName) def x2axis_cget(self, key): return self.tk.call(self._w, 'x2axis', 'cget', '-' + key) def x2axis_configure(self, option=None, **kw): subcommand = (self._w, 'x2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def x2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'x2axis', 'invtransform', value)) def x2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'x2axis', 'limits')) def x2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'x2axis', 'transform', value)) def x2axis_use(self, axisName = None): return self.tk.call(self._w, 'x2axis', 'use', axisName) def yaxis_cget(self, key): return self.tk.call(self._w, 'yaxis', 'cget', '-' + key) def yaxis_configure(self, option=None, **kw): subcommand = (self._w, 'yaxis', 'configure') return _doConfigure(self, subcommand, option, kw) def yaxis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'yaxis', 'invtransform', value)) def yaxis_limits(self): return self._getdoubles(self.tk.call(self._w, 'yaxis', 'limits')) def yaxis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'yaxis', 'transform', value)) def yaxis_use(self, axisName = None): return self.tk.call(self._w, 'yaxis', 'use', axisName) def y2axis_cget(self, key): return self.tk.call(self._w, 'y2axis', 'cget', '-' + key) def y2axis_configure(self, option=None, **kw): subcommand = (self._w, 'y2axis', 'configure') return _doConfigure(self, subcommand, option, kw) def y2axis_invtransform(self, value): return self.tk.getdouble(self.tk.call( self._w, 'y2axis', 'invtransform', value)) def y2axis_limits(self): return self._getdoubles(self.tk.call(self._w, 'y2axis', 'limits')) def y2axis_transform(self, value): return self.tk.getint(self.tk.call( self._w, 'y2axis', 'transform', value)) def y2axis_use(self, axisName = None): return self.tk.call(self._w, 'y2axis', 'use', axisName) def crosshairs_cget(self, key): return self.tk.call(self._w, 'crosshairs', 'cget', '-' + key) def crosshairs_configure(self, option=None, **kw): subcommand = (self._w, 'crosshairs', 'configure') return _doConfigure(self, subcommand, option, kw) def crosshairs_off(self): self.tk.call(self._w, 'crosshairs', 'off') def crosshairs_on(self): self.tk.call(self._w, 'crosshairs', 'on') def crosshairs_toggle(self): self.tk.call(self._w, 'crosshairs', 'toggle') def element_activate(self, name, *args): self.tk.call((self._w, 'element', 'activate', name) + args) def element_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'element', 'bind', tagName), sequence, func, add) def element_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'element', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def element_cget(self, name, key): return self.tk.call(self._w, 'element', 'cget', name, '-' + key) def element_closest(self, x, y, *args, **kw): var = 'python_private_1' success = self.tk.getint(self.tk.call( (self._w, 'element', 'closest', x, y, var) + self._options(kw) + args)) if success: rtn = {} rtn['dist'] = self.tk.getdouble(self.tk.globalgetvar(var, 'dist')) rtn['x'] = self.tk.getdouble(self.tk.globalgetvar(var, 'x')) rtn['y'] = self.tk.getdouble(self.tk.globalgetvar(var, 'y')) rtn['index'] = self.tk.getint(self.tk.globalgetvar(var, 'index')) rtn['name'] = self.tk.globalgetvar(var, 'name') return rtn else: return None def element_configure(self, names, option=None, **kw): # <names> may be a list of elemNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'element', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def element_deactivate(self, *args): self.tk.call((self._w, 'element', 'deactivate') + args) def element_delete(self, *args): self.tk.call((self._w, 'element', 'delete') + args) def element_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'element', 'exists', name)) def element_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'element', 'names') + args)) def element_show(self, nameList=None): if nameList is not None: nameList = tuple(nameList) return self.tk.splitlist( self.tk.call(self._w, 'element', 'show', nameList)) def element_type(self, name): return self.tk.call(self._w, 'element', 'type', name) def grid_cget(self, key): return self.tk.call(self._w, 'grid', 'cget', '-' + key) def grid_configure(self, option=None, **kw): subcommand = (self._w, 'grid', 'configure') return _doConfigure(self, subcommand, option, kw) def grid_off(self): self.tk.call(self._w, 'grid', 'off') def grid_on(self): self.tk.call(self._w, 'grid', 'on') def grid_toggle(self): self.tk.call(self._w, 'grid', 'toggle') def legend_activate(self, *args): self.tk.call((self._w, 'legend', 'activate') + args) def legend_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'legend', 'bind', tagName), sequence, func, add) def legend_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'legend', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def legend_cget(self, key): return self.tk.call(self._w, 'legend', 'cget', '-' + key) def legend_configure(self, option=None, **kw): subcommand = (self._w, 'legend', 'configure') return _doConfigure(self, subcommand, option, kw) def legend_deactivate(self, *args): self.tk.call((self._w, 'legend', 'deactivate') + args) def legend_get(self, pos): return self.tk.call(self._w, 'legend', 'get', pos) def pen_cget(self, name, key): return self.tk.call(self._w, 'pen', 'cget', name, '-' + key) def pen_configure(self, names, option=None, **kw): # <names> may be a list of penNames. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'pen', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def pen_create(self, name, **kw): self.tk.call((self._w, 'pen', 'create', name) + self._options(kw)) def pen_delete(self, *args): self.tk.call((self._w, 'pen', 'delete') + args) def pen_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'pen', 'names') + args)) def postscript_cget(self, key): return self.tk.call(self._w, 'postscript', 'cget', '-' + key) def postscript_configure(self, option=None, **kw): subcommand = (self._w, 'postscript', 'configure') return _doConfigure(self, subcommand, option, kw) def postscript_output(self, fileName=None, **kw): prefix = (self._w, 'postscript', 'output') if fileName is None: return self.tk.call(prefix + self._options(kw)) else: self.tk.call(prefix + (fileName,) + self._options(kw)) def marker_after(self, first, second=None): self.tk.call(self._w, 'marker', 'after', first, second) def marker_before(self, first, second=None): self.tk.call(self._w, 'marker', 'before', first, second) def marker_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'marker', 'bind', tagName), sequence, func, add) def marker_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'marker', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def marker_cget(self, name, key): return self.tk.call(self._w, 'marker', 'cget', name, '-' + key) def marker_configure(self, names, option=None, **kw): # <names> may be a list of markerIds. if type(names) == types.StringType: names = [names] subcommand = (self._w, 'marker', 'configure') + tuple(names) return _doConfigure(self, subcommand, option, kw) def marker_create(self, type, **kw): return self.tk.call( (self._w, 'marker', 'create', type) + self._options(kw)) def marker_delete(self, *args): self.tk.call((self._w, 'marker', 'delete') + args) def marker_exists(self, name): return self.tk.getboolean( self.tk.call(self._w, 'marker', 'exists', name)) def marker_names(self, *args): return self.tk.splitlist( self.tk.call((self._w, 'marker', 'names') + args)) def marker_type(self, name): type = self.tk.call(self._w, 'marker', 'type', name) if type == '': type = None return type #============================================================================= class Stripchart(Graph): # Wrapper for the blt stripchart widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _chartCommand, cnf, kw) #============================================================================= class Tabset(Tkinter.Widget): # Wrapper for the blt TabSet widget, version 2.4. def __init__(self, master=None, cnf={}, **kw): _loadBlt(master) Tkinter.Widget.__init__(self, master, _tabsetCommand, cnf, kw) def activate(self, tabIndex): self.tk.call(self._w, 'activate', tabIndex) # This is the 'bind' sub-command: def tag_bind(self, tagName, sequence=None, func=None, add=None): return self._bind((self._w, 'bind', tagName), sequence, func, add) def tag_unbind(self, tagName, sequence, funcid=None): self.tk.call(self._w, 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def delete(self, first, last = None): self.tk.call(self._w, 'delete', first, last) # This is the 'focus' sub-command: def tab_focus(self, tabIndex): self.tk.call(self._w, 'focus', tabIndex) def get(self, tabIndex): return self.tk.call(self._w, 'get', tabIndex) def index(self, tabIndex): index = self.tk.call(self._w, 'index', tabIndex) if index == '': return None else: return self.tk.getint(self.tk.call(self._w, 'index', tabIndex)) def insert(self, position, name1, *names, **kw): self.tk.call( (self._w, 'insert', position, name1) + names + self._options(kw)) def invoke(self, tabIndex): return self.tk.call(self._w, 'invoke', tabIndex) def move(self, tabIndex1, beforeOrAfter, tabIndex2): self.tk.call(self._w, 'move', tabIndex1, beforeOrAfter, tabIndex2) def nearest(self, x, y): return self.tk.call(self._w, 'nearest', x, y) def scan_mark(self, x, y): self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): self.tk.call(self._w, 'see', index) def see(self, tabIndex): self.tk.call(self._w,'see',tabIndex) def size(self): return self.tk.getint(self.tk.call(self._w, 'size')) def tab_cget(self, tabIndex, option): if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tab', 'cget', tabIndex, option) def tab_configure(self, tabIndexes, option=None, **kw): # <tabIndexes> may be a list of tabs. if type(tabIndexes) in (types.StringType, types.IntType): tabIndexes = [tabIndexes] subcommand = (self._w, 'tab', 'configure') + tuple(tabIndexes) return _doConfigure(self, subcommand, option, kw) def tab_names(self, *args): return self.tk.splitlist(self.tk.call((self._w, 'tab', 'names') + args)) def tab_tearoff(self, tabIndex, newName = None): if newName is None: name = self.tk.call(self._w, 'tab', 'tearoff', tabIndex) return self.nametowidget(name) else: self.tk.call(self._w, 'tab', 'tearoff', tabIndex, newName) def view(self): s = self.tk.call(self._w, 'view') return tuple(map(self.tk.getint, self.tk.splitlist(s))) def view_moveto(self, fraction): self.tk.call(self._w, 'view', 'moveto', fraction) def view_scroll(self, number, what): self.tk.call(self._w, 'view', 'scroll', number, what)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # # import exifrotate import exifdatename # # rotates the file using jpegtran if orientation is not horizontal # def rotate( filename ): exifrotate.rotate( filename ) # # return (newdir, newname) tuple based on the EXIF createdate infromation # def newname( filename ): return exifdatename.newname( filename )
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os.path from subprocess import Popen, PIPE from fileops import quotepath def eqlen( str ): if len(str) == 1: str = "0" + str return str # ----------------------------------------------------------------------- # return ('<year>/<month>', <datename>') tuple based on files EXIF date # def newname( filename ): # --a no duplicate tags # -f force printing of tags even if values are not found # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -CreateDate " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() # parse createdate values (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "problem running exiftool (%s)" % filename ) if str.strip().lower() != "create date": ui.ERR( "exiftool: createdate not found (%s)" % filename ) try: (date,time) = data.strip().split(' ') (year,mon,day) = date.split(':') mon = eqlen( mon ) day = eqlen( day ) (hour,min,sec) = time.split(':') hour = eqlen( hour ) min = eqlen( min ) sec = eqlen( sec ) except: ui.ERR( "problem parsing EXIF date (%s)" % data) newdir = year + os.path.sep + mon newname = "%s%s%s-%s%s%s" % (year,mon,day,hour,min,sec) return (newdir, newname)
Python
# This file is part of FlickFleck. # Copyright (C) 2008 Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import config import ui import os, os.path import tempfile from subprocess import Popen, PIPE from fileops import copy, quotepath # # map orientation values to jpegtran commands to make the pic right # data is from # http://sylvana.net/jpegcrop/exif_orientation.html TRANS = [ [ "" ], # not in use [ "" ], [ "-flip horizontal" ], [ "-rotate 180 -trim" ], [ "-flip vertical" ], [ "-transpose" ], [ "-rotate 90 -trim" ], [ "-transverse" ], [ "-rotate 90 -trim", "-rotate 180 -trim" ] ] # -------------------------------------------------------------------- def rotate( filename ): dir = os.path.dirname( filename ) file = os.path.basename( filename ) # --a no duplicate tags # -f force printing of tags even if values are not found (0 is unknown) # -n print values as numbers cmd = config.exiftool + " --a -f -fast -n -Orientation " + \ quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (read orientation1) (%s)" % filename ) # parse orientation (str, data) = pipe.stdout.readline().split(':', 1) except: ui.ERR( "exception in exiftool (read orientation2) (%s)" % filename ) if str.strip().lower() != "orientation": ui.ERR( "exiftool: orientation not found (%s)" % str ) orientation = int( data.strip() ) if orientation > 8: ui.ERR( "orientation out of range (%d,%s)" % (orientation, filename) ) # 0 : unknown orientation -> do not touch # 1 : horizontal orientation -> no need to rotate if orientation == 0 or orientation == 1: return # # execute rotation operations defined in table 'TRANS' # rotations are written to a new file which is copied to the # original file in the last step # fromfile = filename tmpfiles = [] for op in TRANS[ orientation ]: (fd, tmp) = tempfile.mkstemp( '', '', dir ) os.close(fd) # XXX: closing tmpfile and using the filename creates a race condition # but target is usually in users subdirectory and this program is usually # run in a personal computer, so risk should be minimal/acceptable tmpfiles.append( tmp ) # record name for cleanup later # -copy all preserves original EXIF information rot_cmd = config.jpegtran + " -copy all -outfile " \ + quotepath(tmp) + " " + op + " " + quotepath(fromfile) try: pipe = Popen( rot_cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running jpegtran (%s)" % fromfile ) except: ui.ERR("exception in jpegtran (%s)" % rot_cmd ) fromfile = tmp # endfor # move the last resultfile into original name if fromfile != filename: try: os.remove( filename ) os.rename( fromfile, filename ) except: ui.ERR("error finalizing jpegtran (%s)" % filename ) # rotation should have made the picture into 'horizontal' orientation so # change the orientation EXIF info to match that cmd = config.exiftool + " -overwrite_original_in_place -n -Orientation=1 " \ + quotepath(filename) try: pipe = Popen(cmd, shell=True, stdout=PIPE) pipe.wait() if pipe.returncode != 0: ui.ERR("problem running exiftool (set orientation) (%s)" % filename ) except: ui.ERR( "exception in exiftool (set orientation) (%s)" % filename ) # remove any tempfiles still present in the filesystem for f in tmpfiles: if os.path.exists( f ): try: os.remove( f ) except: ui.ERR("cannot remove tempfile (%s)" % f )
Python
from distutils.core import setup import py2app opts = { "py2app": { # i18n languages are loaded at runtime so py2exe won't find em "includes": "i18n.finnish, i18n.english", "optimize" : 2, "argv_emulation":True, "iconfile" : "flickfleck.icns", # "semi_standalone":True, # "bundle_files" : 1, # does not seem to work in my env "dist_dir": "packaging/macos", } } setup(name = "flickfleck", version = "1.0.0", author = "Jyke Tapani Jokinen", author_email = "jyke.t.jokinen(at)gmail.com", # packages = ["ui", "jpegops"], data_files =[('', ['GPL.txt', 'README.txt', 'config.txt', 'flickfleck.ico']) # ('tools', ['tools/jpegtran', 'tools/exiftool']) ], url = 'http://flickfleck.googlecode.com/', download_url = 'http://flickfleck.googlecode.com/', options = opts, app=[{"script": 'flickfleck.py', "icon_resources" : [(1, "flickfleck.icns")], }])
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
from distutils.core import setup import py2exe opts = { "py2exe": { # i18n languages are loaded at runtime so py2exe won't find em "includes": "i18n.finnish, i18n.english", "optimize" : 2, # "bundle_files" : 1, # does not seem to work in my env "dist_dir": "packaging/windows", } } setup(name = "flickfleck", version = "1.0.0", author = "Jyke Tapani Jokinen", author_email = "jyke.t.jokinen(at)gmail.com", # packages = ["ui", "jpegops"], data_files =[('', ['GPL.txt', 'README.txt', 'config.txt', 'flickfleck.ico']), ('tools', ['tools/jpegtran.exe', 'tools/exiftool.exe']) ], url = 'http://flickfleck.googlecode.com/', download_url = 'http://flickfleck.googlecode.com/', options = opts, windows=[{"script": 'flickfleck.py', "icon_resources" : [(1, "flickfleck.ico")], }])
Python
#!/usr/bin/env python # This file is part of FlickFleck. # Copyright 2008 by Jyke Tapani Jokinen # # FlickFleck is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # FlickFleck is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with FlickFleck. If not, see <http://www.gnu.org/licenses/>. # import sys, os, os.path import Tkinter import config import configuration import engine import ui import i18n def main(): configuration.init() i18n.init() ui.init() ui.wins.engine.init() ui.start() if __name__=='__main__': # Get the directory where this program is and add that to the # module search-path. try: # XXX does any of these raise exceptions? basepath = os.path.dirname( os.path.abspath( sys.argv[0] ) ) sys.path.append( basepath ) os.chdir( basepath ) config.installdir = basepath main() # # all error handling should be done in modules below # so we wont report anything here: except KeyboardInterrupt: pass
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import i18n if __name__=='__main__': print i18n.name['Start']
Python
#!/usr/bin/env python # import sys sys.path.append("..") import config import ui import engine if __name__=='__main__': ui.wins.engine.init() print ui.wins.engine.jpegtran print ui.wins.engine.exiftool
Python