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.
"""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
# Should work for Python2.6 and higher.
import json as simplejson
except ImportError: # pragma: no cover
try:
import simplejson
except ImportError:
# Try to import from django, should work on App Engine
from django.utils import simplejson
| Python |
import Cookie
import datetime
import time
import email.utils
import calendar
import base64
import hashlib
import hmac
import re
import logging
# Ripped from the Tornado Framework's web.py
# http://github.com/facebook/tornado/commit/39ac6d169a36a54bb1f6b9bf1fdebb5c9da96e09
#
# Tornado is licensed under the Apache Licence, Version 2.0
# (http://www.apache.org/licenses/LICENSE-2.0.html).
#
# Example:
# from vendor.prayls.lilcookies import LilCookies
# cookieutil = LilCookies(self, application_settings['cookie_secret'])
# cookieutil.set_secure_cookie(name = 'mykey', value = 'myvalue', expires_days= 365*100)
# cookieutil.get_secure_cookie(name = 'mykey')
class LilCookies:
@staticmethod
def _utf8(s):
if isinstance(s, unicode):
return s.encode("utf-8")
assert isinstance(s, str)
return s
@staticmethod
def _time_independent_equals(a, b):
if len(a) != len(b):
return False
result = 0
for x, y in zip(a, b):
result |= ord(x) ^ ord(y)
return result == 0
@staticmethod
def _signature_from_secret(cookie_secret, *parts):
""" Takes a secret salt value to create a signature for values in the `parts` param."""
hash = hmac.new(cookie_secret, digestmod=hashlib.sha1)
for part in parts: hash.update(part)
return hash.hexdigest()
@staticmethod
def _signed_cookie_value(cookie_secret, name, value):
""" Returns a signed value for use in a cookie.
This is helpful to have in its own method if you need to re-use this function for other needs. """
timestamp = str(int(time.time()))
value = base64.b64encode(value)
signature = LilCookies._signature_from_secret(cookie_secret, name, value, timestamp)
return "|".join([value, timestamp, signature])
@staticmethod
def _verified_cookie_value(cookie_secret, name, signed_value):
"""Returns the un-encrypted value given the signed value if it validates, or None."""
value = signed_value
if not value: return None
parts = value.split("|")
if len(parts) != 3: return None
signature = LilCookies._signature_from_secret(cookie_secret, name, parts[0], parts[1])
if not LilCookies._time_independent_equals(parts[2], signature):
logging.warning("Invalid cookie signature %r", value)
return None
timestamp = int(parts[1])
if timestamp < time.time() - 31 * 86400:
logging.warning("Expired cookie %r", value)
return None
try:
return base64.b64decode(parts[0])
except:
return None
def __init__(self, handler, cookie_secret):
"""You must specify the cookie_secret to use any of the secure methods.
It should be a long, random sequence of bytes to be used as the HMAC
secret for the signature.
"""
if len(cookie_secret) < 45:
raise ValueError("LilCookies cookie_secret should at least be 45 characters long, but got `%s`" % cookie_secret)
self.handler = handler
self.request = handler.request
self.response = handler.response
self.cookie_secret = cookie_secret
def cookies(self):
"""A dictionary of Cookie.Morsel objects."""
if not hasattr(self, "_cookies"):
self._cookies = Cookie.BaseCookie()
if "Cookie" in self.request.headers:
try:
self._cookies.load(self.request.headers["Cookie"])
except:
self.clear_all_cookies()
return self._cookies
def get_cookie(self, name, default=None):
"""Gets the value of the cookie with the given name, else default."""
if name in self.cookies():
return self._cookies[name].value
return default
def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
"""Sets the given cookie name/value with the given options.
Additional keyword arguments are set on the Cookie.Morsel
directly.
See http://docs.python.org/library/cookie.html#morsel-objects
for available attributes.
"""
name = LilCookies._utf8(name)
value = LilCookies._utf8(value)
if re.search(r"[\x00-\x20]", name + value):
# Don't let us accidentally inject bad stuff
raise ValueError("Invalid cookie %r: %r" % (name, value))
if not hasattr(self, "_new_cookies"):
self._new_cookies = []
new_cookie = Cookie.BaseCookie()
self._new_cookies.append(new_cookie)
new_cookie[name] = value
if domain:
new_cookie[name]["domain"] = domain
if expires_days is not None and not expires:
expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
if expires:
timestamp = calendar.timegm(expires.utctimetuple())
new_cookie[name]["expires"] = email.utils.formatdate(
timestamp, localtime=False, usegmt=True)
if path:
new_cookie[name]["path"] = path
for k, v in kwargs.iteritems():
new_cookie[name][k] = v
# The 2 lines below were not in Tornado. Instead, they output all their cookies to the headers at once before a response flush.
for vals in new_cookie.values():
self.response.headers._headers.append(('Set-Cookie', vals.OutputString(None)))
def clear_cookie(self, name, path="/", domain=None):
"""Deletes the cookie with the given name."""
expires = datetime.datetime.utcnow() - datetime.timedelta(days=365)
self.set_cookie(name, value="", path=path, expires=expires,
domain=domain)
def clear_all_cookies(self):
"""Deletes all the cookies the user sent with this request."""
for name in self.cookies().iterkeys():
self.clear_cookie(name)
def set_secure_cookie(self, name, value, expires_days=30, **kwargs):
"""Signs and timestamps a cookie so it cannot be forged.
To read a cookie set with this method, use get_secure_cookie().
"""
value = LilCookies._signed_cookie_value(self.cookie_secret, name, value)
self.set_cookie(name, value, expires_days=expires_days, **kwargs)
def get_secure_cookie(self, name, value=None):
"""Returns the given signed cookie if it validates, or None."""
if value is None: value = self.get_cookie(name)
return LilCookies._verified_cookie_value(self.cookie_secret, name, value)
def _cookie_signature(self, *parts):
return LilCookies._signature_from_secret(self.cookie_secret)
| Python |
# Copyright (C) 2007 Joe Gregorio
#
# Licensed under the MIT License
"""MIME-Type Parser
This module provides basic functions for handling mime-types. It can handle
matching mime-types against a list of media-ranges. See section 14.1 of the
HTTP specification [RFC 2616] for a complete explanation.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Contents:
- parse_mime_type(): Parses a mime-type into its component parts.
- parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
quality parameter.
- quality(): Determines the quality ('q') of a mime-type when
compared against a list of media-ranges.
- quality_parsed(): Just like quality() except the second parameter must be
pre-parsed.
- best_match(): Choose the mime-type with the highest quality ('q')
from a list of candidates.
"""
__version__ = '0.1.3'
__author__ = 'Joe Gregorio'
__email__ = 'joe@bitworking.org'
__license__ = 'MIT License'
__credits__ = ''
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
"""
parts = mime_type.split(';')
params = dict([tuple([s.strip() for s in param.split('=', 1)])\
for param in parts[1:]
])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
(type, subtype) = full_type.split('/')
return (type.strip(), subtype.strip(), params)
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
"""
(type, subtype, params) = parse_mime_type(range)
if not params.has_key('q') or not params['q'] or \
not float(params['q']) or float(params['q']) > 1\
or float(params['q']) < 0:
params['q'] = '1'
return (type, subtype, params)
def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) =\
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
type_match = (type == target_type or\
type == '*' or\
target_type == '*')
subtype_match = (subtype == target_subtype or\
subtype == '*' or\
target_subtype == '*')
if type_match and subtype_match:
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
params.has_key(key) and value == params[key]], 0)
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return best_fitness, float(best_fit_q)
def quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns the 'q'
quality parameter of the best match, 0 if no match was found. This function
bahaves the same as quality() except that 'parsed_ranges' must be a list of
parsed media ranges.
"""
return fitness_and_quality_parsed(mime_type, parsed_ranges)[1]
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
"""
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges)
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
"""
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((fitness_and_quality_parsed(mime_type,
parsed_header), pos, mime_type))
pos += 1
weighted_matches.sort()
return weighted_matches[-1][0][1] and weighted_matches[-1][2] or ''
def _filter_blank(i):
for s in i:
if s.strip():
yield s
| Python |
# Copyright (C) 2012 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.
"""Classes to encapsulate a single HTTP request.
The classes implement a command pattern, with every
object supporting an execute() method that does the
actuall HTTP request.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import StringIO
import base64
import copy
import gzip
import httplib2
import mimeparse
import mimetypes
import os
import urllib
import urlparse
import uuid
from email.generator import Generator
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.parser import FeedParser
from errors import BatchError
from errors import HttpError
from errors import ResumableUploadError
from errors import UnexpectedBodyError
from errors import UnexpectedMethodError
from model import JsonModel
from oauth2client.anyjson import simplejson
DEFAULT_CHUNK_SIZE = 512*1024
class MediaUploadProgress(object):
"""Status of a resumable upload."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes sent so far.
total_size: int, total bytes in complete upload, or None if the total
upload size isn't known ahead of time.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of upload completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the upload is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaDownloadProgress(object):
"""Status of a resumable download."""
def __init__(self, resumable_progress, total_size):
"""Constructor.
Args:
resumable_progress: int, bytes received so far.
total_size: int, total bytes in complete download.
"""
self.resumable_progress = resumable_progress
self.total_size = total_size
def progress(self):
"""Percent of download completed, as a float.
Returns:
the percentage complete as a float, returning 0.0 if the total size of
the download is unknown.
"""
if self.total_size is not None:
return float(self.resumable_progress) / float(self.total_size)
else:
return 0.0
class MediaUpload(object):
"""Describes a media object to upload.
Base class that defines the interface of MediaUpload subclasses.
Note that subclasses of MediaUpload may allow you to control the chunksize
when upload a media object. It is important to keep the size of the chunk as
large as possible to keep the upload efficient. Other factors may influence
the size of the chunk you use, particularly if you are working in an
environment where individual HTTP requests may have a hardcoded time limit,
such as under certain classes of requests under Google App Engine.
"""
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
raise NotImplementedError()
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return 'application/octet-stream'
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return None
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return False
def getbytes(self, begin, end):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
raise NotImplementedError()
def _to_json(self, strip=None):
"""Utility function for creating a JSON representation of a MediaUpload.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
if strip is not None:
for member in strip:
del d[member]
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Create a JSON representation of an instance of MediaUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json()
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a MediaUpload subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of MediaUpload that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
class MediaFileUpload(MediaUpload):
"""A MediaUpload for a file.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed uploading images:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals()..insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Constructor.
Args:
filename: string, Name of the file.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._filename = filename
self._size = os.path.getsize(filename)
self._fd = None
if mimetype is None:
(mimetype, encoding) = mimetypes.guess_type(filename)
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
if self._fd is None:
self._fd = open(self._filename, 'rb')
self._fd.seek(begin)
return self._fd.read(length)
def to_json(self):
"""Creating a JSON representation of an instance of MediaFileUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(['_fd'])
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaFileUpload(
d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable'])
class MediaIoBaseUpload(MediaUpload):
"""A MediaUpload for a io.Base objects.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
fh = io.BytesIO('...Some data to upload...')
media = MediaIoBaseUpload(fh, mimetype='image/png',
chunksize=1024*1024, resumable=True)
farm.animals().insert(
id='cow',
name='cow.png',
media_body=media).execute()
"""
def __init__(self, fh, mimetype, chunksize=DEFAULT_CHUNK_SIZE,
resumable=False):
"""Constructor.
Args:
fh: io.Base or file object, The source of the bytes to upload. MUST be
opened in blocking mode, do not use streams opened in non-blocking mode.
mimetype: string, Mime-type of the file. If None then a mime-type will be
guessed from the file extension.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._fh = fh
self._mimetype = mimetype
self._chunksize = chunksize
self._resumable = resumable
self._size = None
try:
if hasattr(self._fh, 'fileno'):
fileno = self._fh.fileno()
# Pipes and such show up as 0 length files.
size = os.fstat(fileno).st_size
if size:
self._size = os.fstat(fileno).st_size
except IOError:
pass
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return self._size
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorted than length if EOF was reached
first.
"""
self._fh.seek(begin)
return self._fh.read(length)
def to_json(self):
"""This upload type is not serializable."""
raise NotImplementedError('MediaIoBaseUpload is not serializable.')
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method.
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=DEFAULT_CHUNK_SIZE, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body, or None of the size is unknown.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def to_json(self):
"""Create a JSON representation of a MediaInMemoryUpload.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
del d['_body']
d['_class'] = t.__name__
d['_module'] = t.__module__
d['_b64body'] = base64.b64encode(self._body)
return simplejson.dumps(d)
@staticmethod
def from_json(s):
d = simplejson.loads(s)
return MediaInMemoryUpload(base64.b64decode(d['_b64body']),
d['_mimetype'], d['_chunksize'],
d['_resumable'])
class MediaIoBaseDownload(object):
""""Download media resources.
Note that the Python file object is compatible with io.Base and can be used
with this class also.
Example:
request = farms.animals().get_media(id='cow')
fh = io.FileIO('cow.png', mode='wb')
downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)
done = False
while done is False:
status, done = downloader.next_chunk()
if status:
print "Download %d%%." % int(status.progress() * 100)
print "Download Complete!"
"""
def __init__(self, fh, request, chunksize=DEFAULT_CHUNK_SIZE):
"""Constructor.
Args:
fh: io.Base or file object, The stream in which to write the downloaded
bytes.
request: apiclient.http.HttpRequest, the media request to perform in
chunks.
chunksize: int, File will be downloaded in chunks of this many bytes.
"""
self.fh_ = fh
self.request_ = request
self.uri_ = request.uri
self.chunksize_ = chunksize
self.progress_ = 0
self.total_size_ = None
self.done_ = False
def next_chunk(self):
"""Get the next chunk of the download.
Returns:
(status, done): (MediaDownloadStatus, boolean)
The value of 'done' will be True when the media has been fully
downloaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
headers = {
'range': 'bytes=%d-%d' % (
self.progress_, self.progress_ + self.chunksize_)
}
http = self.request_.http
http.follow_redirects = False
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [301, 302, 303, 307, 308] and 'location' in resp:
self.uri_ = resp['location']
resp, content = http.request(self.uri_, headers=headers)
if resp.status in [200, 206]:
self.progress_ += len(content)
self.fh_.write(content)
if 'content-range' in resp:
content_range = resp['content-range']
length = content_range.rsplit('/', 1)[1]
self.total_size_ = int(length)
if self.progress_ == self.total_size_:
self.done_ = True
return MediaDownloadProgress(self.progress_, self.total_size_), self.done_
else:
raise HttpError(resp, content, self.uri_)
class HttpRequest(object):
"""Encapsulates a single HTTP request."""
def __init__(self, http, postproc, uri,
method='GET',
body=None,
headers=None,
methodId=None,
resumable=None):
"""Constructor for an HttpRequest.
Args:
http: httplib2.Http, the transport object to use to make a request
postproc: callable, called on the HTTP response and content to transform
it into a data object before returning, or raising an exception
on an error.
uri: string, the absolute URI to send the request to
method: string, the HTTP method to use
body: string, the request body of the HTTP request,
headers: dict, the HTTP request headers
methodId: string, a unique identifier for the API method being called.
resumable: MediaUpload, None if this is not a resumbale request.
"""
self.uri = uri
self.method = method
self.body = body
self.headers = headers or {}
self.methodId = methodId
self.http = http
self.postproc = postproc
self.resumable = resumable
self._in_error_state = False
# Pull the multipart boundary out of the content-type header.
major, minor, params = mimeparse.parse_mime_type(
headers.get('content-type', 'application/json'))
# The size of the non-media part of the request.
self.body_size = len(self.body or '')
# The resumable URI to send chunks to.
self.resumable_uri = None
# The bytes that have been uploaded.
self.resumable_progress = 0
def execute(self, http=None):
"""Execute the request.
Args:
http: httplib2.Http, an http object to be used in place of the
one the HttpRequest request object was constructed with.
Returns:
A deserialized object model of the response body as determined
by the postproc.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable:
body = None
while body is None:
_, body = self.next_chunk(http)
return body
else:
if 'content-length' not in self.headers:
self.headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=self.headers)
if resp.status >= 300:
raise HttpError(resp, content, self.uri)
return self.postproc(resp, content)
def next_chunk(self, http=None):
"""Execute the next step of a resumable upload.
Can only be used if the method being executed supports media uploads and
the MediaUpload object passed in was flagged as using resumable upload.
Example:
media = MediaFileUpload('cow.png', mimetype='image/png',
chunksize=1000, resumable=True)
request = farm.animals().insert(
id='cow',
name='cow.png',
media_body=media)
response = None
while response is None:
status, response = request.next_chunk()
if status:
print "Upload %d%% complete." % int(status.progress() * 100)
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx.
httplib2.Error if a transport error has occured.
"""
if http is None:
http = self.http
if self.resumable.size() is None:
size = '*'
else:
size = str(self.resumable.size())
if self.resumable_uri is None:
start_headers = copy.copy(self.headers)
start_headers['X-Upload-Content-Type'] = self.resumable.mimetype()
if size != '*':
start_headers['X-Upload-Content-Length'] = size
start_headers['content-length'] = str(self.body_size)
resp, content = http.request(self.uri, self.method,
body=self.body,
headers=start_headers)
if resp.status == 200 and 'location' in resp:
self.resumable_uri = resp['location']
else:
raise ResumableUploadError("Failed to retrieve starting URI.")
elif self._in_error_state:
# If we are in an error state then query the server for current state of
# the upload by sending an empty PUT and reading the 'range' header in
# the response.
headers = {
'Content-Range': 'bytes */%s' % size,
'content-length': '0'
}
resp, content = http.request(self.resumable_uri, 'PUT',
headers=headers)
status, body = self._process_response(resp, content)
if body:
# The upload was complete.
return (status, body)
data = self.resumable.getbytes(
self.resumable_progress, self.resumable.chunksize())
# A short read implies that we are at EOF, so finish the upload.
if len(data) < self.resumable.chunksize():
size = str(self.resumable_progress + len(data))
headers = {
'Content-Range': 'bytes %d-%d/%s' % (
self.resumable_progress, self.resumable_progress + len(data) - 1,
size)
}
try:
resp, content = http.request(self.resumable_uri, 'PUT',
body=data,
headers=headers)
except:
self._in_error_state = True
raise
return self._process_response(resp, content)
def _process_response(self, resp, content):
"""Process the response from a single chunk upload.
Args:
resp: httplib2.Response, the response object.
content: string, the content of the response.
Returns:
(status, body): (ResumableMediaStatus, object)
The body will be None until the resumable media is fully uploaded.
Raises:
apiclient.errors.HttpError if the response was not a 2xx or a 308.
"""
if resp.status in [200, 201]:
self._in_error_state = False
return None, self.postproc(resp, content)
elif resp.status == 308:
self._in_error_state = False
# A "308 Resume Incomplete" indicates we are not done.
self.resumable_progress = int(resp['range'].split('-')[1]) + 1
if 'location' in resp:
self.resumable_uri = resp['location']
else:
self._in_error_state = True
raise HttpError(resp, content, self.uri)
return (MediaUploadProgress(self.resumable_progress, self.resumable.size()),
None)
def to_json(self):
"""Returns a JSON representation of the HttpRequest."""
d = copy.copy(self.__dict__)
if d['resumable'] is not None:
d['resumable'] = self.resumable.to_json()
del d['http']
del d['postproc']
return simplejson.dumps(d)
@staticmethod
def from_json(s, http, postproc):
"""Returns an HttpRequest populated with info from a JSON object."""
d = simplejson.loads(s)
if d['resumable'] is not None:
d['resumable'] = MediaUpload.new_from_json(d['resumable'])
return HttpRequest(
http,
postproc,
uri=d['uri'],
method=d['method'],
body=d['body'],
headers=d['headers'],
methodId=d['methodId'],
resumable=d['resumable'])
class BatchHttpRequest(object):
"""Batches multiple HttpRequest objects into a single HTTP request.
Example:
from apiclient.http import BatchHttpRequest
def list_animals(request_id, response):
\"\"\"Do something with the animals list response.\"\"\"
pass
def list_farmers(request_id, response):
\"\"\"Do something with the farmers list response.\"\"\"
pass
service = build('farm', 'v2')
batch = BatchHttpRequest()
batch.add(service.animals().list(), list_animals)
batch.add(service.farmers().list(), list_farmers)
batch.execute(http)
"""
def __init__(self, callback=None, batch_uri=None):
"""Constructor for a BatchHttpRequest.
Args:
callback: callable, A callback to be called for each response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
batch_uri: string, URI to send batch requests to.
"""
if batch_uri is None:
batch_uri = 'https://www.googleapis.com/batch'
self._batch_uri = batch_uri
# Global callback to be called for each individual response in the batch.
self._callback = callback
# A map from id to request.
self._requests = {}
# A map from id to callback.
self._callbacks = {}
# List of request ids, in the order in which they were added.
self._order = []
# The last auto generated id.
self._last_auto_id = 0
# Unique ID on which to base the Content-ID headers.
self._base_id = None
# A map from request id to (headers, content) response pairs
self._responses = {}
# A map of id(Credentials) that have been refreshed.
self._refreshed_credentials = {}
def _refresh_and_apply_credentials(self, request, http):
"""Refresh the credentials and apply to the request.
Args:
request: HttpRequest, the request.
http: httplib2.Http, the global http object for the batch.
"""
# For the credentials to refresh, but only once per refresh_token
# If there is no http per the request then refresh the http passed in
# via execute()
creds = None
if request.http is not None and hasattr(request.http.request,
'credentials'):
creds = request.http.request.credentials
elif http is not None and hasattr(http.request, 'credentials'):
creds = http.request.credentials
if creds is not None:
if id(creds) not in self._refreshed_credentials:
creds.refresh(http)
self._refreshed_credentials[id(creds)] = 1
# Only apply the credentials if we are using the http object passed in,
# otherwise apply() will get called during _serialize_request().
if request.http is None or not hasattr(request.http.request,
'credentials'):
creds.apply(request.headers)
def _id_to_header(self, id_):
"""Convert an id to a Content-ID header value.
Args:
id_: string, identifier of individual request.
Returns:
A Content-ID header with the id_ encoded into it. A UUID is prepended to
the value because Content-ID headers are supposed to be universally
unique.
"""
if self._base_id is None:
self._base_id = uuid.uuid4()
return '<%s+%s>' % (self._base_id, urllib.quote(id_))
def _header_to_id(self, header):
"""Convert a Content-ID header value to an id.
Presumes the Content-ID header conforms to the format that _id_to_header()
returns.
Args:
header: string, Content-ID header value.
Returns:
The extracted id value.
Raises:
BatchError if the header is not in the expected format.
"""
if header[0] != '<' or header[-1] != '>':
raise BatchError("Invalid value for Content-ID: %s" % header)
if '+' not in header:
raise BatchError("Invalid value for Content-ID: %s" % header)
base, id_ = header[1:-1].rsplit('+', 1)
return urllib.unquote(id_)
def _serialize_request(self, request):
"""Convert an HttpRequest object into a string.
Args:
request: HttpRequest, the request to serialize.
Returns:
The request as a string in application/http format.
"""
# Construct status line
parsed = urlparse.urlparse(request.uri)
request_line = urlparse.urlunparse(
(None, None, parsed.path, parsed.params, parsed.query, None)
)
status_line = request.method + ' ' + request_line + ' HTTP/1.1\n'
major, minor = request.headers.get('content-type', 'application/json').split('/')
msg = MIMENonMultipart(major, minor)
headers = request.headers.copy()
if request.http is not None and hasattr(request.http.request,
'credentials'):
request.http.request.credentials.apply(headers)
# MIMENonMultipart adds its own Content-Type header.
if 'content-type' in headers:
del headers['content-type']
for key, value in headers.iteritems():
msg[key] = value
msg['Host'] = parsed.netloc
msg.set_unixfrom(None)
if request.body is not None:
msg.set_payload(request.body)
msg['content-length'] = str(len(request.body))
# Serialize the mime message.
fp = StringIO.StringIO()
# maxheaderlen=0 means don't line wrap headers.
g = Generator(fp, maxheaderlen=0)
g.flatten(msg, unixfrom=False)
body = fp.getvalue()
# Strip off the \n\n that the MIME lib tacks onto the end of the payload.
if request.body is None:
body = body[:-2]
return status_line.encode('utf-8') + body
def _deserialize_response(self, payload):
"""Convert string into httplib2 response and content.
Args:
payload: string, headers and body as a string.
Returns:
A pair (resp, content) like would be returned from httplib2.request.
"""
# Strip off the status line
status_line, payload = payload.split('\n', 1)
protocol, status, reason = status_line.split(' ', 2)
# Parse the rest of the response
parser = FeedParser()
parser.feed(payload)
msg = parser.close()
msg['status'] = status
# Create httplib2.Response from the parsed headers.
resp = httplib2.Response(msg)
resp.reason = reason
resp.version = int(protocol.split('/', 1)[1].replace('.', ''))
content = payload.split('\r\n\r\n', 1)[1]
return resp, content
def _new_id(self):
"""Create a new id.
Auto incrementing number that avoids conflicts with ids already used.
Returns:
string, a new unique id.
"""
self._last_auto_id += 1
while str(self._last_auto_id) in self._requests:
self._last_auto_id += 1
return str(self._last_auto_id)
def add(self, request, callback=None, request_id=None):
"""Add a new request.
Every callback added will be paired with a unique id, the request_id. That
unique id will be passed back to the callback when the response comes back
from the server. The default behavior is to have the library generate it's
own unique id. If the caller passes in a request_id then they must ensure
uniqueness for each request_id, and if they are not an exception is
raised. Callers should either supply all request_ids or nevery supply a
request id, to avoid such an error.
Args:
request: HttpRequest, Request to add to the batch.
callback: callable, A callback to be called for this response, of the
form callback(id, response). The first parameter is the request id, and
the second is the deserialized response object.
request_id: string, A unique id for the request. The id will be passed to
the callback with the response.
Returns:
None
Raises:
BatchError if a media request is added to a batch.
KeyError is the request_id is not unique.
"""
if request_id is None:
request_id = self._new_id()
if request.resumable is not None:
raise BatchError("Media requests cannot be used in a batch request.")
if request_id in self._requests:
raise KeyError("A request with this ID already exists: %s" % request_id)
self._requests[request_id] = request
self._callbacks[request_id] = callback
self._order.append(request_id)
def _execute(self, http, order, requests):
"""Serialize batch request, send to server, process response.
Args:
http: httplib2.Http, an http object to be used to make the request with.
order: list, list of request ids in the order they were added to the
batch.
request: list, list of request objects to send.
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
message = MIMEMultipart('mixed')
# Message should not write out it's own headers.
setattr(message, '_write_headers', lambda self: None)
# Add all the individual requests.
for request_id in order:
request = requests[request_id]
msg = MIMENonMultipart('application', 'http')
msg['Content-Transfer-Encoding'] = 'binary'
msg['Content-ID'] = self._id_to_header(request_id)
body = self._serialize_request(request)
msg.set_payload(body)
message.attach(msg)
body = message.as_string()
headers = {}
headers['content-type'] = ('multipart/mixed; '
'boundary="%s"') % message.get_boundary()
resp, content = http.request(self._batch_uri, 'POST', body=body,
headers=headers)
if resp.status >= 300:
raise HttpError(resp, content, self._batch_uri)
# Now break out the individual responses and store each one.
boundary, _ = content.split(None, 1)
# Prepend with a content-type header so FeedParser can handle it.
header = 'content-type: %s\r\n\r\n' % resp['content-type']
for_parser = header + content
parser = FeedParser()
parser.feed(for_parser)
mime_response = parser.close()
if not mime_response.is_multipart():
raise BatchError("Response not in multipart/mixed format.", resp,
content)
for part in mime_response.get_payload():
request_id = self._header_to_id(part['Content-ID'])
headers, content = self._deserialize_response(part.get_payload())
self._responses[request_id] = (headers, content)
def execute(self, http=None):
"""Execute all the requests as a single batched HTTP request.
Args:
http: httplib2.Http, an http object to be used in place of the one the
HttpRequest request object was constructed with. If one isn't supplied
then use a http object from the requests in this batch.
Returns:
None
Raises:
httplib2.Error if a transport error has occured.
apiclient.errors.BatchError if the response is the wrong format.
"""
# If http is not supplied use the first valid one given in the requests.
if http is None:
for request_id in self._order:
request = self._requests[request_id]
if request is not None:
http = request.http
break
if http is None:
raise ValueError("Missing a valid http object.")
self._execute(http, self._order, self._requests)
# Loop over all the requests and check for 401s. For each 401 request the
# credentials should be refreshed and then sent again in a separate batch.
redo_requests = {}
redo_order = []
for request_id in self._order:
headers, content = self._responses[request_id]
if headers['status'] == '401':
redo_order.append(request_id)
request = self._requests[request_id]
self._refresh_and_apply_credentials(request, http)
redo_requests[request_id] = request
if redo_requests:
self._execute(http, redo_order, redo_requests)
# Now process all callbacks that are erroring, and raise an exception for
# ones that return a non-2xx response? Or add extra parameter to callback
# that contains an HttpError?
for request_id in self._order:
headers, content = self._responses[request_id]
request = self._requests[request_id]
callback = self._callbacks[request_id]
response = None
exception = None
try:
r = httplib2.Response(headers)
response = request.postproc(r, content)
except HttpError, e:
exception = e
if callback is not None:
callback(request_id, response, exception)
if self._callback is not None:
self._callback(request_id, response, exception)
class HttpRequestMock(object):
"""Mock of HttpRequest.
Do not construct directly, instead use RequestMockBuilder.
"""
def __init__(self, resp, content, postproc):
"""Constructor for HttpRequestMock
Args:
resp: httplib2.Response, the response to emulate coming from the request
content: string, the response body
postproc: callable, the post processing function usually supplied by
the model class. See model.JsonModel.response() as an example.
"""
self.resp = resp
self.content = content
self.postproc = postproc
if resp is None:
self.resp = httplib2.Response({'status': 200, 'reason': 'OK'})
if 'reason' in self.resp:
self.resp.reason = self.resp['reason']
def execute(self, http=None):
"""Execute the request.
Same behavior as HttpRequest.execute(), but the response is
mocked and not really from an HTTP request/response.
"""
return self.postproc(self.resp, self.content)
class RequestMockBuilder(object):
"""A simple mock of HttpRequest
Pass in a dictionary to the constructor that maps request methodIds to
tuples of (httplib2.Response, content, opt_expected_body) that should be
returned when that method is called. None may also be passed in for the
httplib2.Response, in which case a 200 OK response will be generated.
If an opt_expected_body (str or dict) is provided, it will be compared to
the body and UnexpectedBodyError will be raised on inequality.
Example:
response = '{"data": {"id": "tag:google.c...'
requestBuilder = RequestMockBuilder(
{
'plus.activities.get': (None, response),
}
)
apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder)
Methods that you do not supply a response for will return a
200 OK with an empty string as the response content or raise an excpetion
if check_unexpected is set to True. The methodId is taken from the rpcName
in the discovery document.
For more details see the project wiki.
"""
def __init__(self, responses, check_unexpected=False):
"""Constructor for RequestMockBuilder
The constructed object should be a callable object
that can replace the class HttpResponse.
responses - A dictionary that maps methodIds into tuples
of (httplib2.Response, content). The methodId
comes from the 'rpcName' field in the discovery
document.
check_unexpected - A boolean setting whether or not UnexpectedMethodError
should be raised on unsupplied method.
"""
self.responses = responses
self.check_unexpected = check_unexpected
def __call__(self, http, postproc, uri, method='GET', body=None,
headers=None, methodId=None, resumable=None):
"""Implements the callable interface that discovery.build() expects
of requestBuilder, which is to build an object compatible with
HttpRequest.execute(). See that method for the description of the
parameters and the expected response.
"""
if methodId in self.responses:
response = self.responses[methodId]
resp, content = response[:2]
if len(response) > 2:
# Test the body against the supplied expected_body.
expected_body = response[2]
if bool(expected_body) != bool(body):
# Not expecting a body and provided one
# or expecting a body and not provided one.
raise UnexpectedBodyError(expected_body, body)
if isinstance(expected_body, str):
expected_body = simplejson.loads(expected_body)
body = simplejson.loads(body)
if body != expected_body:
raise UnexpectedBodyError(expected_body, body)
return HttpRequestMock(resp, content, postproc)
elif self.check_unexpected:
raise UnexpectedMethodError(methodId)
else:
model = JsonModel(False)
return HttpRequestMock(None, '{}', model.response)
class HttpMock(object):
"""Mock of httplib2.Http"""
def __init__(self, filename, headers=None):
"""
Args:
filename: string, absolute filename to read response from
headers: dict, header to return with response
"""
if headers is None:
headers = {'status': '200 OK'}
f = file(filename, 'r')
self.data = f.read()
f.close()
self.headers = headers
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
return httplib2.Response(self.headers), self.data
class HttpMockSequence(object):
"""Mock of httplib2.Http
Mocks a sequence of calls to request returning different responses for each
call. Create an instance initialized with the desired response headers
and content and then use as if an httplib2.Http instance.
http = HttpMockSequence([
({'status': '401'}, ''),
({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
({'status': '200'}, 'echo_request_headers'),
])
resp, content = http.request("http://examples.com")
There are special values you can pass in for content to trigger
behavours that are helpful in testing.
'echo_request_headers' means return the request headers in the response body
'echo_request_headers_as_json' means return the request headers in
the response body
'echo_request_body' means return the request body in the response body
'echo_request_uri' means return the request uri in the response body
"""
def __init__(self, iterable):
"""
Args:
iterable: iterable, a sequence of pairs of (headers, body)
"""
self._iterable = iterable
self.follow_redirects = True
def request(self, uri,
method='GET',
body=None,
headers=None,
redirections=1,
connection_type=None):
resp, content = self._iterable.pop(0)
if content == 'echo_request_headers':
content = headers
elif content == 'echo_request_headers_as_json':
content = simplejson.dumps(headers)
elif content == 'echo_request_body':
content = body
elif content == 'echo_request_uri':
content = uri
return httplib2.Response(resp), content
def set_user_agent(http, user_agent):
"""Set the user-agent on every request.
Args:
http - An instance of httplib2.Http
or something that acts like it.
user_agent: string, the value for the user-agent header.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = set_user_agent(h, "my-app-name/6.0")
Most of the time the user-agent will be set doing auth, this is for the rare
cases where you are accessing an unauthenticated endpoint.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if 'user-agent' in headers:
headers['user-agent'] = user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
def tunnel_patch(http):
"""Tunnel PATCH requests over POST.
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = tunnel_patch(h, "my-app-name/6.0")
Useful if you are running on a platform that doesn't support PATCH.
Apply this last if you are using OAuth 1.0, as changing the method
will result in a different signature.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the user-agent."""
if headers is None:
headers = {}
if method == 'PATCH':
if 'oauth_token' in headers.get('authorization', ''):
logging.warning(
'OAuth 1.0 request made with Credentials after tunnel_patch.')
headers['x-http-method-override'] = "PATCH"
method = 'POST'
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
return resp, content
http.request = new_request
return http
| 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.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
import httplib2
import logging
import oauth2 as oauth
import urllib
import urlparse
from anyjson import simplejson
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
class Error(Exception):
"""Base error for this module."""
pass
class RequestError(Error):
"""Error occurred during request."""
pass
class MissingParameter(Error):
pass
class CredentialsInvalidError(Error):
pass
def _abstract():
raise NotImplementedError('You need to override this function')
def _oauth_uri(name, discovery, params):
"""Look up the OAuth URI from the discovery
document and add query parameters based on
params.
name - The name of the OAuth URI to lookup, one
of 'request', 'access', or 'authorize'.
discovery - Portion of discovery document the describes
the OAuth endpoints.
params - Dictionary that is used to form the query parameters
for the specified URI.
"""
if name not in ['request', 'access', 'authorize']:
raise KeyError(name)
keys = discovery[name]['parameters'].keys()
query = {}
for key in keys:
if key in params:
query[key] = params[key]
return discovery[name]['url'] + '?' + urllib.urlencode(query)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method
that applies the credentials to an HTTP transport.
"""
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential.
"""
def get(self):
"""Retrieve credential.
Returns:
apiclient.oauth.Credentials
"""
_abstract()
def put(self, credentials):
"""Write a credential.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
class OAuthCredentials(Credentials):
"""Credentials object for OAuth 1.0a
"""
def __init__(self, consumer, token, user_agent):
"""
consumer - An instance of oauth.Consumer.
token - An instance of oauth.Token constructed with
the access token and secret.
user_agent - The HTTP User-Agent to provide for this application.
"""
self.consumer = consumer
self.token = token
self.user_agent = user_agent
self.store = None
# True if the credentials have been revoked
self._invalid = False
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked."""
return getattr(self, "_invalid", False)
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
req = oauth.Request.from_consumer_and_token(
self.consumer, self.token, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, self.token)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
# Update the stored credential if it becomes invalid.
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
self._invalid = True
if self.store is not None:
self.store(self)
raise CredentialsInvalidError("Credentials are no longer valid.")
return resp, content
http.request = new_request
return http
class TwoLeggedOAuthCredentials(Credentials):
"""Two Legged Credentials object for OAuth 1.0a.
The Two Legged object is created directly, not from a flow. Once you
authorize and httplib2.Http instance you can change the requestor and that
change will propogate to the authorized httplib2.Http instance. For example:
http = httplib2.Http()
http = credentials.authorize(http)
credentials.requestor = 'foo@example.info'
http.request(...)
credentials.requestor = 'bar@example.info'
http.request(...)
"""
def __init__(self, consumer_key, consumer_secret, user_agent):
"""
Args:
consumer_key: string, An OAuth 1.0 consumer key
consumer_secret: string, An OAuth 1.0 consumer secret
user_agent: string, The HTTP User-Agent to provide for this application.
"""
self.consumer = oauth.Consumer(consumer_key, consumer_secret)
self.user_agent = user_agent
self.store = None
# email address of the user to act on the behalf of.
self._requestor = None
@property
def invalid(self):
"""True if the credentials are invalid, such as being revoked.
Always returns False for Two Legged Credentials.
"""
return False
def getrequestor(self):
return self._requestor
def setrequestor(self, email):
self._requestor = email
requestor = property(getrequestor, setrequestor, None,
'The email address of the user to act on behalf of')
def set_store(self, store):
"""Set the storage for the credential.
Args:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has been revoked.
"""
self.store = store
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def authorize(self, http):
"""Authorize an httplib2.Http instance with these Credentials
Args:
http - An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth
subclass of httplib2.Authenication because
it never gets passed the absolute URI, which is
needed for signing. So instead we have to overload
'request' with a closure that adds in the
Authorization header and then calls the original version
of 'request()'.
"""
request_orig = http.request
signer = oauth.SignatureMethod_HMAC_SHA1()
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
"""Modify the request headers to add the appropriate
Authorization header."""
response_code = 302
http.follow_redirects = False
while response_code in [301, 302]:
# add in xoauth_requestor_id=self._requestor to the uri
if self._requestor is None:
raise MissingParameter(
'Requestor must be set before using TwoLeggedOAuthCredentials')
parsed = list(urlparse.urlparse(uri))
q = parse_qsl(parsed[4])
q.append(('xoauth_requestor_id', self._requestor))
parsed[4] = urllib.urlencode(q)
uri = urlparse.urlunparse(parsed)
req = oauth.Request.from_consumer_and_token(
self.consumer, None, http_method=method, http_url=uri)
req.sign_request(signer, self.consumer, None)
if headers is None:
headers = {}
headers.update(req.to_header())
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
response_code = resp.status
if response_code in [301, 302]:
uri = resp['location']
if response_code == 401:
logging.info('Access token no longer valid: %s' % content)
# Do not store the invalid state of the Credentials because
# being 2LO they could be reinstated in the future.
raise CredentialsInvalidError("Credentials are invalid.")
return resp, content
http.request = new_request
return http
class FlowThreeLegged(Flow):
"""Does the Three Legged Dance for OAuth 1.0a.
"""
def __init__(self, discovery, consumer_key, consumer_secret, user_agent,
**kwargs):
"""
discovery - Section of the API discovery document that describes
the OAuth endpoints.
consumer_key - OAuth consumer key
consumer_secret - OAuth consumer secret
user_agent - The HTTP User-Agent that identifies the application.
**kwargs - The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.discovery = discovery
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.user_agent = user_agent
self.params = kwargs
self.request_token = {}
required = {}
for uriinfo in discovery.itervalues():
for name, value in uriinfo['parameters'].iteritems():
if value['required'] and not name.startswith('oauth_'):
required[name] = 1
for key in required.iterkeys():
if key not in self.params:
raise MissingParameter('Required parameter %s not supplied' % key)
def step1_get_authorize_url(self, oauth_callback='oob'):
"""Returns a URI to redirect to the provider.
oauth_callback - Either the string 'oob' for a non-web-based application,
or a URI that handles the callback from the authorization
server.
If oauth_callback is 'oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
body = urllib.urlencode({'oauth_callback': oauth_callback})
uri = _oauth_uri('request', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers,
body=body)
if resp['status'] != '200':
logging.error('Failed to retrieve temporary authorization: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
self.request_token = dict(parse_qsl(content))
auth_params = copy.copy(self.params)
auth_params['oauth_token'] = self.request_token['oauth_token']
return _oauth_uri('authorize', self.discovery, auth_params)
def step2_exchange(self, verifier):
"""Exhanges an authorized request token
for OAuthCredentials.
Args:
verifier: string, dict - either the verifier token, or a dictionary
of the query parameters to the callback, which contains
the oauth_verifier.
Returns:
The Credentials object.
"""
if not (isinstance(verifier, str) or isinstance(verifier, unicode)):
verifier = verifier['oauth_verifier']
token = oauth.Token(
self.request_token['oauth_token'],
self.request_token['oauth_token_secret'])
token.set_verifier(verifier)
consumer = oauth.Consumer(self.consumer_key, self.consumer_secret)
client = oauth.Client(consumer, token)
headers = {
'user-agent': self.user_agent,
'content-type': 'application/x-www-form-urlencoded'
}
uri = _oauth_uri('access', self.discovery, self.params)
resp, content = client.request(uri, 'POST', headers=headers)
if resp['status'] != '200':
logging.error('Failed to retrieve access token: %s', content)
raise RequestError('Invalid response %s.' % resp['status'])
oauth_params = dict(parse_qsl(content))
token = oauth.Token(
oauth_params['oauth_token'],
oauth_params['oauth_token_secret'])
return OAuthCredentials(consumer, token, self.user_agent)
| 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.
"""Model objects for requests and responses.
Each API may support one or more serializations, such
as JSON, Atom, etc. The model classes are responsible
for converting between the wire format and the Python
object representation.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import urllib
from errors import HttpError
from oauth2client.anyjson import simplejson
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('dump_request_response', False,
'Dump all http server requests and responses. '
)
def _abstract():
raise NotImplementedError('You need to override this function')
class Model(object):
"""Model base class.
All Model classes should implement this interface.
The Model serializes and de-serializes between a wire
format such as JSON and a Python object representation.
"""
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized in the desired wire format.
"""
_abstract()
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
_abstract()
class BaseModel(Model):
"""Base model class.
Subclasses should provide implementations for the "serialize" and
"deserialize" methods, as well as values for the following class attributes.
Attributes:
accept: The value to use for the HTTP Accept header.
content_type: The value to use for the HTTP Content-type header.
no_content_response: The value to return when deserializing a 204 "No
Content" response.
alt_param: The value to supply as the "alt" query parameter for requests.
"""
accept = None
content_type = None
no_content_response = None
alt_param = None
def _log_request(self, headers, path_params, query, body):
"""Logs debugging information about the request if requested."""
if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for h, v in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for h, v in path_params.iteritems():
logging.info('%s: %s', h, v)
logging.info('-path-parameters-end-')
logging.info('body: %s', body)
logging.info('query: %s', query)
logging.info('--request-end--')
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized as JSON
"""
query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is not None:
headers['content-type'] = self.content_type
body_value = self.serialize(body_value)
self._log_request(headers, path_params, query, body_value)
return (headers, path_params, query, body_value)
def _build_query(self, params):
"""Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.
"""
if self.alt_param is not None:
params.update({'alt': self.alt_param})
astuples = []
for key, value in params.iteritems():
if type(value) == type([]):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def _log_response(self, resp, content):
"""Logs debugging information about the response if requested."""
if FLAGS.dump_request_response:
logging.info('--response-start--')
for h, v in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
self._log_response(resp, content)
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
if resp.status == 204:
# A 204: No Content response should be treated differently
# to all the other success states
return self.no_content_response
return self.deserialize(content)
else:
logging.debug('Content from bad request was: %s' % content)
raise HttpError(resp, content)
def serialize(self, body_value):
"""Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.
"""
_abstract()
def deserialize(self, content):
"""Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
"""
_abstract()
class JsonModel(BaseModel):
"""Model class for JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request and response bodies.
"""
accept = 'application/json'
content_type = 'application/json'
alt_param = 'json'
def __init__(self, data_wrapper=False):
"""Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper
"""
self._data_wrapper = data_wrapper
def serialize(self, body_value):
if (isinstance(body_value, dict) and 'data' not in body_value and
self._data_wrapper):
body_value = {'data': body_value}
return simplejson.dumps(body_value)
def deserialize(self, content):
body = simplejson.loads(content)
if isinstance(body, dict) and 'data' in body:
body = body['data']
return body
@property
def no_content_response(self):
return {}
class RawModel(JsonModel):
"""Model class for requests that don't return JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = None
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class MediaModel(JsonModel):
"""Model class for requests that return Media.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = 'media'
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class ProtocolBufferModel(BaseModel):
"""Model class for protocol buffers.
Serializes and de-serializes the binary protocol buffer sent in the HTTP
request and response bodies.
"""
accept = 'application/x-protobuf'
content_type = 'application/x-protobuf'
alt_param = 'proto'
def __init__(self, protocol_buffer):
"""Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.
"""
self._protocol_buffer = protocol_buffer
def serialize(self, body_value):
return body_value.SerializeToString()
def deserialize(self, content):
return self._protocol_buffer.FromString(content)
@property
def no_content_response(self):
return self._protocol_buffer()
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the original deserialized resource
modified: object, the modified deserialized resource
Returns:
An object that contains only the changes from original to modified, in a
form suitable to pass to a PATCH method.
Example usage:
item = service.activities().get(postid=postid, userid=userid).execute()
original = copy.deepcopy(item)
item['object']['content'] = 'This is updated.'
service.activities.patch(postid=postid, userid=userid,
body=makepatch(original, item)).execute()
"""
patch = {}
for key, original_value in original.iteritems():
modified_value = modified.get(key, None)
if modified_value is None:
# Use None to signal that the element is deleted
patch[key] = None
elif original_value != modified_value:
if type(original_value) == type({}):
# Recursively descend objects
patch[key] = makepatch(original_value, modified_value)
else:
# In the case of simple types or arrays we just replace
patch[key] = modified_value
else:
# Don't add anything to patch if there's no change
pass
for key in modified:
if key not in original:
patch[key] = modified[key]
return patch
| 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.
"""Client for discovery based APIs
A client library for Google's discovery based APIs.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
__all__ = [
'build',
'build_from_document'
'fix_method_name',
'key2param'
]
import copy
import httplib2
import logging
import os
import random
import re
import uritemplate
import urllib
import urlparse
import mimeparse
import mimetypes
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
from apiclient.errors import HttpError
from apiclient.errors import InvalidJsonError
from apiclient.errors import MediaUploadSizeError
from apiclient.errors import UnacceptableMimeTypeError
from apiclient.errors import UnknownApiNameOrVersion
from apiclient.errors import UnknownLinkType
from apiclient.http import HttpRequest
from apiclient.http import MediaFileUpload
from apiclient.http import MediaUpload
from apiclient.model import JsonModel
from apiclient.model import MediaModel
from apiclient.model import RawModel
from apiclient.schema import Schemas
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from oauth2client.anyjson import simplejson
logger = logging.getLogger(__name__)
URITEMPLATE = re.compile('{[^}]*}')
VARNAME = re.compile('[a-zA-Z0-9_-]+')
DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
'{api}/{apiVersion}/rest')
DEFAULT_METHOD_DOC = 'A description of how to use this function'
# Parameters accepted by the stack, but not visible via discovery.
STACK_QUERY_PARAMETERS = ['trace', 'pp', 'userip', 'strict']
# Python reserved words.
RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try', 'while' ]
def fix_method_name(name):
"""Fix method names to avoid reserved word conflicts.
Args:
name: string, method name.
Returns:
The name with a '_' prefixed if the name is a reserved word.
"""
if name in RESERVED_WORDS:
return name + '_'
else:
return name
def _add_query_parameter(url, name, value):
"""Adds a query parameter to a url.
Replaces the current value if it already exists in the URL.
Args:
url: string, url to add the query parameter to.
name: string, query parameter name.
value: string, query parameter value.
Returns:
Updated query parameter. Does not update the url if value is None.
"""
if value is None:
return url
else:
parsed = list(urlparse.urlparse(url))
q = dict(parse_qsl(parsed[4]))
q[name] = value
parsed[4] = urllib.urlencode(q)
return urlparse.urlunparse(parsed)
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
Args:
key: string, the method key name.
Returns:
A safe method name based on the key name.
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result)
def build(serviceName,
version,
http=None,
discoveryServiceUrl=DISCOVERY_URI,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Construct a Resource for interacting with an API.
Construct a Resource object for interacting with an API. The serviceName and
version are the names from the Discovery service.
Args:
serviceName: string, name of the service.
version: string, the version of the service.
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
discoveryServiceUrl: string, a URI Template that points to the location of
the discovery service. It should have two parameters {api} and
{apiVersion} that when filled in produce an absolute URI to the discovery
document for that service.
developerKey: string, key obtained from
https://code.google.com/apis/console.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: apiclient.http.HttpRequest, encapsulator for an HTTP
request.
Returns:
A Resource object with methods for interacting with the service.
"""
params = {
'api': serviceName,
'apiVersion': version
}
if http is None:
http = httplib2.Http()
requested_url = uritemplate.expand(discoveryServiceUrl, params)
# REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
# variable that contains the network address of the client sending the
# request. If it exists then add that to the request for the discovery
# document to avoid exceeding the quota on discovery requests.
if 'REMOTE_ADDR' in os.environ:
requested_url = _add_query_parameter(requested_url, 'userIp',
os.environ['REMOTE_ADDR'])
logger.info('URL being requested: %s' % requested_url)
resp, content = http.request(requested_url)
if resp.status == 404:
raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
version))
if resp.status >= 400:
raise HttpError(resp, content, requested_url)
try:
service = simplejson.loads(content)
except ValueError, e:
logger.error('Failed to parse as JSON: ' + content)
raise InvalidJsonError()
return build_from_document(content, discoveryServiceUrl, http=http,
developerKey=developerKey, model=model, requestBuilder=requestBuilder)
def build_from_document(
service,
base,
future=None,
http=None,
developerKey=None,
model=None,
requestBuilder=HttpRequest):
"""Create a Resource for interacting with an API.
Same as `build()`, but constructs the Resource object from a discovery
document that is it given, as opposed to retrieving one over HTTP.
Args:
service: string, discovery document.
base: string, base URI for all HTTP requests, usually the discovery URI.
future: string, discovery document with future capabilities (deprecated).
http: httplib2.Http, An instance of httplib2.Http or something that acts
like it that HTTP requests will be made through.
developerKey: string, Key for controlling API usage, generated
from the API Console.
model: Model class instance that serializes and de-serializes requests and
responses.
requestBuilder: Takes an http request and packages it up to be executed.
Returns:
A Resource object with methods for interacting with the service.
"""
# future is no longer used.
future = {}
service = simplejson.loads(service)
base = urlparse.urljoin(base, service['basePath'])
schema = Schemas(service)
if model is None:
features = service.get('features', [])
model = JsonModel('dataWrapper' in features)
resource = _createResource(http, base, model, requestBuilder, developerKey,
service, service, schema)
return resource
def _cast(value, schema_type):
"""Convert value to a string based on JSON Schema type.
See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
JSON Schema.
Args:
value: any, the value to convert
schema_type: string, the type that value should be interpreted as
Returns:
A string representation of 'value' based on the schema_type.
"""
if schema_type == 'string':
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
elif schema_type == 'integer':
return str(int(value))
elif schema_type == 'number':
return str(float(value))
elif schema_type == 'boolean':
return str(bool(value)).lower()
else:
if type(value) == type('') or type(value) == type(u''):
return value
else:
return str(value)
MULTIPLIERS = {
"KB": 2 ** 10,
"MB": 2 ** 20,
"GB": 2 ** 30,
"TB": 2 ** 40,
}
def _media_size_to_long(maxSize):
"""Convert a string media size, such as 10GB or 3TB into an integer.
Args:
maxSize: string, size as a string, such as 2MB or 7GB.
Returns:
The size as an integer value.
"""
if len(maxSize) < 2:
return 0
units = maxSize[-2:].upper()
multiplier = MULTIPLIERS.get(units, 0)
if multiplier:
return int(maxSize[:-2]) * multiplier
else:
return int(maxSize)
def _createResource(http, baseUrl, model, requestBuilder,
developerKey, resourceDesc, rootDesc, schema):
"""Build a Resource from the API description.
Args:
http: httplib2.Http, Object to make http requests with.
baseUrl: string, base URL for the API. All requests are relative to this
URI.
model: apiclient.Model, converts to and from the wire format.
requestBuilder: class or callable that instantiates an
apiclient.HttpRequest object.
developerKey: string, key obtained from
https://code.google.com/apis/console
resourceDesc: object, section of deserialized discovery document that
describes a resource. Note that the top level discovery document
is considered a resource.
rootDesc: object, the entire deserialized discovery document.
schema: object, mapping of schema names to schema descriptions.
Returns:
An instance of Resource with all the methods attached for interacting with
that resource.
"""
class Resource(object):
"""A class for interacting with a resource."""
def __init__(self):
self._http = http
self._baseUrl = baseUrl
self._model = model
self._developerKey = developerKey
self._requestBuilder = requestBuilder
def createMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates a method for attaching to a Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
pathUrl = methodDesc['path']
httpMethod = methodDesc['httpMethod']
methodId = methodDesc['id']
mediaPathUrl = None
accept = []
maxSize = 0
if 'mediaUpload' in methodDesc:
mediaUpload = methodDesc['mediaUpload']
# TODO(jcgregorio) Use URLs from discovery once it is updated.
parsed = list(urlparse.urlparse(baseUrl))
basePath = parsed[2]
mediaPathUrl = '/upload' + basePath + pathUrl
accept = mediaUpload['accept']
maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
if 'parameters' not in methodDesc:
methodDesc['parameters'] = {}
# Add in the parameters common to all methods.
for name, desc in rootDesc.get('parameters', {}).iteritems():
methodDesc['parameters'][name] = desc
# Add in undocumented query parameters.
for name in STACK_QUERY_PARAMETERS:
methodDesc['parameters'][name] = {
'type': 'string',
'location': 'query'
}
if httpMethod in ['PUT', 'POST', 'PATCH'] and 'request' in methodDesc:
methodDesc['parameters']['body'] = {
'description': 'The request body.',
'type': 'object',
'required': True,
}
if 'request' in methodDesc:
methodDesc['parameters']['body'].update(methodDesc['request'])
else:
methodDesc['parameters']['body']['type'] = 'object'
if 'mediaUpload' in methodDesc:
methodDesc['parameters']['media_body'] = {
'description': 'The filename of the media request body.',
'type': 'string',
'required': False,
}
if 'body' in methodDesc['parameters']:
methodDesc['parameters']['body']['required'] = False
argmap = {} # Map from method parameter name to query parameter name
required_params = [] # Required parameters
repeated_params = [] # Repeated parameters
pattern_params = {} # Parameters that must match a regex
query_params = [] # Parameters that will be used in the query string
path_params = {} # Parameters that will be used in the base URL
param_type = {} # The type of the parameter
enum_params = {} # Allowable enumeration values for each parameter
if 'parameters' in methodDesc:
for arg, desc in methodDesc['parameters'].iteritems():
param = key2param(arg)
argmap[param] = arg
if desc.get('pattern', ''):
pattern_params[param] = desc['pattern']
if desc.get('enum', ''):
enum_params[param] = desc['enum']
if desc.get('required', False):
required_params.append(param)
if desc.get('repeated', False):
repeated_params.append(param)
if desc.get('location') == 'query':
query_params.append(param)
if desc.get('location') == 'path':
path_params[param] = param
param_type[param] = desc.get('type', 'string')
for match in URITEMPLATE.finditer(pathUrl):
for namematch in VARNAME.finditer(match.group(0)):
name = key2param(namematch.group(0))
path_params[name] = name
if name in query_params:
query_params.remove(name)
def method(self, **kwargs):
# Don't bother with doc string, it will be over-written by createMethod.
for name in kwargs.iterkeys():
if name not in argmap:
raise TypeError('Got an unexpected keyword argument "%s"' % name)
# Remove args that have a value of None.
keys = kwargs.keys()
for name in keys:
if kwargs[name] is None:
del kwargs[name]
for name in required_params:
if name not in kwargs:
raise TypeError('Missing required parameter "%s"' % name)
for name, regex in pattern_params.iteritems():
if name in kwargs:
if isinstance(kwargs[name], basestring):
pvalues = [kwargs[name]]
else:
pvalues = kwargs[name]
for pvalue in pvalues:
if re.match(regex, pvalue) is None:
raise TypeError(
'Parameter "%s" value "%s" does not match the pattern "%s"' %
(name, pvalue, regex))
for name, enums in enum_params.iteritems():
if name in kwargs:
# We need to handle the case of a repeated enum
# name differently, since we want to handle both
# arg='value' and arg=['value1', 'value2']
if (name in repeated_params and
not isinstance(kwargs[name], basestring)):
values = kwargs[name]
else:
values = [kwargs[name]]
for value in values:
if value not in enums:
raise TypeError(
'Parameter "%s" value "%s" is not an allowed value in "%s"' %
(name, value, str(enums)))
actual_query_params = {}
actual_path_params = {}
for key, value in kwargs.iteritems():
to_type = param_type.get(key, 'string')
# For repeated parameters we cast each member of the list.
if key in repeated_params and type(value) == type([]):
cast_value = [_cast(x, to_type) for x in value]
else:
cast_value = _cast(value, to_type)
if key in query_params:
actual_query_params[argmap[key]] = cast_value
if key in path_params:
actual_path_params[argmap[key]] = cast_value
body_value = kwargs.get('body', None)
media_filename = kwargs.get('media_body', None)
if self._developerKey:
actual_query_params['key'] = self._developerKey
model = self._model
# If there is no schema for the response then presume a binary blob.
if methodName.endswith('_media'):
model = MediaModel()
elif 'response' not in methodDesc:
model = RawModel()
headers = {}
headers, params, query, body = model.request(headers,
actual_path_params, actual_query_params, body_value)
expanded_url = uritemplate.expand(pathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
resumable = None
multipart_boundary = ''
if media_filename:
# Ensure we end up with a valid MediaUpload object.
if isinstance(media_filename, basestring):
(media_mime_type, encoding) = mimetypes.guess_type(media_filename)
if media_mime_type is None:
raise UnknownFileType(media_filename)
if not mimeparse.best_match([media_mime_type], ','.join(accept)):
raise UnacceptableMimeTypeError(media_mime_type)
media_upload = MediaFileUpload(media_filename, media_mime_type)
elif isinstance(media_filename, MediaUpload):
media_upload = media_filename
else:
raise TypeError('media_filename must be str or MediaUpload.')
# Check the maxSize
if maxSize > 0 and media_upload.size() > maxSize:
raise MediaUploadSizeError("Media larger than: %s" % maxSize)
# Use the media path uri for media uploads
expanded_url = uritemplate.expand(mediaPathUrl, params)
url = urlparse.urljoin(self._baseUrl, expanded_url + query)
if media_upload.resumable():
url = _add_query_parameter(url, 'uploadType', 'resumable')
if media_upload.resumable():
# This is all we need to do for resumable, if the body exists it gets
# sent in the first request, otherwise an empty body is sent.
resumable = media_upload
else:
# A non-resumable upload
if body is None:
# This is a simple media upload
headers['content-type'] = media_upload.mimetype()
body = media_upload.getbytes(0, media_upload.size())
url = _add_query_parameter(url, 'uploadType', 'media')
else:
# This is a multipart/related upload.
msgRoot = MIMEMultipart('related')
# msgRoot should not write out it's own headers
setattr(msgRoot, '_write_headers', lambda self: None)
# attach the body as one part
msg = MIMENonMultipart(*headers['content-type'].split('/'))
msg.set_payload(body)
msgRoot.attach(msg)
# attach the media as the second part
msg = MIMENonMultipart(*media_upload.mimetype().split('/'))
msg['Content-Transfer-Encoding'] = 'binary'
payload = media_upload.getbytes(0, media_upload.size())
msg.set_payload(payload)
msgRoot.attach(msg)
body = msgRoot.as_string()
multipart_boundary = msgRoot.get_boundary()
headers['content-type'] = ('multipart/related; '
'boundary="%s"') % multipart_boundary
url = _add_query_parameter(url, 'uploadType', 'multipart')
logger.info('URL being requested: %s' % url)
return self._requestBuilder(self._http,
model.response,
url,
method=httpMethod,
body=body,
headers=headers,
methodId=methodId,
resumable=resumable)
docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
if len(argmap) > 0:
docs.append('Args:\n')
# Skip undocumented params and params common to all methods.
skip_parameters = rootDesc.get('parameters', {}).keys()
skip_parameters.append(STACK_QUERY_PARAMETERS)
for arg in argmap.iterkeys():
if arg in skip_parameters:
continue
repeated = ''
if arg in repeated_params:
repeated = ' (repeated)'
required = ''
if arg in required_params:
required = ' (required)'
paramdesc = methodDesc['parameters'][argmap[arg]]
paramdoc = paramdesc.get('description', 'A parameter')
if '$ref' in paramdesc:
docs.append(
(' %s: object, %s%s%s\n The object takes the'
' form of:\n\n%s\n\n') % (arg, paramdoc, required, repeated,
schema.prettyPrintByName(paramdesc['$ref'])))
else:
paramtype = paramdesc.get('type', 'string')
docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
repeated))
enum = paramdesc.get('enum', [])
enumDesc = paramdesc.get('enumDescriptions', [])
if enum and enumDesc:
docs.append(' Allowed values\n')
for (name, desc) in zip(enum, enumDesc):
docs.append(' %s - %s\n' % (name, desc))
if 'response' in methodDesc:
if methodName.endswith('_media'):
docs.append('\nReturns:\n The media object as a string.\n\n ')
else:
docs.append('\nReturns:\n An object of the form:\n\n ')
docs.append(schema.prettyPrintSchema(methodDesc['response']))
setattr(method, '__doc__', ''.join(docs))
setattr(theclass, methodName, method)
def createNextMethod(theclass, methodName, methodDesc, rootDesc):
"""Creates any _next methods for attaching to a Resource.
The _next methods allow for easy iteration through list() responses.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
methodId = methodDesc['id'] + '.next'
def methodNext(self, previous_request, previous_response):
"""Retrieves the next page of results.
Args:
previous_request: The request for the previous page.
previous_response: The response from the request for the previous page.
Returns:
A request object that you can call 'execute()' on to request the next
page. Returns None if there are no more items in the collection.
"""
# Retrieve nextPageToken from previous_response
# Use as pageToken in previous_request to create new request.
if 'nextPageToken' not in previous_response:
return None
request = copy.copy(previous_request)
pageToken = previous_response['nextPageToken']
parsed = list(urlparse.urlparse(request.uri))
q = parse_qsl(parsed[4])
# Find and remove old 'pageToken' value from URI
newq = [(key, value) for (key, value) in q if key != 'pageToken']
newq.append(('pageToken', pageToken))
parsed[4] = urllib.urlencode(newq)
uri = urlparse.urlunparse(parsed)
request.uri = uri
logger.info('URL being requested: %s' % uri)
return request
setattr(theclass, methodName, methodNext)
# Add basic methods to Resource
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
createMethod(Resource, methodName, methodDesc, rootDesc)
# Add in _media methods. The functionality of the attached method will
# change when it sees that the method name ends in _media.
if methodDesc.get('supportsMediaDownload', False):
createMethod(Resource, methodName + '_media', methodDesc, rootDesc)
# Add in nested resources
if 'resources' in resourceDesc:
def createResourceMethod(theclass, methodName, methodDesc, rootDesc):
"""Create a method on the Resource to access a nested Resource.
Args:
theclass: type, the class to attach methods to.
methodName: string, name of the method to use.
methodDesc: object, fragment of deserialized discovery document that
describes the method.
rootDesc: object, the entire deserialized discovery document.
"""
methodName = fix_method_name(methodName)
def methodResource(self):
return _createResource(self._http, self._baseUrl, self._model,
self._requestBuilder, self._developerKey,
methodDesc, rootDesc, schema)
setattr(methodResource, '__doc__', 'A collection resource.')
setattr(methodResource, '__is_resource__', True)
setattr(theclass, methodName, methodResource)
for methodName, methodDesc in resourceDesc['resources'].iteritems():
createResourceMethod(Resource, methodName, methodDesc, rootDesc)
# Add _next() methods
# Look for response bodies in schema that contain nextPageToken, and methods
# that take a pageToken parameter.
if 'methods' in resourceDesc:
for methodName, methodDesc in resourceDesc['methods'].iteritems():
if 'response' in methodDesc:
responseSchema = methodDesc['response']
if '$ref' in responseSchema:
responseSchema = schema.get(responseSchema['$ref'])
hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
{})
hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
if hasNextPageToken and hasPageToken:
createNextMethod(Resource, methodName + '_next',
resourceDesc['methods'][methodName],
methodName)
return Resource()
| 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.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 1.0 credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pickle
import threading
from apiclient.oauth import Storage as BaseStorage
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def get(self):
"""Retrieve Credential from file.
Returns:
apiclient.oauth.Credentials
"""
self._lock.acquire()
try:
f = open(self._filename, 'r')
credentials = pickle.loads(f.read())
f.close()
credentials.set_store(self.put)
except:
credentials = None
self._lock.release()
return credentials
def put(self, credentials):
"""Write a pickled Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._lock.acquire()
f = open(self._filename, 'w')
f.write(pickle.dumps(credentials))
f.close()
self._lock.release()
| 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.
import apiclient
import base64
import pickle
from django.db import models
class OAuthCredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
if value is None:
return None
if isinstance(value, apiclient.oauth.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
class FlowThreeLeggedField(models.Field):
__metaclass__ = models.SubfieldBase
def db_type(self):
return 'VARCHAR'
def to_python(self, value):
print "In to_python", value
if value is None:
return None
if isinstance(value, apiclient.oauth.FlowThreeLegged):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value):
return base64.b64encode(pickle.dumps(value))
| 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.
"""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Έ'
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 sys
import os
import platform
import sconsUtils
msvc_version = ""
if os.environ.has_key("MSVC_VERSION"):
msvc_version = os.environ["MSVC_VERSION"]
sconsUtils.importBuildEnvs()
buildMode = sconsUtils.getEnvVar("CORAL_BUILD_MODE")
env = Environment(
CPPPATH = [
os.path.join(os.pardir, "coral", "src"),
sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH")],
LIBS = [
sconsUtils.getEnvVar("CORAL_IMATH_LIB"),
sconsUtils.getEnvVar("CORAL_IMATH_IEX_LIB"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB")],
LIBPATH = [
sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH")],
SHLIBPREFIX = "",
MSVC_VERSION=msvc_version,
TARGET_ARCH = platform.machine())
if sys.platform == "darwin":
env["SHLIBSUFFIX"] = ".so"
elif sys.platform.startswith("win"):
env["SHLIBSUFFIX"] = ".pyd"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t /MP")
env["CCFLAGS"] = "-DBOOST_PYTHON_MAX_ARITY=16"
env["LINKFLAGS"] = ["/MANIFEST:NO"]
target = env.SharedLibrary(
target = "Imath",
source = sconsUtils.findFiles("ImathPythonWrapper", pattern = "*.cpp"),
OBJPREFIX = os.path.join(os.pardir, "debug" + buildMode, ""))
Return("target")
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
import os
import shutil
import sconsUtils
os.environ["CORAL_BUILD_FLAVOUR"] = "coralMaya"
os.environ["CORAL_BUILD_MODE"] = "DEBUG"
sconsUtils.importBuildEnvs()
coralLib = SConscript(os.path.join("coral", "SConstruct"))
coralUiLib = SConscript(os.path.join("coralUi", "SConstruct"), exports = {"coralLib": coralLib})
imathLib = SConscript(os.path.join("imath", "SConstruct"))
coralMaya = SConscript(os.path.join("coralMaya", "SConstruct"), exports = {"coralLib": coralLib})
mayaPlugin = SConscript(os.path.join("coralMaya", "plugin", "SConstruct"), exports = {"coralLib": coralLib, "coralUiLib": coralUiLib, "coralMayaLib": coralMaya})
def postBuildAction(target, source, env):
coralLib = str(source[0])
coralUiLib = str(source[1])
imathLib = str(source[2])
mayaPlugin = str(source[3])
coralMaya = str(source[4])
buildDir = os.path.join("build", "coralMayaBuild")
shutil.rmtree(buildDir, ignore_errors = True)
shutil.copytree(os.path.join("coralMaya", "py"), os.path.join(buildDir, "coralMaya"))
shutil.copytree(os.path.join("coral", "py", "coral"), os.path.join(buildDir, "coral"))
shutil.copy(coralLib, os.path.join(buildDir, "coral"))
shutil.copy(coralMaya, os.path.join(buildDir, "coralMaya"))
shutil.copy(mayaPlugin, os.path.join(buildDir, "coralMaya"))
shutil.copy(imathLib, buildDir)
shutil.copytree(os.path.join("coralUi", "py", "coralUi"), os.path.join(buildDir, "coral", "coralUi"))
shutil.copy(coralUiLib, os.path.join(buildDir, "coral", "coralUi"))
if sys.platform == "darwin":
# fix lib link path on Mac Os X
sconsUtils.autoFixDynamicLinks(os.path.join(buildDir, "coralMaya", "coralMayaPlugin.bundle"))
sconsUtils.autoFixDynamicLinks(os.path.join(buildDir, "coral", "_coral.so"))
sconsUtils.autoFixDynamicLinks(os.path.join(buildDir, "coral", "coralUi", "_coralUi.so"))
sconsUtils.autoFixDynamicLinks(os.path.join(buildDir, "coralMaya", "_coralMaya.so"))
pycFiles = sconsUtils.findFiles(os.path.join(buildDir), pattern = "*.pyc")
for pycFile in pycFiles:
os.remove(pycFile)
posBuildTarget = Command("postBuildTarget", [coralLib[0], coralUiLib[0], imathLib[0], mayaPlugin[0], coralMaya[0]], postBuildAction)
Default(posBuildTarget)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
# To load this plugin in coral run the following script:
# from coral import coralApp
# coralApp.loadPlugin("pathToPlugin/jitterNodePlugin.py")
from coral.plugin import Plugin
from jitterNode import JitterNode
def loadPlugin():
plugin = Plugin("jitterNodePlugin")
plugin.registerNode("JitterNode", JitterNode, tags = ["examples"], description = "An example node to jitter points.")
return plugin
| Python |
import coralBuilder
module = coralBuilder.buildModule("jitterNode", ["JitterNode.cpp"])
| Python |
from PyQt4 import QtGui, QtCore
from coral.coralUi.pluginUi import PluginUi
from coral.coralUi.nodeInspector.nodeInspector import NodeInspectorWidget
class JitterNodeInspectorWidget(NodeInspectorWidget):
def build(self):
NodeInspectorWidget.build(self)
button = QtGui.QPushButton("Say Hi!", self)
self.layout().addWidget(button)
self.connect(button, QtCore.SIGNAL("clicked()"), self._buttonClicked)
def _buttonClicked(self):
print self.coralNode().sayHi()
def loadPluginUi():
pluginUi = PluginUi("JitterNodePluginUi")
pluginUi.registerInspectorWidget("JitterNode", JitterNodeInspectorWidget)
return pluginUi | Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
# To load this plugin in coral run the following script:
# from coral import coralApp
# coralApp.loadPlugin("pathToPlugin/sineNodePolyPlugin.py")
from coral.plugin import Plugin
from sineNodePolymorphic import SineNodePolymorphic
def loadPlugin():
plugin = Plugin("sineNodePolymorphic")
plugin.registerNode("SineNodePolymorphic", SineNodePolymorphic, tags = ["examples"], description = "Exampe node with polymorphic attributes.")
return plugin
| Python |
import coralBuilder
module = coralBuilder.buildModule("sineNodePolymorphic", ["sineNodePolymorphic.cpp"])
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from coral import Node, NumericAttribute
from coral.plugin import Plugin
class SimplePyNode(Node):
def __init__(self, name, parent):
Node.__init__(self, name, parent)
self.input1 = NumericAttribute("input1", self)
self.input2 = NumericAttribute("input2", self)
self.output = NumericAttribute("output", self)
self.addInputAttribute(self.input1)
self.addInputAttribute(self.input2)
self.addOutputAttribute(self.output)
self._setAttributeAffect(self.input1, self.output)
self._setAttributeAffect(self.input2, self.output)
self._setAttributeAllowedSpecializations(self.input1, ["Float"])
self._setAttributeAllowedSpecializations(self.input2, ["Float"])
self._setAttributeAllowedSpecializations(self.output, ["Float"])
def update(self, attribute):
value1 = self.input1.value().floatValueAt(0)
value2 = self.input2.value().floatValueAt(0)
self.output.outValue().setFloatValueAt(0, value1 + value2)
def loadPlugin():
plugin = Plugin("simplePyNodePlugin")
plugin.registerNode("SimplePyNode", SimplePyNode, tags = ["examples"], description = "Example python node")
return plugin
| Python |
import sys
import os
import platform
import sconsUtils
msvc_version = ""
if os.environ.has_key("MSVC_VERSION"):
msvc_version = os.environ["MSVC_VERSION"]
sconsUtils.importBuildEnvs()
coralPath = os.path.join(os.pardir, "coral")
coralLib = None
try:
Import("coralLib")
except:
coralLib = SConscript(os.path.join(coralPath, "SConstruct"))
if sys.platform.startswith("win"):
coralLib = coralLib[1]
buildMode = sconsUtils.getEnvVar("CORAL_BUILD_MODE")
env = Environment(
CPPPATH = [
os.path.join(os.pardir),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_GLEW_INCLUDES_PATH")],
LIBS = [
coralLib,
sconsUtils.getEnvVar("CORAL_IMATH_LIB"),
sconsUtils.getEnvVar("CORAL_IMATH_IEX_LIB"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_GLEW_LIB")],
LIBPATH = [
coralPath,
sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_GLEW_LIBS_PATH")],
SHLIBPREFIX = "",
MSVC_VERSION=msvc_version,
TARGET_ARCH = platform.machine())
if os.environ.has_key("CORAL_PARALLEL"):
if os.environ["CORAL_PARALLEL"] == "CORAL_PARALLEL_TBB":
env["CPPPATH"].append(sconsUtils.getEnvVar("CORAL_TBB_INCLUDES_PATH"))
env["LIBS"].append(sconsUtils.getEnvVar("CORAL_TBB_LIB"))
env["LIBPATH"].append(sconsUtils.getEnvVar("CORAL_TBB_LIBS_PATH"))
if sys.platform.startswith("linux"):
pass
elif sys.platform == "darwin":
env["SHLIBSUFFIX"] = ".so"
env["FRAMEWORKS"] = ["OpenGL"]
elif sys.platform.startswith("win"):
env["SHLIBSUFFIX"] = ".pyd"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t /bigobj /MP")
env["CCFLAGS"] = "-DCORAL_UI_COMPILE"
env["LINKFLAGS"] = Split("/MANIFEST:NO OpenGL32.lib glu32.lib")
target = env.SharedLibrary(
target = "_coralUi",
source = sconsUtils.findFiles("src", pattern = "*.cpp"),
OBJPREFIX = os.path.join("debug" + os.environ["CORAL_BUILD_FLAVOUR"] + buildMode, ""))
Return("target")
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore, QtOpenGL
import _coralUi
from .. import _coral
from ..observer import Observer
from .. import coralApp
import mainWindow
class ViewportData:
_viewports = []
_cameraNodes = []
def addCameraNode(node):
if hasattr(node, "cameraChanged"):
ViewportData._cameraNodes.append(weakref.ref(node))
def removeCameraNode(node):
for nodeRef in ViewportData._cameraNodes:
currNode = nodeRef()
if currNode is node:
del ViewportData._cameraNodes[ViewportData._cameraNodes.index(nodeRef)]
break
def instancedViewports():
vports = []
for viewport in ViewportData._viewports:
vports.append(viewport())
return vports
class ViewportGlWidget(QtOpenGL.QGLWidget):
orbit = 1
pan = 2
timedRefresh = 0
immediateRefresh = 1
_sharedWidget = None
def __init__(self, parent = None):
if ViewportGlWidget._sharedWidget:
QtOpenGL.QGLWidget.__init__(self, parent, ViewportGlWidget._sharedWidget)
else:
ViewportGlWidget._sharedWidget = self
QtOpenGL.QGLWidget.__init__(self, QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers), parent)
self.makeCurrent()
self._viewport = _coralUi.Viewport()
self._oldPos = QtCore.QPoint(0, 0)
self._pressed = False
self._mode = 0
self.setFocusPolicy(QtCore.Qt.StrongFocus)
self.connect(mainWindow.MainWindow.globalInstance(), QtCore.SIGNAL("coralViewportUpdateGL"), QtCore.SLOT("updateGL()"))
self.connect(mainWindow.MainWindow.globalInstance(), QtCore.SIGNAL("coralViewportRefreshMode(int)"), self._changeRefreshMode)
ViewportData._viewports.append(weakref.ref(self._viewport))
self._timer = -1
def _changeRefreshMode(self, mode):
if mode == ViewportGlWidget.timedRefresh:
if self._timer == -1:
self._timer = self.startTimer(50)
elif mode == ViewportGlWidget.immediateRefresh:
if self._timer != -1:
self.killTimer(self._timer)
self._timer = -1
def timerEvent(self, event):
self.makeCurrent()
self.updateGL()
def closeEvent(self, event):
self._viewport = None
self._removeGlobally()
QtCore.QObject.disconnect(mainWindow.MainWindow.globalInstance(), QtCore.SIGNAL("coralViewportUpdateGL"), self, QtCore.SLOT("updateGL()"))
QtCore.QObject.disconnect(mainWindow.MainWindow.globalInstance(), QtCore.SIGNAL("coralViewportRefreshMode(int)"), self._changeRefreshMode)
if self._timer:
self.killTimer(self._timer)
self._timer = -1
def _removeGlobally(self):
for viewportRef in ViewportData._viewports:
viewport = viewportRef()
if viewport is self._viewport:
del ViewportData._viewports[ViewportData._viewports.index(viewportRef)]
break
def __del__(self):
self._removeGlobally()
def minimumSizeHint(self):
return QtCore.QSize(100, 100)
def sizeHint(self):
return QtCore.QSize(500, 500)
def initializeGL(self):
self.makeCurrent()
self._viewport.initializeGL()
self._dirtyCameraNodes()
def resizeGL(self, w, h):
self.makeCurrent()
self._viewport.resizeGL(w, h)
self._dirtyCameraNodes()
def paintGL(self):
self.makeCurrent()
self._viewport.draw()
def keyPressEvent(self, qKeyEvent):
pass
def keyReleaseEvent(self, qKeyEvent):
pass
def mousePressEvent(self, qMouseEvent):
self.setFocus()
self._pressed = True
self._oldPos = qMouseEvent.pos()
if qMouseEvent.button() == QtCore.Qt.LeftButton and qMouseEvent.modifiers() == QtCore.Qt.AltModifier:
self._mode = ViewportGlWidget.orbit
elif qMouseEvent.button() == QtCore.Qt.MiddleButton and qMouseEvent.modifiers() == QtCore.Qt.AltModifier:
self._mode = ViewportGlWidget.pan
elif qMouseEvent.button() == QtCore.Qt.LeftButton and qMouseEvent.modifiers() == QtCore.Qt.AltModifier | QtCore.Qt.ControlModifier: # Os X
self._mode = ViewportGlWidget.pan
def mouseReleaseEvent(self, qMouseEvent):
self.makeCurrent()
self._pressed = False
self._mode = 0
self._dirtyCameraNodes()
def mouseMoveEvent(self, qMouseEvent):
self.makeCurrent()
if self._pressed:
pos = qMouseEvent.pos()
deltaPos = pos - self._oldPos
if self._mode == ViewportGlWidget.orbit:
self._viewport.orbit(deltaPos.x(), deltaPos.y())
elif self._mode == ViewportGlWidget.pan:
self._viewport.pan(deltaPos.x(), deltaPos.y())
self._oldPos = qMouseEvent.pos()
self.updateGL()
def wheelEvent(self, qWheelEvent):
self.makeCurrent()
if qWheelEvent.orientation() == QtCore.Qt.Vertical:
self._viewport.dolly(int(qWheelEvent.delta() * -0.1))
self.updateGL()
self._dirtyCameraNodes()
def _dirtyCameraNodes(self):
self.makeCurrent()
for cameraNodeRef in ViewportData._cameraNodes:
cameraNode = cameraNodeRef()
cameraNode.cameraChanged()
class ViewportWidget(QtGui.QWidget):
_mainWin = mainWindow.MainWindow.globalInstance()
_initialized = False
_networkLoadedObserver = Observer()
@staticmethod
def refreshViewports():
ViewportWidget._mainWin.emit(QtCore.SIGNAL("coralViewportUpdateGL"))
@staticmethod
def _activateTimedRefresh():
ViewportWidget._disableRefreshCallback()
ViewportWidget._mainWin.emit(QtCore.SIGNAL("coralViewportRefreshMode(int)"), ViewportGlWidget.timedRefresh)
@staticmethod
def _activateImmediateRefresh():
ViewportWidget._mainWin.emit(QtCore.SIGNAL("coralViewportRefreshMode(int)"), ViewportGlWidget.immediateRefresh)
ViewportWidget._enableRefreshcallback()
@staticmethod
def _disableRefreshCallback():
_coral.setCallback("mainDrawRoutine_viewportRefresh", None)
@staticmethod
def _enableRefreshcallback():
_coral.setCallback("mainDrawRoutine_viewportRefresh", ViewportWidget.refreshViewports)
ViewportWidget.refreshViewports()
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("viewport")
self._viewportGlWidget = ViewportGlWidget(self)
self._networkLoadingObserver = Observer()
self._networkLoadedObserver = Observer()
self._initializingNewNetworkObserver = Observer()
self._initializedNewNetworkObserver = Observer()
self.setLayout(QtGui.QVBoxLayout(self))
self.setContentsMargins(0, 0, 0, 0)
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().setSpacing(0)
self.layout().addWidget(self._viewportGlWidget)
_coral.setCallback("mainDrawRoutine_viewportRefresh", ViewportWidget.refreshViewports)
coralApp.addInitializingNewNetworkObserver(self._initializingNewNetworkObserver, ViewportWidget._disableRefreshCallback)
coralApp.addInitializedNewNetworkObserver(self._initializedNewNetworkObserver, ViewportWidget._enableRefreshcallback)
coralApp.addNetworkLoadingObserver(self._networkLoadingObserver, ViewportWidget._disableRefreshCallback)
coralApp.addNetworkLoadedObserver(self._networkLoadedObserver, ViewportWidget._enableRefreshcallback)
if not ViewportWidget._initialized:
coralApp.addNetworkLoadedObserver(ViewportWidget._networkLoadedObserver, ViewportWidget.refreshViewports)
ViewportWidget._initialized = True
def closeEvent(self, event):
if self._viewportGlWidget:
self._viewportGlWidget.close()
if self._viewportGlWidget is not ViewportGlWidget._sharedWidget:
# we will leave ViewportGlWidget._sharedWidget alive to guarantee the first context created doesn't get destroyed
self._viewportGlWidget = None
self.destroy()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
import copy
import fnmatch
from PyQt4 import QtGui, QtCore
from ..observer import Observer
from .. import coralApp
import coralUi
import mainWindow
class NodeSearchField(QtGui.QLineEdit):
def __init__(self, parent):
QtGui.QLineEdit.__init__(self, parent)
self._originalPalette = self.palette()
def focusInEvent(self, event):
QtGui.QLineEdit.focusInEvent(self, event)
palette = self.palette()
palette.setColor(QtGui.QPalette.Normal, QtGui.QPalette.Base, QtGui.QColor(255, 255, 200))
self.setPalette(palette);
def focusOutEvent(self, event):
QtGui.QLineEdit.focusOutEvent(self, event)
self.setPalette(self._originalPalette)
def keyPressEvent(self, qKeyEvent):
if qKeyEvent.key() == QtCore.Qt.Key_Up:
self.emit(QtCore.SIGNAL("nodeSearchFieldMovedEntry(QString)"), "up")
elif qKeyEvent.key() == QtCore.Qt.Key_Down:
self.emit(QtCore.SIGNAL("nodeSearchFieldMovedEntry(QString)"), "down")
else:
QtGui.QLineEdit.keyPressEvent(self, qKeyEvent)
class NodeShelf(QtGui.QListWidget):
def __init__(self, parent):
QtGui.QListWidget.__init__(self, parent)
self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
self.setDragEnabled(True)
class NodeBoxMenu(QtGui.QMenu):
def __init__(self, parent):
QtGui.QMenu.__init__(self, parent)
self.setLayout(QtGui.QVBoxLayout(self))
self._nodeBox = NodeBox(parent)
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().setSpacing(5)
self.layout().addWidget(self._nodeBox)
self.resize(self._nodeBox.sizeHint())
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.connect(self._nodeBox, QtCore.SIGNAL("coralDataDropped"), self._done)
def hideEvent(self, event):
self.close()
def _done(self):
self.close()
class NodeBox(QtGui.QWidget):
_globalInstance = None
@staticmethod
def globalInstance():
inst = None
if NodeBox._globalInstance:
inst = NodeBox._globalInstance()
return inst
@staticmethod
def enableQuickSearch():
mainWin = mainWindow.MainWindow.globalInstance()
nodeBox = None
if NodeBox._globalInstance:
nodeBox = NodeBox._globalInstance
else:
menu = NodeBoxMenu(mainWin)
nodeBox = menu._nodeBox
cursorPos = QtGui.QCursor.pos()
menu.move(cursorPos.x(), cursorPos.y())
menu.show()
nodeBox = NodeBox._globalInstance()
nodeBox._nodeSearchField.setFocus()
@staticmethod
def _createFromItemData(itemData):
from nodeEditor import nodeEditor
sceneItem = None
className = itemData["data"]["className"]
parentNode = nodeEditor.NodeEditor.focusedInstance().currentNode().fullName()
if itemData["type"] == "attributeClassName":
name = "input"
if itemData["data"]["output"]:
name = "output"
newAttributeName = coralApp.executeCommand("CreateAttribute",
className = className,
name = name,
parentNode = parentNode,
input = itemData["data"]["input"], output = itemData["data"]["output"])
if newAttributeName:
newAttribute = coralApp.findAttribute(newAttributeName)
attributeUi = nodeEditor.NodeEditor.findAttributeUi(newAttribute.id())
if attributeUi.proxy():
sceneItem = attributeUi.proxy()
elif itemData["type"] == "nodeClassName":
newNodeName = coralApp.executeCommand("CreateNode", className = className, name = className, parentNode = parentNode)
if newNodeName:
newNode = coralApp.findNode(newNodeName)
sceneItem = nodeEditor.NodeEditor.findNodeUi(newNode.id())
return sceneItem
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._header = QtGui.QWidget(self)
self._headerLayout = QtGui.QHBoxLayout(self._header)
self._nodeSearchField = NodeSearchField(self._header)
self._nodeShelf = NodeShelf(self)
self._nodeHelp = QtGui.QTextEdit(self)
self._registeredNodeClassesObserver = Observer()
self.setWindowTitle("node box")
self.setLayout(self._mainLayout)
self._header.setLayout(self._headerLayout)
self._mainLayout.setContentsMargins(5, 5, 5, 5)
self._mainLayout.setSpacing(5)
self._mainLayout.addWidget(self._header)
self._mainLayout.addWidget(self._nodeShelf)
self._mainLayout.addWidget(self._nodeHelp)
self._headerLayout.addWidget(self._nodeSearchField)
self._headerLayout.setContentsMargins(0, 0, 0, 0)
self._nodeHelp.setMaximumHeight(150)
self._nodeHelp.setReadOnly(True)
palette = self._nodeHelp.palette()
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(97, 108, 117))
palette.setColor(QtGui.QPalette.Text, QtGui.QColor(200, 190, 200))
self._nodeHelp.setPalette(palette)
self.connect(self._nodeSearchField, QtCore.SIGNAL("textChanged(QString)"), self._searchTextChanged)
self.connect(self._nodeSearchField, QtCore.SIGNAL("returnPressed()"), self._shelfReturnPressed)
self.connect(self._nodeSearchField, QtCore.SIGNAL("nodeSearchFieldMovedEntry(QString)"), self._searchFieldMovedUpDown)
self.connect(self._nodeShelf, QtCore.SIGNAL("itemPressed (QListWidgetItem *)"), self._nodeShelfItemClicked)
self.connect(self._nodeShelf, QtCore.SIGNAL("currentRowChanged (int)"), self._nodeShelfRowChanged)
self.connect(mainWindow.MainWindow.globalInstance(), QtCore.SIGNAL("coralDataDropped"), self._dropEnd)
coralApp.addRegisteredNodeClassesObserver(self._registeredNodeClassesObserver, self._registeredNodeClassesCallback)
self._rebuildNodeShelf()
NodeBox._globalInstance = weakref.ref(self)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
def __del__(self):
NodeBox._globalInstance = None
def _searchFieldMovedUpDown(self, direction):
if direction == "up":
nextItem = self._nodeShelf.item(self._nodeShelf.currentRow() - 1)
if nextItem:
self._nodeShelf.setCurrentRow(self._nodeShelf.currentRow() - 1)
elif direction == "down":
nextItem = self._nodeShelf.item(self._nodeShelf.currentRow() + 1)
if nextItem:
self._nodeShelf.setCurrentRow(self._nodeShelf.currentRow() + 1)
if str(self._nodeShelf.currentItem().text()).startswith("::") and self._nodeShelf.currentRow() > 0:
self._searchFieldMovedUpDown(direction)
self._nodeShelfItemClicked(self._nodeShelf.currentItem())
def _nodeShelfRowChanged(self, row):
item = self._nodeShelf.currentItem()
if item:
className = str(item.text())
if not str(className).startswith("::"):
self._nodeShelfItemClicked(item)
def _shelfReturnPressed(self):
from nodeEditor import nodeEditor
item = self._nodeShelf.currentItem()
if item:
className = str(item.text())
if not str(className).startswith("::"):
itemData = self._itemData(item)
sceneItem = NodeBox._createFromItemData(itemData)
if sceneItem:
nodeView = nodeEditor.NodeEditor.focusedInstance().nodeView()
if type(self.parent()) is NodeBoxMenu:
pos = QtGui.QCursor.pos()
scenePos = nodeView.mapToScene(nodeView.mapFromGlobal(pos))
sceneItem.setPos(scenePos)
else:
sceneItem.setPos(nodeView.mapToScene(nodeView.rect().center()))
self._nodeSearchField.setText("")
self._rebuildNodeShelf()
self.emit(QtCore.SIGNAL("coralDataDropped"))
def _dropEnd(self):
self._nodeSearchField.setText("")
def _itemData(self, item):
data = {}
value = str(item.text())
if value == "InputAttribute":
data = {
"type": "attributeClassName",
"data": {"className": "PassThroughAttribute", "input": True, "output": False}}
elif value == "OutputAttribute":
data = {
"type": "attributeClassName",
"data": {"className": "PassThroughAttribute", "input": False, "output": True}}
else:
data = {
"type": "nodeClassName",
"data": {"className": value}}
return data
def _nodeShelfItemClicked(self, item):
data = self._itemData(item)
coralUi.setDropData(data, "nodeBoxItemData")
type = "Node"
className = data["data"]["className"]
if data["type"] == "attributeClassName":
type = "Attribute"
helpText = "<h4>" + className + " " + type + "</h4>\n"
helpText += "<p>" + coralApp.registeredNodeDescription(className) + "</p>"
self._nodeHelp.setText(helpText)
def _registeredNodeClassesCallback(self):
self._rebuildNodeShelf()
def _rebuildNodeShelf(self, filter = ""):
wildcard = "*" + str(filter).lower() + "*"
classNameTags = copy.copy(coralApp.classNameTags())
if "InputAttribute" not in classNameTags["encapsulation"] and "OutputAttribute" not in classNameTags["encapsulation"]:
classNameTags["encapsulation"].extend(["InputAttribute", "OutputAttribute"])
tags = classNameTags.keys()
tags.sort()
self._nodeShelf.clear()
for classNameTag in tags:
tagItem = QtGui.QListWidgetItem(":: " + classNameTag + " ::")
tagItem.setFlags(QtCore.Qt.NoItemFlags)
tagItem.setTextColor(QtGui.QColor(QtCore.Qt.darkCyan))
classNameItems = []
for className in classNameTags[classNameTag]:
if fnmatch.fnmatch(className.lower(), wildcard):
classNameItem = QtGui.QListWidgetItem(className)
classNameItem.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled | QtCore.Qt.ItemIsDropEnabled)
classNameItems.append(classNameItem)
if classNameItems:
self._nodeShelf.addItem(tagItem)
for classNameItem in classNameItems:
self._nodeShelf.addItem(classNameItem)
if filter and self._nodeShelf.count():
self._nodeShelf.setCurrentRow(1)
self._nodeShelfItemClicked(self._nodeShelf.currentItem())
def sizeHint(self):
return QtCore.QSize(200, 400)
def _searchTextChanged(self, text):
self._rebuildNodeShelf(text)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
import nodeInspector
from .. import mainWindow
from ... import coralApp
from ... import utils
from ...observer import Observer
from ... import Imath
class ObjectField(QtGui.QWidget):
def __init__(self, label, coralObject, parentWidget):
QtGui.QWidget.__init__(self, parentWidget)
self._mainLayout = QtGui.QHBoxLayout(self)
self._label = QtGui.QLabel(label, self)
self._valueWidget = None
self._coralObject = weakref.ref(coralObject)
self.setLayout(self._mainLayout)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.addWidget(self._label)
def label(self):
return self._label
def valueWidget(self):
return self._valueWidget
def setObjectWidget(self, widget, endOfEditSignal = None, endOfEditCallback = None):
self._valueWidget = widget
self._mainLayout.addWidget(widget)
if endOfEditSignal:
self.connect(self._valueWidget, QtCore.SIGNAL(endOfEditSignal), endOfEditCallback)
def coralObject(self):
return self._coralObject()
class AttributeField(ObjectField):
def __init__(self, coralAttribute, parentWidget):
ObjectField.__init__(self, coralAttribute.name().split(":")[-1], coralAttribute, parentWidget)
self._sourceAttributes = self._findSourceAttributes()
self._timer = self.startTimer(500)
def timerEvent(self, event):
valueWidget = self.valueWidget()
if valueWidget:
if valueWidget.hasFocus() == False:
self.attributeValueChanged()
def widgetValueChanged(self):
value = self.getWidgetValue(self.valueWidget())
somethingChanged = False
for sourceAttr in self._sourceAttributes:
attr = sourceAttr()
if self.getAttributeValue(attr) != value:
self.setAttributeValue(attr, value)
somethingChanged = True
if somethingChanged:
self.coralObject().forceDirty()
def attributeValueChanged(self):
value = self.getAttributeValue(self._sourceAttributes[0]())
if value != self.getWidgetValue(self.valueWidget()):
self.setWidgetValue(self.valueWidget(), value)
def getWidgetValue(self, widget):
return None
def setWidgetValue(self, widget):
pass
def getAttributeValue(self, attribute):
return None
def setAttributeValue(self, attribute, value):
pass
def setAttributeWidget(self, widget, endOfEditSignal = None):
ObjectField.setObjectWidget(self, widget, endOfEditSignal, self.widgetValueChanged)
attribute = self.coralObject()
if attribute.input() or attribute.affectedBy():
self.label().setText(">" + self.label().text())
self.attributeValueChanged()
def _collectOutAttrsNonPass(self, attribute, outAttrs):
if attribute.isPassThrough() == False:
outAttrs.append(weakref.ref(attribute))
else:
for outAttr in attribute.outputs():
self._collectOutAttrsNonPass(outAttr, outAttrs)
def _findSourceAttributes(self):
attr = self.coralObject()
attrs = []
if attr.isPassThrough():
self._collectOutAttrsNonPass(attr, attrs)
if len(attrs) == 0:
attrs = [weakref.ref(attr)]
return attrs
class CustomDoubleSpinBox(QtGui.QDoubleSpinBox):
def __init__(self, parent):
QtGui.QDoubleSpinBox.__init__(self, parent)
self.setDecimals(4)
self._wheelCallback = None
def wheelEvent(self, wheelEvent):
QtGui.QDoubleSpinBox.wheelEvent(self, wheelEvent)
self._wheelCallback()
class FloatValueField(AttributeField):
def __init__(self, coralAttribute, parentWidget):
AttributeField.__init__(self, coralAttribute, parentWidget)
attrWidget = CustomDoubleSpinBox(self)
attrWidget._wheelCallback = utils.weakRef(self.widgetValueChanged)
attrWidget.setRange(-99999999999.0, 99999999999.0)
attrWidget.setSingleStep(0.1)
self.setAttributeWidget(attrWidget, "editingFinished()")
def setAttributeValue(self, attribute, value):
attribute.outValue().setFloatValueAt(0, value)
def getAttributeValue(self, attribute):
return attribute.value().floatValueAt(0)
def setWidgetValue(self, widget, value):
widget.setValue(value)
def getWidgetValue(self, widget):
return widget.value()
class CustomIntSpinBox(QtGui.QSpinBox):
def __init__(self, parent):
QtGui.QSpinBox.__init__(self, parent)
self._wheelCallback = None
def wheelEvent(self, wheelEvent):
QtGui.QSpinBox.wheelEvent(self, wheelEvent)
self._wheelCallback()
class IntValueField(AttributeField):
def __init__(self, coralAttribute, parentWidget):
AttributeField.__init__(self, coralAttribute, parentWidget)
attrWidget = CustomIntSpinBox(self)
attrWidget._wheelCallback = utils.weakRef(self.widgetValueChanged)
attrWidget.setRange(-999999999, 999999999)
self.setAttributeWidget(attrWidget, "editingFinished()")
def setAttributeValue(self, attribute, value):
attribute.outValue().setIntValueAt(0, value)
def getAttributeValue(self, attribute):
return attribute.value().intValueAt(0)
def setWidgetValue(self, widget, value):
widget.setValue(value)
def getWidgetValue(self, widget):
return widget.value()
class BoolValueField(AttributeField):
def __init__(self, coralAttribute, parentWidget):
AttributeField.__init__(self, coralAttribute, parentWidget)
attrWidget = QtGui.QCheckBox(self)
self.setAttributeWidget(attrWidget, "stateChanged(int)")
attrWidget.setTristate(False)
def setAttributeValue(self, attribute, value):
attribute.outValue().setBoolValueAt(0, value)
def getAttributeValue(self, attribute):
return attribute.value().boolValueAt(0)
def setWidgetValue(self, widget, value):
widget.setCheckState(value)
def getWidgetValue(self, widget):
return widget.isChecked()
class CustomLineEdit(QtGui.QLineEdit):
def __init__(self, parent):
QtGui.QLineEdit.__init__(self, parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
urls = event.mimeData().urls()
path = ""
if urls:
path = str(urls[0].toLocalFile())
self.setText(path)
self.emit(QtCore.SIGNAL("editingFinished()"))
else:
event.ignore()
class StringValueField(AttributeField):
def __init__(self, coralAttribute, parentWidget):
AttributeField.__init__(self, coralAttribute, parentWidget)
if coralAttribute.longString():
textEdit = QtGui.QTextEdit(self)
textEdit.setLineWrapMode(QtGui.QTextEdit.NoWrap)
textEdit.setAcceptRichText(False)
textEdit.setMaximumHeight(100)
self.setAttributeWidget(textEdit, "textChanged()")
self.layout().setAlignment(textEdit, QtCore.Qt.AlignTop)
else:
self.setAttributeWidget(CustomLineEdit(self), "editingFinished()")
def setAttributeValue(self, attribute, value):
attribute.outValue().setStringValue(value)
def getAttributeValue(self, attribute):
return attribute.value().stringValue()
def setWidgetValue(self, widget, value):
if type(widget) is QtGui.QTextEdit:
widget.setPlainText(value)
else:
widget.setText(value)
def getWidgetValue(self, widget):
text = ""
if type(widget) is QtGui.QTextEdit:
text = widget.toPlainText()
else:
text = widget.text()
return str(text)
class NameField(ObjectField):
def __init__(self, coralNode, parentWidget):
ObjectField.__init__(self, "name", coralNode, parentWidget)
self._nameChangedObserver = Observer()
self.setObjectWidget(QtGui.QLineEdit(coralNode.name(), self), "editingFinished()", self.widgetValueChanged)
coralApp.addNameChangedObserver(self._nameChangedObserver, coralNode, self._nameChanged)
def widgetValueChanged(self):
newName = str(self.valueWidget().text())
if self.coralObject().name() != newName:
self.coralObject().setName(newName)
def _nameChanged(self):
newName = self.coralObject().name()
if newName != str(self.valueWidget().text()):
self.valueWidget().setText(newName)
class ColorField(AttributeField):
def __init__(self, coralAttribute, parentWidget):
AttributeField.__init__(self, coralAttribute, parentWidget)
self._colorButton = QtGui.QPushButton(self)
self.setAttributeWidget(self._colorButton)
self.connect(self._colorButton, QtCore.SIGNAL("clicked()"), self._colButtonClicked)
def _colorDialogChangedColor(self, color):
rgbStr = str(255*color.redF()) + "," + str(255*color.greenF()) + "," + str(255*color.blueF()) + "," + str(255*color.alphaF())
self._colorButton.setStyleSheet("background-color: rgba(" + rgbStr + ");")
self._colorButton.setText(str(round(color.redF(), 2)) + ", " + str(round(color.greenF(), 2)) + ", " + str(round(color.blueF(), 2)) + ", " + str(round(color.alphaF(), 2)))
self.widgetValueChanged()
def _colButtonClicked(self):
self.killTimer(self._timer)
col = self._colorButton.palette().background().color()
colDialog = QtGui.QColorDialog(col, self)
colDialog.setOption(QtGui.QColorDialog.DontUseNativeDialog, True)
colDialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True)
self.connect(colDialog, QtCore.SIGNAL("currentColorChanged(const QColor&)"), self._colorDialogChangedColor)
colDialog.exec_()
newCol = col
if colDialog.result():
newCol = colDialog.selectedColor()
rgbStr = str(255*newCol.redF()) + "," + str(255*newCol.greenF()) + "," + str(255*newCol.blueF()) + "," + str(255*newCol.alphaF())
self._colorButton.setStyleSheet("background-color: rgba(" + rgbStr + ");")
self._colorButton.setText(str(round(newCol.redF(), 2)) + ", " + str(round(newCol.greenF(), 2)) + ", " + str(round(newCol.blueF(), 2)) + ", " + str(round(newCol.alphaF(), 2)))
self.widgetValueChanged()
self._timer = self.startTimer(500)
def setAttributeValue(self, attribute, value):
attribute.outValue().setCol4ValueAt(0, Imath.Color4f(value[0], value[1], value[2], value[3]))
def getAttributeValue(self, attribute):
col = attribute.value().col4ValueAt(0)
return [col.r, col.g, col.b, col.a]
def setWidgetValue(self, widget, value):
for i in range(4):
val = value[i]
if val < 0.0:
value[i] = 0.0
elif val > 1.0:
value[i] = 1.0
rgbStr = str(255*value[0]) + "," + str(255*value[1]) + "," + str(255*value[2]) + "," + str(255.0*value[3])
self._colorButton.setStyleSheet("background-color: rgba(" + rgbStr + ");")
self._colorButton.setText(str(round(value[0], 2)) + ", " + str(round(value[1], 2)) + ", " + str(round(value[2], 2)) + ", " + str(round(value[3], 2)))
def getWidgetValue(self, widget):
col = self._colorButton.palette().background().color()
return [col.redF(), col.greenF(), col.blueF(), col.alphaF()]
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from ... import coralApp
from ... import utils
from ...observer import Observer
from ..nodeEditor import nodeEditor
from .. import mainWindow
import fields
class CustomComboBox(QtGui.QComboBox):
def __init__(self, parent):
QtGui.QComboBox.__init__(self, parent)
self._showPopupCallback = None
self._currentItemChangedCallback = None
self._currentItemChangedCallbackEnabled = True
self.connect(self, QtCore.SIGNAL("currentIndexChanged(QString)"), self._currentItemChanged)
def setShowPopupCallback(self, callback):
self._showPopupCallback = utils.weakRef(callback)
def setCurrentItemChangedCallback(self, callback):
self._currentItemChangedCallback = utils.weakRef(callback)
def _currentItemChanged(self, itemText):
if self._currentItemChangedCallbackEnabled:
if self._currentItemChangedCallback:
self._currentItemChangedCallback()
def showPopup(self):
self._currentItemChangedCallbackEnabled = False
if self._showPopupCallback:
self._showPopupCallback()
QtGui.QComboBox.showPopup(self)
self._currentItemChangedCallbackEnabled = True
class SpecializationCombo(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._label = QtGui.QLabel("specialization:", self)
self._combo = CustomComboBox(self)
self.setLayout(QtGui.QHBoxLayout(self))
self.layout().setContentsMargins(0, 0, 0, 0)
self.layout().setSpacing(0)
self.layout().addWidget(self._label)
self.layout().addWidget(self._combo)
class NodeInspectorWidget(QtGui.QWidget):
def __init__(self, coralNode, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._coralNode = weakref.ref(coralNode)
self._nameField = None
self._nameEditable = False
self._attributeWidgets = {}
self._presetCombo = None
self._nodeInspector = weakref.ref(parent)
self.setLayout(self._mainLayout)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setSpacing(2)
def nodeInspector(self):
return self._nodeInspector()
def attributeWidget(self, name):
widget = None
if self._attributeWidgets.has_key(name):
if self._attributeWidgets[name]() is not None:
widget = self._attributeWidgets[name]()
return widget
def setNameEditable(self, value = True):
self._nameEditable = value
def coralNode(self):
node = None
if self._coralNode:
node = self._coralNode()
return node
def _hasDefaultSpecialization(self, coralNode):
for attr in coralNode.attributes():
if attr.defaultSpecialization():
return True
return False
def _nodeIsConnected(self, coralNode):
for attr in coralNode.attributes():
if attr.input():
return True
elif attr.outputs():
return True
return False
def _presetComboItemChanged(self):
coralNode = self._coralNode()
combo = self._presetCombo._combo
selectedPreset = str(combo.currentText())
if selectedPreset.endswith("(not allowed)") == False:
coralNode.enableSpecializationPreset(selectedPreset)
else:
coralNode.enableSpecializationPreset("none")
combo.setCurrentIndex(combo.count() - 1)
def _populatePresetCombo(self):
coralNode = self._coralNode()
coralNode.enableSpecializationPreset("none")
combo = self._presetCombo._combo
combo.clear()
presets = coralNode.specializationPresets()
for preset in presets:
presetAllowed = True
if preset != "none":
for attr in coralNode.attributes():
presetSpecialization = coralNode.attributeSpecializationPreset(preset, attr)
if presetSpecialization:
currentSpecialization = attr.specialization()
if presetSpecialization not in currentSpecialization:
presetAllowed = False
break
if presetAllowed:
combo.addItem(preset)
else:
combo.addItem(preset + " (not allowed)")
currentPreset = coralNode.enabledSpecializationPreset()
combo.setCurrentIndex(presets.index(currentPreset))
def _updatePresetCombo(self):
coralNode = self._coralNode()
presets = coralNode.specializationPresets()
if len(presets) > 1:
self._presetCombo = SpecializationCombo(self)
self.layout().addWidget(self._presetCombo)
currentPreset = coralNode.enabledSpecializationPreset()
self._presetCombo._combo.addItem(currentPreset)
self._presetCombo._combo.setCurrentIndex(0)
self._presetCombo._combo.setShowPopupCallback(self._populatePresetCombo)
self._presetCombo._combo.setCurrentItemChangedCallback(self._presetComboItemChanged)
#if self._nodeIsConnected(coralNode):
# self._presetCombo._combo.setDisabled(True)
def _findFirstConnectedAtributeNonPassThrough(self, coralAttribute, processedAttributes):
foundAttr = None
if coralAttribute not in processedAttributes:
processedAttributes.append(coralAttribute)
if coralAttribute.isPassThrough() == False:
return coralAttribute
else:
if coralAttribute.input():
foundAttr = self._findFirstConnectedAtributeNonPassThrough(coralAttribute.input(), processedAttributes)
if foundAttr:
return foundAttr
for out in coralAttribute.outputs():
foundAttr = self._findFirstConnectedAtributeNonPassThrough(out, processedAttributes)
if foundAttr:
return foundAttr
return foundAttr
def build(self):
coralNode = self.coralNode()
if self._nameEditable:
self._nameField = fields.NameField(coralNode, self)
self.layout().addWidget(self._nameField)
self._updatePresetCombo()
nodeUi = nodeEditor.NodeEditor.findNodeUi(coralNode.id())
attrUis = nodeUi.attributeUis(includeHidden = True)
for attrUi in attrUis:
attribute = attrUi.coralAttribute()
if attribute.name().startswith("_") == False:
className = attribute.className()
if className == "PassThroughAttribute":
processedAttrs = []
sourceAttr = self._findFirstConnectedAtributeNonPassThrough(attribute, processedAttrs)
if sourceAttr:
className = sourceAttr.className()
if NodeInspector._inspectorWidgetClasses.has_key(className):
inspectorWidgetClass = NodeInspector._inspectorWidgetClasses[className]
inspectorWidget = inspectorWidgetClass(attribute, self)
self._attributeWidgets[attribute.name()] = weakref.ref(inspectorWidget)
self._mainLayout.addWidget(inspectorWidget)
inspectorWidget.build()
class ProxyAttributeInspectorWidget(QtGui.QWidget):
def __init__(self, coralAttribute, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._coralAttribute = weakref.ref(coralAttribute)
self._nameField = None
self._specializationCombo = None
self.setLayout(self._mainLayout)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setSpacing(0)
def _specializationComboChanged(self):
specialization = str(self._specializationCombo._combo.currentText())
attr = self._coralAttribute()
if specialization != "" and specialization != "none":
attr.setSpecializationOverride(str(specialization));
else:
attr.removeSpecializationOverride()
attr.forceSpecializationUpdate()
def _populateSpecializationCombo(self):
coralAttribute = self._coralAttribute()
coralAttribute.removeSpecializationOverride()
coralAttribute.forceSpecializationUpdate()
attrSpecialization = coralAttribute.specialization()
self._specializationCombo._combo.clear()
for spec in coralAttribute.specialization():
self._specializationCombo._combo.addItem(spec)
self._specializationCombo._combo.addItem("none")
self._specializationCombo._combo.setCurrentIndex(len(attrSpecialization))
def build(self):
coralAttribute = self._coralAttribute()
parentNode = coralAttribute.parent()
if coralAttribute in parentNode.dynamicAttributes():
self._nameField = fields.NameField(coralAttribute, self)
self._specializationCombo = SpecializationCombo(self)
self.layout().addWidget(self._specializationCombo)
self.layout().addWidget(self._nameField)
self._specializationCombo._combo.setShowPopupCallback(self._populateSpecializationCombo)
self._specializationCombo._combo.setCurrentItemChangedCallback(self._specializationComboChanged)
spec = coralAttribute.specialization()
if len(spec) == 1:
self._specializationCombo._combo.addItem(spec[0])
self._specializationCombo._combo.setCurrentIndex(0)
else:
self._specializationCombo._combo.addItem("none")
self._specializationCombo._combo.setCurrentIndex(0)
else:
label = QtGui.QLabel("name: " + coralAttribute.name(), self)
self.layout().addWidget(label)
class AttributeInspectorWidget(QtGui.QWidget):
def __init__(self, coralAttribute, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._coralAttribute = weakref.ref(coralAttribute)
self.setLayout(self._mainLayout)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setSpacing(0)
def coralAttribute(self):
attr = None
if self._coralAttribute:
attr = self._coralAttribute()
return attr
def build(self):
pass
class NodeInspectorHeader(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QHBoxLayout(self)
self._lockButton = QtGui.QToolButton(self)
self._classNameLabel = QtGui.QLabel(self)
self.setLayout(self._mainLayout)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setAlignment(QtCore.Qt.AlignRight)
self._lockButton.setText("lock")
self._lockButton.setCheckable(True)
self._mainLayout.addWidget(self._classNameLabel)
self._mainLayout.addWidget(self._lockButton)
def lockButton(self):
return self._lockButton
class NodeInspector(QtGui.QWidget):
_inspectorWidgetClasses = {}
@staticmethod
def registerInspectorWidget(nestedObjectClassName, inspectorWidgetClass):
NodeInspector._inspectorWidgetClasses[nestedObjectClassName] = inspectorWidgetClass
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._header = NodeInspectorHeader(self)
self._contentWidget = QtGui.QWidget(self)
self._contentLayout = QtGui.QVBoxLayout(self._contentWidget)
self._isLocked = False
self._selectedNodesChangedObserver = Observer()
self._nodeConnectionChangedObserver = Observer()
self._inspectorWidget = None
self._node = None
self._attribute = None
self.setLayout(self._mainLayout)
self.setWindowTitle("node inspector")
self._mainLayout.setContentsMargins(5, 5, 5, 5)
self._mainLayout.setAlignment(QtCore.Qt.AlignTop)
self._contentWidget.setLayout(self._contentLayout)
self._contentLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.addWidget(self._header)
self._mainLayout.addWidget(self._contentWidget)
self.connect(self._header.lockButton(), QtCore.SIGNAL("toggled(bool)"), self.lock)
nodeEditor.NodeEditor.addSelectedNodesChangedObserver(self._selectedNodesChangedObserver, self._selectionChanged)
self._selectionChanged()
def refresh(self):
self.clear()
node = None
attribute = None
if self._node:
node = self._node()
elif self._attribute:
attribute = self._attribute()
self._rebuild(node, attribute)
def clear(self):
self._header._classNameLabel.setText("")
if self._inspectorWidget:
self._inspectorWidget.setParent(None)
self._inspectorWidget = None
def _rebuild(self, node = None, attribute = None):
if node:
inspectorWidgetClass = NodeInspectorWidget
classNames = node.classNames()
classNames.reverse()
for className in classNames:
if NodeInspector._inspectorWidgetClasses.has_key(className):
inspectorWidgetClass = NodeInspector._inspectorWidgetClasses[className]
break
self._inspectorWidget = inspectorWidgetClass(node, self)
self._inspectorWidget.setNameEditable(True)
self._inspectorWidget.build()
self._contentLayout.addWidget(self._inspectorWidget)
self._header._classNameLabel.setText(node.className())
coralApp.addNodeConnectionChangedObserver(self._nodeConnectionChangedObserver, node, self.refresh)
elif attribute:
self._inspectorWidget = ProxyAttributeInspectorWidget(attribute, self)
self._inspectorWidget.build()
self._contentLayout.addWidget(self._inspectorWidget)
self._header._classNameLabel.setText(attribute.className())
coralApp.addNodeConnectionChangedObserver(self._nodeConnectionChangedObserver, attribute.parent(), self.refresh)
def _selectionChanged(self):
if self._isLocked:
return
self.clear()
self._node = None
self._attribute = None
self._nodeConnectionChangedObserver = Observer()
nodes = nodeEditor.NodeEditor.selectedNodes()
if nodes:
node = nodes[0]
self._node = weakref.ref(node)
self._rebuild(node)
else:
attributes = nodeEditor.NodeEditor.selectedAttributes()
if attributes:
attr = attributes[0]
self._attribute = weakref.ref(attr)
self._rebuild(attribute = attr)
def lock(self, value):
self._isLocked = value
if not self._isLocked:
self._selectionChanged()
def sizeHint(self):
return QtCore.QSize(200, 500)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from ... import coralApp
from ...observer import Observer
import nodeEditor
from connection import Connection
from connectionHook import ConnectionHook
from ..._coral import NetworkManager
from attributeUiProxy import AttributeUiProxy
class AttributeUi(QtGui.QGraphicsWidget):
def __init__(self, coralAttribute, parentNodeUi):
QtGui.QGraphicsWidget.__init__(self, parentNodeUi)
self._coralAttribute = weakref.ref(coralAttribute)
self._coralAttributeId = coralAttribute.id()
self._parentNodeUi = weakref.ref(parentNodeUi)
self._spacerConstant = 5.0
self._label = QtGui.QGraphicsSimpleTextItem(self)
self._inputHook = None
self._outputHook = None
self._proxy = None
self._attributeSpecializedObserver = Observer()
self._disconnectedInputObserver = Observer()
self._nameChangedObserver = Observer()
self._labelSuffix = ""
self._labelText = ""
if coralAttribute.isInput():
self._inputHook = ConnectionHook(self, isInput = True)
else:
self._outputHook = ConnectionHook(self, isOutput = True)
self._label.setBrush(parentNodeUi.labelsColor())
self._labelText = coralAttribute.name().split(":")[-1]
self._label.setText(self._labelText)
self.setHooksColor(self.hooksColor(self._coralAttribute().allowedSpecialization()))
coralApp.addDisconnectedInputObserver(self._disconnectedInputObserver, coralAttribute, self._disconnected)
coralApp.addAttributeSpecializedObserver(self._attributeSpecializedObserver, coralAttribute, self.specialized)
coralApp.addNameChangedObserver(self._nameChangedObserver, coralAttribute, self._coralAttributeNameChanged)
if coralAttribute.name().startswith("_"):
self.setVisible(False)
if parentNodeUi.attributesProxyEnabled():
self._enableProxy()
self.specialized()
def labelColor(self):
return self._label.brush().color()
def _coralAttributeNameChanged(self):
newName = self.coralAttribute().name().split(":")[-1]
self._labelText = newName
self._label.setText(self._labelText + self._labelSuffix)
self.parentNodeUi().updateLayout()
parentNodeScene = self.parentNodeUi().scene()
if parentNodeScene:
parentNodeScene.update()
if self._proxy:
self._proxy()._label.setText(self._labelText + self._labelSuffix)
self._proxy().updateLayout()
self._proxy().scene().update()
def label(self):
return self._label
'''
Override this method to return a more detailed toolTip.
'''
def toolTip(self):
return self.coralAttribute().shortDebugInfo()
def _disconnected(self):
if self._inputHook:
if self._inputHook._connections:
self._inputHook._connections[0].deleteIt()
elif self._proxy:
self._proxy().deleteInputConnection()
def onChangedScene(self, scene):
if self._outputHook:
self._outputHook.onChangedScene(scene)
if self._inputHook:
self._inputHook.onChangedScene(scene)
if self._proxy:
self._proxy().onChangedScene(scene)
def connectTo(self, attributeUi):
startHook = self._outputHook
endHook = attributeUi.inputHook()
if endHook is None:
proxy = attributeUi.proxy()
if proxy:
endHook = proxy.inputHook()
if startHook is None:
if self._proxy:
startHook = self._proxy().outputHook()
Connection(startHook, endHook)
def _enableProxy(self):
attr = self._coralAttribute()
if attr.isInput() or attr.isPassThrough():
proxy = AttributeUiProxy(self)
self._proxy = weakref.ref(proxy)
self.parentNodeUi().containedScene().addItem(proxy)
def proxy(self):
retProxy = None
if self._proxy:
retProxy = self._proxy()
return retProxy
def hooksColor(self, specialization):
return QtGui.QColor(255, 255, 255)
def _updateLabel(self):
attr = self.coralAttribute()
val = attr.outValue()
if attr.isPassThrough():
source = attr.connectedNonPassThrough()
if source:
val = source.outValue()
self._labelSuffix = ""
if hasattr(val, "isArray"):
if val.isArray():
self._labelSuffix = "[]"
self.label().setText(self._labelText + self._labelSuffix)
def labelSuffix(self):
return self._labelSuffix
def specialized(self):
self._updateLabel()
specialization = self.coralAttribute().specialization()
color = self.hooksColor(specialization)
mixedColor = False
if len(specialization) > 1:
mixedColor = True
self.setHooksColor(color, mixedColor)
self.parentNodeUi().updateLayout()
if self._outputHook:
for conn in self._outputHook._connections:
conn.update()
elif self._inputHook:
for conn in self._inputHook._connections:
conn.update()
if self._proxy:
self._proxy().specialized()
def setHooksColor(self, color, mixedColor = False):
hook = None
if self._outputHook:
hook = self._outputHook
else:
hook = self._inputHook
hook.setColor(color)
hook.setMixedColor(mixedColor)
def coralAttribute(self):
return self._coralAttribute()
def parentNodeUi(self):
parent = None
if self._parentNodeUi:
parent = self._parentNodeUi()
return parent
def allowConnectionTo(self, targetAttributeUi, errorObject):
allow = NetworkManager.allowConnection(self._coralAttribute(), targetAttributeUi.coralAttribute(), errorObject)
return allow
def inputHook(self):
return self._inputHook
def outputHook(self):
return self._outputHook
def updateLayout(self):
height = self._label.boundingRect().height()
hookY = 0
if self._outputHook:
hookY = (height - self._outputHook.boundingRect().height()) / 2.0
elif self._inputHook:
hookY = (height - self._inputHook.boundingRect().height()) / 2.0
inputHookWidth = self._spacerConstant * 2.0
if self._inputHook:
self._inputHook.setPos(0.0, hookY)
self._label.setPos(inputHookWidth + self._spacerConstant, 0)
if self._outputHook:
self._outputHook.setPos(self._label.pos().x() + self._label.boundingRect().width() + self._spacerConstant, hookY)
self.resize(self._outputHook.pos().x() + self._outputHook.boundingRect().width(), height)
else:
self.resize(self._label.pos().x() + self._label.boundingRect().width(), height)
def setParentNodeUi(self, nodeUi):
self.setParentItem(None)
if self.scene():
if self in self.scene().items():
self.scene().removeItem(self)
if self._parentNodeUi:
parentNodeUi = self._parentNodeUi()
if self in parentNodeUi._attributeUis:
del parentNodeUi._attributeUis[parentNodeUi._attributeUis.index(self)]
if nodeUi:
self._parentNodeUi = weakref.ref(nodeUi)
self.setParentItem(nodeUi)
if self not in nodeUi._attributeUis:
nodeUi._attributeUis.append(self)
else:
self._parentNodeUi = None
def deleteIt(self):
if self._outputHook:
self._outputHook.deleteIt()
elif self._inputHook:
self._inputHook.deleteIt()
if self._proxy:
self._proxy().deleteIt()
self.setParentNodeUi(None)
if nodeEditor.NodeEditor._attributeUis.has_key(self._coralAttributeId):
del nodeEditor.NodeEditor._attributeUis[self._coralAttributeId]
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import copy
import weakref
from PyQt4 import QtGui, QtCore
from ... import coralApp
from ..._coral import ErrorObject
import connection
import nodeView
class ConnectionHook(QtGui.QGraphicsItem):
_outstandingDraggingConnection = None
@staticmethod
def _removeOutstandingDraggingConnection():
if ConnectionHook._outstandingDraggingConnection:
draggingConnection = ConnectionHook._outstandingDraggingConnection()
draggingConnection.deleteIt()
ConnectionHook._outstandingDraggingConnection = None
def __init__(self, parentAttributeUi, parentItem = None, isInput = False, isOutput = False):
if parentItem is None:# parentItem is used by builtinUis.ContainedAttributeUiProxy
parentItem = parentAttributeUi
QtGui.QGraphicsItem.__init__(self, parentItem)
self._parentNodeUi = weakref.ref(parentAttributeUi.parentNodeUi())
self._parentAttributeUi = weakref.ref(parentAttributeUi)
self._isInput = isInput
self._isOutput = isOutput
self._rect = QtCore.QRectF(0, 0, 12, 12)
self._color = QtGui.QColor(200, 200, 200)
self._brush = QtGui.QBrush(self.color())
self._pen = QtGui.QPen(QtCore.Qt.NoPen)
self._draggingConnection = None
self._draggingConnectionEndHook = None
self._connections = []
self._mixedColor = False
self._lastDropNode = None
self.setFlags(QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
self._pen.setWidthF(1.0)
self.setAcceptsHoverEvents(True)
def hoverEnterEvent(self, event):
for conn in self._connections:
conn._pen.setWidth(2)
conn.update()
def hoverLeaveEvent(self, event):
for conn in self._connections:
conn._pen.setWidth(1)
conn.update()
def setMixedColor(self, value = True):
self._mixedColor = value
def setBorderEnabled(self, value = True):
if value:
self._pen.setStyle(QtCore.Qt.SolidLine)
else:
self._pen.setStyle(QtCore.Qt.NoPen)
def updateToolTip(self):
self.setToolTip(self._parentAttributeUi().toolTip())
def onChangedScene(self, scene):
for conn in self._connections:
if conn.scene():
conn.scene().removeItem(conn)
if scene:
scene.addItem(conn)
def itemChange(self, change, value):
if change == QtGui.QGraphicsItem.ItemScenePositionHasChanged:
self.updateWorldPos()
return value
def updateWorldPos(self):
if self._isInput:
for conn in self._connections:
conn.updateEndPos()
else:
for conn in self._connections:
conn.updateStartPos()
def addConnection(self, connection):
self._connections.append(connection)
def removeConnection(self, connection):
if connection in self._connections:
del self._connections[self._connections.index(connection)]
def connections(self):
return copy.copy(self._connections)
def parentAttributeUi(self):
return self._parentAttributeUi()
def parentNodeUi(self):
return self._parentNodeUi()
def setColor(self, color):
self._color.setRgb(color.red(), color.green(), color.blue())
self._brush.setColor(self._color)
self._pen.setColor(self._color.darker(150))
def color(self):
return QtGui.QColor(self._color)
def mixedColor(self):
return self._mixedColor
def setColorRef(self, color):
self._color = color
def colorRef(self):
return self._color
def mousePressEvent(self, event):
if self._isOutput:
self._draggingConnection = connection.Connection(self)
self._draggingConnection._pen.setWidth(2)
ConnectionHook._outstandingDraggingConnection = weakref.ref(self._draggingConnection)
elif self._connections:
inputConnection = self._connections[0]
coralAttribute = self.parentAttributeUi().coralAttribute()
coralApp.executeCommand("DisconnectInput", attribute = coralAttribute.fullName())
self.parentAttributeUi().parentNodeUi().update()
outHook = inputConnection.startHook()
self._draggingConnection = connection.Connection(outHook)
mousePos = self._draggingConnection.mapFromScene(event.scenePos())
self._draggingConnection.endHook().setPos(mousePos)
self._draggingConnection.updateEndPos()
def _handleHover(self, item):
nodeHovered = None
collidingItems = item.collidingItems(QtCore.Qt.IntersectsItemBoundingRect)
if collidingItems:
nodeHovered = collidingItems[0]
if nodeHovered:
nodeHovered.hoverEnterEvent(None)
elif nodeView.NodeView._lastHoveredItem:
nodeView.NodeView._lastHoveredItem.hoverLeaveEvent(None)
def mouseMoveEvent(self, event):
if self._draggingConnection:
connectionStartHook = self._draggingConnection.startHook()
self._draggingConnectionEndHook = None
self._draggingConnection.setColor(connectionStartHook.color())
self._draggingConnection.setDashedPen(True)
connectionEndHook = self._draggingConnection.endHook()
mousePos = self._draggingConnection.mapFromScene(event.scenePos())
connectionEndHook.setPos(mousePos)
self._handleHover(self._draggingConnection.endHook())
endHook = self._draggingConnection.findClosestHook()
if endHook:
sourceAttribute = connectionStartHook.parentAttributeUi()
destinationAttribute = endHook.parentAttributeUi()
errorObject = ErrorObject()
if sourceAttribute.allowConnectionTo(destinationAttribute, errorObject):
hookSize = endHook.boundingRect().bottomRight() / 2.0
hookPos = self._draggingConnection.mapFromItem(endHook, hookSize.x(), hookSize.y())
connectionEndHook.setPos(hookPos)
self._draggingConnectionEndHook = endHook
self._draggingConnection.setDashedPen(False)
else:
self._draggingConnection.setColor(QtGui.QColor(255.0, 5.0, 10.0))
message = errorObject.message()
if message:
QtGui.QToolTip.showText(event.screenPos(), message)
else:
if QtGui.QToolTip.isVisible():
QtGui.QToolTip.hideText()
self._draggingConnection.updateEndPos()
def mouseReleaseEvent(self, event):
if self._draggingConnection:
startHook = self._draggingConnection.startHook()
self._draggingConnection.deleteIt()
self._draggingConnection = None
ConnectionHook._outstandingDraggingConnection = None
if self._draggingConnectionEndHook:
sourceAttribute = startHook.parentAttributeUi().coralAttribute()
destinationAttribute = self._draggingConnectionEndHook.parentAttributeUi().coralAttribute()
self._draggingConnectionEndHook = None
success = coralApp.executeCommand("ConnectAttributes", sourceAttribute = sourceAttribute.fullName(), destinationAttribute = destinationAttribute.fullName())
self.parentAttributeUi().parentNodeUi().update()
def boundingRect(self):
return self._rect
def paint(self, painter, option, widget):
painter.setBrush(self._brush)
painter.setPen(self._pen)
painter.drawEllipse(self._rect)
if self._mixedColor:
painter.setBrush(painter.brush().color().darker(130))
painter.drawChord(self._rect, 1 * 16, 180 * 16)
def isInput(self):
return self._isInput
def isOutput(self):
return self._isOutput
def deleteIt(self):
conns = copy.copy(self._connections)
for conn in conns:
conn.deleteIt()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from ... import coralApp
from ..._coral import Command, Node
from ...observer import Observer, ObserverCollector
from nodeUi import NodeUi, AttributeUi, Connection
from nodeView import NodeView
from rootNodeUi import RootNodeUi
from addressBar import AddressBar
def _checkClassIsNodeUi(class_):
if NodeUi in class_.__bases__:
return True
else:
for baseClass in class_.__bases__:
val = _checkClassIsNodeUi(baseClass)
if val:
return val
class NodeEditor(QtGui.QWidget):
_rootNodeUi = None
_nodeUis = {}
_attributeUis = {}
_attributeUiClasses = {}
_nodeUiClasses = {}
_selectedNodesId = []
_selectedAttributesId = []
_selectedNodesChangedObservers = ObserverCollector()
_instances = []
_focusedInstance = None
_initializedNewNetworkObserver = Observer()
_createdNodeObserver = Observer()
_deletingNodeObserver = Observer()
_connectedAttributesObserver = Observer()
_createdAttributeObserver = Observer()
_deletingAttributeObserver = Observer()
_removedNodeObserver = Observer()
_addedNodeObserver = Observer()
_addedAttributeObserver = Observer()
_collapsedNodeObserver = Observer()
_generatingSaveScriptObserver = Observer()
_networkLoadedObserver = Observer()
_removedAttributeObserver = Observer()
@staticmethod
def instances():
return NodeEditor._instances
@staticmethod
def _addInstance(nodeEditor):
NodeEditor._instances.append(nodeEditor)
@staticmethod
def _removeInstance(nodeEditor):
if nodeEditor in NodeEditor._instances:
del NodeEditor._instances[NodeEditor._instances.index(nodeEditor)]
@staticmethod
def addSelectedNodesChangedObserver(observer, callback):
NodeEditor._selectedNodesChangedObservers.add(observer)
observer.setNotificationCallback(callback)
@staticmethod
def _notifySelectedNodesChangedObservers():
for observer in NodeEditor._selectedNodesChangedObservers.observers():
observer.notify()
@staticmethod
def _setSelectedNodes(nodes):
oldSel = NodeEditor._selectedNodesId
NodeEditor._selectedNodesId = []
for node in nodes:
NodeEditor._selectedNodesId.append(node.id())
selectionUpdated = False
if oldSel != NodeEditor._selectedNodesId:
selectionUpdated = True
return selectionUpdated
@staticmethod
def _setSelectedAttributes(attributes):
oldSel = NodeEditor._selectedAttributesId
NodeEditor._selectedAttributesId = []
for attr in attributes:
NodeEditor._selectedAttributesId.append(attr.id())
selectionUpdated = False
if oldSel != NodeEditor._selectedAttributesId:
selectionUpdated = True
return selectionUpdated
@staticmethod
def _setSelection(nodes = [], attributes = [], updateSelected = True):
if updateSelected:
for nodeId in NodeEditor._selectedNodesId:
nodeUi = NodeEditor.findNodeUi(nodeId)
if nodeUi:
nodeUi.setSelected(False)
for attrId in NodeEditor._selectedAttributesId:
attrUi = NodeEditor.findAttributeUi(attrId)
if attrUi:
attrUi.proxy().setSelected(False)
nodeSelUpdated = NodeEditor._setSelectedNodes(nodes)
attrSelUpdated = NodeEditor._setSelectedAttributes(attributes)
if nodeSelUpdated or attrSelUpdated:
NodeEditor._notifySelectedNodesChangedObservers()
if updateSelected:
for node in nodes:
nodeUi = NodeEditor.findNodeUi(node.id())
if nodeUi:
nodeUi.setSelected(True)
for attr in attributes:
attrUi = NodeEditor.findAttributeUi(attr.id())
if attrUi:
attrUi.proxy().setSelected(True)
@staticmethod
def selectedNodes():
nodes = []
for nodeId in NodeEditor._selectedNodesId:
node = coralApp.findObjectById(nodeId)
if node:
nodes.append(node)
return nodes
@staticmethod
def selectedAttributes():
attrs = []
for attrId in NodeEditor._selectedAttributesId:
attr = coralApp.findObjectById(attrId)
if attr:
attrs.append(attr)
return attrs
@staticmethod
def _setFocusedInstance(nodeEditor):
NodeEditor._focusedInstance = weakref.ref(nodeEditor)
@staticmethod
def focusedInstance():
nodeEditor = None
if NodeEditor._focusedInstance:
nodeEditor = NodeEditor._focusedInstance()
return nodeEditor
@staticmethod
def currentNodeUi():
currentNodeUi = None
nodeEditor = NodeEditor.focusedInstance()
if nodeEditor:
currentNodeUi = nodeEditor.nodeView().currentNodeUi()
return currentNodeUi
@staticmethod
def currentNode():
currentNode = None
currentNodeUi = NodeEditor.currentNodeUi()
if currentNodeUi:
currentNode = currentNodeUi.coralNode()
return currentNode
@staticmethod
def registerNodeUiClass(coralNodeClassName, nodeUiClass):
if _checkClassIsNodeUi(nodeUiClass):
NodeEditor._nodeUiClasses[coralNodeClassName] = nodeUiClass
else:
coralApp.logError("could not register nodeUi, expected NodeUi subclass: " + str(nodeUiClass))
@staticmethod
def registerAttributeUiClass(coralAttributeClassName, attributeUiClass):
if AttributeUi in attributeUiClass.__bases__:
NodeEditor._attributeUiClasses[coralAttributeClassName] = attributeUiClass
else:
coralApp.logError("could not register attributeUi, expected AttributeUi subclass: " + str(attributeUiClass))
@staticmethod
def _init():
NodeEditor._coralInitializedNewNetwork()
coralApp.addInitializedNewNetworkObserver(NodeEditor._initializedNewNetworkObserver, NodeEditor._coralInitializedNewNetwork)
coralApp.addCreatedNodeObserver(NodeEditor._createdNodeObserver, NodeEditor._coralCreatedNodeCallback)
coralApp.addDeletingNodeObserver(NodeEditor._deletingNodeObserver, NodeEditor._coralDeletingNodeCallback)
coralApp.addConnectedAttributesObserver(NodeEditor._connectedAttributesObserver, NodeEditor._coralConnectedAttributesCallback)
coralApp.addCreatedAttributeObserver(NodeEditor._createdAttributeObserver, NodeEditor._coralCreatedAttributeCallback)
coralApp.addDeletingAttributeObserver(NodeEditor._deletingAttributeObserver, NodeEditor._coralDeletingAttributeCallback)
coralApp.addRemovedNodeObserver(NodeEditor._removedNodeObserver, NodeEditor._coralRemovedNodeCallback)
coralApp.addAddedNodeObserver(NodeEditor._addedNodeObserver, NodeEditor._coralAddedNodeCallback)
coralApp.addAddedAttributeObserver(NodeEditor._addedAttributeObserver, NodeEditor._coralAddedAttributeCallback)
coralApp.addCollapsedNodeObserver(NodeEditor._collapsedNodeObserver, NodeEditor._coralCollapsedNodeCallback)
coralApp.addGeneratingSaveScriptObserver(NodeEditor._generatingSaveScriptObserver, NodeEditor._coralGeneratingSaveScriptCallback)
coralApp.addNetworkLoadedObserver(NodeEditor._networkLoadedObserver, NodeEditor._networkLoadedCallback)
coralApp.addRemovedAttributeObserver(NodeEditor._removedAttributeObserver, NodeEditor._removedAttributeCallback)
import nodeEditorCommands
coralApp.loadPluginModule(nodeEditorCommands)
@staticmethod
def _saveNodeUiData(nodeUi, rootNode = False):
saveScript = ""
if nodeUi:
nodeUiData = nodeUi.data()
if rootNode:
if nodeUiData.has_key("pos"):
del nodeUiData["pos"]
setNodeUiDataCmd = Command()
setNodeUiDataCmd.setName("SetNodeUiData")
setNodeUiDataCmd.setArgString("node", nodeUi.coralNode().fullName())
setNodeUiDataCmd.setArgUndefined("data", str(nodeUiData))
saveScript += setNodeUiDataCmd.asScript() + "\n"
for coralNode in nodeUi.coralNode().nodes():
nodeUi = NodeEditor.findNodeUi(coralNode.id())
saveScript += NodeEditor._saveNodeUiData(nodeUi)
return saveScript
@staticmethod
def _networkLoadedCallback():
NodeEditor.focusedInstance().nodeView().frameSceneContent()
@staticmethod
def _coralGeneratingSaveScriptCallback():
nodeId = NodeEditor._generatingSaveScriptObserver.data("nodeId")
nodeUi = NodeEditor.findNodeUi(nodeId)
saveScript = NodeEditor._generatingSaveScriptObserver.data("saveScript")
saveScript[0] += "# nodeEditor save data\n"
saveScript[0] += NodeEditor._saveNodeUiData(nodeUi, rootNode = True)
@staticmethod
def _coralInitializedNewNetwork():
coralRootNode = coralApp.rootNode()
NodeEditor._rootNodeUi = RootNodeUi(coralRootNode)
NodeEditor._nodeUis[coralRootNode.id()] = NodeEditor._rootNodeUi
for instance in NodeEditor._instances:
instance.nodeView().setCurrentNodeUi(NodeEditor._rootNodeUi)
@staticmethod
def _coralCollapsedNodeCallback():
collapsedNodeId = NodeEditor._collapsedNodeObserver.data("collapsedNodeId")
collapsedNodeUi = NodeEditor.findNodeUi(collapsedNodeId)
collapsedNodeUi.repositionAmongConnectedNodes()
collapsedNodeUi.repositionContainedProxys()
@staticmethod
def _coralAddedAttributeCallback():
parentNodeId = NodeEditor._addedAttributeObserver.data("parentNodeId")
attributeAddedId = NodeEditor._addedAttributeObserver.data("attributeAddedId")
parentNodeUi = NodeEditor.findNodeUi(parentNodeId)
if parentNodeUi:
attributeAddedUi = NodeEditor.findAttributeUi(attributeAddedId)
if attributeAddedUi is None:
attr = coralApp.findObjectById(attributeAddedId)
attributeAddedUi = NodeEditor._createAttributeUi(attr, parentNodeUi)
parentNodeUi.addInputAttributeUi(attributeAddedUi)
parentNodeUi.updateLayout()
if NodeEditor._addedAttributeObserver.data("input"):
parentNodeUi.addInputAttributeUi(attributeAddedUi)
else:
parentNodeUi.addOutputAttributeUi(attributeAddedUi)
@staticmethod
def _removedAttributeCallback():
parentNodeId = NodeEditor._removedAttributeObserver.data("parentNodeId")
parentNodeUi = NodeEditor.findNodeUi(parentNodeId)
if parentNodeUi:
attributeAddedId = NodeEditor._removedAttributeObserver.data("attributeRemovedId")
attributeAddedUi = NodeEditor.findAttributeUi(attributeAddedId)
if attributeAddedUi:
parentNodeUi.removeAttributeUi(attributeAddedUi)
attributeAddedUi.setParentNodeUi(None)
parentNodeUi.updateLayout()
@staticmethod
def _coralAddedNodeCallback():
parentNodeId = NodeEditor._addedNodeObserver.data("parentNodeId")
nodeAddedId = NodeEditor._addedNodeObserver.data("nodeAddedId")
parentNodeUi = NodeEditor.findNodeUi(parentNodeId)
nodeAddedUi = NodeEditor.findNodeUi(nodeAddedId)
parentNodeUi.addNodeUi(nodeAddedUi)
@staticmethod
def _coralRemovedNodeCallback():
parentNodeId = NodeEditor._removedNodeObserver.data("parentNodeId")
nodeRemovedId = NodeEditor._removedNodeObserver.data("nodeRemovedId")
parentNodeUi = NodeEditor.findNodeUi(parentNodeId)
if parentNodeUi:
nodeRemovedUi = NodeEditor.findNodeUi(nodeRemovedId)
if nodeRemovedUi:
parentNodeUi.removeNodeUi(nodeRemovedUi)
@staticmethod
def _coralDeletingAttributeCallback():
attributeId = NodeEditor._deletingAttributeObserver.data("attributeId")
attributeUi = NodeEditor.findAttributeUi(attributeId)
if attributeUi:
parentNodeUi = attributeUi.parentNodeUi()
attributeUi.deleteIt()
parentNodeUi.updateLayout()
@staticmethod
def _coralCreatedAttributeCallback():
attributeId = NodeEditor._createdAttributeObserver.data("attributeId")
coralAttribute = coralApp.findObjectById(attributeId)
parentNodeUi = NodeEditor.findNodeUi(coralAttribute.parent().id())
attributeUi = NodeEditor._createAttributeUi(coralAttribute, parentNodeUi)
if coralAttribute.isInput():
parentNodeUi.addInputAttributeUi(attributeUi)
else:
parentNodeUi.addOutputAttributeUi(attributeUi)
parentNodeUi.updateLayout()
@staticmethod
def _coralConnectedAttributesCallback():
sourceAttributeId = NodeEditor._connectedAttributesObserver.data("sourceAttributeId")
destinationAttributeId = NodeEditor._connectedAttributesObserver.data("destinationAttributeId")
sourceAttributeUi = NodeEditor.findAttributeUi(sourceAttributeId)
destinationAttributeUi = NodeEditor.findAttributeUi(destinationAttributeId)
sourceAttributeUi.connectTo(destinationAttributeUi)
@staticmethod
def _coralDeletingNodeCallback():
nodeId = NodeEditor._deletingNodeObserver.data("nodeId")
nodeUi = NodeEditor.findNodeUi(nodeId)
if nodeUi:
nodeUi.deleteIt()
@staticmethod
def _coralCreatedNodeCallback():
nodeId = NodeEditor._createdNodeObserver.data("nodeId")
coralNode = coralApp.findObjectById(nodeId)
NodeEditor._createNodeUi(coralNode)
NodeEditor._setSelection(nodes = [coralNode])
@staticmethod
def _createNodeUi(coralNode):
nodeUiClass = NodeUi
classNames = coralNode.classNames()
classNames.reverse()
for className in classNames:
if NodeEditor._nodeUiClasses.has_key(className):
nodeUiClass = NodeEditor._nodeUiClasses[className]
break
nodeUi = nodeUiClass(coralNode)
nodeUi.buildFromCoralNode()
# this container is meant to keep nodeUi alive when Qt releases ownership
NodeEditor._nodeUis[coralNode.id()] = nodeUi
return nodeUi
@staticmethod
def _createAttributeUi(coralAttribute, parentNodeUi):
attributeUi = None
attributeUiClass = AttributeUi
className = coralAttribute.className()
if NodeEditor._attributeUiClasses.has_key(className):
attributeUiClass = NodeEditor._attributeUiClasses[className]
attributeUi = attributeUiClass(coralAttribute, parentNodeUi)
# keeping this instance alive when ownership is released by Qt
NodeEditor._attributeUis[coralAttribute.id()] = attributeUi
return attributeUi
@staticmethod
def findNodeUi(coralNodeId):
nodeUi = None
if NodeEditor._nodeUis.has_key(coralNodeId):
nodeUi = NodeEditor._nodeUis[coralNodeId]
return nodeUi
@staticmethod
def findAttributeUi(coralAttributeId):
attributeUi = None
if NodeEditor._attributeUis.has_key(coralAttributeId):
attributeUi = NodeEditor._attributeUis[coralAttributeId]
return attributeUi
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QVBoxLayout(self)
self._addressBar = AddressBar(self)
self._nodeView = NodeView(self)
self.setWindowTitle("node editor")
self.setLayout(self._mainLayout)
self.setContentsMargins(5, 5, 5, 5)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setSpacing(5)
self._mainLayout.addWidget(self._addressBar)
self._mainLayout.addWidget(self._nodeView)
self.connect(self._nodeView, QtCore.SIGNAL("currentNodeUiChanged"), self._currentNodeUiChanged)
self.connect(self._addressBar.upButton(), QtCore.SIGNAL("clicked()"), self._upButtonClicked)
self.connect(self._addressBar, QtCore.SIGNAL("addressBarChanged"), self._addressBarChanged)
self._nodeView.setCurrentNodeUi(NodeEditor._rootNodeUi)
NodeEditor._addInstance(self)
NodeEditor._setFocusedInstance(self)
def closeEvent(self, event):
NodeEditor._removeInstance(self)
def sizeHint(self):
return QtCore.QSize(500, 500)
def _addressBarChanged(self):
address = self._addressBar.address()
node = coralApp.findNode(address)
opened = False
if node:
nodeUi = NodeEditor.findNodeUi(node.id())
if nodeUi.canOpenThis():
self._nodeView.setCurrentNodeUi(nodeUi)
opened = True
if not opened:
self._addressBar.setAddress(self._nodeView.currentNodeUi().coralNode().fullName())
def _currentNodeUiChanged(self):
coralNode = self._nodeView.currentNodeUi().coralNode()
self._addressBar.setAddress(coralNode.fullName())
self.setWindowTitle(coralNode.name())
if type(self.parentWidget()) is QtGui.QDockWidget:
self.parentWidget().setWindowTitle(coralNode.name())
def _upButtonClicked(self):
parentNodeUi = self._nodeView.currentNodeUi().parentNodeUi()
if parentNodeUi:
self._nodeView.setCurrentNodeUi(parentNodeUi)
def nodeView(self):
return self._nodeView
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
import nodeEditor
class NodeUiScene(QtGui.QGraphicsScene):
def __init__(self, parentNodeUi):
QtGui.QGraphicsScene.__init__(self)
self._backgroundColor = QtGui.QColor(50, 55, 60)
self._parentNodeUi = weakref.ref(parentNodeUi)
self._gridPen = QtGui.QPen(self._backgroundColor.lighter(120))
self._zoom = 1.0
self._centerPos = QtCore.QPointF(0.0, 0.0)
self._firstTimeEntering = True
self._gridPen.setWidth(1)
self.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex) # fixes bug with scene.removeItem()
self.setBackgroundBrush(self._backgroundColor)
def helpEvent(self, event):
items = self.items(event.scenePos())
for item in items:
if hasattr(item, "updateToolTip"):
item.updateToolTip()
break
QtGui.QGraphicsScene.helpEvent(self, event)
def mouseReleaseEvent(self, event):
QtGui.QGraphicsScene.mouseReleaseEvent(self, event)
if event.isAccepted() == False:
if event.button() == QtCore.Qt.LeftButton:
from connectionHook import ConnectionHook
if ConnectionHook._outstandingDraggingConnection:
ConnectionHook._removeOutstandingDraggingConnection()
elif event.button() == QtCore.Qt.RightButton:
self._parentNodeUi().showRightClickMenu()
self._selectionChanged()
def _selectionChanged(self):
nodes = []
attributes = []
for item in self.selectedItems():
if hasattr(item, "coralNode"):
nodes.append(item.coralNode())
elif hasattr(item, "coralAttribute"):
attributes.append(item.coralAttribute())
nodeEditor.NodeEditor._setSelection(nodes, attributes, updateSelected = False)
def setZoom(self, zoom):
self._zoom = zoom
def zoom(self):
return self._zoom
def setCenterPos(self, pos):
self._centerPos = QtCore.QPointF(pos)
def centerPos(self):
return QtCore.QPointF(self._centerPos)
def parentNodeUi(self):
return self._parentNodeUi()
def drawBackground(self, painter, rect):
QtGui.QGraphicsScene.drawBackground(self, painter, rect)
painter.setPen(self._gridPen)
gridSize = 50
left = int(rect.left()) - (int(rect.left()) % gridSize)
top = int(rect.top()) - (int(rect.top()) % gridSize)
lines = []
x = left
while x < rect.right():
painter.drawLine(x, rect.top(), x, rect.bottom())
x += gridSize
y = top
while y < rect.bottom():
painter.drawLine(rect.left(), y, rect.right(), y)
y += gridSize
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from connectionHook import ConnectionHook
import nodeView
class AttributeUiProxy(QtGui.QGraphicsWidget):
def __init__(self, attributeUi):
QtGui.QGraphicsWidget.__init__(self)
self._parentNodeUi = weakref.ref(attributeUi.parentNodeUi())
self._attributeUi = weakref.ref(attributeUi)
self._shapePen = self._parentNodeUi().shapePen()
self._inputHook = None
self._outputHook = None
self._label = QtGui.QGraphicsSimpleTextItem(self)
self._spacerConstant = 5.0
self._currentMagnifyFactor = 0.0
self._zValue = self.zValue()
hookColor = QtGui.QColor(100, 100, 100)
if attributeUi.outputHook():
hookColor = attributeUi.outputHook().color()
elif attributeUi.inputHook():
hookColor = attributeUi.inputHook().color()
if attributeUi.inputHook():
self._outputHook = ConnectionHook(attributeUi, parentItem = self, isOutput = True)
self._outputHook.setColor(hookColor)
self._outputHook.setFlags(QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
else:
self._inputHook = ConnectionHook(attributeUi, parentItem = self, isInput = True)
self._inputHook.setColor(hookColor)
self._inputHook.setFlags(QtGui.QGraphicsItem.ItemSendsScenePositionChanges)
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable)
self._label.setBrush(attributeUi.labelColor())
self._label.setText(attributeUi.coralAttribute().name())
self._shapePen.setStyle(QtCore.Qt.NoPen)
self.setAcceptHoverEvents(True)
self.updateLayout()
def _magnifyAnimStep(self, frame):
step = frame / nodeView.NodeView._animSteps
invStep = 1.0 - step
self.setScale((self.scale() * invStep) + ((1.0 * self._currentMagnifyFactor) * step))
if self._inputHook:
self._inputHook.updateWorldPos()
elif self._outputHook:
self._outputHook.updateWorldPos()
self.scene().update()
def _magnify(self, factor):
self._currentMagnifyFactor = factor
timer = QtCore.QTimeLine(nodeView.NodeView._animSpeed, self)
timer.setFrameRange(0, nodeView.NodeView._animSteps)
self.connect(timer, QtCore.SIGNAL("frameChanged(int)"), self._magnifyAnimStep);
timer.start()
def hoverEnterEvent(self, event):
if nodeView.NodeView._lastHoveredItem is not self:
if nodeView.NodeView._lastHoveredItem:
nodeView.NodeView._lastHoveredItem.hoverLeaveEvent(None)
zoom = self.scene().zoom()
if zoom < 0.6:
factor = 0.7 / zoom
self.setTransformOriginPoint(self.rect().center())
self._magnify(factor)
nodeView.NodeView._lastHoveredItem = self
self.setZValue(9999999)
def hoverLeaveEvent(self, event):
if nodeView.NodeView._lastHoveredItem is self:
self._magnify(1.0)
self.setZValue(self._zValue)
nodeView.NodeView._lastHoveredItem = None
def deleteInputConnection(self):
if self._inputHook:
if self._inputHook._connections:
self._inputHook._connections[0].deleteIt()
def onChangedScene(self, scene):
pass
def deleteIt(self):
if self._outputHook:
self._outputHook.deleteIt()
if self._inputHook:
self._inputHook.deleteIt()
self.scene().removeItem(self)
def coralAttribute(self):
return self._attributeUi().coralAttribute()
def inputHook(self):
return self._inputHook
def outputHook(self):
return self._outputHook
def specialized(self):
attributeUi = self._attributeUi()
hookColor = QtGui.QColor(100, 100, 100)
hookMixedColor = hookColor
if attributeUi.outputHook():
hook = attributeUi.outputHook()
hookColor = hook.color()
hookMixedColor = hook.mixedColor()
elif attributeUi.inputHook():
hook = attributeUi.inputHook()
hookColor = hook.color()
hookMixedColor = hook.mixedColor()
hook = None
if self._outputHook:
hook = self._outputHook
elif self._inputHook:
hook = self._inputHook
hook.setColor(hookColor)
hook.setMixedColor(hookMixedColor)
self._label.setText(attributeUi._labelText + attributeUi._labelSuffix)
self.updateLayout()
self.update()
def itemChange(self, change, value):
if change == QtGui.QGraphicsItem.ItemSelectedHasChanged:
if self.isSelected():
self._shapePen.setStyle(QtCore.Qt.SolidLine)
else:
self._shapePen.setStyle(QtCore.Qt.NoPen)
return value
def updateLayout(self):
labelHeight = self._label.boundingRect().height()
height = self._spacerConstant + labelHeight + self._spacerConstant
inputHookOffset = 0
if self._inputHook:
hookY = (height - self._inputHook.boundingRect().height()) / 2.0
self._inputHook.setPos(self._spacerConstant, hookY)
inputHookOffset = self._inputHook.boundingRect().width() + self._inputHook.pos().x()
self._label.setPos(inputHookOffset + self._spacerConstant, (height - labelHeight) / 2.0)
outputHookOffset = self._label.pos().x() + self._label.boundingRect().width()
if self._outputHook:
hookY = (height - self._outputHook.boundingRect().height()) / 2.0
self._outputHook.setPos(outputHookOffset + self._spacerConstant, hookY)
outputHookOffset = self._outputHook.pos().x() + self._outputHook.boundingRect().width()
self.resize(QtCore.QSizeF(outputHookOffset + self._spacerConstant, height))
def paint(self, painter, option, widget):
attributeUi = self._attributeUi()
parentNodeUi = self._parentNodeUi()
shape = QtGui.QPainterPath()
shape.addRoundedRect(self.rect(), 2, 2)
painter.setPen(self._shapePen)
painter.setBrush(parentNodeUi.color())
painter.drawPath(shape)
def data(self):
data = {"name": self.coralAttribute().name(), "pos": [self.pos().x(), self.pos().y()]}
return data
def setData(self, data):
if data.has_key("pos"):
pos = data["pos"]
self.setPos(pos[0], pos[1])
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from ... import coralApp
from .. import coralUi
from .. import nodeBox
import nodeEditor
class NodeView(QtGui.QGraphicsView):
_lastHoveredItem = None
_animSpeed = 50.0
_animSteps = 50.0
_panning = False
def __init__(self, parent):
QtGui.QGraphicsView.__init__(self, parent)
self._zoom = 1.0
self._currentNodeUi = None
self._panning = False
self._currentCenterPoint = QtCore.QPointF()
self._lastPanPoint = QtCore.QPoint()
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.setAcceptDrops(True)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setDragMode(QtGui.QGraphicsView.RubberBandDrag)
self.setSceneRect(-5000, -5000, 10000, 10000)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
QtGui.QShortcut(QtGui.QKeySequence("Delete"), self, self._deleteKey)
QtGui.QShortcut(QtGui.QKeySequence("Backspace"), self, self._deleteKey)
QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self, self._copyKey)
QtGui.QShortcut(QtGui.QKeySequence("Ctrl+V"), self, self._pasteKey)
def _selectedNodesName(self):
selectedNodes = self._selectedNodes()
nodesName = []
for node in selectedNodes:
nodesName.append(node.fullName())
return nodesName
def _selectedAttributesName(self):
selectedAttributes = self._selectedAttributes()
attributesName = []
for attribute in selectedAttributes:
attributesName.append(attribute.fullName())
return attributesName
def _copyKey(self):
nodesName = self._selectedNodesName()
attributesName = self._selectedAttributesName()
if nodesName or attributesName:
clipboardData = {"nodesName": nodesName}
coralUi.copyToClipboard(clipboardData)
def _pasteKey(self):
clipboardData = coralUi.clipboardData()
if clipboardData:
nodesName = []
if clipboardData.has_key("nodesName"):
nodesName = clipboardData["nodesName"]
pastedNodesStr = coralApp.executeCommand("Paste", nodes = nodesName, parentNode = self._currentNodeUi().coralNode().fullName())
pastedNodes = eval(pastedNodesStr)
self.scene().clearSelection()
for pastedNode in pastedNodes:
node = coralApp.findNode(pastedNode)
nodeUi = nodeEditor.NodeEditor.findNodeUi(node.id())
nodeUi.setPos(nodeUi.pos().x() + 10.0, nodeUi.pos().y() + 20.0)
nodeUi.setSelected(True)
self.scene()._selectionChanged()
def _deleteKey(self):
nodesName = self._selectedNodesName()
attributesName = self._selectedAttributesName()
if nodesName or attributesName:
self.setSelectedItems([])
coralApp.executeCommand("DeleteObjects", nodes = nodesName, attributes = attributesName)
def currentNodeUi(self):
nodeUi = None
if self._currentNodeUi:
nodeUi = self._currentNodeUi()
return nodeUi
def focusInEvent(self, focusEvent):
nodeEditor.NodeEditor._setFocusedInstance(self.parentWidget())
def setCurrentNodeUi(self, nodeUi):
if self._currentNodeUi:
oldNodeUi = self._currentNodeUi()
if oldNodeUi:
oldNodeUi.containedScene().clearSelection()
newScene = nodeUi.containedScene()
self._currentNodeUi = weakref.ref(nodeUi)
self.setScene(newScene)
self.setZoom(newScene.zoom())
newCenter = newScene.centerPos()
self.centerOn(newCenter)
self._currentCenterPoint = newCenter
newScene.clearSelection()
newScene._selectionChanged()
if newScene._firstTimeEntering:
self.frameSceneContent()
newScene._firstTimeEntering = False
self.emit(QtCore.SIGNAL("currentNodeUiChanged"))
def frameSceneContent(self):
self.scene().setCenterPos(self.scene().itemsBoundingRect().center())
newCenter = self.scene().centerPos()
self.centerOn(newCenter)
self._currentCenterPoint = newCenter
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
if coralUi.dropDataType() == "nodeBoxItemData":
event.accept()
sceneItem = nodeBox.NodeBox._createFromItemData(coralUi.dropData())
if sceneItem:
scenePos = self.mapToScene(event.pos())
sceneItem.setPos(scenePos)
self.setSelectedItems([sceneItem])
def setSelectedItems(self, items):
self.scene().clearSelection()
for item in items:
item.setSelected(True)
self.scene()._selectionChanged()
def getCenter(self):
return self._currentCenterPoint
def setCenter(self, centerPoint):
self._currentCenterPoint = centerPoint
self.scene().setCenterPos(centerPoint)
self.centerOn(self._currentCenterPoint);
def mousePressEvent(self, mouseEvent):
if mouseEvent.modifiers() == QtCore.Qt.AltModifier:
self._lastPanPoint = mouseEvent.pos()
self.setCursor(QtCore.Qt.ClosedHandCursor)
self._panning = True
NodeView._panning = True
else:
QtGui.QGraphicsView.mousePressEvent(self, mouseEvent)
def mouseMoveEvent(self, mouseEvent):
if self._panning:
delta = self.mapToScene(self._lastPanPoint) - self.mapToScene(mouseEvent.pos())
self._lastPanPoint = mouseEvent.pos()
self.setCenter(self.getCenter() + delta)
else:
QtGui.QGraphicsView.mouseMoveEvent(self, mouseEvent)
def mouseReleaseEvent(self, mouseEvent):
if self._panning:
self.setCursor(QtCore.Qt.ArrowCursor)
self._lastPanPoint = QtCore.QPoint()
self._panning = False
NodeView._panning = False
else:
QtGui.QGraphicsView.mouseReleaseEvent(self, mouseEvent)
def wheelEvent(self, event):
if event.orientation() == QtCore.Qt.Vertical:
delta = event.delta()
zoom = self._zoom
if delta > 0:
zoom += 0.05
else:
zoom -= 0.05
self.setZoom(zoom)
def _selectedNodes(self):
nodes = []
sel = self.scene().selectedItems()
for item in sel:
if hasattr(item, "coralNode"):
nodes.append(item.coralNode())
return nodes
def _selectedAttributes(self):
attributes = []
sel = self.scene().selectedItems()
for item in sel:
if hasattr(item, "coralAttribute"):
attributes.append(item.coralAttribute())
return attributes
def setZoom(self, zoom):
self._zoom = zoom
if zoom >= 1.0:
self._zoom = 1.0
elif zoom <= 0.1:
self._zoom = 0.1
transform = self.transform()
newTransform = QtGui.QTransform.fromTranslate(transform.dx(), transform.dy())
newTransform.scale(self._zoom, self._zoom)
self.setTransform(newTransform)
self.scene().setZoom(self._zoom)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from ..._coral import Command
from ... import coralApp
from ...plugin import Plugin
import nodeEditor
class SetNodeUiData(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("node", "")
self.setArgUndefined("data", "{}")
def doIt(self):
node = coralApp.findNode(self.argAsString("node"))
nodeUi = nodeEditor.NodeEditor.findNodeUi(node.id())
data = eval(self.argAsString("data"))
nodeUi.setData(data)
class Paste(Command):
def __init__(self):
Command.__init__(self)
self.setArgUndefined("nodes", "[]")
self.setArgString("parentNode", "")
def doIt(self):
nodesName = eval(self.argAsString("nodes"))
parentNodeName = self.argAsString("parentNode")
parentNode = coralApp.findNode(parentNodeName)
if parentNode is None:
return
# create nodes save script
script = "from coral.coralApp import *\n"
nodes = []
sourceParentNode = None
oldNames = []
for nodeName in nodesName:
node = coralApp.findNode(nodeName)
nodes.append(node)
name = node.name()
oldNames.append(name)
node.setName(name + "_copy")
script += node.asScript()
script += node.contentAsScript()
nodeUi = nodeEditor.NodeEditor.findNodeUi(node.id())
script += nodeEditor.NodeEditor._saveNodeUiData(nodeUi)
if sourceParentNode is None:
sourceParentNode = node.parent()
# add connections to save script
for node in nodes:
connectCmd = Command()
connectCmd.setName("ConnectAttributes")
for attr in node.attributes():
input = attr.input()
if input:
if input.parent().parent() is sourceParentNode:
connectCmd.setArgString("sourceAttribute", input.fullName())
connectCmd.setArgString("destinationAttribute", attr.fullName())
script += connectCmd.asScript() + "\n"
for out in attr.outputs():
if out.parent().parent() is sourceParentNode and out.isPassThrough():
connectCmd.setArgString("sourceAttribute", attr.fullName())
connectCmd.setArgString("destinationAttribute", out.fullName())
script += connectCmd.asScript() + "\n"
i = 0
for node in nodes:
node.setName(oldNames[i])
i += 1
script = script.replace(sourceParentNode.fullName(), parentNodeName)
# execute save script
coralApp.CoralAppData.lastCreatedNodes = []
coralApp.CoralAppData.appendToLastCreatedNodes = True
coralApp.CoralAppData.loadingNetwork = True
coralApp.setUndoLimit(0)
exec(script)
coralApp.setUndoLimit(100)
coralApp.CoralAppData.loadingNetwork = False
coralApp.CoralAppData.appendToLastCreatedNodes = False
# return only the top nodes created
outNodes = []
for nodeName in coralApp.CoralAppData.lastCreatedNodes:
node = coralApp.findNode(nodeName)
if node.parent() is parentNode:
outNodes.append(nodeName)
self.setResultString(str(outNodes))
coralApp.CoralAppData.lastCreatedNodes = []
def loadPlugin():
plugin = Plugin("nodeEditorCommands")
plugin.registerCommand(SetNodeUiData)
plugin.registerCommand(Paste)
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from connectionHook import ConnectionHook
class Connection(QtGui.QGraphicsItem):
def __init__(self, startHook, endHook = None):
QtGui.QGraphicsItem.__init__(self, None, startHook.scene())
self._rect = QtCore.QRectF(0, 0, 0, 0)
self._startHook = weakref.ref(startHook)
self._endHook = None
self._color = startHook.colorRef()
self._pen = QtGui.QPen(self._color)
self._pen.setWidth(1)
self._isTempConnection = False
self._path = QtGui.QPainterPath()
startHook.addConnection(self)
if endHook:
self._endHook = weakref.ref(endHook)
endHook.addConnection(self)
else:
# creating a dummy endHook for temporary connection dragging
self._endHook = weakref.ref(ConnectionHook(startHook.parentAttributeUi(), parentItem = self))
self._endHook().boundingRect().setSize(QtCore.QSizeF(2.0, 2.0))
self._isTempConnection = True
self.updateStartPos()
self.setZValue(-1.0)
def setDashedPen(self, value = True):
if value:
self._pen.setStyle(QtCore.Qt.DashLine)
else:
self._pen.setStyle(QtCore.Qt.SolidLine)
def deleteIt(self):
if self.scene():
self.scene().removeItem(self)
if self._endHook:
if self._endHook():
self._endHook().removeConnection(self)
self._endHook().parentAttributeUi().parentNodeUi().update()
if self._startHook():
self._startHook().removeConnection(self)
def updateStartPos(self):
startHook = self._startHook()
self.setPos(startHook.scenePos() + startHook.boundingRect().center())
self._updatePath()
def updateEndPos(self):
self._updatePath()
def setColor(self, color):
self._color = QtGui.QColor(color)
def setEndHook(self, connectionHook):
self._endHook = weakref.ref(connectionHook)
def endHook(self):
return self._endHook()
def startHook(self):
return self._startHook()
def setEndHook(self, connectionHook):
self._endPos = connectionHook.pos()
self._endTangent = connectionHook.inputTangent()
def findClosestHook(self):
closestHook = None
collidingItems = self._endHook().collidingItems(QtCore.Qt.IntersectsItemBoundingRect)
for collidingItem in collidingItems:
if type(collidingItem) is ConnectionHook:
if collidingItem.isInput() and collidingItem.isVisible():
closestHook = collidingItem
break
return closestHook
def _updatePath(self):
self.prepareGeometryChange()
endHook = self._endHook()
endPos = self.mapFromItem(endHook, 0.0, 0.0) + endHook.boundingRect().center()
tangentLength = (abs(endPos.x()) / 2.0) + (abs(endPos.y()) / 4.0)
startTangent = QtCore.QPointF(tangentLength, 0.0)
endTangent = QtCore.QPointF(endPos.x() - tangentLength, endPos.y())
path = QtGui.QPainterPath()
path.cubicTo(startTangent, endTangent, endPos)
strokeWidth = self._pen.widthF()
rect = path.boundingRect().adjusted(-strokeWidth, -strokeWidth, strokeWidth, strokeWidth)
self._path = path
self._rect = rect
def boundingRect(self):
return self._rect
def paint(self, painter, option, widget):
self._pen.setColor(self._color)
painter.setPen(self._pen)
painter.drawPath(self._path)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from nodeUi import NodeUi
class RootNodeUi(NodeUi):
def __init__(self, coralRootNode):
NodeUi.__init__(self, coralRootNode)
self.setCanOpenThis(True) | Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from PyQt4 import QtGui, QtCore
class AddressBar(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._mainLayout = QtGui.QHBoxLayout(self)
self._upButton = QtGui.QToolButton(self)
self._addressEdit = QtGui.QLineEdit(self)
self.setLayout(self._mainLayout)
self.setContentsMargins(0, 0, 0, 0)
self._mainLayout.setContentsMargins(0, 0, 0, 0)
self._mainLayout.addWidget(self._upButton)
self._mainLayout.addWidget(self._addressEdit)
self._upButton.setText("up")
self.connect(self._addressEdit, QtCore.SIGNAL("returnPressed ()"), self._addressChanged)
def _addressChanged(self):
self.emit(QtCore.SIGNAL("addressBarChanged"))
def setAddress(self, address):
self._addressEdit.setText(address)
def address(self):
return str(self._addressEdit.text())
def upButton(self):
return self._upButton
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import copy
import weakref
from PyQt4 import QtGui, QtCore
from ...import coralApp
from ...observer import Observer
import nodeEditor
from nodeUiScene import NodeUiScene
from connection import Connection
from connectionHook import ConnectionHook
from attributeUi import AttributeUi
import nodeView
class NodeUi(QtGui.QGraphicsWidget):
def __init__(self, coralNode):
QtGui.QGraphicsWidget.__init__(self)
self._coralNode = weakref.ref(coralNode)
self._coralNodeId = coralNode.id()
self._spacerConstant = 5.0
self._label = QtGui.QGraphicsSimpleTextItem(self)
self._containedScene = NodeUiScene(self)
self._shapePen = QtGui.QPen(QtCore.Qt.NoPen)
self._attributeUis = []
self._brush = QtGui.QBrush(self.color())
self._selectedColor = QtGui.QColor(255, 255, 255)
self._dropShadowEffect = QtGui.QGraphicsDropShadowEffect()
self._canOpenThis = False
self._parentNodeUi = None
self._nodeUis = []
self._showingRightClickMenu = False
self._rightClickMenuItems = []
self._nameChangedObserver = Observer()
self._doubleClicked = False
self._nodeViewWatching = None
self._attributesProxyEnabled = False
self._zValue = self.zValue()
self._currentMagnifyFactor = 1.0
parentNodeUi = self._addToParentScene(coralNode)
if parentNodeUi:
self._parentNodeUi = weakref.ref(parentNodeUi)
self.setGraphicsEffect(self._dropShadowEffect)
self._dropShadowEffect.setOffset(0.0, 10.0)
self._dropShadowEffect.setBlurRadius(8.0)
self._dropShadowEffect.setColor(QtGui.QColor(0, 0, 0, 50))
self.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable)
self.setAcceptHoverEvents(True)
self._label.setBrush(self.labelsColor())
self._shapePen.setColor(self._selectedColor)
self._shapePen.setWidthF(1.5)
coralApp.addNameChangedObserver(self._nameChangedObserver, self.coralNode(), self._coralNodeNameChanged)
def _magnifyAnimStep(self, frame):
step = frame / nodeView.NodeView._animSteps
invStep = 1.0 - step
self.setScale((self.scale() * invStep) + ((1.0 * self._currentMagnifyFactor) * step))
for attr in self._attributeUis:
if attr._inputHook:
attr._inputHook.updateWorldPos()
if attr._outputHook:
attr._outputHook.updateWorldPos()
self.scene().update()
def _magnify(self, factor):
self._currentMagnifyFactor = factor
timer = QtCore.QTimeLine(nodeView.NodeView._animSpeed, self)
timer.setFrameRange(0, nodeView.NodeView._animSteps)
self.connect(timer, QtCore.SIGNAL("frameChanged(int)"), self._magnifyAnimStep);
timer.start()
def hoverEnterEvent(self, event):
if not nodeView.NodeView._panning:
if nodeView.NodeView._lastHoveredItem is not self:
if nodeView.NodeView._lastHoveredItem:
nodeView.NodeView._lastHoveredItem.hoverLeaveEvent(None)
zoom = self.scene().zoom()
if zoom < 0.6:
factor = 0.7 / zoom
self.setTransformOriginPoint(self.rect().center())
self._magnify(factor)
nodeView.NodeView._lastHoveredItem = self
self.setZValue(9999999)
def hoverLeaveEvent(self, event):
if nodeView.NodeView._lastHoveredItem is self:
self._magnify(1.0)
self.setZValue(self._zValue)
nodeView.NodeView._lastHoveredItem = None
def setAttributesProxyEnabled(self, value = True):
self._attributesProxyEnabled = value
def attributesProxyEnabled(self):
return self._attributesProxyEnabled
def buildFromCoralNode(self):
coralNode = self._coralNode()
self._label.setText(coralNode.name())
self._clearAttributeUis()
attrs = []
for attribute in coralNode.inputAttributes():
attributeUi = nodeEditor.NodeEditor._createAttributeUi(attribute, self)
self.addInputAttributeUi(attributeUi)
attrs.append(attributeUi)
for attribute in coralNode.outputAttributes():
attributeUi = nodeEditor.NodeEditor._createAttributeUi(attribute, self)
self.addOutputAttributeUi(attributeUi)
attrs.append(attributeUi)
if self._attributesProxyEnabled:
offset = 0
for attr in attrs:
proxy = attr.proxy()
proxy.setPos(0, offset)
offset += proxy.size().height() * 2
self.updateLayout()
def _clearAttributeUis(self):
for attrUi in self._attributeUis:
attrUi.setParent(None)
self._attributeUis = []
def _coralNodeNameChanged(self):
self._label.setText(self.coralNode().name())
self.updateLayout()
self.scene().update()
def updateToolTip(self):
self.setToolTip(self.toolTip())
def toolTip(self):
return self.coralNode().shortDebugInfo()
def addRightClickMenuItem(self, label, callback):
self._rightClickMenuItems.append({label: callback})
def showRightClickMenu(self):
menu = QtGui.QMenu(nodeEditor.NodeEditor.focusedInstance())
titleAction = menu.addAction(self.coralNode().name() + ":")
titleAction.setDisabled(True)
for item in self._rightClickMenuItems:
label = item.keys()[0]
callback = item.values()[0]
menu.addAction(label, callback)
cursorPos = QtGui.QCursor.pos()
menu.move(cursorPos.x(), cursorPos.y())
menu.show()
def attributeUis(self, includeHidden = False):
orderedAttributes = []
if self._canOpenThis:
inputAttributes = {}
outputAttributes = {}
for attributeUi in self._attributeUis:
if attributeUi.isVisible() or includeHidden == True:
if attributeUi.inputHook():
inputAttributes[attributeUi.coralAttribute().name()] = attributeUi
else:
outputAttributes[attributeUi.coralAttribute().name()] = attributeUi
inputKeys = inputAttributes.keys()
inputKeys.sort()
outputKeys = outputAttributes.keys()
outputKeys.sort()
for key in inputKeys:
orderedAttributes.append(inputAttributes[key])
for key in outputKeys:
orderedAttributes.append(outputAttributes[key])
else:
inputAttributes = []
outputAttributes = []
for attributeUi in self._attributeUis:
if attributeUi.isVisible() or includeHidden == True:
if attributeUi.inputHook():
inputAttributes.append(attributeUi)
else:
outputAttributes.append(attributeUi)
orderedAttributes = inputAttributes
orderedAttributes.extend(outputAttributes)
return orderedAttributes
def findAttributeUi(self, name):
attributeUi = None
for attr in self._attributeUis:
if attr.coralAttribute().name() == name:
attributeUi = attr
return attributeUi
def nodeUis(self):
return copy.copy(self._nodeUis)
def addNodeUi(self, nodeUi):
nodeUi.setParentNodeUi(self)
def removeNodeUi(self, nodeUi):
nodeUiRef = weakref.ref(nodeUi)
if nodeUiRef in self._nodeUis:
nodeUiRef().setParentNodeUi(None)
def setParentNodeUi(self, nodeUi):
if self.scene():
self.scene().removeItem(self)
if self._parentNodeUi:
parentNodeUi = self._parentNodeUi()
if self in parentNodeUi._nodeUis:
del parentNodeUi._nodeUis[parentNodeUi._nodeUis.index(self)]
if nodeUi:
self._parentNodeUi = weakref.ref(nodeUi)
if self not in nodeUi.containedScene().items():
nodeUi.containedScene().addItem(self)
if self not in nodeUi._nodeUis:
nodeUi._nodeUis.append(self)
else:
self._parentNodeUi = None
for attr in self._attributeUis:
attr.onChangedScene(self.scene())
def shapePen(self):
return QtGui.QPen(self._shapePen)
def parentNodeUi(self):
parent = None
if self._parentNodeUi:
parent = self._parentNodeUi()
return parent
def setCanOpenThis(self, value = True):
self._canOpenThis = value
def canOpenThis(self):
return self._canOpenThis
def color(self):
return QtGui.QColor(0, 0, 0)
def labelsColor(self):
return QtGui.QColor(255, 255, 255)
def onSelected(self):
if self.isSelected():
self._shapePen.setStyle(QtCore.Qt.SolidLine)
else:
self._shapePen.setStyle(QtCore.Qt.NoPen)
def itemChange(self, change, value):
if change == QtGui.QGraphicsItem.ItemSelectedHasChanged:
self.onSelected()
return value
def _addToParentScene(self, coralNode):
parentNodeUi = None
coralNodeParent = coralNode.parent()
if coralNodeParent:
parentNodeUi = nodeEditor.NodeEditor.findNodeUi(coralNodeParent.id())
parentNodeUi.containedScene().addItem(self)
return parentNodeUi
def coralNode(self):
return self._coralNode()
def containedScene(self):
return self._containedScene
def removeAttributeUi(self, attributeUi):
if attributeUi in self._attributeUis:
del self._attributeUis[self._attributeUis.index(attributeUi)]
def addInputAttributeUi(self, attributeUi):
if attributeUi not in self._attributeUis:
self._attributeUis.append(attributeUi)
def addOutputAttributeUi(self, attributeUi):
if attributeUi not in self._attributeUis:
self._attributeUis.append(attributeUi)
def updateLayout(self):
labelWidth = self._label.boundingRect().width()
width = labelWidth
yPos = self._label.boundingRect().bottom() + self._spacerConstant
attributes = self.attributeUis()
for attributeUi in attributes:
if attributeUi.isVisible():
attributeUi.updateLayout()
attributeUi.setPos(self._spacerConstant, yPos)
yPos += attributeUi.boundingRect().height()
attributeWidth = attributeUi.boundingRect().width()
if attributeWidth > width:
width = attributeWidth
for attributeUi in self._attributeUis:
if attributeUi.isVisible():
outHook = attributeUi.outputHook()
if outHook:
outHook.setPos(width - outHook.boundingRect().width(), outHook.pos().y())
width = self._spacerConstant + width + self._spacerConstant
self._label.setPos((width - labelWidth) / 2.0, self._spacerConstant)
self.resize(width, yPos + self._spacerConstant)
self.update()
def paint(self, painter, option, widget):
shape = QtGui.QPainterPath()
shape.addRoundedRect(self.rect(), 2, 2)
painter.setPen(self._shapePen)
painter.setBrush(self._brush)
painter.drawPath(shape)
def deleteIt(self):
if self.isSelected():
nodeEditor.NodeEditor._setSelectedNodes([])
if self._nodeViewWatching:
parentNodeUi = self.parentNodeUi()
if parentNodeUi:
self._nodeViewWatching().setCurrentNodeUi(parentNodeUi)
attrs = copy.copy(self._attributeUis)
for attr in attrs:
attr.deleteIt()
nodes = copy.copy(self._nodeUis)
for node in nodes:
node.deleteIt()
self.setParentNodeUi(None)
if nodeEditor.NodeEditor._nodeUis.has_key(self._coralNodeId):
del nodeEditor.NodeEditor._nodeUis[self._coralNodeId]
def _openThis(self):
if self._canOpenThis:
focusedNodeEditor = nodeEditor.NodeEditor.focusedInstance()
nodeView = focusedNodeEditor.nodeView()
if nodeView:
nodeView.setCurrentNodeUi(self)
self._nodeViewWatching = weakref.ref(nodeView)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.RightButton:
pass
else:
QtGui.QGraphicsWidget.mousePressEvent(self, event)
def mouseReleaseEvent(self, event):
if self._doubleClicked:
self._doubleClicked = False
self._openThis()
elif event.button() == QtCore.Qt.RightButton:
self.showRightClickMenu()
else:
QtGui.QGraphicsWidget.mouseReleaseEvent(self, event)
def mouseMoveEvent(self, event):
if self._doubleClicked:
return
else:
QtGui.QGraphicsWidget.mouseMoveEvent(self, event)
def mouseDoubleClickEvent(self, event):
self._doubleClicked = True
# returns the data of this node in a dictionary of primitive data types.
def data(self):
data = {"pos": [self.pos().x(), self.pos().y()]}
if self._attributesProxyEnabled:
attributes = []
for attrUi in self.attributeUis():
attributes.append(attrUi.proxy().data())
data["attributes"] = attributes
return data
# takes care of setting the internal data of this node by reading the content of the data dictionary passed in.
def setData(self, data):
if data.has_key("pos"):
pos = data["pos"]
self.setPos(pos[0], pos[1])
if self._attributesProxyEnabled and data.has_key("attributes"):
for attrData in data["attributes"]:
attrName = attrData["name"]
attrUi = self.findAttributeUi(attrName)
if attrUi:
attrUi.proxy().setData(attrData)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
import weakref
from PyQt4 import QtGui, QtCore
from .. import coralApp
from .. import utils
from ..observer import Observer
from pluginUi import PluginUi
from nodeEditor.nodeUi import NodeUi
from nodeEditor.attributeUi import AttributeUi
from nodeEditor.connectionHook import ConnectionHook
from nodeEditor.connection import Connection
from nodeEditor.nodeEditor import NodeEditor
from nodeInspector.fields import IntValueField, FloatValueField, BoolValueField, StringValueField, ColorField
from nodeInspector.nodeInspector import NodeInspector, NodeInspectorWidget, AttributeInspectorWidget
import mainWindow
import viewport
class GeoInstanceArrayAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
return QtGui.QColor(240, 230, 250)
class GeoAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
return QtGui.QColor(200, 200, 250)
class NumericAttributeUi(AttributeUi):
typeColor = {
"Any": QtGui.QColor(255, 255, 95),
"Int": QtGui.QColor(255, 107, 109),
"Float": QtGui.QColor(5, 247, 176),
"Vec3": QtGui.QColor(0, 120, 255),
"Col4": QtGui.QColor(88, 228, 255),
"Quat": QtGui.QColor(0, 255, 0),
"Matrix44": QtGui.QColor(179, 102, 255)
}
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
color = NumericAttributeUi.typeColor["Any"]
if len(specialization) == 2:
prefix1 = specialization[0].replace("Array", "")
prefix2 = specialization[1].replace("Array", "")
if(prefix1 == prefix2):
color = NumericAttributeUi.typeColor[prefix1]
elif len(specialization) == 1:
prefix = specialization[0].replace("Array", "")
suffix = specialization[0].replace(prefix, "")
color = NumericAttributeUi.typeColor[prefix]
if suffix == "Array":
color = color.lighter(110)
return color
class NumericAttributeInspectorWidget(AttributeInspectorWidget):
def __init__(self, coralAttribute, parentWidget, sourceCoralAttributes = []):
AttributeInspectorWidget.__init__(self, coralAttribute, parentWidget)
self._valueField = None
self._attributeSpecializedObserver = Observer()
coralApp.addAttributeSpecializedObserver(self._attributeSpecializedObserver, coralAttribute, self._specialized)
self._update()
def _clear(self):
for i in range(self.layout().count()):
widget = self.layout().takeAt(0).widget()
widget.setParent(None)
del widget
def _update(self):
attr = self.coralAttribute()
numericAttribute = attr
if attr.isPassThrough():
processedAttrs = []
numericAttribute = _findFirstConnectedAtributeNonPassThrough(attr, processedAttrs)
valueField = None
if numericAttribute:
numericValue = numericAttribute.outValue()
specializationType = numericValue.type()
if specializationType == numericValue.numericTypeInt:
valueField = IntValueField(attr, self)
elif specializationType == numericValue.numericTypeFloat:
valueField = FloatValueField(attr, self)
elif specializationType == numericValue.numericTypeIntArray:
if numericAttribute.value().size() == 1:
valueField = IntValueField(attr, self)
elif specializationType == numericValue.numericTypeFloatArray:
if numericAttribute.value().size() == 1:
valueField = FloatValueField(attr, self)
elif specializationType == numericValue.numericTypeCol4:
valueField = ColorField(attr, self)
elif specializationType == numericValue.numericTypeCol4Array:
if numericAttribute.value().size() == 1:
valueField = ColorField(attr, self)
self._valueField = valueField
if valueField is None:
valueField = QtGui.QLabel(attr.name().split(":")[-1], self)
self.layout().addWidget(valueField)
def valueField(self):
return self._valueField
def _specialized(self):
self._clear()
self._update()
def _findFirstConnectedAtributeNonPassThrough(coralAttribute, processedAttributes):
foundAttr = None
if coralAttribute not in processedAttributes:
processedAttributes.append(coralAttribute)
if coralAttribute.isPassThrough() == False:
return coralAttribute
else:
if coralAttribute.input():
foundAttr = _findFirstConnectedAtributeNonPassThrough(coralAttribute.input(), processedAttributes)
if foundAttr:
return foundAttr
for out in coralAttribute.outputs():
foundAttr = _findFirstConnectedAtributeNonPassThrough(out, processedAttributes)
if foundAttr:
return foundAttr
return foundAttr
class EnumAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
self.setVisible(False)
class EnumAttributeInspectorWidget(AttributeInspectorWidget):
def __init__(self, coralAttribute, parentWidget):
AttributeInspectorWidget.__init__(self, coralAttribute, parentWidget)
self._combo = QtGui.QComboBox(self)
self._label = QtGui.QLabel(coralAttribute.name() + " ", self)
self._hlayout = QtGui.QHBoxLayout()
self._hlayout.addWidget(self._label)
self._hlayout.addWidget(self._combo)
self.layout().addLayout(self._hlayout)
coralEnum = coralAttribute.value()
indices = coralEnum.indices()
i = 0
for entry in coralEnum.entries():
self._combo.insertItem(indices[i], entry)
i += 1
self._combo.setCurrentIndex(coralEnum.currentIndex())
self.connect(self._combo, QtCore.SIGNAL("currentIndexChanged(int)"), self._comboChanged)
def _comboChanged(self, index):
self.coralAttribute().outValue().setCurrentIndex(index)
self.coralAttribute().valueChanged()
class BoolAttributeInspectorWidget(AttributeInspectorWidget):
def __init__(self, coralAttribute, parentWidget):
AttributeInspectorWidget.__init__(self, coralAttribute, parentWidget)
if coralAttribute.value().size() == 1:
valueField = BoolValueField(coralAttribute, self)
self.layout().addWidget(valueField)
else:
label = QtGui.QLabel(coralAttribute.name(), self)
self.layout().addWidget(label)
class StringAttributeInspectorWidget(AttributeInspectorWidget):
def __init__(self, coralAttribute, parentWidget):
AttributeInspectorWidget.__init__(self, coralAttribute, parentWidget)
valueField = StringValueField(coralAttribute, self)
self.layout().addWidget(valueField)
class ProcessSimulationNodeInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
def build(self):
NodeInspectorWidget.build(self)
addAttrButton = QtGui.QPushButton("Add Input Data", self)
self.layout().addWidget(addAttrButton)
self.connect(addAttrButton, QtCore.SIGNAL("clicked()"), self._addInputClicked)
def _addInputClicked(self):
node = self.coralNode()
node.addInputData()
self.nodeInspector().refresh()
class AttributeSpecializationComboBox(QtGui.QComboBox):
def __init__(self, coralAttribute, parent):
QtGui.QComboBox.__init__(self, parent)
self._coralAttribute = weakref.ref(coralAttribute)
self._showPopupCallback = None
self._currentItemChangedCallback = None
self._currentItemChangedCallbackEnabled = True
self.connect(self, QtCore.SIGNAL("currentIndexChanged(QString)"), self._currentItemChanged)
def coralAttribute(self):
return self._coralAttribute()
def setShowPopupCallback(self, callback):
self._showPopupCallback = utils.weakRef(callback)
def setCurrentItemChangedCallback(self, callback):
self._currentItemChangedCallback = utils.weakRef(callback)
def _currentItemChanged(self, itemText):
if self._currentItemChangedCallbackEnabled:
if self._currentItemChangedCallback:
self._currentItemChangedCallback(self)
def showPopup(self):
self._currentItemChangedCallbackEnabled = False
if self._showPopupCallback:
self._showPopupCallback(self)
QtGui.QComboBox.showPopup(self)
self._currentItemChangedCallbackEnabled = True
class GeoInstanceGeneratorInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
def build(self):
NodeInspectorWidget.build(self)
addGeoButton = QtGui.QPushButton("add input geo", self)
self.layout().addWidget(addGeoButton)
self.connect(addGeoButton, QtCore.SIGNAL("clicked()"), self._addGeoButtonClicked)
def _addGeoButtonClicked(self):
node = self.coralNode()
node.addInputGeo();
self.nodeInspector().refresh()
class BuildArrayInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
def build(self):
NodeInspectorWidget.build(self)
addAttrButton = QtGui.QPushButton("Add Input", self)
self.layout().addWidget(addAttrButton)
self.connect(addAttrButton, QtCore.SIGNAL("clicked()"), self._addInputClicked)
def _addInputClicked(self):
node = self.coralNode()
node.addNumericAttribute()
self.nodeInspector().refresh()
class TimeNodeInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
self._playButton = None
def build(self):
NodeInspectorWidget.build(self)
self._playButton = QtGui.QToolButton(self)
self._playButton.setText("Play")
self._playButton.setCheckable(True)
self._playButton.setChecked(self.coralNode().isPlaying())
self.layout().addWidget(self._playButton)
self.connect(self._playButton, QtCore.SIGNAL("toggled(bool)"), self._playButtonToggled)
def _playButtonToggled(self, play):
if play:
viewport.ViewportWidget._activateTimedRefresh()
self.coralNode().play(True)
else:
self.coralNode().play(False)
viewport.ViewportWidget._activateImmediateRefresh()
class PassThroughAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
color = QtGui.QColor(100, 100, 100)
processedAttributes = []
connectedAttribute = _findFirstConnectedAtributeNonPassThrough(self.coralAttribute(), processedAttributes)
if connectedAttribute:
connectedAttributeUi = NodeEditor.findAttributeUi(connectedAttribute.id())
if connectedAttributeUi:
color = connectedAttributeUi.hooksColor(self.coralAttribute().specialization())
return color
class StringAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
return QtGui.QColor(204, 255, 102)
class BoolAttributeUi(AttributeUi):
def __init__(self, coralAttribute, parentNodeUi):
AttributeUi.__init__(self, coralAttribute, parentNodeUi)
def hooksColor(self, specialization):
color = QtGui.QColor(255, 160, 130)
if len(specialization) == 1:
if specialization[0].endswith("Array"):
color.lighter(140)
return color
class ForLoopNodeUi(NodeUi):
def __init__(self, coralNode):
NodeUi.__init__(self, coralNode)
self.setCanOpenThis(True)
self.setAttributesProxyEnabled(True)
def color(self):
return QtGui.QColor(245, 181, 118)
class CollapsedNodeUi(NodeUi):
def __init__(self, coralNode):
NodeUi.__init__(self, coralNode)
self.setCanOpenThis(True)
self.setAttributesProxyEnabled(True)
self.addRightClickMenuItem("include selected nodes", self._includeSelectedNodes)
def toolTip(self):
tooltip = NodeUi.toolTip(self) + "\n\n"
tooltip += "(double click to open)"
return tooltip
def _includeSelectedNodes(self):
coralApp.collapseNodes(NodeEditor.selectedNodes(), collapsedNode = self.coralNode())
def color(self):
return QtGui.QColor(0, 204, 255)
def repositionAmongConnectedNodes(self):
fixedDistance = QtCore.QPointF(self.boundingRect().width() * 2.0, 0.0)
nNodes = 0
pos = QtCore.QPointF(0.0, 0.0)
for attrUi in self.attributeUis():
if attrUi.outputHook():
for conn in attrUi.outputHook().connections():
pos += conn.endHook().scenePos() - fixedDistance
nNodes += 1
elif attrUi.inputHook():
if attrUi.inputHook().connections():
pos += attrUi.inputHook().connections()[0].startHook().scenePos() + fixedDistance
nNodes += 1
if nNodes:
pos /= nNodes
finalPos = pos - self.boundingRect().center()
self.setPos(finalPos)
def repositionContainedProxys(self):
for attrUi in self.attributeUis():
proxyAttr = attrUi.proxy()
if proxyAttr.pos() == QtCore.QPointF(0.0, 0.0):
if proxyAttr.outputHook():
positions = []
for conn in proxyAttr.outputHook().connections():
positions.append(conn.endHook().scenePos())
averagePos = QtCore.QPointF(0.0, 0.0)
for pos in positions:
averagePos += pos
nPositions = len(positions)
if nPositions:
averagePos /= nPositions
averagePos.setX(averagePos.x() - (proxyAttr.boundingRect().width() * 2.0))
finalPos = averagePos - (proxyAttr.outputHook().scenePos() - proxyAttr.scenePos())
proxyAttr.setPos(proxyAttr.mapFromScene(finalPos))
elif proxyAttr.inputHook():
connections = proxyAttr.inputHook().connections()
if connections:
hookPos = connections[0].startHook().scenePos()
hookPos.setX(hookPos.x() + proxyAttr.boundingRect().width() * 2.0)
finalPos = hookPos - (proxyAttr.inputHook().scenePos() - proxyAttr.scenePos())
proxyAttr.setPos(finalPos)
class ShaderNodeInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
self._log = None
self._logTimer = None
def _compileShaderButtonClicked(self):
node = self.coralNode()
node.recompileShader()
self.nodeInspector().refresh()
def build(self):
NodeInspectorWidget.build(self)
layout = self.layout()
compileShaderButton = QtGui.QPushButton("compile shader", self)
layout.addWidget(compileShaderButton)
self.connect(compileShaderButton, QtCore.SIGNAL("clicked()"), self._compileShaderButtonClicked)
self._log = QtGui.QTextEdit(self)
layout.addWidget(self._log)
layout.setAlignment(self._log, QtCore.Qt.AlignTop)
self._log.setMaximumHeight(100)
self._log.setReadOnly(True)
self._log.setLineWrapMode(QtGui.QTextEdit.NoWrap)
palette = self._log.palette()
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(50, 55, 60))
self._log.setPalette(palette)
self._log.setTextColor(QtGui.QColor(200, 190, 200))
if self._logTimer is not None:
self.killTimer(self._logTimer)
self._logTimer = self.startTimer(500)
def timerEvent(self, event):
self._log.setText(self.coralNode().recompileShaderLog())
def loadPluginUi():
plugin = PluginUi("builtinUis")
plugin.registerAttributeUi("GeoInstanceArrayAttribute", GeoInstanceArrayAttributeUi)
plugin.registerAttributeUi("GeoAttribute", GeoAttributeUi)
plugin.registerAttributeUi("NumericAttribute", NumericAttributeUi)
plugin.registerAttributeUi("PassThroughAttribute", PassThroughAttributeUi)
plugin.registerAttributeUi("GeoAttribute", GeoAttributeUi)
plugin.registerAttributeUi("StringAttribute", StringAttributeUi)
plugin.registerAttributeUi("BoolAttribute", BoolAttributeUi)
plugin.registerAttributeUi("EnumAttribute", EnumAttributeUi)
plugin.registerNodeUi("CollapsedNode", CollapsedNodeUi)
plugin.registerNodeUi("ForLoop", ForLoopNodeUi)
plugin.registerInspectorWidget("NumericAttribute", NumericAttributeInspectorWidget)
plugin.registerInspectorWidget("StringAttribute", StringAttributeInspectorWidget)
plugin.registerInspectorWidget("BoolAttribute", BoolAttributeInspectorWidget)
plugin.registerInspectorWidget("BuildArray", BuildArrayInspectorWidget)
plugin.registerInspectorWidget("Time", TimeNodeInspectorWidget)
plugin.registerInspectorWidget("EnumAttribute", EnumAttributeInspectorWidget)
plugin.registerInspectorWidget("ProcessSimulation", ProcessSimulationNodeInspectorWidget)
plugin.registerInspectorWidget("GeoInstanceGenerator", GeoInstanceGeneratorInspectorWidget)
plugin.registerInspectorWidget("Shader", ShaderNodeInspectorWidget)
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from coral import Node, NumericAttribute
from coral.plugin import Plugin
import viewport
class ViewportCameraNode(Node):
def __init__(self, name, parent):
Node.__init__(self, name, parent)
self.setClassName("ViewportCamera")
self._modelMatrix = NumericAttribute("modelMatrix", self)
self._fov = NumericAttribute("fov", self)
self._zNear = NumericAttribute("zNear", self)
self._zFar = NumericAttribute("zFar", self)
self.addOutputAttribute(self._modelMatrix)
self.addOutputAttribute(self._fov)
self.addOutputAttribute(self._zNear)
self.addOutputAttribute(self._zFar)
self._setAttributeAllowedSpecializations(self._modelMatrix, ["Matrix44"])
self._setAttributeAllowedSpecializations(self._fov, ["Float"])
self._setAttributeAllowedSpecializations(self._zNear, ["Float"])
self._setAttributeAllowedSpecializations(self._zFar, ["Float"])
viewport.addCameraNode(self)
self._extractViewportInfo()
def __del__(self):
viewport.removeCameraNode(self)
def cameraChanged(self):
# called by viewport.py
# here we have to dirty each camera related attribute in order to cause an update
self._extractViewportInfo()
self._modelMatrix.valueChanged()
self._fov.valueChanged()
self._zNear.valueChanged()
self._zFar.valueChanged()
def _extractViewportInfo(self):
viewports = viewport.instancedViewports()
if viewports:
vport = viewports[0]
modelMatrix = vport.modelMatrix()
self._modelMatrix.outValue().setMatrix44ValueAt(0, modelMatrix)
fov = vport.fov()
self._fov.outValue().setFloatValueAt(0, fov)
zNear = vport.zNear()
self._zNear.outValue().setFloatValueAt(0, zNear)
zFar = vport.zFar()
self._zFar.outValue().setFloatValueAt(0, zFar) | Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from PyQt4 import QtGui, QtCore
import mainWindow
class DockWidget(QtGui.QDockWidget):
def __init__(self, contentWidget, parent):
QtGui.QDockWidget.__init__(self, contentWidget.windowTitle(), parent)
contentWidget.setParent(parent)
self.setWidget(contentWidget)
self.setAcceptDrops(True)
self._restoreSettings()
def _restoreSettings(self):
mainWin = mainWindow.MainWindow.globalInstance()
geometry = str(mainWin.settings().value(self.windowTitle() + "_geometry").toString())
if geometry:
geometry = eval(geometry)
self.move(geometry[0], geometry[1])
self.resize(geometry[2], geometry[3])
def _storeSettings(self):
mainWin = mainWindow.MainWindow.globalInstance()
mainWin.settings().setValue(self.windowTitle() + "_geometry", str([self.pos().x(), self.pos().y(), self.size().width(), self.size().height()]))
def closeEvent(self, event):
self._storeSettings()
if self.widget():
self.widget().close()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
import os
import traceback
from PyQt4 import QtGui, QtCore
from .. import coralApp
from .. import utils
from mainWindow import MainWindow
class DropData(object):
def __init__(self, data = None, type = ""):
self._data = data
self._type = type
def data(self):
MainWindow.globalInstance().emit(QtCore.SIGNAL("coralDataDropped"))
return self._data
def type(self):
return self._type
class CoralUiData:
app = None
lastNetworkFileDir = ""
configModule = None
dropData = DropData()
clipboardData = {}
def init(configModule = None):
from nodeEditor.nodeEditor import NodeEditor
coralApp.init()
CoralUiData.app = QtCore.QCoreApplication.instance()
if CoralUiData.app is None:
CoralUiData.app = QtGui.QApplication(sys.argv)
else:
coralApp.logInfo("using existing QApplication")
MainWindow._init()
NodeEditor._init()
import builtinUis
loadPluginUiModule(builtinUis)
import builtinDrawNodes
coralApp.loadPluginModule(builtinDrawNodes)
if configModule:
configModule.apply()
if os.environ.has_key("CORAL_STARTUP_SCRIPT"):
startupScriptFile = os.environ["CORAL_STARTUP_SCRIPT"]
if startupScriptFile:
utils.runtimeImport(startupScriptFile)
def scanPathForPlugins(path):
verbLev = coralApp.verboseLevel()
coralApp.setVerboseLevel(0)
entries = os.listdir(path)
for entry in entries:
if entry.split(".")[-1] == "py":
filename = os.path.join(path, entry)
loadPluginUi(filename)
coralApp.setVerboseLevel(verbLev)
def scanAutoLoadPaths():
for path in coralApp.CoralAppData.autoLoadPaths:
scanPathForPlugins(path)
def application():
return CoralUiData.app
def startApp():
return CoralUiData.app.exec_()
def mainWindow():
return MainWindow.globalInstance()
# Sets arbitrary data that can be retrieved later using dropData().
# This global data is usefull for simplified drag & drop data retrieving.
def setDropData(data, type):
CoralUiData.dropData = DropData(data, type)
# Returns the data set with setDropData(),
# once the data is returned, the global data stored is erased.
def dropData():
data = CoralUiData.dropData
CoralUiData.dropData = DropData()
return data.data()
def dropDataType():
return CoralUiData.dropData.type()
def loadPluginUiModule(pluginUiModule):
from nodeEditor.nodeEditor import NodeEditor
from nodeInspector.nodeInspector import NodeInspector
pluginUi = pluginUiModule.loadPluginUi()
for attributeClassName in pluginUi._registeredAttributeUis.keys():
NodeEditor.registerAttributeUiClass(attributeClassName, pluginUi._registeredAttributeUis[attributeClassName])
for nodeClassName in pluginUi._registeredNodeUis.keys():
NodeEditor.registerNodeUiClass(nodeClassName, pluginUi._registeredNodeUis[nodeClassName])
for nestedObjectClassName in pluginUi._registeredInspectorWidgets.keys():
NodeInspector.registerInspectorWidget(nestedObjectClassName, pluginUi._registeredInspectorWidgets[nestedObjectClassName])
def loadPluginUi(filename):
searchPaths = ["", os.getcwd()]
found = False
for searchPath in searchPaths:
path = os.path.join(searchPath, filename)
if os.path.isfile(path):
found = True
module = None
try:
module = utils.runtimeImport(filename)
except:
coralApp.logError("skipping pluginUi " + str(filename))
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, limit = 2, file = sys.stdout)
if module:
if hasattr(module, "loadPluginUi"):
found = True
loadPluginUiModule(module)
else:
coralApp.logError("no loadPluginUi function found in file " + str(filename))
break
if not found:
coralApp.logError("could not find file " + str(filename))
def copyToClipboard(data):
CoralUiData.clipboardData = data
def clipboardData():
return CoralUiData.clipboardData
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
from PyQt4 import QtGui, QtCore
from mainWindow import MainWindow
class ConsoleOut(object):
def __init__(self, textEdit, out, color):
self._textEdit = textEdit
self._out = out
self._color = color
def write(self, stream):
self._textEdit.moveCursor(QtGui.QTextCursor.End)
self._textEdit.setTextColor(self._color)
self._textEdit.insertPlainText(stream)
self._out.write(stream)
class ScriptEditorBar(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self._executeButton = QtGui.QToolButton(self)
self.setLayout(QtGui.QHBoxLayout(self))
self.layout().setContentsMargins(0, 0, 0, 0)
self.layout().setAlignment(QtCore.Qt.AlignLeft)
self.layout().addWidget(self._executeButton)
self._executeButton.setText("execute script")
def executeButton(self):
return self._executeButton
class ScriptEditor(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self._consoleTextEdit = QtGui.QTextEdit(self)
self._stdOut = ConsoleOut(self._consoleTextEdit, sys.stdout, QtGui.QColor(200, 190, 200))
self._stdErr = ConsoleOut(self._consoleTextEdit, sys.stderr, QtGui.QColor(255, 92, 133))
self._bar = ScriptEditorBar(self)
self._scriptTextEdit = QtGui.QPlainTextEdit(self)
self.setWindowTitle("script editor")
self.setLayout(QtGui.QVBoxLayout(self))
self.layout().setSpacing(5)
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().addWidget(self._consoleTextEdit)
self.layout().addWidget(self._bar)
self.layout().addWidget(self._scriptTextEdit)
self._consoleTextEdit.setReadOnly(True)
self._consoleTextEdit.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self._scriptTextEdit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
palette = self._consoleTextEdit.palette()
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(50, 55, 60))
self._consoleTextEdit.setPalette(palette)
sys.stdout = self._stdOut
sys.stderr = self._stdErr
self.connect(self._bar.executeButton(), QtCore.SIGNAL("clicked()"), self._executeScript)
self._restoreSettings()
def _restoreSettings(self):
mainWin = MainWindow.globalInstance()
settings = mainWin.settings()
self._scriptTextEdit.setPlainText(settings.value("scriptEditorText").toString())
def closeEvent(self, event):
mainWin = MainWindow.globalInstance()
settings = mainWin.settings()
settings.setValue("scriptEditorText", self._scriptTextEdit.toPlainText())
def _executeScript(self):
from .. import coralApp
exec(str(self._scriptTextEdit.toPlainText()),
coralApp.__dict__ # allows for a script to run every coralApp function without the coralApp module being imported
)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from ..plugin import Plugin
def loadPlugin():
plugin = Plugin("builtinDrawNodes")
import _coralUi
import viewportCameraNode
plugin.registerNode("DrawGeo", _coralUi.GeoDrawNode, tags = ["draw"])
plugin.registerNode("DrawPoint", _coralUi.DrawPointNode, tags = ["draw"])
plugin.registerNode("DrawLine", _coralUi.DrawLineNode, tags = ["draw"])
plugin.registerNode("DrawMatrix", _coralUi.DrawMatrixNode, tags = ["draw"])
plugin.registerNode("DrawGeoInstance", _coralUi.DrawGeoInstance, tags = ["draw"])
plugin.registerNode("ViewportCamera", viewportCameraNode.ViewportCameraNode, tags = ["render"], description = "A node to extract informations from the viewport camera.")
plugin.registerNode("Shader", _coralUi.ShaderNode, tags = ["draw"])
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from _coralUi import *
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import math
import weakref
import os
from PyQt4 import QtGui, QtCore
from .. import coralApp
from ..observer import Observer
import dockWidget
class InfoBox(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
layout = QtGui.QVBoxLayout(self)
self.setLayout(layout)
self._message = QtGui.QLabel("whatever")
self._animStep = 0.0
self._animMaxFrame = 5000.0
self._animStopFrame = 50.0
self._color = QtGui.QColor(0, 0, 0, 100)
layout.setContentsMargins(2, 2, 2, 2)
layout.addWidget(self._message)
palette = self._message.palette()
palette.setColor(self._message.foregroundRole(), QtGui.QColor(200, 190, 200))
self._message.setPalette(palette)
self.resize(0, 0)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
shape = QtGui.QPainterPath()
parentWidget = self.parentWidget()
shape.addRoundedRect(QtCore.QRectF(self.rect()), 2, 2)
painter.setPen(QtCore.Qt.NoPen)
painter.setBrush(self._color)
painter.drawPath(shape)
def _advanceAnimStep(self, frame):
if frame <= self._animStopFrame:
self._animStep = frame / self._animStopFrame
self.updateSize()
elif frame >= (self._animMaxFrame - self._animStopFrame):
self._animStep = (self._animMaxFrame - frame) / self._animStopFrame
self.updateSize()
def showMessage(self, message):
self._message.setText(message)
self._color = QtGui.QColor(0, 0, 0, 100)
self._startAnim()
def showError(self, message):
self._message.setText(message)
self._color = QtGui.QColor(100, 0, 20, 100)
self._startAnim()
def _startAnim(self):
if self._animStep == 0.0:
timer = QtCore.QTimeLine(self._animMaxFrame, self)
timer.setFrameRange(0, self._animMaxFrame)
self.connect(timer, QtCore.SIGNAL("frameChanged(int)"), self._advanceAnimStep);
timer.start()
def updateSize(self):
parent = self.parentWidget()
self.resize(self._message.fontMetrics().width(self._message.text()) + 4, (self._message.fontMetrics().height() + 8) * self._animStep)
self.move((parent.width() / 2) - (self.width() / 2), parent.height() - (self.height() + 6))
class MainWindow(QtGui.QMainWindow):
_globalInstance = None
_lastFileDialogDir = ""
_closedWidgets = {}
_registeredWidgets = {}
@staticmethod
def openRegisteredWidget(widgetName):
if MainWindow._registeredWidgets.has_key(widgetName):
widgetClass = MainWindow._registeredWidgets[widgetName]
MainWindow._globalInstance.dockWidget(widgetClass(MainWindow._globalInstance))
@staticmethod
def registerWidget(widgetName, widget):
MainWindow._registeredWidgets[widgetName] = widget
@staticmethod
def _init():
MainWindow._globalInstance = MainWindow()
@staticmethod
def globalInstance():
return MainWindow._globalInstance
@staticmethod
def okCancelDialog(message):
dialog = QtGui.QMessageBox(MainWindow._globalInstance)
dialog.setText(message)
dialog.addButton("No", QtGui.QMessageBox.NoRole)
dialog.addButton("Yes", QtGui.QMessageBox.YesRole)
result = dialog.exec_()
return result
@staticmethod
def saveFileDialog(title, fileType):
filename = QtGui.QFileDialog.getSaveFileName(MainWindow._globalInstance, title, MainWindow._lastFileDialogDir, fileType)
MainWindow._lastFileDialogDir = os.path.split(str(filename))[0]
return str(filename)
@staticmethod
def openFileDialog(title, fileType):
filename = QtGui.QFileDialog.getOpenFileName(MainWindow._globalInstance, title, MainWindow._lastFileDialogDir, fileType)
MainWindow._lastFileDialogDir = os.path.split(str(filename))[0]
return str(filename)
def __init__(self, parent = None):
QtGui.QMainWindow.__init__(self, parent)
self._menuBar = QtGui.QMenuBar()
self._messageLoggedObserver = Observer()
self.setWindowTitle("coral")
self.resize(900, 500)
self.setMenuBar(self._menuBar)
self.setDockOptions(QtGui.QMainWindow.AllowTabbedDocks | QtGui.QMainWindow.AllowNestedDocks | QtGui.QMainWindow.AnimatedDocks)
self._menuBar.clear()
coralApp.addMessageLoggedObserver(self._messageLoggedObserver, self._messageLogged)
def _messageLogged(self):
message = self._messageLoggedObserver.data("message")
verboseLevel = self._messageLoggedObserver.data("verboseLevel")
if verboseLevel == coralApp.VerboseLevel.logInfos:
self._infoBox.showMessage(message)
elif verboseLevel == coralApp.VerboseLevel.logErrors:
self._infoBox.showError(message)
def about(self):
aboutBox = QtGui.QMessageBox(self)
aboutBox.setWindowTitle("About Coral")
aboutMsg = '<h2>Coral Version ' + coralApp.version() + '</h2>'
aboutMsg += '<p style="color: #333333; font-size: small;">Created by Andrea Interguglielmi</p>'
aboutMsg += '<p style="color: #333333; font-size: small;">Developed at <a href="http://code.google.com/p/coral-repo/">code.google.com/p/coral-repo</a></p>'
aboutBox.setTextFormat(QtCore.Qt.RichText)
aboutBox.setText(aboutMsg)
aboutBox.exec_()
def menuBar(self):
return self._menuBar
def dockWidget(self, widget, area = None):
dock = dockWidget.DockWidget(widget, self)
dock.setObjectName(widget.windowTitle())
dock.show()
if area is None:
dock.setFloating(True)
else:
self.addDockWidget(area, dock)
return dock
def _restoreLastOpenWindows(self, settings):
widgetsLastOpen = settings.value("openWidgets").toString()
if widgetsLastOpen:
widgetsLastOpen = eval(str(widgetsLastOpen))
openWidgetsName = []
for dockWidget in self.dockWidgets():
openWidgetsName.append(str(dockWidget.windowTitle()))
for widgetName in widgetsLastOpen:
if widgetName not in openWidgetsName:
if MainWindow._registeredWidgets.has_key(widgetName):
widgetClass = MainWindow._registeredWidgets[widgetName]
self.dockWidget(widgetClass(self))
def restoreSettings(self):
settings = self.settings()
self._restoreLastOpenWindows(settings)
geometry = str(settings.value("mainWinGeometry").toString())
if geometry:
geometry = eval(geometry)
self.move(geometry[0], geometry[1])
self.resize(geometry[2], geometry[3])
self.restoreState(settings.value("mainWinState").toByteArray())
lastFileDialogDir = settings.value("lastFileDialogDir").toString()
if lastFileDialogDir:
MainWindow._lastFileDialogDir = lastFileDialogDir
def settings(self):
return QtCore.QSettings(self.windowTitle())
def dockWidgets(self):
dockWidgets = []
for obj in self.children():
if type(obj) is dockWidget.DockWidget:
dockWidgets.append(obj)
return dockWidgets
def closeEvent(self, event):
settings = self.settings()
settings.setValue("mainWinGeometry", str([self.pos().x(), self.pos().y(), self.size().width(), self.size().height()]))
settings.setValue("mainWinState", self.saveState())
openWidgets = []
for dockWidget in self.dockWidgets():
widgetName = str(dockWidget.windowTitle())
if dockWidget.isVisible() and widgetName not in openWidgets:
openWidgets.append(widgetName)
dockWidget.closeEvent(event)
settings.setValue("openWidgets", str(openWidgets))
settings.setValue("lastFileDialogDir", MainWindow._lastFileDialogDir)
settings.setValue("settingsStored", True)
QtGui.QMainWindow.closeEvent(self, event)
def setShortcutsMap(self, shortcuts):
for key, function in shortcuts.iteritems():
QtGui.QShortcut(QtGui.QKeySequence(key), self, function)
def setCentralWidget(self, widget):
QtGui.QMainWindow.setCentralWidget(self, widget)
self._infoBox = InfoBox(widget)
def resizeEvent(self, event):
self._infoBox.updateSize() | Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
from PyQt4 import QtGui, QtCore
from nodeEditor import nodeEditor
from ..observer import Observer
from .. import coralApp
from .. import _coral
class NodeDebugInfo(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self.setLayout(QtGui.QVBoxLayout(self))
self._textEdit = QtGui.QPlainTextEdit(self)
self._selectedNodesChangedObserver = Observer()
self._selectedNode = None
self.layout().addWidget(self._textEdit)
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().setSpacing(5)
self._textEdit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
self._textEdit.setReadOnly(True)
nodeEditor.NodeEditor.addSelectedNodesChangedObserver(self._selectedNodesChangedObserver, self._selectionChanged)
self._selectionChanged()
def _selectionChanged(self):
self._selectedNode = None
nodes = nodeEditor.NodeEditor.selectedNodes()
if nodes:
self._selectedNode = weakref.ref(nodes[0])
self.update()
def update(self):
text = "# node debug info\n\n"
if self._selectedNode:
selectedNode = self._selectedNode()
if selectedNode:
text += selectedNode.debugInfo()
self._textEdit.setPlainText(text)
class ProfiledAttribute(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self._attributeLabel = QtGui.QLabel("attribute:", self)
self._lineEdit = QtGui.QLineEdit(self)
self.setLayout(QtGui.QHBoxLayout(self))
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().setSpacing(5)
self.layout().addWidget(self._attributeLabel)
self.layout().addWidget(self._lineEdit)
class Profiler(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self._profiledAttribute = ProfiledAttribute(self)
self._table = QtGui.QTableWidget(self)
self._timer = QtCore.QTimer(self)
self.setLayout(QtGui.QVBoxLayout(self))
self.layout().setContentsMargins(5, 5, 5, 5)
self.layout().setSpacing(5)
self._table.setColumnCount(2)
self._table.setHorizontalHeaderLabels(["Node", "Time"])
self._table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
self.layout().addWidget(self._profiledAttribute)
self.layout().addWidget(self._table)
self.connect(self._profiledAttribute._lineEdit, QtCore.SIGNAL("editingFinished()"), self.update)
self.connect(self._timer, QtCore.SIGNAL("timeout()"), self._time)
self._timer.setInterval(1000)
self._timer.setSingleShot(False)
self._timer.start()
def _time(self):
self.update()
def _collectNodes(self, attribute, nodes):
if attribute.isOutput():
parentNode = attribute.parent()
if parentNode and parentNode not in nodes:
nodes.append(parentNode)
inputAttr = attribute.input()
if inputAttr:
self._collectNodes(inputAttr, nodes)
for attr in attribute.affectedBy():
self._collectNodes(attr, nodes)
def update(self):
profiledAttr = str(self._profiledAttribute._lineEdit.text())
attr = None
if profiledAttr:
attr = coralApp.findAttribute(profiledAttr)
if attr:
nodes = []
self._collectNodes(attr, nodes)
profiledNodes = {}
for node in nodes:
computeTicks = node.computeTimeTicks()
if computeTicks not in profiledNodes.keys():
profiledNodes[computeTicks] = []
profiledNodes[computeTicks].append(node)
ticks = profiledNodes.keys()
self._table.setRowCount(len(ticks))
ticks.sort()
ticks.reverse()
row = 0
for tick in ticks:
nodes = profiledNodes[tick]
for node in nodes:
cell1 = QtGui.QTableWidgetItem(node.fullName())
computeTime = "secs:" + str(node.computeTimeSeconds()) + " millisecs:" + str(node.computeTimeMilliseconds())
cell2 = QtGui.QTableWidgetItem(computeTime)
self._table.setItem(row, 0, cell1)
self._table.setItem(row, 1, cell2)
row += 1
if attr is None:
self._table.setRowCount(1)
self._table.setItem(0, 0, QtGui.QTableWidgetItem("no attribute to profile"))
self._table.setItem(0, 1, QtGui.QTableWidgetItem("-- : --"))
class VisualDebugger(QtGui.QWidget):
def __init__(self, parent):
QtGui.QWidget.__init__(self)
self.setLayout(QtGui.QVBoxLayout(self))
self._tabWidget = QtGui.QTabWidget(self)
self.layout().addWidget(self._tabWidget)
self._nodeDebugInfo = NodeDebugInfo(self)
self._profiler = Profiler(self)
self._tabWidget.addTab(self._nodeDebugInfo, "Node Debug Info")
self._tabWidget.addTab(self._profiler, "Profiler")
def sizeHint(self):
return QtCore.QSize(250, 300)
def closeEvent(self, event):
self._profiler._timer.stop()
self._nodeDebugInfo._selectedNodesChangedObserver = Observer()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
class PluginUi(object):
def __init__(self, name):
self._name = name
self._registeredAttributeUis = {}
self._registeredNodeUis = {}
self._registeredInspectorWidgets = {}
def registerAttributeUi(self, attributeClassName, attributeUiClass):
self._registeredAttributeUis[attributeClassName] = attributeUiClass
def registerNodeUi(self, nodeClassName, nodeUiClass):
self._registeredNodeUis[nodeClassName] = nodeUiClass
def registerInspectorWidget(self, nestedObjectClassName, inspectorWidgetClass):
self._registeredInspectorWidgets[nestedObjectClassName] = inspectorWidgetClass
| Python |
import sys
import os
import platform
import sconsUtils
os.environ["CORAL_BUILD_FLAVOUR"] = "coralMaya"
msvc_version = ""
if os.environ.has_key("MSVC_VERSION"):
msvc_version = os.environ["MSVC_VERSION"]
sconsUtils.importBuildEnvs()
coralPath = os.path.join(os.pardir, "coral")
coralLib = None
try:
Import("coralLib")
except:
coralLib = SConscript(os.path.join(coralPath, "SConstruct"))
if sys.platform.startswith("win"):
coralLib = coralLib[1]
env = Environment(
CPPPATH = [
os.path.join(os.pardir),
sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_MAYA_INCLUDES_PATH")],
LIBS = [
coralLib,
"Imath",
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB"),
"Foundation", "OpenMaya", "OpenMayaAnim", "OpenMayaUI"],
LIBPATH = [
coralPath,
sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_MAYA_LIBS_PATH")],
SHLIBPREFIX = "",
MSVC_VERSION=msvc_version,
TARGET_ARCH = platform.machine())
if sys.platform.startswith("linux"):
env.Append(CCFLAGS = "-m64 -D_BOOL -DLINUX -DREQUIRE_IOSTREAM -O3")
elif sys.platform == "darwin":
env.Append(CCFLAGS = "-DOSMac_ -DOSMacOSX_ -m64 -D_BOOL -DREQUIRE_IOSTREAM -O3")
env["SHLIBSUFFIX"] = ".so"
elif sys.platform.startswith("win"):
env["SHLIBSUFFIX"] = ".pyd"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /DGLUT_BUILDING_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t /MP")
env["LINKFLAGS"] = Split("/MANIFEST:NO /INCREMENTAL:NO OpenGL32.lib glu32.lib")
env["CCFLAGS"] = Split("-DCORAL_MAYA_COMPILE -DNT_PLUGIN -DREQUIRE_IOSTREAM")
env.Append(CPPPATH = sconsUtils.getEnvVar("CORAL_OPENGL_INCLUDES_PATH"))
env.Append(LIBS = sconsUtils.getEnvVar("CORAL_OPENGL_LIB"))
env.Append(LIBPATH = sconsUtils.getEnvVar("CORAL_OPENGL_LIBS_PATH"))
target = env.SharedLibrary(
target = "_coralMaya",
source = sconsUtils.findFiles("src", pattern = "*.cpp"),
OBJPREFIX = os.path.join("debugCoralMaya", ""))
Return("target")
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import os
from coral import coralApp
from coral.coralUi import coralUi
from maya import cmds, OpenMaya
class FiberMayaAppData:
_initialized = False
_associateCoralNetworkNode = ""
_coralDrawNode = ""
def _saveFiberNetwork(coralNetworkNode):
coralNodeId = cmds.getAttr(coralNetworkNode + ".coralNodeId")
coralNode = coralApp.findObjectById(coralNodeId) # should return a MayaContextNode
saveScript = coralApp._generateNetworkScript(coralNode, saveTopNode = True)
cmds.setAttr(coralNetworkNode + ".saveData", saveScript, type = "string")
def _mayaSavingScene(arg):
mayaNodes = cmds.ls(type = "coralNetworkNode")
for mayaNode in mayaNodes:
_saveFiberNetwork(mayaNode)
def _loadFiberNetwork(coralNetworkNode):
saveScript = cmds.getAttr(coralNetworkNode + ".saveData")
FiberMayaAppData._associateCoralNetworkNode = coralNetworkNode # the MayaContextNode created by the current saveScript wil catch this global variable and use it
coralApp._loadNetworkScript(saveScript, topNode = "root")
FiberMayaAppData._associateCoralNetworkNode = ""
def _mayaOpenedScene(arg):
mayaNodes = cmds.ls(type = "coralNetworkNode")
for mayaNode in mayaNodes:
_loadFiberNetwork(mayaNode)
def _mayaClearScene(arg):
coralApp.newNetwork()
def _initMayaEnvironment():
OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kBeforeNew, _mayaClearScene)
OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kBeforeSave, _mayaSavingScene)
OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kAfterOpen, _mayaOpenedScene)
OpenMaya.MSceneMessage.addCallback(OpenMaya.MSceneMessage.kBeforeOpen, _mayaClearScene)
def start():
if FiberMayaAppData._initialized == False:
import coralMayaConfig
coralUi.init(configModule = coralMayaConfig)
import coralMayaPlugin
coralApp.loadPluginModule(coralMayaPlugin)
import coralMayaPluginUi
coralUi.loadPluginUiModule(coralMayaPluginUi)
mayaPluginPath = os.path.dirname(__file__)
cmds.loadPlugin(os.path.join(mayaPluginPath, "coralMayaPlugin"))
_initMayaEnvironment()
FiberMayaAppData._coralDrawNode = cmds.createNode("coralDrawNode")
coralApp.scanAutoLoadPaths()
FiberMayaAppData._initialized = True
coralUi.mainWindow().restoreSettings()
def showWindow():
coralUi.mainWindow().show()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import weakref
import coral
import coralMayaApp
from maya import cmds, OpenMaya
class NodeChangedNameCallback(object):
#fixes a problem with the scriptJob callback that doesn't pass the new name.
def __init__(self, mayaNodeName, callback):
self._instance = weakref.ref(callback.im_self)
self._callback = callback.im_func
sel = OpenMaya.MSelectionList()
sel.add(mayaNodeName)
obj = OpenMaya.MObject()
sel.getDependNode(0, obj)
self._nodeFn = OpenMaya.MFnDependencyNode(obj)
def __call__(self):
self._callback(self._instance(), self._nodeFn.name())
# The network of nodes contained in a MayaContextNode forms the algorithm processed in CoralNetworkNode::compute,
# all the CoralMayaNode found under this node wil form the input and output attributes of the CoralNetworkNode in maya.
class MayaContextNode(coral.Node):
def __init__(self, name, parent):
coral.Node.__init__(self, name, parent)
self.setClassName("MayaContext")
self._mayaNode = ""
if self.className() in parent.classNames():
self._setIsInvalid(True, self.className() + " can only be created under the root!")
return
associateCoralNetworkNode = coralMayaApp.FiberMayaAppData._associateCoralNetworkNode
if associateCoralNetworkNode: # this var is set from coralMayaApp
self._mayaNode = str(associateCoralNetworkNode)
else:
self._mayaNode = str(cmds.createNode("coralNetworkNode", name = "coralNetworkNode"))
cmds.lockNode(self._mayaNode, lock = True)
cmds.setAttr(self._mayaNode + ".coralNodeId", self.id())
cmds.scriptJob(nodeNameChanged = [self._mayaNode, NodeChangedNameCallback(self._mayaNode, self._mayaNodeChangedName)])
def deleteIt(self):
coral.Node.deleteIt(self)
if self._mayaNode:
cmds.lockNode(self._mayaNode, lock = False)
cmds.delete(self._mayaNode)
self._mayaNode = ""
def _mayaNodeChangedName(self, newName):
self._mayaNode = str(newName)
for node in self.nodes():
if "CoralMayaNode" in node.classNames():
for attr in node.attributes():
if hasattr(attr, "setMayaNode"):
attr.setMayaNode(self._mayaNode)
def mayaNode(self):
return self._mayaNode;
def addNode(self, node):
coral.Node.addNode(self, node)
if "CoralMayaNode" in node.classNames():
# we have to call updateCoralAttributeMap here because doing so in a CoralMayaNode contructor we would be wrong (the CoralMayaNode wouldn't be under its parent yet).
cmds.coralMayaCmd("updateCoralAttributeMap", self._mayaNode)
for attr in node.inputAttributes():
if hasattr(attr, "mayaAttribute"):
# this will guarantee things are up to date from the start
cmds.dgdirty(attr.mayaNode() + "." + attr.mayaAttribute())
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from maya import cmds
from coralMayaNode import CoralMayaNode
import _coralMaya
class MayaGeoInput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaGeoInput")
if self.isValid():
self._value = _coralMaya.MayaGeoAttribute("geo", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.meshAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaGeoOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaGeoOutput")
if self.isValid():
self._value = _coralMaya.MayaGeoAttribute("geo", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.meshAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from maya import cmds
import coral
# This is the base class for those nodes that intend to exchanged data with maya.
# Each one of these nodes is associated with a maya-attribute under a CoralNetworkNode.
class CoralMayaNode(coral.Node):
floatAttributeType = 1
intAttributeType = 2
meshAttributeType = 3
floatArrayAttributeType = 4
matrixAttributeType = 5
matrixArrayAttributeType = 6
angleAttributeType = 7
angle3ArrayAttributeType = 8
float3ArrayAttributeType = 9
def __init__(self, name, parent):
coral.Node.__init__(self, name, parent)
self.setClassName("CoralMayaNode")
if parent.className() != "MayaContext":
self._setIsInvalid(True, self.className() + " must be created under a MayaContextNode!")
return
def deleteIt(self):
mayaNode = self.parent().mayaNode()
cmds.lockNode(mayaNode, lock = False)
if self.isValid():
for attr in self.attributes():
if hasattr(attr, "mayaAttribute"):
cmds.deleteAttr(attr.mayaNode() + "." + attr.mayaAttribute())
cmds.coralMayaCmd("updateCoralAttributeMap", self.parent().mayaNode())
coral.Node.deleteIt(self)
cmds.lockNode(mayaNode, lock = True)
def setName(self, name):
coral.Node.setName(self, str(name))
newName = str(self.name())
mayaNode = self.parent().mayaNode()
cmds.lockNode(mayaNode, lock = False)
for attr in self.attributes():
if hasattr(attr, "setMayaAttribute"):
cmds.renameAttr(attr.mayaNode() + "." + attr.mayaAttribute(), newName)
attr.setMayaAttribute(newName)
cmds.lockNode(mayaNode, lock = True)
# this is just a utility method to create the most common maya-attribute types,
def createMayaAttribute(self, type):
mayaNode = self.parent().mayaNode()
attrName = self.name()
if cmds.listAttr(mayaNode, string = attrName) is None:
cmds.select(mayaNode, replace = True)
cmds.lockNode(mayaNode, lock = False)
if type == CoralMayaNode.floatAttributeType:
cmds.addAttr(longName = attrName, attributeType = "float", keyable = True)
elif type == CoralMayaNode.intAttributeType:
cmds.addAttr(longName = attrName, attributeType = "long", keyable = True)
elif type == CoralMayaNode.meshAttributeType:
cmds.addAttr(longName = attrName, dataType = "mesh")
elif type == CoralMayaNode.floatArrayAttributeType:
cmds.addAttr(longName = attrName, attributeType = "float", multi = True)
elif type == CoralMayaNode.matrixAttributeType:
cmds.addAttr(longName = attrName, attributeType = "matrix")
elif type == CoralMayaNode.matrixArrayAttributeType:
cmds.addAttr(longName = attrName, dataType = "matrix", multi = True)
elif type == CoralMayaNode.angleAttributeType:
cmds.addAttr(longName = attrName, attributeType = "doubleAngle", keyable = True)
elif type == CoralMayaNode.angle3ArrayAttributeType:
cmds.addAttr(longName = attrName, numberOfChildren = 3, attributeType = "compound", multi = True)
cmds.addAttr(longName = attrName + "_angleX", attributeType = "doubleAngle", parent = attrName)
cmds.addAttr(longName = attrName + "_angleY", attributeType = "doubleAngle", parent = attrName)
cmds.addAttr(longName = attrName + "_angleZ", attributeType = "doubleAngle", parent = attrName)
elif type == CoralMayaNode.float3ArrayAttributeType:
cmds.addAttr(longName = attrName, numberOfChildren = 3, attributeType = "compound", multi = True)
cmds.addAttr(longName = attrName + "_valueX", attributeType = "float", parent = attrName)
cmds.addAttr(longName = attrName + "_valueY", attributeType = "float", parent = attrName)
cmds.addAttr(longName = attrName + "_valueZ", attributeType = "float", parent = attrName)
cmds.lockNode(mayaNode, lock = True)
return attrName
# This method has to be called in the constructor of the subclass in order
# to associate a maya-attribute to a coral-attribute.
def associateMayaAttribute(self, mayaAttribute, coralAttribute):
mayaNodeName = self.parent().mayaNode()
coralAttribute.setMayaNode(mayaNodeName)
coralAttribute.setMayaAttribute(mayaAttribute)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from PyQt4 import QtGui, QtCore
from maya import cmds
from coral.coralUi.pluginUi import PluginUi
from coral.coralUi.nodeEditor.nodeUi import NodeUi
mayaColor = QtGui.QColor(154, 103, 205)
class MayaNodeUi(NodeUi):
def __init__(self, coralNode):
NodeUi.__init__(self, coralNode)
def color(self):
return mayaColor
class MayaContextNodeUi(NodeUi):
def __init__(self, coralNode):
NodeUi.__init__(self, coralNode)
self.setCanOpenThis(True)
self.addRightClickMenuItem("Select Node In Maya", self._selectNodeInMaya)
def _selectNodeInMaya(self):
cmds.select(self.coralNode().mayaNode(), replace = True)
def color(self):
return mayaColor
def loadPluginUi():
pluginUi = PluginUi("coralMayaUi")
pluginUi.registerNodeUi("MayaContext", MayaContextNodeUi)
pluginUi.registerNodeUi("CoralMayaNode", MayaNodeUi)
return pluginUi
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from maya import cmds
from coralMayaNode import CoralMayaNode
import _coralMaya
class MayaFloatInput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaFloatInput")
if self.isValid():
self._value = _coralMaya.MayaFloatAttribute("value", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.floatAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaFloatOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaFloatOutput")
if self.isValid():
self._value = _coralMaya.MayaFloatAttribute("value", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.floatAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaIntInput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaIntInput")
if self.isValid():
self._value = _coralMaya.MayaIntAttribute("value", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.intAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaIntOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaIntOutput")
if self.isValid():
self._value = _coralMaya.MayaIntAttribute("value", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.intAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaMatrixInput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaMatrixInput")
if self.isValid():
self._value = _coralMaya.MayaMatrixAttribute("value", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.matrixAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaMatrixOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaMatrixOutput")
if self.isValid():
self._value = _coralMaya.MayaMatrixAttribute("value", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.matrixAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaAngleInput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaAngleInput")
if self.isValid():
self._value = _coralMaya.MayaAngleAttribute("value", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.angleAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaAngleOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaAngleOutput")
if self.isValid():
self._value = _coralMaya.MayaAngleAttribute("value", self)
self.addOutputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.angleAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaAngle3ArrayOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaAngle3ArrayOutput")
if self.isValid():
self._value = _coralMaya.MayaAngle3ArrayAttribute("value", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.angle3ArrayAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
class MayaFloat3ArrayOutput(CoralMayaNode):
def __init__(self, name, parent):
CoralMayaNode.__init__(self, name, parent)
self.setClassName("MayaFloat3ArrayOutput")
if self.isValid():
self._value = _coralMaya.MayaFloat3ArrayAttribute("value", self)
self.addInputAttribute(self._value)
mayaAttr = self.createMayaAttribute(CoralMayaNode.float3ArrayAttributeType)
self.associateMayaAttribute(mayaAttr, self._value)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from PyQt4 import QtGui, QtCore
def _aboutClicked():
from coral.coralUi.mainWindow import MainWindow
mainWin = MainWindow.globalInstance()
mainWin.about()
def _openNodeEditorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("node editor")
def _openNodeBoxClicked():
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeBox import NodeBox
if NodeBox.globalInstance() is None:
MainWindow.openRegisteredWidget("node box")
def _openNodeInspectorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("node inspector")
def _openViewportClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("viewport")
def _openVisualDebuggerClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("visual debugger")
def _collapseClicked():
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral import coralApp
nodesName = []
for node in NodeEditor.selectedNodes():
nodesName.append(node.fullName())
if nodesName:
coralApp.executeCommand("CollapseNodes", nodes = nodesName)
def _explodeClicked():
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral import coralApp
sel = NodeEditor.selectedNodes()
if sel:
coralApp.executeCommand("ExplodeCollapsedNode", collapsedNode = sel[0].fullName())
def _clearAllClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
if MainWindow.okCancelDialog("Clear the current network?"):
coralApp.newNetwork()
def _saveNetworkClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
filename = MainWindow.saveFileDialog("save network file", "Coral Network (*.crl)")
if filename:
coralApp.saveNetworkFile(filename)
def _openNetworkClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
filename = MainWindow.openFileDialog("open network file", "Coral Network (*.crl)")
if filename:
coralApp.openNetworkFile(filename)
def _saveCollapsedNodeClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
filename = MainWindow.saveFileDialog("save collapsed node", "Coral CollapsedNode (*.py)")
sel = NodeEditor.selectedNodes()
if filename and sel:
coralApp.saveCollapsedNodeFile(sel[0], filename)
def _openScriptEditorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("script editor")
def _nodeBoxSearch():
from coral.coralUi.nodeBox import NodeBox
NodeBox.enableQuickSearch()
def apply():
#imports here to avoid cycles
from coral.coralUi import coralUi
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral.coralUi.nodeBox import NodeBox
from coral.coralUi.nodeInspector.nodeInspector import NodeInspector
from coral.coralUi.scriptEditor import ScriptEditor
from coral.coralUi.viewport import ViewportWidget
from coral.coralUi.visualDebugger import VisualDebugger
coralUi.application().setApplicationName("coralMaya")
mainWin = MainWindow.globalInstance()
mainWin.setWindowTitle("coralMaya")
nodeBox = NodeBox(mainWin)
nodeBoxDock = mainWin.dockWidget(nodeBox, QtCore.Qt.LeftDockWidgetArea)
nodeEditor = NodeEditor(mainWin)
mainWin.setCentralWidget(nodeEditor)
nodeEditor.nodeView().centerOn(0.0, 0.0)
nodeInspector = NodeInspector(mainWin)
mainWin.dockWidget(nodeInspector, QtCore.Qt.RightDockWidgetArea)
mainWin.registerWidget("node editor", NodeEditor)
mainWin.registerWidget("node box", NodeBox)
mainWin.registerWidget("node inspector", NodeInspector)
mainWin.registerWidget("viewport", ViewportWidget)
mainWin.registerWidget("script editor", ScriptEditor)
mainWin.registerWidget("visual debugger", VisualDebugger)
# menu config
fileMenu = mainWin.menuBar().addMenu("File")
fileMenu.addAction("Clear All...", _clearAllClicked)
fileMenu.addAction("Save Netwok...", _saveNetworkClicked)
fileMenu.addAction("Open Network...", _openNetworkClicked)
fileMenu.addSeparator()
fileMenu.addAction("Save CollapsedNode...", _saveCollapsedNodeClicked)
editMenu = mainWin.menuBar().addMenu("Edit")
editMenu.addAction("Collpase Nodes", _collapseClicked)
editMenu.addAction("Explode Collapsed Node", _explodeClicked)
editMenu.addSeparator()
windowMenu = mainWin.menuBar().addMenu("Window")
windowMenu.addAction("About", _aboutClicked)
windowMenu.addAction("Open Node Editor", _openNodeEditorClicked)
windowMenu.addAction("Open Node Box", _openNodeBoxClicked)
windowMenu.addAction("Open Node Inspector", _openNodeInspectorClicked)
windowMenu.addAction("Open Script Editor", _openScriptEditorClicked)
windowMenu.addAction("Open Viewport", _openViewportClicked)
windowMenu.addAction("Open Visual Debugger", _openVisualDebuggerClicked)
# shortcuts
shprtcutsMap = {
"Shift+G": _explodeClicked,
"G": _collapseClicked,
"Ctrl+S": _saveNetworkClicked,
"Ctrl+O": _openNetworkClicked,
"Ctrl+X": _clearAllClicked,
"Tab": _nodeBoxSearch}
mainWin.setShortcutsMap(shprtcutsMap)
mainWin.restoreSettings()
from coral import coralApp
coralApp.logInfo("running " + mainWin.windowTitle())
| Python |
from maya import cmds, OpenMaya, OpenMayaAnim
def exportSkeleton(topNode, filename):
fileContent = "coralIO:1.0\n"
fileContent += "type:transform\n"
joints = cmds.listRelatives(topNode, allDescendents = True, type = "joint")
fileContent += "transforms:" + str(len(joints)) + "\n"
start = cmds.playbackOptions(query = True, animationStartTime = True)
end = cmds.playbackOptions(query = True, animationEndTime = True)
fileContent += "frames:" + str(int(end - start)) + "\n"
for frame in range(start, end):
cmds.currentTime(frame)
for joint in joints:
xform = cmds.xform(joint, query = True, worldSpace = True, matrix = True)
fileContent += str(xform).strip("[]").replace(", ", ",") + "\n"
file = open(filename, "w")
file.write(fileContent)
file.close()
print "coralIO: saved file " + filename
def exportSkinWeights(topNode, skinClusterNode, filename):
fileContent = "coralIO:1.0\n"
fileContent += "type:skinWeight\n"
sel = OpenMaya.MSelectionList()
sel.add(skinClusterNode)
skinClusterObj = OpenMaya.MObject()
sel.getDependNode(0, skinClusterObj)
skinClusterFn = OpenMayaAnim.MFnSkinCluster(skinClusterObj)
skinPath = OpenMaya.MDagPath()
skinClusterFn.getPathAtIndex(0, skinPath)
influences = OpenMaya.MDagPathArray()
skinClusterFn.influenceObjects(influences)
joints = cmds.listRelatives(topNode, allDescendents = True, type = "joint", fullPath = True)
jointsMap = {}
for i in range(len(joints)):
jointsMap[joints[i]] = i
geoIt = OpenMaya.MItGeometry(skinPath)
fileContent += "vertices:" + str(geoIt.count()) + "\n"
fileContent += "deformers:" + str(influences.length()) + "\n"
for i in range(geoIt.count()):
comp = geoIt.component()
weights = OpenMaya.MFloatArray()
influenceIds = OpenMaya.MIntArray()
infCount = OpenMaya.MScriptUtil()
ccc = infCount.asUintPtr()
skinClusterFn.getWeights(skinPath, comp, weights, ccc)
for j in range(weights.length()):
weight = weights[j]
if weight > 0.0:
influenceName = influences[j].fullPathName()
jointId = jointsMap[influenceName]
fileContent += "vertex:" + str(i) + ",deformer:" + str(jointId) + ",weight:" + str(weights[j]) + "\n"
geoIt.next()
file = open(filename, "w")
file.write(fileContent)
file.close()
print "coralIO: saved file " + filename
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import os
from maya import cmds
from coral.plugin import Plugin
from mayaContextNode import MayaContextNode
import _coralMaya
import mayaNumericNodes
import mayaGeoNodes
def loadPlugin():
plugin = Plugin("coralMaya")
plugin.registerAttribute("MayaIntAttribute", _coralMaya.MayaIntAttribute)
plugin.registerAttribute("MayaFloatAttribute", _coralMaya.MayaFloatAttribute)
plugin.registerAttribute("MayaMatrixAttribute", _coralMaya.MayaMatrixAttribute)
plugin.registerAttribute("MayaGeoAttribute", _coralMaya.MayaGeoAttribute)
plugin.registerNode("MayaContext", MayaContextNode, tags = ["maya"])
plugin.registerNode("MayaFloatInput", mayaNumericNodes.MayaFloatInput, tags = ["maya"])
plugin.registerNode("MayaFloatOutput", mayaNumericNodes.MayaFloatOutput, tags = ["maya"])
plugin.registerNode("MayaIntInput", mayaNumericNodes.MayaIntInput, tags = ["maya"])
plugin.registerNode("MayaIntOutput", mayaNumericNodes.MayaIntOutput, tags = ["maya"])
plugin.registerNode("MayaMatrixInput", mayaNumericNodes.MayaMatrixInput, tags = ["maya"])
plugin.registerNode("MayaMatrixOutput", mayaNumericNodes.MayaMatrixOutput, tags = ["maya"])
plugin.registerNode("MayaAngleInput", mayaNumericNodes.MayaAngleInput, tags = ["maya"])
plugin.registerNode("MayaAngleOutput", mayaNumericNodes.MayaAngleOutput, tags = ["maya"])
plugin.registerNode("MayaAngle3ArrayOutput", mayaNumericNodes.MayaAngle3ArrayOutput, tags = ["maya"])
plugin.registerNode("MayaFloat3ArrayOutput", mayaNumericNodes.MayaFloat3ArrayOutput, tags = ["maya"])
plugin.registerNode("MayaGeoInput", mayaGeoNodes.MayaGeoInput, tags = ["maya"])
plugin.registerNode("MayaGeoOutput", mayaGeoNodes.MayaGeoOutput, tags = ["maya"])
mayaPluginPath = os.path.dirname(__file__)
cmds.loadPlugin(os.path.join(mayaPluginPath, "coralMayaPlugin"))
return plugin
| Python |
import sys
import os
import distutils
import sconsUtils
os.environ["CORAL_BUILD_FLAVOUR"] = "coralMaya"
sconsUtils.importBuildEnvs()
coralPath = os.path.join(os.pardir, os.pardir, "coral")
coralLib = None
try:
Import("coralLib")
except:
coralLib = SConscript(os.path.join(coralPath, "SConstruct"))
coralMayaPath = os.path.join(os.pardir)
coralMayaLib = None
try:
Import("coralMayaLib")
except:
coralMayaLib = SConscript(os.path.join(coralMayaPath, "SConstruct"), exports = {"coralLib": coralLib})
coralUiPath = os.path.join(os.pardir, os.pardir, "coralUi")
coralUiLib = None
try:
Import("coralUiLib")
except:
coralUiLib = SConscript(os.path.join(coralUiPath, "SConstruct"), exports = {"coralLib": coralLib})
if sys.platform.startswith("win"):
coralLib = coralLib[1]
coralMayaLib = coralMayaLib[1]
coralUiLib = coralUiLib[1]
env = Environment(
CPPPATH = [
os.path.join(os.pardir, os.pardir),
os.path.join(coralMayaPath, "src"),
sconsUtils.getEnvVar("CORAL_MAYA_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_GLEW_INCLUDES_PATH")],
LIBS = [
coralLib,
coralUiLib,
coralMayaLib,
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_GLEW_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB"),
"Foundation", "OpenMaya", "OpenMayaAnim", "OpenMayaUI"],
LIBPATH = [
coralPath,
coralUiPath,
coralMayaPath,
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_MAYA_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_GLEW_LIBS_PATH")])
targetName = "coralMayaPlugin"
if sys.platform.startswith("linux"):
env.Append(CCFLAGS = "-m64 -D_BOOL -DLINUX -DREQUIRE_IOSTREAM -O3")
env.Append(SHLIBPREFIX = "")
elif sys.platform == "darwin":
env.Append(CCFLAGS = "-DOSMac_ -DOSMacOSX_ -m64 -D_BOOL -DREQUIRE_IOSTREAM -O3")
targetName += ".bundle"
env["FRAMEWORKS"] = ["OpenGL"]
elif sys.platform.startswith("win"):
env["SHLIBPREFIX"] = ""
env["SHLIBSUFFIX"] = ".mll"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t")
env["LINKFLAGS"] = Split("/MANIFEST:NO /INCREMENTAL:NO /export:initializePlugin /export:uninitializePlugin OpenGL32.lib glu32.lib")
env["CCFLAGS"] = Split("-DWIN64 -DNDEBUG -D_WINDOWS -D_USRDLL -DNT_PLUGIN -DREQUIRE_IOSTREAM")
target = env.LoadableModule(
target = targetName,
source = sconsUtils.findFiles("src", pattern = "*.cpp"),
OBJPREFIX = os.path.join(os.pardir, "debugCoralMaya", ""))
Return("target")
| Python |
import sys
import thread
import time
from coral import Node, NumericAttribute, StringAttribute
from coral.plugin import Plugin
from coral.coralUi import mainWindow
from coralMedia import SoundManager
class SoundStreamNode(Node):
def __init__(self, name, parent):
Node.__init__(self, name, parent)
self._fileName = StringAttribute("fileName", self)
self._leftSpectrum = NumericAttribute("leftSpectrum", self)
self._rightSpectrum = NumericAttribute("rightSpectrum", self)
self._time = NumericAttribute("time", self)
self._play = False
self.addInputAttribute(self._fileName)
self.addOutputAttribute(self._time)
self.addOutputAttribute(self._leftSpectrum)
self.addOutputAttribute(self._rightSpectrum)
self._setAttributeAffect(self._fileName, self._time)
self._setAttributeAffect(self._fileName, self._leftSpectrum)
self._setAttributeAffect(self._fileName, self._rightSpectrum)
self._setAttributeAllowedSpecializations(self._time, ["Float"])
self._setAttributeAllowedSpecializations(self._leftSpectrum, ["FloatArray"])
self._setAttributeAllowedSpecializations(self._rightSpectrum, ["FloatArray"])
self._setUpdateEnabled(False)
self._leftSpectrum.outValue().resize(64)
self._rightSpectrum.outValue().resize(64)
SoundManager.init()
def isPlaying(self):
return self._play
def _advanceTime(self):
leftSpectrum = self._leftSpectrum.outValue()
rightSpectrum = self._rightSpectrum.outValue()
timeVal = self._time.outValue()
framesPerSecond = 24.0
timeStep = 1.0 / framesPerSecond
enlapsedTime = 0.0
while self._play:
enlapsedTime = enlapsedTime + timeStep
SoundManager.setSpectrumOnNumeric(leftSpectrum, 0)
SoundManager.setSpectrumOnNumeric(rightSpectrum, 1)
self._leftSpectrum.valueChanged()
self._rightSpectrum.valueChanged()
timeVal.setFloatValueAt(0, enlapsedTime)
self._time.valueChanged()
time.sleep(timeStep)
def play(self, value = True):
self._play = value
if self._play:
SoundManager.load(self._fileName.value().stringValue())
SoundManager.play()
thread.start_new_thread(self._advanceTime, ())
else:
SoundManager.stop()
self._time.outValue().setFloatValueAt(0, 0.0)
self._time.valueChanged()
def __del__(self):
self._play = False
SoundManager.terminate()
def loadPlugin():
plugin = Plugin("coralMedia")
plugin.registerNode("SoundStream", SoundStreamNode, tags = ["media"])
return plugin
| Python |
import coralBuilder
import os
print os.getcwd()
# To build this pugin you'll need the fmod library: http://www.fmod.org/index.php/download
env = coralBuilder.buildEnv()
env.Append(LIBS = "fmodex")
env.Append(CPPPATH = os.environ["CORAL_FMOD_INCLUDES"])
env.Append(LIBPATH = os.environ["CORAL_FMOD_LIBS_PATH"])
module = coralBuilder.buildModule("coralMedia", ["coralMedia.cpp"], env)
| Python |
from PyQt4 import QtGui, QtCore
from coral.coralUi.pluginUi import PluginUi
from coral.coralUi.nodeInspector.nodeInspector import NodeInspectorWidget
from coral.coralUi.nodeEditor.nodeUi import NodeUi
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi import viewport
from coral import coralApp
class SoundStreamNodeInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
self._playButton = None
def build(self):
NodeInspectorWidget.build(self)
self._playButton = QtGui.QToolButton(self)
self._playButton.setText("Play")
self._playButton.setCheckable(True)
self._playButton.setChecked(self.coralNode().isPlaying())
self.layout().addWidget(self._playButton)
self.connect(self._playButton, QtCore.SIGNAL("toggled(bool)"), self._playButtonToggled)
def _playButtonToggled(self, play):
if play:
viewport.ViewportWidget._activateTimedRefresh()
self.coralNode().play(True)
else:
self.coralNode().play(False)
viewport.ViewportWidget._activateImmediateRefresh()
def loadPluginUi():
pluginUi = PluginUi("pipelineUi")
pluginUi.registerInspectorWidget("SoundStream", SoundStreamNodeInspectorWidget)
return pluginUi
| Python |
class KernelNodeInspectorWidget(NodeInspectorWidget):
def __init__(self, coralNode, parentWidget):
NodeInspectorWidget.__init__(self, coralNode, parentWidget)
self._kernelSourceEdit = None
self._kernelBuildConsole = None
self._attrOrderWidgets = {}
self._useSizeButtons = {}
self._attrNameWidgets = {}
def _addInputClicked(self):
coralApp.createAttribute("NumericAttribute", "input", self.coralNode(), input = True)
self.nodeInspector().refresh()
def _addOutputClicked(self):
coralApp.createAttribute("NumericAttribute", "output", self.coralNode(), output = True)
self.nodeInspector().refresh()
def _popupSpecCombo(self, comboBox):
coralAttribute = comboBox.coralAttribute()
coralAttribute.removeSpecializationOverride()
coralAttribute.forceSpecializationUpdate()
attrSpecialization = coralAttribute.specialization()
comboBox.clear()
for spec in coralAttribute.specialization():
comboBox.addItem(spec)
comboBox.addItem("none")
comboBox.setCurrentIndex(len(attrSpecialization))
def _currentSpecChanged(self, comboBox):
specialization = str(comboBox.currentText())
attr = comboBox.coralAttribute()
if specialization != "" and specialization != "none":
attr.setSpecializationOverride(str(specialization));
else:
attr.removeSpecializationOverride()
attr.forceSpecializationUpdate()
def _setKernelSource(self):
if self._kernelSourceEdit:
kernelSource = str(self._kernelSourceEdit.toPlainText())
kernelSourceAttr = self.coralNode().findObject("_kernelSource")
kernelSourceAttr.value().setStringValue(kernelSource)
kernelSourceAttr.valueChanged()
self._kernelBuildConsole.setPlainText(self.coralNode().buildInfo())
def _openTextEditor(self):
mainWin = mainWindow.MainWindow.globalInstance()
dialog = QtGui.QDialog(mainWin)
dialog.setWindowTitle("kernel editor")
dialog.resize(500, 500)
vlayout = QtGui.QVBoxLayout(dialog)
vlayout.setContentsMargins(5, 5, 5, 5)
vlayout.setSpacing(5)
dialog.setLayout(vlayout)
self._kernelSourceEdit = QtGui.QPlainTextEdit(dialog)
self._kernelSourceEdit.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)
self._kernelSourceEdit.setTabStopWidth(8)
vlayout.addWidget(self._kernelSourceEdit)
compileButton = QtGui.QPushButton("compile kernel", dialog)
vlayout.addWidget(compileButton)
dialog.connect(compileButton, QtCore.SIGNAL("clicked()"), self._setKernelSource)
kernelSource = self.coralNode().findObject("_kernelSource").value().stringValue()
self._kernelSourceEdit.setPlainText(kernelSource)
self._kernelBuildConsole = QtGui.QTextEdit(dialog)
vlayout.addWidget(self._kernelBuildConsole)
self._kernelBuildConsole.setReadOnly(True)
self._kernelBuildConsole.setLineWrapMode(QtGui.QTextEdit.NoWrap)
palette = self._kernelBuildConsole.palette()
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(50, 55, 60))
self._kernelBuildConsole.setPalette(palette)
self._kernelBuildConsole.setTextColor(QtGui.QColor(200, 190, 200))
palette = self._kernelSourceEdit.palette()
palette.setColor(QtGui.QPalette.Base, QtGui.QColor(79, 87, 95))
palette.setColor(QtGui.QPalette.Text, QtGui.QColor(225, 225, 225))
self._kernelSourceEdit.setPalette(palette)
self._kernelBuildConsole.setPlainText("Kernel compiler console")
dialog.show()
def _attrOrderChanged(self, argId):
node = self.coralNode()
dynAttrs = node.dynamicAttributes()
node.clearDynamicAttributes()
orderedDynAttrs = {}
for attr in dynAttrs:
newOrder = self._attrOrderWidgets[attr.id()].value()
while newOrder in orderedDynAttrs.keys():
newOrder += 1
orderedDynAttrs[newOrder] = attr
orderIds = orderedDynAttrs.keys()
orderIds.sort()
for orderId in orderIds:
node.addDynamicAttribute(orderedDynAttrs[orderId])
def _useSizeToggled(self, value):
node = self.coralNode()
dynAttrs = node.dynamicAttributes()
useSize = node.findObject("_useSize").value()
useSize.resize(len(dynAttrs))
i = 0
for attr in dynAttrs:
if attr.isInput():
checked = self._useSizeButtons[attr.id()].isChecked()
useSize.setBoolValueAt(i, checked)
i += 1
def _attrNameChanged(self):
node = self.coralNode()
dynAttrs = node.dynamicAttributes()
for attr in dynAttrs:
widgetValue = str(self._attrNameWidgets[attr.id()].text())
if attr.name() != widgetValue:
attr.setName(widgetValue)
def _removeAttrClicked(self, button):
attr = button._attr()
node = self.coralNode()
node.removeAttribute(attr)
nodeUi = NodeEditor.findNodeUi(node.id())
attrUi = NodeEditor.findAttributeUi(attr.id())
nodeUi.removeAttributeUi(attrUi)
attrUi.setParentNodeUi(None)
nodeUi.updateLayout()
self.nodeInspector().refresh()
def build(self):
NodeInspectorWidget.build(self)
openTextEditorButton = QtGui.QPushButton("edit kernel source", self)
self.layout().addWidget(openTextEditorButton)
self.connect(openTextEditorButton, QtCore.SIGNAL("clicked()"), self._openTextEditor)
groupBox = QtGui.QGroupBox("attribute editor", self)
vlayout = QtGui.QVBoxLayout()
vlayout.setSpacing(5)
vlayout.setContentsMargins(0, 0, 0, 0)
groupBox.setLayout(vlayout)
addInAttrButton = QtGui.QPushButton("Add Input", groupBox)
addOutAttrButton = QtGui.QPushButton("Add Output", groupBox)
vlayout.addWidget(addInAttrButton)
vlayout.addWidget(addOutAttrButton)
self.connect(addInAttrButton, QtCore.SIGNAL("clicked()"), self._addInputClicked)
self.connect(addOutAttrButton, QtCore.SIGNAL("clicked()"), self._addOutputClicked)
useSize = self.coralNode().findObject("_useSize").outValue()
order = 0
for attr in self.coralNode().dynamicAttributes():
hlayout = QtGui.QHBoxLayout()
hlayout.setSpacing(5)
hlayout.setContentsMargins(0, 0, 0, 0)
attrOrder = QtGui.QSpinBox(groupBox)
self._attrOrderWidgets[attr.id()] = attrOrder
attrOrder.setMinimum(0)
attrOrder.setValue(order)
hlayout.addWidget(attrOrder)
self.connect(attrOrder, QtCore.SIGNAL("valueChanged(int)"), self._attrOrderChanged)
attrName = QtGui.QLineEdit(attr.name(), groupBox);
self._attrNameWidgets[attr.id()] = attrName
attrName.setFixedWidth(60)
hlayout.addWidget(attrName)
self.connect(attrName, QtCore.SIGNAL("editingFinished()"), self._attrNameChanged)
specCombo = AttributeSpecializationComboBox(attr, groupBox)
attrSpec = attr.specialization()
if len(attrSpec) == 1:
specCombo.addItem(attrSpec[0])
else:
specCombo.addItem("none")
specCombo.setShowPopupCallback(self._popupSpecCombo)
specCombo.setCurrentItemChangedCallback(self._currentSpecChanged)
hlayout.addWidget(specCombo)
useSizeButton = QtGui.QToolButton(self)
self._useSizeButtons[attr.id()] = useSizeButton
useSizeButton.setText("use size")
useSizeButton.setCheckable(True)
useSizeButton.setChecked(useSize.boolValueAt(order))
hlayout.addWidget(useSizeButton)
self.connect(useSizeButton, QtCore.SIGNAL("toggled(bool)"), self._useSizeToggled)
if attr.isOutput():
useSizeButton.setDisabled(True)
removeButton = QtGui.QPushButton("remove", self)
removeButton._attr = weakref.ref(attr)
hlayout.addWidget(removeButton)
self.connect(removeButton, QtCore.SIGNAL("clicked()"), utils.CallbackWithArgs(self._removeAttrClicked, removeButton))
vlayout.addLayout(hlayout)
order += 1
self.layout().addWidget(groupBox)
def loadPluginUi():
plugin = PluginUi("kernelNodePluginUi")
plugin.registerInspectorWidget("KernelNode", KernelNodeInspectorWidget)
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import os
import sys
import fnmatch
import string
if os.environ.has_key("CORAL_BUILD_FLAVOUR") == False:
os.environ["CORAL_BUILD_FLAVOUR"] = ""
def findFiles(root, recurse = True, pattern = '*.*', return_folders = False):
result = []
try:
names = os.listdir(root)
except os.error:
return result
pattern = pattern or '*'
pat_list = string.splitfields( pattern , ';' )
for name in names:
fullname = os.path.normpath(os.path.join(root, name))
for pat in pat_list:
if fnmatch.fnmatch(name, pat):
if os.path.isfile(fullname) or (return_folders and os.path.isdir(fullname)):
result.append(fullname)
continue
if recurse:
if os.path.isdir(fullname) and not os.path.islink(fullname):
result = result + findFiles( fullname, recurse, pattern, return_folders )
return result
def autoFixDynamicLinks(lib, verbose = False):
f = os.popen('otool -L "%s"'%(lib,))
entries = f.read().split('\n')[1:]
for entry in entries:
oldLibName = entry.split(" ")[0].strip()
if not fnmatch.fnmatch(oldLibName, "/System/Library/Frameworks/*"): #exclude system frameworks
newLibName = entry.split(" ")[0].split("/")[-1].strip()
if verbose:
print "Changing lib path:", oldLibName, "from:", newLibName, "to:", lib
os.system('install_name_tool -change "' + oldLibName + '" "' + newLibName + '" "' + lib + '"')
if verbose:
print "- changeDynamicLink result-------"
print os.system("otool -L %s" %(lib))
print "---------------------------------"
def changeDynamicLink(lib, old_path_prefix, new_path_prefix, quiet = False):
f = os.popen('otool -L "%s"'%(lib,))
x = f.read().split('\n')[1:]
for l in x:
if l.count(old_path_prefix):
ol = l[1:].split(' ')[0]
nw = new_path_prefix + ol.split(old_path_prefix)[-1]
if not quiet:
print "Changing lib path:", lib, "from:", ol, "to:", nw
os.system('install_name_tool -change %s %s %s' %(ol,nw,lib))
if not quiet:
print "- changeDynamicLink result-------"
print os.system("otool -L %s" %(lib))
print "---------------------------------"
tryedImportingBuildEnv = False
def importBuildEnvs():
global tryedImportingBuildEnv
if "buildEnv" not in sys.modules.keys():
try:
import buildEnv
print "* Coral Build: imported buildEnv.py"
except:
if tryedImportingBuildEnv == False:
print "Coral Build: Tried importing buildEnv.py but failed."
tryedImportingBuildEnv = True
def getEnvVar(varName):
var = ""
if varName in os.environ:
var = os.environ[varName]
else:
raise Exception("Could not find env var: " + str(varName))
return var
| Python |
import sys
import os
import platform
import sconsUtils
sconsUtils.importBuildEnvs()
buildMode = sconsUtils.getEnvVar("CORAL_BUILD_MODE")
msvc_version = ""
if os.environ.has_key("MSVC_VERSION"):
msvc_version = os.environ["MSVC_VERSION"]
env = Environment(
CPPPATH = [
sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_OIIO_INCLUDES_PATH")],
LIBS = [
sconsUtils.getEnvVar("CORAL_IMATH_LIB"),
sconsUtils.getEnvVar("CORAL_IMATH_IEX_LIB"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_OIIO_LIB")],
LIBPATH = [
sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_OIIO_LIBS_PATH")],
SHLIBPREFIX = "",
MSVC_VERSION=msvc_version,
TARGET_ARCH = platform.machine())
if os.environ.has_key("CORAL_PARALLEL"):
if os.environ["CORAL_PARALLEL"] == "CORAL_PARALLEL_TBB":
env["CPPPATH"].append(sconsUtils.getEnvVar("CORAL_TBB_INCLUDES_PATH"))
env["LIBS"].append(sconsUtils.getEnvVar("CORAL_TBB_LIB"))
env["LIBPATH"].append(sconsUtils.getEnvVar("CORAL_TBB_LIBS_PATH"))
if sys.platform.startswith("linux"):
pass
elif sys.platform == "darwin":
env["SHLIBSUFFIX"] = ".so"
elif sys.platform.startswith("win"):
env["SHLIBSUFFIX"] = ".pyd"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t /bigobj /MP /openmp")
env["CCFLAGS"] = ["-DCORAL_COMPILE"]
env["LINKFLAGS"] = ["/MANIFEST:NO"]
if os.environ.has_key("CORAL_OPENMP"):
env["CCFLAGS"].append("-DCORAL_OPENMP")
if os.environ.has_key("CORAL_PARALLEL"):
parallel = os.environ["CORAL_PARALLEL"]
if parallel:
print "* Using parallel computation: ", parallel
env["CCFLAGS"].append("-D" + parallel)
builtinNodes = sconsUtils.findFiles("builtinNodes", pattern = "*.cpp")
pythonWrapperFiles = sconsUtils.findFiles("pythonWrappers", pattern = "*.cpp")
srcFiles = sconsUtils.findFiles("src", pattern = "*.cpp")
cppFiles = builtinNodes + pythonWrapperFiles + srcFiles
target = env.SharedLibrary(
target = "_coral",
source = cppFiles,
OBJPREFIX = os.path.join("debug" + os.environ["CORAL_BUILD_FLAVOUR"] + buildMode, ""))
Return("target")
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from coral import coralApp
from coral.coralUi import coralUi
import coralStandaloneConfig
coralUi.init(configModule = coralStandaloneConfig)
coralApp.scanAutoLoadPaths()
coralUi.scanAutoLoadPaths()
coralUi.startApp()
coralApp.finalize()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import random
from PyQt4 import QtGui, QtCore
def _aboutClicked():
from coral.coralUi.mainWindow import MainWindow
mainWin = MainWindow.globalInstance()
mainWin.about()
def _openNodeEditorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("node editor")
def _openNodeBoxClicked():
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeBox import NodeBox
if NodeBox.globalInstance() is None:
MainWindow.openRegisteredWidget("node box")
def _openNodeInspectorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("node inspector")
def _openViewportClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("viewport")
def _openVisualDebuggerClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("visual debugger")
def _collapseClicked():
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral import coralApp
nodesName = []
for node in NodeEditor.selectedNodes():
nodesName.append(node.fullName())
if nodesName:
coralApp.executeCommand("CollapseNodes", nodes = nodesName)
def _explodeClicked():
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral import coralApp
sel = NodeEditor.selectedNodes()
if sel:
coralApp.executeCommand("ExplodeCollapsedNode", collapsedNode = sel[0].fullName())
def _clearAllClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
if MainWindow.okCancelDialog("Clear the current network?"):
coralApp.newNetwork()
def _saveNetworkClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
filename = MainWindow.saveFileDialog("save network file", "Coral Network (*.crl)")
if filename:
coralApp.saveNetworkFile(filename)
def _openNetworkClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
filename = MainWindow.openFileDialog("open network file", "Coral Network (*.crl)")
if filename:
coralApp.openNetworkFile(filename)
def _saveCollapsedNodeClicked():
from coral import coralApp
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
filename = MainWindow.saveFileDialog("save collapsed node", "Coral CollapsedNode (*.py)")
sel = NodeEditor.selectedNodes()
if filename and sel:
coralApp.saveCollapsedNodeFile(sel[0], filename)
def _openScriptEditorClicked():
from coral.coralUi.mainWindow import MainWindow
MainWindow.openRegisteredWidget("script editor")
def _nodeBoxSearch():
from coral.coralUi.nodeBox import NodeBox
NodeBox.enableQuickSearch()
gridVisibilityToggle = True
def _toggleGrid():
global gridVisibilityToggle
gridVisibilityToggle = not gridVisibilityToggle
from coral.coralUi import viewport
for v in viewport.instancedViewports():
v.setGridVisible(gridVisibilityToggle)
viewport.ViewportWidget.refreshViewports()
def apply():
#imports here to avoid cycles
from coral.coralUi import coralUi
from coral.coralUi.mainWindow import MainWindow
from coral.coralUi.nodeEditor.nodeEditor import NodeEditor
from coral.coralUi.nodeBox import NodeBox
from coral.coralUi.nodeInspector.nodeInspector import NodeInspector
from coral.coralUi.scriptEditor import ScriptEditor
from coral.coralUi.viewport import ViewportWidget
from coral.coralUi.visualDebugger import VisualDebugger
mainWin = MainWindow.globalInstance()
mainWin.setWindowTitle("coral standalone")
settingsStored = mainWin.settings().value("settingsStored").toBool()
if not settingsStored:
nodeBox = NodeBox(mainWin)
nodeBoxDock = mainWin.dockWidget(nodeBox, QtCore.Qt.LeftDockWidgetArea)
nodeInspector = NodeInspector(mainWin)
mainWin.dockWidget(nodeInspector, QtCore.Qt.RightDockWidgetArea)
nodeEditor = NodeEditor(mainWin)
mainWin.setCentralWidget(nodeEditor)
nodeEditor.nodeView().centerOn(0.0, 0.0)
mainWin.registerWidget("node editor", NodeEditor)
mainWin.registerWidget("node box", NodeBox)
mainWin.registerWidget("node inspector", NodeInspector)
mainWin.registerWidget("viewport", ViewportWidget)
mainWin.registerWidget("script editor", ScriptEditor)
mainWin.registerWidget("visual debugger", VisualDebugger)
# menu config
fileMenu = mainWin.menuBar().addMenu("File")
fileMenu.addAction("Clear All...", _clearAllClicked)
fileMenu.addAction("Save Netwok...", _saveNetworkClicked)
fileMenu.addAction("Open Network...", _openNetworkClicked)
fileMenu.addSeparator()
fileMenu.addAction("Save CollapsedNode...", _saveCollapsedNodeClicked)
editMenu = mainWin.menuBar().addMenu("Edit")
editMenu.addAction("Collpase Nodes", _collapseClicked)
editMenu.addAction("Explode Collapsed Node", _explodeClicked)
editMenu.addSeparator()
windowMenu = mainWin.menuBar().addMenu("Window")
windowMenu.addAction("About", _aboutClicked)
windowMenu.addAction("Open Node Editor", _openNodeEditorClicked)
windowMenu.addAction("Open Node Box", _openNodeBoxClicked)
windowMenu.addAction("Open Node Inspector", _openNodeInspectorClicked)
windowMenu.addAction("Open Script Editor", _openScriptEditorClicked)
windowMenu.addAction("Open Viewport", _openViewportClicked)
windowMenu.addAction("Open Visual Debugger", _openVisualDebuggerClicked)
# shortcuts
shprtcutsMap = {
"Shift+G": _explodeClicked,
"Ctrl+S": _saveNetworkClicked,
"Ctrl+O": _openNetworkClicked,
"Shift+Tab": _nodeBoxSearch,
"H": _toggleGrid}
mainWin.setShortcutsMap(shprtcutsMap)
mainWin.restoreSettings()
mainWin.show()
from coral import coralApp
coralApp.logInfo("coral v" + coralApp.version())
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
from coral import _coral
from coral import coralApp
import Imath
class TestValue(_coral.Value):
def __init__(self, value):
_coral.Value.__init__(self)
self.value = value
class TestAttribute(_coral.Attribute):
def __init__(self, name, parent):
_coral.Attribute.__init__(self, name, parent)
self._setValuePtr(TestValue(0))
class TestNode(_coral.Node):
def __init__(self, name, parent):
_coral.Node.__init__(self, name, parent)
self.inAttr = TestAttribute("inAttr", self)
self.outAttr = TestAttribute("outAttr", self)
self.addInputAttribute(self.inAttr)
self.addOutputAttribute(self.outAttr)
self._setAttributeAffect(self.inAttr, self.outAttr)
def update(self, attribute):
self.outAttr.outValue().value = self.inAttr.value().value
def testPythonOverloading():
node = TestNode("node", None)
parentNode = _coral.Node("testNode", None)
attr = TestAttribute("attr", parentNode)
parentNode.addOutputAttribute(attr)
_coral.NetworkManager.connect(attr, node.inAttr)
print "testing returned attribute is python subclass"
assert type(node.inAttr.input()) == TestAttribute
print "testing python overrides c++ virtual functions"
attr.value().value = 5
attr.valueChanged()
assert node.outAttr.value().value == 5
def testInterface():
root = _coral.Node("root", None)
node = _coral.Node("testNode", root)
attribute = _coral.Attribute("testAttr", node)
node.addInputAttribute(attribute)
node1 = _coral.Node("testNode1", node)
node.addNode(node1)
assert node1.parent().name() == node.name()
assert node.nodeAt(0).name() == node1.name()
assert node.inputAttributeAt(0).name() == attribute.name()
assert node.containsNode(node1)
assert len(node.nodes()) == 1
node.removeNode(node1)
assert node.containsNode(node1) == False
attribute1 = _coral.Attribute("testAttr1", root)
root.addOutputAttribute(attribute1)
_coral.NetworkManager.connect(attribute1, attribute)
assert attribute1.isConnectedTo(attribute)
assert attribute.input().name() == attribute1.name()
nestedNode = _coral.Node("nestedNode", node)
assert nestedNode.fullName() == "root.testNode.nestedNode"
def testObjectsLifespan():
node0 = _coral.Node("node0", None)
node1 = _coral.Node("node1", node0)
node0.addNode(node1)
print "testing children nodes are kept alive by father node"
del node1
assert _coral.NetworkManager.objectCount() == 2
print "testing children nodes are destroyed by father node"
del node0
assert _coral.NetworkManager.objectCount() == 0
print "testing input attributes are destroyed by father node"
node = _coral.Node("node", None)
attribute = _coral.Attribute("testAttr", node)
node.addInputAttribute(attribute)
del node
del attribute
assert _coral.NetworkManager.objectCount() == 0
print "testing output attributes are destroyed by father node"
node = _coral.Node("node", None)
attribute = _coral.Attribute("testAttr", node)
node.addOutputAttribute(attribute)
del node
del attribute
assert _coral.NetworkManager.objectCount() == 0
def testNodeDeletion():
coralApp.init()
coralApp.createNode("Float", "test", coralApp.findNode("root"))
coralApp.deleteNodes([coralApp.findNode("root.test")])
assert _coral.NetworkManager.objectCount() == 1
coralApp.finalize()
def testOwnership():
n1 = _coral.Node("test", None)
n2 = _coral.Node("nested", None)
n1.addNode(n2)
del n2
assert n1.nodeAt(0)
def testNesting():
coralApp.init()
root = coralApp.findNode("root")
n1 = coralApp.createNode("CollapsedNode", "n1", root)
n2 = coralApp.createNode("CollapsedNode", "n2", n1)
coralApp.finalize()
def testDeletingAttributes():
coralApp.init()
root = coralApp.findNode("root")
n1 = coralApp.createNode("Float", "n1", root)
n2 = coralApp.createNode("Float", "n2", root)
n3 = coralApp.createNode("Add", "n3", root)
n4 = coralApp.createNode("Add", "n4", root)
n5 = coralApp.createNode("Float", "n5", root)
n6 = coralApp.createNode("Add", "n6", root)
_coral.NetworkManager.connect(n1.outputAttributeAt(0), n3.inputAttributeAt(0))
_coral.NetworkManager.connect(n2.outputAttributeAt(0), n3.inputAttributeAt(1))
_coral.NetworkManager.connect(n3.outputAttributeAt(0), n4.inputAttributeAt(0))
_coral.NetworkManager.connect(n5.outputAttributeAt(0), n4.inputAttributeAt(1))
_coral.NetworkManager.connect(n3.outputAttributeAt(0), n6.inputAttributeAt(1))
coralApp.deleteNodes([n3, n5, n6])
coralApp.finalize()
def testFindObject():
coralApp.init()
root = coralApp.findNode("root")
n1 = coralApp.createNode("CollapsedNode", "n1", root)
n2 = coralApp.createNode("CollapsedNode", "n2", n1)
assert coralApp.findObject(n2.fullName()) is n2
coralApp.finalize()
def testObjectsHierarchy():
parentNode = _coral.Node("parentNode", None)
childNode = _coral.Node("childNode", parentNode)
parentNode.addNode(childNode)
assert childNode.fullName() == "parentNode.childNode"
parentNode.removeNode(childNode)
assert childNode.fullName() == "childNode"
def testCollapsedNode():
coralApp.init()
root = coralApp.findNode("root")
n1 = coralApp.createNode("Float", "n1", root)
n2 = coralApp.createNode("Float", "n2", root)
n3 = coralApp.createNode("Add", "n3", root)
_coral.NetworkManager.connect(n1.outputAttributeAt(0), n3.inputAttributeAt(0))
collapsedNode = coralApp.collapseNodes([n3])
assert collapsedNode in root.nodes()
coralApp.finalize()
def testCommand():
cmd = _coral.Command()
cmd.setName("test")
cmd.setArgBool("boolArg", True)
cmd.setArgInt("intArg", 1)
cmd.setArgFloat("floatArg", 1.0)
cmd.setArgString("stringArg", "hello")
cmd.setArgUndefined("undefinedArg", "int(1)")
assert cmd.asScript() == "executeCommand('test', boolArg = True, intArg = 1, floatArg = 1.000000, stringArg = 'hello', undefinedArg = int(1))"
assert cmd.argType("undefinedArg") is 0
assert cmd.argType("boolArg") is 1
assert cmd.argType("intArg") is 2
assert cmd.argType("floatArg") is 3
assert cmd.argType("stringArg") is 4
def testSaveScript():
coralApp.init()
root = coralApp.findNode("root")
n1 = coralApp.createNode("Float", "n1", root)
n2 = coralApp.createNode("Float", "n2", root)
n3 = coralApp.createNode("Add", "n3", root)
n1.outputAttributeAt(0).outValue().setFloatValueAt(0, 5.0)
_coral.NetworkManager.connect(n1.outputAttributeAt(0), n3.inputAttributeAt(0))
saveScript = root.contentAsScript()
coralApp.finalize()
coralApp.init()
coralApp.setShouldLogInfos(False)
coralApp._executeNetworkScript(saveScript)
n1 = coralApp.findNode("root.n1")
n2 = coralApp.findNode("root.n2")
n3 = coralApp.findNode("root.n3")
assert n1 is not None
assert n2 is not None
assert n3 is not None
n1Floats = n1.outputAttributeAt(0).outValue().getFloat()
assert n1Floats[0] == 5.0
assert n3.inputAttributeAt(0).input() is n1.outputAttributeAt(0)
collapsedNode = coralApp.collapseNodes([n3])
root = coralApp.findNode("root")
saveScript = root.contentAsScript()
coralApp.finalize()
coralApp.init()
coralApp._executeNetworkScript(saveScript)
collapseNode = coralApp.findNode("root.CollapsedNode")
assert collapseNode is not None
assert len(collapseNode.attributes()) > 0
coralApp.finalize()
def testSpecializationBug1():
n = _coral.Node("n", None)
a = _coral.Attribute("a", n)
n.addOutputAttribute(a)
n._setAttributeAllowedSpecializations(a, ["Spec1", "Spec3"])
n1 = _coral.Node("n1", None)
a1 = _coral.Attribute("a1", n1)
n1.addInputAttribute(a1)
n1._setAttributeAllowedSpecializations(a1, ["Spec1", "Spec2"])
_coral.NetworkManager.connect(a, a1)
assert a1.specialization() == ["Spec1"] and a.specialization() == ["Spec1"]
def testCollapsingBug1():
coralApp.init()
collapsed = coralApp.createNode("CollapsedNode", "collapsed", coralApp.rootNode())
in1 = coralApp.createAttribute("PassThroughAttribute", "in", collapsed, input = True)
add = coralApp.createNode("Add", "addNode", collapsed)
_coral.NetworkManager.connect(in1, add.inputAttributeAt(0))
float1 = coralApp.createNode("Float", "float1", coralApp.rootNode())
_coral.NetworkManager.connect(float1.outputAttributeAt(0), in1)
newCollapsed = coralApp.collapseNodes([collapsed])
print "testing collapsing operation won't add erroneous output attributes"
assert newCollapsed.outputAttributes() == []
print "testing collapsing operation won't disconnect erroneous attributes"
assert in1.isConnectedTo(add.inputAttributeAt(0))
coralApp.finalize()
def testSpecializingPass():
coralApp.init()
collapsed0 = coralApp.createNode("CollapsedNode", "collapsed0", coralApp.rootNode())
in0 = coralApp.createAttribute("PassThroughAttribute", "in0", collapsed0, input = True)
out0 = coralApp.createAttribute("PassThroughAttribute", "out0", collapsed0, output = True)
collapsed = coralApp.createNode("CollapsedNode", "collapsed", collapsed0)
in1 = coralApp.createAttribute("PassThroughAttribute", "in", collapsed, input = True)
out1 = coralApp.createAttribute("PassThroughAttribute", "out", collapsed, output = True)
add = coralApp.createNode("Add", "addNode", collapsed)
_coral.NetworkManager.connect(in1, add.inputAttributeAt(0))
_coral.NetworkManager.connect(add.outputAttributeAt(0), out1)
_coral.NetworkManager.connect(in0, in1)
_coral.NetworkManager.connect(out1, out0)
float1 = coralApp.createNode("Float", "float1", coralApp.rootNode())
floats = coralApp.createNode("Vec3", "floats", coralApp.rootNode())
_coral.NetworkManager.connect(out0, floats.inputAttributeAt(0))
_coral.NetworkManager.connect(float1.outputAttributeAt(0), in0)
assert add.inputAttributeAt(0).specialization() == ["Float"]
assert add.outputAttributeAt(0).specialization() == ["Float"]
assert in0.specialization() == ["Float"]
assert in1.specialization() == ["Float"]
assert out1.specialization() == ["Float"]
coralApp.finalize()
def runTest(function):
print "* running", function.__name__
function()
assert _coral.NetworkManager.objectCount() == 0
print "*", function.__name__, "done!"
if __name__ == "__main__":
runTest(testObjectsLifespan)
runTest(testInterface)
runTest(testPythonOverloading)
runTest(testNodeDeletion)
runTest(testOwnership)
runTest(testNesting)
runTest(testDeletingAttributes)
runTest(testFindObject)
runTest(testObjectsHierarchy)
runTest(testCollapsedNode)
runTest(testCommand)
runTest(testCollapsingBug1)
runTest(testSpecializingPass)
runTest(testSpecializationBug1)
# _coral.runTests()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from _coral import Command
import coralApp
from _coral import NetworkManager, ErrorObject
from plugin import Plugin
class CreateNode(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("className", "")
self.setArgString("name", "")
self.setArgString("parentNode", "")
self.setArgString("specializationPreset", "")
def doIt(self):
className = self.argAsString("className")
name = self.argAsString("name")
parentNode = self.argAsString("parentNode")
newNode = None
parentNode = coralApp.findNode(parentNode)
if parentNode:
newNode = coralApp.createNode(className, name, parentNode)
if newNode:
specializationPreset = self.argAsString("specializationPreset")
if specializationPreset:
newNode.enableSpecializationPreset(specializationPreset)
self.setResultString(newNode.fullName())
if newNode is None:
coralApp.logDebug("CreateNode Command: failed to create new node.")
class CreateAttribute(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("className", "")
self.setArgString("name", "")
self.setArgString("parentNode", "")
self.setArgBool("input", False)
self.setArgBool("output", False)
self.setArgString("specializationOverride", "none")
def doIt(self):
className = self.argAsString("className")
name = self.argAsString("name")
parentNode = self.argAsString("parentNode")
input = self.argAsBool("input")
output = self.argAsBool("output")
newAttr = None
parentNode = coralApp.findNode(parentNode)
if parentNode:
newAttr = coralApp.createAttribute(className, name, parentNode, input, output)
if newAttr:
specializationOverride = self.argAsString("specializationOverride")
if specializationOverride != "" and specializationOverride != "none":
newAttr.setSpecializationOverride(specializationOverride)
self.setResultString(newAttr.fullName())
if newAttr is None:
coralApp.logDebug("CreateAttribute Command: failed to create new attribute.")
class SetupDynamicAttribute(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("attribute", "")
self.setArgUndefined("affect", "[]")
self.setArgUndefined("affectedBy", "[]")
self.setArgUndefined("allowedSpecialization", "[]")
self.setArgUndefined("specializationLinkedTo", "[]")
self.setArgUndefined("specializationLinkedBy", "[]")
def doIt(self):
attribute = coralApp.findAttribute(self.argAsString("attribute"))
affect = eval(self.argAsString("affect"))
affectedBy = eval(self.argAsString("affectedBy"))
allowedSpecialization = eval(self.argAsString("allowedSpecialization"))
specLinkedTo = eval(self.argAsString("specializationLinkedTo"))
specLinkedBy = eval(self.argAsString("specializationLinkedBy"))
parentNode = attribute.parent()
parentNodeDynamicAttrs = parentNode.dynamicAttributes()
if attribute in parentNodeDynamicAttrs:
for attrName in affect:
attr = coralApp.findAttribute(attrName)
if attr.isAffectedBy(attribute) == False:
parentNode._setAttributeAffect(attribute, attr)
for attrName in affectedBy:
attr = coralApp.findAttribute(attrName)
if attribute.isAffectedBy(attr) == False:
parentNode._setAttributeAffect(attr, attribute)
for attrName in specLinkedTo:
attr = coralApp.findAttribute(attrName)
if attr not in attribute.specializationLinkedTo():
parentNode._addAttributeSpecializationLink(attribute, attr)
for attrName in specLinkedBy:
attr = coralApp.findAttribute(attrName)
if attribute not in attr.specializationLinkedTo():
parentNode._addAttributeSpecializationLink(attr, attribute)
parentNode._setAttributeAllowedSpecializations(attribute, allowedSpecialization)
parentNode._updateAttributeSpecialization(attribute)
class DeleteObjects(Command):
def __init__(self):
Command.__init__(self)
self.setArgUndefined("nodes", "[]")
self.setArgUndefined("attributes", "[]")
def _deleteAttributes(self, attributesName):
attributes = []
for attrName in attributesName:
attr = coralApp.findAttribute(attrName)
if attr:
attributes.append(attr)
if attributes:
coralApp.deleteAttributes(attributes)
def _deleteNodes(self, nodesName):
nodes = []
for nodeName in nodesName:
node = coralApp.findNode(nodeName)
if node:
nodes.append(node)
if nodes:
coralApp.deleteNodes(nodes)
def doIt(self):
attributes = eval(self.argAsString("attributes"))
self._deleteAttributes(attributes)
nodes = eval(self.argAsString("nodes"))
self._deleteNodes(nodes)
class ConnectAttributes(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("sourceAttribute", "")
self.setArgString("destinationAttribute", "")
def doIt(self):
success = False
error = None
sourceAttributeName = self.argAsString("sourceAttribute")
destinationAttributeName = self.argAsString("destinationAttribute")
sourceAttribute = coralApp.findAttribute(sourceAttributeName)
destinationAttribute = coralApp.findAttribute(destinationAttributeName)
if sourceAttribute and destinationAttribute:
if destinationAttribute.input() is not None:
destinationAttribute.disconnectInput()
error = ErrorObject()
success = NetworkManager.connect(sourceAttribute, destinationAttribute, error)
if not success:
errorMessage = "error during connection between " + sourceAttributeName + " and " + destinationAttributeName + "\n"
if error:
if error.message():
errorMessage += "extended info: " + error.message()
coralApp.logDebug(errorMessage)
class DisconnectInput(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("attribute", "")
def doIt(self):
attribute = self.argAsString("attribute")
attribute = coralApp.findAttribute(attribute)
attribute.disconnectInput()
class CollapseNodes(Command):
def __init__(self):
Command.__init__(self)
self.setArgUndefined("nodes", "[]")
def doIt(self):
nodes = eval(self.argAsString("nodes"))
nodeNames = nodes
nodes = []
for nodeName in nodeNames:
node = coralApp.findNode(nodeName)
if node:
nodes.append(node)
coralApp.collapseNodes(nodes)
class ExplodeCollapsedNode(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("collapsedNode", "")
def doIt(self):
from collapsedNode import CollapsedNode
collapsedNodeName = self.argAsString("collapsedNode")
collapsedNode = coralApp.findNode(collapsedNodeName)
if collapsedNode:
if collapsedNode.__class__ is CollapsedNode:
coralApp.explodeCollapsedNode(collapsedNode)
else:
coralApp.logDebug("ExplodeCollapsedNode Command: input node must be of type CollapsedNode")
class SetAttributeValue(Command):
def __init__(self):
Command.__init__(self)
self.setArgString("attribute", "")
self.setArgString("value", "")
def doIt(self):
attribute = self.argAsString("attribute")
value = self.argAsString("value")
attribute = coralApp.findAttribute(attribute)
if attribute:
if attribute.outValue():
attribute.outValue().setFromString(value);
attribute.valueChanged()
def loadPlugin():
plugin = Plugin("builtinCommands")
plugin.registerCommand(CreateNode)
plugin.registerCommand(CreateAttribute)
plugin.registerCommand(DeleteObjects)
plugin.registerCommand(ConnectAttributes)
plugin.registerCommand(DisconnectInput)
plugin.registerCommand(CollapseNodes)
plugin.registerCommand(ExplodeCollapsedNode)
plugin.registerCommand(SetAttributeValue)
plugin.registerCommand(SetupDynamicAttribute)
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import os
import sys
import types
import math
import weakref
class NoneRef(object):
def __call__(self):
return None
class WeakMethod(object):
def __init__(self, method):
self._method = method.im_func
self._object = weakref.ref(method.im_self)
def __nonzero__(self):
return self._object() is not None
def __call__(self, *args):
obj = self._object()
if obj:
return self._method(obj, *args)
def weakRef(object):
ref = NoneRef()
if object:
if hasattr(object, "im_func"):
ref = WeakMethod(object)
else:
ref = weakref.ref(object)
return ref
class CallbackWithArgs(object):
def __init__(self, callback, *args):
self._callback = weakRef(callback)
self._args = args
def __call__(self, *args):
joinedArgs = args + self._args
self._callback(*joinedArgs)
def removeFromList(element, array):
deleted = False
if array.count(element):
elementId = array.index(element)
del array[elementId]
deleted = True
return deleted
def runtimeImport(filename):
modulePath = os.path.dirname(filename)
fileName = os.path.split(filename)[1]
moduleName = fileName.split(".")[0]
alreadyPresent = True
if modulePath not in sys.path:
alreadyPresent = False
sys.path.append(modulePath)
module = __import__(moduleName)
if not alreadyPresent:
sys.path.remove(modulePath)
return module
def isModule(path):
result = False
files = os.listdir(path)
for f in files:
if f == '__init__.py':
result = True
break
return result
def inspectModulePath(modulePath, returnModules):
files = os.listdir(modulePath)
for f in files:
dirfile = os.path.join(modulePath, f)
if os.path.isfile(dirfile):
if os.path.splitext(dirfile)[1] == ".py":
moduleName = os.path.splitext(os.path.basename(f))[0]
returnModules.append(moduleName)
return returnModules
def findSubModulesInModule(module):
modulePath = os.path.dirname(module.__file__)
subModulesNames = inspectModulePath(modulePath, [])
__import__(module.__name__, fromlist=subModulesNames)
returnModules = []
for subModuleName in subModulesNames:
if hasattr(module, subModuleName):
subModule = getattr(module, subModuleName)
if type(subModule).__name__ == "module":
returnModules.append(subModule)
return returnModules
def _findClassesRecursive(module, baseClass, collectedClasses, processedModules = []):
processedModules.append(module)
for attr in dir(module):
moduleAttribute = getattr(module, attr)
if type(moduleAttribute) is types.TypeType:
if issubclass(moduleAttribute, baseClass):
if moduleAttribute not in collectedClasses:
collectedClasses.append(moduleAttribute)
for subModule in findSubModulesInModule(module):
if subModule not in processedModules:
_findClassesRecursive(subModule, baseClass, collectedClasses, processedModules)
def findClasses(module, baseClass, importedModules = None):
foundClasses = []
if importedModules is None:
importedModules = []
_findClassesRecursive(module, baseClass, foundClasses, importedModules)
return foundClasses
def getNumber(name):
number = ""
for char in name:
if char.isdigit():
number += char
return number
def increaseNameNumber(name):
newName = name
numberStr = getNumber(name)
number = 1
if numberStr:
number = int(numberStr)
number += 1
newName = name.replace(numberStr, "")
newName += str(number)
return newName
def getAllParentClasses(classType):
parentClasses = []
parentClass = classType.__bases__
while parentClass:
parentClasses.append(parentClass[0])
parentClass = parentClass[0].__bases__
if parentClasses[-1] is object:
parentClasses.pop(-1)
return parentClasses
| Python |
import time
import thread
from _coral import Node, NumericAttribute
class TimeNode(Node):
def __init__(self, name, parent):
Node.__init__(self, name, parent)
self.setClassName("Time")
self._framesPerSecond = NumericAttribute("framesPerSecond", self)
self._time = NumericAttribute("time", self)
self._play = False
self.addInputAttribute(self._framesPerSecond)
self.addOutputAttribute(self._time)
self._setAttributeAllowedSpecializations(self._framesPerSecond, ["Float"])
self._setAttributeAllowedSpecializations(self._time, ["Float"])
self._setUpdateEnabled(False)
self._framesPerSecond.outValue().setFloatValueAt(0, 24.0)
def _advanceTime(self):
timeValue = self._time.outValue()
framesPerSecond = self._framesPerSecond.outValue().floatValueAt(0)
timeStep = 1.0 / framesPerSecond
enlapsedTime = 0.0
while self._play:
enlapsedTime = enlapsedTime + timeStep
timeValue.setFloatValueAt(0, enlapsedTime * framesPerSecond)
self._time.valueChanged()
time.sleep(timeStep)
def isPlaying(self):
return self._play
def play(self, value = True):
self._play = value
if self._play:
thread.start_new_thread(self._advanceTime, ())
else:
self._time.outValue().setFloatValueAt(0, 0.0)
self._time.valueChanged()
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from observer import ObserverCollector
import utils
class ValueChangedObserverCollector(ObserverCollector):
def __init__(self):
ObserverCollector.__init__(self)
self._observedAttributes = {}
def add(self, observer, attribute):
attrId = attribute.id()
ObserverCollector.add(self, observer, attrId)
self._observedAttributes[attrId] = utils.weakRef(attribute)
attribute.setValueObserved(True)
def removeDeadObserver(self, observerId, subject):
ObserverCollector.removeDeadObserver(self, observerId, subject)
if len(self._dict[subject].values()) == 0:
attribute = self._observedAttributes[subject]()
attribute.setValueObserved(False)
del self._observedAttributes[subject]
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import utils
class Observer(object):
def __init__(self):
self._notificationCallback = utils.weakRef(None)
self._collector = utils.weakRef(None)
self._data = {}
self._id = id(self)
self._subject = None
def setData(self, key, value):
self._data[key] = value
def data(self, key):
return self._data[key]
def setNotificationCallback(self, callback):
self._notificationCallback = utils.weakRef(callback)
def notify(self):
if self._notificationCallback():
self._notificationCallback()()
def __del__(self):
collector = self._collector()
if collector:
collector.removeDeadObserver(self._id, self._subject)
class ObserverCollector(object):
def __init__(self):
self._list = {}
self._dict = {}
def add(self, observer, subject = None):
observerRef = utils.weakRef(observer)
if observerRef not in self._list.values():
observer._collector = utils.weakRef(self)
self._list[observer._id] = observerRef
if subject:
dictList = {}
observer._subject = subject
if self._dict.has_key(subject):
dictList = self._dict[subject]
else:
self._dict[subject] = dictList
dictList[observer._id] = observerRef
def removeDeadObserver(self, observerId, subject = None):
del self._list[observerId]
if subject:
del self._dict[subject][observerId]
def observers(self, subject = None):
list = self._list
if subject:
if self._dict.has_key(subject):
list = self._dict[subject]
else:
list = {}
observersCopy = []
for observerRef in list.values():
observersCopy.append(observerRef())
return observersCopy
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import coralApp
## Instanciate this object to register new attributes, nodes or commands.
class Plugin(object):
def __init__(self, name):
self._name = name
self._registeredAttributes = []
self._registeredNodes = []
self._registeredCommands = []
def registerAttribute(self, className, attributeClass):
self._registeredAttributes.append({"className": className, "attributeClass": attributeClass})
def registerNode(self, className, nodeClass, tags = [], description = ""):
self._registeredNodes.append({"className": className, "nodeClass": nodeClass, "tags": tags, "description": description})
def registerCommand(self, commandClass):
self._registeredCommands.append(commandClass)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
from plugin import Plugin
import _coral
import timeNode
def loadPlugin():
plugin = Plugin("builtinNodes")
plugin.registerAttribute("NumericAttribute", _coral.NumericAttribute)
plugin.registerNode("Int", _coral.IntNode, tags = ["numeric"], description = "Generate an int.")
plugin.registerNode("Float", _coral.FloatNode, tags = ["numeric"], description = "Generate a float.")
plugin.registerNode("Vec3", _coral.Vec3Node, tags = ["numeric"], description = "Generate a vec3.\nWorks with single or array values.")
plugin.registerNode("Vec3ToFloats", _coral.Vec3ToFloats, tags = ["numeric"], description = "Get x, y, z values from a vec3.\nWorks with single or array values.")
plugin.registerNode("Col4", _coral.Col4Node, tags = ["numeric"], description = "Generate a col4.\nWorks with single or array values.")
plugin.registerNode("Col4ToFloats", _coral.Col4ToFloats, tags = ["numeric"], description = "Get r, g, b, a values from a col4.\nWorks with single or array values.")
plugin.registerNode("Col4Reverse", _coral.Col4Reverse, tags = ["numeric"], description = "Get 1-rgb. Alpha doesn't change.\nWorks with single or array values.")
plugin.registerNode("Quat", _coral.QuatNode, tags = ["numeric"], description = "Generate a quaternion.\nWorks with single or array values.")
plugin.registerNode("QuatToFloats", _coral.QuatToFloats, tags = ["numeric"], description = "Get r, x, y, z values from a quaternion.\nWorks with single or array values.")
plugin.registerNode("QuatToAxisAngle", _coral.QuatToAxisAngle, tags = ["numeric"], description = "Convert a quaternion to axis/angle.")
plugin.registerNode("QuatToEulerRotation", _coral.QuatToEulerRotation, tags = ["numeric"], description = "Convert a quaternion to euler rotation.")
plugin.registerNode("QuatToMatrix44", _coral.QuatToMatrix44, tags = ["numeric"], description = "Convert a quaternion to a rotation matrix.")
plugin.registerNode("Matrix44", _coral.Matrix44Node, tags = ["numeric"], description = "Generate a Matrix44.")
plugin.registerNode("ConstantArray", _coral.ConstantArray, tags = ["numeric"], description = "Generate an array from a constant value.")
plugin.registerNode("ArraySize", _coral.ArraySize, tags = ["numeric"], description = "Get the size of a numeric array")
plugin.registerNode("BuildArray", _coral.BuildArray, tags = ["numeric"], description = "Build a numeric array by adding each individual element.")
plugin.registerNode("RangeArray", _coral.RangeArray, tags = ["numeric"], description = "Generate an array from the given range, each element of the array is a progressive value of the range.")
plugin.registerNode("Matrix44Translation", _coral.Matrix44Translation, tags = ["numeric"], description = "Get the translation values of a matrix44.\nWorks with single or array values.")
plugin.registerNode("Matrix44RotationAxis", _coral.Matrix44RotationAxis, tags = ["numeric"], description = "Get each rotation axis of a matrix44 as three individual vectors.\nWorks with single or array values.")
plugin.registerNode("Matrix44FromVectors", _coral.Matrix44FromVectors, tags = ["numeric"], description = "Build a matrix44 from vec3 values.\nWorks with single or array values.")
plugin.registerNode("Matrix44EulerRotation", _coral.Matrix44EulerRotation, tags = ["numeric"], description = "Get the euler angles from a matrix44.\nWorks with single or array values.")
plugin.registerNode("Matrix44ToQuat", _coral.Matrix44ToQuat, tags = ["numeric"], description = "Get the quaternion from a matrix44.\nWorks with single or array values.")
plugin.registerNode("RangeLoop", _coral.RangeLoop, tags = ["numeric"], description = "Generate a value that will loop in a given range of values.\nWorks with single or array values.")
plugin.registerNode("RandomNumber", _coral.RandomNumber, tags = ["numeric"], description = "Generate a random number.\nWorks with single or array values.")
plugin.registerNode("ArrayIndices", _coral.ArrayIndices, tags = ["numeric", "loop"], description = "Build an array composed by all the indexes extracted from the given input array.")
plugin.registerNode("GetArrayElement", _coral.GetArrayElement, tags = ["numeric"], description = "Get a single element of an array.")
plugin.registerNode("SetArrayElement", _coral.SetArrayElement, tags = ["numeric"], description = "Set a single element of an array.")
plugin.registerNode("GetSimulationStep", _coral.GetSimulationStep, tags = ["numeric", "simulation"], description = "Get the values stored by SetSimulationStep and reuse them in the simulation step.\nWhen the step attribute is set to 0 the simulation is reset and the data is taken from the source.")
plugin.registerNode("SetSimulationStep", _coral.SetSimulationStep, tags = ["numeric", "simulation"], description = "Set some numeric values and make them available to a GetSimulationStep node connected to the same source.\n")
plugin.registerNode("FindPointsInRange", _coral.FindPointsInRange, tags = ["numeric"])
plugin.registerNode("Add", _coral.AddNode, tags = ["math"])
plugin.registerNode("Sub", _coral.SubNode, tags = ["math"])
plugin.registerNode("Mul", _coral.MulNode, tags = ["math"])
plugin.registerNode("Div", _coral.DivNode, tags = ["math"])
plugin.registerNode("Abs", _coral.Abs, tags = ["math"])
plugin.registerNode("Atan2", _coral.Atan2, tags = ["math"])
plugin.registerNode("Sqrt", _coral.Sqrt, tags = ["math"])
plugin.registerNode("Pow", _coral.Pow, tags = ["math"])
plugin.registerNode("Exp", _coral.Exp, tags = ["math"])
plugin.registerNode("Log", _coral.Log, tags = ["math"])
plugin.registerNode("Ceil", _coral.Ceil, tags = ["math"])
plugin.registerNode("Floor", _coral.Floor, tags = ["math"])
plugin.registerNode("Round", _coral.Round, tags = ["math"])
plugin.registerNode("Length", _coral.Length, tags = ["math"])
plugin.registerNode("Inverse", _coral.Inverse, tags = ["math"])
plugin.registerNode("CrossProduct", _coral.CrossProduct, tags = ["math"])
plugin.registerNode("DotProduct", _coral.DotProduct, tags = ["math"])
plugin.registerNode("Normalize", _coral.Normalize, tags = ["math"])
plugin.registerNode("TrigonometricFunc", _coral.TrigonometricFunc, tags = ["math"])
plugin.registerNode("Radians", _coral.Radians, tags = ["math"])
plugin.registerNode("Degrees", _coral.Degrees, tags = ["math"])
plugin.registerNode("Min", _coral.Min, tags = ["math"])
plugin.registerNode("Max", _coral.Max, tags = ["math"])
plugin.registerNode("Average", _coral.Average, tags = ["math"])
plugin.registerNode("Slerp", _coral.Slerp, tags = ["math"])
plugin.registerNode("QuatMultiply", _coral.QuatMultiply, tags = ["math"])
plugin.registerNode("Negate", _coral.Negate, tags = ["math"])
plugin.registerAttribute("ImageAttribute", _coral.ImageAttribute)
plugin.registerNode("Image", _coral.ImageNode, tags = ["image"])
plugin.registerAttribute("GeoAttribute", _coral.GeoAttribute)
plugin.registerAttribute("GeoInstanceArrayAttribute", _coral.GeoInstanceArrayAttribute)
plugin.registerNode("SetGeoPoints", _coral.SetGeoPoints, tags = ["geometry"])
plugin.registerNode("GetGeoPoints", _coral.GetGeoPoints, tags = ["geometry"])
plugin.registerNode("GetGeoNormals", _coral.GetGeoNormals, tags = ["geometry"], description = "Get one normal vector per vertex.")
plugin.registerNode("ObjImporter", _coral.ObjImporter, tags = ["geometry"])
plugin.registerNode("GeoGrid", _coral.GeoGrid, tags = ["geometry"])
plugin.registerNode("GeoSphere", _coral.GeoSphere, tags = ["geometry"])
plugin.registerNode("GeoCube", _coral.GeoCube, tags = ["geometry"])
plugin.registerNode("GeoNeighbourPoints", _coral.GeoNeighbourPoints, tags = ["geometry"])
plugin.registerNode("GetGeoElements", _coral.GetGeoElements, tags = ["geometry"])
plugin.registerNode("GetGeoSubElements", _coral.GetGeoSubElements, tags = ["geometry"])
plugin.registerNode("GeoInstanceGenerator", _coral.GeoInstanceGenerator, tags = ["geometry"])
plugin.registerAttribute("StringAttribute", _coral.StringAttribute)
plugin.registerNode("String", _coral.StringNode, tags = ["generic"])
plugin.registerNode("Time", timeNode.TimeNode, tags = ["generic"])
plugin.registerNode("ImportCIOTransforms", _coral.ImportCIOTransforms, tags = ["generic"])
plugin.registerNode("ImportCIOSkinWeights", _coral.ImportCIOSkinWeights, tags = ["generic"])
plugin.registerNode("LoopInput", _coral.LoopInputNode, tags = ["loop"])
plugin.registerNode("LoopOutput", _coral.LoopOutputNode, tags = ["loop"])
plugin.registerNode("ForLoop", _coral.ForLoopNode, tags = ["loop"])
plugin.registerNode("ProcessSimulation", _coral.ProcessSimulationNode, tags = ["generic", "simulation"])
plugin.registerAttribute("BoolAttribute", _coral.BoolAttribute)
plugin.registerNode("Bool", _coral.BoolNode, tags = ["conditional"])
plugin.registerNode("IfGreaterThan", _coral.IfGreaterThan, tags = ["conditional"])
plugin.registerNode("IfLessThan", _coral.IfLessThan, tags = ["conditional"])
plugin.registerNode("ConditionalValue", _coral.ConditionalValue, tags = ["conditional"])
plugin.registerNode("SplinePoint", _coral.SplinePoint, tags = ["curve"])
plugin.registerNode("SkinWeightDeformer", _coral.SkinWeightDeformer, tags = ["deformers"])
return plugin
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import _coral
## This node is placed at the root of the tree and contains the whole graph.
#@implements Node
class RootNode(_coral.Node):
def __init__(self, name):
_coral.Node.__init__(self, name, None)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
##@package coral.coralApp
# Main module to perform the most basic operations.
import traceback
import os, sys
import copy
import weakref
import traceback
import _coral
import utils
from observer import Observer, ObserverCollector
from rootNode import RootNode
from valueChangedObserverCollector import ValueChangedObserverCollector
class VerboseLevel:
logNothing = 0
logInfos = 1
logErrors = 2
logDebugs = 3
class CoralAppData:
version = 0.3
nodeClasses = {}
classNameTags = {}
attributeClasses = {}
commandClasses = {}
shouldLogInfos = True
executedCommands = []
undoLimit = 100
undoneCommands = []
rootNode = None
autoLoadPaths = []
instantiatedNodes = []
loadingNetwork = False
registeredNodeDescriptions = {}
appendToLastCreatedNodes = False
lastCreatedNodes = []
currentNetworkDir = ""
verboseLevel = VerboseLevel.logDebugs
#observer lists
registeredNodeClassesObservers = ObserverCollector()
createdNodeObservers = ObserverCollector()
deletingNodeObservers = ObserverCollector()
connectedAttributesObservers = ObserverCollector()
disconnectedInputObservers = ObserverCollector()
attributeSpecializedObservers = ObserverCollector()
createdAttributeObservers = ObserverCollector()
deletingAttributeObservers = ObserverCollector()
removedNodeObservers = ObserverCollector()
addedNodeObservers = ObserverCollector()
addedAttributeObservers = ObserverCollector()
collapsedNodeObservers = ObserverCollector()
nameChangedObservers = ObserverCollector()
connectedInputObservers = ObserverCollector()
removedAttributeObservers = ObserverCollector()
initializedNewNetworkObservers = ObserverCollector()
initializingNewNetworkObservers = ObserverCollector()
generatingSaveScriptObservers = ObserverCollector()
networkLoadedObservers = ObserverCollector()
nodeConnectionChangedObservers = ObserverCollector()
networkLoadingObservers = ObserverCollector()
messageLoggedObservers = ObserverCollector()
def registeredNodeDescription(className):
description = ""
if CoralAppData.registeredNodeDescriptions.has_key(className):
description = CoralAppData.registeredNodeDescriptions[className]
return description
def instantiatedNodes():
nodes = []
for node in CoralAppData.instantiatedNodes:
nodes.append(node())
return nodes
def addAutoLoadPath(path):
if path not in CoralAppData.autoLoadPaths:
CoralAppData.autoLoadPaths.append(path)
def setVerboseLevel(level):
CoralAppData.verboseLevel = level
def verboseLevel():
return CoralAppData.verboseLevel
def scanPathForPlugins(path):
verbLev = verboseLevel()
setVerboseLevel(0)
entries = os.listdir(path)
for entry in entries:
if entry.split(".")[-1] == "py":
filename = os.path.join(path, entry)
loadPlugin(filename)
setVerboseLevel(verbLev)
def scanAutoLoadPaths():
for path in CoralAppData.autoLoadPaths:
scanPathForPlugins(path)
def version():
return str(CoralAppData.version)
def _notifyMessageLogged(message, verboseLevel):
for observer in CoralAppData.messageLoggedObservers.observers():
observer.setData("message", message)
observer.setData("verboseLevel", verboseLevel)
observer.notify()
def addMessageLoggedObserver(observer, callback):
CoralAppData.messageLoggedObservers.add(observer)
observer.setNotificationCallback(callback)
def addNetworkLoadedObserver(observer, callback):
CoralAppData.networkLoadedObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyNetworkLoadedObservers(topNodeName):
for observer in CoralAppData.networkLoadedObservers.observers():
observer.setData("topNodeName", topNodeName)
observer.notify()
def addNetworkLoadingObserver(observer, callback):
CoralAppData.networkLoadingObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyNetworkLoadingObservers():
for observer in CoralAppData.networkLoadingObservers.observers():
observer.notify()
def addGeneratingSaveScriptObserver(observer, callback):
CoralAppData.generatingSaveScriptObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyGeneratingSaveScriptObservers(node, saveScriptRef):
for observer in CoralAppData.generatingSaveScriptObservers.observers():
observer.setData("saveScript", saveScriptRef)
observer.setData("nodeId", node.id())
observer.notify()
def addInitializedNewNetworkObserver(observer, callback):
CoralAppData.initializedNewNetworkObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyInitializedNewNetworkObservers():
for observer in CoralAppData.initializedNewNetworkObservers.observers():
observer.notify()
def addInitializingNewNetworkObserver(observer, callback):
CoralAppData.initializingNewNetworkObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyInitializingNewNetworkObservers():
for observer in CoralAppData.initializingNewNetworkObservers.observers():
observer.notify()
def addConnectedInputObserver(observer, attribute, callback):
CoralAppData.connectedInputObservers.add(observer, subject = attribute.id())
observer.setNotificationCallback(callback)
def _notifyConnectedInputObservers(attribute):
for observer in CoralAppData.connectedInputObservers.observers(attribute.id()):
observer.notify()
def addNameChangedObserver(observer, nestedObject, callback):
CoralAppData.nameChangedObservers.add(observer, subject = nestedObject.id())
observer.setNotificationCallback(callback)
def _notifyNameChangedObservers(nestedObject):
nestedObjectId = nestedObject.id()
for observer in CoralAppData.nameChangedObservers.observers(nestedObject.id()):
observer.notify()
def addCollapsedNodeObserver(observer, callback):
CoralAppData.collapsedNodeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyCollapsedNodeObservers(collapsedNode):
for observer in CoralAppData.collapsedNodeObservers.observers():
observer.setData("collapsedNodeId", collapsedNode.id())
observer.notify()
def addAddedAttributeObserver(observer, callback):
CoralAppData.addedAttributeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyAddedAttributeObservers(parentNode, attributeAdded, input = False, output = False):
for observer in CoralAppData.addedAttributeObservers.observers():
observer.setData("parentNodeId", parentNode.id())
observer.setData("attributeAddedId", attributeAdded.id())
observer.setData("input", input)
observer.setData("output", output)
observer.notify()
def addRemovedAttributeObserver(observer, callback):
CoralAppData.removedAttributeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyRemovedAttributeObserver(parentNode, attributeRemoved):
for observer in CoralAppData.removedAttributeObservers.observers():
observer.setData("parentNodeId", parentNode.id())
observer.setData("attributeRemovedId", attributeRemoved.id())
observer.notify()
def _notifyNodeConnectionChanged(node, attribute):
for observer in CoralAppData.nodeConnectionChangedObservers.observers(node.id()):
observer.setData("attributeId", attribute.id())
observer.notify()
def addNodeConnectionChangedObserver(observer, node, callback):
CoralAppData.nodeConnectionChangedObservers.add(observer, subject = node.id())
observer.setNotificationCallback(callback)
def addAddedNodeObserver(observer, callback):
CoralAppData.addedNodeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyAddedNodeObservers(parentNode, nodeAdded):
for observer in CoralAppData.addedNodeObservers.observers():
observer.setData("parentNodeId", parentNode.id())
observer.setData("nodeAddedId", nodeAdded.id())
observer.notify()
def addRemovedNodeObserver(observer, callback):
CoralAppData.removedNodeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyRemovedNodeObservers(parentNode, nodeRemoved):
for observer in CoralAppData.removedNodeObservers.observers():
observer.setData("parentNodeId", parentNode.id())
observer.setData("nodeRemovedId", nodeRemoved.id())
observer.notify()
def addCreatedAttributeObserver(observer, callback):
CoralAppData.createdAttributeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyCreatedAttributeObservers(attribute):
for observer in CoralAppData.createdAttributeObservers.observers():
observer.setData("attributeId", attribute.id())
observer.notify()
def addAttributeSpecializedObserver(observer, attribute, callback):
CoralAppData.attributeSpecializedObservers.add(observer, subject = attribute.id())
observer.setNotificationCallback(callback)
def _notifyAttributeSpecialized(attribute):
for observer in CoralAppData.attributeSpecializedObservers.observers(attribute.id()):
observer.notify()
def addDisconnectedInputObserver(observer, attribute, callback):
CoralAppData.disconnectedInputObservers.add(observer, subject = attribute.id())
observer.setNotificationCallback(callback)
def _notifyDisconnectedInputObservers(attribute):
for observer in CoralAppData.disconnectedInputObservers.observers(attribute.id()):
observer.notify()
def addConnectedAttributesObserver(observer, callback):
CoralAppData.connectedAttributesObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyConnectedAttributesObservers(sourceAttribute, destinationAttribute):
for observer in CoralAppData.connectedAttributesObservers.observers():
observer.setData("sourceAttributeId", sourceAttribute.id())
observer.setData("destinationAttributeId", destinationAttribute.id())
observer.notify()
def addDeletingAttributeObserver(observer, callback):
CoralAppData.deletingAttributeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyDeletingAttributeObservers(attribute):
for observer in CoralAppData.deletingAttributeObservers.observers():
observer.setData("attributeId", attribute.id())
observer.notify()
def _notifyDeletingNodeObservers(node):
for observer in CoralAppData.deletingNodeObservers.observers():
observer.setData("nodeId", node.id())
observer.notify()
def addDeletingNodeObserver(observer, callback):
CoralAppData.deletingNodeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyCreatedNodeObservers(node):
for observer in CoralAppData.createdNodeObservers.observers():
observer.setData("nodeId", node.id())
observer.notify()
def addCreatedNodeObserver(observer, callback):
CoralAppData.createdNodeObservers.add(observer)
observer.setNotificationCallback(callback)
def _notifyRegisteredNodeClassesObservers(nodeClasses, tags):
for observer in CoralAppData.registeredNodeClassesObservers.observers():
observer.setData("nodeClasses", nodeClasses)
observer.setData("tags", tags)
observer.notify()
def addRegisteredNodeClassesObserver(observer, callback):
CoralAppData.registeredNodeClassesObservers.add(observer)
observer.setNotificationCallback(callback)
def nodeClasses():
return copy.copy(CoralAppData.nodeClasses)
def classNameTags():
return copy.copy(CoralAppData.classNameTags)
def setShouldLogInfos(value = True):
CoralAppData.shouldLogInfos = value
def logError(message):
exc = Exception("# error: " + str(message))
if(CoralAppData.verboseLevel >= VerboseLevel.logErrors):
print exc
_notifyMessageLogged(message, VerboseLevel.logErrors)
return exc
def logInfo(message):
if(CoralAppData.verboseLevel >= VerboseLevel.logInfos):
print "# info: " + (message)
_notifyMessageLogged(message, VerboseLevel.logInfos)
def logDebug(message):
if(CoralAppData.verboseLevel >= VerboseLevel.logDebugs):
print "# debug: " + (message)
def _instantiateNode(className, name, parent):
coralNodeClass = findNodeClass(className)
coralNode = None
if coralNodeClass.__dict__.has_key("createUnwrapped"):
coralNode = coralNodeClass.createUnwrapped(name, parent)
else:
coralNode = coralNodeClass(name, parent)
if coralNode.isInvalid():
logError("failed to create node " + className + ".\n" + coralNode.invalidityMessage())
return None
slicer = coralNode.slicer()
if not coralNode.sliceable() and slicer:
logError("This node can't be nested under a slicer node like " + slicer.className() + ", sorry : (")
return None
if coralNode.className() != className:
coralNode.setClassName(className)
coralNode._postInit()
parent.addNode(coralNode)
if hasattr(coralNode, "postInit") and CoralAppData.loadingNetwork == False:
coralNode.postInit()
CoralAppData.instantiatedNodes.append(weakref.ref(coralNode))
return coralNode
def createNode(className, name, parent):
nodeClass = findNodeClass(className)
node = None
if nodeClass:
node = _instantiateNode(className, name, parent)
if CoralAppData.appendToLastCreatedNodes:
CoralAppData.lastCreatedNodes.append(node.fullName())
else:
logError("could not find any className named '" + className + "'")
return node
def createAttribute(className, name, parent, input = False, output = False):
attr = None
if parent.allowDynamicAttributes():
attrClass = findAttributeClass(className)
if attrClass:
attr = attrClass(name, parent)
attr._setIsInput(input)
attr._setIsOutput(output)
attr._postInit()
if input:
parent.addInputAttribute(attr)
elif output:
parent.addOutputAttribute(attr)
parent.addDynamicAttribute(attr)
else:
logError("failed to create attribute, the parent node has allowDynamicAttributes set to False.")
return attr
def rootNode():
return CoralAppData.rootNode
def findNode(fullName):
names = fullName.split(".")
firstName = names.pop(0)
node = None
if firstName == rootNode().name():
node = rootNode()
for name in names:
node = node.findNode(name)
if node is None:
break
return node
def findAttribute(fullName):
names = fullName.split(".")
attrName = names.pop(-1)
fullNodeName = ".".join(names)
node = findNode(fullNodeName)
attribute = None
if node:
attribute = node.findAttribute(attrName)
return attribute
def findObject(fullName):
names = fullName.split(".")
rootName = names.pop(0)
object = None
root = rootNode()
if rootName == root.name():
object = root
for name in names:
object = object.findObject(name)
if object is None:
break
return object
def findObjectById(id):
return _coral.NetworkManager.findObjectById(id)
def registerCommandClass(className, commandClass):
CoralAppData.commandClasses[className] = commandClass
def _initCollapsedNodes():
from collapsedNode import CollapsedNode
registerNodeClass("CollapsedNode", CollapsedNode, tags = ["encapsulation"])
registerAttributeClass("PassThroughAttribute", _coral.PassThroughAttribute)
def init():
CoralAppData.rootNode = RootNode("root")
_initCollapsedNodes()
import builtinCommands
loadPluginModule(builtinCommands)
import builtinNodes
loadPluginModule(builtinNodes)
_coral.setCallback("node_created", _node_created)
_coral.setCallback("node_addNode", _node_addNode)
_coral.setCallback("node_removeNode", _node_removeNode)
_coral.setCallback("attribute_created", _attribute_created)
_coral.setCallback("attribute_connectTo", _attribute_connectTo)
_coral.setCallback("attribute_disconnectInput", _attribute_disconnectInput)
_coral.setCallback("node_addInputAttribute", _node_addInputAttribute)
_coral.setCallback("node_addOutputAttribute", _node_addOutputAttribute)
_coral.setCallback("node_removeAttribute", _node_removeAttribute)
_coral.setCallback("node_deleteIt", _node_deleteIt)
_coral.setCallback("node_connectionChanged", _node_connectionChanged)
_coral.setCallback("attribute_deleteIt", _attribute_deleteIt)
_coral.setCallback("nestedObject_setName", _nestedobject_setName)
_coral.setCallback("attribute_specialization", _attribute_specialization)
if os.environ.has_key("CORAL_PLUGINS_PATH"):
path = os.environ["CORAL_PLUGINS_PATH"]
paths = path.split(os.pathsep)
for path in paths:
addAutoLoadPath(path)
# def _attribute_valueChanged(attribute):
# _notifyAttributeValueChangedObservers(attribute)
def _nestedobject_setName(nestedObject, newName):
_notifyNameChangedObservers(nestedObject)
def _attribute_deleteIt(attribute):
_notifyDeletingAttributeObservers(attribute)
def _node_deleteIt(node):
nodeRef = weakref.ref(node)
if nodeRef in CoralAppData.instantiatedNodes:
del CoralAppData.instantiatedNodes[CoralAppData.instantiatedNodes.index(nodeRef)]
_notifyDeletingNodeObservers(node)
def _node_addOutputAttribute(parentNode, attributeAdded):
_notifyAddedAttributeObservers(parentNode, attributeAdded, output = True)
def _node_removeAttribute(parentNode, attributeRemoved):
_notifyRemovedAttributeObserver(parentNode, attributeRemoved)
def _node_connectionChanged(node, attribute):
_notifyNodeConnectionChanged(node, attribute)
def _node_addInputAttribute(parentNode, attributeAdded):
_notifyAddedAttributeObservers(parentNode, attributeAdded, input = True)
def _node_addNode(parentNode, nodeAdded):
_notifyAddedNodeObservers(parentNode, nodeAdded)
def _node_removeNode(parentNode, nodeRemoved):
_notifyRemovedNodeObservers(parentNode, nodeRemoved)
def _attribute_created(attribute):
_notifyCreatedAttributeObservers(attribute)
def _attribute_specialization(attribute):
_notifyAttributeSpecialized(attribute)
def _attribute_disconnectInput(attribute):
_notifyDisconnectedInputObservers(attribute)
def _node_created(node):
_notifyCreatedNodeObservers(node)
def _attribute_connectTo(sourceAttribute, destinationAttribute):
_notifyConnectedAttributesObservers(sourceAttribute, destinationAttribute)
_notifyConnectedInputObservers(destinationAttribute)
def loadPluginModule(pluginModule):
plugin = pluginModule.loadPlugin()
for nodeClassDict in plugin._registeredNodes:
className = nodeClassDict["className"]
nodeClass = nodeClassDict["nodeClass"]
tags = nodeClassDict["tags"]
description = nodeClassDict["description"]
registerNodeClass(className, nodeClass, tags, description)
for attrClassDict in plugin._registeredAttributes:
className = attrClassDict["className"]
attributeClass = attrClassDict["attributeClass"]
registerAttributeClass(className, attributeClass)
for commandClass in plugin._registeredCommands:
registerCommandClass(commandClass.__name__, commandClass)
if plugin._registeredNodes:
_notifyRegisteredNodeClassesObservers(CoralAppData.nodeClasses, CoralAppData.classNameTags)
def loadPlugin(filename):
searchPaths = ["", os.getcwd()]
found = False
for searchPath in searchPaths:
path = os.path.join(searchPath, filename)
if os.path.isfile(path):
found = True
module = None
try:
module = utils.runtimeImport(filename)
except:
logError("skipping plugin " + str(filename))
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback, limit = 2, file = sys.stdout)
if module:
if hasattr(module, "loadPlugin"):
found = True
loadPluginModule(module)
else:
logError("no loadPlugin function found in file " + str(filename))
break
if not found:
logError("could not find file " + str(filename))
def finalize():
_coral.setCallback("node_created", None)
_coral.setCallback("node_addNode", None)
_coral.setCallback("node_removeNode", None)
_coral.setCallback("attribute_created", None)
_coral.setCallback("attribute_connectTo", None)
_coral.setCallback("attribute_disconnectInput", None)
_coral.setCallback("node_addInputAttribute", None)
_coral.setCallback("node_addOutputAttribute", None)
_coral.setCallback("node_deleteIt", None)
_coral.setCallback("attribute_deleteIt", None)
_coral.setCallback("nestedObject_setName", None)
_coral.setCallback("attribute_specialization", None)
_coral.setCallback("attribute_valueChanged", None)
CoralAppData.rootNode.deleteIt()
CoralAppData.rootNode = None
def _setClassNameTag(className, tag):
if CoralAppData.classNameTags.has_key(tag) == False:
CoralAppData.classNameTags[tag] = []
if className not in CoralAppData.classNameTags[tag]:
CoralAppData.classNameTags[tag].append(className)
def registerNodeClass(className, nodeClass, tags = [], description = ""):
CoralAppData.nodeClasses[className] = nodeClass
if not description:
description = "Does what its name says...hopefully."
CoralAppData.registeredNodeDescriptions[className] = description
for tag in tags:
_setClassNameTag(className, tag)
def registerAttributeClass(className, coralAttributeClass):
CoralAppData.attributeClasses[className] = coralAttributeClass
def findNodeClass(className):
nodeClass = None
if CoralAppData.nodeClasses.has_key(className):
nodeClass = CoralAppData.nodeClasses[className]
return nodeClass
def findAttributeClass(className):
attrClass = None
if CoralAppData.attributeClasses.has_key(className):
attrClass = CoralAppData.attributeClasses[className]
return attrClass
def collapseNodes(nodes, collapsedNode = None):
import collapser
if collapsedNode:
if collapsedNode.__class__.__name__ != "CollapsedNode":
logError("invalid collapsedNode passed as argument")
return None
collapsedNode = collapser.collapseNodes(nodes, collapsedNode)
_notifyCollapsedNodeObservers(collapsedNode)
return collapsedNode
def explodeCollapsedNode(collapsedNode):
import collapser
extractedNodes = collapser.explodeCollapsedNode(collapsedNode)
collapsedNode.deleteIt()
return extractedNodes
def _setCommandArgs(command, args):
for argName in command.argNames():
if args.has_key(argName):
arg = args[argName]
argType = command.argType(argName)
if argType == _coral.Command.boolType:
command.setArgBool(argName, arg)
elif argType == _coral.Command.intType:
command.setArgInt(argName, arg)
elif argType == _coral.Command.floatType:
command.setArgFloat(argName, arg)
elif argType == _coral.Command.stringType:
command.setArgString(argName, arg)
elif argType == _coral.Command.undefinedType:
command.setArgUndefined(argName, str(arg))
#else:
# raise Exception("Could not find expected args for command " + command.name() + ",\nexpected " + str(command.argNames()) + ",\npassed " + str(args.keys()))
def _getCommandResult(command):
result = None
resultType = command.resultType()
if resultType != _coral.Command.undefinedType:
if resultType == _coral.Command.boolType:
result = command.resultAsBool()
elif resultType == _coral.Command.intType:
result = command.resultAsInt()
elif resultType == _coral.Command.floatType:
result = command.resultAsFloat()
elif resultType == _coral.Command.stringType:
result = command.resultAsString()
return result
def _executeCommand(cmdName, redo, **args):
result = None
if CoralAppData.commandClasses.has_key(cmdName):
commandClass = CoralAppData.commandClasses[cmdName]
command = commandClass()
command.setName(cmdName)
_setCommandArgs(command, args)
if CoralAppData.shouldLogInfos:
print command.asScript()
command.doIt()
result = _getCommandResult(command)
if len(CoralAppData.executedCommands) > CoralAppData.undoLimit:
CoralAppData.executedCommands.pop(0)
if CoralAppData.undoLimit:
CoralAppData.executedCommands.append(command)
if not redo:
CoralAppData.undoneCommands = []
else:
raise Exception("could not find any commad named " + str(cmdName))
return result
def setUndoLimit(limit):
CoralAppData.undoLimit = limit
def undo():
if CoralAppData.executedCommands:
lastCommand = CoralAppData.executedCommands.pop(-1)
lastCommand.undoIt()
CoralAppData.undoneCommands.append(lastCommand)
if CoralAppData.shouldLogInfos:
print "# Undo: " + lastCommand.asScript()
else:
print "# nothing to be undone"
def redo():
if CoralAppData.undoneCommands:
lastUndone = CoralAppData.undoneCommands.pop(-1)
_executeCommand(lastUndone.name, True, **lastUndone.args)
def executeCommand(cmdName, **args):
return _executeCommand(cmdName, False, **args)
def deleteNodes(nodes):
for node in nodes:
node.deleteIt()
def deleteAttributes(attributes):
for attribute in attributes:
parentNode = attribute.parent()
if attribute in parentNode.dynamicAttributes():
attribute.deleteIt()
def _parseNetworkScript(saveScript):
#returns the variables collected in the saveScript.
# required variables
version = -1.0
exec(saveScript)
return locals() # this builtin function returns the vars in this function (and those collected executing the saveScript
def _loadNetworkScript(networkScript, topNode = ""):
_notifyNetworkLoadingObservers()
networkScriptData = _parseNetworkScript(networkScript)
if networkScriptData["version"] > CoralAppData.version:
logError("version mismatch")
return;
CoralAppData.loadingNetwork = True
networkScriptData["runScript"](topNode)
CoralAppData.loadingNetwork = False
_notifyNetworkLoadedObservers(topNode)
def openNetworkFile(filename):
if filename:
newNetwork()
file = open(filename, "rU")
saveScript = file.read()
file.close()
filePath = os.path.split(filename)[0]
CoralAppData.currentNetworkDir = filePath
_coral.NetworkManager.addSearchPath(filePath)
_loadNetworkScript(saveScript, topNode = CoralAppData.rootNode.fullName())
if CoralAppData.shouldLogInfos:
logInfo("loaded netowrk file: " + filename)
def _generateNetworkScript(topNode, saveTopNode = False):
saveScript = "# coral save script\n" # idiotic comment to make this file look cool ; )
saveScript += "version = 0.1\n" # version to guarantee retro compatibility when necessary
saveScript += "\n"
saveScript += "def runScript(topNode = 'root'):\n" # open a string that will contain the actual script to regenerate the scene
runScript = ""
if saveTopNode:
runScript += topNode.asScript()
runScript += topNode.contentAsScript()
saveScriptRef = [""] #guarantees this string is referenced reather than copied
_notifyGeneratingSaveScriptObservers(topNode, saveScriptRef)
runScript += saveScriptRef[0]
# replace the full name of the parent with a variable that can be set at load time
parent = ""
if saveTopNode:
parent = topNode.parent().fullName()
else:
parent = topNode.fullName()
runScript = runScript.replace("'" + parent, "topNode + '")
runScript = runScript.replace("topNode + ''", "topNode")
# indent script to be run inside runScript() function
lines = runScript.split("\n")
for line in lines:
saveScript += " " + line + "\n"
return saveScript
def saveNetworkFile(filename):
if filename:
saveScript = _generateNetworkScript(topNode = CoralAppData.rootNode)
file = open(filename, "w")
file.write(saveScript)
file.close()
if CoralAppData.shouldLogInfos:
logInfo("saved network file: " + filename)
def newNetwork():
_notifyInitializingNewNetworkObservers()
CoralAppData.rootNode = RootNode("root")
_coral.NetworkManager.removeSearchPath(CoralAppData.currentNetworkDir)
CoralAppData.currentNetworkDir = ""
_notifyInitializedNewNetworkObservers()
def _convertCollapsedNodeToScript(collapsedNode):
className = collapsedNode.name().replace(" ", "_")
if className in CoralAppData.nodeClasses.keys():
className = className + "_"
script = ""
script += "from coral.collapsedNode import CollapsedNode\n"
script += "from coral.coralApp import *\n"
script += "\n"
script += "class " + className + "(CollapsedNode):\n"
script += " def __init__(self, name, parent):\n"
script += " CollapsedNode.__init__(self, name, parent)\n"
script += " self.setClassName('"+ className + "')\n"
script += "\n"
script += " def postInit(self):\n"
script += " topNode = self.fullName()\n"
nodeScript = collapsedNode._attributesAsScript()
nodeScript += collapsedNode.contentAsScript()
saveScriptRef = [""]
_notifyGeneratingSaveScriptObservers(collapsedNode, saveScriptRef)
nodeScript += "\n"
nodeScript += saveScriptRef[0]
parent = collapsedNode.fullName()
nodeScript = nodeScript.replace("'" + parent, "topNode + '")
nodeScript = nodeScript.replace("topNode + ''", "topNode")
for line in nodeScript.split("\n"):
script += " " + line + "\n"
script += "def loadPlugin():\n"
script += " from coral.plugin import Plugin\n"
script += " \n"
script += " plugin = Plugin('" + className + "_plugin')\n"
script += " plugin.registerNode('" + className + "', " + className + ", tags = ['collapsed nodes'])\n"
script += " \n"
script += " return plugin\n"
script += "\n"
return script
def saveCollapsedNodeFile(collapsedNode, filename):
script = _convertCollapsedNodeToScript(collapsedNode)
file = open(filename, "w")
file.write(script)
file.close()
if CoralAppData.shouldLogInfos:
logInfo("saved collapsedNode file: " + filename)
path = os.path.split(filename)[0]
if path in CoralAppData.autoLoadPaths:
scanPathForPlugins(path)
def importCollapsedNodeFile(filename, topNode):
if filename:
file = open(filename, "rU")
saveScript = file.read()
file.close()
saveScriptData = _parseNetworkScript(saveScript)
if saveScriptData["version"] != CoralAppData.version:
logError("version mismatch")
return;
if not saveScriptData.has_key("collapsedNodeFile"):
if saveScriptData["collapsedNodeFile"] != True:
logError("not a CollapsedNode file")
return
saveScriptData["runScript"](topNode = topNode.fullName())
if CoralAppData.shouldLogInfos:
logInfo("loaded netowrk file: " + filename)
def connectAttributes(sourceAttribute, destinationAttribute):
_coral.NetworkManager.connect(sourceAttribute, destinationAttribute)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import _coral
## A node to enclose other nodes and provide a simplified interface to a more complex network.
#@implements Node
class CollapsedNode(_coral.Node):
def __init__(self, name, parent):
_coral.Node.__init__(self, name, parent)
self.setClassName("CollapsedNode")
self._setSliceable(True)
self._setUpdateEnabled(False)
self._setAllowDynamicAttributes(True)
def _attributesAsScript(self):
script = ""
createAttributeCmd = _coral.Command()
createAttributeCmd.setName("CreateAttribute")
createAttributeCmd.setArgString("className", "PassThroughAttribute")
createAttributeCmd.setArgString("name", "")
createAttributeCmd.setArgString("parentNode", self.fullName())
createAttributeCmd.setArgBool("input", False)
createAttributeCmd.setArgBool("output", False)
for attribute in self.inputAttributes():
createAttributeCmd.setArgString("name", attribute.name())
createAttributeCmd.setArgBool("input", True)
createAttributeCmd.setArgBool("output", False)
script += createAttributeCmd.asScript() + "\n"
for attribute in self.outputAttributes():
createAttributeCmd.setArgString("name", attribute.name())
createAttributeCmd.setArgBool("input", False)
createAttributeCmd.setArgBool("output", True)
script += createAttributeCmd.asScript() + "\n"
return script | Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
# init Imath module, don't remove
import Imath
from _coral import *
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import coralApp
import utils
from _coral import NetworkManager
class CollapserData:
collapsedNodeClassName = "CollapsedNode"
def setCollapsedNodeClassName(className):
CollapserData.collapsedNodeClassName = className
def _checkNodesShareSameParent(nodes):
parentNode = None
for node in nodes:
if parentNode is None:
parentNode = node.parent()
if parentNode is not node.parent():
raise Exception("the nodes being collapsed must be under the same parent")
return parentNode
def _disconnectConnectedInputs(node, nodes):
inputAttrs = [[], []]
for attr in node.inputAttributes():
inputAttr = attr.input()
if inputAttr:
if inputAttr.parent() not in nodes:
inputAttrs[0].append([inputAttr, attr])
attr.disconnectInput()
return inputAttrs
def _disconnectConnectedOutputs(node, nodes):
outputAttrs = []
for attr in node.outputAttributes():
outAttrs = attr.outputs()
for outAttr in outAttrs:
if outAttr.parent() not in nodes:
outputAttrs.append([attr, outAttr])
outAttr.disconnectInput()
return outputAttrs
def collapseNodes(nodes, collapsedNode = None):
parentNode = _checkNodesShareSameParent(nodes)
if collapsedNode is None:
collapsedNode = coralApp.createNode(CollapserData.collapsedNodeClassName, CollapserData.collapsedNodeClassName, parentNode)
inPassAttrs = {}
outPassAttrs = {}
for node in nodes:
disconnectedAttributes = _disconnectConnectedInputs(node, nodes)
inputAttributes = disconnectedAttributes[0]
inputAttributesWithOutputConnections = disconnectedAttributes[1]
outputAttributes = _disconnectConnectedOutputs(node, nodes)
parentNode.removeNode(node)
collapsedNode.addNode(node)
for attr in inputAttributes:
sourceAttr = attr[0]
destAttr = attr[1]
passAttrName = sourceAttr.parent().name() + "_" + sourceAttr.name()
if inPassAttrs.has_key(passAttrName) == False:
passAttr = coralApp.createAttribute("PassThroughAttribute", "input", collapsedNode, input = True)
NetworkManager.connect(sourceAttr, passAttr)
inPassAttrs[passAttrName] = passAttr
else:
passAttr = inPassAttrs[passAttrName]
NetworkManager.connect(passAttr, destAttr)
for attr in outputAttributes:
sourceAttr = attr[0]
destAttr = attr[1]
passAttrName = sourceAttr.parent().name() + "_" + sourceAttr.name()
if outPassAttrs.has_key(passAttrName) == False:
passAttr = coralApp.createAttribute("PassThroughAttribute", "output", collapsedNode, output = True)
NetworkManager.connect(sourceAttr, passAttr)
outPassAttrs[passAttrName] = passAttr
else:
passAttr = outPassAttrs[passAttrName]
NetworkManager.connect(passAttr, destAttr)
return collapsedNode
def explodeCollapsedNode(collapsedNode):
parentNode = collapsedNode.parent()
extractedNodes = collapsedNode.nodes()
if parentNode:
connections = []
for attribute in collapsedNode.attributes():
input = attribute.input()
outputs = attribute.outputs()
if input and outputs:
connections.append([input, outputs])
if input:
attribute.disconnectInput()
for output in outputs:
output.disconnectInput()
for node in collapsedNode.nodes():
collapsedNode.removeNode(node)
parentNode.addNode(node)
for connection in connections:
source = connection[0]
dests = connection[1]
for dest in dests:
NetworkManager.connect(source, dest)
else:
raise coralApp.logError("collapsedNode has no parent to explode onto.")
return extractedNodes
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
import os
import shutil
import compileall
import sconsUtils
sconsUtils.importBuildEnvs()
os.environ["CORAL_BUILD_MODE"] = "DEBUG"
if ARGUMENTS.get("mode", 0) == "release":
print "* Building standalone app in release mode"
os.environ["CORAL_BUILD_MODE"] = "RELEASE"
else:
print "* Building standalone dev tree in debug mode"
buildMode = os.environ["CORAL_BUILD_MODE"]
installDir = ARGUMENTS.get("install-dir", 0)
if not installDir:
installDir = os.path.join(os.getcwd(), "build", "coralStandaloneBuild")
print "* Install Dir = " + installDir
sdkInstallDir = ""
buildSdk = False
if buildMode == "RELEASE":
buildSdk = True
elif ARGUMENTS.get("build-sdk", 0) == "1":
buildSdk = True
sdkInstallDir = ARGUMENTS.get("sdk-install-dir", 0)
if not sdkInstallDir:
sdkInstallDir = os.path.join(installDir, "sdk")
if buildSdk:
print "* Build Sdk = true"
print "* Sdk Install Dir = " + sdkInstallDir
coralLib = SConscript(os.path.join("coral", "SConstruct"))
coralUiLib = SConscript(os.path.join("coralUi", "SConstruct"), exports = {"coralLib": coralLib})
imathLib = SConscript(os.path.join("imath", "SConstruct"))
def buildSdkHeaders(buildDir):
coralIncludesDir = os.path.join(buildDir, "coral", "includes", "coral")
coralUiIncludesDir = os.path.join(buildDir, "coralUi", "includes", "coralUi")
os.makedirs(coralIncludesDir)
os.makedirs(coralUiIncludesDir)
coralHeaders = sconsUtils.findFiles(os.path.join("coral", "src"), pattern = "*.h")
for header in coralHeaders:
file = open(header)
fileContent = file.read()
file.close()
if "CORAL_EXPORT" in fileContent:
shutil.copy(header, coralIncludesDir)
coralUiHeaders = sconsUtils.findFiles(os.path.join("coralUi", "src"), pattern = "*.h")
for header in coralUiHeaders:
file = open(header)
fileContent = file.read()
file.close()
if "CORALUI_EXPORT" in fileContent:
shutil.copy(header, coralUiIncludesDir)
shutil.copytree(sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"), os.path.join(buildDir, "Imath", "includes"))
shutil.copytree(sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH"), os.path.join(buildDir, "boost", "includes", "boost"))
def buildSdkLibs(coralLib, coralUiLib, buildDir):
coralLibsDir = os.path.join(buildDir, "coral", "libs")
coralUiLibsDir = os.path.join(buildDir, "coralUi", "libs")
imathLibsDir = os.path.join(buildDir, "Imath", "libs")
boostLibsDir = os.path.join(buildDir, "boost", "libs")
os.makedirs(coralLibsDir)
os.makedirs(coralUiLibsDir)
os.makedirs(imathLibsDir)
os.makedirs(boostLibsDir)
targetCoralLibName = str(SharedLibrary("coral")[0])
targetCoralUiLibName = str(SharedLibrary("coralUi")[0])
sourceCoralLibName = os.path.split(coralLib)[-1]
sourceCoralUiLibName = os.path.split(coralUiLib)[-1]
os.symlink(os.path.join(os.pardir, os.pardir, os.pardir, "coral", sourceCoralLibName), os.path.join(coralLibsDir, targetCoralLibName))
os.symlink(os.path.join(os.pardir, os.pardir, os.pardir, "coral", "coralUi", sourceCoralUiLibName), os.path.join(coralUiLibsDir, targetCoralUiLibName))
ImathLibName = str(SharedLibrary(sconsUtils.getEnvVar("CORAL_IMATH_LIB"))[0])
ImathIexLibName = str(SharedLibrary(sconsUtils.getEnvVar("CORAL_IMATH_IEX_LIB"))[0])
boostPythonLibName = str(SharedLibrary(sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB"))[0])
ImathLib = os.path.join(sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"), ImathLibName)
ImathIexLib = os.path.join(sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"), ImathIexLibName)
boostPythonLib = os.path.join(sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"), boostPythonLibName)
shutil.copy(ImathLib, imathLibsDir)
shutil.copy(ImathIexLib, imathLibsDir)
shutil.copy(boostPythonLib, boostLibsDir)
if sys.platform == "darwin":
sconsUtils.autoFixDynamicLinks(os.path.join(imathLibsDir, ImathLibName))
sconsUtils.autoFixDynamicLinks(os.path.join(imathLibsDir, ImathIexLibName))
sconsUtils.autoFixDynamicLinks(os.path.join(boostLibsDir, boostPythonLibName))
def buildSdkTree(coralLib, coralUiLib, buildDir):
print "* Building sdk..."
shutil.rmtree(buildDir, ignore_errors = True)
buildSdkHeaders(buildDir)
buildSdkLibs(coralLib, coralUiLib, buildDir)
def buildMainTree(coralLib, coralUiLib, imathLib, buildDir):
if sys.platform == "darwin":
# fix lib link path on Mac Os X
sconsUtils.autoFixDynamicLinks(coralLib)
sconsUtils.autoFixDynamicLinks(coralUiLib)
sconsUtils.autoFixDynamicLinks(imathLib)
shutil.copytree(os.path.join("coral", "py"), buildDir)
shutil.copy(coralLib, os.path.join(buildDir, "coral"))
shutil.copy(imathLib, buildDir)
shutil.copytree(os.path.join("coralUi", "py", "coralUi"), os.path.join(buildDir, "coral", "coralUi"))
shutil.copy(coralUiLib, os.path.join(buildDir, "coral", "coralUi"))
pycFiles = sconsUtils.findFiles(os.path.join(buildDir), pattern = "*.pyc")
for pycFile in pycFiles:
os.remove(pycFile)
compileall.compile_dir(buildDir, quiet = True)
if buildSdk:
buildSdkTree(coralLib, coralUiLib, sdkInstallDir)
def buildDevTree(coralLib, coralUiLib, imathLib):
shutil.rmtree(installDir, ignore_errors = True)
buildMainTree(coralLib, coralUiLib, imathLib, installDir)
def buildOsXApp(coralLib, coralUiLib, imathLib):
print "* building app bundle"
# clean
buildDir = os.path.join("build", "coralStandaloneApp")
shutil.rmtree(buildDir, ignore_errors = True)
# make dirs
os.mkdir(buildDir)
appBundle = os.path.join(buildDir, "CoralStandalone.app")
os.mkdir(appBundle)
contentsDir = os.path.join(appBundle, "Contents")
os.mkdir(contentsDir)
resourcesDir = os.path.join(contentsDir, "Resources")
os.mkdir(resourcesDir)
global sdkInstallDir
sdkInstallDir = os.path.join(contentsDir, "sdk")
buildMainTree(coralLib, coralUiLib, imathLib, os.path.join(contentsDir, "coral"))
# copy stuff over
shutil.copy(os.path.join("resources", "macAppBundle", "Info.plist"), contentsDir)
shutil.copy(os.path.join("resources", "macAppBundle", "PkgInfo"), contentsDir)
macOsDir = os.path.join(contentsDir, "MacOS")
os.mkdir(macOsDir)
shutil.copy(os.path.join("resources", "macAppBundle", "CoralStandalone"), macOsDir)
for envName in os.environ.keys():
if envName.startswith("CORAL_Qt"):
qtLib = os.environ[envName]
shutil.copy(qtLib, macOsDir)
shutil.copy("/usr/local/lib/libboost_filesystem.dylib", macOsDir)
shutil.copy("/usr/local/lib/libboost_regex.dylib", macOsDir)
shutil.copy("/usr/local/lib/libboost_system.dylib", macOsDir)
shutil.copy("/usr/local/lib/libboost_thread.dylib", macOsDir)
shutil.copy("/usr/local/lib/libHalf.6.dylib", macOsDir)
shutil.copy("/usr/local/lib/libIex.6.dylib", macOsDir)
shutil.copy("/usr/local/lib/libImath.6.dylib", macOsDir)
shutil.copy("/usr/local/lib/libIlmThread.6.dylib", macOsDir)
shutil.copy("/usr/X11/lib/libpng15.15.dylib", macOsDir)
shutil.copy("/usr/local/lib/libtiff.5.dylib", macOsDir)
shutil.copy("/usr/local/lib/libjpeg.8.dylib", macOsDir)
shutil.copy("/usr/local/lib/libIlmImf.6.dylib", macOsDir)
glewLib = os.path.join(sconsUtils.getEnvVar("CORAL_GLEW_LIBS_PATH"), "lib" + sconsUtils.getEnvVar("CORAL_GLEW_LIB") + ".dylib")
shutil.copy(glewLib, macOsDir)
openImageIoLib = os.path.join(sconsUtils.getEnvVar("CORAL_OIIO_LIBS_PATH"), "lib" + sconsUtils.getEnvVar("CORAL_OIIO_LIB") + ".dylib")
shutil.copy(openImageIoLib, macOsDir)
tbbLib = os.path.join(sconsUtils.getEnvVar("CORAL_TBB_LIBS_PATH"), "lib" + sconsUtils.getEnvVar("CORAL_TBB_LIB") + ".dylib")
shutil.copy(tbbLib, macOsDir)
boostPythonLib = os.path.join(sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH"), "lib" + sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB") + ".dylib")
shutil.copy(boostPythonLib, macOsDir)
qtUiPath = os.path.split(sconsUtils.getEnvVar("CORAL_QtGui_LIB"))[0]
qtnib = os.path.join(qtUiPath, "Resources", "qt_menu.nib")
shutil.copytree(qtnib, os.path.join(resourcesDir, "qt_menu.nib"))
os.system("chmod +x " + os.path.join(macOsDir, "coralStandalone"))
shutil.copy(os.path.join("resources", "macAppBundle", "coral.icns"), resourcesDir)
pythonVersion = os.path.split(sconsUtils.getEnvVar("CORAL_PYTHON_PATH"))[-1]
pythonFrameworkDir = os.path.join(contentsDir, "Frameworks", "Python.framework", "Versions", pythonVersion)
shutil.copytree(sconsUtils.getEnvVar("CORAL_PYTHON_PATH"), pythonFrameworkDir)
shutil.copy(os.path.join(contentsDir, "Frameworks", "Python.framework", "Versions", pythonVersion, "Resources/Python.app/Contents/MacOS/Python-64"), os.path.join(macOsDir, "python"))
# fix dylib links
libs = sconsUtils.findFiles(macOsDir, pattern = "*.dylib")
libs.extend(sconsUtils.findFiles(macOsDir, pattern = "Qt*"))
libs.extend(sconsUtils.findFiles(os.path.join(pythonFrameworkDir, "lib", "python" + pythonVersion, "site-packages", "PyQt4"), pattern = "*.so"))
for lib in libs:
sconsUtils.autoFixDynamicLinks(lib)
def buildApp(coralLib, coralUiLib, imathLib):
if sys.platform == "darwin":
buildOsXApp(coralLib, coralUiLib, imathLib)
def postBuildAction(target, source, env):
coralLib = str(source[0])
coralUiLib = str(source[1])
imathLib = str(source[2])
if buildMode == "RELEASE":
buildApp(coralLib, coralUiLib, imathLib)
else:
buildDevTree(coralLib, coralUiLib, imathLib)
postBuildTarget = Command("postBuildTarget", [coralLib[0], coralUiLib[0], imathLib[0]], postBuildAction)
Default(postBuildTarget)
| Python |
# <license>
# Copyright (C) 2011 Andrea Interguglielmi, All rights reserved.
# This file is part of the coral repository downloaded from http://code.google.com/p/coral-repo.
#
# 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.
#
# 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.
# </license>
import sys
import os
import platform
import sconsUtils
import SCons
sconsUtils.importBuildEnvs()
def buildEnv():
env = SCons.Environment.Environment()
if sys.platform.startswith("win"):
coralLib = coralLib[1]
env.Append(
CPPPATH = [
sconsUtils.getEnvVar("CORAL_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORALUI_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_IMATH_INCLUDES_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_INCLUDES_PATH")])
env.Append(
LIBS = [
"coral",
"coralUi",
sconsUtils.getEnvVar("CORAL_IMATH_LIB"),
sconsUtils.getEnvVar("CORAL_IMATH_IEX_LIB"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIB"),
sconsUtils.getEnvVar("CORAL_BOOST_PYTHON_LIB")])
env.Append(
LIBPATH = [
sconsUtils.getEnvVar("CORAL_LIBS_PATH"),
sconsUtils.getEnvVar("CORALUI_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_IMATH_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_PYTHON_LIBS_PATH"),
sconsUtils.getEnvVar("CORAL_BOOST_LIBS_PATH")])
env["SHLIBPREFIX"] = ""
env["TARGET_ARCH"] = platform.machine()
if sys.platform.startswith("linux"):
pass
elif sys.platform == "darwin":
env["SHLIBSUFFIX"] = ".so"
env["FRAMEWORKS"] = ["OpenGL"]
elif sys.platform.startswith("win"):
env.Append(CPPPATH = sconsUtils.getEnvVar("CORAL_OPENGL_INCLUDES_PATH"))
env.Append(LIBS = sconsUtils.getEnvVar("CORAL_OPENGL_LIB"))
env.Append(LIBPATH = sconsUtils.getEnvVar("CORAL_OPENGL_LIBS_PATH"))
env["SHLIBSUFFIX"] = ".pyd"
env["CXXFLAGS"] = Split("/Zm800 -nologo /EHsc /DBOOST_PYTHON_DYNAMIC_LIB /Z7 /Od /Ob0 /GR /MD /wd4675 /Zc:forScope /Zc:wchar_t")
env["CCFLAGS"] = "-DCORAL_UI_COMPILE"
env["LINKFLAGS"] = ["/MANIFEST:NO"]
return env
def _postBuildAction(target, source, env):
if sys.platform == "darwin":
# fix lib link path on Mac Os X
dylib = str(source[0])
sconsUtils.autoFixDynamicLinks(dylib)
def buildModule(moduleName, sourceFles, env = None):
if env is None:
env = buildEnv()
target = env.SharedLibrary(
target = moduleName,
source = sourceFles,
OBJPREFIX = os.path.join("debug", ""))
postBuildTarget = env.Command("postBuildTarget", target[0], _postBuildAction)
env.Default(postBuildTarget)
return target | Python |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# coding : utf-8
# author : binux(17175297.hk@gmail.com)
from sinastock import *
#!/usr/bin/env python
# encoding: utf-8
"""
Created by Eric Lo on 2010-05-20.
Copyright (c) 2010 __lxneng@gmail.com__. http://lxneng.com All rights reserved.
"""
class Pinyin():
def __init__(self, data_path='./Mandarin.dat'):
self.dict = {}
for line in open(data_path):
k, v = line.split('\t')
self.dict[k] = v
self.splitter = ''
def get_pinyin(self, chars=u"你好吗"):
result = []
for char in chars:
key = "%X" % ord(char)
try:
# print self.dict[key].split(" ")[0][0]#.strip()#[:-1]
# result.append(self.dict[key].split(" ")[0].strip()[:-1].lower())
result.append(self.dict[key].split(" ")[0][0])
except:
# print char
result.append(char)
return self.splitter.join(result)
def get_initials(self, char=u'你'):
try:
return self.dict["%X" % ord(char)].split(" ")[0][0]
except:
return char
if __name__ == '__main__':
print 'start'
p = Pinyin()
print p.get_pinyin(u"*st上海昱")
sina=SINAStock()
slist=sina.getHKstocklistfromSINA()
print slist
for s in slist.keys():
print slist[s],p.get_pinyin(slist[s])
#def getFirstPY(word, encoding='utf-8'):
# if isinstance(word, unicode):
# try:
# word = word[0].encode('gbk')
# except:
# return '?'
# elif isinstance(word, str):
# try:
# word = word.decode(encoding)[0].encode('gbk')
# except:
# return '?'
#
# if len(word) == 1:
# return word
# else:
# asc = ord(word[0])*256 + ord(word[1]) - 65536
# print asc
# if asc >= -20319 and asc <= -20284:
# return 'a'
# if asc >= -20283 and asc <= -19776:
# return 'b'
# if asc >= -19775 and asc <= -19219:
# return 'c'
# if asc >= -19218 and asc <= -18711:
# return 'd'
# if asc >= -18710 and asc <= -18527:
# return 'e'
# if asc >= -18526 and asc <= -18240:
# return 'f'
# if asc >= -18239 and asc <= -17923:
# return 'g'
# if asc >= -17922 and asc <= -17418:
# return 'h'
# if asc >= -17417 and asc <= -16475:
# return 'j'
# if asc >= -16474 and asc <= -16213:
# return 'k'
# if asc >= -16212 and asc <= -15641:
# return 'l'
# if asc >= -15640 and asc <= -15166:
# return 'm'
# if asc >= -15165 and asc <= -14923:
# return 'n'
# if asc >= -14922 and asc <= -14915:
# return 'o'
# if asc >= -14914 and asc <= -14631:
# return 'p'
# if asc >= -14630 and asc <= -14150:
# return 'q'
# if asc >= -14149 and asc <= -14091:
# return 'r'
# if asc >= -14090 and asc <= -13119:
# return 's'
# if asc >= -13118 and asc <= -12839:
# return 't'
# if asc >= -12838 and asc <= -12557:
# return 'w'
# if asc >= -12556 and asc <= -11848:
# return 'x'
# if asc >= -11847 and asc <= -11056:
# return 'y'
# if asc >= -11055 and asc <= -10247:
# return 'z'
# return '?'
#
#def getPY(string, encoding="utf-8"):
# if isinstance(string, str):
# string = string.decode(encoding)
#
# result = []
# for each in string:
# result.append(getFirstPY(each))
# return "".join(result)
#if __name__ == '__main__':
# print getPY('昱')
| Python |
'''
Created on 2011-11-21
@author: Administrator
'''
import urllib2
import datetime
class BBStock():
def stocklist(self,reg):
pass
def getAstocklistfrombloomberg(self):
def parseonestock(src):
nlist=src.split('<td')
ret=[]
for n in nlist:
p=n.find('</td')
k=n.rfind('</span',0,p)
if k>0:p=k
s=n.rfind('>',0,p)
v=n[s:p].strip('>\n\t ')
if len(v)>0: ret.append(v)
return ret
pass
def getonepage(page=1):
url='http://www.bloomberg.com/markets/companies/country/china/'+str(page)+'/'
content=urllib2.urlopen(url).read()
s=content.find('<table class="ticker_data">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist=[]
for n in nlist:
ret=parseonestock(n)
if len(ret)>0:stocklist.append(ret)
return stocklist
stocklist=[]
tlist=[]
page=1
tlist=getonepage(page)
for t in tlist:
stocklist.append(t)
print "page:",page," tlist len:",len(tlist)
while len(tlist)==200:
page=page+1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
for t in tlist:
stocklist.append(t)
return stocklist
if __name__ == '__main__':
starttime=datetime.datetime.now()
bb=BBStock()
result=bb.getAstocklistfrombloomberg()
print len(result)
print starttime,(datetime.datetime.now()-starttime).seconds
pass | Python |
# -*- coding: utf-8 -*-
'''
Created on 2011-11-23
@author: Administrator
'''
from sinastock import *
import urllib2
import simplejson
import os
import urllib2
import sqlite3
import datetime
import threading
import Queue
import time
import shutil
from setting import *
def myfloat(src):
if len(src.strip())==0:return 0
if len(src.replace('-','').strip())==0:return 0
# print src
return float(src)
class ThreadStockDataDownload(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue=urlqueue
def run(self):
code=self.queue.get()
url='http://stockdata.stock.hexun.com/2009_cgjzd_'+code[2:8]+'.shtml'
# print url
req = urllib2.Request(url)
req.add_header('host', 'stockdata.stock.hexun.com')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1')
req.add_header('Accept-Language', 'zh-cn,zh;q=0.5')
req.add_header('Accept-Encoding', 'gzip, deflate')
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
try:
content=urllib2.urlopen(url).read()
except:
print '[x]',url
fname=os.path.join(errordatapath,code)
f=open(fname,'w')
# f.write(content)
f.close()
self.queue.task_done()
return
if content[:5]=='Error':
print '[r]',#url
fname=os.path.join(errordatapath,code)
f=open(fname,'w')
# f.write(content)
f.close()
self.queue.task_done()
return
else:
start=content.find('class="web2">')
end=content.find('</table',start)
tlist=content[start:end].split('<tr')
tlist.pop(0)
tlist.pop(0)
tlist.pop(0)
tlist.pop(len(tlist)-1)
# print len(tlist)
sharelist=[]
for t in tlist:
rlist={}
dlist=t.split('</span')
# print dlist[0]
i=dlist[0].rfind('>',0)
date='20'+dlist[0][i+1:].replace('年前','0').replace('季','').replace('年第','0').replace('年年度','04').replace('年中期','02')
rlist['date']=date
i=dlist[1].rfind('>',0)
rlist['personnumber']=(dlist[1][i+1:].replace(',',''))
i=dlist[2].rfind('>',0)
rlist['personshare']=(dlist[2][i+1:].replace(',',''))
i=dlist[4].rfind('>',0)
rlist['allshare']=(dlist[4][i+1:].replace(',',''))
i=dlist[5].rfind('>',0)
rlist['marketshare']=(dlist[5][i+1:].replace(',',''))
sharelist.append(rlist)
fname=os.path.join(rawcontentpath,code)
f=open(fname,'w')
f.write(rlist['date']+'|')
f.write(rlist['personnumber']+'|')
f.write(rlist['personshare']+'|')
f.write(rlist['allshare']+'|')
f.write(rlist['marketshare']+'\n')
f.close()
filetobedelete=os.path.join(jobtodopath,code)
if os.path.exists(filetobedelete):
try:
os.remove(filetobedelete)
except:
print 'remove error',filetobedelete
self.queue.task_done()
self.__stop()
class ThreadMain(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num=num
def run(self):
# print 'g_jobsnumber',self.num
for i in range(self.num):
dt=ThreadStockDataDownload()
dt.start()
urlqueue.join()
class StockDataDownload():
def __init__(self):
if not os.path.exists(rawcontentpath):os.mkdir(rawcontentpath)
if not os.path.exists(errordatapath):os.mkdir(errordatapath)
if not os.path.exists(jobtodopath):os.mkdir(jobtodopath)
if not os.path.exists(stockbycodepath):os.mkdir(stockbycodepath)
if not os.path.exists(stockbydatepath):os.mkdir(stockbydatepath)
for reg in reglist:
dbpath=os.path.join(stockbycodepath,reg)
if not os.path.exists(dbpath):os.mkdir(dbpath)
# self.clearpathfile(dbpath)
for reg in reglist:
bydatepath=os.path.join(stockbydatepath,reg)
if not os.path.exists(bydatepath):os.mkdir(bydatepath)
def clearpathfile(self,mypath):
for root,dirs,files in os.walk(mypath):
for f in files:
os.remove(os.path.join(root,f))
def movepathfile(self,srcpath,dstpath):
for root,dirs,files in os.walk(srcpath):
for f in files:
dstfile=os.path.join(dstpath,f)
fdst=open(dstfile,'w')
fdst.close()
os.remove(os.path.join(root,f))
def geterrorjobslist(self):
errorlist=self.getpathfilelist(errordatapath)
return errorlist
def getpathfilelist(self,mypath,filter=''):
flist=[]
for root,dirs,files in os.walk(mypath):
for f in files:
if filter=='':flist.append(f.replace('_',':'))
else:
if f.find(filter)>0:flist.append(f.replace('_',':'))
return flist
def downloadstart(self,stockall):
def downloadround():
todolist=[]
todolist=self.getsomejobs()
g_jobsnumber=len(todolist)
# print 'this round todo:',len(todolist)
while g_jobsnumber>0:
print 'this round todo:',g_jobsnumber,datetime.datetime.now()
for job in todolist:
urlqueue.put(job,block=True ,timeout= threadtimeout)
td=ThreadMain(g_jobsnumber)
td.start()
td.join(manthreadtimeout)
todolist=self.getsomejobs()
g_jobsnumber=len(todolist)
errorlist=self.geterrorjobslist()
return len(errorlist)
############################################
self.clearpathfile(rawcontentpath)
self.clearpathfile(errordatapath)
self.clearpathfile(jobtodopath)
# jobs=StockList()
######################################
# print stockall
jobnum=0
for reg in stockall:
for stock in stockall[reg].keys():
fname=os.path.join(jobtodopath,reg+stock+'.txt')
f=open(fname,'w')
f.close()
jobnum=jobnum+1
##################################################
i=0
print 'round start',i
self.movepathfile(errordatapath,jobtodopath)
errornum=downloadround()
print '##########',i,jobnum,errornum
while errornum!=jobnum:
jobnum=errornum
i=i+1
print 'round start',i
self.movepathfile(errordatapath,jobtodopath)
errornum=downloadround()
print '##########',i,jobnum,errornum
##############################################
def getsomejobs(self):
todolist=[]
joblist=self.getpathfilelist(jobtodopath)
errorlist=self.geterrorjobslist()
for job in joblist:
if job not in errorlist:
todolist.append(job)
print 'left job:',len(todolist)
if todolist==[]:return todolist
else:
jobnum=len(todolist)
# print 'go here',jobnum,workers_number,jobnum<=workers_number
if jobnum<=workers_number:
return todolist
else:
# print todolist[:workers_number]
return todolist[:workers_number]
def checkstockfile(self):
rawlist=[]
for root,dirs,files in os.walk(rawcontentpath):
for f in files:
rawlist.append(f)
fname=os.path.join(root,f)
f=open(fname,'r')
content=f.read()
f.close()
tlist=content.split('\n')
s=tlist[0].find('Count')
p=tlist[0].find('=',s)
q=tlist[0].find('"',p)
num=int(tlist[0][p+1:q])
flines=len(tlist)
if flines==num+3:pass
else:print 'checkstockfile failed:',len(tlist),num,fname
print 'raw file num:',len(rawlist),rawlist[0]
dblist=[]
for reg in reglist:
rlist=self.getpathfilelist(os.path.join(stockbycodepath,reg))
for r in rlist:
p=r.find('.')
dblist.append(r[:p]+'_'+reg)
print 'db file num:',len(dblist),dblist[0]
for raw in rawlist:
if raw in dblist:pass
else:print raw,'not in dblist'
return
class ShareHolder():
def __init__(self):
if os.path.exists(shareholderpath) ==False:os.mkdir(shareholderpath)
if os.path.exists(shareholderresultpath) ==False:os.mkdir(shareholderresultpath)
def getshareholderbycode(self,code):
url='http://stockdata.stock.hexun.com/2009_cgjzd_'+code+'.shtml'
req = urllib2.Request(url)
req.add_header('host', 'stockdata.stock.hexun.com')
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1) Gecko/20100101 Firefox/8.0.1')
req.add_header('Accept-Language', 'zh-cn,zh;q=0.5')
req.add_header('Accept-Encoding', 'gzip, deflate')
req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
content=urllib2.urlopen(req).read().decode('gbk')
start=content.find('class="web2">')
end=content.find('</table',start)
tlist=content[start:end].split('<tr')
tlist.pop(0)
tlist.pop(0)
tlist.pop(0)
tlist.pop(len(tlist)-1)
# print len(tlist)
sharelist=[]
for t in tlist:
rlist={}
dlist=t.split('</span')
# print dlist[0]
i=dlist[0].rfind('>',0)
date='20'+dlist[0][i+1:].replace('年前','0').replace('季','').replace('年第','0').replace('年年度','04').replace('年中期','02')
rlist['date']=date
i=dlist[1].rfind('>',0)
rlist['personnumber']=(dlist[1][i+1:].replace(',',''))
i=dlist[2].rfind('>',0)
rlist['personshare']=(dlist[2][i+1:].replace(',',''))
i=dlist[4].rfind('>',0)
rlist['allshare']=(dlist[4][i+1:].replace(',',''))
i=dlist[5].rfind('>',0)
rlist['marketshare']=(dlist[5][i+1:].replace(',',''))
sharelist.append(rlist)
##############################################
fname=os.path.join(shareholderpath,code)
f=open(fname,'w')
for rlist in sharelist:
f.write(rlist['date']+'|')
f.write(rlist['personnumber']+'|')
f.write(rlist['personshare']+'|')
f.write(rlist['allshare']+'|')
f.write(rlist['marketshare']+'\n')
f.close()
return sharelist
def getstocklist(self):
sina=SINAStock()
stocklist={}
slist=sina.getstocklist('SH')
for s in slist.keys():
stocklist[s]=slist[s]
slist=sina.getstocklist('SZ')
for s in slist.keys():
stocklist[s]=slist[s]
return stocklist
def updateshareholder(self):
stocklist=self.getstocklist()
shareholder={}
for stock in stocklist:
print stock
data=self.getshareholderbycode(stock)
shareholder[stock]=data
print len(shareholder.keys())
# for stock in shareholder.keys():
# print stock,len(shareholder[stock])
def loadshareholderfromcode(self,stock):
filename=os.path.join(shareholderpath,stock)
if os.path.exists(filename)==False:self.getshareholderbycode(stock)
f=open(filename,'r')
content=f.read()
tlist=content.split('\n')
result=[]
for t in tlist:
blist=t.split('|')
rlist={}
# print len(blist)
if len(blist)==5:
rlist['date']=int(blist[0])
rlist['personnumber']=myfloat(blist[1])
rlist['personshare']=myfloat(blist[2])
rlist['allshare']=myfloat(blist[3])
rlist['marketshare']=myfloat(blist[4])
result.append(rlist)
return result
def shareholderresult2(self):
result=[]
stocklist=self.getstocklist()
shareholder={}
personmarketrate={}
for stock in stocklist:
shareholder[stock]=self.loadshareholderfromcode(stock)
# print stock,len(shareholder[stock])
personmarketrate[stock]={}
if len(shareholder[stock])>1:
sh=shareholder[stock]
for s in sh:
if s['marketshare']==0:personmarketrate[stock][s['date']]=0
else:personmarketrate[stock][s['date']]=s['personshare']/s['marketshare']
# print stock#,personmarketrate
# break
xlsdict={}
for stock in personmarketrate.keys():
for onejidu in personmarketrate[stock]:
# print 'onejidu=',onejidu,'stock=',stock
if onejidu in xlsdict.keys():
xlsdict[onejidu][stock]=personmarketrate[stock][onejidu]
else:
xlsdict[onejidu]={}
xlsdict[onejidu][stock]=personmarketrate[stock][onejidu]
# print xlsdict
outfilename=os.path.join(shareholderresultpath,str(datetime.date.today())+'.xls')
output=open(outfilename,'w')
dlist=[]
# print reversed(sorted(xlsdict.keys()))
for date in reversed(sorted(xlsdict.keys())):
output.write('\t'+str(date))
dlist.append(date)
output.write('\n')
print dlist
for stock in sorted(personmarketrate.keys()):
output.write(str(stock)+'\t')
for date in dlist:
# print stock,date
output.write(str(personmarketrate[stock][date])+'\t')
output.write('\n')
output.close()
print len(result)
def shareholderresult(self):
result=[]
stocklist=self.getstocklist()
shareholder={}
personnumberrate={}
for stock in stocklist:
shareholder[stock]=self.loadshareholderfromcode(stock)
# print stock,len(shareholder[stock])
personnumberrate[stock]={}
if len(shareholder[stock])>1:
holderlist=shareholder[stock]
for r in range(0,len(holderlist)-1):
if holderlist[r+1]==0:pnrate=0
else:pnrate=holderlist[r]['personnumber']/holderlist[r+1]['personnumber']
shareholder[stock][holderlist[r]['date']]['pnrate']=pnrate
print stock,stocklist[stock]
break
# xlsdict={}
# for stock in personmarketrate.keys():
# for onejidu in personmarketrate[stock]:
## print 'onejidu=',onejidu,'stock=',stock
# if onejidu in xlsdict.keys():
# xlsdict[onejidu][stock]=personmarketrate[stock][onejidu]
# else:
# xlsdict[onejidu]={}
# xlsdict[onejidu][stock]=personmarketrate[stock][onejidu]
## print xlsdict
# outfilename=os.path.join(shareholderresultpath,str(datetime.date.today())+'.xls')
# output=open(outfilename,'w')
# dlist=[]
## print reversed(sorted(xlsdict.keys()))
# for date in reversed(sorted(xlsdict.keys())):
# output.write('\t'+str(date))
# dlist.append(date)
# output.write('\n')
# print dlist
#
# for stock in sorted(personmarketrate.keys()):
#
# output.write(str(stock)+'\t')
# for date in dlist:
## print stock,date
# output.write(str(personmarketrate[stock][date])+'\t')
# output.write('\n')
# output.close()
# print len(result)
if __name__ == '__main__':
starttime=datetime.datetime.now()
print 'this is packStockTakeData tasklist',starttime
sh=ShareHolder()
# sh.getshareholderbycode('000831')
# sh.updateshareholder()
sh.shareholderresult()
# stockall={}
# sina=SINAStock()
# stockall['SH']=sina.getstocklist('SH')
# stockall['SZ']=sina.getstocklist('SZ')
# sdd=StockDataDownload()
# sh=sdd.downloadstart(stockall)
print 'dostockdb OK',starttime,(datetime.datetime.now()-starttime).seconds
pass | Python |
'''
Created on 2011-11-21
@author: Administrator
'''
import urllib2
import datetime
class SINAStock():
'''
get A,HK,US stock list from all vendor
'''
def getstocklist(self,reg):
if reg=='SH':return self.getSHstocklistfromSINA()
elif reg=='HK':return self.getHKstocklistfromSINA()
elif reg=='NS':return self.getUSstocklistfromSINA()
elif reg=='SZ':return self.getSZstocklistfromSINA()
else:print 'error reg'
def getstocklist2(self,reg):
if reg=='CH':return self.getCNstocklist()
elif reg=='HK':return self.getHKstocklist()
elif reg=='US':return self.getUSstocklist()
else:print 'error reg'
def getusstocklistfromimeigu(self):
def getonepage(page):
url='http://hq.imeigu.com/list.jsp?od=0&ac=0&&pagex='+str(page)
content=urllib2.urlopen(url).read().decode('utf8')
s=content.find('<table cellspacing="0">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist={}
for n in nlist:
# print n
tlist=n.split('<td')
onestock=[]
tstock=[]
for t in tlist:
p=t.find('</td')
k=t.rfind('</a',0,p)
if k>0:p=k
s=t.rfind('>',0,p)
v=t[s:p].strip(' >\t\n')
tstock.append(v)
# print '[',v,']',len(v)
if len(tstock)>4:
onestock.append(tstock[1])
onestock.append(tstock[2])
stocklist[onestock[1]]=onestock[2]
return len(nlist)
page=1
ret=getonepage(page)
print ret
# while ret==30:
# page=1+page
# ret=getonepage(page)
return []
def getHKstocklistfrombloomberg(self):
def parseonestock(src):
nlist=src.split('<td')
ret=[]
for n in nlist:
p=n.find('</td')
k=n.rfind('</span',0,p)
if k>0:p=k
s=n.rfind('>',0,p)
v=n[s:p].strip('>\n\t ')
if len(v)>0: ret.append(v)
return ret
pass
def getonepage(page=1):
url='http://www.bloomberg.com/markets/companies/country/usa/'+str(page)+'/'
# url='http://www.bloomberg.com/markets/companies/country/hong-kong/'+str(page)+'/'
# url='http://www.bloomberg.com/markets/companies/country/china/'+str(page)+'/'
content=urllib2.urlopen(url).read()
s=content.find('<table class="ticker_data">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist=[]
for n in nlist:
ret=parseonestock(n)
if len(ret)>0:stocklist.append(ret)
return stocklist
stocklist=[]
tlist=[]
page=1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
if len(tlist)==0:return 0
else:
for t in tlist:
stocklist.append(t)
while len(tlist)>0:
page=page+1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
for t in tlist:
stocklist.append(t)
return stocklist
def getHKstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHKStockData?page=1&num=8000&sort=symbol&asc=1&node=qbgg_hk&_s_r_a=page'
# print url
nlist=urllib2.urlopen(url).read().decode('gb2312').strip('[]{}').split('},{')
# print len(nlist),nlist[0]
stocklist={}
for n in nlist:
tlist=n.split(',')
rlist={}
for t in tlist:
plist=t.split(':')
rlist[plist[0]]=plist[1].strip('"')
stocklist[rlist['symbol']]=rlist['name']
# print rlist
# break
return stocklist
def getUSstocklistfromSINA(self):
nodelist=['china_us','yysp_us','meida_us','auto_us','sales_us','finance_us','tech_us']
urlpre='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getUSList?page=1&num=8000&sort=chg&asc=0&_s_r_a=init&node='
stocklist={}
for node in nodelist:
url=urlpre+node
nlist=urllib2.urlopen(url).read().strip('{}[]').split('},{')
# print node,len(nlist)
for n in nlist:
tlist=n.split(':')
code=tlist[1].strip('"')
stocklist[code]=code
s2list=self.getUSstocklistfromSINA2()
for s2 in s2list.keys():
stocklist[s2]=s2
return stocklist
def getUSstocklistfromSINA2(self):
url='http://vip.stock.finance.sina.com.cn/usstock/ustotal.php'
stocklist={}
nlist=urllib2.urlopen(url).read().split('<div class="col_div">')
nlist.pop(0)
for n in nlist:
i=n.find('</div')
clist=n[:i].split('US100_')
clist.pop(0)
for c in clist:
k=c.find('.')
stocklist[c[:k]]=c[:k]
return stocklist
def getSHstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=20000&sort=symbol&asc=1&node=sh_a&_s_r_a=init'
content=urllib2.urlopen(url).read().decode('gb2312')
# print content
clist=content.strip(' []{}').split('},{')
# print len(clist)
stocklist={}
for c in clist:
flist=c.split(',')
fsone={}
for f in flist:
tlist=f.split(':')
fsone[tlist[0]]=tlist[1].strip('"')
stocklist[fsone['code']]=fsone['name']
return stocklist
def getSZstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=20000&sort=symbol&asc=1&node=sz_a&_s_r_a=init'
content=urllib2.urlopen(url).read().decode('gb2312')
# print content
clist=content.strip(' []{}').split('},{')
# print len(clist)
stocklist={}
for c in clist:
flist=c.split(',')
fsone={}
for f in flist:
tlist=f.split(':')
fsone[tlist[0]]=tlist[1].strip('"')
stocklist[fsone['code']]=fsone['name']
return stocklist
if __name__ == '__main__':
pass | Python |
'''
Created on 2011-11-23
@author: Administrator
'''
from foxtrader import *
import datetime
import os
import shutil
import zipfile,gzip
def date2int(sdate):
return sdate.year*10000+sdate.month*100+sdate.day
def str2date(sdate):
return sdate
return datetime.date(int(sdate[:4]),int(sdate[4:6]),int(sdate[6:8]))
def int2date(s):
sdate=str(s)
if sdate.find('/')<0 and sdate.find('-')<0 :
return datetime.date(int(sdate[:4]),int(sdate[4:6]),int(sdate[6:8]))
sdate=sdate.replace('/','-')
s=[]
s=sdate.split('-')
return datetime.date(int(s[0]),int(s[1]),int(s[2]))
class FoxDataBackup():
def __init__(self):
if os.path.exists(foxdata_backuppath)==False: os.mkdir(foxdata_backuppath)
def backup(self,reg):
srcpath=os.path.join(foxtrader,'data',reg)
print srcpath
srcfilename=os.path.join(srcpath,'day.hqd')
print srcfilename
if os.path.exists(srcfilename):
tday=datetime.date.today()
tyear=tday.year
tmonth=tday.month
dstpath=os.path.join(foxdata_backuppath,reg)
print dstpath
if os.path.exists(dstpath)==False:
os.mkdir(dstpath)
dstfilename=os.path.join(dstpath,str(tyear*100+tmonth))
zf=zipfile.ZipFile(dstfilename+'.zip','w')
zf.write(srcfilename,str(tyear*100+tmonth),zipfile.ZIP_DEFLATED)
zf.close()
#backup now
return
if tmonth in [1,4,7,10]:
dstfilename=os.path.join(dstpath,str(tyear*100+tmonth))
zf=zipfile.ZipFile(dstfilename+'.zip','w')
zf.write(srcfilename,str(tyear*100+tmonth),zipfile.ZIP_DEFLATED)
zf.close()
if __name__ == '__main__':
# fd=FoxTrader()
# stockdata=fd.readdayfile('HK')
starttime=datetime.datetime.now()
print starttime
# downloadandprocessonestock()
fdb=FoxDataBackup()
for reg in ['NS','AS','NQ']:
fdb.backup(reg)
print 'download OK',starttime,(datetime.datetime.now()-starttime).seconds
pass | Python |
# -*- coding: utf-8 -*-
'''
Created on 2011-11-21
@author: Administrator
'''
import struct
import os
from setting import *
import time
import datetime
import urllib2
import simplejson as json
def myfloat(src):
if len(src.strip())==0:return 0
return float(src)
def str2date(src):
# print src
return datetime.datetime(int(src[:4]),int(src[4:6]),int(src[6:8]),9,0,0)
def getstockhistory(stockcode,reg):
if reg in ['SH','SZ']:reg='CH'
if reg in ['NS','NQ','AS']:reg='US'
stockcode=stockcode+':'+reg
if reg=='HK':stockcode=stockcode.strip('0')
# print 'thread stockcode:',stockcode
url='http://www.bloomberg.com/apps/data?pid=webpxta&Securities='+stockcode+'&TimePeriod=5Y&Outfields=HDATE,PR006-H,PR007-H,PR008-H,PR005-H,PR013-H'
# print url
content=''
try:
content=urllib2.urlopen(url).read()
except:
print '[x]',url
if content[:5]=='Error':
print '[r]',#url
else:
clist=content.split('\n')
tlist=[]
for t in range(1,len(clist)-2):
r={}
klist=clist[t].split('"')
r['date']=int(klist[0])
r['open']=myfloat(klist[1])
r['high']=myfloat(klist[2])
r['low']=myfloat(klist[3])
r['close']=myfloat(klist[4])
r['vol']=myfloat(klist[5])
tlist.append(r)
return tlist
class dayProcess():
yearnumber=250
def __init__(self):
self.datalist=[]
self.dresult=[]
self.closelist=[]
self.highlist=[]
self.lowlist=[]
self.datalen=0
# print self.dresult
def isnew(self,newdata):
self.datalen=len(self.datalist)
if self.datalen==0:return True
if self.datalist[self.datalen-1]['date']==newdata['date']:return False
return True
def removeone(self):
olddata=self.datalist.pop()
self.closelist.pop()
self.highlist.pop()
self.lowlist.pop()
self.dresult.pop()
return olddata
def getma(self,mv):
self.datalen=len(self.datalist)
if self.datalen<mv:return 0.0
return sum(self.closelist[self.datalen-mv:self.datalen])/mv
def getxgxd(self):
self.datalen=len(self.datalist)
if self.datalen<self.yearnumber:return (0.0,0.0)
return (max(self.highlist[self.datalen-self.yearnumber:self.datalen]),min(self.lowlist[self.datalen-self.yearnumber:self.datalen]))
def add(self,newdata):
if self.isnew(newdata)==False:
olddata=self.removeone()
# print 'pop date',olddata['date']
newdata['open']=olddata['open']
newdata['high']=max(olddata['high'],newdata['high'])
newdata['low']=min(olddata['low'],newdata['low'])
self.datalist.append(newdata)
self.closelist.append(newdata['close'])
self.highlist.append(newdata['high'])
self.lowlist.append(newdata['low'])
return self.calc(newdata)
else:
self.datalist.append(newdata)
self.closelist.append(newdata['close'])
self.highlist.append(newdata['high'])
self.lowlist.append(newdata['low'])
return self.calc(newdata)
def calc(self,newdata):
r={}
r['ma20']=self.getma(20)
r['ma60']=self.getma(60)
r['ma120']=self.getma(120)
(r['xg'],r['xd'])=self.getxgxd()
r['date']=newdata['date']
r['close']=newdata['close']
self.dresult.append(r)
return r
def getresult(self):
return self.dresult
pass
class monthProcess(dayProcess):
yearnum=12
def isnew(self,newdata):
self.datalen=len(self.datalist)
if self.datalen==0:return True
# print self.weeklist
if self.datalist[self.datalen-1]['date']/100==newdata['date']/100:return False
return True
pass
def calc(self,newdata):
r={}
r['ma20']=self.getma(20)
r['ma60']=self.getma(60)
r['ma120']=self.getma(120)
(r['xg'],r['xd'])=self.getxgxd()
r['date']=newdata['date']/100
r['close']=newdata['close']
self.dresult.append(r)
return r
pass
def getweeklist():
startdate=datetime.date(2020,1,1)
enddate=datetime.date(2000,1,1)
daylist={}
weekindex=0
while startdate>enddate:
# print startdate
daylist[startdate.year*10000+startdate.month*100+startdate.day]=weekindex
newdate=startdate-datetime.timedelta(days=1)
startdate=newdate
if startdate.weekday()==4:weekindex=startdate.year*10000+startdate.month*100+startdate.day
return daylist
class weekProcess(dayProcess):
yearnumber=54
weeklist=getweeklist()
def isnew(self,newdata):
self.datalen=len(self.datalist)
if self.datalen==0:return True
# print self.weeklist
if self.weeklist[self.datalist[self.datalen-1]['date']]==self.weeklist[newdata['date']]:return False
return True
pass
def calc(self,newdata):
r={}
r['ma20']=self.getma(20)
r['ma60']=self.getma(60)
r['ma120']=self.getma(120)
(r['xg'],r['xd'])=self.getxgxd()
r['date']=self.weeklist[newdata['date']]
r['close']=newdata['close']
self.dresult.append(r)
return r
class processByDate():
def __init__(self):
# self.mp=monthProcess()
# self.wp=weekProcess()
# self.dp=dayProcess()
if os.path.exists(stockprocessbydatepath)==False: os.mkdir(stockprocessbydatepath)
for reg in reglist:
regpath=os.path.join(stockprocessbydatepath,reg)
if os.path.exists(regpath)==False: os.mkdir(regpath)
for d in ['day','week','month']:
dpath=os.path.join(stockprocessbydatepath,reg,d)
if os.path.exists(dpath)==False: os.mkdir(dpath)
pass
def getfilelist(self):
stocklist={}
for root,dirs,files in os.walk(rawcontentpath):
for f in files:
# print f
# print os.path.join(root,f)
if f.find('.'): stockcode=f[:-4]
else: stockcode=f
stocklist[stockcode]=os.path.join(root,f)
# print stocklist
return stocklist
def processonestock(self,stockcode,stockfilename):
def loadstockfromfile(stockfilename):
clist=open(stockfilename,'r').read().split('\n')
tlist=[]
for t in range(1,len(clist)-2):
r={}
klist=clist[t].split('"')
r['date']=int(klist[0])
r['open']=myfloat(klist[1])
r['high']=myfloat(klist[2])
r['low']=myfloat(klist[3])
r['close']=myfloat(klist[4])
r['vol']=myfloat(klist[5])
tlist.append(r)
return tlist
stockdata=loadstockfromfile(stockfilename)
for daydata in stockdata:
self.dp.add(daydata)
self.wp.add(daydata)
self.mp.add(daydata)
dret=self.dp.getresult()
wret=self.wp.getresult()
mret=self.mp.getresult()
for d in dret:
reg=stockcode[:2]
# print reg,d
fname=os.path.join(stockprocessbydatepath,reg,'day',str(d['date']))
if os.path.exists(fname)==False:
f=open(fname,'w')
f.close()
f=open(fname,'a')
d['code']=stockcode
f.write(json.dumps(d))
f.write('\n')
f.close
for d in wret:
reg=stockcode[:2]
# print reg,d
fname=os.path.join(stockprocessbydatepath,reg,'week',str(d['date']))
if os.path.exists(fname)==False:
f=open(fname,'w')
f.close()
f=open(fname,'a')
d['code']=stockcode
f.write(json.dumps(d))
f.write('\n')
f.close
for d in mret:
reg=stockcode[:2]
# print reg,d
fname=os.path.join(stockprocessbydatepath,reg,'month',str(d['date']/100))
if os.path.exists(fname)==False:
f=open(fname,'w')
f.close()
f=open(fname,'a')
d['code']=stockcode
f.write(json.dumps(d))
f.write('\n')
f.close
print stockcode,len(stockdata),len(dret),len(wret),len(mret)
pass
def process(self,reg):
def loadstockfromfile(stockfilename):
clist=open(stockfilename,'r').read().split('\n')
tlist=[]
for t in range(0,len(clist)-1):
r={}
klist=clist[t].split('"')
r['date']=int(klist[0])
r['open']=myfloat(klist[1])
r['high']=myfloat(klist[2])
r['low']=myfloat(klist[3])
r['close']=myfloat(klist[4])
r['vol']=myfloat(klist[5])
tlist.append(r)
return tlist
stocklist=self.getfilelist()
daylist={}
weeklist={}
monthlist={}
i=0
for code in sorted(stocklist.keys()):
dp=dayProcess()
wp=weekProcess()
mp=monthProcess()
i=i+1
# print code,stocklist[code],i,starttime,(datetime.datetime.now()-starttime).seconds
datalist=loadstockfromfile(stocklist[code])
while len(datalist)>0:
oneday=datalist.pop(0)
dp.add(oneday)
wp.add(oneday)
mp.add(oneday)
dret=dp.getresult()
dp=None
wret=wp.getresult()
wp=None
mret=mp.getresult()
mp=None
for d in dret:
d['code']=code
if d['date'] in daylist.keys():
daylist[d['date']].append(d)
else:
daylist[d['date']]=[]
daylist[d['date']].append(d)
dret=None
for d in wret:
d['code']=code
if d['date'] in weeklist.keys():
weeklist[d['date']].append(d)
else:
weeklist[d['date']]=[]
weeklist[d['date']].append(d)
wret=None
for d in mret:
d['code']=code
if d['date'] in monthlist.keys():
monthlist[d['date']].append(d)
else:
monthlist[d['date']]=[]
monthlist[d['date']].append(d)
mret=None
print starttime,(datetime.datetime.now()-starttime).seconds
######################################################################
self.removelastfile(reg,'day')
self.removelastfile(reg,'week')
self.removelastfile(reg,'month')
self.dump2file(reg, 'day', daylist)
self.dump2file(reg, 'week', weeklist)
self.dump2file(reg, 'month', monthlist)
def removelastfile(self,reg,duration):
dlist=[]
dpath=os.path.join(stockprocessbydatepath,reg,duration)
# print dpath
for root,dirs,files in os.walk(dpath):
for f in files:
dlist.append({'code':f,'filename':os.path.join(root,f)})
lastone=dlist.pop()
# print 'last ',duration,lastone['filename']
os.remove(lastone['filename'])
def dump2file(self,reg,duration,datalist):
for d in datalist.keys():
fname=os.path.join(stockprocessbydatepath,reg,duration,str(d))
if os.path.exists(fname)==False:
f=open(fname,'w')
f.write(json.dumps(datalist[d]))
f.close
pass
def downloadandprocessonestock():
stockcode='000001'
reg='SZ'
weeklist=getweeklist()
ret=getstockhistory(stockcode,reg)
dp=monthProcess()
# dp=weekProcess()
# dp=dayProcess()
i=0
for rr in ret:
# print rr['date']
rett=dp.add(rr)
# print rett['date']
# print '--------------------------'
# print dp.getresult()
i=i+1
# if i==200: break
dret=dp.getresult()
for rr in dret:
print rr
class outputResult():
def getdatelist(self,reg,duration):
dlist=[]
dpath=os.path.join(stockprocessbydatepath,reg,duration)
print dpath
for root,dirs,files in os.walk(dpath):
for f in files:
dlist.append({'code':f,'filename':os.path.join(root,f)})
return dlist
def parseonedayma(self,filename):
clist=json.load(open(filename,'r'))
result={}
duralist=['ma120','ma60','ma20']
for dura in duralist:
result['close>'+dura]=[]
result['count']=len(clist)
for e in clist:
r={}
for mv in ['ma120','ma60','ma20']:
if e[mv]>0:
if e['close']>e[mv] :result['close>'+mv].append(e['code'])
return result
def outputM120(self,reg):
f=open('c:\\output.xls','w')
dlist=self.getdatelist(reg, 'week')
for d in dlist:
result=self.parseonedayma(d['filename'])
print d['code'],result['count'],len(result['close>ma120']),len(result['close>ma60']),len(result['close>ma20'])
f.write(d['code'])
f.write('\t')
f.write(str(result['count']))
f.write('\t')
f.write(str(len(result['close>ma120'])))
f.write('\t')
f.write(str(len(result['close>ma60'])))
f.write('\t')
f.write(str(len(result['close>ma20'])))
f.write('\n')
f.close()
# print regpath
if __name__ == '__main__':
starttime=datetime.datetime.now()
print starttime
# downloadandprocessonestock()
# pbd=processByDate()
# pbd.process('HK')
out=outputResult()
out.outputM120('SH')
print 'download OK',starttime,(datetime.datetime.now()-starttime).seconds
pass | Python |
'''
Created on 2011-11-14
@author: Administrator
'''
from setting import *
import urllib2
import os
from stockdatadownload import *
import datetime
from foxtrader import *
from sinastock import *
from ibstock import *
from bloombergstock import *
if __name__ == '__main__':
starttime=datetime.datetime.now()
print 'start',starttime
startdate=datetime.date(2020,1,1)
enddate=datetime.date(2000,1,1)
daylist={}
weekindex=0
while startdate>enddate:
print startdate
daylist[startdate.year*10000+startdate.month*100+startdate.day]={'week':weekindex}
newdate=startdate-datetime.timedelta(days=1)
startdate=newdate
if startdate.weekday()==4:weekindex=startdate.year*10000+startdate.month*100+startdate.day
for date in sorted(daylist.keys()):
print date,daylist[date]
print len(daylist)
print 'today US work OK',starttime,(datetime.datetime.now()-starttime).seconds
| Python |
'''
Created on 2011-10-26
test for rawcontent ,errlist,jobslist use dict instead of file
@author: Administrator
'''
import os
import urllib2
import sqlite3
import datetime
import threading
import Queue
import time
import shutil
import simplejson
from setting import *
joblist={1:1}
loglist={1:1}
class StockList():
'''
get A,HK,US stock list from all vendor
'''
def getstocklist(self,reg):
if reg=='SH':return self.getSHstocklistfromSINA()
elif reg=='HK':return self.getHKstocklistfromSINA()
elif reg=='NS':return self.getUSstocklistfromSINA()
elif reg=='SZ':return self.getSZstocklistfromSINA()
else:print 'error reg'
def getstocklist2(self,reg):
if reg=='CH':return self.getCNstocklist()
elif reg=='HK':return self.getHKstocklist()
elif reg=='US':return self.getUSstocklist()
else:print 'error reg'
def getusstocklistfromimeigu(self):
def getonepage(page):
url='http://hq.imeigu.com/list.jsp?od=0&ac=0&&pagex='+str(page)
content=urllib2.urlopen(url).read().decode('utf8')
s=content.find('<table cellspacing="0">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist={}
for n in nlist:
# print n
tlist=n.split('<td')
onestock=[]
tstock=[]
for t in tlist:
p=t.find('</td')
k=t.rfind('</a',0,p)
if k>0:p=k
s=t.rfind('>',0,p)
v=t[s:p].strip(' >\t\n')
tstock.append(v)
# print '[',v,']',len(v)
if len(tstock)>4:
onestock.append(tstock[1])
onestock.append(tstock[2])
stocklist[onestock[1]]=onestock[2]
return len(nlist)
page=1
ret=getonepage(page)
print ret
# while ret==30:
# page=1+page
# ret=getonepage(page)
return []
def getHKstocklistfrombloomberg(self):
def parseonestock(src):
nlist=src.split('<td')
ret=[]
for n in nlist:
p=n.find('</td')
k=n.rfind('</span',0,p)
if k>0:p=k
s=n.rfind('>',0,p)
v=n[s:p].strip('>\n\t ')
if len(v)>0: ret.append(v)
return ret
pass
def getonepage(page=1):
url='http://www.bloomberg.com/markets/companies/country/usa/'+str(page)+'/'
# url='http://www.bloomberg.com/markets/companies/country/hong-kong/'+str(page)+'/'
# url='http://www.bloomberg.com/markets/companies/country/china/'+str(page)+'/'
content=urllib2.urlopen(url).read()
s=content.find('<table class="ticker_data">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist=[]
for n in nlist:
ret=parseonestock(n)
if len(ret)>0:stocklist.append(ret)
return stocklist
stocklist=[]
tlist=[]
page=1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
if len(tlist)==0:return 0
else:
for t in tlist:
stocklist.append(t)
while len(tlist)>0:
page=page+1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
for t in tlist:
stocklist.append(t)
return stocklist
def getAstocklistfrombloomberg(self):
def parseonestock(src):
nlist=src.split('<td')
ret=[]
for n in nlist:
p=n.find('</td')
k=n.rfind('</span',0,p)
if k>0:p=k
s=n.rfind('>',0,p)
v=n[s:p].strip('>\n\t ')
if len(v)>0: ret.append(v)
return ret
pass
def getonepage(page=1):
url='http://www.bloomberg.com/markets/companies/country/china/'+str(page)+'/'
content=urllib2.urlopen(url).read()
s=content.find('<table class="ticker_data">')
p=content.find('</table',s)
nlist=content[s:p].split('<tr')
stocklist=[]
for n in nlist:
ret=parseonestock(n)
if len(ret)>0:stocklist.append(ret)
return stocklist
stocklist=[]
tlist=[]
page=1
tlist=getonepage(page)
print "page:",page," tlist len:",len(tlist)
if len(tlist)==0:return 0
else:
for t in tlist:
stocklist.append(t)
return stocklist
def getHKstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHKStockData?page=1&num=8000&sort=symbol&asc=1&node=qbgg_hk&_s_r_a=page'
# print url
nlist=urllib2.urlopen(url).read().decode('gb2312').strip('[]{}').split('},{')
# print len(nlist),nlist[0]
stocklist={}
for n in nlist:
tlist=n.split(',')
rlist={}
for t in tlist:
plist=t.split(':')
rlist[plist[0]]=plist[1].strip('"')
stocklist[rlist['symbol']]=rlist['name']
# print rlist
# break
return stocklist
def getUSstocklistfromSINA(self):
nodelist=['china_us','yysp_us','meida_us','auto_us','sales_us','finance_us','tech_us']
urlpre='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getUSList?page=1&num=8000&sort=chg&asc=0&_s_r_a=init&node='
stocklist={}
for node in nodelist:
url=urlpre+node
nlist=urllib2.urlopen(url).read().strip('{}[]').split('},{')
# print node,len(nlist)
for n in nlist:
tlist=n.split(':')
code=tlist[1].strip('"')
stocklist[code]=code
# print len(stocklist),stocklist
return stocklist
def getSHstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=20000&sort=symbol&asc=1&node=sh_a&_s_r_a=init'
content=urllib2.urlopen(url).read().decode('gb2312')
# print content
clist=content.strip(' []{}').split('},{')
# print len(clist)
stocklist={}
for c in clist:
flist=c.split(',')
fsone={}
for f in flist:
tlist=f.split(':')
fsone[tlist[0]]=tlist[1].strip('"')
stocklist[fsone['code']]=fsone['name']
return stocklist
def getSZstocklistfromSINA(self):
url='http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=20000&sort=symbol&asc=1&node=sz_a&_s_r_a=init'
content=urllib2.urlopen(url).read().decode('gb2312')
# print content
clist=content.strip(' []{}').split('},{')
# print len(clist)
stocklist={}
for c in clist:
flist=c.split(',')
fsone={}
for f in flist:
tlist=f.split(':')
fsone[tlist[0]]=tlist[1].strip('"')
stocklist[fsone['code']]=fsone['name']
return stocklist
class ThreadStockDataDownload(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.queue=urlqueue
def run(self):
job=self.queue.get()
reg=job[:2]
if reg=='SZ' or reg=='SH':reg='CH'
if reg=='NS':reg='US'
stockcode=job[2:]+':'+reg
if reg=='HK':stockcode=stockcode.strip('0')
# print 'thread stockcode:',stockcode
url='http://www.bloomberg.com/apps/data?pid=webpxta&Securities='+stockcode+'&TimePeriod=5Y&Outfields=HDATE,PR006-H,PR007-H,PR008-H,PR005-H,PR013-H'
stockcode2=job.replace(':','_')
try:
content=urllib2.urlopen(url).read()
except:
print '[x]',#url
loglist[job]='except'
self.queue.task_done()
return
if content[:5]=='Error':
print '[r]',#url
loglist[job]='Error'
self.queue.task_done()
else:
clist=content.split('\n')
tlist=''
for t in range(1,len(clist)-2):
tlist=tlist+clist[t]+'\n'
nlist=job.split(':')
fname=os.path.join(rawcontentpath,job)
f=open(fname,'w')
f.write(tlist)
# f.write(tlist.replace('"',' '))
f.close()
joblist[job]=content
self.queue.task_done()
class ThreadMain(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num=num
def run(self):
# print 'g_jobsnumber',self.num
for i in range(self.num):
dt=ThreadStockDataDownload()
dt.start()
urlqueue.join()
class stock2011():
def __init__(self):
if not os.path.exists(rawcontentpath):os.mkdir(rawcontentpath)
def clearpathfile(self,mypath):
for root,dirs,files in os.walk(mypath):
for f in files:
os.remove(os.path.join(root,f))
def geterrorjobslist(self):
errorlist=self.getpathfilelist(errordatapath)
return errorlist
def getpathfilelist(self,mypath,filter=''):
flist=[]
for root,dirs,files in os.walk(mypath):
for f in files:
if filter=='':flist.append(f.replace('_',':'))
else:
if f.find(filter)>0:flist.append(f.replace('_',':'))
return flist
def downloadstart(self,stockall):
self.clearpathfile(rawcontentpath)
joblist.clear()
loglist.clear()
jobs=StockList()
######################################
for reg in stockall.keys():
print len(stockall[reg]),
for reg in stockall.keys():
for stock in stockall[reg].keys():
joblist[reg+stock]=''
# print 'joblist1:',len(joblist),joblist.keys()
##################################################
todolist=[]
todolist=self.getsomejobs()
g_jobsnumber=len(todolist)
# print 'this round todo:',len(todolist)
while g_jobsnumber>0:
print 'this round todo:',g_jobsnumber,datetime.datetime.now()
for job in todolist:
urlqueue.put(job,block=True ,timeout= threadtimeout)
td=ThreadMain(g_jobsnumber)
td.start()
td.join(10)
todolist=self.getsomejobs()
g_jobsnumber=len(todolist)
# jsonfile=os.path.join(foxdata_rootpath,'rawcontent.json')
# simplejson.dump(joblist,open(jsonfile,'w'))
def getsomejobs(self):
todolist=[]
# print 'joblist:',len(joblist)
for job in joblist:
if joblist[job]=='':todolist.append(job)
print 'left jobs:',len(todolist)
errorlist=[]
for log in loglist:
if loglist[log]=='error':errorlist.append(log)
# loglist={}
# print 'todolist:',todolist
# print errorlist
# print todolist==errorlist
if todolist==errorlist:return []
else:
jobnum=len(todolist)
# print 'go here',jobnum,workers_number,jobnum<=workers_number
if jobnum<=workers_number:
return todolist
else:
# print todolist[:workers_number]
return todolist[:workers_number]
def checkstockfile(self):
rawlist=[]
for root,dirs,files in os.walk(rawcontentpath):
for f in files:
rawlist.append(f)
fname=os.path.join(root,f)
f=open(fname,'r')
content=f.read()
f.close()
tlist=content.split('\n')
s=tlist[0].find('Count')
p=tlist[0].find('=',s)
q=tlist[0].find('"',p)
num=int(tlist[0][p+1:q])
flines=len(tlist)
if flines==num+3:pass
else:print 'checkstockfile failed:',len(tlist),num,fname
print 'raw file num:',len(rawlist),rawlist[0]
dblist=[]
for reg in reglist:
rlist=self.getpathfilelist(os.path.join(stockbycodepath,reg))
for r in rlist:
p=r.find('.')
dblist.append(r[:p]+'_'+reg)
print 'db file num:',len(dblist),dblist[0]
for raw in rawlist:
if raw in dblist:pass
else:print raw,'not in dblist'
return
if __name__ == '__main__':
starttime=datetime.datetime.now()
print 'this is packStockTakeData tasklist',starttime
s=StockList()
slist=s.getSZstocklistfromSINA()
print slist
print 'stocknum:',len(slist)
sj=stock2011()
sj.downloadstart({'SZ':slist})
print 'download OK',starttime,(datetime.datetime.now()-starttime).seconds
# jsonfile=os.path.join(foxdata_rootpath,'rawcontent.json')
# slist=simplejson.load(open(jsonfile,'r'))
# print len(slist)
# for s in slist.keys():
# if len(slist[s])<10:print s,
# sj.dostockdb()
# print 'dostockdb OK',starttime,datetime.datetime.now()
# sj.checkstockfile()
# print 'checkstockfile OK',starttime,datetime.datetime.now()
# sj.trans2bydate()
# print 'start and end time:',starttime,datetime.datetime.now()
# clearallfile() | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.