code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/python2.5
import pacparser
pacparser.init()
pacparser.parse_pac("wpad.dat")
proxy = pacparser.find_proxy("http://www.manugarg.com")
print proxy
pacparser.cleanup()
# Or simply,
print pacparser.just_find_proxy("wpad.dat", "http://www2.manugarg.com")
| Python |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""
Python module to parse pac files. Look at project's homepage
http://code.google.com/p/pacparser for more information.
"""
__author__ = 'manugarg@gmail.com (Manu Garg)'
__copyright__ = 'Copyright (C) 2008 Manu Garg'
__license__ = 'LGPL'
from pacparser import _pacparser
import os
import re
import sys
_url_regex = re.compile('.*\:\/\/([^\/]+).*')
def init():
"""
Initializes pacparser engine.
"""
_pacparser.init()
def parse_pac(pacfile):
"""
(Deprecated) Same as parse_pac_file.
"""
parse_pac_file(pacfile)
def parse_pac_file(pacfile):
"""
Reads the pacfile and evaluates it in the Javascript engine created by
init().
"""
try:
f = open(pacfile)
pac_script = f.read()
except IOError:
print('Could not read the pacfile: %s\n%s' % (pacfile, sys.exc_info()[1]))
return
f.close()
_pacparser.parse_pac_string(pac_script)
def parse_pac_string(pac_script):
"""
Evaluates pac_script in the Javascript engine created by init().
"""
_pacparser.parse_pac_string(pac_script)
def find_proxy(url, host=None):
"""
Finds proxy string for the given url and host. If host is not
defined, it's extracted from the url.
"""
if host is None:
m = _url_regex.match(url)
if not m:
print('URL: %s is not a valid URL' % url)
return None
if len(m.groups()) is 1:
host = m.groups()[0]
else:
print('URL: %s is not a valid URL' % url)
return None
return _pacparser.find_proxy(url, host)
def version():
"""
Returns the compiled pacparser version.
"""
return _pacparser.version()
def cleanup():
"""
Destroys pacparser engine.
"""
_pacparser.cleanup()
def just_find_proxy(pacfile, url, host=None):
"""
This function is a wrapper around init, parse_pac, find_proxy
and cleanup. This is the function to call if you want to find
proxy just for one url.
"""
if os.path.isfile(pacfile):
pass
else:
print('PAC file: %s doesn\'t exist' % pacfile)
return None
if host is None:
m = _url_regex.match(url)
if not m:
print('URL: %s is not a valid URL' % url)
return None
if len(m.groups()) is 1:
host = m.groups()[0]
else:
print('URL: %s is not a valid URL' % url)
return None
init()
parse_pac(pacfile)
proxy = find_proxy(url,host)
cleanup()
return proxy
def setmyip(ip_address):
"""
Set my ip address. This is the IP address returned by myIpAddress()
"""
_pacparser.setmyip(ip_address)
def enable_microsoft_extensions():
"""
Enables Microsoft PAC extensions (dnsResolveEx, isResolvableEx,
myIpAddressEx).
"""
_pacparser.enable_microsoft_extensions()
| Python |
import shutil
import sys
from distutils import sysconfig
def main():
if sys.platform == 'win32':
shutil.rmtree('%s\\pacparser' % sysconfig.get_python_lib(),
ignore_errors=True)
shutil.copytree('pacparser', '%s\\pacparser' % sysconfig.get_python_lib())
else:
print 'This script should be used only on Win32 systems.'
if __name__ == '__main__':
main()
| Python |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
"""
Wrapper script around python module Makefiles. This script take care of
identifying python setup and setting up some environment variables needed by
Makefiles.
"""
import sys
import os
from distutils import sysconfig
from distutils.core import setup
from distutils.core import Extension
def main():
# Use Makefile for windows. distutils doesn't work well with windows.
if sys.platform == 'win32':
pydll = ('C:\windows\system32\python%s.dll' %
sysconfig.get_config_vars('VERSION')[0])
os.system('make -f Makefile.win32 %s PY_HOME="%s" PY_DLL="%s"' %
(' '.join(sys.argv[1:]), sys.prefix, pydll))
return
pacparser_module = Extension('_pacparser',
include_dirs = ['../spidermonkey/js/src', '..'],
sources = ['pacparser_py.c'],
extra_objects = ['../pacparser.o', '../libjs.a'])
setup (name = 'pacparser',
version = '1',
description = 'Pacparser package',
author = 'Manu Garg',
author_email = 'manugarg@gmail.com',
url = 'http://code.google.com/p/pacparser',
long_description = 'python library to parse proxy auto-config (PAC) '
'files.',
license = 'LGPL',
ext_package = 'pacparser',
ext_modules = [pacparser_module],
py_modules = ['pacparser.__init__'])
if __name__ == '__main__':
main()
| Python |
# Copyright (C) 2007 Manu Garg.
# Author: Manu Garg <manugarg@gmail.com>
#
# pacparser is a library that provides methods to parse proxy auto-config
# (PAC) files. Please read README file included with this package for more
# information about this library.
#
# pacparser is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# pacparser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
import getopt
import glob
import os
import sys
def runtests(pacfile, testdata, tests_dir):
py_ver = '.'.join([str(x) for x in sys.version_info[0:2]])
if sys.platform == 'win32':
pacparser_module_path = os.path.join(tests_dir, '..', 'src', 'pymod', 'dist')
if os.path.exists(os.path.join(pacparser_module_path, '_pacparser.pyd')):
raise Exception('Tests failed. Could not determine pacparser path.')
else:
try:
pacparser_module_path = glob.glob(os.path.join(
tests_dir, '..', 'src', 'pymod', 'build', 'lib*%s' % py_ver))[0]
except Exception:
raise Exception('Tests failed. Could not determine pacparser path.')
if 'DEBUG' in os.environ: print('Pacparser module path: %s' %
pacparser_module_path)
sys.path.insert(0, pacparser_module_path)
try:
import pacparser
except ImportError:
raise Exception('Tests failed. Could not import pacparser.')
if 'DEBUG' in os.environ: print('Imported pacparser module: %s' %
sys.modules['pacparser'])
f = open(testdata)
for line in f:
comment = ''
if '#' in line:
comment = line.split('#', 1)[1]
line = line.split('#', 1)[0].strip()
if not line:
continue
if ('NO_INTERNET' in os.environ and os.environ['NO_INTERNET'] and
'INTERNET_REQUIRED' in comment):
continue
if 'DEBUG' in os.environ: print(line)
(params, expected_result) = line.strip().split('|')
args = dict(getopt.getopt(params.split(), 'eu:c:')[0])
if '-e' in args:
pacparser.enable_microsoft_extensions()
if '-c' in args:
pacparser.setmyip(args['-c'])
pacparser.init()
pacparser.parse_pac_file(pacfile)
result = pacparser.find_proxy(args['-u'])
pacparser.cleanup()
if result != expected_result:
raise Exception('Tests failed. Got "%s", expected "%s"' % (result, expected_result))
print('All tests were successful.')
def main():
tests_dir = os.path.dirname(os.path.join(os.getcwd(), sys.argv[0]))
pacfile = os.path.join(tests_dir, 'proxy.pac')
testdata = os.path.join(tests_dir, 'testdata')
runtests(pacfile, testdata, tests_dir)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env pypy
import os, sys, logging, re
import argparse
import fnmatch
configurations = {'lite', 'pro'}
package_dirs = {
'lite': ('src/cx/hell/android/pdfview',),
'pro': ('src/cx/hell/android/pdfviewpro',)
}
file_replaces = {
'lite': (
'cx.hell.android.pdfview.',
'"cx.hell.android.pdfview"',
'package cx.hell.android.pdfview;',
'android:icon="@drawable/pdfviewer"',
),
'pro': (
'cx.hell.android.pdfviewpro.',
'"cx.hell.android.pdfviewpro"',
'package cx.hell.android.pdfviewpro;',
'android:icon="@drawable/apvpro_icon"',
),
}
def make_comment(file_type, line):
"""Add comment to line and return modified line, but try not to add comments to already commented out lines."""
if file_type in ('java', 'c'):
return '// ' + line if not line.startswith('//') else line
elif file_type in ('html', 'xml'):
return '<!-- ' + line.strip() + ' -->\n' if not line.strip().startswith('<!--') else line
else:
raise Exception("unknown file type: %s" % file_type)
def remove_comment(file_type, line):
"""Remove comment from line, but only if line is commented, otherwise return unchanged line."""
if file_type in ('java', 'c'):
if line.startswith('// '): return line[3:]
else: return line
elif file_type in ('html', 'xml'):
if line.strip().startswith('<!-- ') and line.strip().endswith(' -->'): return line.strip()[5:-4] + '\n'
else: return line
else:
raise Exception("unknown file type: %s" % file_type)
def handle_comments(conf, file_type, lines, filename):
new_lines = []
re_cmd_starts = re.compile(r'(?:(//|<!--))\s+#ifdef\s+(?P<def>[a-zA-Z]+)')
re_cmd_ends = re.compile(r'(?:(//|<!--))\s+#endif')
required_defs = []
for i, line in enumerate(lines):
m = re_cmd_starts.search(line)
if m:
required_def = m.group('def')
logging.debug("line %s:%d %s matches as start of %s" % (filename, i+1, line.strip(), required_def))
required_defs.append(required_def)
new_lines.append(line)
continue
m = re_cmd_ends.search(line)
if m:
logging.debug("line %s:%d %s matches as endif" % (filename, i+1, line.strip()))
required_defs.pop()
new_lines.append(line)
continue
if len(required_defs) == 0:
new_lines.append(line)
elif len(required_defs) == 1 and required_defs[0] == conf:
new_line = remove_comment(file_type, line)
new_lines.append(new_line)
else:
new_line = make_comment(file_type, line)
new_lines.append(new_line)
assert len(new_lines) == len(lines)
return new_lines
def find_files(dirname, name):
matches = []
for root, dirnames, filenames in os.walk(dirname):
for filename in fnmatch.filter(filenames, name):
matches.append(os.path.join(root, filename))
return matches
def fix_package_dirs(conf):
for i, dirname in enumerate(package_dirs[conf]):
logging.debug("trying to restore %s" % dirname)
if os.path.exists(dirname):
if os.path.isdir(dirname):
logging.debug(" already exists")
continue
else:
logging.error(" %s already exists, but is not dir" % dirname)
continue
# find other name
found_dirname = None
for other_conf, other_dirnames in package_dirs.items():
other_dirname = other_dirnames[i]
if other_conf == conf: continue # skip this conf when looking for other conf
if os.path.isdir(other_dirname):
if found_dirname is None:
found_dirname = other_dirname
else:
# source dir already found :/
raise Exception("too many possible dirs for this package: %s, %s" % (found_dirname, other_dirname))
if found_dirname is None:
raise Exception("didn't find %s" % dirname)
# now rename found_dirname to dirname
os.rename(found_dirname, dirname)
logging.debug("renamed %s to %s" % (found_dirname, dirname))
def handle_comments_in_files(conf, file_type, filenames):
for filename in filenames:
lines = open(filename).readlines()
new_lines = handle_comments(conf, file_type, lines, filename)
if lines != new_lines:
logging.debug("file %s comments changed" % filename)
f = open(filename, 'w')
f.write(''.join(new_lines))
f.close()
del f
def replace_in_files(conf, filenames):
#logging.debug("about replace to %s in %s" % (conf, ', '.join(filenames)))
other_confs = [other_conf for other_conf in file_replaces.keys() if other_conf != conf]
#logging.debug("there are %d other confs to replace from: %s" % (len(other_confs), ', '.join(other_confs)))
for filename in filenames:
new_lines = []
lines = open(filename).readlines()
for line in lines:
new_line = line
for i, target_string in enumerate(file_replaces[conf]):
for other_conf in other_confs:
source_string = file_replaces[other_conf][i]
new_line = new_line.replace(source_string, target_string)
new_lines.append(new_line)
if new_lines != lines:
logging.debug("file %s changed, writing..." % filename)
f = open(filename, 'w')
f.write(''.join(new_lines))
f.close()
del f
else:
logging.debug("file %s didn't change, no need to rewrite" % filename)
def fix_java_files(conf):
filenames = find_files('src', name='*.java')
replace_in_files(conf, filenames)
handle_comments_in_files(conf, 'java', filenames)
def fix_xml_files(conf):
filenames = find_files('.', name='*.xml')
replace_in_files(conf, filenames)
handle_comments_in_files(conf, 'xml', filenames)
def fix_html_files(conf):
filenames = find_files('res', name='*.html')
replace_in_files(conf, filenames)
handle_comments_in_files(conf, 'html', filenames)
def fix_c_files(conf):
filenames = find_files('jni/pdfview2', name='*.c')
replace_in_files(conf, filenames)
handle_comments_in_files(conf, 'c', filenames)
filenames = find_files('jni/pdfview2', name='*.h')
replace_in_files(conf, filenames)
handle_comments_in_files(conf, 'c', filenames)
def fix_resources(conf):
pass
def main():
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
parser = argparse.ArgumentParser(description='Switch project configurations')
parser.add_argument('--configuration', dest='configuration', default='lite')
args = parser.parse_args()
if not os.path.exists('AndroidManifest.xml'):
raise Exception('android manifest not found, please run this script from main project directory')
conf = args.configuration
if conf not in configurations:
raise Exception("invalid configuration: %s" % conf)
fix_package_dirs(conf)
fix_java_files(conf)
fix_xml_files(conf)
fix_html_files(conf)
fix_c_files(conf)
fix_resources(conf)
if __name__ == '__main__':
main()
| Python |
#TODO remove close games, 52-48 or closer
__author__ = 'william'
__author__ = 'william'
import sys, psycopg2, math, collections
print "Tipping calculator"
print "Enter three digit code\n"
conn_string = "dbname='calcdb' user='william'"
conn = None
try:
conn = psycopg2.connect(conn_string)
except:
print "I am unable to connect bro"
cur = conn.cursor()
def getPosition(team):
query_string = "SELECT * FROM wk18ladder WHERE team='%s'" % team
cur.execute(query_string)
rows = cur.fetchall()
position = 1.0
position1 = 1.0
position2 = 1.0
for row in rows:
position1 = float(row[6])
position2 = float(row[7])
position = (position1/position2)*100.0
return position
def getDefenceAndAttack(team):
query_string = "SELECT * FROM wk18ladder WHERE team='%s'" % team
cur.execute(query_string)
rows = cur.fetchall()
pointsfor = 0.0
pointsagainst = 0.0
for row in rows:
pointsfor = int(row[6])
pointsagainst = int(row[7])
return (pointsfor, pointsagainst)
def getScore(team):
query_string = "SELECT * FROM teamcomparison WHERE team='%s'" % team
cur.execute(query_string)
rows = cur.fetchall()
score = 0
for row in rows:
score = row[1]
return score
def teamBettingPercentage(teamabetting, teambbetting):
teampercentage = (teamabetting / (teamabetting + teambbetting))*1.0
return teampercentage
def getHomeWinTotal():
query_string = "select count(*) from oldhistory where ((home='%s' and away='%s' and homescore>awayscore) or (away='%s' and home='%s' and homescore<awayscore))" % (teama, teamb, teamb, teama)
cur.execute(query_string)
rows = cur.fetchone()
homewin = rows[0]
return homewin
def getCoachScore(team):
query_string = "SELECT * FROM coaches WHERE team='%s'" % team
cur.execute(query_string)
rows = cur.fetchall()
score = 0.0
for row in rows:
score = float(row[1])
return score
def getHomeLoseTotal():
query_string = "select count(*) from oldhistory where ((home='%s' and away='%s' and homescore<awayscore) or (away='%s' and home='%s' and homescore>awayscore))" % (teamb, teama, teama, teamb)
cur.execute(query_string)
rows = cur.fetchone()
homelose = rows[0]
return homelose
def getHomeWinAtHome():
query_string = "select count(*) from oldhistory where (home='%s' and away='%s' and homescore>awayscore)" % (teama, teamb)
cur.execute(query_string)
rows = cur.fetchone()
homewinathome = rows[0]
return homewinathome
def getHomePlayedTotal():
query_string = "select count(*) from oldhistory where home='%s' and away='%s'" % (teama, teamb)
cur.execute(query_string)
rows = cur.fetchone()
homeplayedtotal = rows[0]
return homeplayedtotal
def getPlayedTotal():
query_string = "select count(*) from oldhistory where (home='%s' and away='%s') or (home='%s' and away='%s')" % (teama, teamb, teamb, teama)
cur.execute(query_string)
rows = cur.fetchone()
playedtotal = rows[0]
return playedtotal
def calculateWinner(teama, teamb):
##Part 3 - Attack v defense TO BE COMPLETED
#teamaattack, teamadefence = getDefenceAndAttack(teama)
#teambattack, teambdefence = getDefenceAndAttack(teama)
##Part 1 - history
totalgames = float(getHomeWinTotal()) + float(getHomeLoseTotal())
hometotalratio = float(getHomeWinTotal())/totalgames
homewinratio = float(getHomeWinAtHome())/float(getHomePlayedTotal())
teamaratio = round((homewinratio*0.4) + (hometotalratio*0.6), 2)
teambratio = 1 - teamaratio
##PART 2 - position on ladder code and team score rating
teamaposition = (float(getPosition(teama)))
teambposition = (float(getPosition(teamb)))
teamascore = (float(getScore(teama)))
teambscore = (float(getScore(teamb)))
##attack and defence code
teamaattack, teamadefence = getDefenceAndAttack(teama)
teambattack, teambdefence = getDefenceAndAttack(teamb)
teamaatratio = float(teamaattack/(teamaattack+teambattack))
teambatratio = float(teambattack/(teamaattack+teambattack))
teamadfratio = float(teamadefence/(teamadefence+teambdefence))
teambdfratio = float(teambdefence/(teamadefence+teambdefence))
teamapointstats = float((teamaatratio + teamadfratio) / 2.0)
teambpointstats = float((teambatratio + teambdfratio) / 2.0)
##calcuating ladder position scores
if teamaposition < teambposition:
teamapositionbetting = teamBettingPercentage(teamaposition, teambposition)
teambpositionbetting = 1-teamapositionbetting
else:
teambpositionbetting = teamBettingPercentage(teambposition, teamaposition)
teamapositionbetting = 1-teambpositionbetting
#calculating team overall score
if teamascore < teambscore:
teamascorebetting = teamBettingPercentage(teamascore, teambscore)
teambscorebetting = 1-teamascorebetting
else:
teambscorebetting = teamBettingPercentage(teambscore, teamascore)
teamascorebetting = 1-teambscorebetting
#coaches data
teamacoach = float(getCoachScore(teama))
teambcoach = float(getCoachScore(teamb))
teamafinal = round((teamascorebetting*0.4) + (teamapositionbetting*0.05) + (teamaratio*0.05) + (teamapointstats*0.5) + (teamacoach*0.75), 2)
teambfinal = round((teambscorebetting*0.4) + (teambpositionbetting*0.05) + (teambratio*0.05) + (teambpointstats*0.5) + (teambcoach*0.75), 2)
return (teamafinal, teambfinal)
def setTeams():
team = raw_input("Enter Team: ")
return team
def writeGraph(gamenumber, accountbalance):
filename = 'graph.csv'
outputgraph = open(filename, 'a')
line1 = "%s,%s\n" % (gamenumber, accountbalance)
outputgraph.write(line1)
outputgraph.close()
def resultChecker(teamafinal, teambfinal):
if teamafinal > teambfinal:
result = teamafinal - teambfinal
if result < 0.01:
return True
else:
return False
else:
result = teambfinal - teamafinal
if result < 0.01:
return True
else:
return False
query_string = "select * from results"
cur.execute(query_string)
rows = cur.fetchall()
homelist = list()
awaylist = list()
winnerlist = list()
homeoddslist = list()
awayoddslist = list()
for row in rows:
homelist.append(row[2])
awaylist.append(row[3])
homeoddslist.append(row[6])
awayoddslist.append(row[8])
winnerlist.append(row[9])
correctamount = 0.00
incorrectamount = 0.00
bettingbalance = 100.00
startingbankaccount = bettingbalance
betamount = 0.00
bet = 0.00
##2012 - 0-143
##2009-2012 - 0-740
for x in range(0, 140):
teama = homelist[x]
teamb = awaylist[x]
teamabettingodds = homeoddslist[x]
teambbettingodds = awayoddslist[x]
teamafinal, teambfinal = calculateWinner(teama, teamb)
winner = winnerlist[x]
if teamafinal > teambfinal:
betamount = (bettingbalance / 50) + 5.0
bettingbalance -= betamount
bet = teamabettingodds * betamount
if teama == winner:
answer = "Crct"
correctamount += 1
bettingbalance += bet
else:
answer = "Wrng"
incorrectamount += 1
else:
betamount = (bettingbalance / 50) + 5.0
bettingbalance -= betamount
bet = teamabettingodds * betamount
if teamb == winner:
answer = "Crct"
correctamount += 1
bettingbalance += bet
else:
answer = "Wrng"
incorrectamount += 1
writeGraph(x, bettingbalance)
print "%s - %s: %s %s: %s Winner:%s Answer: %s Bet (odds): %s (a: %s, b: %s) Balance: %s" % (x,teama, teamafinal, teamb, teambfinal, winner, answer, round(betamount, 2), round(teamabettingodds, 2), round(teambbettingodds, 2), round(bettingbalance, 2))
percentage = round((correctamount/(correctamount+incorrectamount)) * 100.00, 2)
print "\n%s games correct, %s games wrong" % (correctamount, incorrectamount)
print "Percentage win rate: %s" % percentage
print "Balance started at $100, starting bet at $4.5 and balance is now... $%s\n" % round(bettingbalance, 2)
print "Total amount made over %s games is %s" % (x, round(bettingbalance-startingbankaccount,2))
| Python |
wordlist=["fish","bird","cat","city","polar","fart","toilet","jesse","apple","hello","goodbye","bannana",]
import random
word= random.choice(wordlist)
print word
wordarray=list(word)
print wordarray
length=len(word)
print " Lets Play Hangman :)"
print (" Your Word is =")
dasharray=list( len(word)*"-")
wronguess=0
while wronguess<9 or dasharray==wordarray:
guess=raw_input("Enter a Lower Case Letter")
i=0
while i<length:
in_word=0
if wordarray[i]==guess:
dasharray[i]=guess
i=i+1
in_word=1
else:
i=i+1
print dasharray
if in_word==0:
wronguess=wronguess+1
print wronguess
| Python |
wordlist=["fish","bird","cat","city","polar","fart","toilet","jesse","apple","hello","goodbye","bannana",]
import random
word= random.choice(wordlist)
wordarray=list(word)
length=len(word)
graphic=["""
_
|
|
|
|
|
|____________
""","""
_____________
| /
| /
|/
|
|
|____________
""",
"""
_____________
| /
| /
|/
|
|
|____________
""","""
_____________
| / |
| /
|/
|
|
|____________
""","""
_____________
| / |
| / O
|/
|
|
|____________
""","""
_____________
| / |
| / O
|/ /
|
|
|____________
""","""
_____________
| / |
| / O
|/ /|
|
|
|____________
""","""
_____________
| / |
| / O
|/ /|
| /
|
|____________
""","""
_____________
| / |
| / O
|/ /|
| /|
| !YOU DEAD!
|____________
""","""
_____________
| / |
| / O
|/ /|
| /|
| !YOU DEAD!
|____________
"""]
print " Lets Play Hangman :)"
dasharray=list( len(word)*"-")
print dasharray
wronguess=0
letters=[]
while wronguess<9 or dasharray!=wordarray:
guess=raw_input("Enter a Lower Case Letter=")
letters.append(guess)
## if guess in letters:
## print "Try again"
## guess=raw_input("Enter a Lower Case Letter=")
print letters
i=0
while i<length:
if wordarray[i]==guess:
dasharray[i]=guess
i=i+1
else:
i=i+1
print dasharray
if guess not in word:
print graphic[wronguess]
wronguess=wronguess+1
if set(wordarray)== set(dasharray):
print "YOU WIN!!"
break
if wronguess==9:
print "you lose"
break
| Python |
from kivyx.lib import runTouchApp
from amaze.kivy.maze import MazeView
from amaze import Maze, Player
from amaze.directions import R, L, U, D
maze = Maze(100, 100)
maze.generate(seed=0)
p = Player("foo", maze[1, 1])
# p.path.append(R, 2)
# p.path.append(U, 2)
# p.path.append(R, 2)
# p.path.append(D, 2)
# p.path.append(R, 2)
# p.path.append(U, 6)
# p.path.append(L, 2)
# p.path.append(U, 2)
# p.path.append(R, 2)
# p.path.append(U, 6)
print p.path
maze.init()
runTouchApp(MazeView(maze))
| Python |
from kivyx.widgets import Widget
class Amaze(Widget):
def __init__(self):
Widget.__init__(self)
| Python |
from kivyx.widgets import Rectangle
from amaze import directions
class PlayerW(Rectangle):
def __init__(self, player):
Rectangle.__init__(self)
self.object = player
self.size = 1, 1
self.center = player.coords
self.rgba = (0, 0, 1, 1)
def update(self):
self.center = self.object.coords
def on_touch_down(self, touch):
if self.collide_point(touch.x, touch.y):
touch.grab(self)
touch.ud.path = [self.object.tile]
return True
else:
return False
def on_touch_move(self, touch):
if touch.grab_current is self:
tile = touch.ud.path[-1]
x = int(touch.x)
y = int(touch.y)
if x == tile.x and y == tile.y:
return True
direction = directions.from_delta(x - tile.x, y - tile.y)
self.object.path.append(direction)
try:
new_tile = self.object.maze[x, y]
except IndexError:
# invalidate_touch(touch)
pass
touch.ud.path.append(new_tile)
return True
return False
def on_touch_up(self, touch):
if touch.grab_current is self:
touch.ungrab(self)
return True
return False
class PathManager(object):
def __init__(self):
pass
def check_touch(self, touch):
x = int(touch.x)
y = int(touch.y)
try:
tile = self.widget.object.maze[x, y]
except IndexError:
return False
try:
index = self.tiles.index(tile)
except ValueError:
return False
del self.tiles[index+1:]
self.tiles.append(self.widget.object.tile)
self.touch = touch
self.widget.grab(touch)
| Python |
from amaze.kivy.entities.player import PlayerW
from amaze.entities.player import Player
ENTITY_WIDGET_MAP = {Player: PlayerW}
| Python |
from kivyx.widgets import Rectangle
from amaze.terrains import Floor, Wall
class TileW(Rectangle):
TERRAIN_COLOR_MAP = {Floor: (1, 1, 1),
Wall: (0, 0, 0)}
def __init__(self, tile):
Rectangle.__init__(self)
self.tile = tile
self.size = (1, 1)
self.pos = tile.coords
self.rgb = TileW.TERRAIN_COLOR_MAP[tile.terrain]
| Python |
from kivyx.widgets import ScatterPlane
from kivyx.lib import Clock
from amaze.kivy.tile import TileW
from amaze.kivy.entities import ENTITY_WIDGET_MAP
class MazeView(ScatterPlane):
def __init__(self, maze):
ScatterPlane.__init__(self)
self.object = maze
self.scale = 20
self.entity_to_widget = {}
for tile in maze.iter_tiles():
self.add_widget(TileW(tile))
for entity in maze.all_entities:
widget_cls = ENTITY_WIDGET_MAP[type(entity)]
widget = widget_cls(entity)
self.add_widget(widget)
self.entity_to_widget[entity] = widget
Clock.schedule_interval(self.step, 1.0 / 60.0)
def step(self, dt):
self.object.step(dt)
for entity in self.object.active_entities:
self.entity_to_widget[entity].update()
| Python |
class Terrain(object):
passable = True
@classmethod
def can_pass(cls, entity):
return cls.passable
class Wall(Terrain):
passable = False
class Floor(Terrain):
pass
class Start(Terrain):
pass
class Exit(Terrain):
pass
| Python |
from amaze.terrains.terrain import Terrain, Floor, Wall, Start, Exit
| Python |
from collections import deque
from utils.interval import Interval
from utils.prettyrepr import prettify_class
from amaze.entities.entity import Entity
from amaze.directions import CHAR, RIGHT, FLOAT_DX, FLOAT_DY
class MovableEntity(Entity):
__slots__ = ("speed", "direction", "path", "x", "y")
default_speed = 1.0 # tiles per time unit
def __init__(self, id, tile=None, speed=None):
Entity.__init__(self, id, tile)
if speed is None:
speed = self.default_speed
self.speed = speed # speed at which the entity moves
self.direction = RIGHT # current direction
self.path = Path(self) # contains a list of directions we will use for movement
self.x = 0.0 # current x (float)
self.y = 0.0 # current y (float)
self.active = True # movable entities are always active
def __info__(self):
return ("%s, x=%.01f, y=%.01f, s=%.01f, d=%s, m=%s" %
(Entity.__info__(self), self.x, self.y, self.speed,
CHAR[self.direction], self.moving))
@property
def coords(self):
return (self.x, self.y)
@property
def moving(self):
return len(self.path) > 0
def move(self, dt):
if not self.moving:
return
distance = self.speed * dt
cx, cy = self.path.tiles[0].center
x0, y0 = self.coords
x1 = x0 + FLOAT_DX[self.direction] * distance
y1 = y0 + FLOAT_DY[self.direction] * distance
# check if we reached the center of the next tile in our path and popleft() from path
if cx in Interval(x0, x1, auto_sort=True) and cy in Interval(y0, y1, auto_sort=True):
# print self.id, "->", cx, cy, "(reached tile center)"
self.x = cx
self.y = cy
self.path.popleft()
# if path is not empty and we haven't spent the whole 'dt', continue moving
if len(self.path) > 0:
traveled_distance = abs(cx - x0) + abs(cy - y0)
elapsed_time = traveled_distance / self.speed
remaining_time = dt - elapsed_time
if remaining_time > 0.0:
self.move(remaining_time)
return
# print self.id, "->", x1, y1,
# check if we moved into a different tile
if int(x1) != int(x0) or int(y1) != int(y0):
self.tile = self.maze[int(x1), int(y1)]
# print "(changed tile to %s)" % self.tile
# else:
# print
# and finally update our position
self.x = x1
self.y = y1
def init(self):
self.x = self.tile.cx
self.y = self.tile.cy
def step(self, dt):
self.move(dt)
@prettify_class
class Path(object):
"""A path is a sequence of directions that an entity will take in the maze."""
__slots__ = ("entity", "directions", "tiles")
def __init__(self, entity):
self.entity = entity
self.directions = deque()
self.tiles = deque()
def __info__(self):
return "+".join(CHAR[direction] for direction in self.directions)
def __len__(self):
return len(self.directions)
def append(self, direction, repeat=1):
if len(self.directions) == 0:
self.entity.direction = direction
tile = self.entity.tile
else:
tile = self.tiles[-1]
for _ in xrange(repeat):
tile = tile.neighbor_tile(direction=direction)
self.directions.append(direction)
self.tiles.append(tile)
def popleft(self):
if len(self.directions) > 1:
print "%s changing direction to %s" % (self.entity.id, CHAR[self.directions[1]])
self.entity.direction = self.directions[1]
self.tiles.popleft()
return self.directions.popleft()
def clear(self):
self.directions.clear()
self.tiles.clear()
| Python |
from amaze.entities.movable import MovableEntity
class Player(MovableEntity):
pass
| Python |
from amaze.entities.movable import MovableEntity
class Monster(MovableEntity):
pass
| Python |
from amaze.entities import Entity
class PowerUp(Entity):
pass
| Python |
from amaze.entities.entity import Entity
from amaze.entities.player import Player
from amaze.entities.monster import Monster
| Python |
from utils.prettyrepr import prettify_class
from utils.relations import One
@prettify_class
class Entity(object):
__slots__ = ("id", "_tile", "_active")
__info_attrs__ = ("id", "tile", "active")
def __init__(self, id, tile=None):
self.id = id
self._tile = None
self._active = False
if tile is not None:
self.tile = tile
@One(complement="entities")
def tile(self):
return self._tile
@tile.setter
def tile(self, tile):
self._tile = tile
@property
def maze(self):
tile = self._tile
return None if tile is None else tile.maze
@property
def active(self):
return self._active
@active.setter
def active(self, active):
active = bool(active)
if active == self._active:
return
tile = self._tile
if tile is not None:
maze = tile.maze
if active and not self._active:
tile.active_entities.add(self)
maze.active_entities.add(self)
elif not active and self._active:
tile.active_entities.remove(self)
maze.active_entities.remove(self)
self._active = active
@property
def maze(self):
tile = self._tile
return None if tile is None else tile.maze
@property
def time(self):
tile = self._tile
return None if tile is None else tile.maze.time
# --------------------------------------------------------------------------
# Game management methods
def init(self):
"""Called by the maze on init()."""
pass
def step(self, dt):
"""Step forward in time."""
pass
def post_step(self):
"""Called after each step() to check for things that should be happening simultaneously to
all entities (e.g. all entities should move first, and only then check for collisions)."""
pass
| Python |
from utils.relations import Many
from utils.prettyrepr import prettify_class
@prettify_class
class Tile(object):
__slots__ = ("maze", "x", "y", "cx", "cy", "terrain", "all_entities", "active_entities")
def __init__(self, maze, x, y, terrain=None):
self.maze = maze
self.x = x
self.y = y
self.cx = x + 0.5
self.cy = y + 0.5
self.terrain = terrain
self.all_entities = set()
self.active_entities = set()
def __info__(self):
terrain = "<no terrain>" if self.terrain is None else self.terrain.__name__
return ("%s@(%d, %d): %d entities [%d active]" %
(terrain, self.x, self.y,
len(self.all_entities),
len(self.active_entities)))
@property
def time(self):
return self.maze.time
@property
def coords(self):
return (self.x, self.y)
@property
def center(self):
return (self.cx, self.cy)
@Many(complement="tile")
def entities(self):
return self.all_entities
@entities.adder
def entities(self, entity):
self.all_entities.add(entity)
self.maze.all_entities.add(entity)
if entity.active:
self.active_entities.add(entity)
self.maze.active_entities.add(entity)
@entities.remover
def entities(self, entity):
self.all_entities.remove(entity)
self.maze.all_entities.remove(entity)
if entity.active:
self.active_entities.remove(entity)
self.maze.active_entities.remove(entity)
def neighbor_tile(self, direction, distance=1):
return self.maze.neighbor_tile(self.x, self.y, direction, distance)
def neighbor_tiles(self, distance=1):
return self.maze.neighbor_tiles(self.x, self.y, distance)
| Python |
from math import pi
R = RIGHT = 0
U = UP = 1
L = LEFT = 2
D = DOWN = 3
ORDERED = (R, U, L, D)
DX = (+1, 0, -1, 0)
DY = (0, +1, 0, -1)
DELTA = zip(DX, DY)
FLOAT_DX = map(float, DX)
FLOAT_DY = map(float, DY)
FLOAT_DELTA = zip(FLOAT_DX, FLOAT_DY)
ANGLE = (0.0, pi/2.0, pi, pi*3.0/2.0)
NAME = ("right", "up", "left", "down")
CHAR = ("R", "U", "L", "D")
def from_delta(dx, dy):
if dx != 0 and dy != 0:
raise ValueError("invalid direction")
if dx > 0:
return RIGHT
elif dx < 0:
return LEFT
elif dy > 0:
return UP
elif dy < 0:
return DOWN
| Python |
"""
TODO:
--- draw player path through the maze using touch
*** implement maze generation algorithms
*** simple text-based visualization of a maze
"""
from amaze.maze import Maze
from amaze.entities import Player
from amaze.directions import *
# m = Maze(50, 50)
# m.generate(seed=0)
# p = Player("foo", m[1, 1])
# m.init()
# p.path.append(R, 2)
# p.path.append(U, 6)
# for _ in xrange(80):
# m.step(0.13)
| Python |
import itertools
import random
from utils.prettyrepr import prettify_class
from amaze.tile import Tile
from amaze.terrains import Floor, Wall
from amaze.directions import ORDERED, DX, DY
@prettify_class
class Maze(object):
__slots__ = ("grid", "width", "height", "time",
"all_entities", "active_entities",
"__weakref__")
def __init__(self, width, height, fill=Floor):
if width % 2 == 0:
width += 1
if height % 2 == 0:
height += 1
self.grid = [[Tile(self, x, y) for x in xrange(width)] for y in xrange(height)]
self.width = width
self.height = height
self.time = 0.0
self.all_entities = set()
self.active_entities = set()
if fill is not None:
self.fill(fill)
def __info__(self):
return ("w=%d, h=%d, %d entities [%d active]" %
(self.width, self.height,
len(self.all_entities),
len(self.active_entities)))
def __getitem__(self, (x, y)):
return self.grid[y][x]
def __setitem__(self, (x, y), terrain):
self.grid[y][x].terrain = terrain
@property
def size(self):
return (self.width, self.height)
def neighbor_coords(self, x, y, distance=1):
for direction in ORDERED:
nx = x + distance * DX[direction]
ny = y + distance * DY[direction]
if 0 <= nx < self.width and 0 <= ny < self.height:
yield (nx, ny)
def neighbor_tiles(self, x, y, distance=1):
for nx, ny in self.neighbor_coords(x, y, distance):
yield self[nx, ny]
def neighbor_tile(self, x, y, direction, distance=1):
nx = x + distance * DX[direction]
ny = y + distance * DY[direction]
if 0 <= nx < self.width and 0 <= ny < self.height:
return self[nx, ny]
raise IndexError("neighbor unavailable")
def iter_coords(self):
return itertools.product(xrange(self.width), xrange(self.height))
def iter_tiles(self):
for x, y in self.iter_coords():
yield self[x, y]
# --------------------------------------------------------------------------
# Game management methods
def init(self):
"""Initialize all active entities in the maze. This should be called exactly once before
the start of a game."""
for entity in self.active_entities:
entity.init()
def step(self, dt):
"""Call step() and then call post_step() on all active entities in the maze. This allows
all entities to move first, and only then check for collisions."""
# Make a list here because during step() new entities may
# become active or some active entities may become inactive.
# The newly active entities will only be activated on the next step.
active_entities = list(self.active_entities)
for entity in active_entities:
entity.step(dt)
self.time += dt
for entity in active_entities:
entity.post_step()
# --------------------------------------------------------------------------
# Manual generation methods
def fill(self, terrain=Floor):
"""Fill the maze with the argument terrain."""
for x, y in self.iter_coords():
self[x, y] = terrain
def make_outer_box(self, terrain=Wall):
"""Make a box around the maze using the argument terrain."""
for x, y in itertools.product((0, self.width-1), xrange(self.height)):
self[x, y] = terrain
for x, y in itertools.product(xrange(self.width), (0, self.height-1)):
self[x, y] = terrain
# --------------------------------------------------------------------------
# Automatic generation methods
def noncell_coords(self):
for x, y in self.iter_coords():
if x % 2 == 0 or y % 2 == 0:
yield (x, y)
def cell_coords(self):
return itertools.product(xrange(1, self.width, 2), xrange(1, self.height, 2))
def generate(self, floor=Floor, wall=Wall, loop_prob=0.01, seed=None):
if seed is not None:
random.seed(seed)
# Create initial setup: the maze is filled with 'floor' terrain and then all non-cell
# positions are set to 'wall' terrain.
self.fill(floor)
for x, y in self.noncell_coords():
self[x, y] = wall
# Now we use a randomized depth-first traversal of the cell graph. Cells are the tiles at
# odd coordinates which initially contain walls between them. When we traverse from one
# cell to the next, the wall between the cells is cleared. At each step, we randomly choose
# a non-visited neighbor of our current cell and move into it. If all neighbor cells have
# been visited, we may create a loop with probability 'loop_prob', and then backtrack.
unvisited_cells = set(self.cell_coords())
loops = 0
while len(unvisited_cells) > 0:
stack = [unvisited_cells.pop()]
while len(stack) > 0:
cx, cy = stack[-1]
neighbors = list(self.neighbor_coords(cx, cy, 2))
unvisited_neighbors = filter(unvisited_cells.__contains__, neighbors)
if len(unvisited_neighbors) > 0:
# Choose an unvisited neighbor randomly and move into it.
nx, ny = neighbor = random.choice(unvisited_neighbors)
unvisited_cells.remove(neighbor)
stack.append(neighbor)
else:
# All neighbors have been visited: backtrack and optionally create a loop.
stack.pop()
if random.random() >= loop_prob:
continue
nx, ny = random.choice(neighbors)
loops += 1
# Clear the wall between the current cell and the chosen neighbor.
x = (cx + nx) / 2
y = (cy + ny) / 2
self[x, y] = floor
# Make sure that all the cells are reachable.
self.check_cell_coverage()
return loops
def check_cell_coverage(self):
"""After generate(), make sure that all the cells are reachable from any starting point
(i.e. the cell graph is not disconnect)."""
unvisited_cells = set(self.cell_coords())
if len(unvisited_cells) == 0:
return
stack = [unvisited_cells.pop()]
while len(stack) > 0:
cx, cy = stack.pop()
neighbors = []
for nx, ny in self.neighbor_coords(cx, cy, 2):
x = (cx + nx) / 2
y = (cy + ny) / 2
if self[x, y].terrain is Floor:
neighbors.append((nx, ny))
unvisited_neighbors = filter(unvisited_cells.__contains__, neighbors)
unvisited_cells.difference_update(unvisited_neighbors)
stack.extend(unvisited_neighbors)
if len(unvisited_cells) > 0:
raise Exception("unreachable cells: %s" % (unvisited_cells,))
# --------------------------------------------------------------------------
# Static visualization
def show(self):
"""Code borrowed from http://en.wikipedia.org/wiki/Maze_generation_algorithm"""
import matplotlib.pyplot as pyplot
X = [[bool(tile.terrain is Wall) for tile in row] for row in reversed(self.grid)]
pyplot.imshow(X, cmap=pyplot.cm.binary, interpolation='nearest')
pyplot.xticks([])
pyplot.yticks([])
pyplot.show()
if __name__ == "__main__":
m = Maze(50, 25)
m.generate()
m.show()
| Python |
import pygame, sys, math, random
pygame.init()
from Block import Block
from Player import Player
from HardBlock import HardBlock
from Enemy import Enemy
from Background import Background
clock = pygame.time.Clock()
width = 800
height = 600
size = width, height
blocksize = [50,50]
playersize = [40,40]
screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0
blocks = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()
Player.containers = (all, players)
Block.containers = (all, blocks)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)
bg = Background("rsc/blocks/grass.png", size)
def loadLevel(level):
f = open("rsc/levels/field.lvl", 'r')
lines = f.readlines()
f.close()
newlines = []
for line in lines:
newline = ""
for c in line:
if c != "\n":
newline += c
newlines += [newline]
for line in newlines:
print line
for y, line in enumerate(newlines):
for x, c in enumerate(line):
if c == "s":
HardBlock("rsc/blocks/black.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "e":
Block("rsc/blocks/purple.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "l":
Block("rsc/blocks/line block.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
blocksize)
elif c == "g":
HardBlock("rsc/blocks/field goal.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
[blocksize[0], blocksize[1]*3])
"""
f = open(level+".tng", 'r')
lines = f.readlines()
f.close()
newlines = []
for line in lines:
newline = ""
for c in line:
if c != "\n":
newline += c
newlines += [newline]
for line in newlines:
print line
for y, line in enumerate(newlines):
for x, c in enumerate(line):
if c == "@":
player = Player([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
playersize,
size)
elif c == "e":
Enemy("rsc/enemy/red guy.png",
[(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
playersize)
for each in all.sprites():
each.fixLocation(player.offsetx, player.offsety)
"""
levels = ["rsc/levels/level1",
"rsc/levels/level2",
"rsc/levels/level3"]
level = 0
loadLevel(levels[level])
#player1 = players.sprites()[0]
player1 = Player([0,0], playersize, size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if level < len(levels)-1:
level += 1
else:
level = 0
for each in all.sprites():
each.kill()
bg = Background("rsc/bg/grass.png", size)
screen.blit(bg.image, bg.rect)
loadLevel(levels[level])
player1 = players.sprites()[0]
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
player1.direction("right")
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
player1.direction("left")
if event.key == pygame.K_w or event.key == pygame.K_UP:
player1.direction("up")
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
player1.direction("down")
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
player1.direction("stop right")
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
player1.direction("stop left")
if event.key == pygame.K_w or event.key == pygame.K_UP:
player1.direction("stop up")
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
player1.direction("stop down")
playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
for player in playersHitBlocks:
for block in playersHitBlocks[player]:
player.collideBlock(block)
for enemy in enemiesHitBlocks:
for block in enemiesHitBlocks[enemy]:
enemy.collideBlock(block)
for enemy in enemiesHitEnemies:
for otherEnemy in enemiesHitEnemies[enemy]:
enemy.collideBlock(otherEnemy)
all.update(size,
player1.speedx,
player1.speedy,
player1.scrollingx,
player1.scrollingy,
player1.realx,
player1.realy)
dirty = all.draw(screen)
pygame.display.update(dirty)
pygame.display.flip()
clock.tick(30)
| Python |
import pygame, sys, math
class Background(pygame.sprite.Sprite):
def __init__(self, image, size):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, size)
self.rect = self.image.get_rect()
def update(*args):
pass
def fixLocation(self, x, y):
pass
| Python |
import pygame, sys, math
class Player(pygame.sprite.Sprite):
def __init__(self, pos = (0,0), blocksize = [50,50], screensize = [800,600]):
pygame.sprite.Sprite.__init__(self, self.containers)
self.screensize = screensize
self.upImages = [pygame.image.load("rsc/player/playerBall_up1.png"),
pygame.image.load("rsc/player/playerBall_up2.png")]
self.upImages = [pygame.transform.scale(self.upImages[0], blocksize),
pygame.transform.scale(self.upImages[1], blocksize)]
self.downImages = [pygame.image.load("rsc/player/playerBall_down1.png"),
pygame.image.load("rsc/player/playerBall_down2.png")]
self.downImages = [pygame.transform.scale(self.downImages[0], blocksize),
pygame.transform.scale(self.downImages[1], blocksize)]
self.rightImages = [pygame.image.load("rsc/player/playerBall_right1.png"),
pygame.image.load("rsc/player/playerBall_right2.png")]
self.rightImages = [pygame.transform.scale(self.rightImages[0], blocksize),
pygame.transform.scale(self.rightImages[1], blocksize)]
self.leftImages = [pygame.image.load("rsc/player/playerBall_left1.png"),
pygame.image.load("rsc/player/playerBall_left2.png")]
self.leftImages = [pygame.transform.scale(self.leftImages[0], blocksize),
pygame.transform.scale(self.leftImages[1], blocksize)]
self.images = self.rightImages
self.frame = 0
self.maxFrame = len(self.images) - 1
self.waitCount = 0
self.waitCountMax = 5
self.image = self.images[self.frame]
self.rect = self.image.get_rect()
self.maxSpeed = blocksize[0]/10.0
self.speed = [0,0]
self.speedx = 0
self.speedy = 0
self.realx = pos[0]
self.realy = pos[1]
self.x = screensize[0]/2
self.y = screensize[1]/2
self.offsetx = self.x - self.realx
self.offsety = self.y - self.realy
self.scrollingx = False
self.scrollingy = False
self.scrollBoundry = 200
self.headingx = "right"
self.headingy = "up"
self.lastHeading = "right"
self.headingChanged = False
self.radius = self.rect.width/2
self.living = True
self.place(pos)
def place(self, pos):
self.rect.center = pos
def fixLocation(self, x, y):
pass
def update(*args):
self = args[0]
self.collideWall(self.screensize)
self.animate()
self.move()
self.headingChanged = False
def animate(self):
if self.headingChanged:
if self.lastHeading == "up":
self.images = self.upImages
if self.lastHeading == "down":
self.images = self.downImages
if self.lastHeading == "right":
self.images = self.rightImages
if self.lastHeading == "left":
self.images = self.leftImages
self.image = self.images[self.frame]
if self.waitCount < self.waitCountMax:
self.waitCount += 1
else:
self.waitCount = 0
if self.frame < self.maxFrame:
self.frame += 1
else:
self.frame = 0
self.image = self.images[self.frame]
def move(self):
self.realx += self.speedx
self.realy += self.speedy
if not self.scrollingx:
self.x += self.speedx
if self.x > self.screensize[0] - self.scrollBoundry and self.headingx == "right":
self.scrollingx = True
elif self.x < self.scrollBoundry and self.headingx == "left":
self.scrollingx = True
else:
self.scrollingx = False
if not self.scrollingy:
self.y += self.speedy
if self.y > self.screensize[1] - self.scrollBoundry and self.headingy == "down":
self.scrollingy = True
elif self.y < self.scrollBoundry and self.headingy == "up":
self.scrollingy = True
else:
self.scrollingy = False
self.rect.center = (round(self.x), round(self.y))
def collideWall(self, size):
if self.rect.left < 0 and self.headingx == "left":
self.speedx = 0
elif self.rect.right > size[0] and self.headingx == "right":
self.speedx = 0
if self.rect.top < 0 and self.headingy == "up":
self.speedy = 0
elif self.rect.bottom > size[1] and self.headingy == "down":
self.speedy = 0
def collideBlock(self, block):
print self.rect, self.headingx, self.headingy
if self.realx < block.realx and self.headingx == "right":
self.speedx = 0
self.realx -= 1
self.x -= 1
print "hit right"
if self.realx > block.realx and self.headingx == "left":
self.speedx = 0
self.realx += 1
self.x += 1
print "hit left"
if self.realy > block.realy and self.headingy == "up":
self.speedy = 0
self.realy += 1
self.y += 1
print "hit up"
if self.realy < block.realy and self.headingy == "down":
self.speedy = 0
self.realy -= 1
self.y -= 1
print "hit down"
def direction(self, dir):
if dir == "right":
self.headingx = "right"
self.speedx = self.maxSpeed
self.lastHeading = "right"
self.headingChanged = True
if dir == "stop right":
self.headingx = "right"
self.speedx = 0
if dir == "left":
self.headingx = "left"
self.speedx = -self.maxSpeed
self.lastHeading = "left"
self.headingChanged = True
if dir == "stop left":
self.headingx = "left"
self.speedx = 0
if dir == "up":
self.headingy = "up"
self.speedy = -self.maxSpeed
self.lastHeading = "up"
self.headingChanged = True
if dir == "stop up":
self.headingy = "up"
self.speedy = 0
if dir == "down":
self.headingy = "down"
self.speedy = self.maxSpeed
self.lastHeading = "down"
self.headingChanged = True
if dir == "stop down":
self.headingy = "down"
self.speedy = 0
| Python |
import pygame, sys, math
from Block import Block
class HardBlock(Block):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, image, pos, blocksize)
| Python |
import pygame, sys, math
class Block(pygame.sprite.Sprite):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = pygame.image.load(image)
self.image = pygame.transform.scale(self.image, blocksize)
self.rect = self.image.get_rect()
self.realx = pos[0]
self.realy = pos[1]
self.x = pos[0]
self.y = pos[1]
self.place(pos)
self.speedx = 0
self.speedy = 0
self.scrollingx = False
self.scrollingy = False
def place(self, pos):
self.rect.center = pos
def fixLocation(self, x, y):
self.x += x
self.y += y
def update(*args):
self = args[0]
self.speedx = args[2]
self.speedy = args[3]
self.scrollingx = args[4]
self.scrollingy = args[5]
self.move()
def move(self):
if self.scrollingx:
self.x -= self.speedx
if self.scrollingy:
self.y -= self.speedy
self.rect.center = (round(self.x), round(self.y))
| Python |
import pygame, sys, math, random
from Block import Block
class Enemy(Block):
def __init__(self, image, pos = (0,0), blocksize = [50,50]):
Block.__init__(self, image, pos, blocksize)
self.maxSpeed = blocksize[0]/14.0
self.living = True
self.detectRange = 100
self.seePlayer = False
self.headingx = "right"
self.headingy = "up"
self.directionCount = 0
self.realx = pos[0]
self.realy = pos[1]
self.x = pos[0]
self.y = pos[1]
self.offsetx = 0
self.offsety = 0
def fixLocation(self, x, y):
self.offsetx += x
self.offsety += y
def update(*args):
self = args[0]
self.playerspeedx = args[2]
self.playerspeedy = args[3]
self.scrollingx = args[4]
self.scrollingy = args[5]
playerx = args[6]
playery = args[7]
print "enemy:", self.realx, self.realy, "player:", playerx, playery
self.move()
self.detectPlayer(playerx, playery)
if not self.seePlayer:
self.ai()
def detectPlayer(self, playerx, playery):
if self.distanceToPoint([playerx, playery]) < self.detectRange:
print "I seeeee you!!!"
self.seePlayer = True
self.speedx = self.maxSpeed
self.speedy = self.maxSpeed
#print playerx, self.realx, playery, self.realy
if playerx > self.realx:
self.headingx = "right"
elif playerx < self.realx:
self.headingx = "left"
if playery > self.realy:
self.headingy = "down"
elif playery < self.realy:
self.headingy = "up"
else:
self.seePlayer = False
print "Where are you?"
def move(self):
#print "enemy", self.realx, self.speedx
if self.headingx == "right":
self.realx += self.speedx
else:
self.realx -= self.speedx
if self.headingy == "down":
self.realy += self.speedy
else:
self.realy -= self.speedy
if self.scrollingx:
self.offsetx -= self.playerspeedx
if self.scrollingy:
self.offsety -= self.playerspeedy
self.x = self.realx + self.offsetx
self.y = self.realy + self.offsety
self.rect.center = (round(self.x), round(self.y))
def ai(self):
if self.directionCount > 0:
self.directionCount -= 1
else:
self.directionCount = random.randint(10,100)
dir = random.randint(0,3);
if dir == 0:
self.headingx = "right"
self.headingy = "up"
if dir == 1:
self.headingx = "right"
self.headingy = "down"
if dir == 2:
self.headingx = "left"
self.headingy = "down"
if dir == 3:
self.headingx = "left"
self.headingy = "up"
self.speedx = random.randint(0, int(self.maxSpeed))
self.speedy = random.randint(0, int(self.maxSpeed))
def collideBlock(self, block):
#print self.rect, self.headingx, self.headingy
if self.realx < block.realx and self.headingx == "right":
self.speedx = 0
self.realx -= 1
self.x -= 1
print "hit right"
self.directionCount = 0
if self.realx > block.realx and self.headingx == "left":
self.speedx = 0
self.realx += 1
self.x += 1
print "hit left"
self.directionCount = 0
if self.realy > block.realy and self.headingy == "up":
self.speedy = 0
self.realy += 1
self.y += 1
print "hit up"
self.directionCount = 0
if self.realy < block.realy and self.headingy == "down":
self.speedy = 0
self.realy -= 1
self.y -= 1
print "hit down"
self.directionCount = 0
def distanceToPoint(self, pt):
x1 = self.realx
y1 = self.realy
x2 = pt[0]
y2 = pt[1]
return math.sqrt(((x2-x1)**2)+((y2-y1)**2))
| Python |
#!/usr/bin/env python2.6
# -*- encoding:utf-8 -*-
# ---------------------------------------------------------
# Copyright (c) 2011 by João dos Santos Gonçalves,
# Andrea Oliveira da Silva e Glevson da Silva Pinto,
# Foo Figther Game(c) e Foo Fighter(c) 2011.
# ---------------------------------------------------------
#* Project: Foo Fighter Game
#* Release: 09/06/2011
#* Version: 0.11
#* More information: http://code.google.com/p/foo-fighter-game/w/list
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#* Universidade Federal de Alagoas - UFAL/ARAPIRACA
#* Ciência da Computação
#* Disciplina: Laboratório de Programação 1
#* Orientador: Mário Hozano
# ************************************************************************
# This is Foo Fighter Game, an implementation in Python,
# is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
# Foo Fighter is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the
# GNU General Public License along with Plague;
# if not, write to the Free Software Foundation, Inc.
# *************************************************************************
import pygame
from pygame.locals import *
import os, sys, getopt
image_diretorio = os.path.join( "..", "imagens" ) # Recebe a imagem do fundo
class Fundo:
"""
Fundo do Game
"""
image = None
posicao = None
def __init__(self, image="foo_fundo.png"):
if isinstance(image, str):
image = os.path.join(image_diretorio, image)
image = pygame.image.load(image).convert()
# Converte a imagem para e melhora o processamento do da\ imagens.
self.asize = image.get_size()
self.posicao = [0, -1 * self.asize[1]]
tela = pygame.display.get_surface()
tela_size = tela.get_size()
from math import ceil
largura = (ceil(float(tela_size[0]) / self.asize[0]) + 1) * self.asize[0]
altura = (ceil(float(tela_size[1]) / self.asize[1]) + 1) * self.asize[1]
back = pygame.Surface((largura, altura))
for i in range((back.get_size()[0] / self.asize[0])):
for j in range((back.get_size()[1] / self.asize[1])):
back.blit(image, (i * self.asize[0], j * self.asize[1]))
self.image = back
def draw(self, tela):
''' Desenha a tela '''
tela.blit(self.image, self.posicao)
def update(self, dt):
self.posicao[1] = self.posicao[1] + 1
if (self.posicao[1] > 0):
self.posicao[1] = self.posicao[1] - self.asize[1]
# Fundo
class Game:
tela = None
tela_size = None
run = True
fundo = None
def __init__(self, asize, fullscreen):
"""
Aqui iniciamos o pygame, a resolução da tela, caption, e por enquanto desativa o mouse
"""
atores = {}
pygame.init()
flags = DOUBLEBUF
if fullscreen:
flags |= FULLSCREEN
self.tela = pygame.display.set_mode( asize, flags)
self.tela_size = self.tela.get_size()
pygame.mouse.set_visible(0) # Deixa o mouse invisivel
pygame.display.set_caption("Foo Fighter v0.11") # Titulo
def controle_eventos(self):
"""
Trata os eventos e toma as ações
"""
for event in pygame.event.get():
evento = event.type
if evento in (KEYDOWN, KEYUP):
k = event.key
if evento == QUIT:
self.run = False
elif evento == KEYDOWN:
if k == K_ESCAPE:
self.run = False
def loop_principal(self):
"""
Laço principal
"""
# Criamos o fundo
self.fundo = Fundo('foo_fundo.png')
# Relogio e o dt que vai limitar o valor de FPS
clock = pygame.time.Clock()
dtime = 16
# Inicia loop principal
while self.run:
clock.tick(1000 / dtime)
# Handle Input Events
self.controle_eventos()
self.atores_update( dtime )
self.atores_draw()
pygame.display.flip()
def atores_update(self, dtime):
self.fundo.update( dtime )
def atores_draw(self):
self.fundo.draw(self.tela)
# Game
def parse_opts(argv):
"""
Retorna as informações da linha de comando
"""
# Analise a linha de commando usando 'getopt'
try:
opts, args = getopt.gnu_getopt( argv[ 1 : ],
"hfr:",
[ "help",
"fullscreen",
"resolution=" ] )
except getopt.GetoptError:
# Informaçao
usage()
sys.exit(2)
options = {
"fullscreen": False,
"resolution": (640, 480),
}
for b, m in opts:
if b in ( "-f", "--fullscreen" ):
options[ "fullscreen" ] = True
elif b in ( "-h", "--help" ):
usage()
sys.exit( 0 )
elif b in ( "-r", "--resolution" ):
m = m.lower()
r = m.split( "x" )
if len( r ) == 2:
options[ "resolution" ] = r
continue
r = m.split( "," )
if len( r ) == 2:
options[ "resolution" ] = r
continue
r = m.split( ":" )
if len( r ) == 2:
options[ "resolution" ] = r
continue
# for b, m in opts
r = options[ "resolution" ]
options[ "resolution" ] = [ int( r[0] ), int( r[1] ) ]
return options
# parse_opts()
def main(argv):
''' Primeiro vamos verificar que estamos no diretorio certo para conseguir encontrar as imagens e outros recursos, e inicializar o pygame com as opcoes passadas pela linha de comando
'''
fullpath = os.path.abspath( argv[ 0 ] )
dir = os.path.dirname( fullpath )
os.chdir( dir )
options = parse_opts(argv)
game = Game( options[ "resolution" ], options[ "fullscreen" ] )
game.loop_principal()
# main()
# Aqui executamos tudo
if __name__ == '__main__':
main(sys.argv)
| Python |
#! /usr/bin/python
import pygtk
pygtk.require("2.0")
import os
import sys
import btctl
import gtk
import gconf
import pycurl
import urllib
def progress_callback (bo, bdaddr):
trayicon.set_blinking(1)
print ("got progress from %s" % (bdaddr))
def request_put_callback (bo, bdaddr):
print ("device %s wants to send a file" % (bdaddr))
bo.set_response (True)
def put_callback (bo, bdaddr, fname, body, timestamp):
print ("device %s sent a file" % (bdaddr))
print "Filename %s, timestamp %d " % (fname, timestamp)
f = open("/tmp" + os.sep + fname,'wb')
f.write(body)
f.close()
print "File saved in /tmp" + os.sep + fname
post_file(bdaddr, "/tmp" + os.sep + fname)
trayicon.set_blinking(0)
bo.set_response (True)
def error_callback (bo, bdaddr, err):
print ("got error %d from %s" % (err, bdaddr))
def complete_callback (bo, bdaddr):
print ("transfer complete from %s" % (bdaddr))
def post_file (sender, file):
username = get_key(USER_KEY)
password = get_key(PASS_KEY)
url = get_key(SERVER_KEY)
ch = pycurl.Curl()
ch.setopt(pycurl.URL, url)
print "Post file to " + url
post_fields = [
('file', (pycurl.FORM_FILE, file)),
('username', username),
('password', password),
('sender', sender)]
ch.setopt(pycurl.HEADER, 1)
ch.setopt(pycurl.POST, 1)
ch.setopt(pycurl.HTTPPOST, post_fields)
ch.perform()
def popup_menu_callback (widget, button, time, data = None):
if button == 3 and data:
data.show_all()
data.popup(None, None, None, 3, time)
def preferences_callback (widget, data = None):
dialog = gtk.Dialog("Foovision preferences")
h = gtk.HBox()
h.set_border_width(6)
h.set_spacing(6)
# Labels
v = gtk.VBox()
v.set_spacing(6)
l = gtk.Label("User:")
v.pack_start(l, True, False, 0)
l = gtk.Label("Password:")
v.pack_start(l, True, False, 0)
l = gtk.Label("Server:")
v.pack_start(l, True, False, 0)
h.pack_start(v, False, False, 0)
# Entries
v = gtk.VBox()
v.set_spacing(6)
user_entry = gtk.Entry()
user_entry.set_width_chars(25)
user_entry.set_text(get_key(USER_KEY))
v.pack_start(user_entry, True, True, 0)
pass_entry = gtk.Entry()
pass_entry.set_width_chars(25)
pass_entry.set_visibility(False)
pass_entry.set_text(get_key(PASS_KEY))
v.pack_start(pass_entry, True, True, 0)
server_entry = gtk.Entry()
server_entry.set_width_chars(25)
server_entry.set_text(get_key(SERVER_KEY))
v.pack_start(server_entry, True, True, 0)
h.pack_start(v, True, True, 0)
dialog.vbox.pack_start(h, False, False, 0)
dialog.vbox.show_all()
dialog.add_button (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
dialog.add_button (gtk.STOCK_APPLY, gtk.RESPONSE_APPLY)
dialog.connect("response", dialog_response_callback, user_entry, pass_entry, server_entry)
dialog.run()
dialog.destroy()
def dialog_response_callback(dialog, response, user, pwd, server):
if (response == gtk.RESPONSE_APPLY):
gconf_client.set_string(USER_KEY, user.get_text())
gconf_client.set_string(PASS_KEY, pwd.get_text())
gconf_client.set_string(SERVER_KEY, server.get_text())
print "Saved preferences"
else:
print "Cancel"
def quit_callback (widget, data = None):
if data:
data.set_visible(False)
gtk.main_quit()
def get_key (k):
v = ""
v = gconf_client.get_string(k)
if (v == None):
if (k == SERVER_KEY):
v = "http://foovision.org/receiver"
else:
v = ""
gconf_client.set_string(k, v)
return v
# Constants
FOOVISION_PATH = "/apps/foovision"
USER_KEY = FOOVISION_PATH + "/user"
PASS_KEY = FOOVISION_PATH + "/password"
SERVER_KEY = FOOVISION_PATH + "/server"
# Obex
bo = btctl.Obex()
bo.connect("progress", progress_callback);
bo.connect("request-put", request_put_callback);
bo.connect("put", put_callback);
bo.connect("error", error_callback);
bo.connect("complete", complete_callback);
if not bo.is_initialised():
print ("Server not initialised")
sys.exit (1)
# GConf client
gconf_client = gconf.client_get_default()
# Tray icon
trayicon = gtk.StatusIcon()
trayicon.set_from_file("foovision.png")
menu = gtk.Menu()
menuItem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
menuItem.connect('activate', preferences_callback)
menu.append(menuItem)
menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuItem.connect('activate', quit_callback, trayicon)
menu.append(menuItem)
trayicon.connect('popup-menu', popup_menu_callback, menu)
print "pyfoovision running..."
gtk.main()
| Python |
#! /usr/bin/python
import pygtk
pygtk.require("2.0")
import os
import sys
import btctl
import gtk
import gconf
import pycurl
import urllib
def progress_callback (bo, bdaddr):
trayicon.set_blinking(1)
print ("got progress from %s" % (bdaddr))
def request_put_callback (bo, bdaddr):
print ("device %s wants to send a file" % (bdaddr))
bo.set_response (True)
def put_callback (bo, bdaddr, fname, body, timestamp):
print ("device %s sent a file" % (bdaddr))
print "Filename %s, timestamp %d " % (fname, timestamp)
f = open("/tmp" + os.sep + fname,'wb')
f.write(body)
f.close()
print "File saved in /tmp" + os.sep + fname
post_file(bdaddr, "/tmp" + os.sep + fname)
trayicon.set_blinking(0)
bo.set_response (True)
def error_callback (bo, bdaddr, err):
print ("got error %d from %s" % (err, bdaddr))
def complete_callback (bo, bdaddr):
print ("transfer complete from %s" % (bdaddr))
def post_file (sender, file):
username = get_key(USER_KEY)
password = get_key(PASS_KEY)
url = get_key(SERVER_KEY)
ch = pycurl.Curl()
ch.setopt(pycurl.URL, url)
print "Post file to " + url
post_fields = [
('file', (pycurl.FORM_FILE, file)),
('username', username),
('password', password),
('sender', sender)]
ch.setopt(pycurl.HEADER, 1)
ch.setopt(pycurl.POST, 1)
ch.setopt(pycurl.HTTPPOST, post_fields)
ch.perform()
def popup_menu_callback (widget, button, time, data = None):
if button == 3 and data:
data.show_all()
data.popup(None, None, None, 3, time)
def preferences_callback (widget, data = None):
dialog = gtk.Dialog("Foovision preferences")
h = gtk.HBox()
h.set_border_width(6)
h.set_spacing(6)
# Labels
v = gtk.VBox()
v.set_spacing(6)
l = gtk.Label("User:")
v.pack_start(l, True, False, 0)
l = gtk.Label("Password:")
v.pack_start(l, True, False, 0)
l = gtk.Label("Server:")
v.pack_start(l, True, False, 0)
h.pack_start(v, False, False, 0)
# Entries
v = gtk.VBox()
v.set_spacing(6)
user_entry = gtk.Entry()
user_entry.set_width_chars(25)
user_entry.set_text(get_key(USER_KEY))
v.pack_start(user_entry, True, True, 0)
pass_entry = gtk.Entry()
pass_entry.set_width_chars(25)
pass_entry.set_visibility(False)
pass_entry.set_text(get_key(PASS_KEY))
v.pack_start(pass_entry, True, True, 0)
server_entry = gtk.Entry()
server_entry.set_width_chars(25)
server_entry.set_text(get_key(SERVER_KEY))
v.pack_start(server_entry, True, True, 0)
h.pack_start(v, True, True, 0)
dialog.vbox.pack_start(h, False, False, 0)
dialog.vbox.show_all()
dialog.add_button (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
dialog.add_button (gtk.STOCK_APPLY, gtk.RESPONSE_APPLY)
dialog.connect("response", dialog_response_callback, user_entry, pass_entry, server_entry)
dialog.run()
dialog.destroy()
def dialog_response_callback(dialog, response, user, pwd, server):
if (response == gtk.RESPONSE_APPLY):
gconf_client.set_string(USER_KEY, user.get_text())
gconf_client.set_string(PASS_KEY, pwd.get_text())
gconf_client.set_string(SERVER_KEY, server.get_text())
print "Saved preferences"
else:
print "Cancel"
def quit_callback (widget, data = None):
if data:
data.set_visible(False)
gtk.main_quit()
def get_key (k):
v = ""
v = gconf_client.get_string(k)
if (v == None):
if (k == SERVER_KEY):
v = "http://foovision.org/receiver"
else:
v = ""
gconf_client.set_string(k, v)
return v
# Constants
FOOVISION_PATH = "/apps/foovision"
USER_KEY = FOOVISION_PATH + "/user"
PASS_KEY = FOOVISION_PATH + "/password"
SERVER_KEY = FOOVISION_PATH + "/server"
# Obex
bo = btctl.Obex()
bo.connect("progress", progress_callback);
bo.connect("request-put", request_put_callback);
bo.connect("put", put_callback);
bo.connect("error", error_callback);
bo.connect("complete", complete_callback);
if not bo.is_initialised():
print ("Server not initialised")
sys.exit (1)
# GConf client
gconf_client = gconf.client_get_default()
# Tray icon
trayicon = gtk.StatusIcon()
trayicon.set_from_file("foovision.png")
menu = gtk.Menu()
menuItem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
menuItem.connect('activate', preferences_callback)
menu.append(menuItem)
menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuItem.connect('activate', quit_callback, trayicon)
menu.append(menuItem)
trayicon.connect('popup-menu', popup_menu_callback, menu)
print "pyfoovision running..."
gtk.main()
| Python |
#!/usr/bin/python
'''
Created on Apr 4, 2014
@Course: CS6242
'''
import requests
import xml.etree.ElementTree as ET
import csv
def getMatch(id):
url = "http://playground.opta.net/?game_id="+str(id)+"&feed_type=F7"
res = requests.get(url)
data = res.content
return data
def getEvent(id):
url = "http://playground.opta.net/?game_id="+str(id)+"&feed_type=F24"
res = requests.get(url)
data = res.content
return data
def saveCSV1(file,data):
with open(file, 'wb') as f:
wtr = csv.writer(f, delimiter=',')
for key, value in data.items():
item = []
item.append(key);
item.extend(value)
wtr.writerow(item)
def saveCSV2(file,data):
with open(file, 'wb') as f:
wtr = csv.writer(f, delimiter=',')
for key, value in data.items():
item = []
item.extend(list(key));
item.extend(value)
wtr.writerow(item)
if __name__=="__main__":
BeginID = 131897
EndID = 131986
Data_Match=dict(); Data_Team=dict(); Data_Player=dict(); Data_PerfFP=dict(); Data_PerfGK=dict()
Data_FPlayer=dict(); Data_GKeeper=dict();Player_Pass = dict()
#------------------------------- F7 feed ---------------------------------#
for id in range(BeginID, EndID+1):
'''131956/131986 is missing'''
temp_match = []; temp_player=[]
data = getMatch(id)
root = ET.fromstring(data)
if root.tag != 'response':
# Get Match info
SoccerDocument = root.find('SoccerDocument')
match_id = SoccerDocument.get('uID')[1:]
for Stat in SoccerDocument.find('Competition').findall('Stat'):
if(Stat.get('Type')=='matchday'):
matchday = Stat.text
for TeamData in SoccerDocument.find('MatchData').findall('TeamData'):
if(TeamData.get('Side')=='Home'):
team_home = TeamData.get('TeamRef')[1:]
score_home = TeamData.get('Score')
if(TeamData.get('Side')=='Away'):
team_away = TeamData.get('TeamRef')[1:]
score_away = TeamData.get('Score')
Data_Match[match_id]= [matchday,team_home,team_away,score_home,score_away]
# Get Team/Player info
for Team in SoccerDocument.findall('Team'):
team_id = Team.get('uID')[1:]
team_name = Team.find('Name').text
for Player in Team.findall('Player'):
player_id = Player.get('uID')[1:]
player_name = Player.find('PersonName')[0].text + " " + Player.find('PersonName')[1].text
Data_Player[player_id]= [team_id,player_name.encode('utf-8')]
Data_Team[team_id]= [team_name.encode('utf-8')]
#------------------------------- F24 feed ---------------------------------#
for id in range(BeginID, EndID+1):
print id
data = getEvent(id)
root = ET.fromstring(data)
list_player = [];list_position = [];list_tshirt=[]; antiGK=dict()
Game = root.find('Game')
match_id = Game.get('id')
away_team_id = Game.get('away_team_id')
home_team_id = Game.get('home_team_id')
# Get player/position list for initialization
for Event in Game.findall('Event'):
if(Event.get('type_id') =="34"):
for Q in Event.findall('Q'):
if Q.get('qualifier_id') =='30':
list_player.extend(p for p in Q.get('value').split(", "))
if Q.get('qualifier_id') =='44':
list_position.extend(p for p in Q.get('value').split(", "))
if Q.get('qualifier_id') =='59':
list_tshirt.extend(p for p in Q.get('value').split(", "))
# Initialize
for i,p in enumerate(list_player):
Data_FPlayer[(p,match_id)] = [0.0]*63
Data_GKeeper[(p,match_id)] = [0]*6
if(i%18 > 10):
#entry time
Data_FPlayer[(p,match_id)][60] = 90.0
#exit time
Data_FPlayer[(p,match_id)][61] = 90.0
#position
Data_FPlayer[(p,match_id)][62] = float(list_position[i])
antiGK[home_team_id] = list_player[18]
antiGK[away_team_id] = list_player[0]
# Update Stats (Raw data)
for Event in Game.findall('Event'):
period_id = Event.get('period_id')
if(period_id =="1" or period_id =="2"):
player_id = Event.get('player_id')
type = Event.get('type_id')
if (player_id != None):
# Field Player
x = Event.get('x'); y = Event.get('y');
if (period_id=='2'):
x = 100.0 - float(x)
y = 100.0 - float(y)
#sum of zone_x
Data_FPlayer[(player_id,match_id)][57]+=float(x)
#sum of zone_y
Data_FPlayer[(player_id,match_id)][58]+=float(y)
#sum of zone_count
Data_FPlayer[(player_id,match_id)][59]+=1
if(type=='1'):
#number of pass
count = 0
for Q in Event.findall('Q'):
if Q.get('qualifier_id') in ['2','5','6','107','123','124']:
count+= 1
if count == 0:
Data_FPlayer[(player_id,match_id)][0]+=1
#pass missed
if(Event.get('outcome')=='0'):
Data_FPlayer[(player_id,match_id)][3]+=1
count = 0
count2 = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id') in ['5','6']):
count+=1
for Q in Event.findall('Q'):
if (Q.get('qualifier_id') =='2'):
count2+=1
if count == 0 and count2 ==1:
#cross
Data_FPlayer[(player_id,match_id)][1]+=1
#ball touched
count = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='123'):
count+=1
if count == 0:
Data_FPlayer[(player_id,match_id)][2]+=1
if(type=='2'):
#offside
for Q in Event.findall('Q'):
if Q.get('qualifier_id') =='7':
p = Q.get('value')
Data_FPlayer[(p,match_id)][4]+=1
if(type in ['2','3','7','8','9','10','11','12','13','14','15','16','41','42','50','52','54','61']):
#ball touched
Data_FPlayer[(player_id,match_id)][2]+=1
if(type=='4'):
#number of fouls
if(Event.get('outcome')=='0'):
Data_FPlayer[(player_id,match_id)][5]+=1
if(type=='7'):
#number of successful tackles
Data_FPlayer[(player_id,match_id)][6]+=1
if(type=='8'):
#number of interception
Data_FPlayer[(player_id,match_id)][7]+=1
if(type in ['13','14','15','16']):
#number of shots
Data_FPlayer[(player_id,match_id)][8]+=1
#number of freekick shots
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='26'):
Data_FPlayer[(player_id,match_id)][9]+=1
if(type=='16'):
#number of goal non-stopped
team_id = Event.get('team_id')
Data_GKeeper[(antiGK[team_id],match_id)][0]+=1
#number of assists
if(Event.get('outcome')=='1'):
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='55'):
event_id = Q.get('value')
for e in root.iter('Event'):
if (e.get('event_id')== event_id):
p = e.get('player_id')
Data_FPlayer[(p,match_id)][10]+=1
if(Event.get('outcome')=='1'):
count = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='28'):
count+=1
if count == 0:
#number of goals
Data_FPlayer[(player_id,match_id)][11]+=1
count2 = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='22'):
#open-play goal
Data_FPlayer[(player_id,match_id)][12]+=1
if (Q.get('qualifier_id')=='15'):
#head goal
Data_FPlayer[(player_id,match_id)][13]+=1
if (Q.get('qualifier_id') in ['24','9']):
count2+=1
if count2!=0:
#freekick goal
Data_FPlayer[(player_id,match_id)][14]+=1
if(type in ['15','16']):
#on-target shot
Data_FPlayer[(player_id,match_id)][15]+=1
if(type=='17'):
count = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id') in ['31','32']):
count +=1
if (Q.get('qualifier_id')=='33'):
#red cards
Data_FPlayer[(player_id,match_id)][17]+=1
if count!=0:
#yellow cards
Data_FPlayer[(player_id,match_id)][16]+=1
if(type=='44'):
#aerial duel
Data_FPlayer[(player_id,match_id)][18]+=1
if(Event.get('outcome')=='1'):
#aerial duel won
Data_FPlayer[(player_id,match_id)][19]+=1
if(type in ['18','32','34','36','40']):
count = 0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='41'):
count+=1
if count!=0:
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='53'):
p = Q.get('value')
#number of injuries
Data_FPlayer[(p,match_id)][20]+=1
if(type=='1'):
if(Event.get('outcome')=='1'):
event_id = int(Event.get('event_id'))+1
team_id = Event.get('team_id')
for e in root.iter('Event'):
if (e.get('event_id')== str(event_id)):
p = e.get('player_id')
t = e.get('team_id')
if p!=None and t==team_id:
idx = list_player.index(p)
# 36 players
Data_FPlayer[(player_id,match_id)][idx+21]+=1
Player_Pass.setdefault((match_id,team_id,player_id,p), [0]*1)
Player_Pass[(match_id,team_id,player_id,p)][0]+=1
if(type=='18'):
#exit
Data_FPlayer[(player_id,match_id)][61]=float(Event.get('min'))
if(type=='19'):
#substitute
Data_FPlayer[(player_id,match_id)][60]= float(Event.get('min'))
for Q in Event.findall('Q'):
if (Q.get('qualifier_id')=='44'):
positionName = Q.get('value')
if(positionName == 'Goalkeeper'):
Data_FPlayer[(player_id,match_id)][62]=1.0
if Event.get('team_id') == home_team_id:
antiGK[away_team_id] = player_id
else :
antiGK[home_team_id] = player_id
elif (positionName == 'Defender'):
Data_FPlayer[(player_id,match_id)][62]=2.0
elif (positionName == 'Midfielder'):
Data_FPlayer[(player_id,match_id)][62]=3.0
elif (positionName == 'Forward'):
Data_FPlayer[(player_id,match_id)][62]=4.0
if(type=='10'):
count=0
for Q in Event.findall('Q'):
if (Q.get('qualifier_id') == '94'):
count+=1
if count==0:
#number of save
Data_GKeeper[(player_id,match_id)][1]+=1
if(type=='11'):
if (Event.get('outcome')=='1'):
#number of cross claimed
Data_GKeeper[(player_id,match_id)][2]+=1
else:
#number of error
Data_GKeeper[(player_id,match_id)][4]+=1
if(type=='41'):
#number of punch
Data_GKeeper[(player_id,match_id)][3]+=1
if(type=='59'):
#number of keeper sweeper
Data_GKeeper[(player_id,match_id)][5]+=1
if (Event.get('outcome')=='0'):
#number of error
Data_GKeeper[(player_id,match_id)][4]+=1
# Transform data
for i,p in enumerate(list_player):
#-----------------------Field Player--------------------------#
num_pass = Data_FPlayer[(p,match_id)][0] #number of pass
num_cross = Data_FPlayer[(p,match_id)][1] #number of cross
num_balltouched = Data_FPlayer[(p,match_id)][2] #number of ball touched
num_goal = Data_FPlayer[(p,match_id)][11] #number of goal
num_headgoal = Data_FPlayer[(p,match_id)][13] #number of head goal
num_freekickgoal = Data_FPlayer[(p,match_id)][14] #number of freekick goal
num_normalgoal = Data_FPlayer[(p,match_id)][12] #number of normal goal
num_shot = Data_FPlayer[(p,match_id)][8] #number of shot
num_freekickshot = Data_FPlayer[(p,match_id)][9] #number of freekick shot
num_tackle = Data_FPlayer[(p,match_id)][6] #number of successful tackle
num_interception = Data_FPlayer[(p,match_id)][7] #number of interception
num_foul = Data_FPlayer[(p,match_id)][5] #number of foul
num_offside = Data_FPlayer[(p,match_id)][4] #number of offside
num_assist = Data_FPlayer[(p,match_id)][10] #number of assist
num_yellowcard = Data_FPlayer[(p,match_id)][16] #number of yellow card
num_redcard = Data_FPlayer[(p,match_id)][17] #number of red card
num_injury = Data_FPlayer[(p,match_id)][20] #number of injury
temp_list = Data_FPlayer[(p,match_id)][21:56]
temp_list.sort()
coplayer1 = list_player[Data_FPlayer[(p,match_id)][21:56].index(temp_list[-1])]
coplayer2 = list_player[Data_FPlayer[(p,match_id)][21:56].index(temp_list[-2])]
coplayer3 = list_player[Data_FPlayer[(p,match_id)][21:56].index(temp_list[-3])]
tshirt = int(list_tshirt[i]) #t-shirt
position = int(Data_FPlayer[(p,match_id)][62])#position
if(Data_FPlayer[(p,match_id)][0]!=0.0):
pass_precision = (Data_FPlayer[(p,match_id)][0]-Data_FPlayer[(p,match_id)][3])/Data_FPlayer[(p,match_id)][0] #pass precision
else:
pass_precision = -1.0
if(Data_FPlayer[(p,match_id)][8]!=0.0):
shot_precision = Data_FPlayer[(p,match_id)][15]/Data_FPlayer[(p,match_id)][8]
else:
shot_precision = -1.0
if(Data_FPlayer[(p,match_id)][18]!=0.0):
aerialduel_won = Data_FPlayer[(p,match_id)][19]/Data_FPlayer[(p,match_id)][18]
else:
aerialduel_won = -1.0
timeplayed = Data_FPlayer[(p,match_id)][61] - Data_FPlayer[(p,match_id)][60]
if Data_FPlayer[(p,match_id)][59]!=0.0:
zone_x = Data_FPlayer[(p,match_id)][57]/Data_FPlayer[(p,match_id)][59]
zone_y = Data_FPlayer[(p,match_id)][58]/Data_FPlayer[(p,match_id)][59]
else:
zone_x = 0.0
zone_y= 0.0
if(position!=1 and timeplayed!=0.0):
Data_PerfFP[(p,match_id)]=[]
Data_PerfFP[(p,match_id)].extend([num_pass,num_cross,num_balltouched,num_goal,num_headgoal, num_freekickgoal, num_normalgoal, num_shot, num_freekickshot
,num_tackle,num_interception,num_foul,num_offside,num_assist,num_yellowcard,num_redcard,num_injury,coplayer1,coplayer2,coplayer3,tshirt,position
,pass_precision,shot_precision,aerialduel_won,timeplayed,zone_x,zone_y])
#-----------------------Goal Keeper--------------------------#
num_nonestoppedgoal = Data_GKeeper[(p,match_id)][0]
num_save = Data_GKeeper[(p,match_id)][1]
num_crossclaimed = Data_GKeeper[(p,match_id)][2]
num_punch = Data_GKeeper[(p,match_id)][3]
num_error = Data_GKeeper[(p,match_id)][4]
num_keepersweeper = Data_GKeeper[(p,match_id)][5]
if(position==1):
Data_PerfGK[(p,match_id)]=[]
Data_PerfGK[(p,match_id)].extend([num_nonestoppedgoal,num_save,num_crossclaimed,num_punch,num_error,num_keepersweeper ])
# Save the file
#saveCSV1('Match.csv',Data_Match)
#saveCSV1('Team.csv',Data_Team)
#saveCSV1('Player.csv',Data_Player)
# saveCSV2('Performance-FP.csv',Data_PerfFP)
# saveCSV2('Performance-GK.csv',Data_PerfGK)
saveCSV2('Player-Pass.csv',Player_Pass)
| Python |
import logging
import os
import os.path
def update_attribute(attributes, name, value):
"""Finds the attribute name and sets it to value in the attributes tuple of tuples, returns the attributes tuple of tuples with the changed attribute."""
ret = list()
# find name in attributes
for n, v in attributes:
if n == name:
ret.append((name, value))
else:
ret.append((n,v))
return tuple(ret)
def split_filename_and_anchor(filename):
parts = filename.split("#")
if len(parts) > 2:
raise Exception("Was passed filename with two (or more) # in it")
elif len(parts) == 2:
file = parts[0]
anchor = parts[1]
else:
file = parts[0]
anchor = None
return tuple([file, anchor])
def change_filename(filename, newext, orginaldir, destdir, makedirs=True):
"""Returns the filename after transforming it to be in destdir and making sure the folders required all exist. Will not damage #anchors at the ends of the paths."""
filename = os.path.normpath(filename)
filename, anchor = split_filename_and_anchor(filename)
if len(filename) != 0:
orginaldir = os.path.normpath(orginaldir)
destdir = os.path.normpath(destdir)
logging.debug(" change_filename('%s', '%s', '%s', '%s', %s)", filename, newext, orginaldir, destdir, makedirs)
outfile_name1 = filename.replace(orginaldir, ".") # files relative name
logging.debug("%s", outfile_name1)
if newext == None:
outfile_name3 = outfile_name1
else:
outfile_name2 = os.path.splitext(outfile_name1)[0] #file's name without ext
logging.debug("%s", outfile_name2)
outfile_name3 = outfile_name2 + newext
logging.debug("%s", outfile_name3)
outfile_name4 = os.path.join(destdir, outfile_name3)
logging.debug("%s", outfile_name4)
outfile_name = os.path.normpath(outfile_name4)
logging.debug("%s", outfile_name)
# make sure that the folder exists to output, if wanted
if makedirs:
outfile_path = os.path.dirname(outfile_name)
if os.path.exists(outfile_path):
if os.path.isdir(outfile_path):
pass # do nothing because the folder already exists
else:
raise Exception("%s already exists but is not a directory"%(outfile_path))
else:
os.makedirs(outfile_path)
else:
outfile_name = filename
if anchor == None:
return outfile_name
else:
return "#".join([outfile_name, anchor])
def make_directory_for_filename(filename):
"""Returns False if direcotry for filename already exists, True if
function was successfully able to create the directory, or raises
and exception for the error."""
path = os.path.dirname(filename)
if os.path.exists(path):
if os.path.isdir(path):
return False
else:
raise ExistsButNotDirectoryError(path)
else:
# only remaing exception to throw is if the user does not have permission
try:
os.makedirs(path)
return True
except:
raise
class ExistsButNotDirectoryError(IOError):
def __init__(self, path="Not Specified"):
self.path = path
def __str__():
return "Path (%s) exists but is not a directory!" | Python |
import sqlite3
import os
import sys
import atexit
import traceback
import shutil
import zipfile
import string
from optparse import OptionParser
import logging
NOTICE = 25 # added level for app
import HTMLParser
try:
import markdown
except ImportError:
print "ERROR: Unable to import markdown the markup parser."
print " Make sure that markdown has been installed"
print " see the ReadMe.txt for more information"
raise
from helpparsers import Stage2Parser, Stage3Parser, Stage4Parser, Stage5Parser
from utilfunctions import change_filename
def main(argv):
parser = OptionParser(usage="%prog <jobtype> <outfile> <indir> [options]")
parser.add_option("-t", "--temp",
help="use TEMPDIR to store the intermedite build files",
metavar="TEMPDIR")
parser.add_option("-q", "--quiet", action="store_true",
dest="quiet", default=False,
help="don't print most status messages to stdout")
parser.add_option("-d", "--debug", action="store_true",
default=False, help="print debugging information to the screen")
parser.add_option("-c", "--cfile", default=None, dest="carrayfilename",
metavar="FILE", help="filename to output the c array to. Defaults to same folder as outfile.")
parser.add_option("-a", "--alwaysbuild", action="store_true",
default=False, dest="always_build",
help="when building, builder should always build source files. (Usally used with filesystems that do not update the modified time)")
(options, args) = parser.parse_args(argv)
if len(args) != 4 :
parser.error("Incorrect number of arguments")
options.type = args[1]
options.outfile = os.path.normpath(args[2])
options.indir = os.path.normpath(args[3])
loglevel=logging.INFO
logging.addLevelName(NOTICE, "NOTICE")
if options.quiet:
loglevel=NOTICE
elif options.debug:
loglevel=logging.DEBUG
logging.basicConfig(level=loglevel, format='%(levelname)7s:%(message)s')
if options.type == "build":
pass
elif options.type == "rebuild":
pass
elif options.type == "clean":
pass
else:
parser.error("jobtype must be one of: build, rebuild, or clean")
if not options.temp:
logging.info("No working directory set. Creating one in system temp.")
options.temp = tempfile.mkdtemp()
def cleanup(dir):
if os.path.exists(dir):
shutil.rmtree(options.temp, onerror=rmtree_error_handler)
atexit.register(cleanup, options.temp)
logging.debug("Doing a '%s'", options.type)
logging.debug("Using '%s' as working directory", options.temp )
logging.debug("Using '%s' as output file", options.outfile )
logging.debug("Using '%s' as input directory", options.indir )
if options.type == "build":
ret = call_logging_exceptions(build, options)
elif options.type == "rebuild":
ret = call_logging_exceptions(rebuild, options)
else:
ret = call_logging_exceptions(clean, options)
sys.exit(ret)
def call_logging_exceptions(func, *args, **kwargs):
"""Protects the caller from all exceptions that occur in the callee. Logs the exceptions that do occur."""
try:
func(*args, **kwargs)
except:
( type, value, tb ) = sys.exc_info()
logging.error("***EXCEPTION:")
logging.error(" %s: %s", type.__name__, value)
for filename, line, function, text in traceback.extract_tb(tb):
logging.error("%s:%d %s", os.path.basename(filename), line, function)
logging.error(" %s", text)
del tb
return 1
return 0
def rebuild(options):
logging.log(NOTICE, "Rebuilding")
ret = call_logging_exceptions(clean, options)
if ret != 0:
return ret
ret = call_logging_exceptions(build, options)
return ret
def clean(options):
logging.log(NOTICE, "Cleaning..")
logging.info("Removing outfile: %s", options.outfile )
if os.path.exists(options.outfile):
if os.path.isfile(options.outfile):
os.remove(options.outfile)
else:
logging.error(" <outfile> is not a file. Make sure your parameters are in the correct order")
sys.exit(2)
else:
logging.info(" Outfile (%s) does not exist", options.outfile)
logging.info("Removing workdirectory: %s", options.temp )
if os.path.exists(options.temp):
if os.path.isdir(options.temp):
shutil.rmtree(options.temp, onerror=rmtree_error_handler)
else:
logging.error("tempdir is not a file. Make sure your parameters are in the correct order")
sys.exit(2)
else:
logging.info(" Work directory (%s) does not exist", options.temp)
def rmtree_error_handler(function, path, excinfo):
if function == os.remove:
logging.warning(" Unable to remove %s", path)
elif function == os.rmdir:
logging.warning(" Unable to remove directory %s", path)
else:
(type, value, tb) = excinfo
logging.error("***EXCEPTION:")
logging.error(" %s: %s", type.__name__, value)
for filename, line, function, text in traceback.extract_tb(tb):
logging.error("%s:%d %s", os.path.basename(filename), line, function)
logging.error(" %s", text)
def build(options):
"""Compiles the files in options.indir to the archive output options.outfile.
Compiled in several stages:
stage1: Transform all input files with markdown placing the results into options.temp+"/stage1".
stage2: Parses and strips the output of stage1 to build the list that will be made into the c-array that contains the compiled names for the detailed help of each control.
stage3: Parses the output of stage2 to grab the images that are refered to in the the output of stage1
stage4: Parses the output of stage1 to fix the relative hyperlinks in the output so that they will refer correctly to the correct files when in output file.
stage5: Generate the index and table of contents for the output file from the output of stage4.
stage6: Zip up the output of stage5 and put it in the output location.
"""
logging.log(NOTICE, "Building...")
files = generate_paths(options)
if should_build(options, files):
input_files = generate_input_files_list(options)
helparray = list()
extrafiles = list()
logging.log(NOTICE, " Processing input files:")
for file in input_files:
logging.log(NOTICE, " %s", file)
logging.info(" Stage 1")
name1 = process_input_stage1(file, options, files)
logging.info(" Stage 2")
name2 = process_input_stage2(name1, options, files, helparray)
logging.info(" Stage 3")
name3 = process_input_stage3(name2, options, files, extrafiles)
logging.info(" Stage 4")
name4 = process_input_stage4(name3, options, files)
logging.info(" Stage 5")
process_input_stage5(options, files, extrafiles)
logging.info(" Stage 6")
process_input_stage6(options, files)
logging.info(" Generating .cpp files")
generate_cpp_files(options, files, helparray)
logging.log(NOTICE, "....Done.")
else:
logging.log(NOTICE, " Up to date.")
def generate_paths(options):
"""Generates the names of the paths that will be needed by the compiler during it's run, storing them in a dictionary that is returned."""
paths = dict()
for i in range(1, 7):
paths['stage%d'%(i)] = os.path.join(options.temp, 'stage%d'%(i))
for path in paths.values():
if not os.path.exists(path):
logging.debug(" Making %s", path)
os.makedirs(path)
return paths
def should_build(options, files):
"""Checks the all of the files touched by the compiler to see if we need to rebuild. Returns True if so."""
if options.always_build:
return True
elif not os.path.exists(options.outfile):
return True
elif options.carrayfilename != None and not os.path.exists(options.carrayfilename):
return True
elif check_source_newer_than_outfile(options, files):
return True
return False
def check_source_newer_than_outfile(options, files):
"""Checks to see if any file in the source directory is newer than the output file."""
try:
outfile_time = os.path.getmtime(options.outfile)
for dirpath, dirnames, filenames in os.walk(options.indir):
for file in filenames:
filepath = os.path.join(dirpath, file)
if os.path.getmtime(filepath) > outfile_time:
logging.info("%s has been changed since outfile. Causing build", filepath)
return True
elif os.path.getctime(filepath) > outfile_time:
logging.info("%s has been created since outfile. Causing build", filepath)
return True
except OSError:
logging.warning("Encountered a file (%s) that the os does not like. Forcing build.", "TODO")
return True
return False
def generate_input_files_list(options):
"""Returns a list of all input (.help) files that need to be parsed by markdown."""
return generate_file_list(options.indir, ".help")
def generate_file_list(directory, extension):
file_list = list()
for path, dirs, files in os.walk(directory):
for file in files:
if os.path.splitext(file)[1] == extension:
# I only want the .help files
file_list.append(os.path.join(path, file))
return file_list
def process_input_stage1(file, options, files):
infile = open(file, mode="r")
input = infile.read()
infile.close()
md = markdown.Markdown(
extensions=['toc']
)
output = md.convert(input)
outfile_name = change_filename(file, ".stage1", options.indir, files['stage1'])
outfile = open(outfile_name, mode="w")
outfile.write(output)
outfile.close()
return outfile_name
def process_input_stage2(file, options, files, helparray):
infile = open(file, mode="r")
input = infile.read()
infile.close()
outname = change_filename(file, ".stage2", files['stage1'], files['stage2'])
outfile = open(outname, mode="w")
parser = Stage2Parser(file=outfile)
parser.feed(input)
parser.close()
outfile.close()
if len(parser.control) > 0:
filename_in_archive = change_filename(outname, ".htm", files['stage2'], ".", makedirs=False)
for control in parser.control:
helparray.append((control, filename_in_archive))
logging.debug(" Control name %s", control)
return outname
def process_input_stage3(file, options, files, extrafiles):
infile = open(file, mode="r")
input = infile.read()
infile.close()
outname = change_filename(file, ".stage3", files['stage2'], files['stage3'])
outfile = open(outname, mode="w")
#figure out what subdirectory of the onlinehelp I am in
subdir = string.replace(os.path.dirname(outname), os.path.normpath(files['stage3']), "")
if subdir.startswith(os.path.sep):
subdir = string.replace(subdir, os.path.sep, "", 1) # I only want to remove the leading sep
parser = Stage3Parser(options, files, file=outfile, extrafiles=extrafiles, subdir=subdir)
parser.feed(input)
parser.close()
outfile.close()
return outname
def process_input_stage4(file, options, files):
"""Fix the a tags so that they point to the htm files that will be in the output archive."""
infile = open(file, mode="r")
input = infile.read()
infile.close()
outname = change_filename(file, ".stage4", files['stage3'], files['stage4'])
outfile = open(outname, mode="w")
#figure out what subdirectory of the onlinehelp I am in
subdir = string.replace(os.path.dirname(outname), os.path.normpath(files['stage4']), "")
if subdir.startswith(os.path.sep):
subdir = string.replace(subdir, os.path.sep, "", 1) # I only want to remove the leading sep
parser = Stage4Parser(files=files, file=outfile, options=options,
subdir=subdir)
parser.feed(input)
parser.close()
outfile.close()
return outname
def process_input_stage5(options, files, extrafiles):
"""Generate the index and table of contents for the output file from the output of stage4."""
# write header file
headerfile_name = os.path.join(files['stage5'], "header.hhp")
headerfile = open(headerfile_name, mode="w")
headerfile.write(
"""Contents file=%(contents)s\nIndex file=%(index)s\nTitle=%(title)s\nDefault topic=%(default)s\nCharset=UTF-8\n""" %
{ "contents": "contents.hhc",
"index": "index.hhk",
"title": "wxLauncher User Guide",
"default": "index.htm"
})
headerfile.close()
# generate both index and table of contents
tocfile_name = os.path.join(files['stage5'], "contents.hhc")
tocfile = open(tocfile_name, mode="w")
tocfile.write("<ul>\n")
toclevel = 1
indexfile_name = os.path.join(files['stage5'], "index.hhk")
indexfile = open(indexfile_name, mode="w")
indexfile.write("<ul>\n")
help_files = generate_file_list(files['stage4'], ".stage4")
last_path_list = []
for path, dirs, thefiles in os.walk(files['stage4']):
"""new directory. If the directory is not the base directory then check if there will be an index.htm for this directory.
If there is an index.htm then parse it for the title so that the subsection will have the title of the index.htm as the name of the subsection.
If there is no index.htm then make a default one and use the name of the directory as the subsection name.
Note that this algorithm requires that os.walk generates the names in alphabetical order."""
# relativize directory path for being in the archive
path_in_arc = make_path_in_archive(path, files['stage4'])
logging.debug("Processing directory '%s'", path_in_arc)
path_list = path_in_arc.split(os.path.sep)
if len(path_list) == 1 and path_list[0] == '':
path_list = []
level = len(path_list)
# parse the index.help to get the name of the section
index_file_name = os.path.join(path, "index.stage4")
# relativize filename for being in the archive
index_in_archive = change_filename(index_file_name, ".htm", files['stage4'], ".", False)
index_in_archive = index_in_archive.replace(os.path.sep, "/") # make the separators the same so that it doesn't matter what platform the launcher is built on.
# find the title
outindex_name = change_filename(index_file_name, ".htm", files['stage4'], files['stage5'])
outindex = open(outindex_name, mode="w")
inindex = open(index_file_name, mode="r")
input = inindex.read()
inindex.close()
parser = Stage5Parser(file=outindex)
parser.feed(input)
parser.close()
outindex.close()
tocfile.write(generate_sections(path_list, last_path_list,index_filename=index_in_archive, section_title=parser.title))
last_path_list = path_list
if level > 0:
# remove index.htm from thefiles because they are used by the section names
try:
thefiles.remove('index.stage4')
except ValueError:
logging.warning("Directory %s does not have an index.help", path_in_arc)
for file in thefiles:
full_filename = os.path.join(path, file)
# relativize filename for being in the archive
filename_in_archive = change_filename(full_filename, ".htm", files['stage4'], ".", False)
# find the title
outfile_name = change_filename(full_filename, ".htm", files['stage4'], files['stage5'])
outfile = open(outfile_name, mode="w")
infile = open(full_filename, mode="r")
input = infile.read()
infile.close()
parser = Stage5Parser(file=outfile)
parser.feed(input)
parser.close()
outfile.close()
tocfile.write(
"""%(tab)s<li> <object type="text/sitemap">\n%(tab)s <param name="Name" value="%(name)s">\n%(tab)s <param name="Local" value="%(file)s">\n%(tab)s </object>\n""" % {
"tab": " "*level,
"name": parser.title,
"file": filename_in_archive, })
indexfile.write(
"""%(tab)s<li> <object type="text/sitemap">\n%(tab)s\t<param name="Name" value="%(name)s">\n%(tab)s\t<param name="Local" value="%(file)s">\n%(tab)s </object>\n""" % {
"tab": "\t",
"name": parser.title,
"file": filename_in_archive, })
tocfile.write(generate_sections([], last_path_list))
tocfile.write("</ul>\n")
tocfile.close()
indexfile.close()
# copy the extra files (i.e. images) from stage3
for extrafilename in extrafiles:
logging.debug(" Copying: %s", extrafilename)
dst = change_filename(extrafilename, None, orginaldir=files['stage3'], destdir=files['stage5'])
shutil.copy2(extrafilename, dst)
def generate_sections(path_list, last_path_list, basetab=0, orginal_path_list=None, index_filename=None, section_title=None):
"""Return the string that will allow me to write in the correct section."""
logging.debug(" generate_sections(%s, %s, %d, %s)", str(path_list), str(last_path_list), basetab, orginal_path_list)
if orginal_path_list == None:
orginal_path_list = path_list
if len(path_list) > 0 and len(last_path_list) > 0 and path_list[0] == last_path_list[0]:
logging.debug(" matches don't need to do anything")
return generate_sections(path_list[1:], last_path_list[1:], basetab+1, orginal_path_list, index_filename, section_title)
elif len(path_list) > 0 and len(last_path_list) > 0:
logging.debug(" go down then up")
s = generate_sections([], last_path_list, basetab, orginal_path_list, index_filename, section_title)
s += generate_sections(path_list, [], basetab, orginal_path_list, index_filename, section_title)
return s
elif len(path_list) > 0 and len(last_path_list) == 0:
logging.debug(" go up (deeper)")
if index_filename == None:
raise Exception("index_filename is None")
if section_title == None:
title = path_list[len(path_list)-1]
else:
title = section_title
s = ""
for path in path_list:
s += """%(tab)s<li> <object type="text/sitemap">\n%(tab)s <param name="Name" value="%(name)s">\n%(tab)s <param name="Local" value="%(file)s">\n%(tab)s </object>\n%(tab)s <ul>\n""" % {
"tab": " "*basetab,
"name": title,
"file": index_filename }
return s
elif len(path_list) == 0 and len(last_path_list) > 0:
logging.debug(" do down")
s = ""
basetab += len(last_path_list)
for path in last_path_list:
s += """%(tab)s</ul>\n""" % { 'tab': " "*(basetab) }
basetab -= 1
return s
elif len(path_list) == 0 and len(last_path_list) == 0:
logging.debug(" both lists empty, doing nothing")
return ''
else:
raise Exception("Should never get here")
return ""
def make_path_in_archive(path, path1):
"""Return the part of the path that is in 'path' but not in 'path1'"""
path = os.path.normpath(path)
path1 = os.path.normpath(path1)
list = path.split(os.path.sep)
list1 = path1.split(os.path.sep)
return os.path.sep.join(make_path_in_archive_helper(list, list1))
def make_path_in_archive_helper(list, list1):
if len(list) > 0 and len(list1) > 0 and list[0] == list1[0]:
return make_path_in_archive_helper(list[1:], list1[1:])
elif len(list) > 0 and len(list1) == 0:
return os.path.join(list)
else:
return []
def process_input_stage6(options, stage_dirs):
#make sure that the directories exist before creating file
outfile_path = os.path.dirname(options.outfile)
if os.path.exists(outfile_path):
if os.path.isdir(outfile_path):
pass
else:
log.error(" %s exists but is not a directory", outfile_path)
else:
os.makedirs(outfile_path)
outzip = zipfile.ZipFile(options.outfile, mode="w", compression=zipfile.ZIP_DEFLATED)
for path, dirs, files in os.walk(stage_dirs['stage5']):
for filename in files:
full_filename = os.path.join(path, filename)
arcname = change_filename(full_filename, None, stage_dirs['stage5'], ".", False)
logging.debug(" Added %s as %s", full_filename, arcname)
outzip.write(full_filename, arcname)
outzip.close()
def enum_directories(dir):
ret = os.path.dirname(dir).split(os.path.sep)
if len(ret) == 1 and len(ret[0]) == 0:
ret = list()
logging.debug(" Enum directories %s", str(ret))
return ret
def generate_cpp_files(options, files, helparray):
if options.carrayfilename == None:
defaultname = os.path.join(os.path.dirname(options.outfile), "helplinks.cpp")
logging.info("Filename for c-array has not been specified.")
logging.info(" using default %s" % (defaultname))
options.carrayfilename = defaultname
logging.log(NOTICE, "Writing to %s", options.carrayfilename)
outfile = open(options.carrayfilename, mode="w")
outfile.write("// Generated by scripts/onlinehelpmaker.py\n")
outfile.write("// GENERATED FILE - DO NOT EDIT\n")
for id, location in helparray:
outfile.write("""{%s,_T("%s")},\n""" %
( id, location.replace(os.path.sep, "/")))
outfile.close()
if __name__ == "__main__":
main(sys.argv)
| Python |
class Tag:
def __init__(self, name, attrs, data=None):
self.name = name
self.attributes = attrs
self.data = data | Python |
from optparse import OptionParser
import os.path
import sys
from version_file_builder import VersionFileBuilder
WORKFILE=3
OUTFILE=2
JOB=1
def main(argv):
parser = OptionParser(usage="%prog <jobtype> <outfile> <workfile> [options]")
parser.add_option("", "--hgpath",
help="use HGPATH as the executable that will be used to generate the version.cpp file. Defaults to hg",
metavar="HGPATH", default="hg")
(options, args) = parser.parse_args(argv)
if len(args) != 4:
parser.error("Incorrect number of arguments")
work = os.path.normcase(os.path.normpath(args[WORKFILE]))
file = os.path.normcase(os.path.normpath(args[OUTFILE]))
maker = VersionFileBuilder(work, file, options.hgpath)
if args[JOB] == "build":
maker.build()
elif args[JOB] == "rebuild":
maker.rebuild()
elif args[JOB] == "clean":
maker.clean()
else:
parser.error("Invalid JOB type. Use build, rebuild, or clean.")
sys.exit(2)
sys.exit(0)
if __name__ == "__main__":
main(sys.argv)
| Python |
import logging
import os
import os.path
import tempfile
import traceback
import sys
import shutil
import HTMLParser
from dataclasses import Tag
from utilfunctions import update_attribute, change_filename
class OutputParser(HTMLParser.HTMLParser):
"""The class is designed to be used as a base class. It will output the same html structure as the input file into a file like object (only needs write)."""
def __init__(self, file, *args, **kwargs):
HTMLParser.HTMLParser.__init__(self, *args, **kwargs)
if hasattr(file, 'write'):
self.outputfile = file
else:
raise Exception("file is not a file like object with a write function")
self.tagstack = list()
def handle_starttag(self, tag, attrs):
logging.debug(" Handle starttag: %s", tag)
logging.debug(" %s", attrs)
self.tagstack.append(Tag(tag, attrs))
def handle_startendtag(self, tag, attrs):
logging.debug(" Handle start and end tag: %s", tag)
logging.debug(" %s", attrs)
self.write_tag(Tag(tag, attrs))
def handle_endtag(self, tagname):
"""Finds the matching tag. If the tags are miss matched, function will go down the stack until it finds the match"""
logging.debug(" End tag: %s", tagname)
tag = self.find_match(tagname)
self.write_tag(tag)
def handle_data(self, data):
logging.debug(" Data: %s", data)
if len(self.tagstack) > 0:
tag = self.tagstack.pop()
if tag.data == None:
tag.data = data
else:
tag.data += data
self.tagstack.append(tag)
else:
self.outputfile.write(data)
def find_match(self, tagtofind, indent=0):
"""Recursive function to match the tag"""
tag = self.tagstack.pop()
if not tag.name == tagtofind:
logging.warning(" %smismatched tag found (expected %s, found %s)", " "*indent, tagtofind, tag.name)
self.write_tag(tag)
tag = self.find_match(tagtofind)
return tag
def write_tag(self, tag):
"""When tag stack is empty, writes tag to file passed in the constructor. When tag stack is not empty formats the tag and sets (or if the next tag.data is not None, appends) the formated string."""
if tag.data == None:
str = "<%s%s />" %(tag.name, self.format_attributes(tag))
else:
str = "<%s%s>%s</%s>" %(
tag.name, self.format_attributes(tag), tag.data, tag.name)
if len(self.tagstack) > 0:
tag = self.tagstack.pop()
if tag.data == None:
tag.data = str
else:
tag.data += str
self.tagstack.append(tag)
else:
self.outputfile.write(str)
def format_attributes(self, tag):
"""Returns the attributes formatted to be placed in a tag."""
ret = ""
if len(tag.attributes) > 0:
for name, value in tag.attributes:
ret = "%s %s=\"%s\"" % (ret, name, value)
return ret
class Stage2Parser(OutputParser):
def __init__(self, *args, **kwargs):
OutputParser.__init__(self, *args, **kwargs)
self.control = []
def handle_starttag(self, tag, attrs):
if tag == "meta":
if attrs[0][0] == "name" and attrs[0][1] == "control" and attrs[1][0] == "content":
self.control.append(attrs[1][1])
else:
OutputParser.handle_starttag(self, tag, attrs)
def handle_startendtag(self, tag, attrs):
if tag == "meta":
if attrs[0][0] == "name" and attrs[0][1] == "control" and attrs[1][0] == "content":
self.control.append(attrs[1][1])
else:
OutputParser.handle_startendtag(self, tag, attrs)
class Stage3Parser(OutputParser):
def __init__(self, options, files, extrafiles, subdir, *args, **kwargs):
OutputParser.__init__(self, *args, **kwargs)
self.options = options
self.files = files
self.extrafiles = extrafiles
self.subdir = subdir
logging.debug(" Subdirectory is '%s'", subdir)
def handle_startendtag(self, tag, attrs):
"""Find the image and copy it to the stage3 folder where it should
be in the file output."""
ALT_INDEX = None
if tag == "img":
# figure out which attribute is src
for x in range(0, len(attrs)):
if attrs[x][0] == "src":
SRC_INDEX = x
elif attrs[x][0] == "alt":
ALT_INDEX = x
if attrs[SRC_INDEX][1].startswith("/"):
# manual wants an absolute path, the help manual does not support
# absolute path, so make sure that the image exists where the
# absolute path indicates, then make the path into a relative path
# with the approriate number of updirs
test = os.path.join(self.options.indir, attrs[SRC_INDEX][1][1:])
if not os.path.exists(test):
raise IOError("Cannot find %s in base path"%(attrs[SRC_INDEX][1]))
# try find a valid relative path
subdirdepth = len(self.subdir.split(os.path.sep))
prefix = "../"*subdirdepth
relpath = os.path.join(prefix, attrs[SRC_INDEX][1][1:])
if not os.path.exists(os.path.join(self.options.indir, self.subdir,relpath)):
raise Exception("Cannot relativize path: %s"%(attrs[SRC_INDEX][1]))
else:
attrs = update_attribute(attrs, 'src', relpath)
location1 = os.path.join(self.options.indir, self.subdir, attrs[SRC_INDEX][1])
location = os.path.normpath(location1)
# check to make sure that the image I am including was in the onlinehelp
# folder, if not change the dst name so that it will be located
# correctly in the stage3 directory
logging.debug("%s - %s", location, self.options.indir)
if location.startswith(self.options.indir):
dst1 = os.path.join(self.files['stage3'], self.subdir, attrs[SRC_INDEX][1])
dst = os.path.normpath(dst1)
else:
# get extention
basename = os.path.basename(attrs[SRC_INDEX][1])
(name, ext) = os.path.splitext(basename)
(file, outname) = tempfile.mkstemp(ext, name, self.files['stage3'])
dst1 = outname.replace(os.getcwd(), ".") # make into a relative path
# fix up attrs
dst = os.path.normpath(dst1)
attrs = update_attribute(attrs, 'src', change_filename(dst, os.path.splitext(dst)[1], self.files['stage3'], ".", makedirs=False))
if ALT_INDEX is None:
ALT_INDEX = SRC_INDEX
logging.debug(" Image (%s) should be in %s and copying to %s", attrs[ALT_INDEX][1], location, dst)
try:
if not os.path.exists(os.path.dirname(dst)):
os.mkdir(os.path.dirname(dst))
shutil.copy2(location, dst)
except:
traceback.print_exc()
logging.error(" '%s' does not exist", location )
sys.exit(3)
self.extrafiles.append(dst)
OutputParser.handle_startendtag(self, tag, attrs)
class Stage4Parser(OutputParser):
def __init__(self, files, options, subdir, *args, **kwargs):
OutputParser.__init__(self, *args, **kwargs)
self.files = files
self.options = options
self.subdir = subdir
def handle_starttag(self, tag, attrs):
if tag == "a":
for name,value in attrs:
if name == "href" and value.startswith("/"):
if value.startswith("/"):
# manual wants an absolute path, the help manual does not support
# absolute path, so make sure that the image exists where the
# absolute path indicates, then make the path into a relative path
# with the approriate number of updirs
test = os.path.join(self.options.indir, value[1:])
if not os.path.exists(test):
raise IOError("Cannot find %s in base path" % (value))
# try find a valid relative path
subdirdepth = len(self.subdir.split(os.path.sep))
prefix = "../"*subdirdepth
relpath = os.path.join(prefix, value[1:])
if not os.path.exists(os.path.join(self.options.indir, self.subdir,relpath)):
raise Exception("Cannot relativize path: %s" % (value))
else:
attrs = update_attribute(attrs, 'src', relpath)
value = relpath
if name == "href" and not value.startswith("http://"):
# make sure the file being refered to exists in stage3
check_ref = change_filename(value, ".stage3", ".", self.files['stage3'], makedirs=False)
if not os.path.exists(check_ref):
logging.debug(" File (%s) does not exist to be bundled into archive!", check_ref)
fixed_ref = change_filename(value, ".htm", ".", ".", makedirs=False)
attrs = update_attribute(attrs, "href", fixed_ref)
OutputParser.handle_starttag(self, tag, attrs)
class Stage5Parser(OutputParser):
def __init__(self, *args, **kwargs):
OutputParser.__init__(self, *args, **kwargs)
self.title = "Untitled"
def handle_endtag(self, tag):
if tag == "title":
t = self.tagstack.pop()
self.title = t.data
self.tagstack.append(t)
elif tag == "h1" and self.title == "Untitled":
# make first h1 tag found into the title, will be overwritten by a title tag if it exists.
t = self.tagstack.pop()
self.title = t.data
self.tagstack.append(t)
OutputParser.handle_endtag(self, tag)
| Python |
import os
import os.path
import string
import subprocess
import sys
import tempfile
import traceback
import utilfunctions
class VersionFileBuilder:
def __init__(self, workfile, outfile, hgpath="hg", out=sys.stdout,
err=sys.stderr):
self.workfile = workfile
self.outfile = outfile
self.hgpath = hgpath
self.out = out
self.err = err
def rebuild(self):
"""Calls clean then build"""
self.clean()
self.build()
def clean(self):
"""Removes all temporary files and the output files that were passed,
if they exist"""
self.out.write("Cleaning...\n")
try:
self.out.write(" Removing %s: " % (self.filepath))
os.remove(self.filepath)
self.out.write("Done.\n")
except:
self.out.write("Failed!\n")
traceback.print_exc(None, self.err)
try:
self.out.write(" Removing %s: " % (self.workfile))
os.remove(self.workfile)
self.out.write("Done.\n")
except:
self.out.write("Failed!\n")
traceback.print_exc(None, self.err)
def build(self):
self.out.write("Checking if build is needed...\n")
if self.need_to_update():
self.out.write("Generating...\n")
self.out.write(" Writing to tempfile %s.\n" % (self.workfile))
if not utilfunctions.make_directory_for_filename(self.workfile):
self.out.write(" Directory already exists...\n")
out = open(self.outfile, "wb")
out.write('const wchar_t *HGVersion = L"')
out.flush()
out.write(self.get_hg_id())
out.flush()
out.write('";\n')
out.write('const wchar_t *HGDate = L"')
out.flush()
datecmd = '%s parents --template {date|date}' % (self.hgpath)
datecmd = datecmd.split()
subprocess.Popen(datecmd, stdout=out).wait()
out.flush()
out.write('";\n')
out.close()
self.out.write(" Done.\n")
else:
self.out.write(" Up to date.\n")
def get_hg_id(self):
"""Return the hg id string after striping the newline from the end
of the command output"""
id = tempfile.TemporaryFile()
s = "%s id -i -b -t" % (self.hgpath)
s = s.split()
subprocess.Popen(s, stdout=id).wait()
id.seek(0)
rawidoutput = id.readline()
# split on the line ending and return the first peice which will
# contain the entire id (all of the tags, etc) of the current
# repository without any newlines
return string.split(rawidoutput, "\n")[0]
def need_to_update(self):
"""Returns False if the self.outfile is up to date, True otherwise"""
if os.path.exists(self.workfile) == True:
if os.path.exists(self.outfile) == True:
# check the id to see if it has changed
workfile = open(self.workfile, 'rb')
if workfile.readline() == self.get_hg_id():
return False
else:
self.out.write(" hg id changed\n")
else:
self.out.write(" %s does not exist\n" % (self.outfile))
else:
self.out.write(" %s does not exist\n" % (self.workfile))
return True | Python |
import os, shutil, datetime
import Version
Import("env")
if env["SCONS_STAGE"] == "build" :
myenv = env.Clone()
myenv.MergeFlags(env["SWIFTEN_FLAGS"])
myenv.MergeFlags(env["SWIFTEN_DEP_FLAGS"])
sources = [
"main.cpp",
"ActiveSessionPair.cpp",
"StaticDomainNameResolver.cpp",
"IdleSession.cpp",
"LatencyWorkloadBenchmark.cpp",
"BenchmarkNetworkFactories.cpp",
"BoostEventLoop.cpp",
]
myenv.Program("xmppench", sources)
| Python |
#====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ====================================================================
#
# This software consists of voluntary contributions made by many
# individuals on behalf of the Apache Software Foundation. For more
# information on the Apache Software Foundation, please see
# <http://www.apache.org/>.
#
import os
import re
import tempfile
import shutil
ignore_pattern = re.compile('^(.svn|target|bin|classes)')
java_pattern = re.compile('^.*\.java')
annot_pattern = re.compile('import org\.apache\.http\.annotation\.')
def process_dir(dir):
files = os.listdir(dir)
for file in files:
f = os.path.join(dir, file)
if os.path.isdir(f):
if not ignore_pattern.match(file):
process_dir(f)
else:
if java_pattern.match(file):
process_source(f)
def process_source(filename):
tmp = tempfile.mkstemp()
tmpfd = tmp[0]
tmpfile = tmp[1]
try:
changed = False
dst = os.fdopen(tmpfd, 'w')
try:
src = open(filename)
try:
for line in src:
if annot_pattern.match(line):
changed = True
line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.')
dst.write(line)
finally:
src.close()
finally:
dst.close();
if changed:
shutil.move(tmpfile, filename)
else:
os.remove(tmpfile)
except:
os.remove(tmpfile)
process_dir('.')
| Python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
""" Define the menu structure used by the Pentacle applications """
MenuStructure = [
["&File", [
["&New", "<control>N"],
["&Open...", "<control>O"],
["&Save", "<control>S"],
["Save &As...", "<control><shift>S"],
["Test", ""],
["Exercised", ""],
["Uncalled", ""],
["-", ""],
["&Exit", ""]]],
[ "&Edit", [
["&Undo", "<control>Z"],
["&Redo", "<control>Y"],
["-", ""],
["Cu&t", "<control>X"],
["&Copy", "<control>C"],
["&Paste", "<control>V"],
["&Delete", "Del"],
["Select &All", "<control>A"],
]],
]
| Python |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from __future__ import unicode_literals
import codecs, ctypes, os, sys, unittest
import XiteWin
class TestSimple(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testLength(self):
self.assertEquals(self.ed.Length, 0)
def testAddText(self):
self.ed.AddText(1, "x")
self.assertEquals(self.ed.Length, 1)
self.assertEquals(self.ed.GetCharAt(0), ord("x"))
self.assertEquals(self.ed.GetStyleAt(0), 0)
self.ed.ClearAll()
self.assertEquals(self.ed.Length, 0)
def testDeleteRange(self):
self.ed.AddText(5, b"abcde")
self.assertEquals(self.ed.Length, 5)
self.ed.DeleteRange(1, 2)
self.assertEquals(self.ed.Length, 3)
self.assertEquals(self.ed.Contents(), b"ade")
def testAddStyledText(self):
self.assertEquals(self.ed.EndStyled, 0)
self.ed.AddStyledText(2, b"x\002")
self.assertEquals(self.ed.Length, 1)
self.assertEquals(self.ed.GetCharAt(0), ord("x"))
self.assertEquals(self.ed.GetStyleAt(0), 2)
self.assertEquals(self.ed.StyledTextRange(0, 1), b"x\002")
self.ed.ClearDocumentStyle()
self.assertEquals(self.ed.Length, 1)
self.assertEquals(self.ed.GetCharAt(0), ord("x"))
self.assertEquals(self.ed.GetStyleAt(0), 0)
self.assertEquals(self.ed.StyledTextRange(0, 1), b"x\0")
def testStyling(self):
self.assertEquals(self.ed.EndStyled, 0)
self.ed.AddStyledText(4, b"x\002y\003")
self.assertEquals(self.ed.StyledTextRange(0, 2), b"x\002y\003")
self.ed.StartStyling(0,0xf)
self.ed.SetStyling(1, 5)
self.assertEquals(self.ed.StyledTextRange(0, 2), b"x\005y\003")
# Set the mask so 0 bit changed but not 2 bit
self.ed.StartStyling(0,0x1)
self.ed.SetStyling(1, 0)
self.assertEquals(self.ed.StyledTextRange(0, 2), b"x\004y\003")
self.ed.StartStyling(0,0xff)
self.ed.SetStylingEx(2, b"\100\101")
self.assertEquals(self.ed.StyledTextRange(0, 2), b"x\100y\101")
def testPosition(self):
self.assertEquals(self.ed.CurrentPos, 0)
self.assertEquals(self.ed.Anchor, 0)
self.ed.AddText(1, "x")
# Caret has automatically moved
self.assertEquals(self.ed.CurrentPos, 1)
self.assertEquals(self.ed.Anchor, 1)
self.ed.SelectAll()
self.assertEquals(self.ed.CurrentPos, 0)
self.assertEquals(self.ed.Anchor, 1)
self.ed.Anchor = 0
self.assertEquals(self.ed.Anchor, 0)
# Check line positions
self.assertEquals(self.ed.PositionFromLine(0), 0)
self.assertEquals(self.ed.GetLineEndPosition(0), 1)
self.assertEquals(self.ed.PositionFromLine(1), 1)
self.ed.CurrentPos = 1
self.assertEquals(self.ed.Anchor, 0)
self.assertEquals(self.ed.CurrentPos, 1)
def testSelection(self):
self.assertEquals(self.ed.CurrentPos, 0)
self.assertEquals(self.ed.Anchor, 0)
self.assertEquals(self.ed.SelectionStart, 0)
self.assertEquals(self.ed.SelectionEnd, 0)
self.ed.AddText(1, "x")
self.ed.SelectionStart = 0
self.assertEquals(self.ed.CurrentPos, 1)
self.assertEquals(self.ed.Anchor, 0)
self.assertEquals(self.ed.SelectionStart, 0)
self.assertEquals(self.ed.SelectionEnd, 1)
self.ed.SelectionStart = 1
self.assertEquals(self.ed.CurrentPos, 1)
self.assertEquals(self.ed.Anchor, 1)
self.assertEquals(self.ed.SelectionStart, 1)
self.assertEquals(self.ed.SelectionEnd, 1)
self.ed.SelectionEnd = 0
self.assertEquals(self.ed.CurrentPos, 0)
self.assertEquals(self.ed.Anchor, 0)
def testSetSelection(self):
self.ed.AddText(4, b"abcd")
self.ed.SetSel(1, 3)
self.assertEquals(self.ed.SelectionStart, 1)
self.assertEquals(self.ed.SelectionEnd, 3)
result = b"\0" * 5
length = self.ed.GetSelText(0, result)
self.assertEquals(length, 3)
self.assertEquals(result[:length], b"bc\0")
self.ed.ReplaceSel(0, b"1234")
self.assertEquals(self.ed.Length, 6)
self.assertEquals(self.ed.Contents(), b"a1234d")
def testReadOnly(self):
self.ed.AddText(1, b"x")
self.assertEquals(self.ed.ReadOnly, 0)
self.assertEquals(self.ed.Contents(), b"x")
self.ed.ReadOnly = 1
self.assertEquals(self.ed.ReadOnly, 1)
self.ed.AddText(1, b"x")
self.assertEquals(self.ed.Contents(), b"x")
self.ed.ReadOnly = 0
self.ed.AddText(1, b"x")
self.assertEquals(self.ed.Contents(), b"xx")
self.ed.Null()
self.assertEquals(self.ed.Contents(), b"xx")
def testAddLine(self):
data = b"x" * 70 + b"\n"
for i in range(5):
self.ed.AddText(len(data), data)
self.xite.DoEvents()
self.assertEquals(self.ed.LineCount, i + 2)
self.assert_(self.ed.Length > 0)
def testInsertText(self):
data = b"xy"
self.ed.InsertText(0, data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(data, self.ed.ByteRange(0,2))
self.ed.InsertText(1, data)
# Should now be "xxyy"
self.assertEquals(self.ed.Length, 4)
self.assertEquals(b"xxyy", self.ed.ByteRange(0,4))
def testInsertNul(self):
data = b"\0"
self.ed.AddText(1, data)
self.assertEquals(self.ed.Length, 1)
self.assertEquals(data, self.ed.ByteRange(0,1))
def testUndoRedo(self):
data = b"xy"
self.assertEquals(self.ed.Modify, 0)
self.assertEquals(self.ed.UndoCollection, 1)
self.assertEquals(self.ed.CanRedo(), 0)
self.assertEquals(self.ed.CanUndo(), 0)
self.ed.InsertText(0, data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.ed.Modify, 1)
self.assertEquals(self.ed.CanRedo(), 0)
self.assertEquals(self.ed.CanUndo(), 1)
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.ed.Modify, 0)
self.assertEquals(self.ed.CanRedo(), 1)
self.assertEquals(self.ed.CanUndo(), 0)
self.ed.Redo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.ed.Modify, 1)
self.assertEquals(data, self.ed.Contents())
self.assertEquals(self.ed.CanRedo(), 0)
self.assertEquals(self.ed.CanUndo(), 1)
def testUndoSavePoint(self):
data = b"xy"
self.assertEquals(self.ed.Modify, 0)
self.ed.InsertText(0, data)
self.assertEquals(self.ed.Modify, 1)
self.ed.SetSavePoint()
self.assertEquals(self.ed.Modify, 0)
self.ed.InsertText(0, data)
self.assertEquals(self.ed.Modify, 1)
def testUndoCollection(self):
data = b"xy"
self.assertEquals(self.ed.UndoCollection, 1)
self.ed.UndoCollection = 0
self.assertEquals(self.ed.UndoCollection, 0)
self.ed.InsertText(0, data)
self.assertEquals(self.ed.CanRedo(), 0)
self.assertEquals(self.ed.CanUndo(), 0)
self.ed.UndoCollection = 1
def testGetColumn(self):
self.ed.AddText(1, b"x")
self.assertEquals(self.ed.GetColumn(0), 0)
self.assertEquals(self.ed.GetColumn(1), 1)
# Next line caused infinite loop in 1.71
self.assertEquals(self.ed.GetColumn(2), 1)
self.assertEquals(self.ed.GetColumn(3), 1)
def testTabWidth(self):
self.assertEquals(self.ed.TabWidth, 8)
self.ed.AddText(3, b"x\tb")
self.assertEquals(self.ed.GetColumn(0), 0)
self.assertEquals(self.ed.GetColumn(1), 1)
self.assertEquals(self.ed.GetColumn(2), 8)
for col in range(10):
if col == 0:
self.assertEquals(self.ed.FindColumn(0, col), 0)
elif col == 1:
self.assertEquals(self.ed.FindColumn(0, col), 1)
elif col == 8:
self.assertEquals(self.ed.FindColumn(0, col), 2)
elif col == 9:
self.assertEquals(self.ed.FindColumn(0, col), 3)
else:
self.assertEquals(self.ed.FindColumn(0, col), 1)
self.ed.TabWidth = 4
self.assertEquals(self.ed.TabWidth, 4)
self.assertEquals(self.ed.GetColumn(0), 0)
self.assertEquals(self.ed.GetColumn(1), 1)
self.assertEquals(self.ed.GetColumn(2), 4)
def testIndent(self):
self.assertEquals(self.ed.Indent, 0)
self.assertEquals(self.ed.UseTabs, 1)
self.ed.Indent = 8
self.ed.UseTabs = 0
self.assertEquals(self.ed.Indent, 8)
self.assertEquals(self.ed.UseTabs, 0)
self.ed.AddText(3, b"x\tb")
self.assertEquals(self.ed.GetLineIndentation(0), 0)
self.ed.InsertText(0, b" ")
self.assertEquals(self.ed.GetLineIndentation(0), 1)
self.assertEquals(self.ed.GetLineIndentPosition(0), 1)
self.assertEquals(self.ed.Contents(), b" x\tb")
self.ed.SetLineIndentation(0,2)
self.assertEquals(self.ed.Contents(), b" x\tb")
self.assertEquals(self.ed.GetLineIndentPosition(0), 2)
self.ed.UseTabs = 1
self.ed.SetLineIndentation(0,8)
self.assertEquals(self.ed.Contents(), b"\tx\tb")
self.assertEquals(self.ed.GetLineIndentPosition(0), 1)
def testGetCurLine(self):
self.ed.AddText(1, b"x")
data = b"\0" * 100
caret = self.ed.GetCurLine(len(data), data)
data = data.rstrip(b"\0")
self.assertEquals(caret, 1)
self.assertEquals(data, b"x")
def testGetLine(self):
self.ed.AddText(1, b"x")
data = b"\0" * 100
length = self.ed.GetLine(0, data)
self.assertEquals(length, 1)
data = data[:length]
self.assertEquals(data, b"x")
def testLineEnds(self):
self.ed.AddText(3, b"x\ny")
self.assertEquals(self.ed.GetLineEndPosition(0), 1)
self.assertEquals(self.ed.GetLineEndPosition(1), 3)
self.assertEquals(self.ed.LineLength(0), 2)
self.assertEquals(self.ed.LineLength(1), 1)
self.assertEquals(self.ed.EOLMode, self.ed.SC_EOL_CRLF)
lineEnds = [b"\r\n", b"\r", b"\n"]
for lineEndType in [self.ed.SC_EOL_CR, self.ed.SC_EOL_LF, self.ed.SC_EOL_CRLF]:
self.ed.EOLMode = lineEndType
self.assertEquals(self.ed.EOLMode, lineEndType)
self.ed.ConvertEOLs(lineEndType)
self.assertEquals(self.ed.Contents(), b"x" + lineEnds[lineEndType] + b"y")
self.assertEquals(self.ed.LineLength(0), 1 + len(lineEnds[lineEndType]))
def testGoto(self):
self.ed.AddText(5, b"a\nb\nc")
self.assertEquals(self.ed.CurrentPos, 5)
self.ed.GotoLine(1)
self.assertEquals(self.ed.CurrentPos, 2)
self.ed.GotoPos(4)
self.assertEquals(self.ed.CurrentPos, 4)
def testCutCopyPaste(self):
self.ed.AddText(5, b"a1b2c")
self.ed.SetSel(1,3)
self.ed.Cut()
self.assertEquals(self.ed.CanPaste(), 1)
self.ed.SetSel(0, 0)
self.ed.Paste()
self.assertEquals(self.ed.Contents(), b"1ba2c")
self.ed.SetSel(4,5)
self.ed.Copy()
self.ed.SetSel(1,3)
self.ed.Paste()
self.assertEquals(self.ed.Contents(), b"1c2c")
self.ed.SetSel(2,4)
self.ed.Clear()
self.assertEquals(self.ed.Contents(), b"1c")
def testGetSet(self):
self.ed.SetText(0, b"abc")
self.assertEquals(self.ed.TextLength, 3)
result = b"\0" * 5
length = self.ed.GetText(4, result)
result = result[:length]
self.assertEquals(result, b"abc")
def testAppend(self):
self.ed.SetText(0, b"abc")
self.assertEquals(self.ed.SelectionStart, 0)
self.assertEquals(self.ed.SelectionEnd, 0)
text = b"12"
self.ed.AppendText(len(text), text)
self.assertEquals(self.ed.SelectionStart, 0)
self.assertEquals(self.ed.SelectionEnd, 0)
self.assertEquals(self.ed.Contents(), b"abc12")
def testTarget(self):
self.ed.SetText(0, b"abcd")
self.ed.TargetStart = 1
self.ed.TargetEnd = 3
self.assertEquals(self.ed.TargetStart, 1)
self.assertEquals(self.ed.TargetEnd, 3)
rep = b"321"
self.ed.ReplaceTarget(len(rep), rep)
self.assertEquals(self.ed.Contents(), b"a321d")
self.ed.SearchFlags = self.ed.SCFIND_REGEXP
self.assertEquals(self.ed.SearchFlags, self.ed.SCFIND_REGEXP)
searchString = b"\([1-9]+\)"
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(1, pos)
tagString = b"abcdefghijklmnop"
lenTag = self.ed.GetTag(1, tagString)
tagString = tagString[:lenTag]
self.assertEquals(tagString, b"321")
rep = b"\\1"
self.ed.TargetStart = 0
self.ed.TargetEnd = 0
self.ed.ReplaceTargetRE(len(rep), rep)
self.assertEquals(self.ed.Contents(), b"321a321d")
self.ed.SetSel(4,5)
self.ed.TargetFromSelection()
self.assertEquals(self.ed.TargetStart, 4)
self.assertEquals(self.ed.TargetEnd, 5)
def testTargetEscape(self):
# Checks that a literal \ can be in the replacement. Bug #2959876
self.ed.SetText(0, b"abcd")
self.ed.TargetStart = 1
self.ed.TargetEnd = 3
rep = b"\\\\n"
self.ed.ReplaceTargetRE(len(rep), rep)
self.assertEquals(self.ed.Contents(), b"a\\nd")
def testPointsAndPositions(self):
self.ed.AddText(1, b"x")
# Start of text
self.assertEquals(self.ed.PositionFromPoint(0,0), 0)
# End of text
self.assertEquals(self.ed.PositionFromPoint(0,100), 1)
def testLinePositions(self):
text = b"ab\ncd\nef"
nl = b"\n"
if sys.version_info[0] == 3:
nl = ord(b"\n")
self.ed.AddText(len(text), text)
self.assertEquals(self.ed.LineFromPosition(-1), 0)
line = 0
for pos in range(len(text)+1):
self.assertEquals(self.ed.LineFromPosition(pos), line)
if pos < len(text) and text[pos] == nl:
line += 1
def testWordPositions(self):
text = b"ab cd\tef"
self.ed.AddText(len(text), text)
self.assertEquals(self.ed.WordStartPosition(3, 0), 2)
self.assertEquals(self.ed.WordStartPosition(4, 0), 3)
self.assertEquals(self.ed.WordStartPosition(5, 0), 3)
self.assertEquals(self.ed.WordStartPosition(6, 0), 5)
self.assertEquals(self.ed.WordEndPosition(2, 0), 3)
self.assertEquals(self.ed.WordEndPosition(3, 0), 5)
self.assertEquals(self.ed.WordEndPosition(4, 0), 5)
self.assertEquals(self.ed.WordEndPosition(5, 0), 6)
self.assertEquals(self.ed.WordEndPosition(6, 0), 8)
MODI = 1
UNDO = 2
REDO = 4
class TestContainerUndo(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.data = b"xy"
def UndoState(self):
return (MODI if self.ed.Modify else 0) | \
(UNDO if self.ed.CanUndo() else 0) | \
(REDO if self.ed.CanRedo() else 0)
def testContainerActNoCoalesce(self):
self.ed.InsertText(0, self.data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 0)
self.ed.Undo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO | REDO)
self.ed.Redo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
def testContainerActCoalesce(self):
self.ed.InsertText(0, self.data)
self.ed.AddUndoAction(5, 1)
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
self.ed.Redo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
def testContainerMultiStage(self):
self.ed.InsertText(0, self.data)
self.ed.AddUndoAction(5, 1)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
self.ed.Redo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
def testContainerMultiStageNoText(self):
self.ed.AddUndoAction(5, 1)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
self.assertEquals(self.UndoState(), REDO)
self.ed.Redo()
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
self.assertEquals(self.UndoState(), REDO)
def testContainerActCoalesceEnd(self):
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.InsertText(0, self.data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
self.ed.Redo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
def testContainerBetweenInsertAndInsert(self):
self.assertEquals(self.ed.Length, 0)
self.ed.InsertText(0, self.data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.InsertText(2, self.data)
self.assertEquals(self.ed.Length, 4)
self.assertEquals(self.UndoState(), MODI | UNDO)
# Undoes both insertions and the containerAction in the middle
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
def testContainerNoCoalesceBetweenInsertAndInsert(self):
self.assertEquals(self.ed.Length, 0)
self.ed.InsertText(0, self.data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 0)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.InsertText(2, self.data)
self.assertEquals(self.ed.Length, 4)
self.assertEquals(self.UndoState(), MODI | UNDO)
# Undo last insertion
self.ed.Undo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO | REDO)
# Undo container
self.ed.Undo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO | REDO)
# Undo first insertion
self.ed.Undo()
self.assertEquals(self.ed.Length, 0)
self.assertEquals(self.UndoState(), REDO)
def testContainerBetweenDeleteAndDelete(self):
self.ed.InsertText(0, self.data)
self.ed.EmptyUndoBuffer()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), 0)
self.ed.SetSel(2,2)
self.ed.DeleteBack()
self.assertEquals(self.ed.Length, 1)
self.ed.AddUndoAction(5, 1)
self.ed.DeleteBack()
self.assertEquals(self.ed.Length, 0)
# Undoes both deletions and the containerAction in the middle
self.ed.Undo()
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), REDO)
def testContainerBetweenInsertAndDelete(self):
self.assertEquals(self.ed.Length, 0)
self.ed.InsertText(0, self.data)
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.AddUndoAction(5, 1)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.SetSel(0,1)
self.ed.Cut()
self.assertEquals(self.ed.Length, 1)
self.assertEquals(self.UndoState(), MODI | UNDO)
self.ed.Undo() # Only undoes the deletion
self.assertEquals(self.ed.Length, 2)
self.assertEquals(self.UndoState(), MODI | UNDO | REDO)
class TestKeyCommands(unittest.TestCase):
""" These commands are normally assigned to keys and take no arguments """
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def selRange(self):
return self.ed.CurrentPos, self.ed.Anchor
def testLineMove(self):
self.ed.AddText(8, b"x1\ny2\nz3")
self.ed.SetSel(0,0)
self.ed.ChooseCaretX()
self.ed.LineDown()
self.ed.LineDown()
self.assertEquals(self.selRange(), (6, 6))
self.ed.LineUp()
self.assertEquals(self.selRange(), (3, 3))
self.ed.LineDownExtend()
self.assertEquals(self.selRange(), (6, 3))
self.ed.LineUpExtend()
self.ed.LineUpExtend()
self.assertEquals(self.selRange(), (0, 3))
def testCharMove(self):
self.ed.AddText(8, b"x1\ny2\nz3")
self.ed.SetSel(0,0)
self.ed.CharRight()
self.ed.CharRight()
self.assertEquals(self.selRange(), (2, 2))
self.ed.CharLeft()
self.assertEquals(self.selRange(), (1, 1))
self.ed.CharRightExtend()
self.assertEquals(self.selRange(), (2, 1))
self.ed.CharLeftExtend()
self.ed.CharLeftExtend()
self.assertEquals(self.selRange(), (0, 1))
def testWordMove(self):
self.ed.AddText(10, b"a big boat")
self.ed.SetSel(3,3)
self.ed.WordRight()
self.ed.WordRight()
self.assertEquals(self.selRange(), (10, 10))
self.ed.WordLeft()
self.assertEquals(self.selRange(), (6, 6))
self.ed.WordRightExtend()
self.assertEquals(self.selRange(), (10, 6))
self.ed.WordLeftExtend()
self.ed.WordLeftExtend()
self.assertEquals(self.selRange(), (2, 6))
def testHomeEndMove(self):
self.ed.AddText(10, b"a big boat")
self.ed.SetSel(3,3)
self.ed.Home()
self.assertEquals(self.selRange(), (0, 0))
self.ed.LineEnd()
self.assertEquals(self.selRange(), (10, 10))
self.ed.SetSel(3,3)
self.ed.HomeExtend()
self.assertEquals(self.selRange(), (0, 3))
self.ed.LineEndExtend()
self.assertEquals(self.selRange(), (10, 3))
def testStartEndMove(self):
self.ed.AddText(10, b"a\nbig\nboat")
self.ed.SetSel(3,3)
self.ed.DocumentStart()
self.assertEquals(self.selRange(), (0, 0))
self.ed.DocumentEnd()
self.assertEquals(self.selRange(), (10, 10))
self.ed.SetSel(3,3)
self.ed.DocumentStartExtend()
self.assertEquals(self.selRange(), (0, 3))
self.ed.DocumentEndExtend()
self.assertEquals(self.selRange(), (10, 3))
class TestMarkers(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.ed.AddText(5, b"x\ny\nz")
def testMarker(self):
handle = self.ed.MarkerAdd(1,1)
self.assertEquals(self.ed.MarkerLineFromHandle(handle), 1)
self.ed.MarkerDelete(1,1)
self.assertEquals(self.ed.MarkerLineFromHandle(handle), -1)
def testTwiceAddedDelete(self):
handle = self.ed.MarkerAdd(1,1)
self.assertEquals(self.ed.MarkerGet(1), 2)
handle2 = self.ed.MarkerAdd(1,1)
self.assertEquals(self.ed.MarkerGet(1), 2)
self.ed.MarkerDelete(1,1)
self.assertEquals(self.ed.MarkerGet(1), 2)
self.ed.MarkerDelete(1,1)
self.assertEquals(self.ed.MarkerGet(1), 0)
def testMarkerDeleteAll(self):
h1 = self.ed.MarkerAdd(0,1)
h2 = self.ed.MarkerAdd(1,2)
self.assertEquals(self.ed.MarkerLineFromHandle(h1), 0)
self.assertEquals(self.ed.MarkerLineFromHandle(h2), 1)
self.ed.MarkerDeleteAll(1)
self.assertEquals(self.ed.MarkerLineFromHandle(h1), -1)
self.assertEquals(self.ed.MarkerLineFromHandle(h2), 1)
self.ed.MarkerDeleteAll(-1)
self.assertEquals(self.ed.MarkerLineFromHandle(h1), -1)
self.assertEquals(self.ed.MarkerLineFromHandle(h2), -1)
def testMarkerDeleteHandle(self):
handle = self.ed.MarkerAdd(0,1)
self.assertEquals(self.ed.MarkerLineFromHandle(handle), 0)
self.ed.MarkerDeleteHandle(handle)
self.assertEquals(self.ed.MarkerLineFromHandle(handle), -1)
def testMarkerBits(self):
self.assertEquals(self.ed.MarkerGet(0), 0)
self.ed.MarkerAdd(0,1)
self.assertEquals(self.ed.MarkerGet(0), 2)
self.ed.MarkerAdd(0,2)
self.assertEquals(self.ed.MarkerGet(0), 6)
def testMarkerAddSet(self):
self.assertEquals(self.ed.MarkerGet(0), 0)
self.ed.MarkerAddSet(0,5)
self.assertEquals(self.ed.MarkerGet(0), 5)
self.ed.MarkerDeleteAll(-1)
def testMarkerNext(self):
self.assertEquals(self.ed.MarkerNext(0, 2), -1)
h1 = self.ed.MarkerAdd(0,1)
h2 = self.ed.MarkerAdd(2,1)
self.assertEquals(self.ed.MarkerNext(0, 2), 0)
self.assertEquals(self.ed.MarkerNext(1, 2), 2)
self.assertEquals(self.ed.MarkerNext(2, 2), 2)
self.assertEquals(self.ed.MarkerPrevious(0, 2), 0)
self.assertEquals(self.ed.MarkerPrevious(1, 2), 0)
self.assertEquals(self.ed.MarkerPrevious(2, 2), 2)
def testMarkerNegative(self):
self.assertEquals(self.ed.MarkerNext(-1, 2), -1)
def testLineState(self):
self.assertEquals(self.ed.MaxLineState, 0)
self.assertEquals(self.ed.GetLineState(0), 0)
self.assertEquals(self.ed.GetLineState(1), 0)
self.assertEquals(self.ed.GetLineState(2), 0)
self.ed.SetLineState(1, 100)
self.assertNotEquals(self.ed.MaxLineState, 0)
self.assertEquals(self.ed.GetLineState(0), 0)
self.assertEquals(self.ed.GetLineState(1), 100)
self.assertEquals(self.ed.GetLineState(2), 0)
def testSymbolRetrieval(self):
self.ed.MarkerDefine(1,3)
self.assertEquals(self.ed.MarkerSymbolDefined(1), 3)
class TestIndicators(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testSetIndicator(self):
self.assertEquals(self.ed.IndicGetStyle(0), 1)
self.assertEquals(self.ed.IndicGetFore(0), 0x007f00)
self.ed.IndicSetStyle(0, 2)
self.ed.IndicSetFore(0, 0xff0080)
self.assertEquals(self.ed.IndicGetStyle(0), 2)
self.assertEquals(self.ed.IndicGetFore(0), 0xff0080)
class TestScrolling(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
# 150 should be enough lines
self.ed.InsertText(0, b"a\n" * 150)
def testTop(self):
self.ed.GotoLine(0)
self.assertEquals(self.ed.FirstVisibleLine, 0)
def testLineScroll(self):
self.ed.GotoLine(0)
self.ed.LineScroll(0, 3)
self.assertEquals(self.ed.FirstVisibleLine, 3)
def testVisibleLine(self):
self.ed.FirstVisibleLine = 7
self.assertEquals(self.ed.FirstVisibleLine, 7)
class TestSearch(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.ed.InsertText(0, b"a\tbig boat\t")
def testFind(self):
pos = self.ed.FindBytes(0, self.ed.Length, b"zzz", 0)
self.assertEquals(pos, -1)
pos = self.ed.FindBytes(0, self.ed.Length, b"big", 0)
self.assertEquals(pos, 2)
def testFindEmpty(self):
pos = self.ed.FindBytes(0, self.ed.Length, b"", 0)
self.assertEquals(pos, 0)
def testCaseFind(self):
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"big", 0), 2)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bIg", 0), 2)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bIg",
self.ed.SCFIND_MATCHCASE), -1)
def testWordFind(self):
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bi", 0), 2)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bi",
self.ed.SCFIND_WHOLEWORD), -1)
def testWordStartFind(self):
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bi", 0), 2)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"bi",
self.ed.SCFIND_WORDSTART), 2)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"ig", 0), 3)
self.assertEquals(self.ed.FindBytes(0, self.ed.Length, b"ig",
self.ed.SCFIND_WORDSTART), -1)
def testREFind(self):
flags = self.ed.SCFIND_REGEXP
self.assertEquals(-1, self.ed.FindBytes(0, self.ed.Length, b"b.g", 0))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"b.g", flags))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"\<b.g\>", flags))
self.assertEquals(-1, self.ed.FindBytes(0, self.ed.Length, b"b[A-Z]g",
flags | self.ed.SCFIND_MATCHCASE))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"b[a-z]g", flags))
self.assertEquals(6, self.ed.FindBytes(0, self.ed.Length, b"b[a-z]*t", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"^a", flags))
self.assertEquals(10, self.ed.FindBytes(0, self.ed.Length, b"\t$", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"\([a]\).*\0", flags))
def testPosixREFind(self):
flags = self.ed.SCFIND_REGEXP | self.ed.SCFIND_POSIX
self.assertEquals(-1, self.ed.FindBytes(0, self.ed.Length, b"b.g", 0))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"b.g", flags))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"\<b.g\>", flags))
self.assertEquals(-1, self.ed.FindBytes(0, self.ed.Length, b"b[A-Z]g",
flags | self.ed.SCFIND_MATCHCASE))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"b[a-z]g", flags))
self.assertEquals(6, self.ed.FindBytes(0, self.ed.Length, b"b[a-z]*t", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"^a", flags))
self.assertEquals(10, self.ed.FindBytes(0, self.ed.Length, b"\t$", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"([a]).*\0", flags))
def testPhilippeREFind(self):
# Requires 1.,72
flags = self.ed.SCFIND_REGEXP
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"\w", flags))
self.assertEquals(1, self.ed.FindBytes(0, self.ed.Length, b"\W", flags))
self.assertEquals(-1, self.ed.FindBytes(0, self.ed.Length, b"\d", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"\D", flags))
self.assertEquals(1, self.ed.FindBytes(0, self.ed.Length, b"\s", flags))
self.assertEquals(0, self.ed.FindBytes(0, self.ed.Length, b"\S", flags))
self.assertEquals(2, self.ed.FindBytes(0, self.ed.Length, b"\x62", flags))
class TestProperties(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testSet(self):
self.ed.SetProperty(b"test", b"12")
self.assertEquals(self.ed.GetPropertyInt(b"test"), 12)
result = b"\0" * 10
length = self.ed.GetProperty(b"test", result)
result = result[:length]
self.assertEquals(result, b"12")
self.ed.SetProperty(b"test.plus", b"[$(test)]")
result = b"\0" * 10
length = self.ed.GetPropertyExpanded(b"test.plus", result)
result = result[:length]
self.assertEquals(result, b"[12]")
class TestTextMargin(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.txt = b"abcd"
self.ed.AddText(1, b"x")
def testAscent(self):
lineHeight = self.ed.TextHeight(0)
self.ed.ExtraAscent
self.assertEquals(self.ed.ExtraAscent, 0)
self.assertEquals(self.ed.ExtraDescent, 0)
self.ed.ExtraAscent = 1
self.assertEquals(self.ed.ExtraAscent, 1)
self.ed.ExtraDescent = 2
self.assertEquals(self.ed.ExtraDescent, 2)
# Allow line height to recalculate
self.xite.DoEvents()
lineHeightIncreased = self.ed.TextHeight(0)
self.assertEquals(lineHeightIncreased, lineHeight + 2 + 1)
def testTextMargin(self):
self.ed.MarginSetText(0, self.txt)
result = b"\0" * 10
length = self.ed.MarginGetText(0, result)
result = result[:length]
self.assertEquals(result, self.txt)
self.ed.MarginTextClearAll()
def testTextMarginStyle(self):
self.ed.MarginSetText(0, self.txt)
self.ed.MarginSetStyle(0, 33)
self.assertEquals(self.ed.MarginGetStyle(0), 33)
self.ed.MarginTextClearAll()
def testTextMarginStyles(self):
styles = b"\001\002\003\004"
self.ed.MarginSetText(0, self.txt)
self.ed.MarginSetStyles(0, styles)
result = b"\0" * 10
length = self.ed.MarginGetStyles(0, result)
result = result[:length]
self.assertEquals(result, styles)
self.ed.MarginTextClearAll()
def testTextMarginStyleOffset(self):
self.ed.MarginSetStyleOffset(300)
self.assertEquals(self.ed.MarginGetStyleOffset(), 300)
class TestAnnotation(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.txt = b"abcd"
self.ed.AddText(1, b"x")
def testTextAnnotation(self):
self.assertEquals(self.ed.AnnotationGetLines(), 0)
self.ed.AnnotationSetText(0, self.txt)
self.assertEquals(self.ed.AnnotationGetLines(), 1)
result = b"\0" * 10
length = self.ed.AnnotationGetText(0, result)
self.assertEquals(length, 4)
result = result[:length]
self.assertEquals(result, self.txt)
self.ed.AnnotationClearAll()
def testTextAnnotationStyle(self):
self.ed.AnnotationSetText(0, self.txt)
self.ed.AnnotationSetStyle(0, 33)
self.assertEquals(self.ed.AnnotationGetStyle(0), 33)
self.ed.AnnotationClearAll()
def testTextAnnotationStyles(self):
styles = b"\001\002\003\004"
self.ed.AnnotationSetText(0, self.txt)
self.ed.AnnotationSetStyles(0, styles)
result = b"\0" * 10
length = self.ed.AnnotationGetStyles(0, result)
result = result[:length]
self.assertEquals(result, styles)
self.ed.AnnotationClearAll()
def testTextAnnotationStyleOffset(self):
self.ed.AnnotationSetStyleOffset(300)
self.assertEquals(self.ed.AnnotationGetStyleOffset(), 300)
def testTextAnnotationVisible(self):
self.assertEquals(self.ed.AnnotationGetVisible(), 0)
self.ed.AnnotationSetVisible(2)
self.assertEquals(self.ed.AnnotationGetVisible(), 2)
self.ed.AnnotationSetVisible(0)
class TestMultiSelection(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
# 3 lines of 3 characters
t = b"xxx\nxxx\nxxx"
self.ed.AddText(len(t), t)
def testSelectionCleared(self):
self.ed.ClearSelections()
self.assertEquals(self.ed.Selections, 1)
self.assertEquals(self.ed.MainSelection, 0)
self.assertEquals(self.ed.GetSelectionNCaret(0), 0)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 0)
def test1Selection(self):
self.ed.SetSelection(1, 2)
self.assertEquals(self.ed.Selections, 1)
self.assertEquals(self.ed.MainSelection, 0)
self.assertEquals(self.ed.GetSelectionNCaret(0), 1)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 2)
self.assertEquals(self.ed.GetSelectionNStart(0), 1)
self.assertEquals(self.ed.GetSelectionNEnd(0), 2)
self.ed.SwapMainAnchorCaret()
self.assertEquals(self.ed.Selections, 1)
self.assertEquals(self.ed.MainSelection, 0)
self.assertEquals(self.ed.GetSelectionNCaret(0), 2)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 1)
def test1SelectionReversed(self):
self.ed.SetSelection(2, 1)
self.assertEquals(self.ed.Selections, 1)
self.assertEquals(self.ed.MainSelection, 0)
self.assertEquals(self.ed.GetSelectionNCaret(0), 2)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 1)
self.assertEquals(self.ed.GetSelectionNStart(0), 1)
self.assertEquals(self.ed.GetSelectionNEnd(0), 2)
def test1SelectionByStartEnd(self):
self.ed.SetSelectionNStart(0, 2)
self.ed.SetSelectionNEnd(0, 3)
self.assertEquals(self.ed.Selections, 1)
self.assertEquals(self.ed.MainSelection, 0)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 2)
self.assertEquals(self.ed.GetSelectionNCaret(0), 3)
self.assertEquals(self.ed.GetSelectionNStart(0), 2)
self.assertEquals(self.ed.GetSelectionNEnd(0), 3)
def test2Selections(self):
self.ed.SetSelection(1, 2)
self.ed.AddSelection(4, 5)
self.assertEquals(self.ed.Selections, 2)
self.assertEquals(self.ed.MainSelection, 1)
self.assertEquals(self.ed.GetSelectionNCaret(0), 1)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 2)
self.assertEquals(self.ed.GetSelectionNCaret(1), 4)
self.assertEquals(self.ed.GetSelectionNAnchor(1), 5)
self.assertEquals(self.ed.GetSelectionNStart(0), 1)
self.assertEquals(self.ed.GetSelectionNEnd(0), 2)
self.ed.MainSelection = 0
self.assertEquals(self.ed.MainSelection, 0)
self.ed.RotateSelection()
self.assertEquals(self.ed.MainSelection, 1)
def testRectangularSelection(self):
self.ed.RectangularSelectionAnchor = 1
self.assertEquals(self.ed.RectangularSelectionAnchor, 1)
self.ed.RectangularSelectionCaret = 10
self.assertEquals(self.ed.RectangularSelectionCaret, 10)
self.assertEquals(self.ed.Selections, 3)
self.assertEquals(self.ed.MainSelection, 2)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 1)
self.assertEquals(self.ed.GetSelectionNCaret(0), 2)
self.assertEquals(self.ed.GetSelectionNAnchor(1), 5)
self.assertEquals(self.ed.GetSelectionNCaret(1), 6)
self.assertEquals(self.ed.GetSelectionNAnchor(2), 9)
self.assertEquals(self.ed.GetSelectionNCaret(2), 10)
def testVirtualSpace(self):
self.ed.SetSelection(3, 7)
self.ed.SetSelectionNCaretVirtualSpace(0, 3)
self.assertEquals(self.ed.GetSelectionNCaretVirtualSpace(0), 3)
self.ed.SetSelectionNAnchorVirtualSpace(0, 2)
self.assertEquals(self.ed.GetSelectionNAnchorVirtualSpace(0), 2)
# Does not check that virtual space is valid by being at end of line
self.ed.SetSelection(1, 1)
self.ed.SetSelectionNCaretVirtualSpace(0, 3)
self.assertEquals(self.ed.GetSelectionNCaretVirtualSpace(0), 3)
def testRectangularVirtualSpace(self):
self.ed.VirtualSpaceOptions=1
self.ed.RectangularSelectionAnchor = 3
self.assertEquals(self.ed.RectangularSelectionAnchor, 3)
self.ed.RectangularSelectionCaret = 7
self.assertEquals(self.ed.RectangularSelectionCaret, 7)
self.ed.RectangularSelectionAnchorVirtualSpace = 1
self.assertEquals(self.ed.RectangularSelectionAnchorVirtualSpace, 1)
self.ed.RectangularSelectionCaretVirtualSpace = 10
self.assertEquals(self.ed.RectangularSelectionCaretVirtualSpace, 10)
self.assertEquals(self.ed.Selections, 2)
self.assertEquals(self.ed.MainSelection, 1)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 3)
self.assertEquals(self.ed.GetSelectionNAnchorVirtualSpace(0), 1)
self.assertEquals(self.ed.GetSelectionNCaret(0), 3)
self.assertEquals(self.ed.GetSelectionNCaretVirtualSpace(0), 10)
def testRectangularVirtualSpaceOptionOff(self):
# Same as previous test but virtual space option off so no virtual space in result
self.ed.VirtualSpaceOptions=0
self.ed.RectangularSelectionAnchor = 3
self.assertEquals(self.ed.RectangularSelectionAnchor, 3)
self.ed.RectangularSelectionCaret = 7
self.assertEquals(self.ed.RectangularSelectionCaret, 7)
self.ed.RectangularSelectionAnchorVirtualSpace = 1
self.assertEquals(self.ed.RectangularSelectionAnchorVirtualSpace, 1)
self.ed.RectangularSelectionCaretVirtualSpace = 10
self.assertEquals(self.ed.RectangularSelectionCaretVirtualSpace, 10)
self.assertEquals(self.ed.Selections, 2)
self.assertEquals(self.ed.MainSelection, 1)
self.assertEquals(self.ed.GetSelectionNAnchor(0), 3)
self.assertEquals(self.ed.GetSelectionNAnchorVirtualSpace(0), 0)
self.assertEquals(self.ed.GetSelectionNCaret(0), 3)
self.assertEquals(self.ed.GetSelectionNCaretVirtualSpace(0), 0)
class TestCaseMapping(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def tearDown(self):
self.ed.SetCodePage(0)
self.ed.StyleSetCharacterSet(self.ed.STYLE_DEFAULT, self.ed.SC_CHARSET_DEFAULT)
def testEmpty(self):
# Trying to upper case an empty string caused a crash at one stage
t = b"x"
self.ed.SetText(len(t), t)
self.ed.UpperCase()
self.assertEquals(self.ed.Contents(), b"x")
def testASCII(self):
t = b"x"
self.ed.SetText(len(t), t)
self.ed.SetSel(0,1)
self.ed.UpperCase()
self.assertEquals(self.ed.Contents(), b"X")
def testLatin1(self):
t = "å".encode("Latin-1")
r = "Å".encode("Latin-1")
self.ed.SetText(len(t), t)
self.ed.SetSel(0,1)
self.ed.UpperCase()
self.assertEquals(self.ed.Contents(), r)
def testRussian(self):
self.ed.StyleSetCharacterSet(self.ed.STYLE_DEFAULT, self.ed.SC_CHARSET_RUSSIAN)
t = "Б".encode("Windows-1251")
r = "б".encode("Windows-1251")
self.ed.SetText(len(t), t)
self.ed.SetSel(0,1)
self.ed.LowerCase()
self.assertEquals(self.ed.Contents(), r)
def testUTF(self):
self.ed.SetCodePage(65001)
t = "å".encode("UTF-8")
r = "Å".encode("UTF-8")
self.ed.SetText(len(t), t)
self.ed.SetSel(0,2)
self.ed.UpperCase()
self.assertEquals(self.ed.Contents(), r)
def testUTFDifferentLength(self):
self.ed.SetCodePage(65001)
t = "ı".encode("UTF-8")
r = "I".encode("UTF-8")
self.ed.SetText(len(t), t)
self.assertEquals(self.ed.Length, 2)
self.ed.SetSel(0,2)
self.ed.UpperCase()
self.assertEquals(self.ed.Length, 1)
self.assertEquals(self.ed.Contents(), r)
class TestCaseInsensitiveSearch(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def tearDown(self):
self.ed.SetCodePage(0)
self.ed.StyleSetCharacterSet(self.ed.STYLE_DEFAULT, self.ed.SC_CHARSET_DEFAULT)
def testEmpty(self):
text = b" x X"
searchString = b""
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(0, pos)
def testASCII(self):
text = b" x X"
searchString = b"X"
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(1, pos)
def testLatin1(self):
text = "Frånd Åå".encode("Latin-1")
searchString = "Å".encode("Latin-1")
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(2, pos)
def testRussian(self):
self.ed.StyleSetCharacterSet(self.ed.STYLE_DEFAULT, self.ed.SC_CHARSET_RUSSIAN)
text = "=(Б tex б)".encode("Windows-1251")
searchString = "б".encode("Windows-1251")
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(2, pos)
def testUTF(self):
self.ed.SetCodePage(65001)
text = "Frånd Åå".encode("UTF-8")
searchString = "Å".encode("UTF-8")
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(2, pos)
def testUTFDifferentLength(self):
# Searching for a two byte string "ı" finds a single byte "I"
self.ed.SetCodePage(65001)
text = "Fråndi Ååİ $".encode("UTF-8")
firstPosition = len("Frånd".encode("UTF-8"))
searchString = "İ".encode("UTF-8")
self.assertEquals(len(searchString), 2)
self.ed.SetText(len(text), text)
self.ed.TargetStart = 0
self.ed.TargetEnd = self.ed.Length-1
self.ed.SearchFlags = 0
pos = self.ed.SearchInTarget(len(searchString), searchString)
self.assertEquals(firstPosition, pos)
self.assertEquals(firstPosition+1, self.ed.TargetEnd)
class TestLexer(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testLexerNumber(self):
self.ed.Lexer = self.ed.SCLEX_CPP
self.assertEquals(self.ed.GetLexer(), self.ed.SCLEX_CPP)
def testLexerName(self):
self.ed.LexerLanguage = b"cpp"
self.assertEquals(self.ed.GetLexer(), self.ed.SCLEX_CPP)
name = b"-" * 100
length = self.ed.GetLexerLanguage(0, name)
name = name[:length]
self.assertEquals(name, b"cpp")
class TestAutoComplete(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
# 1 line of 3 characters
t = b"xxx\n"
self.ed.AddText(len(t), t)
def testDefaults(self):
self.assertEquals(self.ed.AutoCGetSeparator(), ord(' '))
self.assertEquals(self.ed.AutoCGetMaxHeight(), 5)
self.assertEquals(self.ed.AutoCGetMaxWidth(), 0)
self.assertEquals(self.ed.AutoCGetTypeSeparator(), ord('?'))
self.assertEquals(self.ed.AutoCGetIgnoreCase(), 0)
self.assertEquals(self.ed.AutoCGetAutoHide(), 1)
self.assertEquals(self.ed.AutoCGetDropRestOfWord(), 0)
def testChangeDefaults(self):
self.ed.AutoCSetSeparator(ord('-'))
self.assertEquals(self.ed.AutoCGetSeparator(), ord('-'))
self.ed.AutoCSetSeparator(ord(' '))
self.ed.AutoCSetMaxHeight(100)
self.assertEquals(self.ed.AutoCGetMaxHeight(), 100)
self.ed.AutoCSetMaxHeight(5)
self.ed.AutoCSetMaxWidth(100)
self.assertEquals(self.ed.AutoCGetMaxWidth(), 100)
self.ed.AutoCSetMaxWidth(0)
self.ed.AutoCSetTypeSeparator(ord('@'))
self.assertEquals(self.ed.AutoCGetTypeSeparator(), ord('@'))
self.ed.AutoCSetTypeSeparator(ord('?'))
self.ed.AutoCSetIgnoreCase(1)
self.assertEquals(self.ed.AutoCGetIgnoreCase(), 1)
self.ed.AutoCSetIgnoreCase(0)
self.ed.AutoCSetAutoHide(0)
self.assertEquals(self.ed.AutoCGetAutoHide(), 0)
self.ed.AutoCSetAutoHide(1)
self.ed.AutoCSetDropRestOfWord(1)
self.assertEquals(self.ed.AutoCGetDropRestOfWord(), 1)
self.ed.AutoCSetDropRestOfWord(0)
def testAutoShow(self):
self.assertEquals(self.ed.AutoCActive(), 0)
self.ed.SetSel(0, 0)
self.ed.AutoCShow(0, b"za defn ghi")
self.assertEquals(self.ed.AutoCActive(), 1)
#~ time.sleep(2)
self.assertEquals(self.ed.AutoCPosStart(), 0)
self.assertEquals(self.ed.AutoCGetCurrent(), 0)
t = b"xxx"
l = self.ed.AutoCGetCurrentText(5, t)
#~ self.assertEquals(l, 3)
self.assertEquals(t, b"za\0")
self.ed.AutoCCancel()
self.assertEquals(self.ed.AutoCActive(), 0)
def testAutoShowComplete(self):
self.assertEquals(self.ed.AutoCActive(), 0)
self.ed.SetSel(0, 0)
self.ed.AutoCShow(0, b"za defn ghi")
self.ed.AutoCComplete()
self.assertEquals(self.ed.Contents(), b"zaxxx\n")
self.assertEquals(self.ed.AutoCActive(), 0)
def testAutoShowSelect(self):
self.assertEquals(self.ed.AutoCActive(), 0)
self.ed.SetSel(0, 0)
self.ed.AutoCShow(0, b"za defn ghi")
self.ed.AutoCSelect(0, b"d")
self.ed.AutoCComplete()
self.assertEquals(self.ed.Contents(), b"defnxxx\n")
self.assertEquals(self.ed.AutoCActive(), 0)
class TestDirectAccess(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testGapPosition(self):
text = b"abcd"
self.ed.SetText(len(text), text)
self.assertEquals(self.ed.GapPosition, 4)
self.ed.TargetStart = 1
self.ed.TargetEnd = 1
rep = b"-"
self.ed.ReplaceTarget(len(rep), rep)
self.assertEquals(self.ed.GapPosition, 2)
def testCharacterPointerAndRangePointer(self):
text = b"abcd"
self.ed.SetText(len(text), text)
characterPointer = self.ed.CharacterPointer
rangePointer = self.ed.GetRangePointer(0,3)
self.assertEquals(characterPointer, rangePointer)
cpBuffer = ctypes.c_char_p(characterPointer)
self.assertEquals(cpBuffer.value, text)
# Gap will not be moved as already moved for CharacterPointer call
rangePointer = self.ed.GetRangePointer(1,3)
cpBuffer = ctypes.c_char_p(rangePointer)
self.assertEquals(cpBuffer.value, text[1:])
class TestWordChars(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def tearDown(self):
self.ed.SetCharsDefault()
def _setChars(self, charClass, chars):
""" Wrapper to call self.ed.Set*Chars with the right type
@param charClass {str} the character class, "word", "space", etc.
@param chars {iterable of int} characters to set
"""
if sys.version_info.major == 2:
# Python 2, use latin-1 encoded str
unichars = (unichr(x) for x in chars if x != 0)
# can't use literal u"", that's a syntax error in Py3k
# uncode() doesn't exist in Py3k, but we never run it there
result = unicode("").join(unichars).encode("latin-1")
else:
# Python 3, use bytes()
result = bytes(x for x in chars if x != 0)
meth = getattr(self.ed, "Set%sChars" % (charClass.capitalize()))
return meth(None, result)
def assertCharSetsEqual(self, first, second, *args, **kwargs):
""" Assert that the two character sets are equal.
If either set are an iterable of numbers, convert them to chars
first. """
first_set = set()
for c in first:
first_set.add(chr(c) if isinstance(c, int) else c)
second_set = set()
for c in second:
second_set.add(chr(c) if isinstance(c, int) else c)
return self.assertEqual(first_set, second_set, *args, **kwargs)
def testDefaultWordChars(self):
# check that the default word chars are as expected
import string
dataLen = self.ed.GetWordChars(None, None)
data = b"\0" * dataLen
self.ed.GetWordChars(None, data)
self.assertEquals(dataLen, len(data))
expected = set(string.digits + string.ascii_letters + '_') | \
set(chr(x) for x in range(0x80, 0x100))
self.assertCharSetsEqual(data, expected)
def testDefaultWhitespaceChars(self):
# check that the default whitespace chars are as expected
import string
dataLen = self.ed.GetWhitespaceChars(None, None)
data = b"\0" * dataLen
self.ed.GetWhitespaceChars(None, data)
self.assertEquals(dataLen, len(data))
expected = (set(chr(x) for x in (range(0, 0x20))) | set(' ')) - \
set(['\r', '\n'])
self.assertCharSetsEqual(data, expected)
def testDefaultPunctuationChars(self):
# check that the default punctuation chars are as expected
import string
dataLen = self.ed.GetPunctuationChars(None, None)
data = b"\0" * dataLen
self.ed.GetPunctuationChars(None, data)
self.assertEquals(dataLen, len(data))
expected = set(chr(x) for x in range(0x20, 0x80)) - \
set(string.ascii_letters + string.digits + "\r\n_ ")
self.assertCharSetsEqual(data, expected)
def testCustomWordChars(self):
# check that setting things to whitespace chars makes them not words
self._setChars("whitespace", range(1, 0x100))
dataLen = self.ed.GetWordChars(None, None)
data = b"\0" * dataLen
self.ed.GetWordChars(None, data)
self.assertEquals(dataLen, len(data))
expected = set()
self.assertCharSetsEqual(data, expected)
# and now set something to make sure that works too
expected = set(range(1, 0x100, 2))
self._setChars("word", expected)
dataLen = self.ed.GetWordChars(None, None)
data = b"\0" * dataLen
self.ed.GetWordChars(None, data)
self.assertEquals(dataLen, len(data))
self.assertCharSetsEqual(data, expected)
def testCustomWhitespaceChars(self):
# check setting whitespace chars to non-default values
self._setChars("word", range(1, 0x100))
# we can't change chr(0) from being anything but whitespace
expected = set([0])
dataLen = self.ed.GetWhitespaceChars(None, None)
data = b"\0" * dataLen
self.ed.GetWhitespaceChars(None, data)
self.assertEquals(dataLen, len(data))
self.assertCharSetsEqual(data, expected)
# now try to set it to something custom
expected = set(range(1, 0x100, 2)) | set([0])
self._setChars("whitespace", expected)
dataLen = self.ed.GetWhitespaceChars(None, None)
data = b"\0" * dataLen
self.ed.GetWhitespaceChars(None, data)
self.assertEquals(dataLen, len(data))
self.assertCharSetsEqual(data, expected)
def testCustomPunctuationChars(self):
# check setting punctuation chars to non-default values
self._setChars("word", range(1, 0x100))
expected = set()
dataLen = self.ed.GetPunctuationChars(None, None)
data = b"\0" * dataLen
self.ed.GetPunctuationChars(None, data)
self.assertEquals(dataLen, len(data))
self.assertEquals(set(data), expected)
# now try to set it to something custom
expected = set(range(1, 0x100, 1))
self._setChars("punctuation", expected)
dataLen = self.ed.GetPunctuationChars(None, None)
data = b"\0" * dataLen
self.ed.GetPunctuationChars(None, data)
self.assertEquals(dataLen, len(data))
self.assertCharSetsEqual(data, expected)
#~ import os
#~ for x in os.getenv("PATH").split(";"):
#~ n = "scilexer.dll"
#~ nf = x + "\\" + n
#~ print os.access(nf, os.R_OK), nf
if __name__ == '__main__':
uu = XiteWin.main("simpleTests")
#~ for x in sorted(uu.keys()):
#~ print(x, uu[x])
#~ print()
| Python |
# List many windows message numbers
msgs = {
"WM_ACTIVATE":6,
"WM_ACTIVATEAPP":28,
"WM_CAPTURECHANGED":533,
"WM_CHAR":258,
"WM_CLOSE":16,
"WM_CREATE":1,
"WM_COMMAND":273,
"WM_DESTROY":2,
"WM_ENTERSIZEMOVE":561,
"WM_ERASEBKGND":20,
"WM_EXITSIZEMOVE":562,
"WM_GETMINMAXINFO":36,
"WM_GETTEXT":13,
"WM_IME_SETCONTEXT":0x0281,
"WM_IME_NOTIFY":0x0282,
"WM_KEYDOWN":256,
"WM_KEYUP":257,
"WM_KILLFOCUS":8,
"WM_LBUTTONDOWN":513,
"WM_LBUTTONUP":514,
"WM_MBUTTONDOWN":519,
"WM_MBUTTONUP":520,
"WM_MBUTTONDBLCLK":521,
"WM_MOUSEACTIVATE":33,
"WM_MOUSEMOVE":512,
"WM_MOVE":3,
"WM_MOVING":534,
"WM_NCACTIVATE":134,
"WM_NCCALCSIZE":131,
"WM_NCCREATE":129,
"WM_NCDESTROY":130,
"WM_NCHITTEST":132,
"WM_NCLBUTTONDBLCLK":163,
"WM_NCLBUTTONDOWN":161,
"WM_NCLBUTTONUP":162,
"WM_NCMOUSEMOVE":160,
"WM_NCPAINT":133,
"WM_PAINT":15,
"WM_PARENTNOTIFY":528,
"WM_SETCURSOR":32,
"WM_SETFOCUS":7,
"WM_SETFONT":48,
"WM_SETTEXT":12,
"WM_SHOWWINDOW":24,
"WM_SIZE":5,
"WM_SIZING":532,
"WM_SYNCPAINT":136,
"WM_SYSCOMMAND":274,
"WM_SYSKEYDOWN":260,
"WM_TIMER":275,
"WM_USER":1024,
"WM_USER+1":1025,
"WM_WINDOWPOSCHANGED":71,
"WM_WINDOWPOSCHANGING":70,
}
sgsm={}
for k,v in msgs.items():
sgsm[v] = k
| Python |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from __future__ import unicode_literals
import os, sys, unittest
import ctypes
from ctypes import wintypes
from ctypes import c_int, c_ulong, c_char_p, c_wchar_p, c_ushort
user32=ctypes.windll.user32
gdi32=ctypes.windll.gdi32
kernel32=ctypes.windll.kernel32
from MessageNumbers import msgs, sgsm
import XiteMenu
scintillaDirectory = ".."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.append(scintillaIncludeDirectory)
import Face
scintillaBinDirectory = os.path.join(scintillaDirectory, "bin")
os.environ['PATH'] = os.environ['PATH'] + ";" + scintillaBinDirectory
#print(os.environ['PATH'])
WFUNC = ctypes.WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int)
WS_CHILD = 0x40000000
WS_CLIPCHILDREN = 0x2000000
WS_OVERLAPPEDWINDOW = 0xcf0000
WS_VISIBLE = 0x10000000
WS_HSCROLL = 0x100000
WS_VSCROLL = 0x200000
WA_INACTIVE = 0
MF_POPUP = 16
MF_SEPARATOR = 0x800
IDYES = 6
OFN_HIDEREADONLY = 4
MB_OK = 0
MB_YESNOCANCEL = 3
MF_CHECKED = 8
MF_UNCHECKED = 0
SW_SHOW = 5
PM_REMOVE = 1
VK_SHIFT = 16
VK_CONTROL = 17
VK_MENU = 18
class OPENFILENAME(ctypes.Structure):
_fields_ = (("lStructSize", c_int),
("hwndOwner", c_int),
("hInstance", c_int),
("lpstrFilter", c_wchar_p),
("lpstrCustomFilter", c_char_p),
("nMaxCustFilter", c_int),
("nFilterIndex", c_int),
("lpstrFile", c_wchar_p),
("nMaxFile", c_int),
("lpstrFileTitle", c_wchar_p),
("nMaxFileTitle", c_int),
("lpstrInitialDir", c_wchar_p),
("lpstrTitle", c_wchar_p),
("flags", c_int),
("nFileOffset", c_ushort),
("nFileExtension", c_ushort),
("lpstrDefExt", c_char_p),
("lCustData", c_int),
("lpfnHook", c_char_p),
("lpTemplateName", c_char_p),
("pvReserved", c_char_p),
("dwReserved", c_int),
("flagsEx", c_int))
def __init__(self, win, title):
ctypes.Structure.__init__(self)
self.lStructSize = ctypes.sizeof(OPENFILENAME)
self.nMaxFile = 1024
self.hwndOwner = win
self.lpstrTitle = title
self.Flags = OFN_HIDEREADONLY
trace = False
#~ trace = True
def WindowSize(w):
rc = ctypes.wintypes.RECT()
user32.GetClientRect(w, ctypes.byref(rc))
return rc.right - rc.left, rc.bottom - rc.top
def IsKeyDown(key):
return (user32.GetKeyState(key) & 0x8000) != 0
def KeyTranslate(w):
tr = { 9: "Tab", 0xD:"Enter", 0x1B: "Esc" }
if w in tr:
return tr[w]
elif ord("A") <= w <= ord("Z"):
return chr(w)
elif 0x70 <= w <= 0x7b:
return "F" + str(w-0x70+1)
else:
return "Unknown_" + hex(w)
class WNDCLASS(ctypes.Structure):
_fields_= (\
('style', c_int),
('lpfnWndProc', WFUNC),
('cls_extra', c_int),
('wnd_extra', c_int),
('hInst', c_int),
('hIcon', c_int),
('hCursor', c_int),
('hbrBackground', c_int),
('menu_name', c_wchar_p),
('lpzClassName', c_wchar_p),
)
class XTEXTRANGE(ctypes.Structure):
_fields_= (\
('cpMin', c_int),
('cpMax', c_int),
('lpstrText', c_char_p),
)
class TEXTRANGE(ctypes.Structure):
_fields_= (\
('cpMin', c_int),
('cpMax', c_int),
('lpstrText', ctypes.POINTER(ctypes.c_char)),
)
class FINDTEXT(ctypes.Structure):
_fields_= (\
('cpMin', c_int),
('cpMax', c_int),
('lpstrText', c_char_p),
('cpMinText', c_int),
('cpMaxText', c_int),
)
hinst = ctypes.windll.kernel32.GetModuleHandleW(0)
def RegisterClass(name, func, background = 0):
# register a window class for toplevel windows.
wc = WNDCLASS()
wc.style = 0
wc.lpfnWndProc = func
wc.cls_extra = 0
wc.wnd_extra = 0
wc.hInst = hinst
wc.hIcon = 0
wc.hCursor = 0
wc.hbrBackground = background
wc.menu_name = 0
wc.lpzClassName = name
user32.RegisterClassW(ctypes.byref(wc))
class SciCall:
def __init__(self, fn, ptr, msg):
self._fn = fn
self._ptr = ptr
self._msg = msg
def __call__(self, w=0, l=0):
return self._fn(self._ptr, self._msg, w, l)
class Scintilla:
def __init__(self, face, hwndParent, hinstance):
self.__dict__["face"] = face
self.__dict__["used"] = set()
self.__dict__["all"] = set()
# The k member is for accessing constants as a dictionary
self.__dict__["k"] = {}
for f in face.features:
self.all.add(f)
if face.features[f]["FeatureType"] == "val":
self.k[f] = int(self.face.features[f]["Value"], 0)
elif face.features[f]["FeatureType"] == "evt":
self.k["SCN_"+f] = int(self.face.features[f]["Value"], 0)
# Get the function first as that also loads the DLL
self.__dict__["_scifn"] = ctypes.windll.SciLexer.Scintilla_DirectFunction
self.__dict__["_hwnd"] = user32.CreateWindowExW(0,
"Scintilla", "Source",
WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_CLIPCHILDREN,
0, 0, 100, 100, hwndParent, 0, hinstance, 0)
self.__dict__["_sciptr"] = user32.SendMessageW(self._hwnd,
int(self.face.features["GetDirectPointer"]["Value"], 0), 0,0)
user32.ShowWindow(self._hwnd, SW_SHOW)
def __getattr__(self, name):
if name in self.face.features:
self.used.add(name)
feature = self.face.features[name]
value = int(feature["Value"], 0)
#~ print("Feature", name, feature)
if feature["FeatureType"] == "val":
self.__dict__[name] = value
return value
else:
return SciCall(self._scifn, self._sciptr, value)
elif ("Get" + name) in self.face.features:
self.used.add("Get" + name)
feature = self.face.features["Get" + name]
value = int(feature["Value"], 0)
if feature["FeatureType"] == "get" and \
not name.startswith("Get") and \
not feature["Param1Type"] and \
not feature["Param2Type"] and \
feature["ReturnType"] in ["bool", "int", "position"]:
#~ print("property", feature)
return self._scifn(self._sciptr, value, 0, 0)
elif name.startswith("SCN_") and name in self.k:
self.used.add(name)
feature = self.face.features[name[4:]]
value = int(feature["Value"], 0)
#~ print("Feature", name, feature)
if feature["FeatureType"] == "val":
return value
raise AttributeError(name)
def __setattr__(self, name, val):
if ("Set" + name) in self.face.features:
self.used.add("Set" + name)
feature = self.face.features["Set" + name]
value = int(feature["Value"], 0)
#~ print("setproperty", feature)
if feature["FeatureType"] == "set" and not name.startswith("Set"):
if feature["Param1Type"] in ["bool", "int", "position"]:
return self._scifn(self._sciptr, value, val, 0)
elif feature["Param2Type"] in ["string"]:
return self._scifn(self._sciptr, value, 0, val)
raise AttributeError(name)
raise AttributeError(name)
def getvalue(self, name):
if name in self.face.features:
feature = self.face.features[name]
if feature["FeatureType"] != "evt":
try:
return int(feature["Value"], 0)
except ValueError:
return -1
return -1
def ByteRange(self, start, end):
tr = TEXTRANGE()
tr.cpMin = start
tr.cpMax = end
length = end - start
tr.lpstrText = ctypes.create_string_buffer(length + 1)
self.GetTextRange(0, ctypes.byref(tr))
text = tr.lpstrText[:length]
text += b"\0" * (length - len(text))
return text
def StyledTextRange(self, start, end):
tr = TEXTRANGE()
tr.cpMin = start
tr.cpMax = end
length = 2 * (end - start)
tr.lpstrText = ctypes.create_string_buffer(length + 2)
self.GetStyledText(0, ctypes.byref(tr))
styledText = tr.lpstrText[:length]
styledText += b"\0" * (length - len(styledText))
return styledText
def FindBytes(self, start, end, s, flags):
ft = FINDTEXT()
ft.cpMin = start
ft.cpMax = end
ft.lpstrText = s
ft.cpMinText = 0
ft.cpMaxText = 0
pos = self.FindText(flags, ctypes.byref(ft))
#~ print(start, end, ft.cpMinText, ft.cpMaxText)
return pos
def Contents(self):
return self.ByteRange(0, self.Length)
def SizeTo(self, width, height):
user32.SetWindowPos(self._hwnd, 0, 0, 0, width, height, 0)
def FocusOn(self):
user32.SetFocus(self._hwnd)
class XiteWin():
def __init__(self, test=""):
self.face = Face.Face()
self.face.ReadFromFile(os.path.join(scintillaIncludeDirectory, "Scintilla.iface"))
self.titleDirty = True
self.fullPath = ""
self.test = test
self.appName = "xite"
self.cmds = {}
self.windowName = "XiteWindow"
self.wfunc = WFUNC(self.WndProc)
RegisterClass(self.windowName, self.wfunc)
user32.CreateWindowExW(0, self.windowName, self.appName, \
WS_VISIBLE | WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, \
0, 0, 500, 700, 0, 0, hinst, 0)
args = sys.argv[1:]
self.SetMenus()
if args:
self.GrabFile(args[0])
self.ed.FocusOn()
self.ed.GotoPos(self.ed.Length)
if self.test:
print(self.test)
for k in self.cmds:
if self.cmds[k] == "Test":
user32.PostMessageW(self.win, msgs["WM_COMMAND"], k, 0)
def OnSize(self):
width, height = WindowSize(self.win)
self.ed.SizeTo(width, height)
user32.InvalidateRect(self.win, 0, 0)
def OnCreate(self, hwnd):
self.win = hwnd
self.ed = Scintilla(self.face, hwnd, hinst)
self.ed.FocusOn()
def Invalidate(self):
user32.InvalidateRect(self.win, 0, 0)
def WndProc(self, h, m, w, l):
ms = sgsm.get(m, "XXX")
if trace:
print("%s %s %s %s" % (hex(h)[2:],ms,w,l))
if ms == "WM_CLOSE":
user32.PostQuitMessage(0)
elif ms == "WM_CREATE":
self.OnCreate(h)
return 0
elif ms == "WM_SIZE":
# Work out size
if w != 1:
self.OnSize()
return 0
elif ms == "WM_COMMAND":
cmdCode = w & 0xffff
if cmdCode in self.cmds:
self.Command(self.cmds[cmdCode])
return 0
elif ms == "WM_ACTIVATE":
if w != WA_INACTIVE:
self.ed.FocusOn()
return 0
else:
return user32.DefWindowProcW(h, m, w, l)
return 0
def Command(self, name):
name = name.replace(" ", "")
method = "Cmd" + name
cmd = None
try:
cmd = getattr(self, method)
except AttributeError:
return
if cmd:
cmd()
def KeyDown(self, w, prefix = ""):
keyName = prefix
if IsKeyDown(VK_CONTROL):
keyName += "<control>"
if IsKeyDown(VK_SHIFT):
keyName += "<shift>"
keyName += KeyTranslate(w)
if trace:
print("Key:", keyName)
if keyName in self.keys:
method = "Cmd" + self.keys[keyName]
getattr(self, method)()
return True
#~ print("UKey:", keyName)
return False
def Accelerator(self, msg):
ms = sgsm.get(msg.message, "XXX")
if ms == "WM_KEYDOWN":
return self.KeyDown(msg.wParam)
elif ms == "WM_SYSKEYDOWN":
return self.KeyDown(msg.wParam, "<alt>")
return False
def AppLoop(self):
msg = ctypes.wintypes.MSG()
lpmsg = ctypes.byref(msg)
while user32.GetMessageW(lpmsg, 0, 0, 0):
if trace and msg.message != msgs["WM_TIMER"]:
print('mm', hex(msg.hWnd)[2:],sgsm.get(msg.message, "XXX"))
if not self.Accelerator(msg):
user32.TranslateMessage(lpmsg)
user32.DispatchMessageW(lpmsg)
def DoEvents(self):
msg = ctypes.wintypes.MSG()
lpmsg = ctypes.byref(msg)
cont = True
while cont:
cont = user32.PeekMessageW(lpmsg, 0, 0, 0, PM_REMOVE)
if cont:
if not self.Accelerator(msg):
user32.TranslateMessage(lpmsg)
user32.DispatchMessageW(lpmsg)
def SetTitle(self, changePath):
if changePath or self.titleDirty != self.ed.Modify:
self.titleDirty = self.ed.Modify
self.title = self.fullPath
if self.titleDirty:
self.title += " * "
else:
self.title += " - "
self.title += self.appName
if self.win:
user32.SetWindowTextW(self.win, self.title)
def Open(self):
ofx = OPENFILENAME(self.win, "Open File")
opath = "\0" * 1024
ofx.lpstrFile = opath
filters = ["Python (.py;.pyw)|*.py;*.pyw|All|*.*"]
filterText = "\0".join([f.replace("|", "\0") for f in filters])+"\0\0"
ofx.lpstrFilter = filterText
if ctypes.windll.comdlg32.GetOpenFileNameW(ctypes.byref(ofx)):
absPath = opath.replace("\0", "")
self.GrabFile(absPath)
self.ed.FocusOn()
self.ed.LexerLanguage = "python"
self.ed.Lexer = self.ed.SCLEX_PYTHON
self.ed.SetKeyWords(0, b"class def else for from if import print return while")
for style in [k for k in self.ed.k if k.startswith("SCE_P_")]:
self.ed.StyleSetFont(self.ed.k[style], b"Verdana")
if "COMMENT" in style:
self.ed.StyleSetFore(self.ed.k[style], 127 * 256)
self.ed.StyleSetFont(self.ed.k[style], b"Comic Sans MS")
elif "OPERATOR" in style:
self.ed.StyleSetBold(self.ed.k[style], 1)
self.ed.StyleSetFore(self.ed.k[style], 127 * 256 * 256)
elif "WORD" in style:
self.ed.StyleSetItalic(self.ed.k[style], 255)
self.ed.StyleSetFore(self.ed.k[style], 255 * 256 * 256)
elif "TRIPLE" in style:
self.ed.StyleSetFore(self.ed.k[style], 0xA0A0)
elif "STRING" in style or "CHARACTER" in style:
self.ed.StyleSetFore(self.ed.k[style], 0xA000A0)
else:
self.ed.StyleSetFore(self.ed.k[style], 0)
def SaveAs(self):
ofx = OPENFILENAME(self.win, "Save File")
opath = "\0" * 1024
ofx.lpstrFile = opath
if ctypes.windll.comdlg32.GetSaveFileNameW(ctypes.byref(ofx)):
self.fullPath = opath.replace("\0", "")
self.Save()
self.SetTitle(1)
self.ed.FocusOn()
def SetMenus(self):
ui = XiteMenu.MenuStructure
self.cmds = {}
self.keys = {}
cmdId = 0
self.menuBar = user32.CreateMenu()
for name, contents in ui:
cmdId += 1
menu = user32.CreateMenu()
for item in contents:
text, key = item
cmdText = text.replace("&", "")
cmdText = cmdText.replace("...", "")
cmdText = cmdText.replace(" ", "")
cmdId += 1
if key:
keyText = key.replace("<control>", "Ctrl+")
keyText = keyText.replace("<shift>", "Shift+")
text += "\t" + keyText
if text == "-":
user32.AppendMenuW(menu, MF_SEPARATOR, cmdId, text)
else:
user32.AppendMenuW(menu, 0, cmdId, text)
self.cmds[cmdId] = cmdText
self.keys[key] = cmdText
#~ print(cmdId, item)
user32.AppendMenuW(self.menuBar, MF_POPUP, menu, name)
user32.SetMenu(self.win, self.menuBar)
self.CheckMenuItem("Wrap", True)
user32.ShowWindow(self.win, SW_SHOW)
def CheckMenuItem(self, name, val):
#~ print(name, val)
if self.cmds:
for k,v in self.cmds.items():
if v == name:
#~ print(name, k)
user32.CheckMenuItem(user32.GetMenu(self.win), \
k, [MF_UNCHECKED, MF_CHECKED][val])
def Exit(self):
sys.exit(0)
def DisplayMessage(self, msg, ask):
return IDYES == user32.MessageBoxW(self.win, \
msg, self.appName, [MB_OK, MB_YESNOCANCEL][ask])
def NewDocument(self):
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
self.ed.SetSavePoint()
def SaveIfUnsure(self):
if self.ed.Modify:
msg = "Save changes to \"" + self.fullPath + "\"?"
print(msg)
decision = self.DisplayMessage(msg, True)
if decision:
self.CmdSave()
return decision
return True
def New(self):
if self.SaveIfUnsure():
self.fullPath = ""
self.overrideMode = None
self.NewDocument()
self.SetTitle(1)
self.Invalidate()
def CheckMenus(self):
pass
def MoveSelection(self, caret, anchor=-1):
if anchor == -1:
anchor = caret
self.ed.SetSelectionStart(caret)
self.ed.SetSelectionEnd(anchor)
self.ed.ScrollCaret()
self.Invalidate()
def GrabFile(self, name):
self.fullPath = name
self.overrideMode = None
self.NewDocument()
fsr = open(name, "rb")
data = fsr.read()
fsr.close()
self.ed.AddText(len(data), data)
self.ed.EmptyUndoBuffer()
self.MoveSelection(0)
self.SetTitle(1)
def Save(self):
fos = open(self.fullPath, "wb")
blockSize = 1024
length = self.ed.Length
i = 0
while i < length:
grabSize = length - i
if grabSize > blockSize:
grabSize = blockSize
#~ print(i, grabSize, length)
data = self.ed.ByteRange(i, i + grabSize)
fos.write(data)
i += grabSize
fos.close()
self.ed.SetSavePoint()
self.SetTitle(0)
# Command handlers are called by menu actions
def CmdNew(self):
self.New()
def CmdOpen(self):
self.Open()
def CmdSave(self):
if (self.fullPath == None) or (len(self.fullPath) == 0):
self.SaveAs()
else:
self.Save()
def CmdSaveAs(self):
self.SaveAs()
def CmdTest(self):
runner = unittest.TextTestRunner()
if self.test:
tests = unittest.defaultTestLoader.loadTestsFromName(self.test)
else:
tests = unittest.defaultTestLoader.loadTestsFromName("simpleTests")
results = runner.run(tests)
#~ print(results)
if self.test:
user32.PostQuitMessage(0)
def CmdExercised(self):
print()
unused = sorted(self.ed.all.difference(self.ed.used))
print("Unused", len(unused))
print()
print("\n".join(unused))
print()
print("Used", len(self.ed.used))
print()
print("\n".join(sorted(self.ed.used)))
def Uncalled(self):
print("")
unused = sorted(self.ed.all.difference(self.ed.used))
uu = {}
for u in unused:
v = self.ed.getvalue(u)
if v > 2000:
uu[v] = u
#~ for x in sorted(uu.keys())[150:]:
return uu
def CmdExit(self):
self.Exit()
def CmdUndo(self):
self.ed.Undo()
def CmdRedo(self):
self.ed.Redo()
def CmdCut(self):
self.ed.Cut()
def CmdCopy(self):
self.ed.Copy()
def CmdPaste(self):
self.ed.Paste()
def CmdDelete(self):
self.ed.Clear()
xiteFrame = None
def main(test):
global xiteFrame
xiteFrame = XiteWin(test)
xiteFrame.AppLoop()
#~ xiteFrame.CmdExercised()
return xiteFrame.Uncalled()
| Python |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import io
import os
import unittest
import XiteWin
keywordsHTML = [
b"b body content head href html link meta "
b"name rel script strong title type xmlns",
b"function",
b"sub"
]
class TestLexers(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def AsStyled(self):
text = self.ed.Contents()
data = io.BytesIO()
prevStyle = -1
for o in range(self.ed.Length):
styleNow = self.ed.GetStyleAt(o)
if styleNow != prevStyle:
styleBuf = "{%0d}" % styleNow
data.write(styleBuf.encode('utf-8'))
prevStyle = styleNow
data.write(text[o:o+1])
return data.getvalue()
def LexExample(self, name, lexerName, keywords=None):
if keywords is None:
keywords = []
self.ed.LexerLanguage = lexerName
bits = self.ed.StyleBitsNeeded
mask = 2 << bits - 1
self.ed.StyleBits = bits
for i in range(len(keywords)):
self.ed.SetKeyWords(i, keywords[i])
nameExample = os.path.join("examples", name)
namePrevious = nameExample +".styled"
nameNew = nameExample +".new"
with open(nameExample, "rb") as f:
prog = f.read()
BOM = b"\xEF\xBB\xBF"
if prog.startswith(BOM):
prog = prog[len(BOM):]
lenDocument = len(prog)
self.ed.AddText(lenDocument, prog)
self.ed.Colourise(0, lenDocument)
self.assertEquals(self.ed.EndStyled, lenDocument)
with open(namePrevious, "rb") as f:
prevStyled = f.read()
progStyled = self.AsStyled()
if progStyled != prevStyled:
with open(nameNew, "wb") as f:
f.write(progStyled)
print(progStyled)
print(prevStyled)
self.assertEquals(progStyled, prevStyled)
# The whole file doesn't parse like it did before so don't try line by line
# as that is likely to fail many times.
return
# Try partial lexes from the start of every line which should all be identical.
for line in range(self.ed.LineCount):
lineStart = self.ed.PositionFromLine(line)
self.ed.StartStyling(lineStart, mask)
self.assertEquals(self.ed.EndStyled, lineStart)
self.ed.Colourise(lineStart, lenDocument)
progStyled = self.AsStyled()
if progStyled != prevStyled:
with open(nameNew, "wb") as f:
f.write(progStyled)
self.assertEquals(progStyled, prevStyled)
# Give up after one failure
return
def testCXX(self):
self.LexExample("x.cxx", b"cpp", [b"int"])
def testPython(self):
self.LexExample("x.py", b"python",
[b"class def else for if import in print return while"])
def testHTML(self):
self.LexExample("x.html", b"hypertext", keywordsHTML)
def testASP(self):
self.LexExample("x.asp", b"hypertext", keywordsHTML)
def testPHP(self):
self.LexExample("x.php", b"hypertext", keywordsHTML)
def testVB(self):
self.LexExample("x.vb", b"vb", [b"as dim or string"])
def testD(self):
self.LexExample("x.d", b"d",
[b"keyword1", b"keyword2", b"", b"keyword4", b"keyword5",
b"keyword6", b"keyword7"])
if __name__ == '__main__':
XiteWin.main("lexTests")
| Python |
# Convert all punctuation characters except '_', '*', and '.' into spaces.
def depunctuate(s):
'''A docstring'''
"""Docstring 2"""
d = ""
for ch in s:
if ch in 'abcde':
d = d + ch
else:
d = d + " "
return d
| Python |
# -*- coding: utf-8 -*-
import XiteWin
if __name__ == "__main__":
XiteWin.main("")
| Python |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from __future__ import unicode_literals
import os, string, time, unittest
import XiteWin
class TestPerformance(unittest.TestCase):
def setUp(self):
self.xite = XiteWin.xiteFrame
self.ed = self.xite.ed
self.ed.ClearAll()
self.ed.EmptyUndoBuffer()
def testAddLine(self):
data = (string.ascii_letters + string.digits + "\n").encode('utf-8')
start = time.time()
for i in range(1000):
self.ed.AddText(len(data), data)
self.assertEquals(self.ed.LineCount, i + 2)
end = time.time()
duration = end - start
print("%6.3f testAddLine" % duration)
self.xite.DoEvents()
self.assert_(self.ed.Length > 0)
def testAddLineMiddle(self):
data = (string.ascii_letters + string.digits + "\n").encode('utf-8')
start = time.time()
for i in range(1000):
self.ed.AddText(len(data), data)
self.assertEquals(self.ed.LineCount, i + 2)
end = time.time()
duration = end - start
print("%6.3f testAddLineMiddle" % duration)
self.xite.DoEvents()
self.assert_(self.ed.Length > 0)
def testHuge(self):
data = (string.ascii_letters + string.digits + "\n").encode('utf-8')
data = data * 100000
start = time.time()
self.ed.AddText(len(data), data)
end = time.time()
duration = end - start
print("%6.3f testHuge" % duration)
self.xite.DoEvents()
self.assert_(self.ed.Length > 0)
def testHugeInserts(self):
data = (string.ascii_letters + string.digits + "\n").encode('utf-8')
data = data * 100000
insert = (string.digits + "\n").encode('utf-8')
self.ed.AddText(len(data), data)
start = time.time()
for i in range(1000):
self.ed.InsertText(0, insert)
end = time.time()
duration = end - start
print("%6.3f testHugeInserts" % duration)
self.xite.DoEvents()
self.assert_(self.ed.Length > 0)
def testHugeReplace(self):
oneLine = (string.ascii_letters + string.digits + "\n").encode('utf-8')
data = oneLine * 100000
insert = (string.digits + "\n").encode('utf-8')
self.ed.AddText(len(data), data)
start = time.time()
for i in range(1000):
self.ed.TargetStart = i * len(insert)
self.ed.TargetEnd = self.ed.TargetStart + len(oneLine)
self.ed.ReplaceTarget(len(insert), insert)
end = time.time()
duration = end - start
print("%6.3f testHugeReplace" % duration)
self.xite.DoEvents()
self.assert_(self.ed.Length > 0)
if __name__ == '__main__':
XiteWin.main("performanceTests")
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide.QtCore import *
from PySide.QtGui import *
import ScintillaConstants as sci
sys.path.append("../..")
from bin import ScintillaEditPy
txtInit = "int main(int argc, char **argv) {\n" \
" // Start up the gnome\n" \
" gnome_init(\"stest\", \"1.0\", argc, argv);\n}\n";
keywords = \
"and and_eq asm auto bitand bitor bool break " \
"case catch char class compl const const_cast continue " \
"default delete do double dynamic_cast else enum explicit export extern false float for " \
"friend goto if inline int long mutable namespace new not not_eq " \
"operator or or_eq private protected public " \
"register reinterpret_cast return short signed sizeof static static_cast struct switch " \
"template this throw true try typedef typeid typename union unsigned using " \
"virtual void volatile wchar_t while xor xor_eq";
def uriDropped():
print "uriDropped"
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.resize(460,300)
# Create widgets
self.edit = ScintillaEditPy.ScintillaEdit(self)
self.edit.uriDropped.connect(uriDropped)
self.edit.command.connect(self.receive_command)
self.edit.notify.connect(self.receive_notification)
self.edit.styleClearAll()
self.edit.setMarginWidthN(0, 35)
self.edit.setScrollWidth(200)
self.edit.setScrollWidthTracking(1)
self.edit.setLexer(sci.SCLEX_CPP)
self.edit.styleSetFore(sci.SCE_C_COMMENT, 0x008000)
self.edit.styleSetFore(sci.SCE_C_COMMENTLINE, 0x008000)
self.edit.styleSetFore(sci.SCE_C_COMMENTDOC, 0x008040)
self.edit.styleSetItalic(sci.SCE_C_COMMENTDOC, 1)
self.edit.styleSetFore(sci.SCE_C_NUMBER, 0x808000)
self.edit.styleSetFore(sci.SCE_C_WORD, 0x800000)
self.edit.styleSetBold(sci.SCE_C_WORD, True)
self.edit.styleSetFore(sci.SCE_C_STRING, 0x800080)
self.edit.styleSetFore(sci.SCE_C_PREPROCESSOR, 0x008080)
self.edit.styleSetBold(sci.SCE_C_OPERATOR, True)
self.edit.setMultipleSelection(1)
self.edit.setVirtualSpaceOptions(
sci.SCVS_RECTANGULARSELECTION | sci.SCVS_USERACCESSIBLE)
self.edit.setAdditionalSelectionTyping(1)
self.edit.styleSetFore(sci.STYLE_INDENTGUIDE, 0x808080)
self.edit.setIndentationGuides(sci.SC_IV_LOOKBOTH)
self.edit.setKeyWords(0, keywords)
self.edit.addText(len(txtInit), txtInit)
self.edit.setSel(1,10)
retriever = str(self.edit.getLine(1))
print(type(retriever), len(retriever))
print('[' + retriever + ']')
someText = str(self.edit.textRange(2,5))
print(len(someText), '[' + someText + ']')
someText = self.edit.getCurLine(100)
print(len(someText), '[' + someText + ']')
someText = self.edit.styleGetFont(1)
print(len(someText), '[' + someText + ']')
someText = self.edit.getSelText()
print(len(someText), '[' + someText + ']')
someText = self.edit.getTag(1)
print(len(someText), '[' + someText + ']')
someText = self.edit.autoCGetCurrentText()
print(len(someText), '[' + someText + ']')
someText = self.edit.annotationText(1)
print(len(someText), '[' + someText + ']')
someText = self.edit.annotationStyles(1)
print(len(someText), '[' + someText + ']')
someText = self.edit.describeKeyWordSets()
print(len(someText), '[' + someText + ']')
someText = self.edit.propertyNames()
print(len(someText), '[' + someText + ']')
self.edit.setProperty("fold", "1")
someText = self.edit.getProperty("fold")
print(len(someText), '[' + someText + ']')
someText = self.edit.getPropertyExpanded("fold")
print(len(someText), '[' + someText + ']')
someText = self.edit.lexerLanguage()
print(len(someText), '[' + someText + ']')
someText = self.edit.describeProperty("styling.within.preprocessor")
print(len(someText), '[' + someText + ']')
xx = self.edit.findText(0, "main", 0, 25)
print(type(xx), xx)
print("isBold", self.edit.styleBold(sci.SCE_C_WORD))
# Retrieve the document and write into it
doc = self.edit.get_doc()
doc.insert_string(40, "***")
stars = doc.get_char_range(40,3)
assert stars == "***"
# Create a new independent document and attach it to the editor
doc = ScintillaEditPy.ScintillaDocument()
doc.insert_string(0, "/***/\nif(a)\n")
self.edit.set_doc(doc)
self.edit.setLexer(sci.SCLEX_CPP)
def Call(self, message, wParam=0, lParam=0):
return self.edit.send(message, wParam, lParam)
def resizeEvent(self, e):
self.edit.resize(e.size().width(), e.size().height())
def receive_command(self, wParam, lParam):
# Show underline at start when focussed
notifyCode = wParam >> 16
if (notifyCode == sci.SCEN_SETFOCUS) or (notifyCode == sci.SCEN_KILLFOCUS):
self.edit.setIndicatorCurrent(sci.INDIC_CONTAINER);
self.edit.indicatorClearRange(0, self.edit.length())
if notifyCode == sci.SCEN_SETFOCUS:
self.edit.indicatorFillRange(0, 2);
def receive_notification(self, scn):
if scn.nmhdr.code == sci.SCN_CHARADDED:
print "Char %02X" % scn.ch
elif scn.nmhdr.code == sci.SCN_SAVEPOINTREACHED:
print "Saved"
elif scn.nmhdr.code == sci.SCN_SAVEPOINTLEFT:
print "Unsaved"
elif scn.nmhdr.code == sci.SCN_MODIFIED:
print "Modified"
elif scn.nmhdr.code == sci.SCN_UPDATEUI:
print "Update UI"
elif scn.nmhdr.code == sci.SCN_PAINTED:
#print "Painted"
pass
else:
print "Notification", scn.nmhdr.code
pass
if __name__ == '__main__':
# Create the Qt Application
app = QApplication(sys.argv)
# Create and show the form
form = Form()
form.show()
# Run the main Qt loop
sys.exit(app.exec_())
| Python |
import distutils.sysconfig
import getopt
import glob
import os
import platform
import shutil
import subprocess
import stat
import sys
sys.path.append(os.path.join("..", "ScintillaEdit"))
import WidgetGen
# Decide up front which platform, treat anything other than Windows or OS X as Linux
PLAT_WINDOWS = platform.system() == "Windows"
PLAT_DARWIN = platform.system() == "Darwin"
PLAT_LINUX = not (PLAT_DARWIN or PLAT_WINDOWS)
def IsFileNewer(name1, name2):
""" Returns whether file with name1 is newer than file with name2. Returns 1
if name2 doesn't exist. """
if not os.path.exists(name1):
return 0
if not os.path.exists(name2):
return 1
mod_time1 = os.stat(name1)[stat.ST_MTIME]
mod_time2 = os.stat(name2)[stat.ST_MTIME]
return (mod_time1 > mod_time2)
def textFromRun(args):
(stdoutdata, stderrdata) = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE).communicate()
return stdoutdata
def runProgram(args, exitOnFailure):
print(" ".join(args))
retcode = subprocess.call(" ".join(args), shell=True, stderr=subprocess.STDOUT)
if retcode:
print("Failed in " + " ".join(args) + " return code = " + str(retcode))
if exitOnFailure:
sys.exit()
def usage():
print("sepbuild.py [-h|--help][-c|--clean][-u|--underscore-names]")
print("")
print("Generate PySide wappers and build them.")
print("")
print("options:")
print("")
print("-c --clean remove all object and generated files")
print("-b --pyside-base Location of the PySide+Qt4 sandbox to use")
print("-h --help display this text")
print("-d --debug=yes|no force debug build (or non-debug build)")
print("-u --underscore-names use method_names consistent with GTK+ standards")
modifyFunctionElement = """ <modify-function signature="%s">%s
</modify-function>
"""
injectCode = """
<inject-code class="target" position="beginning">%s
</inject-code>"""
injectCheckN = """
if (!cppArg%d) {
PyErr_SetString(PyExc_ValueError, "Null string argument");
return 0;
}"""
def methodSignature(name, v, options):
argTypes = ""
p1Type = WidgetGen.cppAlias(v["Param1Type"])
if p1Type:
argTypes = argTypes + p1Type
p2Type = WidgetGen.cppAlias(v["Param2Type"])
if p2Type and v["Param2Type"] != "stringresult":
if p1Type:
argTypes = argTypes + ", "
argTypes = argTypes + p2Type
methodName = WidgetGen.normalisedName(name, options, v["FeatureType"])
constDeclarator = " const" if v["FeatureType"] == "get" else ""
return methodName + "(" + argTypes + ")" + constDeclarator
def printTypeSystemFile(f,out, options):
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
feat = v["FeatureType"]
if feat in ["fun", "get", "set"]:
checks = ""
if v["Param1Type"] == "string":
checks = checks + (injectCheckN % 0)
if v["Param2Type"] == "string":
if v["Param1Type"] == "": # Only arg 2 -> treat as first
checks = checks + (injectCheckN % 0)
else:
checks = checks + (injectCheckN % 1)
if checks:
inject = injectCode % checks
out.write(modifyFunctionElement % (methodSignature(name, v, options), inject))
#if v["Param1Type"] == "string":
# out.write("<string-xml>" + name + "</string-xml>\n")
def doubleBackSlashes(s):
# Quote backslashes so qmake does not produce warnings
return s.replace("\\", "\\\\")
class SepBuilder:
def __init__(self):
# Discover configuration parameters
self.ScintillaEditIncludes = [".", "../ScintillaEdit", "../ScintillaEditBase", "../../include"]
if PLAT_WINDOWS:
self.MakeCommand = "nmake"
self.MakeTarget = "release"
else:
self.MakeCommand = "make"
self.MakeTarget = ""
if PLAT_DARWIN:
self.QMakeOptions = "-spec macx-g++"
else:
self.QMakeOptions = ""
# Default to debug build if running in a debug build interpreter
self.DebugBuild = hasattr(sys, 'getobjects')
# Python
self.PyVersion = "%d.%d" % sys.version_info[:2]
self.PyVersionSuffix = distutils.sysconfig.get_config_var("VERSION")
self.PyIncludes = distutils.sysconfig.get_python_inc()
self.PyPrefix = distutils.sysconfig.get_config_var("prefix")
self.PyLibDir = distutils.sysconfig.get_config_var(
("LIBDEST" if sys.platform == 'win32' else "LIBDIR"))
# Scintilla
with open("../../version.txt") as f:
version = f.read()
self.ScintillaVersion = version[0] + '.' + version[1] + '.' + version[2]
# Find out what qmake is called
self.QMakeCommand = "qmake"
if not PLAT_WINDOWS:
# On Unix qmake may not be present but qmake-qt4 may be so check
pathToQMake = textFromRun("which qmake-qt4 || which qmake").rstrip()
self.QMakeCommand = os.path.basename(pathToQMake)
# Qt default location from qmake
self._SetQtIncludeBase(textFromRun(self.QMakeCommand + " -query QT_INSTALL_HEADERS").rstrip())
# PySide default location
# No standard for installing PySide development headers and libs on Windows so
# choose /usr to be like Linux
self._setPySideBase('\\usr' if PLAT_WINDOWS else '/usr')
self.ProInclude = "sepbuild.pri"
self.qtStyleInterface = True
def _setPySideBase(self, base):
self.PySideBase = base
if PLAT_LINUX:
self.PySideTypeSystem = textFromRun("pkg-config --variable=typesystemdir pyside").rstrip()
self.PySideIncludeBase = textFromRun("pkg-config --variable=includedir pyside").rstrip()
self.ShibokenIncludeBase = textFromRun("pkg-config --variable=includedir shiboken").rstrip()
else:
self.PySideTypeSystem = os.path.join(self.PySideBase, "share", "PySide", "typesystems")
self.ShibokenIncludeBase = os.path.join(self.PySideBase, "include", "shiboken")
self.PySideIncludeBase = os.path.join(self.PySideBase, "include", "PySide")
self.PySideIncludes = [
self.ShibokenIncludeBase,
self.PySideIncludeBase,
os.path.join(self.PySideIncludeBase, "QtCore"),
os.path.join(self.PySideIncludeBase, "QtGui")]
self.PySideLibDir = os.path.join(self.PySideBase, "lib")
self.AllIncludes = os.pathsep.join(self.QtIncludes + self.ScintillaEditIncludes + self.PySideIncludes)
self.ShibokenGenerator = "shiboken"
# Is this still needed? It doesn't work with latest shiboken sources
#if PLAT_DARWIN:
# # On OS X, can not automatically find Shiboken dylib so provide a full path
# self.ShibokenGenerator = os.path.join(self.PySideLibDir, "generatorrunner", "shiboken")
def generateAPI(self, args):
os.chdir(os.path.join("..", "ScintillaEdit"))
if not self.qtStyleInterface:
args.insert(0, '--underscore-names')
WidgetGen.main(args)
f = WidgetGen.readInterface(False)
os.chdir(os.path.join("..", "ScintillaEditPy"))
options = {"qtStyle": self.qtStyleInterface}
WidgetGen.Generate("typesystem_ScintillaEdit.xml.template", "typesystem_ScintillaEdit.xml", printTypeSystemFile, f, options)
def runGenerator(self):
generatorrunner = "shiboken"
for name in ('shiboken', 'generatorrunner'):
if PLAT_WINDOWS:
name += '.exe'
name = os.path.join(self.PySideBase, "bin", name)
if os.path.exists(name):
generatorrunner = name
break
args = [
generatorrunner,
"--generator-set=" + self.ShibokenGenerator,
"global.h ",
"--avoid-protected-hack",
"--enable-pyside-extensions",
"--include-paths=" + self.AllIncludes,
"--typesystem-paths=" + self.PySideTypeSystem,
"--output-directory=.",
"typesystem_ScintillaEdit.xml"]
print(" ".join(args))
retcode = subprocess.call(" ".join(args), shell=True, stderr=subprocess.STDOUT)
if retcode:
print("Failed in generatorrunner", retcode)
sys.exit()
def writeVariables(self):
# Write variables needed into file to be included from project so it does not have to discover much
with open(self.ProInclude, "w") as f:
f.write("SCINTILLA_VERSION=" + self.ScintillaVersion + "\n")
f.write("PY_VERSION=" + self.PyVersion + "\n")
f.write("PY_VERSION_SUFFIX=" + self.PyVersionSuffix + "\n")
f.write("PY_PREFIX=" + doubleBackSlashes(self.PyPrefix) + "\n")
f.write("PY_INCLUDES=" + doubleBackSlashes(self.PyIncludes) + "\n")
f.write("PY_LIBDIR=" + doubleBackSlashes(self.PyLibDir) + "\n")
f.write("PYSIDE_INCLUDES=" + doubleBackSlashes(self.PySideIncludeBase) + "\n")
f.write("PYSIDE_LIB=" + doubleBackSlashes(self.PySideLibDir) + "\n")
f.write("SHIBOKEN_INCLUDES=" + doubleBackSlashes(self.ShibokenIncludeBase) + "\n")
if self.DebugBuild:
f.write("CONFIG += debug\n")
else:
f.write("CONFIG += release\n")
def make(self):
runProgram([self.QMakeCommand, self.QMakeOptions], exitOnFailure=True)
runProgram([self.MakeCommand, self.MakeTarget], exitOnFailure=True)
def cleanEverything(self):
self.generateAPI(["--clean"])
runProgram([self.MakeCommand, "distclean"], exitOnFailure=False)
filesToRemove = [self.ProInclude, "typesystem_ScintillaEdit.xml",
"../../bin/ScintillaEditPy.so", "../../bin/ScintillaConstants.py"]
for file in filesToRemove:
try:
os.remove(file)
except OSError:
pass
for logFile in glob.glob("*.log"):
try:
os.remove(logFile)
except OSError:
pass
shutil.rmtree("debug", ignore_errors=True)
shutil.rmtree("release", ignore_errors=True)
shutil.rmtree("ScintillaEditPy", ignore_errors=True)
def buildEverything(self):
cleanGenerated = False
opts, args = getopt.getopt(sys.argv[1:], "hcdub",
["help", "clean", "debug=",
"underscore-names", "pyside-base="])
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-c", "--clean"):
cleanGenerated = True
elif opt in ("-d", "--debug"):
self.DebugBuild = (arg == '' or arg.lower() == 'yes')
if self.DebugBuild and sys.platform == 'win32':
self.MakeTarget = 'debug'
elif opt in ("-b", '--pyside-base'):
self._SetQtIncludeBase(os.path.join(os.path.normpath(arg), 'include'))
self._setPySideBase(os.path.normpath(arg))
elif opt in ("-u", "--underscore-names"):
self.qtStyleInterface = False
if cleanGenerated:
self.cleanEverything()
else:
self.writeVariables()
self.generateAPI([""])
self.runGenerator()
self.make()
self.copyScintillaConstants()
def copyScintillaConstants(self):
orig = 'ScintillaConstants.py'
dest = '../../bin/' + orig
if IsFileNewer(dest, orig):
return
f = open(orig, 'r')
contents = f.read()
f.close()
f = open(dest, 'w')
f.write(contents)
f.close()
def _SetQtIncludeBase(self, base):
self.QtIncludeBase = base
self.QtIncludes = [self.QtIncludeBase] + [os.path.join(self.QtIncludeBase, sub) for sub in ["QtCore", "QtGui"]]
# Set path so correct qmake is found
path = os.environ.get('PATH', '').split(os.pathsep)
qt_bin_dir = os.path.join(os.path.dirname(base), 'bin')
if qt_bin_dir not in path:
path.insert(0, qt_bin_dir)
os.environ['PATH'] = os.pathsep.join(path)
if __name__ == "__main__":
sepBuild = SepBuilder()
sepBuild.buildEverything()
| Python |
#!/usr/bin/env python
# WidgetGen.py - regenerate the ScintillaWidgetCpp.cpp and ScintillaWidgetCpp.h files
# Check that API includes all gtkscintilla2 functions
import sys
import os
import getopt
scintillaDirectory = "../.."
scintillaIncludeDirectory = os.path.join(scintillaDirectory, "include")
sys.path.append(scintillaIncludeDirectory)
import Face
def Contains(s,sub):
return s.find(sub) != -1
def underscoreName(s):
# Name conversion fixes to match gtkscintilla2
irregular = ['WS', 'EOL', 'AutoC', 'KeyWords', 'BackSpace', 'UnIndents', 'RE', 'RGBA']
for word in irregular:
replacement = word[0] + word[1:].lower()
s = s.replace(word, replacement)
out = ""
for c in s:
if c.isupper():
if out:
out += "_"
out += c.lower()
else:
out += c
return out
def normalisedName(s, options, role=None):
if options["qtStyle"]:
if role == "get":
s = s.replace("Get", "")
return s[0].lower() + s[1:]
else:
return underscoreName(s)
typeAliases = {
"position": "int",
"colour": "int",
"keymod": "int",
"string": "const char *",
"stringresult": "const char *",
"cells": "const char *",
}
def cppAlias(s):
if s in typeAliases:
return typeAliases[s]
else:
return s
understoodTypes = ["", "void", "int", "bool", "position",
"colour", "keymod", "string", "stringresult", "cells"]
def checkTypes(name, v):
understandAllTypes = True
if v["ReturnType"] not in understoodTypes:
#~ print("Do not understand", v["ReturnType"], "for", name)
understandAllTypes = False
if v["Param1Type"] not in understoodTypes:
#~ print("Do not understand", v["Param1Type"], "for", name)
understandAllTypes = False
if v["Param2Type"] not in understoodTypes:
#~ print("Do not understand", v["Param2Type"], "for", name)
understandAllTypes = False
return understandAllTypes
def arguments(v, stringResult, options):
ret = ""
p1Type = cppAlias(v["Param1Type"])
if p1Type:
ret = ret + p1Type + " " + normalisedName(v["Param1Name"], options)
p2Type = cppAlias(v["Param2Type"])
if p2Type and not stringResult:
if p1Type:
ret = ret + ", "
ret = ret + p2Type + " " + normalisedName(v["Param2Name"], options)
return ret
def printPyFile(f,out, options):
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
feat = v["FeatureType"]
if feat in ["val"]:
out.write(name + "=" + v["Value"] + "\n")
if feat in ["evt"]:
out.write("SCN_" + name.upper() + "=" + v["Value"] + "\n")
def printHFile(f,out, options):
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
feat = v["FeatureType"]
if feat in ["fun", "get", "set"]:
if checkTypes(name, v):
constDeclarator = " const" if feat == "get" else ""
returnType = cppAlias(v["ReturnType"])
stringResult = v["Param2Type"] == "stringresult"
if stringResult:
returnType = "QByteArray"
out.write("\t" + returnType + " " + normalisedName(name, options, feat) + "(")
out.write(arguments(v, stringResult, options))
out.write(")" + constDeclarator + ";\n")
def methodNames(f, options):
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
feat = v["FeatureType"]
if feat in ["fun", "get", "set"]:
if checkTypes(name, v):
yield normalisedName(name, options)
def printCPPFile(f,out, options):
for name in f.order:
v = f.features[name]
if v["Category"] != "Deprecated":
feat = v["FeatureType"]
if feat in ["fun", "get", "set"]:
if checkTypes(name, v):
constDeclarator = " const" if feat == "get" else ""
featureDefineName = "SCI_" + name.upper()
returnType = cppAlias(v["ReturnType"])
stringResult = v["Param2Type"] == "stringresult"
if stringResult:
returnType = "QByteArray"
returnStatement = ""
if returnType != "void":
returnStatement = "return "
out.write(returnType + " ScintillaEdit::" + normalisedName(name, options, feat) + "(")
out.write(arguments(v, stringResult, options))
out.write(")" + constDeclarator + " {\n")
if stringResult:
out.write(" " + returnStatement + "TextReturner(" + featureDefineName + ", ")
if "*" in cppAlias(v["Param1Type"]):
out.write("(uptr_t)")
if v["Param1Name"]:
out.write(normalisedName(v["Param1Name"], options))
else:
out.write("0")
out.write(");\n")
else:
out.write(" " + returnStatement + "send(" + featureDefineName + ", ")
if "*" in cppAlias(v["Param1Type"]):
out.write("(uptr_t)")
if v["Param1Name"]:
out.write(normalisedName(v["Param1Name"], options))
else:
out.write("0")
out.write(", ")
if "*" in cppAlias(v["Param2Type"]):
out.write("(sptr_t)")
if v["Param2Name"]:
out.write(normalisedName(v["Param2Name"], options))
else:
out.write("0")
out.write(");\n")
out.write("}\n")
out.write("\n")
def CopyWithInsertion(input, output, genfn, definition, options):
copying = 1
for line in input.readlines():
if copying:
output.write(line)
if "/* ++Autogenerated" in line or "# ++Autogenerated" in line or "<!-- ++Autogenerated" in line:
copying = 0
genfn(definition, output, options)
# ~~ form needed as XML comments can not contain --
if "/* --Autogenerated" in line or "# --Autogenerated" in line or "<!-- ~~Autogenerated" in line:
copying = 1
output.write(line)
def contents(filename):
with open(filename, "U") as f:
t = f.read()
return t
def Generate(templateFile, destinationFile, genfn, definition, options):
inText = contents(templateFile)
try:
currentText = contents(destinationFile)
except IOError:
currentText = ""
tempname = "WidgetGen.tmp"
with open(tempname, "w") as out:
with open(templateFile, "U") as hfile:
CopyWithInsertion(hfile, out, genfn, definition, options)
outText = contents(tempname)
if currentText == outText:
os.unlink(tempname)
else:
try:
os.unlink(destinationFile)
except OSError:
# Will see failure if file does not yet exist
pass
os.rename(tempname, destinationFile)
def gtkNames():
# The full path on my machine: should be altered for anyone else
p = "C:/Users/Neil/Downloads/wingide-source-4.0.1-1/wingide-source-4.0.1-1/external/gtkscintilla2/gtkscintilla.c"
with open(p) as f:
for l in f.readlines():
if "gtk_scintilla_" in l:
name = l.split()[1][14:]
if '(' in name:
name = name.split('(')[0]
yield name
def usage():
print("WidgetGen.py [-c|--clean][-h|--help][-u|--underscore-names]")
print("")
print("Generate full APIs for ScintillaEdit class and ScintillaConstants.py.")
print("")
print("options:")
print("")
print("-c --clean remove all generated code from files")
print("-h --help display this text")
print("-u --underscore-names use method_names consistent with GTK+ standards")
def readInterface(cleanGenerated):
f = Face.Face()
if not cleanGenerated:
f.ReadFromFile("../../include/Scintilla.iface")
return f
def main(argv):
# Using local path for gtkscintilla2 so don't default to checking
checkGTK = False
cleanGenerated = False
qtStyleInterface = True
# The --gtk-check option checks for full coverage of the gtkscintilla2 API but
# depends on a particular directory so is not mentioned in --help.
opts, args = getopt.getopt(argv, "hcgu", ["help", "clean", "gtk-check", "underscore-names"])
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-c", "--clean"):
cleanGenerated = True
elif opt in ("-g", "--gtk-check"):
checkGTK = True
elif opt in ("-u", "--underscore-names"):
qtStyleInterface = False
options = {"qtStyle": qtStyleInterface}
f = readInterface(cleanGenerated)
try:
Generate("ScintillaEdit.cpp.template", "ScintillaEdit.cpp", printCPPFile, f, options)
Generate("ScintillaEdit.h.template", "ScintillaEdit.h", printHFile, f, options)
Generate("../ScintillaEditPy/ScintillaConstants.py.template",
"../ScintillaEditPy/ScintillaConstants.py",
printPyFile, f, options)
if checkGTK:
names = set(methodNames(f))
#~ print("\n".join(names))
namesGtk = set(gtkNames())
for name in namesGtk:
if name not in names:
print(name, "not found in Qt version")
for name in names:
if name not in namesGtk:
print(name, "not found in GTK+ version")
except:
raise
if cleanGenerated:
for file in ["ScintillaEdit.cpp", "ScintillaEdit.h", "../ScintillaEditPy/ScintillaConstants.py"]:
try:
os.remove(file)
except OSError:
pass
if __name__ == "__main__":
main(sys.argv[1:])
| Python |
#!/usr/bin/env python
# LexGen.py - implemented 2002 by Neil Hodgson neilh@scintilla.org
# Released to the public domain.
# Regenerate the Scintilla and SciTE source files that list
# all the lexers and all the properties files.
# Should be run whenever a new lexer is added or removed.
# Requires Python 2.4 or later
# Most files are regenerated in place with templates stored in comments.
# The VS .NET project file is generated into a different file as the
# VS .NET environment will not retain comments when modifying the file.
# The files are copied to a string apart from sections between a
# ++Autogenerated comment and a --Autogenerated comment which is
# generated by the CopyWithInsertion function. After the whole
# string is instantiated, it is compared with the target file and
# if different the file is rewritten.
# Does not regenerate the Visual C++ 6 project files but does the VS .NET
# project file.
import string
import sys
import os
import glob
# EOL constants
CR = "\r"
LF = "\n"
CRLF = "\r\n"
if sys.platform == "win32":
NATIVE = CRLF
else:
# Yes, LF is the native EOL even on Mac OS X. CR is just for
# Mac OS <=9 (a.k.a. "Mac Classic")
NATIVE = LF
# Automatically generated sections contain start and end comments,
# a definition line and the results.
# The results are replaced by regenerating based on the definition line.
# The definition line is a comment prefix followed by "**".
# If there is a digit after the ** then this indicates which list to use
# and the digit and next character are not part of the definition
# Backslash is used as an escape within the definition line.
# The part between \( and \) is repeated for each item in the list.
# \* is replaced by each list item. \t, and \n are tab and newline.
def CopyWithInsertion(input, commentPrefix, retainDefs, eolType, *lists):
copying = 1
listid = 0
output = []
for line in input.splitlines(0):
isStartGenerated = line.startswith(commentPrefix + "++Autogenerated")
if copying and not isStartGenerated:
output.append(line)
if isStartGenerated:
if retainDefs:
output.append(line)
copying = 0
definition = ""
elif not copying and line.startswith(commentPrefix + "**"):
if retainDefs:
output.append(line)
definition = line[len(commentPrefix + "**"):]
if (commentPrefix == "<!--") and (" -->" in definition):
definition = definition.replace(" -->", "")
listid = 0
if definition[0] in string.digits:
listid = int(definition[:1])
definition = definition[2:]
# Hide double slashes as a control character
definition = definition.replace("\\\\", "\001")
# Do some normal C style transforms
definition = definition.replace("\\n", "\n")
definition = definition.replace("\\t", "\t")
# Get the doubled backslashes back as single backslashes
definition = definition.replace("\001", "\\")
startRepeat = definition.find("\\(")
endRepeat = definition.find("\\)")
intro = definition[:startRepeat]
out = ""
if intro.endswith("\n"):
pos = 0
else:
pos = len(intro)
out += intro
middle = definition[startRepeat+2:endRepeat]
for i in lists[listid]:
item = middle.replace("\\*", i)
if pos and (pos + len(item) >= 80):
out += "\\\n"
pos = 0
out += item
pos += len(item)
if item.endswith("\n"):
pos = 0
outro = definition[endRepeat+2:]
out += outro
out = out.replace("\n", eolType) # correct EOLs in generated content
output.append(out)
elif line.startswith(commentPrefix + "--Autogenerated"):
copying = 1
if retainDefs:
output.append(line)
output = [line.rstrip(" \t") for line in output] # trim trailing whitespace
return eolType.join(output) + eolType
def UpdateFile(filename, updated):
""" If the file is different to updated then copy updated
into the file else leave alone so CVS and make don't treat
it as modified. """
try:
infile = open(filename, "rb")
except IOError: # File is not there yet
out = open(filename, "wb")
out.write(updated.encode('utf-8'))
out.close()
print("New %s" % filename)
return
original = infile.read()
infile.close()
original = original.decode('utf-8')
if updated != original:
os.unlink(filename)
out = open(filename, "wb")
out.write(updated.encode('utf-8'))
out.close()
print("Changed %s " % filename)
#~ else:
#~ print "Unchanged", filename
def Generate(inpath, outpath, commentPrefix, eolType, *lists):
"""Generate 'outpath' from 'inpath'.
"eolType" indicates the type of EOLs to use in the generated
file. It should be one of following constants: LF, CRLF,
CR, or NATIVE.
"""
#print "generate '%s' -> '%s' (comment prefix: %r, eols: %r)"\
# % (inpath, outpath, commentPrefix, eolType)
try:
infile = open(inpath, "rb")
except IOError:
print("Can not open %s" % inpath)
return
original = infile.read()
infile.close()
original = original.decode('utf-8')
updated = CopyWithInsertion(original, commentPrefix,
inpath == outpath, eolType, *lists)
UpdateFile(outpath, updated)
def Regenerate(filename, commentPrefix, eolType, *lists):
"""Regenerate the given file.
"eolType" indicates the type of EOLs to use in the generated
file. It should be one of following constants: LF, CRLF,
CR, or NATIVE.
"""
Generate(filename, filename, commentPrefix, eolType, *lists)
def FindModules(lexFile):
modules = []
f = open(lexFile)
for l in f.readlines():
if l.startswith("LexerModule"):
l = l.replace("(", " ")
modules.append(l.split()[1])
return modules
# Properties that start with lexer. or fold. are automatically found but there are some
# older properties that don't follow this pattern so must be explicitly listed.
knownIrregularProperties = [
"fold",
"styling.within.preprocessor",
"tab.timmy.whinge.level",
"asp.default.language",
"html.tags.case.sensitive",
"ps.level",
"ps.tokenize",
"sql.backslash.escapes",
"nsis.uservars",
"nsis.ignorecase"
]
def FindProperties(lexFile):
properties = {}
f = open(lexFile)
for l in f.readlines():
if ("GetProperty" in l or "DefineProperty" in l) and "\"" in l:
l = l.strip()
if not l.startswith("//"): # Drop comments
propertyName = l.split("\"")[1]
if propertyName.lower() == propertyName:
# Only allow lower case property names
if propertyName in knownIrregularProperties or \
propertyName.startswith("fold.") or \
propertyName.startswith("lexer."):
properties[propertyName] = 1
return properties
def FindPropertyDocumentation(lexFile):
documents = {}
f = open(lexFile)
name = ""
for l in f.readlines():
l = l.strip()
if "// property " in l:
propertyName = l.split()[2]
if propertyName.lower() == propertyName:
# Only allow lower case property names
name = propertyName
documents[name] = ""
elif "DefineProperty" in l and "\"" in l:
propertyName = l.split("\"")[1]
if propertyName.lower() == propertyName:
# Only allow lower case property names
name = propertyName
documents[name] = ""
elif name:
if l.startswith("//"):
if documents[name]:
documents[name] += " "
documents[name] += l[2:].strip()
elif l.startswith("\""):
l = l[1:].strip()
if l.endswith(";"):
l = l[:-1].strip()
if l.endswith(")"):
l = l[:-1].strip()
if l.endswith("\""):
l = l[:-1]
# Fix escaped double quotes
l = l.replace("\\\"", "\"")
documents[name] += l
else:
name = ""
for name in list(documents.keys()):
if documents[name] == "":
del documents[name]
return documents
def ciCompare(a,b):
return cmp(a.lower(), b.lower())
def ciKey(a):
return a.lower()
def sortListInsensitive(l):
try: # Try key function
l.sort(key=ciKey)
except TypeError: # Earlier version of Python, so use comparison function
l.sort(ciCompare)
def UpdateLineInFile(path, linePrefix, lineReplace):
lines = []
with open(path, "r") as f:
for l in f.readlines():
l = l.rstrip()
if l.startswith(linePrefix):
lines.append(lineReplace)
else:
lines.append(l)
contents = NATIVE.join(lines) + NATIVE
UpdateFile(path, contents)
def UpdateVersionNumbers(root):
with open(root + "scintilla/version.txt") as f:
version = f.read()
versionDotted = version[0] + '.' + version[1] + '.' + version[2]
versionCommad = version[0] + ', ' + version[1] + ', ' + version[2] + ', 0'
UpdateLineInFile(root + "scintilla/win32/ScintRes.rc", "#define VERSION_SCINTILLA",
"#define VERSION_SCINTILLA \"" + versionDotted + "\"")
UpdateLineInFile(root + "scintilla/win32/ScintRes.rc", "#define VERSION_WORDS",
"#define VERSION_WORDS " + versionCommad)
UpdateLineInFile(root + "scintilla/qt/ScintillaEditBase/ScintillaEditBase.pro",
"VERSION =",
"VERSION = " + versionDotted)
UpdateLineInFile(root + "scintilla/qt/ScintillaEdit/ScintillaEdit.pro",
"VERSION =",
"VERSION = " + versionDotted)
UpdateLineInFile(root + "scintilla/doc/ScintillaDownload.html", " Release",
" Release " + versionDotted)
UpdateLineInFile(root + "scintilla/doc/index.html",
' <font color="#FFCC99" size="3"> Release version',
' <font color="#FFCC99" size="3"> Release version ' + versionDotted + '<br />')
if os.path.exists(root + "scite"):
UpdateLineInFile(root + "scite/src/SciTE.h", "#define VERSION_SCITE",
"#define VERSION_SCITE \"" + versionDotted + "\"")
UpdateLineInFile(root + "scite/src/SciTE.h", "#define VERSION_WORDS",
"#define VERSION_WORDS " + versionCommad)
UpdateLineInFile(root + "scite/doc/SciTEDownload.html", " Release",
" Release " + versionDotted)
UpdateLineInFile(root + "scite/doc/SciTE.html",
' <font color="#FFCC99" size="3"> Release version',
' <font color="#FFCC99" size="3"> Release version ' + versionDotted + '<br />')
def RegenerateAll():
root="../../"
# Find all the lexer source code files
lexFilePaths = glob.glob(root + "scintilla/lexers/Lex*.cxx")
sortListInsensitive(lexFilePaths)
lexFiles = [os.path.basename(f)[:-4] for f in lexFilePaths]
print(lexFiles)
lexerModules = []
lexerProperties = {}
propertyDocuments = {}
for lexFile in lexFilePaths:
lexerModules.extend(FindModules(lexFile))
for k in FindProperties(lexFile).keys():
lexerProperties[k] = 1
documents = FindPropertyDocumentation(lexFile)
for k in documents.keys():
propertyDocuments[k] = documents[k]
sortListInsensitive(lexerModules)
lexerProperties = list(lexerProperties.keys())
sortListInsensitive(lexerProperties)
# Generate HTML to document each property
# This is done because tags can not be safely put inside comments in HTML
documentProperties = list(propertyDocuments.keys())
sortListInsensitive(documentProperties)
propertiesHTML = []
for k in documentProperties:
propertiesHTML.append("\t<tr id='property-%s'>\n\t<td>%s</td>\n\t<td>%s</td>\n\t</tr>" %
(k, k, propertyDocuments[k]))
# Find all the SciTE properties files
otherProps = ["abbrev.properties", "Embedded.properties", "SciTEGlobal.properties", "SciTE.properties"]
if os.path.exists(root + "scite"):
propFilePaths = glob.glob(root + "scite/src/*.properties")
sortListInsensitive(propFilePaths)
propFiles = [os.path.basename(f) for f in propFilePaths if os.path.basename(f) not in otherProps]
sortListInsensitive(propFiles)
print(propFiles)
Regenerate(root + "scintilla/src/Catalogue.cxx", "//", NATIVE, lexerModules)
Regenerate(root + "scintilla/win32/scintilla.mak", "#", NATIVE, lexFiles)
Regenerate(root + "scintilla/win32/scintilla_vc6.mak", "#", NATIVE, lexFiles)
if os.path.exists(root + "scite"):
Regenerate(root + "scite/win32/makefile", "#", NATIVE, propFiles)
Regenerate(root + "scite/win32/scite.mak", "#", NATIVE, propFiles)
Regenerate(root + "scite/src/SciTEProps.cxx", "//", NATIVE, lexerProperties)
Regenerate(root + "scite/doc/SciTEDoc.html", "<!--", NATIVE, propertiesHTML)
Generate(root + "scite/boundscheck/vcproj.gen",
root + "scite/boundscheck/SciTE.vcproj", "#", NATIVE, lexFiles)
UpdateVersionNumbers(root)
RegenerateAll()
| Python |
# Module for reading and parsing Scintilla.iface file
def sanitiseLine(line):
if line[-1:] == '\n': line = line[:-1]
if line.find("##") != -1:
line = line[:line.find("##")]
line = line.strip()
return line
def decodeFunction(featureVal):
retType, rest = featureVal.split(" ", 1)
nameIdent, params = rest.split("(")
name, value = nameIdent.split("=")
params, rest = params.split(")")
param1, param2 = params.split(",")
return retType, name, value, param1, param2
def decodeEvent(featureVal):
retType, rest = featureVal.split(" ", 1)
nameIdent, params = rest.split("(")
name, value = nameIdent.split("=")
return retType, name, value
def decodeParam(p):
param = p.strip()
type = ""
name = ""
value = ""
if " " in param:
type, nv = param.split(" ")
if "=" in nv:
name, value = nv.split("=")
else:
name = nv
return type, name, value
class Face:
def __init__(self):
self.order = []
self.features = {}
self.values = {}
self.events = {}
def ReadFromFile(self, name):
currentCategory = ""
currentComment = []
currentCommentFinished = 0
file = open(name)
for line in file.readlines():
line = sanitiseLine(line)
if line:
if line[0] == "#":
if line[1] == " ":
if currentCommentFinished:
currentComment = []
currentCommentFinished = 0
currentComment.append(line[2:])
else:
currentCommentFinished = 1
featureType, featureVal = line.split(" ", 1)
if featureType in ["fun", "get", "set"]:
try:
retType, name, value, param1, param2 = decodeFunction(featureVal)
except ValueError:
print("Failed to decode %s" % line)
raise
p1 = decodeParam(param1)
p2 = decodeParam(param2)
self.features[name] = {
"FeatureType": featureType,
"ReturnType": retType,
"Value": value,
"Param1Type": p1[0], "Param1Name": p1[1], "Param1Value": p1[2],
"Param2Type": p2[0], "Param2Name": p2[1], "Param2Value": p2[2],
"Category": currentCategory, "Comment": currentComment
}
if value in self.values:
raise Exception("Duplicate value " + value + " " + name)
self.values[value] = 1
self.order.append(name)
elif featureType == "evt":
retType, name, value = decodeEvent(featureVal)
self.features[name] = {
"FeatureType": featureType,
"ReturnType": retType,
"Value": value,
"Category": currentCategory, "Comment": currentComment
}
if value in self.events:
raise Exception("Duplicate event " + value + " " + name)
self.events[value] = 1
self.order.append(name)
elif featureType == "cat":
currentCategory = featureVal
elif featureType == "val":
try:
name, value = featureVal.split("=", 1)
except ValueError:
print("Failure %s" % featureVal)
raise Exception()
self.features[name] = {
"FeatureType": featureType,
"Category": currentCategory,
"Value": value }
self.order.append(name)
elif featureType == "enu" or featureType == "lex":
name, value = featureVal.split("=", 1)
self.features[name] = {
"FeatureType": featureType,
"Category": currentCategory,
"Value": value }
self.order.append(name)
| Python |
from google.appengine.ext import db
class PredictionData(db.Model):
user_id = db.StringProperty()
match_id = db.StringProperty()
team1_count = db.IntegerProperty()
team2_count = db.IntegerProperty()
draw_count = db.IntegerProperty()
class WorldCupData(db.Model):
user_id = db.StringProperty()
match_id = db.IntegerProperty()
fav_team = db.StringProperty()
class WorldCupStatistics(db.Model):
match_id = db.IntegerProperty()
team1_count = db.IntegerProperty()
team2_count = db.IntegerProperty()
draw_count = db.IntegerProperty()
class Token(db.Model):
token = db.StringProperty()
| Python |
# Standard libs
import base64
import hashlib
import logging
import urllib
import time
import datetime
# App Engine imports
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import users
# Third party imports
import json
import os, random, string
import StringIO
import re
# GData API imports
import gdata
import atom
import gdata.service
import gdata.photos.service
import gdata.spreadsheet.service
# Project specific imports
from models import Token
USERID = 'LOGIN'
PASSWORD = 'PASSWORD'
SPREADSHEET_KEY = 'KEY' # ID of photo contest spreadsheet
WORKSHEET_KEY = 'od6' # Id of default worksheet.
class DataIO(webapp.RequestHandler):
def RenderTemplate(self, filename, dictionary):
"""Render the given template definition file with the given dictionary.
Args:
filename: The filename of the template to expand.
dict: The dictionary that contains the values to populate in the template.
"""
path = os.path.join(os.path.dirname(__file__), filename)
self.response.headers['Content-Type'] = 'text/javascript'
self.response.out.write(template.render(path, dictionary))
def GetMatchesDetail(self, gd_client):
matches = []
q = gdata.spreadsheet.service.DocumentQuery()
q['title'] = 'football fever 2010'
q['title-exact'] = 'true'
feed = gd_client.GetSpreadsheetsFeed(query=q)
rows = gd_client.GetListFeed(SPREADSHEET_KEY, WORKSHEET_KEY).entry
for row in rows:
item = {}
for key in row.custom:
item[key] = row.custom[key].text
matches.append(item)
logging.error(matches)
self.RenderTemplate('templates/matches.js', {'data': json.write(matches)})
def GetMatchDetail(self, gd_client):
match_id = self.request.get('matchId', '')
json_data = {}
self.response.headers['Content-Type'] = 'text/json'
if match_id == '':
self.response.out.write(json.write({'error': 'No match id?'}))
else:
q = gdata.spreadsheet.service.DocumentQuery()
q['title'] = 'football fever 2010'
q['title-exact'] = 'true'
feed = gd_client.GetSpreadsheetsFeed(query=q)
rows = gd_client.GetListFeed(SPREADSHEET_KEY, WORKSHEET_KEY).entry
item = {'error': 'No item found'}
for row in rows:
if row.custom['matchnumber'].text == match_id:
item = {'error': 0}
for key in row.custom:
item[key] = row.custom[key].text
break
logging.info(item)
self.response.out.write(json.write(item))
def GetMatches(self):
token = Token.all().get()
if token is None:
gd_client = self.Login()
self.AddOrUpdateToken(gd_client.GetClientLoginToken())
else:
gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
gd_client.SetClientLoginToken(token.token)
try:
self.GetMatchesDetail(gd_client)
except Exception, err:
# To handle 'Token Expired' error.
logging.error('Error occured: ' + str(err))
gd_client = self.Login()
self.AddOrUpdateToken(gd_client.GetClientLoginToken())
self.GetMatchesDetail(gd_client)
def GetMatch(self):
token = Token.all().get()
if token is None:
gd_client = self.Login()
self.AddOrUpdateToken(gd_client.GetClientLoginToken())
else:
gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
gd_client.SetClientLoginToken(token.token)
try:
self.GetMatchDetail(gd_client)
except Exception, err:
# To handle 'Token Expired' error.
logging.error('Error occured: ' + str(err))
gd_client = self.Login()
self.AddOrUpdateToken(gd_client.GetClientLoginToken())
self.GetMatchDetail(gd_client)
def AddOrUpdateToken(self, login_token):
token = Token.all().get()
if token is None:
token = Token()
token.token = login_token
token.put()
def Login(self):
# Create a client class which will make HTTP requests with Google Spreadsheet server.
gd_client = gdata.spreadsheet.service.SpreadsheetsService(SPREADSHEET_KEY, WORKSHEET_KEY)
# Authenticate using your Google Docs email address and password.
gd_client.email = USERID
gd_client.password = PASSWORD
gd_client.source = 'football-fever'
try:
gd_client.ProgrammaticLogin()
except Exception, err:
# TODO Need to handle 'Captcha Required' exception properly.
logging.error('Error occured' + str(err))
return gd_client
def get(self):
if self.request.path.startswith('/getmatches'):
self.GetMatches()
elif self.request.path.startswith('/getmatch'):
self.GetMatch()
else:
pass
def post(self):
self.get()
| Python |
#!/usr/bin/python2.5
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""To check whether set of robot is done correctly."""
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import prediction
import dataio
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Some thing happened..')
class VerifyHandler(webapp.RequestHandler):
def get(self):
st = self.request.get('st', '')
self.response.out.write('KEY')
def main():
handles = [(r'/_wave/verify_token.*', VerifyHandler),
(r'/getprediction', prediction.Prediction),
(r'/saveprediction', prediction.Prediction),
(r'/getmatches', dataio.DataIO),
(r'/getmatch', dataio.DataIO),
(r'/updatematches', dataio.DataIO),
(r'/.*', MainHandler)]
application = webapp.WSGIApplication(handles, debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python2.5
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Robot that creates issue tracker for an issue."""
import logging
import time
import urlparse
from datetime import datetime
from datetime import timedelta
from waveapi import appengine_robot_runner
from waveapi import element
from waveapi import events
from waveapi import robot
from waveapi import util
from waveapi import blip
CONSUMER_KEY = 'XXX'
CONSUMER_SECRET = 'XXX'
ROBOT_KEY = 'robot.football.request'
ROBOT_ID = u'football-fever@appspot.com'
SANDBOX_DOMAIN = 'wavesandbox.com'
PREVIEW_DOMAIN = 'wave.google.com/wave'
SANDBOX_RPC_BASE = 'http://sandbox.gmodules.com/api/rpc'
PREVIEW_RPC_BASE = 'http://gmodules.com/api/rpc'
WELCOME_TEXT = 'Welcome to your personal match wave, where you can make predictions with your friends or colleagues. To add them to this wave, just click the "+" button above.'
WELCOME_TEXT_PARTY = 'Welcome to your party wave, where you can plan a viewing party to watch the match together with your friends. To add them to this wave, just click the "+" button above.'
#TODO Delete these.
BUG_KEY = 'robot.football.id'
# Final links.
FAV_PLAYER_URL = 'http://football-fever.appspot.com/static/player.xml'
ICON = 'http://football-fever.appspot.com/images/icon.png'
LOADING_GADGET_URL = 'http://football-fever.appspot.com/static/loading.xml'
MAP_GADGET_URL = 'http://google-wave-resources.googlecode.com/svn/trunk/samples/extensions/gadgets/mappy/mappy.xml'
POLL_GADGET_URL = 'http://football-fever.appspot.com/static/polly.xml'
PREDICTION_GADGET_URL = 'http://football-fever.appspot.com/static/prediction.xml'
RSS_GADGET_URL = 'http://football-fever.appspot.com/static/rss.xml'
TWITTER_URL = 'http://football-fever.appspot.com/static/twitter.xml'
YESNO_GADGET_URL = 'http://football-fever.appspot.com/static/yesno.xml'
def GetRPCBase(domain):
logging.info('GetRPCBase -->' + domain)
if domain.find(SANDBOX_DOMAIN) != -1:
return SANDBOX_RPC_BASE
if domain.find(PREVIEW_DOMAIN) != -1:
return PREVIEW_RPC_BASE
else:
return PREVIEW_RPC_BASE
def OnWaveletSelfAdded(event, wavelet):
"""Called when the annotation changes."""
logging.info('WaveletSelfAdded')
pass
def appendAnnotatedText(bl, text, name, value):
"""Append text to a blip with a single bundled annotation."""
bl.append(text+'\n', bundled_annotations=[(name, value)])
def appendTitle(bl, text):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_WEIGHT, 'bold'),
(blip.Annotation.FONT_SIZE, '18px')]
bl.append('\n' + text + '\n', bundled_annotations=bundle)
def appendSectionTitle(bl, text):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_WEIGHT, 'bold'),
(blip.Annotation.FONT_SIZE, '16px')]
bl.append(text + '\n\n', bundled_annotations=bundle)
def appendSubTitle(bl, text):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_WEIGHT, 'bold'),
(blip.Annotation.FONT_SIZE, '14px')]
bl.append(text + '\n', bundled_annotations=bundle)
def appendContent(bl, text):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_WEIGHT, 'bold'),
(blip.Annotation.FONT_SIZE, '12px')]
bl.append(text + '\n', bundled_annotations=bundle)
def appendContentInline(bl, text):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_SIZE, '12px')]
bl.append(text, bundled_annotations=bundle)
def appendLink(bl, text, link):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
('link/manual', link),
(blip.Annotation.FONT_SIZE, '12px')]
bl.append(text + '\n', bundled_annotations=bundle)
def appendWelcomeInfo(bl, statium, event_date, welcome_text):
""" Append the text with title specific font size."""
text = statium + ', at ' + event_date.strftime('%A, %d %B %Y %I:%M%p') + ' (South Africa Standard Time)'
bundle = [
(blip.Annotation.FONT_FAMILY, 'Arial'),
(blip.Annotation.FONT_WEIGHT, 'normal'),
(blip.Annotation.FONT_SIZE, '12px')]
bl.append(text + '\n\n', bundled_annotations=bundle)
bl.append(welcome_text + '\n\n', bundled_annotations=bundle)
def addLineBreak(bl):
""" Append the text with title specific font size."""
bundle = [
(blip.Annotation.FONT_SIZE, '16px')]
bl.append('\n\n', bundled_annotations=bundle)
def LoadingGadgetStateChanged(event, wavelet, loading_gadget):
logging.info(util.serialize(loading_gadget))
team_info = GetTeamInformation(loading_gadget)
logging.info(util.serialize(team_info))
if loading_gadget.status == '1':
root_blip = wavelet.root_blip
props = {
'team1': team_info['team1'],
'match': team_info['match'],
'team2': team_info['team2'],
'action': team_info['action'],
'location': team_info['location'],
'match_date': team_info['match_date'],
'status': 'New'
}
match_date = datetime.fromtimestamp(team_info['match_date'] / 1000)
location = team_info['location']
#RemoveDefaultTitleAndLink(root_blip)
ChangeDefaultTitleStyle(root_blip)
RemoveDefaultLink(root_blip)
# Add Welcome message.
# TODO Need to implement timezone specific logic.
aus_date = match_date + timedelta(hours=2)
# Adding action specific gadget.
if team_info['action'] == 'party':
# Add 'Match party' sub title and gadget.
appendWelcomeInfo(root_blip, location, aus_date, WELCOME_TEXT_PARTY)
appendSectionTitle(root_blip, 'Plan a viewing party!')
appendContent(root_blip, 'When:')
appendContent(root_blip, 'Where:')
logging.error('Adding Map gadget.')
root_blip.append(element.Gadget(MAP_GADGET_URL, props))
addLineBreak(root_blip)
appendContent(root_blip, 'Are you coming?\n')
root_blip.append(element.Gadget(YESNO_GADGET_URL, props))
else:
# Add 'Betting' sub title and gadget.
appendWelcomeInfo(root_blip, location, aus_date, WELCOME_TEXT)
appendSubTitle(root_blip, 'Predict this match!')
logging.error('Adding Betting gadget.')
root_blip.append(element.Gadget(PREDICTION_GADGET_URL, props))
addLineBreak(root_blip)
# Add 'Player of the match' sub title and gadget.
appendSubTitle(root_blip, 'Player of the match!')
logging.error('Adding Favorite player gadget.')
root_blip.append(element.Gadget(FAV_PLAYER_URL, props))
addLineBreak(root_blip)
# Add 'Player of the match' sub title and gadget.
appendSubTitle(root_blip, 'Custom Polls! (thumbs up/down)')
root_blip.append(element.Gadget(POLL_GADGET_URL, props))
addLineBreak(root_blip)
# Add 'RSS gadget' gadget and 'Live Feeds!' section title.
appendSectionTitle(root_blip, 'Live Feeds!')
logging.error('Adding RSS gadget.')
root_blip.append(element.Gadget(RSS_GADGET_URL, props))
# Add 'Twitter' gadget and 'Live Feeds!' section title.
appendSectionTitle(root_blip, '')
logging.error('Adding Twitter.')
root_blip.append(element.Gadget(TWITTER_URL, props))
logging.error('Gadgets added in root blip.')
# Add footer text.
appendContentInline(root_blip, '\nThis wave created by Football Fever. ')
# Add footer link.
appendLink(root_blip, 'Make your own!', 'http://wave.google.com/footballfever.html')
# TODO thangaraju@google.com The loading gadget could be deleted.
logging.error('The loading gadget could be deleted now.')
loading_gadget.delete()
pass
def ChangeDefaultTitleStyle(blip_ins):
for ann in blip_ins.annotations:
if ann.name == 'conv/title':
blip_ref = blip_ins.range(ann.start, ann.end)
blip_ref.annotate(blip.Annotation.FONT_FAMILY, 'Arial')
blip_ref.annotate(blip.Annotation.FONT_WEIGHT, 'bold')
blip_ref.annotate(blip.Annotation.FONT_SIZE, '18px')
def RemoveDefaultLink(blip_ins):
for ann in blip_ins.annotations:
logging.info(ann)
if ann.name == 'link/manual':
try:
blip_ref = blip_ins.range(ann.start, ann.end)
blip_ref.delete()
logging.info('blip_ref deleted')
except:
logging.error('blip_ref')
logging.error(blip_ref)
pass
def RemoveDefaultTitleAndLink(blip_ins):
to_be_removed = []
for ann in blip_ins.annotations:
if ann.name == 'link/manual' or ann.name == 'conv/title':
#if ann.name == 'conv/title':
to_be_removed.append(blip_ins.range(ann.start, ann.end))
logging.error(to_be_removed)
to_be_removed.reverse()
logging.error(to_be_removed)
for item in to_be_removed:
try:
logging.error(item)
logging.error(item.get('name', ''))
logging.error(item.get('value', ''))
item.delete()
except:
pass
def OnGadgetStateChanged(event, wavelet):
logging.info('OnGadgetStateChanged event:')
logging.info(util.serialize(event))
logging.info('wavelet')
logging.info(util.serialize(wavelet))
loading_gadget = GetLoadingGadget(event, wavelet)
if IsGadget(loading_gadget):
""" Loads at first time only. """
LoadingGadgetStateChanged(event, wavelet, loading_gadget)
def IsGadget(gadget):
try:
if gadget.status == '1':
logging.error('Success')
return True
else:
logging.info(gadget.status)
return False
except:
logging.info('Exception')
return False
def OnAnnotationChanged(event, wavelet):
"""Called when the annotation changes."""
blip_ins = event.blip
logging.info('AnnotationChanged')
def GetRSSGadget(event, wavelet):
"""Get Loading Gadget."""
blip_ins = event.blip
gadget = blip_ins.first(element.Gadget, url=RSS_GADGET_URL)
return gadget
def GetLoadingGadget(event, wavelet):
"""Get Loading Gadget."""
blip_ins = event.blip
gadget = blip_ins.first(element.Gadget, url=LOADING_GADGET_URL)
return gadget
def parse_query(url):
""" TODO use urlparse.parse_qs and remove this function """
parse_result = urlparse.urlparse(url, True)
url = parse_result.query
key_values = url.split('&')
query = dict()
for item in key_values:
item_key_value = item.split('=')
key = item_key_value[0] or ''
value = item_key_value[1] or ''
if key:
query[key] = value
return query
def GetTeamInformation(loading_gadget):
"""Get Loading Gadget."""
referer = loading_gadget.wavethis_referer or ''
logging.info(referer)
query = parse_query(referer)
return {
'team1': query['team1'] or 'No team1',
'team2': query['team2'] or 'No team2',
'action': query['action'] or '',
'match': query['match'] or '0',
'location': query['location'] or '',
'match_date': int(query['matchDate']) or None
}
def AddParticipant(wavelet, participant_id):
participants = wavelet.participants
if not participants.__contains__(participant_id):
participants.add(participant_id.encode('utf-8'))
def UpdateParentWave(parent_wavelet, bug_id, status):
"""Update reference wave."""
logging.info('UpdateParentWave')
if __name__ == '__main__':
fifa_robot = robot.Robot('Football Fever - Worldcup 2010', image_url=ICON, profile_url='http://wave.google.com/footballfever.html')
fifa_robot.register_handler(events.WaveletSelfAdded, OnWaveletSelfAdded)
fifa_robot.register_handler(events.AnnotatedTextChanged,
OnAnnotationChanged,
filter=ROBOT_KEY)
fifa_robot.register_handler(events.GadgetStateChanged, OnGadgetStateChanged)
appengine_robot_runner.run(fifa_robot, debug=True)
| Python |
#!/usr/bin/python2.6
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Library to handle data request with Yahoo."""
# Python language specific imports.
import Cookie
import datetime
import math
import logging
import os
import time
import urllib
# AppEngine imports.
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class Feed(webapp.RequestHandler):
"""The class to handle all yahoo mail related requests."""
def RenderTemplate(self, filename, dictionary):
"""Render the given template definition file with the given dictionary.
Args:
filename: The filename of the template to expand.
dictionary: The dictionary that contains the values to populate
in the template.
"""
self.response.out.write(template.render(filename, dictionary))
def get(self, *args):
"""The initial function call."""
url = self.request.get('url', '')
if url:
self.response.headers['Content-Type'] = 'application/xml'
try:
file = urllib.urlopen(url)
text = file.read()
self.response.out.write(text)
except:
self.response.out.write('<root><Error>Error occured</Error></root>')
else:
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
self.RenderTemplate('templates/error.html', {})
def post(self, *args):
self.get(*args)
def main():
application = webapp.WSGIApplication([(r'/makeRequest', Feed),
(r'/.*', Feed)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python2.5
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""To check whether set of robot is done correctly."""
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import prediction
import dataio
class MainHandler(webapp.RequestHandler):
def get(self):
self.response.out.write('Some thing happened..')
class VerifyHandler(webapp.RequestHandler):
def get(self):
st = self.request.get('st', '')
self.response.out.write('KEY')
def main():
handles = [(r'/_wave/verify_token.*', VerifyHandler),
(r'/getprediction', prediction.Prediction),
(r'/saveprediction', prediction.Prediction),
(r'/getmatches', dataio.DataIO),
(r'/getmatch', dataio.DataIO),
(r'/updatematches', dataio.DataIO),
(r'/.*', MainHandler)]
application = webapp.WSGIApplication(handles, debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| Python |
import string
import types
import logging
## json.py implements a JSON (http://json.org) reader and writer.
## Copyright (C) 2005 Patrick D. Logan
## Contact mailto:patrickdlogan@stardecisions.com
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this library; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
class _StringGenerator(object):
def __init__(self, string):
self.string = string
self.index = -1
def peek(self):
i = self.index + 1
if i < len(self.string):
return self.string[i]
else:
return None
def next(self):
self.index += 1
if self.index < len(self.string):
return self.string[self.index]
else:
raise StopIteration
def all(self):
return self.string
class WriteException(Exception):
pass
class ReadException(Exception):
pass
class JsonReader(object):
hex_digits = {'A': 10,'B': 11,'C': 12,'D': 13,'E': 14,'F':15}
escapes = {'t':'\t','n':'\n','f':'\f','r':'\r','b':'\b'}
def read(self, s):
self._generator = _StringGenerator(s)
result = self._read()
return result
def _read(self):
self._eatWhitespace()
peek = self._peek()
if peek is None:
raise ReadException, "Nothing to read: '%s'" % self._generator.all()
if peek == '{':
return self._readObject()
elif peek == '[':
return self._readArray()
elif peek == '"':
return self._readString()
elif peek == '-' or peek.isdigit():
return self._readNumber()
elif peek == 't':
return self._readTrue()
elif peek == 'f':
return self._readFalse()
elif peek == 'n':
return self._readNull()
elif peek == '/':
self._readComment()
return self._read()
else:
raise ReadException, "Input is not valid JSON: '%s'" % self._generator.all()
def _readTrue(self):
self._assertNext('t', "true")
self._assertNext('r', "true")
self._assertNext('u', "true")
self._assertNext('e', "true")
return True
def _readFalse(self):
self._assertNext('f', "false")
self._assertNext('a', "false")
self._assertNext('l', "false")
self._assertNext('s', "false")
self._assertNext('e', "false")
return False
def _readNull(self):
self._assertNext('n', "null")
self._assertNext('u', "null")
self._assertNext('l', "null")
self._assertNext('l', "null")
return None
def _assertNext(self, ch, target):
if self._next() != ch:
raise ReadException, "Trying to read %s: '%s'" % (target, self._generator.all())
def _readNumber(self):
isfloat = False
result = self._next()
peek = self._peek()
while peek is not None and (peek.isdigit() or peek == "."):
isfloat = isfloat or peek == "."
result = result + self._next()
peek = self._peek()
try:
if isfloat:
return float(result)
else:
return int(result)
except ValueError:
raise ReadException, "Not a valid JSON number: '%s'" % result
def _readString(self):
result = ""
assert self._next() == '"'
try:
while self._peek() != '"':
ch = self._next()
if ch == "\\":
ch = self._next()
if ch in 'brnft':
ch = self.escapes[ch]
elif ch == "u":
ch4096 = self._next()
ch256 = self._next()
ch16 = self._next()
ch1 = self._next()
n = 4096 * self._hexDigitToInt(ch4096)
n += 256 * self._hexDigitToInt(ch256)
n += 16 * self._hexDigitToInt(ch16)
n += self._hexDigitToInt(ch1)
ch = unichr(n)
elif ch not in '"/\\':
raise ReadException, "Not a valid escaped JSON character: '%s' in %s" % (ch, self._generator.all())
result = result + ch
except StopIteration:
raise ReadException, "Not a valid JSON string: '%s'" % self._generator.all()
assert self._next() == '"'
return result
def _hexDigitToInt(self, ch):
try:
result = self.hex_digits[ch.upper()]
except KeyError:
try:
result = int(ch)
except ValueError:
raise ReadException, "The character %s is not a hex digit." % ch
return result
def _readComment(self):
assert self._next() == "/"
second = self._next()
if second == "/":
self._readDoubleSolidusComment()
elif second == '*':
self._readCStyleComment()
else:
raise ReadException, "Not a valid JSON comment: %s" % self._generator.all()
def _readCStyleComment(self):
try:
done = False
while not done:
ch = self._next()
done = (ch == "*" and self._peek() == "/")
if not done and ch == "/" and self._peek() == "*":
raise ReadException, "Not a valid JSON comment: %s, '/*' cannot be embedded in the comment." % self._generator.all()
self._next()
except StopIteration:
raise ReadException, "Not a valid JSON comment: %s, expected */" % self._generator.all()
def _readDoubleSolidusComment(self):
try:
ch = self._next()
while ch != "\r" and ch != "\n":
ch = self._next()
except StopIteration:
pass
def _readArray(self):
result = []
assert self._next() == '['
done = self._peek() == ']'
while not done:
item = self._read()
result.append(item)
self._eatWhitespace()
done = self._peek() == ']'
if not done:
ch = self._next()
if ch != ",":
raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
assert ']' == self._next()
return result
def _readObject(self):
count = 0
result = {}
assert self._next() == '{'
done = self._peek() == '}'
while not done:
count = count + 1
key = self._read()
logging.error(key)
if type(key) is not types.StringType:
logging.error(count)
logging.error('tomar')
raise ReadException, "Not a valid JSON object key (should be a string): %s" % key
self._eatWhitespace()
ch = self._next()
if ch != ":":
raise ReadException, "Not a valid JSON object: '%s' due to: '%s'" % (self._generator.all(), ch)
self._eatWhitespace()
val = self._read()
result[key] = val
self._eatWhitespace()
done = self._peek() == '}'
if not done:
ch = self._next()
if ch != ",":
raise ReadException, "Not a valid JSON array: '%s' due to: '%s'" % (self._generator.all(), ch)
assert self._next() == "}"
return result
def _eatWhitespace(self):
p = self._peek()
while p is not None and p in string.whitespace or p == '/':
if p == '/':
self._readComment()
else:
self._next()
p = self._peek()
def _peek(self):
return self._generator.peek()
def _next(self):
return self._generator.next()
class JsonWriter(object):
def _append(self, s):
self._results.append(s)
def write(self, obj, escaped_forward_slash=False):
self._escaped_forward_slash = escaped_forward_slash
self._results = []
self._write(obj)
return "".join(self._results)
def _write(self, obj):
ty = type(obj)
if ty is types.DictType:
n = len(obj)
self._append("{")
for k, v in obj.items():
self._write(k)
self._append(":")
self._write(v)
n = n - 1
if n > 0:
self._append(",")
self._append("}")
elif ty is types.ListType or ty is types.TupleType:
n = len(obj)
self._append("[")
for item in obj:
self._write(item)
n = n - 1
if n > 0:
self._append(",")
self._append("]")
elif ty is types.StringType or ty is types.UnicodeType:
self._append('"')
obj = obj.replace('\\', r'\\')
if self._escaped_forward_slash:
obj = obj.replace('/', r'\/')
obj = obj.replace('"', r'\"')
obj = obj.replace('\b', r'\b')
obj = obj.replace('\f', r'\f')
obj = obj.replace('\n', r'\n')
obj = obj.replace('\r', r'\r')
obj = obj.replace('\t', r'\t')
self._append(obj)
self._append('"')
elif ty is types.IntType or ty is types.LongType:
self._append(str(obj))
elif ty is types.FloatType:
self._append("%f" % obj)
elif obj is True:
self._append("true")
elif obj is False:
self._append("false")
elif obj is None:
self._append("null")
else:
raise WriteException, "Cannot write in JSON: %s" % repr(obj)
def write(obj, escaped_forward_slash=False):
return JsonWriter().write(obj, escaped_forward_slash)
def read(s):
return JsonReader().read(s)
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the element module."""
import base64
import unittest
import element
import util
class TestElement(unittest.TestCase):
"""Tests for the element.Element class."""
def testProperties(self):
el = element.Element(element.Gadget.class_type,
key='value')
self.assertEquals('value', el.key)
def testFormElement(self):
el = element.Input('input')
self.assertEquals(element.Input.class_type, el.type)
self.assertEquals(el.value, '')
self.assertEquals(el.name, 'input')
def testImage(self):
image = element.Image('http://test.com/image.png', width=100, height=100)
self.assertEquals(element.Image.class_type, image.type)
self.assertEquals(image.url, 'http://test.com/image.png')
self.assertEquals(image.width, 100)
self.assertEquals(image.height, 100)
def testAttachment(self):
attachment = element.Attachment(caption='My Favorite', data='SomefakeData')
self.assertEquals(element.Attachment.class_type, attachment.type)
self.assertEquals(attachment.caption, 'My Favorite')
self.assertEquals(attachment.data, 'SomefakeData')
def testGadget(self):
gadget = element.Gadget('http://test.com/gadget.xml')
self.assertEquals(element.Gadget.class_type, gadget.type)
self.assertEquals(gadget.url, 'http://test.com/gadget.xml')
def testInstaller(self):
installer = element.Installer('http://test.com/installer.xml')
self.assertEquals(element.Installer.class_type, installer.type)
self.assertEquals(installer.manifest, 'http://test.com/installer.xml')
def testSerialize(self):
image = element.Image('http://test.com/image.png', width=100, height=100)
s = util.serialize(image)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 3)
self.assertEquals(props['url'], 'http://test.com/image.png')
self.assertEquals(props['width'], 100)
self.assertEquals(props['height'], 100)
def testSerializeAttachment(self):
attachment = element.Attachment(caption='My Favorite', data='SomefakeData')
s = util.serialize(attachment)
k = s.keys()
k.sort()
# we should really have two things to serialize
props = s['properties']
self.assertEquals(len(props), 2)
self.assertEquals(props['caption'], 'My Favorite')
self.assertEquals(props['data'], base64.encodestring('SomefakeData'))
self.assertEquals(attachment.data, 'SomefakeData')
def testSerializeLine(self):
line = element.Line(element.Line.TYPE_H1, alignment=element.Line.ALIGN_LEFT)
s = util.serialize(line)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 2)
self.assertEquals(props['alignment'], 'l')
self.assertEquals(props['lineType'], 'h1')
def testSerializeGadget(self):
gadget = element.Gadget('http://test.com', {'prop1': 'a', 'prop_cap': None})
s = util.serialize(gadget)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 3)
self.assertEquals(props['url'], 'http://test.com')
self.assertEquals(props['prop1'], 'a')
self.assertEquals(props['prop_cap'], None)
def testGadgetElementFromJson(self):
url = 'http://www.foo.com/gadget.xml'
json = {
'type': element.Gadget.class_type,
'properties': {
'url': url,
}
}
gadget = element.Element.from_json(json)
self.assertEquals(element.Gadget.class_type, gadget.type)
self.assertEquals(url, gadget.url)
def testImageElementFromJson(self):
url = 'http://www.foo.com/image.png'
width = '32'
height = '32'
attachment_id = '2'
caption = 'Test Image'
json = {
'type': element.Image.class_type,
'properties': {
'url': url,
'width': width,
'height': height,
'attachmentId': attachment_id,
'caption': caption,
}
}
image = element.Element.from_json(json)
self.assertEquals(element.Image.class_type, image.type)
self.assertEquals(url, image.url)
self.assertEquals(width, image.width)
self.assertEquals(height, image.height)
self.assertEquals(attachment_id, image.attachmentId)
self.assertEquals(caption, image.caption)
def testAttachmentElementFromJson(self):
caption = 'fake caption'
data = 'fake data'
mime_type = 'fake mime'
attachment_id = 'fake id'
attachment_url = 'fake URL'
json = {
'type': element.Attachment.class_type,
'properties': {
'caption': caption,
'data': data,
'mimeType': mime_type,
'attachmentId': attachment_id,
'attachmentUrl': attachment_url,
}
}
attachment = element.Element.from_json(json)
self.assertEquals(element.Attachment.class_type, attachment.type)
self.assertEquals(caption, attachment.caption)
self.assertEquals(data, attachment.data)
self.assertEquals(mime_type, attachment.mimeType)
self.assertEquals(attachment_id, attachment.attachmentId)
self.assertEquals(attachment_url, attachment.attachmentUrl)
def testFormElementFromJson(self):
name = 'button'
value = 'value'
default_value = 'foo'
json = {
'type': element.Label.class_type,
'properties': {
'name': name,
'value': value,
'defaultValue': default_value,
}
}
el = element.Element.from_json(json)
self.assertEquals(element.Label.class_type, el.type)
self.assertEquals(name, el.name)
self.assertEquals(value, el.value)
def testCanInstantiate(self):
bag = [element.Check(name='check', value='value'),
element.Button(name='button', value='caption'),
element.Input(name='input', value='caption'),
element.Label(label_for='button', caption='caption'),
element.RadioButton(name='name', group='group'),
element.RadioButtonGroup(name='name', value='value'),
element.Password(name='name', value='geheim'),
element.TextArea(name='name', value='\n\n\n'),
element.Installer(manifest='test.com/installer.xml'),
element.Line(line_type='type',
indent='3',
alignment='r',
direction='d'),
element.Gadget(url='test.com/gadget.xml',
props={'key1': 'val1', 'key2': 'val2'}),
element.Image(url='test.com/image.png', width=100, height=200),
element.Attachment(caption='fake caption', data='fake data')]
types_constructed = set([type(x) for x in bag])
types_required = set(element.ALL.values())
missing_required = types_constructed.difference(types_required)
self.assertEquals(missing_required, set())
missing_constructed = types_required.difference(types_constructed)
self.assertEquals(missing_constructed, set())
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the util module."""
__author__ = 'davidbyttow@google.com (David Byttow)'
import unittest
import ops
import util
class TestUtils(unittest.TestCase):
"""Tests utility functions."""
def testIsIterable(self):
self.assertTrue(util.is_iterable([]))
self.assertTrue(util.is_iterable({}))
self.assertTrue(util.is_iterable(set()))
self.assertTrue(util.is_iterable(()))
self.assertFalse(util.is_iterable(42))
self.assertFalse(util.is_iterable('list?'))
self.assertFalse(util.is_iterable(object))
def testIsDict(self):
self.assertFalse(util.is_dict([]))
self.assertTrue(util.is_dict({}))
self.assertFalse(util.is_dict(set()))
self.assertFalse(util.is_dict(()))
self.assertFalse(util.is_dict(42))
self.assertFalse(util.is_dict('dict?'))
self.assertFalse(util.is_dict(object))
def testIsUserDefinedNewStyleClass(self):
class OldClass:
pass
class NewClass(object):
pass
self.assertFalse(util.is_user_defined_new_style_class(OldClass()))
self.assertTrue(util.is_user_defined_new_style_class(NewClass()))
self.assertFalse(util.is_user_defined_new_style_class({}))
self.assertFalse(util.is_user_defined_new_style_class(()))
self.assertFalse(util.is_user_defined_new_style_class(42))
self.assertFalse(util.is_user_defined_new_style_class('instance?'))
def testLowerCamelCase(self):
self.assertEquals('foo', util.lower_camel_case('foo'))
self.assertEquals('fooBar', util.lower_camel_case('foo_bar'))
self.assertEquals('fooBar', util.lower_camel_case('fooBar'))
self.assertEquals('blipId', util.lower_camel_case('blip_id'))
self.assertEquals('fooBar', util.lower_camel_case('foo__bar'))
self.assertEquals('fooBarBaz', util.lower_camel_case('foo_bar_baz'))
self.assertEquals('f', util.lower_camel_case('f'))
self.assertEquals('f', util.lower_camel_case('f_'))
self.assertEquals('', util.lower_camel_case(''))
self.assertEquals('', util.lower_camel_case('_'))
self.assertEquals('aBCDEF', util.lower_camel_case('_a_b_c_d_e_f_'))
def assertListsEqual(self, a, b):
self.assertEquals(len(a), len(b))
for i in range(len(a)):
self.assertEquals(a[i], b[i])
def assertDictsEqual(self, a, b):
self.assertEquals(len(a.keys()), len(b.keys()))
for k, v in a.iteritems():
self.assertEquals(v, b[k])
def testSerializeList(self):
data = [1, 2, 3]
output = util.serialize(data)
self.assertListsEqual(data, output)
def testSerializeDict(self):
data = {'key': 'value', 'under_score': 'value2'}
expected = {'key': 'value', 'underScore': 'value2'}
output = util.serialize(data)
self.assertDictsEqual(expected, output)
def testNonNoneDict(self):
a = {'a': 1, 'b': 1}
self.assertDictsEqual(a, util.non_none_dict(a))
b = a.copy()
b['c'] = None
self.assertDictsEqual(a, util.non_none_dict(b))
def testForceUnicode(self):
self.assertEquals(u"aaa", util.force_unicode("aaa"))
self.assertEquals(u"12", util.force_unicode(12))
self.assertEquals(u"\u0430\u0431\u0432",
util.force_unicode("\xd0\xb0\xd0\xb1\xd0\xb2"))
self.assertEquals(u'\u30e6\u30cb\u30b3\u30fc\u30c9',
util.force_unicode(u'\u30e6\u30cb\u30b3\u30fc\u30c9'))
def testSerializeAttributes(self):
class Data(object):
def __init__(self):
self.public = 1
self._protected = 2
self.__private = 3
def Func(self):
pass
data = Data()
output = util.serialize(data)
# Functions and non-public fields should not be serialized.
self.assertEquals(1, len(output.keys()))
self.assertEquals(data.public, output['public'])
def testStringEnum(self):
util.StringEnum()
single = util.StringEnum('foo')
self.assertEquals('foo', single.foo)
multi = util.StringEnum('foo', 'bar')
self.assertEquals('foo', multi.foo)
self.assertEquals('bar', multi.bar)
def testParseMarkup(self):
self.assertEquals('foo', util.parse_markup('foo'))
self.assertEquals('foo bar', util.parse_markup('foo <b>bar</b>'))
self.assertEquals('foo\nbar', util.parse_markup('foo<br>bar'))
self.assertEquals('foo\nbar', util.parse_markup('foo<p indent="3">bar'))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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 element
import errors
import util
class Annotation(object):
"""Models an annotation on a document.
Annotations are key/value pairs over a range of content. Annotations
can be used to store data or to be interpreted by a client when displaying
the data.
"""
# Use the following constants to control the display of the client
#: Reserved annotation for setting background color of text.
BACKGROUND_COLOR = "style/backgroundColor"
#: Reserved annotation for setting color of text.
COLOR = "style/color"
#: Reserved annotation for setting font family of text.
FONT_FAMILY = "style/fontFamily"
#: Reserved annotation for setting font family of text.
FONT_SIZE = "style/fontSize"
#: Reserved annotation for setting font style of text.
FONT_STYLE = "style/fontStyle"
#: Reserved annotation for setting font weight of text.
FONT_WEIGHT = "style/fontWeight"
#: Reserved annotation for setting text decoration.
TEXT_DECORATION = "style/textDecoration"
#: Reserved annotation for setting vertical alignment.
VERTICAL_ALIGN = "style/verticalAlign"
def __init__(self, name, value, start, end):
self._name = name
self._value = value
self._start = start
self._end = end
@property
def name(self):
return self._name
@property
def value(self):
return self._value
@property
def start(self):
return self._start
@property
def end(self):
return self._end
def _shift(self, where, inc):
"""Shift annotation by 'inc' if it (partly) overlaps with 'where'."""
if self._start >= where:
self._start += inc
if self._end >= where:
self._end += inc
def serialize(self):
"""Serializes the annotation.
Returns:
A dict containing the name, value, and range values.
"""
return {'name': self._name,
'value': self._value,
'range': {'start': self._start,
'end': self._end}}
class Annotations(object):
"""A dictionary-like object containing the annotations, keyed by name."""
def __init__(self, operation_queue, blip):
self._operation_queue = operation_queue
self._blip = blip
self._store = {}
def __contains__(self, what):
if isinstance(what, Annotation):
what = what.name
return what in self._store
def _add_internal(self, name, value, start, end):
"""Internal add annotation does not send out operations."""
if name in self._store:
# TODO: use bisect to make this more efficient.
new_list = []
for existing in self._store[name]:
if start > existing.end or end < existing.start:
new_list.append(existing)
else:
if existing.value == value:
# merge the annotations:
start = min(existing.start, start)
end = max(existing.end, end)
else:
# chop the bits off the existing annotation
if existing.start < start:
new_list.append(Annotation(
existing.name, existing.value, existing.start, start))
if existing.end > end:
new_list.append(Annotation(
existing.name, existing.value, existing.end, end))
new_list.append(Annotation(name, value, start, end))
self._store[name] = new_list
else:
self._store[name] = [Annotation(name, value, start, end)]
def _delete_internal(self, name, start=0, end=-1):
"""Remove the passed annotaion from the internal representation."""
if not name in self._store:
return
if end < 0:
end = len(self._blip) + end
new_list = []
for a in self._store[name]:
if start > a.end or end < a.start:
new_list.append(a)
elif start < a.start and end > a.end:
continue
else:
if a.start < start:
new_list.append(Annotation(name, a.value, a.start, start))
if a.end > end:
new_list.append(Annotation(name, a.value, end, a.end))
if new_list:
self._store[name] = new_list
else:
del self._store[name]
def _shift(self, where, inc):
"""Shift annotation by 'inc' if it (partly) overlaps with 'where'."""
for annotations in self._store.values():
for annotation in annotations:
annotation._shift(where, inc)
# Merge fragmented annotations that should be contiguous, for example:
# Annotation('foo', 'bar', 1, 2) and Annotation('foo', 'bar', 2, 3).
for name, annotations in self._store.items():
new_list = []
for i, annotation in enumerate(annotations):
name = annotation.name
value = annotation.value
start = annotation.start
end = annotation.end
# Find the last end index.
for j, next_annotation in enumerate(annotations[i + 1:]):
# Not contiguous, skip.
if (end < next_annotation.start):
break
# Contiguous, merge.
if (end == next_annotation.start and value == next_annotation.value):
end = next_annotation.end
del annotations[j]
new_list.append(Annotation(name, value, start, end))
self._store[name] = new_list
def __len__(self):
return len(self._store)
def __getitem__(self, key):
return self._store[key]
def __iter__(self):
for l in self._store.values():
for ann in l:
yield ann
def names(self):
"""Return the names of the annotations in the store."""
return self._store.keys()
def serialize(self):
"""Return a list of the serialized annotations."""
res = []
for v in self._store.values():
res += [a.serialize() for a in v]
return res
class Blips(object):
"""A dictionary-like object containing the blips, keyed on blip ID."""
def __init__(self, blips):
self._blips = blips
def __getitem__(self, blip_id):
return self._blips[blip_id]
def __iter__(self):
return self._blips.__iter__()
def __len__(self):
return len(self._blips)
def _add(self, ablip):
self._blips[ablip.blip_id] = ablip
def _remove_with_id(self, blip_id):
del_blip = self._blips[blip_id]
if del_blip:
# Remove the reference to this blip from its parent.
parent_blip = self._blips[blip_id].parent_blip
if parent_blip:
parent_blip._child_blip_ids.remove(blip_id)
del self._blips[blip_id]
def get(self, blip_id, default_value=None):
"""Retrieves a blip.
Returns:
A Blip object. If none found for the ID, it returns None,
or if default_value is specified, it returns that.
"""
return self._blips.get(blip_id, default_value)
def serialize(self):
"""Serializes the blips.
Returns:
A dict of serialized blips.
"""
res = {}
for blip_id, item in self._blips.items():
res[blip_id] = item.serialize()
return res
class BlipRefs(object):
"""Represents a set of references to contents in a blip.
For example, a BlipRefs instance can represent the results
of a search, an explicitly set range, a regular expression,
or refer to the entire blip. BlipRefs are used to express
operations on a blip in a consistent way that can easily
be transfered to the server.
The typical way of creating a BlipRefs object is to use
selector methods on the Blip object. Developers will not
usually instantiate a BlipRefs object directly.
"""
DELETE = 'DELETE'
REPLACE = 'REPLACE'
INSERT = 'INSERT'
INSERT_AFTER = 'INSERT_AFTER'
ANNOTATE = 'ANNOTATE'
CLEAR_ANNOTATION = 'CLEAR_ANNOTATION'
UPDATE_ELEMENT = 'UPDATE_ELEMENT'
def __init__(self, blip, maxres=1):
self._blip = blip
self._maxres = maxres
@classmethod
def all(cls, blip, findwhat, maxres=-1, **restrictions):
"""Construct an instance representing the search for text or elements."""
obj = cls(blip, maxres)
obj._findwhat = findwhat
obj._restrictions = restrictions
obj._hits = lambda: obj._find(findwhat, maxres, **restrictions)
if findwhat is None:
# No findWhat, take the entire blip
obj._params = {}
else:
query = {'maxRes': maxres}
if isinstance(findwhat, basestring):
query['textMatch'] = findwhat
else:
query['elementMatch'] = findwhat.class_type
query['restrictions'] = restrictions
obj._params = {'modifyQuery': query}
return obj
@classmethod
def range(cls, blip, begin, end):
"""Constructs an instance representing an explicitly set range."""
obj = cls(blip)
obj._begin = begin
obj._end = end
obj._hits = lambda: [(begin, end)]
obj._params = {'range': {'start': begin, 'end': end}}
return obj
def _elem_matches(self, elem, clz, **restrictions):
if not isinstance(elem, clz):
return False
for key, val in restrictions.items():
if getattr(elem, key) != val:
return False
return True
def _find(self, what, maxres=-1, **restrictions):
"""Iterates where 'what' occurs in the associated blip.
What can be either a string or a class reference.
Examples:
self._find('hello') will return the first occurence of the word hello
self._find(element.Gadget, url='http://example.com/gadget.xml')
will return the first gadget that has as url example.com.
Args:
what: what to search for. Can be a class or a string. The class
should be an element from element.py
maxres: number of results to return at most, or <= 0 for all.
restrictions: if what specifies a class, further restrictions
of the found instances.
Yields:
Tuples indicating the range of the matches. For a one
character/element match at position x, (x, x+1) is yielded.
"""
blip = self._blip
if what is None:
yield 0, len(blip)
raise StopIteration
if isinstance(what, basestring):
idx = blip._content.find(what)
count = 0
while idx != -1:
yield idx, idx + len(what)
count += 1
if count == maxres:
raise StopIteration
idx = blip._content.find(what, idx + len(what))
else:
count = 0
for idx, el in blip._elements.items():
if self._elem_matches(el, what, **restrictions):
yield idx, idx + 1
count += 1
if count == maxres:
raise StopIteration
def _execute(self, modify_how, what, bundled_annotations=None):
"""Executes this BlipRefs object.
Args:
modify_how: What to do. Any of the operation declared at the top.
what: Depending on the operation. For delete, has to be None.
For the others it is a singleton, a list or a function returning
what to do; for ANNOTATE tuples of (key, value), for the others
either string or elements.
If what is a function, it takes three parameters, the content of
the blip, the beginning of the matching range and the end.
bundled_annotations: Annotations to apply immediately.
Raises:
IndexError when trying to access content outside of the blip.
ValueError when called with the wrong values.
Returns:
self for chainability.
"""
blip = self._blip
if modify_how != BlipRefs.DELETE:
if type(what) != list:
what = [what]
next_index = 0
matched = []
# updated_elements is used to store the element type of the
# element to update
updated_elements = []
# For now, if we find one markup, we'll use it everywhere.
next = None
hit_found = False
for start, end in self._hits():
hit_found = True
if start < 0:
start += len(blip)
if end == 0:
end += len(blip)
if end < 0:
end += len(blip)
if len(blip) == 0:
if start != 0 or end != 0:
raise IndexError('Start and end have to be 0 for empty document')
elif start < 0 or end < 1 or start >= len(blip) or end > len(blip):
raise IndexError('Position outside the document')
if modify_how == BlipRefs.DELETE:
for i in range(start, end):
if i in blip._elements:
del blip._elements[i]
blip._delete_annotations(start, end)
blip._shift(end, start - end)
blip._content = blip._content[:start] + blip._content[end:]
else:
if callable(what):
next = what(blip._content, start, end)
matched.append(next)
else:
next = what[next_index]
next_index = (next_index + 1) % len(what)
if isinstance(next, str):
next = util.force_unicode(next)
if modify_how == BlipRefs.ANNOTATE:
key, value = next
blip.annotations._add_internal(key, value, start, end)
elif modify_how == BlipRefs.CLEAR_ANNOTATION:
blip.annotations._delete_internal(next, start, end)
elif modify_how == BlipRefs.UPDATE_ELEMENT:
el = blip._elements.get(start)
if not element:
raise ValueError('No element found at index %s' % start)
# the passing around of types this way feels a bit dirty:
updated_elements.append(element.Element.from_json({'type': el.type,
'properties': next}))
for k, b in next.items():
setattr(el, k, b)
else:
if modify_how == BlipRefs.INSERT:
end = start
elif modify_how == BlipRefs.INSERT_AFTER:
start = end
elif modify_how == BlipRefs.REPLACE:
pass
else:
raise ValueError('Unexpected modify_how: ' + modify_how)
if isinstance(next, element.Element):
text = ' '
else:
text = next
# in the case of a replace, and the replacement text is shorter,
# delete the delta.
if start != end and len(text) < end - start:
blip._delete_annotations(start + len(text), end)
blip._shift(end, len(text) + start - end)
blip._content = blip._content[:start] + text + blip._content[end:]
if bundled_annotations:
end_annotation = start + len(text)
blip._delete_annotations(start, end_annotation)
for key, value in bundled_annotations:
blip.annotations._add_internal(key, value, start, end_annotation)
if isinstance(next, element.Element):
blip._elements[start] = next
# No match found, return immediately without generating op.
if not hit_found:
return
operation = blip._operation_queue.document_modify(blip.wave_id,
blip.wavelet_id,
blip.blip_id)
for param, value in self._params.items():
operation.set_param(param, value)
modify_action = {'modifyHow': modify_how}
if modify_how == BlipRefs.DELETE:
pass
elif modify_how == BlipRefs.UPDATE_ELEMENT:
modify_action['elements'] = updated_elements
elif (modify_how == BlipRefs.REPLACE or
modify_how == BlipRefs.INSERT or
modify_how == BlipRefs.INSERT_AFTER):
if callable(what):
what = matched
if what:
if not isinstance(next, element.Element):
modify_action['values'] = [util.force_unicode(value) for value in what]
else:
modify_action['elements'] = what
elif modify_how == BlipRefs.ANNOTATE:
modify_action['values'] = [x[1] for x in what]
modify_action['annotationKey'] = what[0][0]
elif modify_how == BlipRefs.CLEAR_ANNOTATION:
modify_action['annotationKey'] = what[0]
if bundled_annotations:
modify_action['bundledAnnotations'] = [
{'key': key, 'value': value} for key, value in bundled_annotations]
operation.set_param('modifyAction', modify_action)
return self
def insert(self, what, bundled_annotations=None):
"""Inserts what at the matched positions."""
return self._execute(
BlipRefs.INSERT, what, bundled_annotations=bundled_annotations)
def insert_after(self, what, bundled_annotations=None):
"""Inserts what just after the matched positions."""
return self._execute(
BlipRefs.INSERT_AFTER, what, bundled_annotations=bundled_annotations)
def replace(self, what, bundled_annotations=None):
"""Replaces the matched positions with what."""
return self._execute(
BlipRefs.REPLACE, what, bundled_annotations=bundled_annotations)
def delete(self):
"""Deletes the content at the matched positions."""
return self._execute(BlipRefs.DELETE, None)
def annotate(self, name, value=None):
"""Annotates the content at the matched positions.
You can either specify both name and value to set the
same annotation, or supply as the first parameter something
that yields name/value pairs. The name and value should both be strings.
"""
if value is None:
what = name
else:
what = (name, value)
return self._execute(BlipRefs.ANNOTATE, what)
def clear_annotation(self, name):
"""Clears the annotation at the matched positions."""
return self._execute(BlipRefs.CLEAR_ANNOTATION, name)
def update_element(self, new_values):
"""Update an existing element with a set of new values."""
return self._execute(BlipRefs.UPDATE_ELEMENT, new_values)
def __nonzero__(self):
"""Return whether we have a value."""
for start, end in self._hits():
return True
return False
def value(self):
"""Convenience method to convert a BlipRefs to value of its first match."""
for start, end in self._hits():
if end - start == 1 and start in self._blip._elements:
return self._blip._elements[start]
else:
return self._blip.text[start:end]
raise ValueError('BlipRefs has no values')
def __getattr__(self, attribute):
"""Mirror the getattr of value().
This allows for clever things like
first(IMAGE).url
or
blip.annotate_with(key, value).upper()
"""
return getattr(self.value(), attribute)
def __radd__(self, other):
"""Make it possible to add this to a string."""
return other + self.value()
def __cmp__(self, other):
"""Support comparision with target."""
return cmp(self.value(), other)
def __iter__(self):
for start_end in self._hits():
yield start_end
class Blip(object):
"""Models a single blip instance.
Blips are essentially the documents that make up a conversation. Blips can
live in a hierarchy of blips. A root blip has no parent blip id, but all
blips have the ids of the wave and wavelet that they are associated with.
Blips also contain annotations, content and elements, which are accessed via
the Document object.
"""
def __init__(self, json, other_blips, operation_queue):
"""Inits this blip with JSON data.
Args:
json: JSON data dictionary from Wave server.
other_blips: A dictionary like object that can be used to resolve
ids of blips to blips.
operation_queue: an OperationQueue object to store generated operations
in.
"""
self._blip_id = json.get('blipId')
self._operation_queue = operation_queue
self._child_blip_ids = set(json.get('childBlipIds', []))
self._content = json.get('content', '')
self._contributors = set(json.get('contributors', []))
self._creator = json.get('creator')
self._last_modified_time = json.get('lastModifiedTime', 0)
self._version = json.get('version', 0)
self._parent_blip_id = json.get('parentBlipId')
self._wave_id = json.get('waveId')
self._wavelet_id = json.get('waveletId')
if isinstance(other_blips, Blips):
self._other_blips = other_blips
else:
self._other_blips = Blips(other_blips)
self._annotations = Annotations(operation_queue, self)
for annjson in json.get('annotations', []):
r = annjson['range']
self._annotations._add_internal(annjson['name'],
annjson['value'],
r['start'],
r['end'])
self._elements = {}
json_elements = json.get('elements', {})
for elem in json_elements:
self._elements[int(elem)] = element.Element.from_json(json_elements[elem])
self.raw_data = json
@property
def blip_id(self):
"""The id of this blip."""
return self._blip_id
@property
def wave_id(self):
"""The id of the wave that this blip belongs to."""
return self._wave_id
@property
def wavelet_id(self):
"""The id of the wavelet that this blip belongs to."""
return self._wavelet_id
@property
def child_blip_ids(self):
"""The set of the ids of this blip's children."""
return self._child_blip_ids
@property
def child_blips(self):
"""The set of blips that are children of this blip."""
return set([self._other_blips[blid_id] for blid_id in self._child_blip_ids
if blid_id in self._other_blips])
@property
def contributors(self):
"""The set of participant ids that contributed to this blip."""
return self._contributors
@property
def creator(self):
"""The id of the participant that created this blip."""
return self._creator
@property
def last_modified_time(self):
"""The time in seconds since epoch when this blip was last modified."""
return self._last_modified_time
@property
def version(self):
"""The version of this blip."""
return self._version
@property
def parent_blip_id(self):
"""The parent blip_id or None if this is the root blip."""
return self._parent_blip_id
@property
def parent_blip(self):
"""The parent blip or None if it is the root."""
# if parent_blip_id is None, get will also return None
return self._other_blips.get(self._parent_blip_id)
@property
def inline_blip_offset(self):
"""The offset in the parent if this blip is inline or -1 if not.
If the parent is not in the context, this function will always
return -1 since it can't determine the inline blip status.
"""
parent = self.parent_blip
if not parent:
return -1
for offset, el in parent._elements.items():
if el.type == element.Element.INLINE_BLIP_TYPE and el.id == self.blip_id:
return offset
return -1
def is_root(self):
"""Returns whether this is the root blip of a wavelet."""
return self._parent_blip_id is None
@property
def annotations(self):
"""The annotations for this document."""
return self._annotations
@property
def elements(self):
"""Returns a list of elements for this document.
The elements of a blip are things like forms elements and gadgets
that cannot be expressed as plain text. In the text of the blip, you'll
typically find a space as a place holder for the element.
If you want to retrieve the element at a particular index in the blip, use
blip[index].value().
"""
return self._elements.values()
def __len__(self):
return len(self._content)
def __getitem__(self, item):
"""returns a BlipRefs for the given slice."""
if isinstance(item, slice):
if item.step:
raise errors.Error('Step not supported for blip slices')
return self.range(item.start, item.stop)
else:
return self.at(item)
def __setitem__(self, item, value):
"""short cut for self.range/at().replace(value)."""
self.__getitem__(item).replace(value)
def __delitem__(self, item):
"""short cut for self.range/at().delete()."""
self.__getitem__(item).delete()
def _shift(self, where, inc):
"""Move element and annotations after 'where' up by 'inc'."""
new_elements = {}
for idx, el in self._elements.items():
if idx >= where:
idx += inc
new_elements[idx] = el
self._elements = new_elements
self._annotations._shift(where, inc)
def _delete_annotations(self, start, end):
"""Delete all annotations between 'start' and 'end'."""
for annotation_name in self._annotations.names():
self._annotations._delete_internal(annotation_name, start, end)
def all(self, findwhat=None, maxres=-1, **restrictions):
"""Returns a BlipRefs object representing all results for the search.
If searching for an element, the restrictions can be used to specify
additional element properties to filter on, like the url of a Gadget.
"""
return BlipRefs.all(self, findwhat, maxres, **restrictions)
def first(self, findwhat=None, **restrictions):
"""Returns a BlipRefs object representing the first result for the search.
If searching for an element, the restrictions can be used to specify
additional element properties to filter on, like the url of a Gadget.
"""
return BlipRefs.all(self, findwhat, 1, **restrictions)
def at(self, index):
"""Returns a BlipRefs object representing a 1-character range."""
return BlipRefs.range(self, index, index + 1)
def range(self, start, end):
"""Returns a BlipRefs object representing the range."""
return BlipRefs.range(self, start, end)
def serialize(self):
"""Return a dictionary representation of this blip ready for json."""
return {'blipId': self._blip_id,
'childBlipIds': list(self._child_blip_ids),
'content': self._content,
'creator': self._creator,
'contributors': list(self._contributors),
'lastModifiedTime': self._last_modified_time,
'version': self._version,
'parentBlipId': self._parent_blip_id,
'waveId': self._wave_id,
'waveletId': self._wavelet_id,
'annotations': self._annotations.serialize(),
'elements': dict([(index, e.serialize())
for index, e in self._elements.items()])
}
def proxy_for(self, proxy_for_id):
"""Return a view on this blip that will proxy for the specified id.
A shallow copy of the current blip is returned with the proxy_for_id
set. Any modifications made to this copy will be done using the
proxy_for_id, i.e. the robot+<proxy_for_id>@appspot.com address will
be used.
"""
operation_queue = self._operation_queue.proxy_for(proxy_for_id)
res = Blip(json={},
other_blips={},
operation_queue=operation_queue)
res._blip_id = self._blip_id
res._child_blip_ids = self._child_blip_ids
res._content = self._content
res._contributors = self._contributors
res._creator = self._creator
res._last_modified_time = self._last_modified_time
res._version = self._version
res._parent_blip_id = self._parent_blip_id
res._wave_id = self._wave_id
res._wavelet_id = self._wavelet_id
res._other_blips = self._other_blips
res._annotations = self._annotations
res._elements = self._elements
res.raw_data = self.raw_data
return res
@property
def text(self):
"""Returns the raw text content of this document."""
return self._content
def find(self, what, **restrictions):
"""Iterate to matching bits of contents.
Yield either elements or pieces of text.
"""
br = BlipRefs.all(self, what, **restrictions)
for start, end in br._hits():
if end - start == 1 and start in self._elements:
yield self._elements[start]
else:
yield self._content[start:end]
raise StopIteration
def append(self, what, bundled_annotations=None):
"""Convenience method covering a common pattern."""
return BlipRefs.all(self, findwhat=None).insert_after(
what, bundled_annotations=bundled_annotations)
def reply(self):
"""Create and return a reply to this blip."""
blip_data = self._operation_queue.blip_create_child(self.wave_id,
self.wavelet_id,
self.blip_id)
new_blip = Blip(blip_data, self._other_blips, self._operation_queue)
self._other_blips._add(new_blip)
return new_blip
def append_markup(self, markup):
"""Interpret the markup text as xhtml and append the result to the doc.
Args:
markup: The markup'ed text to append.
"""
markup = util.force_unicode(markup)
self._operation_queue.document_append_markup(self.wave_id,
self.wavelet_id,
self.blip_id,
markup)
self._content += util.parse_markup(markup)
def insert_inline_blip(self, position):
"""Inserts an inline blip into this blip at a specific position.
Args:
position: Position to insert the blip at. This has to be greater than 0.
Returns:
The JSON data of the blip that was created.
"""
if position <= 0:
raise IndexError(('Illegal inline blip position: %d. Position has to ' +
'be greater than 0.') % position)
blip_data = self._operation_queue.document_inline_blip_insert(
self.wave_id,
self.wavelet_id,
self.blip_id,
position)
new_blip = Blip(blip_data, self._other_blips, self._operation_queue)
self._other_blips._add(new_blip)
return new_blip
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the robot module."""
import unittest
import events
import ops
import robot
import simplejson
BLIP_JSON = ('{"wdykLROk*13":'
'{"lastModifiedTime":1242079608457,'
'"contributors":["someguy@test.com"],'
'"waveletId":"test.com!conv+root",'
'"waveId":"test.com!wdykLROk*11",'
'"parentBlipId":null,'
'"version":3,'
'"creator":"someguy@test.com",'
'"content":"\\nContent!",'
'"blipId":"wdykLROk*13","'
'annotations":[{"range":{"start":0,"end":1},'
'"name":"user/e/davidbyttow@google.com","value":"David"}],'
'"elements":{},'
'"childBlipIds":[]}'
'}')
WAVELET_JSON = ('{"lastModifiedTime":1242079611003,'
'"title":"A title",'
'"waveletId":"test.com!conv+root",'
'"rootBlipId":"wdykLROk*13",'
'"dataDocuments":null,'
'"creationTime":1242079608457,'
'"waveId":"test.com!wdykLROk*11",'
'"participants":["someguy@test.com","monty@appspot.com"],'
'"creator":"someguy@test.com",'
'"version":5}')
EVENTS_JSON = ('[{"timestamp":1242079611003,'
'"modifiedBy":"someguy@test.com",'
'"properties":{"participantsRemoved":[],'
'"participantsAdded":["monty@appspot.com"]},'
'"type":"WAVELET_PARTICIPANTS_CHANGED"}]')
TEST_JSON = '{"blips":%s,"wavelet":%s,"events":%s}' % (
BLIP_JSON, WAVELET_JSON, EVENTS_JSON)
NEW_WAVE_JSON = [{"data":
{"waveletId": "wavesandbox.com!conv+root",
"blipId": "b+LrODcLZkDlu", "waveId":
"wavesandbox.com!w+LrODcLZkDlt"},
"id": "op2"}]
NEW_WAVE_JSON_OLD = [{'data':
[{'data':
{'waveletId': 'googlewave.com!conv+root',
'blipId': 'b+VqQXQbZkCP1',
'waveId': 'googlewave.com!w+VqQXQbZkCP0'},
'id': 'wavelet.create1265055048410'}],
'id': 'op10'}];
class TestRobot(unittest.TestCase):
"""Tests for testing the basic parsing of json in robots."""
def setUp(self):
self.robot = robot.Robot('Testy')
def testCreateWave(self):
self.robot.submit = lambda x: NEW_WAVE_JSON
new_wave = self.robot.new_wave('wavesandbox.com', submit=True)
self.assertEqual('wavesandbox.com!w+LrODcLZkDlt', new_wave.wave_id)
self.robot.submit = lambda x: NEW_WAVE_JSON_OLD
new_wave = self.robot.new_wave('googlewave.com', submit=True)
self.assertEqual('googlewave.com!w+VqQXQbZkCP0', new_wave.wave_id)
def testEventParsing(self):
def check(event, wavelet):
# Test some basic properties; the rest should be covered by
# ops.CreateContext.
root = wavelet.root_blip
self.assertEqual(1, len(wavelet.blips))
self.assertEqual('wdykLROk*13', root.blip_id)
self.assertEqual('test.com!wdykLROk*11', root.wave_id)
self.assertEqual('test.com!conv+root', root.wavelet_id)
self.assertEqual('WAVELET_PARTICIPANTS_CHANGED', event.type)
self.assertEqual({'participantsRemoved': [],
'participantsAdded': ['monty@appspot.com']},
event.properties)
self.robot.test_called = True
self.robot.test_called = False
self.robot.register_handler(events.WaveletParticipantsChanged,
check)
json = self.robot.process_events(TEST_JSON)
self.assertTrue(self.robot.test_called)
operations = simplejson.loads(json)
# there should be one operation indicating the current version:
self.assertEqual(1, len(operations))
def testWrongEventsIgnored(self):
self.robot.test_called = True
def check(event, wavelet):
called = True
self.robot.test_called = False
self.robot.register_handler(events.BlipSubmitted,
check)
self.robot.process_events(TEST_JSON)
self.assertFalse(self.robot.test_called)
def testOperationParsing(self):
def check(event, wavelet):
wavelet.reply()
wavelet.title = 'new title'
wavelet.root_blip.append_markup('<b>Hello</b>')
self.robot.register_handler(events.WaveletParticipantsChanged,
check)
json = self.robot.process_events(TEST_JSON)
operations = simplejson.loads(json)
expected = set([ops.ROBOT_NOTIFY_CAPABILITIES_HASH,
ops.WAVELET_APPEND_BLIP,
ops.WAVELET_SET_TITLE,
ops.DOCUMENT_APPEND_MARKUP])
methods = [operation['method'] for operation in operations]
for method in methods:
self.assertTrue(method in expected)
expected.remove(method)
self.assertEquals(0, len(expected))
def testSerializeWavelets(self):
wavelet = self.robot.blind_wavelet(TEST_JSON)
serialized = wavelet.serialize()
unserialized = self.robot.blind_wavelet(serialized)
self.assertEquals(wavelet.creator, unserialized.creator)
self.assertEquals(wavelet.creation_time, unserialized.creation_time)
self.assertEquals(wavelet.last_modified_time,
unserialized.last_modified_time)
self.assertEquals(wavelet.root_blip.blip_id, unserialized.root_blip.blip_id)
self.assertEquals(wavelet.title, unserialized.title)
self.assertEquals(wavelet.wave_id, unserialized.wave_id)
self.assertEquals(wavelet.wavelet_id, unserialized.wavelet_id)
self.assertEquals(wavelet.domain, unserialized.domain)
def testProxiedBlindWavelet(self):
def handler(event, wavelet):
blind_wavelet = self.robot.blind_wavelet(TEST_JSON, 'proxyid')
blind_wavelet.reply()
blind_wavelet.submit_with(wavelet)
self.robot.register_handler(events.WaveletParticipantsChanged, handler)
json = self.robot.process_events(TEST_JSON)
operations = simplejson.loads(json)
self.assertEqual(2, len(operations))
self.assertEquals(ops.ROBOT_NOTIFY_CAPABILITIES_HASH,
operations[0]['method'])
self.assertEquals(ops.WAVELET_APPEND_BLIP, operations[1]['method'])
self.assertEquals('proxyid', operations[1]['params']['proxyingFor'])
def testCapabilitiesHashIncludesContextAndFilter(self):
robot1 = robot.Robot('Robot1')
robot1.register_handler(events.WaveletSelfAdded, lambda: '')
robot2 = robot.Robot('Robot2')
robot2.register_handler(events.WaveletSelfAdded, lambda: '',
context=events.Context.ALL)
self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash())
robot3 = robot.Robot('Robot3')
robot2.register_handler(events.WaveletSelfAdded, lambda: '',
context=events.Context.ALL, filter="foo")
self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash())
self.assertNotEqual(robot1.capabilities_hash(), robot3.capabilities_hash())
self.assertNotEqual(robot2.capabilities_hash(), robot3.capabilities_hash())
class TestGetCapabilitiesXml(unittest.TestCase):
def setUp(self):
self.robot = robot.Robot('Testy')
self.robot.capabilities_hash = lambda: '1'
def assertStringsEqual(self, s1, s2):
self.assertEqual(s1, s2, 'Strings differ:\n%s--\n%s' % (s1, s2))
def testDefault(self):
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testUrls(self):
profile_robot = robot.Robot(
'Testy',
image_url='http://example.com/image.png',
profile_url='http://example.com/profile.xml')
profile_robot.capabilities_hash = lambda: '1'
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = profile_robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testConsumerKey(self):
# setup_oauth doesn't work during testing, so heavy handed setting of
# properties it is:
self.robot._consumer_key = 'consumer'
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:consumer_key>consumer</w:consumer_key>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testCapsAndEvents(self):
self.robot.register_handler(events.BlipSubmitted, None,
context=[events.Context.SELF,
events.Context.ROOT])
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n'
' <w:capability name="%s" context="SELF,ROOT"/>\n'
'</w:capabilities>\n'
'</w:robot>\n') % (ops.PROTOCOL_VERSION, events.BlipSubmitted.type)
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Run robot from the commandline for testing.
This robot_runner let's you define event handlers using flags and takes the
json input from the std in and writes out the json output to stdout.
for example
cat events | commandline_robot_runner.py \
--eventdef-blip_submitted="wavelet.title='title'"
"""
__author__ = 'douwe@google.com (Douwe Osinga)'
import sys
import urllib
from google3.pyglib import app
from google3.pyglib import flags
from google3.walkabout.externalagents import api
from google3.walkabout.externalagents.api import blip
from google3.walkabout.externalagents.api import element
from google3.walkabout.externalagents.api import errors
from google3.walkabout.externalagents.api import events
from google3.walkabout.externalagents.api import ops
from google3.walkabout.externalagents.api import robot
from google3.walkabout.externalagents.api import util
FLAGS = flags.FLAGS
for event in events.ALL:
flags.DEFINE_string('eventdef_' + event.type.lower(),
'',
'Event definition for the %s event' % event.type)
def handle_event(src, bot, e, w):
"""Handle an event by executing the source code src."""
globs = {'e': e, 'w': w, 'api': api, 'bot': bot,
'blip': blip, 'element': element, 'errors': errors,
'events': events, 'ops': ops, 'robot': robot,
'util': util}
exec src in globs
def run_bot(input_file, output_file):
"""Run a robot defined on the command line."""
cmdbot = robot.Robot('Commandline bot')
for event in events.ALL:
src = getattr(FLAGS, 'eventdef_' + event.type.lower())
src = urllib.unquote_plus(src)
if src:
cmdbot.register_handler(event,
lambda event, wavelet, src=src, bot=cmdbot:
handle_event(src, bot, event, wavelet))
json_body = unicode(input_file.read(), 'utf8')
json_response = cmdbot.process_events(json_body)
output_file.write(json_response)
def main(argv):
run_bot(sys.stdin, sys.stdout)
if __name__ == '__main__':
app.run()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the robot module."""
import unittest
import events
import ops
import robot
import simplejson
BLIP_JSON = ('{"wdykLROk*13":'
'{"lastModifiedTime":1242079608457,'
'"contributors":["someguy@test.com"],'
'"waveletId":"test.com!conv+root",'
'"waveId":"test.com!wdykLROk*11",'
'"parentBlipId":null,'
'"version":3,'
'"creator":"someguy@test.com",'
'"content":"\\nContent!",'
'"blipId":"wdykLROk*13","'
'annotations":[{"range":{"start":0,"end":1},'
'"name":"user/e/davidbyttow@google.com","value":"David"}],'
'"elements":{},'
'"childBlipIds":[]}'
'}')
WAVELET_JSON = ('{"lastModifiedTime":1242079611003,'
'"title":"A title",'
'"waveletId":"test.com!conv+root",'
'"rootBlipId":"wdykLROk*13",'
'"dataDocuments":null,'
'"creationTime":1242079608457,'
'"waveId":"test.com!wdykLROk*11",'
'"participants":["someguy@test.com","monty@appspot.com"],'
'"creator":"someguy@test.com",'
'"version":5}')
EVENTS_JSON = ('[{"timestamp":1242079611003,'
'"modifiedBy":"someguy@test.com",'
'"properties":{"participantsRemoved":[],'
'"participantsAdded":["monty@appspot.com"]},'
'"type":"WAVELET_PARTICIPANTS_CHANGED"}]')
TEST_JSON = '{"blips":%s,"wavelet":%s,"events":%s}' % (
BLIP_JSON, WAVELET_JSON, EVENTS_JSON)
NEW_WAVE_JSON = [{"data":
{"waveletId": "wavesandbox.com!conv+root",
"blipId": "b+LrODcLZkDlu", "waveId":
"wavesandbox.com!w+LrODcLZkDlt"},
"id": "op2"}]
NEW_WAVE_JSON_OLD = [{'data':
[{'data':
{'waveletId': 'googlewave.com!conv+root',
'blipId': 'b+VqQXQbZkCP1',
'waveId': 'googlewave.com!w+VqQXQbZkCP0'},
'id': 'wavelet.create1265055048410'}],
'id': 'op10'}];
class TestRobot(unittest.TestCase):
"""Tests for testing the basic parsing of json in robots."""
def setUp(self):
self.robot = robot.Robot('Testy')
def testCreateWave(self):
self.robot.submit = lambda x: NEW_WAVE_JSON
new_wave = self.robot.new_wave('wavesandbox.com', submit=True)
self.assertEqual('wavesandbox.com!w+LrODcLZkDlt', new_wave.wave_id)
self.robot.submit = lambda x: NEW_WAVE_JSON_OLD
new_wave = self.robot.new_wave('googlewave.com', submit=True)
self.assertEqual('googlewave.com!w+VqQXQbZkCP0', new_wave.wave_id)
def testEventParsing(self):
def check(event, wavelet):
# Test some basic properties; the rest should be covered by
# ops.CreateContext.
root = wavelet.root_blip
self.assertEqual(1, len(wavelet.blips))
self.assertEqual('wdykLROk*13', root.blip_id)
self.assertEqual('test.com!wdykLROk*11', root.wave_id)
self.assertEqual('test.com!conv+root', root.wavelet_id)
self.assertEqual('WAVELET_PARTICIPANTS_CHANGED', event.type)
self.assertEqual({'participantsRemoved': [],
'participantsAdded': ['monty@appspot.com']},
event.properties)
self.robot.test_called = True
self.robot.test_called = False
self.robot.register_handler(events.WaveletParticipantsChanged,
check)
json = self.robot.process_events(TEST_JSON)
self.assertTrue(self.robot.test_called)
operations = simplejson.loads(json)
# there should be one operation indicating the current version:
self.assertEqual(1, len(operations))
def testWrongEventsIgnored(self):
self.robot.test_called = True
def check(event, wavelet):
called = True
self.robot.test_called = False
self.robot.register_handler(events.BlipSubmitted,
check)
self.robot.process_events(TEST_JSON)
self.assertFalse(self.robot.test_called)
def testOperationParsing(self):
def check(event, wavelet):
wavelet.reply()
wavelet.title = 'new title'
wavelet.root_blip.append_markup('<b>Hello</b>')
self.robot.register_handler(events.WaveletParticipantsChanged,
check)
json = self.robot.process_events(TEST_JSON)
operations = simplejson.loads(json)
expected = set([ops.ROBOT_NOTIFY_CAPABILITIES_HASH,
ops.WAVELET_APPEND_BLIP,
ops.WAVELET_SET_TITLE,
ops.DOCUMENT_APPEND_MARKUP])
methods = [operation['method'] for operation in operations]
for method in methods:
self.assertTrue(method in expected)
expected.remove(method)
self.assertEquals(0, len(expected))
def testSerializeWavelets(self):
wavelet = self.robot.blind_wavelet(TEST_JSON)
serialized = wavelet.serialize()
unserialized = self.robot.blind_wavelet(serialized)
self.assertEquals(wavelet.creator, unserialized.creator)
self.assertEquals(wavelet.creation_time, unserialized.creation_time)
self.assertEquals(wavelet.last_modified_time,
unserialized.last_modified_time)
self.assertEquals(wavelet.root_blip.blip_id, unserialized.root_blip.blip_id)
self.assertEquals(wavelet.title, unserialized.title)
self.assertEquals(wavelet.wave_id, unserialized.wave_id)
self.assertEquals(wavelet.wavelet_id, unserialized.wavelet_id)
self.assertEquals(wavelet.domain, unserialized.domain)
def testProxiedBlindWavelet(self):
def handler(event, wavelet):
blind_wavelet = self.robot.blind_wavelet(TEST_JSON, 'proxyid')
blind_wavelet.reply()
blind_wavelet.submit_with(wavelet)
self.robot.register_handler(events.WaveletParticipantsChanged, handler)
json = self.robot.process_events(TEST_JSON)
operations = simplejson.loads(json)
self.assertEqual(2, len(operations))
self.assertEquals(ops.ROBOT_NOTIFY_CAPABILITIES_HASH,
operations[0]['method'])
self.assertEquals(ops.WAVELET_APPEND_BLIP, operations[1]['method'])
self.assertEquals('proxyid', operations[1]['params']['proxyingFor'])
def testCapabilitiesHashIncludesContextAndFilter(self):
robot1 = robot.Robot('Robot1')
robot1.register_handler(events.WaveletSelfAdded, lambda: '')
robot2 = robot.Robot('Robot2')
robot2.register_handler(events.WaveletSelfAdded, lambda: '',
context=events.Context.ALL)
self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash())
robot3 = robot.Robot('Robot3')
robot2.register_handler(events.WaveletSelfAdded, lambda: '',
context=events.Context.ALL, filter="foo")
self.assertNotEqual(robot1.capabilities_hash(), robot2.capabilities_hash())
self.assertNotEqual(robot1.capabilities_hash(), robot3.capabilities_hash())
self.assertNotEqual(robot2.capabilities_hash(), robot3.capabilities_hash())
class TestGetCapabilitiesXml(unittest.TestCase):
def setUp(self):
self.robot = robot.Robot('Testy')
self.robot.capabilities_hash = lambda: '1'
def assertStringsEqual(self, s1, s2):
self.assertEqual(s1, s2, 'Strings differ:\n%s--\n%s' % (s1, s2))
def testDefault(self):
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testUrls(self):
profile_robot = robot.Robot(
'Testy',
image_url='http://example.com/image.png',
profile_url='http://example.com/profile.xml')
profile_robot.capabilities_hash = lambda: '1'
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = profile_robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testConsumerKey(self):
# setup_oauth doesn't work during testing, so heavy handed setting of
# properties it is:
self.robot._consumer_key = 'consumer'
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:consumer_key>consumer</w:consumer_key>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n</w:capabilities>\n'
'</w:robot>\n') % ops.PROTOCOL_VERSION
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
def testCapsAndEvents(self):
self.robot.register_handler(events.BlipSubmitted, None,
context=[events.Context.SELF,
events.Context.ROOT])
expected = (
'<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>1</w:version>\n'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n'
' <w:capability name="%s" context="SELF,ROOT"/>\n'
'</w:capabilities>\n'
'</w:robot>\n') % (ops.PROTOCOL_VERSION, events.BlipSubmitted.type)
xml = self.robot.capabilities_xml()
self.assertStringsEqual(expected, xml)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the wavelet module."""
import unittest
import blip
import element
import ops
import wavelet
import simplejson
ROBOT_NAME = 'robot@appspot.com'
TEST_WAVELET_DATA = {
'creator': ROBOT_NAME,
'creationTime': 100,
'lastModifiedTime': 101,
'participants': [ROBOT_NAME],
'participantsRoles': {ROBOT_NAME: wavelet.Participants.ROLE_FULL},
'rootBlipId': 'blip-1',
'title': 'Title',
'waveId': 'test.com!w+g3h3im',
'waveletId': 'test.com!root+conv',
'tags': ['tag1', 'tag2'],
}
TEST_BLIP_DATA = {
'blipId': TEST_WAVELET_DATA['rootBlipId'],
'childBlipIds': [],
'content': '\ntesting',
'contributors': [TEST_WAVELET_DATA['creator'], 'robot@google.com'],
'creator': TEST_WAVELET_DATA['creator'],
'lastModifiedTime': TEST_WAVELET_DATA['lastModifiedTime'],
'parentBlipId': None,
'waveId': TEST_WAVELET_DATA['waveId'],
'elements': {},
'waveletId': TEST_WAVELET_DATA['waveletId'],
}
class TestWavelet(unittest.TestCase):
"""Tests the wavelet class."""
def setUp(self):
self.operation_queue = ops.OperationQueue()
self.all_blips = {}
self.blip = blip.Blip(TEST_BLIP_DATA,
self.all_blips,
self.operation_queue)
self.all_blips[self.blip.blip_id] = self.blip
self.wavelet = wavelet.Wavelet(TEST_WAVELET_DATA,
self.all_blips,
None,
self.operation_queue)
self.wavelet.robot_address = ROBOT_NAME
def testWaveletProperties(self):
w = self.wavelet
self.assertEquals(TEST_WAVELET_DATA['creator'], w.creator)
self.assertEquals(TEST_WAVELET_DATA['creationTime'], w.creation_time)
self.assertEquals(TEST_WAVELET_DATA['lastModifiedTime'],
w.last_modified_time)
self.assertEquals(len(TEST_WAVELET_DATA['participants']),
len(w.participants))
self.assertTrue(TEST_WAVELET_DATA['participants'][0] in w.participants)
self.assertEquals(TEST_WAVELET_DATA['rootBlipId'], w.root_blip.blip_id)
self.assertEquals(TEST_WAVELET_DATA['title'], w.title)
self.assertEquals(TEST_WAVELET_DATA['waveId'], w.wave_id)
self.assertEquals(TEST_WAVELET_DATA['waveletId'], w.wavelet_id)
self.assertEquals('test.com', w.domain)
def testWaveletMethods(self):
w = self.wavelet
reply = w.reply()
self.assertEquals(2, len(w.blips))
w.delete(reply)
self.assertEquals(1, len(w.blips))
self.assertEquals(0, len(w.data_documents))
self.wavelet.data_documents['key'] = 'value'
self.assert_('key' in w.data_documents)
self.assertEquals(1, len(w.data_documents))
for key in w.data_documents:
self.assertEquals(key, 'key')
self.assertEquals(1, len(w.data_documents.keys()))
self.wavelet.data_documents['key'] = None
self.assertEquals(0, len(w.data_documents))
num_participants = len(w.participants)
w.proxy_for('proxy').reply()
self.assertEquals(2, len(w.blips))
# check that the new proxy for participant was added
self.assertEquals(num_participants + 1, len(w.participants))
w._robot_address = ROBOT_NAME.replace('@', '+proxy@')
w.proxy_for('proxy').reply()
self.assertEquals(num_participants + 1, len(w.participants))
self.assertEquals(3, len(w.blips))
def testSetTitle(self):
self.blip._content = '\nOld title\n\nContent'
self.wavelet.title = 'New title \xd0\xb0\xd0\xb1\xd0\xb2'
self.assertEquals(1, len(self.operation_queue))
self.assertEquals('wavelet.setTitle',
self.operation_queue.serialize()[1]['method'])
self.assertEquals(u'\nNew title \u0430\u0431\u0432\n\nContent',
self.blip._content)
def testSetTitleAdjustRootBlipWithOneLineProperly(self):
self.blip._content = '\nOld title'
self.wavelet.title = 'New title'
self.assertEquals(1, len(self.operation_queue))
self.assertEquals('wavelet.setTitle',
self.operation_queue.serialize()[1]['method'])
self.assertEquals('\nNew title\n', self.blip._content)
def testSetTitleAdjustEmptyRootBlipProperly(self):
self.blip._content = '\n'
self.wavelet.title = 'New title'
self.assertEquals(1, len(self.operation_queue))
self.assertEquals('wavelet.setTitle',
self.operation_queue.serialize()[1]['method'])
self.assertEquals('\nNew title\n', self.blip._content)
def testTags(self):
w = self.wavelet
self.assertEquals(2, len(w.tags))
w.tags.append('tag3')
self.assertEquals(3, len(w.tags))
w.tags.append('tag3')
self.assertEquals(3, len(w.tags))
w.tags.remove('tag1')
self.assertEquals(2, len(w.tags))
self.assertEquals('tag2', w.tags[0])
def testParticipantRoles(self):
w = self.wavelet
self.assertEquals(wavelet.Participants.ROLE_FULL,
w.participants.get_role(ROBOT_NAME))
w.participants.set_role(ROBOT_NAME, wavelet.Participants.ROLE_READ_ONLY)
self.assertEquals(wavelet.Participants.ROLE_READ_ONLY,
w.participants.get_role(ROBOT_NAME))
def testSerialize(self):
self.blip.append(element.Gadget('http://test.com', {'a': 3}))
self.wavelet.title = 'A wavelet title'
self.blip.append(element.Image(url='http://www.google.com/logos/clickortreat1.gif',
width=320, height=118))
self.blip.append(element.Attachment(caption='fake', data='fake data'))
self.blip.append(element.Line(line_type='li', indent='2'))
self.blip.append('bulleted!')
self.blip.append(element.Installer(
'http://wave-skynet.appspot.com/public/extensions/areyouin/manifest.xml'))
self.wavelet.proxy_for('proxy').reply().append('hi from douwe')
inlineBlip = self.blip.insert_inline_blip(5)
inlineBlip.append('hello again!')
serialized = self.wavelet.serialize()
serialized = simplejson.dumps(serialized)
self.assertTrue(serialized.find('test.com') > 0)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Contains various API-specific exception classes.
This module contains various specific exception classes that are raised by
the library back to the client.
"""
class Error(Exception):
"""Base library error type."""
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Defines classes that are needed to model a wavelet."""
import blip
import errors
import util
class DataDocs(object):
"""Class modeling a bunch of data documents in pythonic way."""
def __init__(self, init_docs, wave_id, wavelet_id, operation_queue):
self._docs = init_docs
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __iter__(self):
return self._docs.__iter__()
def __contains__(self, key):
return key in self._docs
def __delitem__(self, key):
if not key in self._docs:
return
self._operation_queue.wavelet_datadoc_set(
self._wave_id, self._wavelet_id, key, None)
del self._docs[key]
def __getitem__(self, key):
return self._docs[key]
def __setitem__(self, key, value):
self._operation_queue.wavelet_datadoc_set(
self._wave_id, self._wavelet_id, key, value)
if value is None and key in self._docs:
del self._docs[key]
else:
self._docs[key] = value
def __len__(self):
return len(self._docs)
def keys(self):
return self._docs.keys()
def serialize(self):
"""Returns a dictionary of the data documents."""
return self._docs
class Participants(object):
"""Class modelling a set of participants in pythonic way."""
#: Designates full access (read/write) role.
ROLE_FULL = "FULL"
#: Designates read-only role.
ROLE_READ_ONLY = "READ_ONLY"
def __init__(self, participants, roles, wave_id, wavelet_id, operation_queue):
self._participants = set(participants)
self._roles = roles.copy()
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __contains__(self, participant):
return participant in self._participants
def __len__(self):
return len(self._participants)
def __iter__(self):
return self._participants.__iter__()
def add(self, participant_id):
"""Adds a participant by their ID (address)."""
self._operation_queue.wavelet_add_participant(
self._wave_id, self._wavelet_id, participant_id)
self._participants.add(participant_id)
def get_role(self, participant_id):
"""Return the role for the given participant_id."""
return self._roles.get(participant_id, Participants.ROLE_FULL)
def set_role(self, participant_id, role):
"""Sets the role for the given participant_id."""
if role != Participants.ROLE_FULL and role != Participants.ROLE_READ_ONLY:
raise ValueError(role + ' is not a valid role')
self._operation_queue.wavelet_modify_participant_role(
self._wave_id, self._wavelet_id, participant_id, role)
self._roles[participant_id] = role
def serialize(self):
"""Returns a list of the participants."""
return list(self._participants)
class Tags(object):
"""Class modelling a list of tags."""
def __init__(self, tags, wave_id, wavelet_id, operation_queue):
self._tags = list(tags)
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __getitem__(self, index):
return self._tags[index]
def __len__(self):
return len(self._tags)
def __iter__(self):
return self._tags.__iter__()
def append(self, tag):
"""Appends a tag if it doesn't already exist."""
tag = util.force_unicode(tag)
if tag in self._tags:
return
self._operation_queue.wavelet_modify_tag(
self._wave_id, self._wavelet_id, tag)
self._tags.append(tag)
def remove(self, tag):
"""Removes a tag if it exists."""
tag = util.force_unicode(tag)
if not tag in self._tags:
return
self._operation_queue.wavelet_modify_tag(
self._wave_id, self._wavelet_id, tag, modify_how='remove')
self._tags.remove(tag)
def serialize(self):
"""Returns a list of tags."""
return list(self._tags)
class Wavelet(object):
"""Models a single wavelet.
A single wavelet is composed of metadata, participants, and its blips.
To guarantee that all blips are available, specify Context.ALL for events.
"""
def __init__(self, json, blips, robot, operation_queue):
"""Inits this wavelet with JSON data.
Args:
json: JSON data dictionary from Wave server.
blips: a dictionary object that can be used to resolve blips.
robot: the robot owning this wavelet.
operation_queue: an OperationQueue object to be used to
send any generated operations to.
"""
self._robot = robot
self._operation_queue = operation_queue
self._wave_id = json.get('waveId')
self._wavelet_id = json.get('waveletId')
self._creator = json.get('creator')
self._creation_time = json.get('creationTime', 0)
self._data_documents = DataDocs(json.get('dataDocuments', {}),
self._wave_id,
self._wavelet_id,
operation_queue)
self._last_modified_time = json.get('lastModifiedTime')
self._participants = Participants(json.get('participants', []),
json.get('participantRoles', {}),
self._wave_id,
self._wavelet_id,
operation_queue)
self._title = json.get('title', '')
self._tags = Tags(json.get('tags', []),
self._wave_id,
self._wavelet_id,
operation_queue)
self._raw_data = json
self._blips = blip.Blips(blips)
self._root_blip_id = json.get('rootBlipId')
if self._root_blip_id and self._root_blip_id in self._blips:
self._root_blip = self._blips[self._root_blip_id]
else:
self._root_blip = None
self._robot_address = None
@property
def wavelet_id(self):
"""Returns this wavelet's id."""
return self._wavelet_id
@property
def wave_id(self):
"""Returns this wavelet's parent wave id."""
return self._wave_id
@property
def creator(self):
"""Returns the participant id of the creator of this wavelet."""
return self._creator
@property
def creation_time(self):
"""Returns the time that this wavelet was first created in milliseconds."""
return self._creation_time
@property
def data_documents(self):
"""Returns the data documents for this wavelet based on key name."""
return self._data_documents
@property
def domain(self):
"""Return the domain that wavelet belongs to."""
p = self._wave_id.find('!')
if p == -1:
return None
else:
return self._wave_id[:p]
@property
def last_modified_time(self):
"""Returns the time that this wavelet was last modified in ms."""
return self._last_modified_time
@property
def participants(self):
"""Returns a set of participants on this wavelet."""
return self._participants
@property
def tags(self):
"""Returns a list of tags for this wavelet."""
return self._tags
@property
def robot(self):
"""The robot that owns this wavelet."""
return self._robot
def _get_title(self):
return self._title
def _set_title(self, title):
title = util.force_unicode(title)
if title.find('\n') != -1:
raise errors.Error('Wavelet title should not contain a newline ' +
'character. Specified: ' + title)
self._operation_queue.wavelet_set_title(self.wave_id, self.wavelet_id,
title)
self._title = title
# Adjust the content of the root blip, if it is available in the context.
if self._root_blip:
content = '\n'
splits = self._root_blip._content.split('\n', 2)
if len(splits) == 3:
content += splits[2]
self._root_blip._content = '\n' + title + content
#: Returns or sets the wavelet's title.
title = property(_get_title, _set_title,
doc='Get or set the title of the wavelet.')
def _get_robot_address(self):
return self._robot_address
def _set_robot_address(self, address):
if self._robot_address:
raise errors.Error('robot address already set')
self._robot_address = address
robot_address = property(_get_robot_address, _set_robot_address,
doc='Get or set the address of the current robot.')
@property
def root_blip(self):
"""Returns this wavelet's root blip."""
return self._root_blip
@property
def blips(self):
"""Returns the blips for this wavelet."""
return self._blips
def get_operation_queue(self):
"""Returns the OperationQueue for this wavelet."""
return self._operation_queue
def serialize(self):
"""Return a dict of the wavelet properties."""
return {'waveId': self._wave_id,
'waveletId': self._wavelet_id,
'creator': self._creator,
'creationTime': self._creation_time,
'dataDocuments': self._data_documents.serialize(),
'lastModifiedTime': self._last_modified_time,
'participants': self._participants.serialize(),
'title': self._title,
'blips': self._blips.serialize(),
'rootBlipId': self._root_blip_id
}
def proxy_for(self, proxy_for_id):
"""Return a view on this wavelet that will proxy for the specified id.
A shallow copy of the current wavelet is returned with the proxy_for_id
set. Any modifications made to this copy will be done using the
proxy_for_id, i.e. the robot+<proxy_for_id>@appspot.com address will
be used.
If the wavelet was retrieved using the Active Robot API, that is
by fetch_wavelet, then the address of the robot must be added to the
wavelet by setting wavelet.robot_address before calling proxy_for().
"""
self.add_proxying_participant(proxy_for_id)
operation_queue = self.get_operation_queue().proxy_for(proxy_for_id)
res = Wavelet(json={},
blips={},
robot=self.robot,
operation_queue=operation_queue)
res._wave_id = self._wave_id
res._wavelet_id = self._wavelet_id
res._creator = self._creator
res._creation_time = self._creation_time
res._data_documents = self._data_documents
res._last_modified_time = self._last_modified_time
res._participants = self._participants
res._title = self._title
res._raw_data = self._raw_data
res._blips = self._blips
res._root_blip = self._root_blip
return res
def add_proxying_participant(self, id):
"""Ads a proxying participant to the wave.
Proxying participants are of the form robot+proxy@domain.com. This
convenience method constructs this id and then calls participants.add.
"""
if not self.robot_address:
raise errors.Error(
'Need a robot address to add a proxying for participant')
robotid, domain = self.robot_address.split('@', 1)
if '#' in robotid:
robotid, version = robotid.split('#')
else:
version = None
if '+' in robotid:
newid = robotid.split('+', 1)[0] + '+' + id
else:
newid = robotid + '+' + id
if version:
newid += '#' + version
newid += '@' + domain
self.participants.add(newid)
def submit_with(self, other_wavelet):
"""Submit this wavelet when the passed other wavelet is submited.
wavelets constructed outside of the event callback need to
be either explicitly submited using robot.submit(wavelet) or be
associated with a different wavelet that will be submited or
is part of the event callback.
"""
other_wavelet._operation_queue.copy_operations(self._operation_queue)
self._operation_queue = other_wavelet._operation_queue
def reply(self, initial_content=None):
"""Replies to the conversation in this wavelet.
Args:
initial_content: If set, start with this (string) content.
Returns:
A transient version of the blip that contains the reply.
"""
if not initial_content:
initial_content = u'\n'
initial_content = util.force_unicode(initial_content)
blip_data = self._operation_queue.wavelet_append_blip(
self.wave_id, self.wavelet_id, initial_content)
instance = blip.Blip(blip_data, self._blips, self._operation_queue)
self._blips._add(instance)
return instance
def delete(self, todelete):
"""Remove a blip from this wavelet.
Args:
todelete: either a blip or a blip id to be removed.
"""
if isinstance(todelete, blip.Blip):
blip_id = todelete.blip_id
else:
blip_id = todelete
self._operation_queue.blip_delete(self.wave_id, self.wavelet_id, blip_id)
self._blips._remove_with_id(blip_id)
| Python |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Tests for google3.walkabout.externalagents.api.commandline_robot_runner."""
__author__ = 'douwe@google.com (Douwe Osinga)'
import StringIO
from google3.pyglib import app
from google3.pyglib import flags
from google3.testing.pybase import googletest
from google3.walkabout.externalagents.api import commandline_robot_runner
from google3.walkabout.externalagents.api import events
FLAGS = flags.FLAGS
BLIP_JSON = ('{"wdykLROk*13":'
'{"lastModifiedTime":1242079608457,'
'"contributors":["someguy@test.com"],'
'"waveletId":"test.com!conv+root",'
'"waveId":"test.com!wdykLROk*11",'
'"parentBlipId":null,'
'"version":3,'
'"creator":"someguy@test.com",'
'"content":"\\nContent!",'
'"blipId":"wdykLROk*13",'
'"annotations":[{"range":{"start":0,"end":1},'
'"name":"user/e/otherguy@test.com","value":"Other"}],'
'"elements":{},'
'"childBlipIds":[]}'
'}')
WAVELET_JSON = ('{"lastModifiedTime":1242079611003,'
'"title":"A title",'
'"waveletId":"test.com!conv+root",'
'"rootBlipId":"wdykLROk*13",'
'"dataDocuments":null,'
'"creationTime":1242079608457,'
'"waveId":"test.com!wdykLROk*11",'
'"participants":["someguy@test.com","monty@appspot.com"],'
'"creator":"someguy@test.com",'
'"version":5}')
EVENTS_JSON = ('[{"timestamp":1242079611003,'
'"modifiedBy":"someguy@test.com",'
'"properties":{"participantsRemoved":[],'
'"participantsAdded":["monty@appspot.com"]},'
'"type":"WAVELET_PARTICIPANTS_CHANGED"}]')
TEST_JSON = '{"blips":%s,"wavelet":%s,"events":%s}' % (
BLIP_JSON, WAVELET_JSON, EVENTS_JSON)
class CommandlineRobotRunnerTest(googletest.TestCase):
def testSimpleFlow(self):
FLAGS.eventdef_wavelet_participants_changed = 'x'
flag = 'eventdef_' + events.WaveletParticipantsChanged.type.lower()
setattr(FLAGS, flag, 'w.title="New title!"')
input_stream = StringIO.StringIO(TEST_JSON)
output_stream = StringIO.StringIO()
commandline_robot_runner.run_bot(input_stream, output_stream)
res = output_stream.getvalue()
self.assertTrue('wavelet.setTitle' in res)
def main(unused_argv):
googletest.main()
if __name__ == '__main__':
app.run()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Script to run all unit tests in this package."""
import blip_test
import element_test
import module_test_runner
import ops_test
import robot_test
import util_test
import wavelet_test
def RunUnitTests():
"""Runs all registered unit tests."""
test_runner = module_test_runner.ModuleTestRunner()
test_runner.modules = [
blip_test,
element_test,
ops_test,
robot_test,
util_test,
wavelet_test,
]
test_runner.RunAllTests()
if __name__ == "__main__":
RunUnitTests()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the util module."""
__author__ = 'davidbyttow@google.com (David Byttow)'
import unittest
import ops
import util
class TestUtils(unittest.TestCase):
"""Tests utility functions."""
def testIsIterable(self):
self.assertTrue(util.is_iterable([]))
self.assertTrue(util.is_iterable({}))
self.assertTrue(util.is_iterable(set()))
self.assertTrue(util.is_iterable(()))
self.assertFalse(util.is_iterable(42))
self.assertFalse(util.is_iterable('list?'))
self.assertFalse(util.is_iterable(object))
def testIsDict(self):
self.assertFalse(util.is_dict([]))
self.assertTrue(util.is_dict({}))
self.assertFalse(util.is_dict(set()))
self.assertFalse(util.is_dict(()))
self.assertFalse(util.is_dict(42))
self.assertFalse(util.is_dict('dict?'))
self.assertFalse(util.is_dict(object))
def testIsUserDefinedNewStyleClass(self):
class OldClass:
pass
class NewClass(object):
pass
self.assertFalse(util.is_user_defined_new_style_class(OldClass()))
self.assertTrue(util.is_user_defined_new_style_class(NewClass()))
self.assertFalse(util.is_user_defined_new_style_class({}))
self.assertFalse(util.is_user_defined_new_style_class(()))
self.assertFalse(util.is_user_defined_new_style_class(42))
self.assertFalse(util.is_user_defined_new_style_class('instance?'))
def testLowerCamelCase(self):
self.assertEquals('foo', util.lower_camel_case('foo'))
self.assertEquals('fooBar', util.lower_camel_case('foo_bar'))
self.assertEquals('fooBar', util.lower_camel_case('fooBar'))
self.assertEquals('blipId', util.lower_camel_case('blip_id'))
self.assertEquals('fooBar', util.lower_camel_case('foo__bar'))
self.assertEquals('fooBarBaz', util.lower_camel_case('foo_bar_baz'))
self.assertEquals('f', util.lower_camel_case('f'))
self.assertEquals('f', util.lower_camel_case('f_'))
self.assertEquals('', util.lower_camel_case(''))
self.assertEquals('', util.lower_camel_case('_'))
self.assertEquals('aBCDEF', util.lower_camel_case('_a_b_c_d_e_f_'))
def assertListsEqual(self, a, b):
self.assertEquals(len(a), len(b))
for i in range(len(a)):
self.assertEquals(a[i], b[i])
def assertDictsEqual(self, a, b):
self.assertEquals(len(a.keys()), len(b.keys()))
for k, v in a.iteritems():
self.assertEquals(v, b[k])
def testSerializeList(self):
data = [1, 2, 3]
output = util.serialize(data)
self.assertListsEqual(data, output)
def testSerializeDict(self):
data = {'key': 'value', 'under_score': 'value2'}
expected = {'key': 'value', 'underScore': 'value2'}
output = util.serialize(data)
self.assertDictsEqual(expected, output)
def testNonNoneDict(self):
a = {'a': 1, 'b': 1}
self.assertDictsEqual(a, util.non_none_dict(a))
b = a.copy()
b['c'] = None
self.assertDictsEqual(a, util.non_none_dict(b))
def testForceUnicode(self):
self.assertEquals(u"aaa", util.force_unicode("aaa"))
self.assertEquals(u"12", util.force_unicode(12))
self.assertEquals(u"\u0430\u0431\u0432",
util.force_unicode("\xd0\xb0\xd0\xb1\xd0\xb2"))
self.assertEquals(u'\u30e6\u30cb\u30b3\u30fc\u30c9',
util.force_unicode(u'\u30e6\u30cb\u30b3\u30fc\u30c9'))
def testSerializeAttributes(self):
class Data(object):
def __init__(self):
self.public = 1
self._protected = 2
self.__private = 3
def Func(self):
pass
data = Data()
output = util.serialize(data)
# Functions and non-public fields should not be serialized.
self.assertEquals(1, len(output.keys()))
self.assertEquals(data.public, output['public'])
def testStringEnum(self):
util.StringEnum()
single = util.StringEnum('foo')
self.assertEquals('foo', single.foo)
multi = util.StringEnum('foo', 'bar')
self.assertEquals('foo', multi.foo)
self.assertEquals('bar', multi.bar)
def testParseMarkup(self):
self.assertEquals('foo', util.parse_markup('foo'))
self.assertEquals('foo bar', util.parse_markup('foo <b>bar</b>'))
self.assertEquals('foo\nbar', util.parse_markup('foo<br>bar'))
self.assertEquals('foo\nbar', util.parse_markup('foo<p indent="3">bar'))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Run robot from the commandline for testing.
This robot_runner let's you define event handlers using flags and takes the
json input from the std in and writes out the json output to stdout.
for example
cat events | commandline_robot_runner.py \
--eventdef-blip_submitted="wavelet.title='title'"
"""
__author__ = 'douwe@google.com (Douwe Osinga)'
import sys
import urllib
from google3.pyglib import app
from google3.pyglib import flags
from google3.walkabout.externalagents import api
from google3.walkabout.externalagents.api import blip
from google3.walkabout.externalagents.api import element
from google3.walkabout.externalagents.api import errors
from google3.walkabout.externalagents.api import events
from google3.walkabout.externalagents.api import ops
from google3.walkabout.externalagents.api import robot
from google3.walkabout.externalagents.api import util
FLAGS = flags.FLAGS
for event in events.ALL:
flags.DEFINE_string('eventdef_' + event.type.lower(),
'',
'Event definition for the %s event' % event.type)
def handle_event(src, bot, e, w):
"""Handle an event by executing the source code src."""
globs = {'e': e, 'w': w, 'api': api, 'bot': bot,
'blip': blip, 'element': element, 'errors': errors,
'events': events, 'ops': ops, 'robot': robot,
'util': util}
exec src in globs
def run_bot(input_file, output_file):
"""Run a robot defined on the command line."""
cmdbot = robot.Robot('Commandline bot')
for event in events.ALL:
src = getattr(FLAGS, 'eventdef_' + event.type.lower())
src = urllib.unquote_plus(src)
if src:
cmdbot.register_handler(event,
lambda event, wavelet, src=src, bot=cmdbot:
handle_event(src, bot, event, wavelet))
json_body = unicode(input_file.read(), 'utf8')
json_response = cmdbot.process_events(json_body)
output_file.write(json_response)
def main(argv):
run_bot(sys.stdin, sys.stdout)
if __name__ == '__main__':
app.run()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Support for operations that can be applied to the server.
Contains classes and utilities for creating operations that are to be
applied on the server.
"""
import errors
import random
import util
import sys
PROTOCOL_VERSION = '0.21'
# Operation Types
WAVELET_APPEND_BLIP = 'wavelet.appendBlip'
WAVELET_SET_TITLE = 'wavelet.setTitle'
WAVELET_ADD_PARTICIPANT = 'wavelet.participant.add'
WAVELET_DATADOC_SET = 'wavelet.datadoc.set'
WAVELET_MODIFY_TAG = 'wavelet.modifyTag'
WAVELET_MODIFY_PARTICIPANT_ROLE = 'wavelet.modifyParticipantRole'
BLIP_CREATE_CHILD = 'blip.createChild'
BLIP_DELETE = 'blip.delete'
DOCUMENT_APPEND_MARKUP = 'document.appendMarkup'
DOCUMENT_INLINE_BLIP_INSERT = 'document.inlineBlip.insert'
DOCUMENT_MODIFY = 'document.modify'
ROBOT_CREATE_WAVELET = 'robot.createWavelet'
ROBOT_FETCH_WAVE = 'robot.fetchWave'
ROBOT_NOTIFY_CAPABILITIES_HASH = 'robot.notifyCapabilitiesHash'
class Operation(object):
"""Represents a generic operation applied on the server.
This operation class contains data that is filled in depending on the
operation type.
It can be used directly, but doing so will not result
in local, transient reflection of state on the blips. In other words,
creating a 'delete blip' operation will not remove the blip from the local
context for the duration of this session. It is better to use the OpBased
model classes directly instead.
"""
def __init__(self, method, opid, params):
"""Initializes this operation with contextual data.
Args:
method: Method to call or type of operation.
opid: The id of the operation. Any callbacks will refer to these.
params: An operation type dependent dictionary
"""
self.method = method
self.id = opid
self.params = params
def __str__(self):
return '%s[%s]%s' % (self.method, self.id, str(self.params))
def set_param(self, param, value):
self.params[param] = value
return self
def serialize(self, method_prefix=''):
"""Serialize the operation.
Args:
method_prefix: prefixed for each method name to allow for specifying
a namespace.
Returns:
a dict representation of the operation.
"""
if method_prefix and not method_prefix.endswith('.'):
method_prefix += '.'
return {'method': method_prefix + self.method,
'id': self.id,
'params': util.serialize(self.params)}
def set_optional(self, param, value):
"""Sets an optional parameter.
If value is None or "", this is a no op. Otherwise it calls
set_param.
"""
if value == '' or value is None:
return self
else:
return self.set_param(param, value)
class OperationQueue(object):
"""Wraps the queuing of operations using easily callable functions.
The operation queue wraps single operations as functions and queues the
resulting operations in-order. Typically there shouldn't be a need to
call this directly unless operations are needed on entities outside
of the scope of the robot. For example, to modify a blip that
does not exist in the current context, you might specify the wave, wavelet
and blip id to generate an operation.
Any calls to this will not be reflected in the robot in any way.
For example, calling wavelet_append_blip will not result in a new blip
being added to the robot, only an operation to be applied on the
server.
"""
# Some class global counters:
_next_operation_id = 1
def __init__(self, proxy_for_id=None):
self.__pending = []
self._capability_hash = 0
self._proxy_for_id = proxy_for_id
def _new_blipdata(self, wave_id, wavelet_id, initial_content='',
parent_blip_id=None):
"""Creates JSON of the blip used for this session."""
temp_blip_id = 'TBD_%s_%s' % (wavelet_id,
hex(random.randint(0, sys.maxint)))
return {'waveId': wave_id,
'waveletId': wavelet_id,
'blipId': temp_blip_id,
'content': initial_content,
'parentBlipId': parent_blip_id}
def _new_waveletdata(self, domain, participants):
"""Creates an ephemeral WaveletData instance used for this session.
Args:
domain: the domain to create the data for.
participants initially on the wavelet
Returns:
Blipdata (for the rootblip), WaveletData.
"""
wave_id = domain + '!TBD_%s' % hex(random.randint(0, sys.maxint))
wavelet_id = domain + '!conv+root'
root_blip_data = self._new_blipdata(wave_id, wavelet_id)
participants = set(participants)
wavelet_data = {'waveId': wave_id,
'waveletId': wavelet_id,
'rootBlipId': root_blip_data['blipId'],
'participants': participants}
return root_blip_data, wavelet_data
def __len__(self):
return len(self.__pending)
def __iter__(self):
return self.__pending.__iter__()
def clear(self):
self.__pending = []
def proxy_for(self, proxy):
"""Return a view of this operation queue with the proxying for set to proxy.
This method returns a new instance of an operation queue that shares the
operation list, but has a different proxying_for_id set so the robot using
this new queue will send out operations with the proxying_for field set.
"""
res = OperationQueue()
res.__pending = self.__pending
res._capability_hash = self._capability_hash
res._proxy_for_id = proxy
return res
def set_capability_hash(self, capability_hash):
self._capability_hash = capability_hash
def serialize(self):
first = Operation(ROBOT_NOTIFY_CAPABILITIES_HASH,
'0',
{'capabilitiesHash': self._capability_hash,
'protocolVersion': PROTOCOL_VERSION})
operations = [first] + self.__pending
res = util.serialize(operations)
return res
def copy_operations(self, other_queue):
"""Copy the pending operations from other_queue into this one."""
for op in other_queue:
self.__pending.append(op)
def new_operation(self, method, wave_id, wavelet_id, props=None, **kwprops):
"""Creates and adds a new operation to the operation list."""
if props is None:
props = {}
props.update(kwprops)
props['waveId'] = wave_id
props['waveletId'] = wavelet_id
if self._proxy_for_id:
props['proxyingFor'] = self._proxy_for_id
operation = Operation(method,
'op%s' % OperationQueue._next_operation_id,
props)
self.__pending.append(operation)
OperationQueue._next_operation_id += 1
return operation
def wavelet_append_blip(self, wave_id, wavelet_id, initial_content=''):
"""Appends a blip to a wavelet.
Args:
wave_id: The wave id owning the containing wavelet.
wavelet_id: The wavelet id that this blip should be appended to.
initial_content: optionally the content to start with
Returns:
JSON representing the information of the new blip.
"""
blip_data = self._new_blipdata(wave_id, wavelet_id, initial_content)
self.new_operation(WAVELET_APPEND_BLIP, wave_id,
wavelet_id, blipData=blip_data)
return blip_data
def wavelet_add_participant(self, wave_id, wavelet_id, participant_id):
"""Adds a participant to a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
participant_id: Id of the participant to add.
Returns:
data for the root_blip, wavelet
"""
return self.new_operation(WAVELET_ADD_PARTICIPANT, wave_id, wavelet_id,
participantId=participant_id)
def wavelet_datadoc_set(self, wave_id, wavelet_id, name, data):
"""Sets a key/value pair on the data document of a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
name: The key name for this data.
data: The value of the data to set.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_DATADOC_SET, wave_id, wavelet_id,
datadocName=name, datadocValue=data)
def robot_create_wavelet(self, domain, participants=None, message=''):
"""Creates a new wavelet.
Args:
domain: the domain to create the wave in
participants: initial participants on this wavelet or None if none
message: an optional payload that is returned with the corresponding
event.
Returns:
data for the root_blip, wavelet
"""
if participants is None:
participants = []
blip_data, wavelet_data = self._new_waveletdata(domain, participants)
op = self.new_operation(ROBOT_CREATE_WAVELET,
wave_id=wavelet_data['waveId'],
wavelet_id=wavelet_data['waveletId'],
waveletData=wavelet_data)
op.set_optional('message', message)
return blip_data, wavelet_data
def robot_fetch_wave(self, wave_id, wavelet_id):
"""Requests a snapshot of the specified wave.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(ROBOT_FETCH_WAVE, wave_id, wavelet_id)
def wavelet_set_title(self, wave_id, wavelet_id, title):
"""Sets the title of a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
title: The title to set.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_SET_TITLE, wave_id, wavelet_id,
waveletTitle=title)
def wavelet_modify_participant_role(
self, wave_id, wavelet_id, participant_id, role):
"""Modify the role of a participant on a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
participant_id: Id of the participant to add.
role: the new roles
Returns:
data for the root_blip, wavelet
"""
return self.new_operation(WAVELET_MODIFY_PARTICIPANT_ROLE, wave_id,
wavelet_id, participantId=participant_id,
participantRole=role)
def wavelet_modify_tag(self, wave_id, wavelet_id, tag, modify_how=None):
"""Modifies a tag in a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
tag: The tag (a string).
modify_how: (optional) how to apply the tag. The default is to add
the tag. Specify 'remove' to remove. Specify None or 'add' to
add.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_MODIFY_TAG, wave_id, wavelet_id,
name=tag).set_optional("modify_how", modify_how)
def blip_create_child(self, wave_id, wavelet_id, blip_id):
"""Creates a child blip of another blip.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
JSON of blip for which further operations can be applied.
"""
blip_data = self._new_blipdata(wave_id, wavelet_id, parent_blip_id=blip_id)
self.new_operation(BLIP_CREATE_CHILD, wave_id, wavelet_id,
blipId=blip_id,
blipData=blip_data)
return blip_data
def blip_delete(self, wave_id, wavelet_id, blip_id):
"""Deletes the specified blip.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(BLIP_DELETE, wave_id, wavelet_id, blipId=blip_id)
def document_append_markup(self, wave_id, wavelet_id, blip_id, content):
"""Appends content with markup to a document.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
content: The markup content to append.
Returns:
The operation created.
"""
return self.new_operation(DOCUMENT_APPEND_MARKUP, wave_id, wavelet_id,
blipId=blip_id, content=content)
def document_modify(self, wave_id, wavelet_id, blip_id):
"""Creates and queues a document modify operation
The returned operation still needs to be filled with details before
it makes sense.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(DOCUMENT_MODIFY,
wave_id,
wavelet_id,
blipId=blip_id)
def document_inline_blip_insert(self, wave_id, wavelet_id, blip_id, position):
"""Inserts an inline blip at a specific location.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
position: The position in the document to insert the blip.
Returns:
JSON data for the blip that was created for further operations.
"""
inline_blip_data = self._new_blipdata(wave_id, wavelet_id)
inline_blip_data['parentBlipId'] = blip_id
self.new_operation(DOCUMENT_INLINE_BLIP_INSERT, wave_id, wavelet_id,
blipId=blip_id,
index=position,
blipData=inline_blip_data)
return inline_blip_data
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""A module to run wave robots on app engine."""
import logging
import sys
import events
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class CapabilitiesHandler(webapp.RequestHandler):
"""Handler to forward a request ot a handler of a robot."""
def __init__(self, method, contenttype):
"""Initializes this handler with a specific robot."""
self._method = method
self._contenttype = contenttype
def get(self):
"""Handles HTTP GET request."""
self.response.headers['Content-Type'] = self._contenttype
self.response.out.write(self._method())
class ProfileHandler(webapp.RequestHandler):
"""Handler to forward a request ot a handler of a robot."""
def __init__(self, method, contenttype):
"""Initializes this handler with a specific robot."""
self._method = method
self._contenttype = contenttype
def get(self):
"""Handles HTTP GET request."""
self.response.headers['Content-Type'] = self._contenttype
# Respond with proxied profile if name specified
if self.request.get('name'):
self.response.out.write(self._method(self.request.get('name')))
else:
self.response.out.write(self._method())
class RobotEventHandler(webapp.RequestHandler):
"""Handler for the dispatching of events to various handlers to a robot.
This handler only responds to post events with a JSON post body. Its primary
task is to separate out the context data from the events in the post body
and dispatch all events in order. Once all events have been dispatched
it serializes the context data and its associated operations as a response.
"""
def __init__(self, robot):
"""Initializes self with a specific robot."""
self._robot = robot
def get(self):
"""Handles the get event for debugging.
This is useful for debugging but since event bundles tend to be
rather big it often won't fit for more complex requests.
"""
ops = self.request.get('events')
if ops:
self.request.body = events
self.post()
def post(self):
"""Handles HTTP POST requests."""
json_body = self.request.body
if not json_body:
# TODO(davidbyttow): Log error?
return
# Redirect stdout to stderr while executing handlers. This way, any stray
# "print" statements in bot code go to the error logs instead of breaking
# the JSON response sent to the HTTP channel.
saved_stdout, sys.stdout = sys.stdout, sys.stderr
json_body = unicode(json_body, 'utf8')
logging.info('Incoming: %s', json_body)
json_response = self._robot.process_events(json_body)
logging.info('Outgoing: %s', json_response)
sys.stdout = saved_stdout
# Build the response.
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write(json_response.encode('utf-8'))
def operation_error_handler(event, wavelet):
"""Default operation error handler, logging what went wrong."""
if isinstance(event, events.OperationError):
logging.error('Previously operation failed: id=%s, message: %s',
event.operation_id, event.error_message)
def appengine_post(url, data, headers):
result = urlfetch.fetch(
method='POST',
url=url,
payload=data,
headers=headers,
deadline=10)
return result.status_code, result.content
class RobotVerifyTokenHandler(webapp.RequestHandler):
"""Handler for the token_verify request."""
def __init__(self, robot):
"""Initializes self with a specific robot."""
self._robot = robot
def get(self):
"""Handles the get event for debugging. Ops usually too long."""
token, st = self._robot.get_verification_token_info()
logging.info('token=' + token)
if token is None:
self.error(404)
self.response.out.write('No token set')
return
if not st is None:
if self.request.get('st') != st:
self.response.out.write('Invalid st value passed')
return
self.response.out.write(token)
def create_robot_webapp(robot, debug=False, extra_handlers=None):
"""Returns an instance of webapp.WSGIApplication with robot handlers."""
if not extra_handlers:
extra_handlers = []
return webapp.WSGIApplication([('.*/_wave/capabilities.xml',
lambda: CapabilitiesHandler(
robot.capabilities_xml,
'application/xml')),
('.*/_wave/robot/profile',
lambda: ProfileHandler(
robot.profile_json,
'application/json')),
('.*/_wave/robot/jsonrpc',
lambda: RobotEventHandler(robot)),
('.*/_wave/verify_token',
lambda: RobotVerifyTokenHandler(robot)),
] + extra_handlers,
debug=debug)
def run(robot, debug=False, log_errors=True, extra_handlers=None):
"""Sets up the webapp handlers for this robot and starts listening.
A robot is typically setup in the following steps:
1. Instantiate and define robot.
2. Register various handlers that it is interested in.
3. Call Run, which will setup the handlers for the app.
For example:
robot = Robot('Terminator',
image_url='http://www.sky.net/models/t800.png',
profile_url='http://www.sky.net/models/t800.html')
robot.register_handler(WAVELET_PARTICIPANTS_CHANGED, KillParticipant)
run(robot)
Args:
robot: the robot to run. This robot is modified to use app engines
urlfetch for posting http.
debug: Optional variable that defaults to False and is passed through
to the webapp application to determine if it should show debug info.
log_errors: Optional flag that defaults to True and determines whether
a default handlers to catch errors should be setup that uses the
app engine logging to log errors.
extra_handlers: Optional list of tuples that are passed to the webapp
to install more handlers. For example, passing
[('/about', AboutHandler),] would install an extra about handler
for the robot.
"""
# App Engine expects to construct a class with no arguments, so we
# pass a lambda that constructs the appropriate handler with
# arguments from the enclosing scope.
if log_errors:
robot.register_handler(events.OperationError, operation_error_handler)
robot.http_post = appengine_post
app = create_robot_webapp(robot, debug, extra_handlers)
run_wsgi_app(app)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Unit tests for the ops module."""
import unittest
import ops
class TestOperation(unittest.TestCase):
"""Test case for Operation class."""
def testFields(self):
op = ops.Operation(ops.WAVELET_SET_TITLE, 'opid02',
{'waveId': 'wavelet-id',
'title': 'a title'})
self.assertEqual(ops.WAVELET_SET_TITLE, op.method)
self.assertEqual('opid02', op.id)
self.assertEqual(2, len(op.params))
def testConstructModifyTag(self):
q = ops.OperationQueue()
op = q.wavelet_modify_tag('waveid', 'waveletid', 'tag')
self.assertEqual(3, len(op.params))
op = q.wavelet_modify_tag(
'waveid', 'waveletid', 'tag', modify_how='remove')
self.assertEqual(4, len(op.params))
def testConstructRobotFetchWave(self):
q = ops.OperationQueue('proxyid')
op = q.robot_fetch_wave('wave1', 'wavelet1')
self.assertEqual(3, len(op.params))
self.assertEqual('proxyid', op.params['proxyingFor'])
self.assertEqual('wave1', op.params['waveId'])
self.assertEqual('wavelet1', op.params['waveletId'])
class TestOperationQueue(unittest.TestCase):
"""Test case for OperationQueue class."""
def testSerialize(self):
q = ops.OperationQueue()
q.set_capability_hash('hash')
op = q.wavelet_modify_tag('waveid', 'waveletid', 'tag')
json = q.serialize()
self.assertEqual(2, len(json))
self.assertEqual('robot.notifyCapabilitiesHash', json[0]['method'])
self.assertEqual('hash', json[0]['params']['capabilitiesHash'])
self.assertEqual(ops.PROTOCOL_VERSION, json[0]['params']['protocolVersion'])
self.assertEqual('wavelet.modifyTag', json[1]['method'])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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 library containing various helpers used by the API."""
import re
CUSTOM_SERIALIZE_METHOD_NAME = 'serialize'
MARKUP_RE = re.compile(r'<([^>]*?)>')
def force_unicode(object):
""" Return the Unicode string version of object, with UTF-8 encoding. """
if isinstance(object, unicode):
return object
return unicode(str(object), 'utf-8')
def parse_markup(markup):
"""Parses a bit of markup into robot compatible text.
For now this is a rough approximation.
"""
def replace_tag(group):
if not group.groups:
return ''
tag = group.groups()[0].split(' ', 1)[0]
if (tag == 'p' or tag == 'br'):
return '\n'
return ''
return MARKUP_RE.sub(replace_tag, markup)
def is_iterable(inst):
"""Returns whether or not this is a list, tuple, set or dict .
Note that this does not return true for strings.
"""
return hasattr(inst, '__iter__')
def is_dict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems')
def is_user_defined_new_style_class(obj):
"""Returns whether or not the specified instance is a user-defined type."""
return type(obj).__module__ != '__builtin__'
def lower_camel_case(s):
"""Converts a string to lower camel case.
Examples:
foo => foo
foo_bar => fooBar
foo__bar => fooBar
foo_bar_baz => fooBarBaz
Args:
s: The string to convert to lower camel case.
Returns:
The lower camel cased string.
"""
return reduce(lambda a, b: a + (a and b.capitalize() or b), s.split('_'))
def non_none_dict(d):
"""return a copy of the dictionary without none values."""
return dict([a for a in d.items() if not a[1] is None])
def _serialize_attributes(obj):
"""Serializes attributes of an instance.
Iterates all attributes of an object and invokes serialize if they are
public and not callable.
Args:
obj: The instance to serialize.
Returns:
The serialized object.
"""
data = {}
for attr_name in dir(obj):
if attr_name.startswith('_'):
continue
attr = getattr(obj, attr_name)
if attr is None or callable(attr):
continue
# Looks okay, serialize it.
data[lower_camel_case(attr_name)] = serialize(attr)
return data
def _serialize_dict(d):
"""Invokes serialize on all of its key/value pairs.
Args:
d: The dict instance to serialize.
Returns:
The serialized dict.
"""
data = {}
for k, v in d.items():
data[lower_camel_case(k)] = serialize(v)
return data
def serialize(obj):
"""Serializes any instance.
If this is a user-defined instance
type, it will first check for a custom Serialize() function and use that
if it exists. Otherwise, it will invoke serialize all of its public
attributes. Lists and dicts are serialized trivially.
Args:
obj: The instance to serialize.
Returns:
The serialized object.
"""
if is_user_defined_new_style_class(obj):
if obj and hasattr(obj, CUSTOM_SERIALIZE_METHOD_NAME):
method = getattr(obj, CUSTOM_SERIALIZE_METHOD_NAME)
if callable(method):
return method()
return _serialize_attributes(obj)
elif is_dict(obj):
return _serialize_dict(obj)
elif is_iterable(obj):
return [serialize(v) for v in obj]
return obj
class StringEnum(object):
"""Enum like class that is configured with a list of values.
This class effectively implements an enum for Elements, except for that
the actual values of the enums will be the string values.
"""
def __init__(self, *values):
for name in values:
setattr(self, name, name)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Declares the api package."""
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Defines the generic robot classes.
This module provides the Robot class and RobotListener interface,
as well as some helper functions for web requests and responses.
"""
import base64
import logging
import sys
try:
__import__('google3') # setup internal test environment
except ImportError:
pass
import simplejson
import blip
import events
import ops
import util
import wavelet
import errors
# We only import oauth when we need it
oauth = None
DEFAULT_PROFILE_URL = (
'http://code.google.com/apis/wave/extensions/robots/python-tutorial.html')
class Robot(object):
"""Robot metadata class.
This class holds on to basic robot information like the name and profile.
It also maintains the list of event handlers and cron jobs and
dispatches events to the appropriate handlers.
"""
def __init__(self, name, image_url='', profile_url=DEFAULT_PROFILE_URL):
"""Initializes self with robot information.
Args:
name: The name of the robot
image_url: (optional) url of an image that should be used as the avatar
for this robot.
profile_url: (optional) url of a webpage with more information about
this robot.
"""
self._handlers = {}
self._name = name
self._verification_token = None
self._st = None
self._consumer_key = None
self._consumer_secret = None
self._server_rpc_base = None
self._profile_handler = None
self._image_url = image_url
self._profile_url = profile_url
self._capability_hash = 0
@property
def name(self):
"""Returns the name of the robot."""
return self._name
@property
def image_url(self):
"""Returns the URL of the avatar image."""
return self._image_url
@property
def profile_url(self):
"""Returns the URL of an info page for the robot."""
return self._profile_url
def http_post(self, url, data, headers):
"""Execute an http post.
Monkey patch this method to use something other than
the default urllib.
Args:
url: to post to
body: post body
headers: extra headers to pass along
Returns:
response_code, returned_page
"""
import urllib2
req = urllib2.Request(url,
data=data,
headers=headers)
try:
f = urllib2.urlopen(req)
return f.code, f.read()
except urllib2.URLError, e:
return e.code, e.read()
def get_verification_token_info(self):
"""Returns the verification token and ST parameter."""
return self._verification_token, self._st
def capabilities_hash(self):
"""Return the capabilities hash as a hex string."""
return hex(self._capability_hash)
def register_handler(self, event_class, handler, context=None, filter=None):
"""Registers a handler on a specific event type.
Multiple handlers may be registered on a single event type and are
guaranteed to be called in order of registration.
The handler takes two arguments, the event object and the corresponding
wavelet.
Args:
event_class: An event to listen for from the classes defined in the
events module.
handler: A function handler which takes two arguments, the wavelet for
the event and the event object.
context: The context to provide for this handler.
filter: Depending on the event, a filter can be specified that restricts
for which values the event handler will be called from the server.
Valuable to restrict the amount of traffic send to the robot.
"""
payload = (handler, event_class, context, filter)
self._handlers.setdefault(event_class.type, []).append(payload)
if type(context) == list:
context = ','.join(context)
self._capability_hash = (self._capability_hash * 13 +
hash(event_class.type) +
hash(context) +
hash(filter)) & 0xfffffff
def set_verification_token_info(self, token, st=None):
"""Set the verification token used in the ownership verification.
/wave/robot/register starts this process up and will produce this token.
Args:
token: the token provided by /wave/robot/register.
st: optional parameter to verify the request for the token came from
the wave server.
"""
self._verification_token = token
self._st = st
def setup_oauth(self, consumer_key, consumer_secret,
server_rpc_base='http://gmodules.com/api/rpc'):
"""Configure this robot to use the oauth'd json rpc.
Args:
consumer_key: consumer key received from the verification process.
consumer_secret: secret received from the verification process.
server_rpc_base: url of the rpc gateway to use. Specify None for default.
For wave preview, http://gmodules.com/api/rpc should be used.
For wave sandbox, http://sandbox.gmodules.com/api/rpc should be used.
"""
# Import oauth inline and using __import__ for pyexe compatibility
# when oauth is not installed.
global oauth
__import__('waveapi.oauth')
oauth = sys.modules['waveapi.oauth']
self._server_rpc_base = server_rpc_base
self._consumer_key = consumer_key
self._consumer_secret = consumer_secret
self._oauth_signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
self._oauth_consumer = oauth.OAuthConsumer(self._consumer_key,
self._consumer_secret)
def register_profile_handler(self, handler):
"""Sets the profile handler for this robot.
The profile handler will be called when a profile is needed. The handler
gets passed the name for which a profile is needed or None for the
robot itself. A dictionary with keys for name, imageUrl and
profileUrl should be returned.
"""
self._profile_handler = handler
def _hash(self, value):
"""return b64encoded sha1 hash of value."""
try:
hashlib = __import__('hashlib') # 2.5
hashed = hashlib.sha1(value)
except ImportError:
import sha # deprecated
hashed = sha.sha(value)
return base64.b64encode(hashed.digest())
def make_rpc(self, operations):
"""Make an rpc call, submitting the specified operations."""
if not oauth or not self._oauth_consumer.key:
raise errors.Error('OAuth has not been configured')
if (not type(operations) == list and
not isinstance(operations, ops.OperationQueue)):
operations = [operations]
rpcs = [op.serialize(method_prefix='wave') for op in operations]
post_body = simplejson.dumps(rpcs)
body_hash = self._hash(post_body)
params = {
'oauth_consumer_key': 'google.com:' + self._oauth_consumer.key,
'oauth_timestamp': oauth.generate_timestamp(),
'oauth_nonce': oauth.generate_nonce(),
'oauth_version': oauth.OAuthRequest.version,
'oauth_body_hash': body_hash,
}
oauth_request = oauth.OAuthRequest.from_request('POST',
self._server_rpc_base,
parameters=params)
oauth_request.sign_request(self._oauth_signature_method,
self._oauth_consumer,
None)
code, content = self.http_post(
url=oauth_request.to_url(),
data=post_body,
headers={'Content-Type': 'application/json'})
logging.info('Active URL: %s' % oauth_request.to_url())
logging.info('Active Outgoing: %s' % post_body)
if code != 200:
logging.info(oauth_request.to_url())
logging.info(content)
raise IOError('HttpError ' + str(code))
return simplejson.loads(content)
def _first_rpc_result(self, result):
"""result is returned from make_rpc. Get the first data record
or throw an exception if it was an error."""
if type(result) == list:
result = result[0]
error = result.get('error')
if error:
raise errors.Error('RPC Error' + str(error['code'])
+ ': ' + error['message'])
data = result.get('data')
if data:
return data
raise errors.Error('RPC Error: No data record.')
def capabilities_xml(self):
"""Return this robot's capabilities as an XML string."""
lines = []
for capability, payloads in self._handlers.items():
for payload in payloads:
handler, event_class, context, filter = payload
line = ' <w:capability name="%s"' % capability
if context:
if type(context) == list:
context = ','.join(context)
line += ' context="%s"' % context
if filter:
line += ' filter="%s"' % filter
line += '/>\n'
lines.append(line)
if self._consumer_key:
oauth_tag = '<w:consumer_key>%s</w:consumer_key>\n' % self._consumer_key
else:
oauth_tag = ''
return ('<?xml version="1.0"?>\n'
'<w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0">\n'
'<w:version>%s</w:version>\n'
'%s'
'<w:protocolversion>%s</w:protocolversion>\n'
'<w:capabilities>\n'
'%s'
'</w:capabilities>\n'
'</w:robot>\n') % (self.capabilities_hash(),
oauth_tag,
ops.PROTOCOL_VERSION,
'\n'.join(lines))
def profile_json(self, name=None):
"""Returns a JSON representation of the profile.
This method is called both for the basic profile of the robot and to
get a proxying for profile, in which case name is set. By default
the information supplied at registration is returned.
Use register_profile_handler to override this default behavior.
"""
if self._profile_handler:
data = self._profile_handler(name)
else:
data = {'name': self.name,
'imageUrl': self.image_url,
'profileUrl': self.profile_url}
return simplejson.dumps(data)
def _wavelet_from_json(self, json, pending_ops):
"""Construct a wavelet from the passed json.
The json should either contain a wavelet and a blips record that
define those respective object. The returned wavelet
will be constructed using the passed pending_ops
OperationQueue.
Alternatively the json can be the result of a previous
wavelet.serialize() call. In that case the blips will
be contaned in the wavelet record.
"""
if isinstance(json, basestring):
json = simplejson.loads(json)
blips = {}
for blip_id, raw_blip_data in json['blips'].items():
blips[blip_id] = blip.Blip(raw_blip_data, blips, pending_ops)
if 'wavelet' in json:
raw_wavelet_data = json['wavelet']
elif 'waveletData' in json:
raw_wavelet_data = json['waveletData']
else:
raw_wavelet_data = json
wavelet_blips = {}
wavelet_id = raw_wavelet_data['waveletId']
wave_id = raw_wavelet_data['waveId']
for blip_id, instance in blips.items():
if instance.wavelet_id == wavelet_id and instance.wave_id == wave_id:
wavelet_blips[blip_id] = instance
result = wavelet.Wavelet(raw_wavelet_data, wavelet_blips, self, pending_ops)
robot_address = json.get('robotAddress')
if robot_address:
result.robot_address = robot_address
return result
def process_events(self, json):
"""Process an incoming set of events encoded as json."""
parsed = simplejson.loads(json)
pending_ops = ops.OperationQueue()
event_wavelet = self._wavelet_from_json(parsed, pending_ops)
for event_data in parsed['events']:
for payload in self._handlers.get(event_data['type'], []):
handler, event_class, context, filter = payload
event = event_class(event_data, event_wavelet)
handler(event, event_wavelet)
pending_ops.set_capability_hash(self.capabilities_hash())
return simplejson.dumps(pending_ops.serialize())
def new_wave(self, domain, participants=None, message='', proxy_for_id=None,
submit=False):
"""Create a new wave with the initial participants on it.
A new wave is returned with its own operation queue. It the
responsibility of the caller to make sure this wave gets
submitted to the server, either by calling robot.submit() or
by calling .submit_with() on the returned wave.
Args:
domain: the domain to create the wavelet on. This should
in general correspond to the domain of the incoming
wavelet. (wavelet.domain). Exceptions are situations
where the robot is calling new_wave outside of an
event or when the server is handling multiple domains.
participants: initial participants on the wave. The robot
as the creator of the wave is always added.
message: a string that will be passed back to the robot
when the WAVELET_CREATOR event is fired. This is a
lightweight way to pass around state.
submit: if true, use the active gateway to make a round
trip to the server. This will return immediately an
actual waveid/waveletid and blipId for the root blip.
"""
operation_queue = ops.OperationQueue(proxy_for_id)
if not isinstance(message, basestring):
message = simplejson.dumps(message)
blip_data, wavelet_data = operation_queue.robot_create_wavelet(
domain=domain,
participants=participants,
message=message)
blips = {}
root_blip = blip.Blip(blip_data, blips, operation_queue)
blips[root_blip.blip_id] = root_blip
created = wavelet.Wavelet(wavelet_data,
blips=blips,
robot=self,
operation_queue=operation_queue)
if submit:
result = self._first_rpc_result(self.submit(created))
if type(result) == list:
result = result[0]
# Currently, data is sometimes wrapped in an outer 'data'
# Remove these 2 lines when that is no longer an issue.
if 'data' in result and len(result) == 2:
result = result['data']
if 'blipId' in result:
blip_data['blipId'] = result['blipId']
wavelet_data['rootBlipId'] = result['blipId']
for field in 'waveId', 'waveletId':
if field in result:
wavelet_data[field] = result[field]
blip_data[field] = result[field]
blips = {}
root_blip = blip.Blip(blip_data, blips, operation_queue)
blips[root_blip.blip_id] = root_blip
created = wavelet.Wavelet(wavelet_data,
blips=blips,
robot=self,
operation_queue=operation_queue)
return created
def fetch_wavelet(self, wave_id, wavelet_id, proxy_for_id=None):
"""Use the REST interface to fetch a wave and return it.
The returned wavelet contains a snapshot of the state of the
wavelet at that point. It can be used to modify the wavelet,
but the wavelet might change in between, so treat carefully.
Also note that the wavelet returned has its own operation
queue. It the responsibility of the caller to make sure this
wavelet gets submited to the server, either by calling
robot.submit() or by calling .submit_with() on the returned
wavelet.
"""
operation_queue = ops.OperationQueue(proxy_for_id)
operation_queue.robot_fetch_wave(wave_id, wavelet_id)
result = self._first_rpc_result(self.make_rpc(operation_queue))
return self._wavelet_from_json(result, ops.OperationQueue(proxy_for_id))
def blind_wavelet(self, json, proxy_for_id=None):
"""Construct a blind wave from a json string.
Call this method if you have a snapshot of a wave that you
want to operate on outside of an event. Since the wave might
have changed since you last saw it, you should take care to
submit operations that are as safe as possible.
Args:
json: a json object or string containing at least a key
wavelet defining the wavelet and a key blips defining the
blips in the view.
proxy_for_id: the proxying information that will be set on the wavelet's
operation queue.
Returns:
A new wavelet with its own operation queue. It the
responsibility of the caller to make sure this wavelet gets
submited to the server, either by calling robot.submit() or
by calling .submit_with() on the returned wavelet.
"""
return self._wavelet_from_json(json, ops.OperationQueue(proxy_for_id))
def submit(self, wavelet_to_submit):
"""Submit the pending operations associated with wavelet_to_submit.
Typically the wavelet will be the result of fetch_wavelet, blind_wavelet
or new_wave.
"""
pending = wavelet_to_submit.get_operation_queue()
res = self.make_rpc(pending)
pending.clear()
logging.info('submit returned:%s', res)
return res
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the blip module."""
import unittest
import blip
import element
import ops
import simplejson
TEST_BLIP_DATA = {
'childBlipIds': [],
'content': '\nhello world!\nanother line',
'contributors': ['robot@test.com', 'user@test.com'],
'creator': 'user@test.com',
'lastModifiedTime': 1000,
'parentBlipId': None,
'annotations': [{'range': {'start': 2, 'end': 3},
'name': 'key', 'value': 'val'}],
'waveId': 'test.com!w+g3h3im',
'waveletId': 'test.com!root+conv',
'elements':{'14':{'type':'GADGET','properties':{'url':'http://a/b.xml'}}},
}
CHILD_BLIP_ID = 'b+42'
ROOT_BLIP_ID = 'b+43'
class TestBlip(unittest.TestCase):
"""Tests the primary data structures for the wave model."""
def assertBlipStartswith(self, expected, totest):
actual = totest.text[:len(expected)]
self.assertEquals(expected, actual)
def new_blip(self, **args):
"""Create a blip for testing."""
data = TEST_BLIP_DATA.copy()
data.update(args)
res = blip.Blip(data, self.all_blips, self.operation_queue)
self.all_blips[res.blip_id] = res
return res
def setUp(self):
self.all_blips = {}
self.operation_queue = ops.OperationQueue()
def testBlipProperties(self):
root = self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID])
child = self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
self.assertEquals(ROOT_BLIP_ID, root.blip_id)
self.assertEquals(set([CHILD_BLIP_ID]), root.child_blip_ids)
self.assertEquals(set(TEST_BLIP_DATA['contributors']), root.contributors)
self.assertEquals(TEST_BLIP_DATA['creator'], root.creator)
self.assertEquals(TEST_BLIP_DATA['content'], root.text)
self.assertEquals(TEST_BLIP_DATA['lastModifiedTime'],
root.last_modified_time)
self.assertEquals(TEST_BLIP_DATA['parentBlipId'], root.parent_blip_id)
self.assertEquals(TEST_BLIP_DATA['waveId'], root.wave_id)
self.assertEquals(TEST_BLIP_DATA['waveletId'], root.wavelet_id)
self.assertEquals(TEST_BLIP_DATA['content'][3], root[3])
self.assertEquals(element.Gadget.class_type, root[14].type)
self.assertEquals('http://a/b.xml', root[14].url)
self.assertEquals('a', root.text[14])
self.assertEquals(len(TEST_BLIP_DATA['content']), len(root))
self.assertTrue(root.is_root())
self.assertFalse(child.is_root())
self.assertEquals(root, child.parent_blip)
def testBlipSerialize(self):
root = self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID])
serialized = root.serialize()
unserialized = blip.Blip(serialized, self.all_blips, self.operation_queue)
self.assertEquals(root.blip_id, unserialized.blip_id)
self.assertEquals(root.child_blip_ids, unserialized.child_blip_ids)
self.assertEquals(root.contributors, unserialized.contributors)
self.assertEquals(root.creator, unserialized.creator)
self.assertEquals(root.text, unserialized.text)
self.assertEquals(root.last_modified_time, unserialized.last_modified_time)
self.assertEquals(root.parent_blip_id, unserialized.parent_blip_id)
self.assertEquals(root.wave_id, unserialized.wave_id)
self.assertEquals(root.wavelet_id, unserialized.wavelet_id)
self.assertTrue(unserialized.is_root())
def testDocumentOperations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
newlines = [x for x in blip.find('\n')]
self.assertEquals(2, len(newlines))
blip.first('world').replace('jupiter')
bits = blip.text.split('\n')
self.assertEquals(3, len(bits))
self.assertEquals('hello jupiter!', bits[1])
blip.range(2, 5).delete()
self.assertBlipStartswith('\nho jupiter', blip)
blip.first('ho').insert_after('la')
self.assertBlipStartswith('\nhola jupiter', blip)
blip.at(3).insert(' ')
self.assertBlipStartswith('\nho la jupiter', blip)
def testElementHandling(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
url = 'http://www.test.com/image.png'
org_len = len(blip)
blip.append(element.Image(url=url))
elems = [elem for elem in blip.find(element.Image, url=url)]
self.assertEquals(1, len(elems))
elem = elems[0]
self.assertTrue(isinstance(elem, element.Image))
blip.at(1).insert('twelve chars')
self.assertTrue(blip.text.startswith('\ntwelve charshello'))
elem = blip[org_len + 12].value()
self.assertTrue(isinstance(elem, element.Image))
blip.first('twelve ').delete()
self.assertTrue(blip.text.startswith('\nchars'))
elem = blip[org_len + 12 - len('twelve ')].value()
self.assertTrue(isinstance(elem, element.Image))
blip.first('chars').replace(element.Image(url=url))
elems = [elem for elem in blip.find(element.Image, url=url)]
self.assertEquals(2, len(elems))
self.assertTrue(blip.text.startswith('\n hello'))
elem = blip[1].value()
self.assertTrue(isinstance(elem, element.Image))
def testAnnotationHandling(self):
key = 'style/fontWeight'
def get_bold():
for an in blip.annotations[key]:
if an.value == 'bold':
return an
return None
json = ('[{"range":{"start":3,"end":6},"name":"%s","value":"bold"}]'
% key)
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json))
self.assertEquals(1, len(blip.annotations))
self.assertNotEqual(None, get_bold().value)
self.assertTrue(key in blip.annotations)
# extend the bold annotation by adding:
blip.range(5, 8).annotate(key, 'bold')
self.assertEquals(1, len(blip.annotations))
self.assertEquals(8, get_bold().end)
# clip by adding a same keyed:
blip[4:12].annotate(key, 'italic')
self.assertEquals(2, len(blip.annotations[key]))
self.assertEquals(4, get_bold().end)
# now split the italic one:
blip.range(6, 7).clear_annotation(key)
self.assertEquals(3, len(blip.annotations[key]))
# test names and iteration
self.assertEquals(1, len(blip.annotations.names()))
self.assertEquals(3, len([x for x in blip.annotations]))
blip[3: 5].annotate('foo', 'bar')
self.assertEquals(2, len(blip.annotations.names()))
self.assertEquals(4, len([x for x in blip.annotations]))
blip[3: 5].clear_annotation('foo')
# clear the whole thing
blip.all().clear_annotation(key)
# getting to the key should now throw an exception
self.assertRaises(KeyError, blip.annotations.__getitem__, key)
def testBlipOperations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEquals(1, len(self.all_blips))
otherblip = blip.reply()
otherblip.append('hello world')
self.assertEquals('hello world', otherblip.text)
self.assertEquals(blip.blip_id, otherblip.parent_blip_id)
self.assertEquals(2, len(self.all_blips))
inline = blip.insert_inline_blip(3)
self.assertEquals(blip.blip_id, inline.parent_blip_id)
self.assertEquals(3, len(self.all_blips))
def testInsertInlineBlipCantInsertAtTheBeginning(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEquals(1, len(self.all_blips))
self.assertRaises(IndexError, blip.insert_inline_blip, 0)
self.assertEquals(1, len(self.all_blips))
def testDocumentModify(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('a text with text and then some text')
blip[7].insert('text ')
blip.all('text').replace('thing')
self.assertEquals('a thing thing with thing and then some thing',
blip.text)
def testIteration(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('aaa 012 aaa 345 aaa 322')
count = 0
prev = -1
for start, end in blip.all('aaa'):
count += 1
self.assertTrue(prev < start)
prev = start
self.assertEquals(3, count)
def testBlipRefValue(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
content = blip.text
content = content[:4] + content[5:]
del blip[4]
self.assertEquals(content, blip.text)
content = content[:2] + content[3:]
del blip[2:3]
self.assertEquals(content, blip.text)
blip[2:3] = 'bike'
content = content[:2] + 'bike' + content[3:]
self.assertEquals(content, blip.text)
url = 'http://www.test.com/image.png'
blip.append(element.Image(url=url))
self.assertEqual(url, blip.first(element.Image).url)
url2 = 'http://www.test.com/another.png'
blip[-1].update_element({'url': url2})
self.assertEqual(url2, blip.first(element.Image).url)
self.assertTrue(blip[3:5] == blip.text[3:5])
blip.append('geheim')
self.assertTrue(blip.first('geheim'))
self.assertFalse(blip.first(element.Button))
blip.append(element.Button(name='test1', value='Click'))
button = blip.first(element.Button)
button.update_element({'name': 'test2'})
self.assertEqual('test2', button.name)
def testReplace(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('\nxxxx')
blip.all('yyy').replace('zzz')
self.assertEqual('\nxxxx', blip.text)
def testDeleteRangeThatSpansAcrossAnnotationEndPoint(self):
json = ('[{"range":{"start":1,"end":3},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).delete()
self.assertEqual('\nF bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(2, blip.annotations['style'][0].end)
def testInsertBeforeAnnotationStartPoint(self):
json = ('[{"range":{"start":4,"end":9},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.at(4).insert('d and')
self.assertEqual('\nFood and bar.', blip.text)
self.assertEqual(9, blip.annotations['style'][0].start)
self.assertEqual(14, blip.annotations['style'][0].end)
def testDeleteRangeInsideAnnotation(self):
json = ('[{"range":{"start":1,"end":5},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).delete()
self.assertEqual('\nF bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(3, blip.annotations['style'][0].end)
def testReplaceInsideAnnotation(self):
json = ('[{"range":{"start":1,"end":5},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).replace('ooo')
self.assertEqual('\nFooo bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(6, blip.annotations['style'][0].end)
blip.range(2, 5).replace('o')
self.assertEqual('\nFo bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(4, blip.annotations['style'][0].end)
def testReplaceSpanAnnotation(self):
json = ('[{"range":{"start":1,"end":4},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 9).replace('')
self.assertEqual('\nF', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(2, blip.annotations['style'][0].end)
def testSearchWithNoMatchShouldNotGenerateOperation(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEqual(-1, blip.text.find(':('))
self.assertEqual(0, len(self.operation_queue))
blip.all(':(').replace(':)')
self.assertEqual(0, len(self.operation_queue))
def testBlipsRemoveWithId(self):
blip_dict = {
ROOT_BLIP_ID: self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID]),
CHILD_BLIP_ID: self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
}
blips = blip.Blips(blip_dict)
blips._remove_with_id(CHILD_BLIP_ID)
self.assertEqual(1, len(blips))
self.assertEqual(0, len(blips[ROOT_BLIP_ID].child_blip_ids))
def testAppendMarkup(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID, content='\nFoo bar.')
markup = '<p><span>markup<span> content</p>'
blip.append_markup(markup)
self.assertEqual(1, len(self.operation_queue))
self.assertEqual('\nFoo bar.\nmarkup content', blip.text)
def testBundledAnnotations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID, content='\nFoo bar.')
blip.append('not bold')
blip.append('bold', bundled_annotations=[('style/fontWeight', 'bold')])
self.assertEqual(2, len(blip.annotations))
self.assertEqual('bold', blip.annotations['style/fontWeight'][0].value)
def testInlineBlipOffset(self):
offset = 14
self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID],
elements={str(offset):
{'type': element.Element.INLINE_BLIP_TYPE,
'properties': {'id': CHILD_BLIP_ID}}})
child = self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
self.assertEqual(offset, child.inline_blip_offset)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Module defines the ModuleTestRunnerClass."""
import unittest
class ModuleTestRunner(object):
"""Responsible for executing all test cases in a list of modules."""
def __init__(self, module_list=None, module_test_settings=None):
self.modules = module_list or []
self.settings = module_test_settings or {}
def RunAllTests(self):
"""Executes all tests present in the list of modules."""
runner = unittest.TextTestRunner()
for module in self.modules:
for setting, value in self.settings.iteritems():
try:
setattr(module, setting, value)
except AttributeError:
print '\nError running ' + str(setting)
print '\nRunning all tests in module', module.__name__
runner.run(unittest.defaultTestLoader.loadTestsFromModule(module))
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Defines event types that are sent from the wave server.
This module defines all of the event types currently supported by the wave
server. Each event type is sub classed from Event and has its own
properties depending on the type.
"""
class Context(object):
"""Specifies constants representing different context requests."""
#: Requests the root blip.
ROOT = 'ROOT'
#: Requests the parent blip of the event blip.
PARENT = 'PARENT'
#: Requests the siblings blip of the event blip.
SIBLINGS = 'SIBLINGS'
#: Requests the child blips of the event blip.
CHILDREN = 'CHILDREN'
#: Requests the event blip itself.
SELF = 'SELF'
#: Requests all of the blips of the event wavelet.
ALL = 'ALL'
class Event(object):
"""Object describing a single event.
Attributes:
modified_by: Participant id that caused this event.
timestamp: Timestamp that this event occurred on the server.
type: Type string of this event.
properties: Dictionary of all extra properties. Typically the derrived
event type should have these explicitly set as attributes, but
experimental features might appear in properties before that.
blip_id: The blip_id of the blip for blip related events or the root
blip for wavelet related events.
blip: If available, the blip with id equal to the events blip_id.
proxying_for: If available, the proxyingFor id of the robot that caused the
event.
"""
def __init__(self, json, wavelet):
"""Inits this event with JSON data.
Args:
json: JSON data from Wave server.
"""
self.modified_by = json.get('modifiedBy')
self.timestamp = json.get('timestamp', 0)
self.type = json.get('type')
self.raw_data = json
self.properties = json.get('properties', {})
self.blip_id = self.properties.get('blipId')
self.blip = wavelet.blips.get(self.blip_id)
self.proxying_for = json.get('proxyingFor')
class WaveletBlipCreated(Event):
"""Event triggered when a new blip is created.
Attributes:
new_blip_id: The id of the newly created blip.
new_blip: If in context, the actual new blip.
"""
type = 'WAVELET_BLIP_CREATED'
def __init__(self, json, wavelet):
super(WaveletBlipCreated, self).__init__(json, wavelet)
self.new_blip_id = self.properties['newBlipId']
self.new_blip = wavelet.blips.get(self.new_blip_id)
class WaveletBlipRemoved(Event):
"""Event triggered when a new blip is removed.
Attributes:
removed_blip_id: the id of the removed blip
removed_blip: if in context, the removed blip
"""
type = 'WAVELET_BLIP_REMOVED'
def __init__(self, json, wavelet):
super(WaveletBlipRemoved, self).__init__(json, wavelet)
self.removed_blip_id = self.properties['removedBlipId']
self.removed_blip = wavelet.blips.get(self.removed_blip_id)
class WaveletParticipantsChanged(Event):
"""Event triggered when the participants on a wave change.
Attributes:
participants_added: List of participants added.
participants_removed: List of participants removed.
"""
type = 'WAVELET_PARTICIPANTS_CHANGED'
def __init__(self, json, wavelet):
super(WaveletParticipantsChanged, self).__init__(json, wavelet)
self.participants_added = self.properties['participantsAdded']
self.participants_removed = self.properties['participantsRemoved']
class WaveletSelfAdded(Event):
"""Event triggered when the robot is added to the wavelet."""
type = 'WAVELET_SELF_ADDED'
class WaveletSelfRemoved(Event):
"""Event triggered when the robot is removed from the wavelet."""
type = 'WAVELET_SELF_REMOVED'
class WaveletTitleChanged(Event):
"""Event triggered when the title of the wavelet has changed.
Attributes:
title: The new title.
"""
type = 'WAVELET_TITLE_CHANGED'
def __init__(self, json, wavelet):
super(WaveletTitleChanged, self).__init__(json, wavelet)
self.title = self.properties['title']
class BlipContributorsChanged(Event):
"""Event triggered when the contributors to this blip change.
Attributes:
contributors_added: List of contributors that were added.
contributors_removed: List of contributors that were removed.
"""
type = 'BLIP_CONTRIBUTORS_CHANGED'
def __init__(self, json, wavelet):
super(BlipContributorsChanged, self).__init__(json, wavelet)
self.contibutors_added = self.properties['contributorsAdded']
self.contibutors_removed = self.properties['contributorsRemoved']
class BlipSubmitted(Event):
"""Event triggered when a blip is submitted."""
type = 'BLIP_SUBMITTED'
class DocumentChanged(Event):
"""Event triggered when a document is changed.
This event is fired after any changes in the document and should be used
carefully to keep the amount of traffic to the robot reasonable. Use
filters where appropriate.
"""
type = 'DOCUMENT_CHANGED'
class FormButtonClicked(Event):
"""Event triggered when a form button is clicked.
Attributes:
button_name: The name of the button that was clicked.
"""
type = 'FORM_BUTTON_CLICKED'
def __init__(self, json, wavelet):
super(FormButtonClicked, self).__init__(json, wavelet)
self.button_name = self.properties['buttonName']
class GadgetStateChanged(Event):
"""Event triggered when the state of a gadget changes.
Attributes:
index: The index of the gadget that changed in the document.
old_state: The old state of the gadget.
"""
type = 'GADGET_STATE_CHANGED'
def __init__(self, json, wavelet):
super(GadgetStateChanged, self).__init__(json, wavelet)
self.index = self.properties['index']
self.old_state = self.properties['oldState']
class AnnotatedTextChanged(Event):
"""Event triggered when text with an annotation has changed.
This is mainly useful in combination with a filter on the
name of the annotation.
Attributes:
name: The name of the annotation.
value: The value of the annotation that changed.
"""
type = 'ANNOTATED_TEXT_CHANGED'
def __init__(self, json, wavelet):
super(AnnotatedTextChanged, self).__init__(json, wavelet)
self.name = self.properties['name']
self.value = self.properties.get('value')
class OperationError(Event):
"""Triggered when an event on the server occurred.
Attributes:
operation_id: The operation id of the failing operation.
error_message: More information as to what went wrong.
"""
type = 'OPERATION_ERROR'
def __init__(self, json, wavelet):
super(OperationError, self).__init__(json, wavelet)
self.operation_id = self.properties['operationId']
self.error_message = self.properties['message']
class WaveletCreated(Event):
"""Triggered when a new wavelet is created.
This event is only triggered if the robot creates a new
wavelet and can be used to initialize the newly created wave.
wavelets created by other participants remain invisible
to the robot until the robot is added to the wave in
which case WaveletSelfAdded is triggered.
Attributes:
message: Whatever string was passed into the new_wave
call as message (if any).
"""
type = 'WAVELET_CREATED'
def __init__(self, json, wavelet):
super(WaveletCreated, self).__init__(json, wavelet)
self.message = self.properties['message']
class WaveletFetched(Event):
"""Triggered when a new wavelet is fetched.
This event is triggered after a robot requests to
see another wavelet. The robot has to be on the other
wavelet already.
Attributes:
message: Whatever string was passed into the new_wave
call as message (if any).
"""
type = 'WAVELET_FETCHED'
def __init__(self, json, wavelet):
super(WaveletFetched, self).__init__(json, wavelet)
self.message = self.properties['message']
class WaveletTagsChanged(Event):
"""Event triggered when the tags on a wavelet change."""
type = 'WAVELET_TAGS_CHANGED'
def __init__(self, json, wavelet):
super(WaveletTagsChanged, self).__init__(json, wavelet)
def is_event(cls):
"""Returns whether the passed class is an event."""
try:
if not issubclass(cls, Event):
return False
return hasattr(cls, 'type')
except TypeError:
return False
ALL = [item for item in globals().copy().values() if is_event(item)]
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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 element
import errors
import util
class Annotation(object):
"""Models an annotation on a document.
Annotations are key/value pairs over a range of content. Annotations
can be used to store data or to be interpreted by a client when displaying
the data.
"""
# Use the following constants to control the display of the client
#: Reserved annotation for setting background color of text.
BACKGROUND_COLOR = "style/backgroundColor"
#: Reserved annotation for setting color of text.
COLOR = "style/color"
#: Reserved annotation for setting font family of text.
FONT_FAMILY = "style/fontFamily"
#: Reserved annotation for setting font family of text.
FONT_SIZE = "style/fontSize"
#: Reserved annotation for setting font style of text.
FONT_STYLE = "style/fontStyle"
#: Reserved annotation for setting font weight of text.
FONT_WEIGHT = "style/fontWeight"
#: Reserved annotation for setting text decoration.
TEXT_DECORATION = "style/textDecoration"
#: Reserved annotation for setting vertical alignment.
VERTICAL_ALIGN = "style/verticalAlign"
def __init__(self, name, value, start, end):
self._name = name
self._value = value
self._start = start
self._end = end
@property
def name(self):
return self._name
@property
def value(self):
return self._value
@property
def start(self):
return self._start
@property
def end(self):
return self._end
def _shift(self, where, inc):
"""Shift annotation by 'inc' if it (partly) overlaps with 'where'."""
if self._start >= where:
self._start += inc
if self._end >= where:
self._end += inc
def serialize(self):
"""Serializes the annotation.
Returns:
A dict containing the name, value, and range values.
"""
return {'name': self._name,
'value': self._value,
'range': {'start': self._start,
'end': self._end}}
class Annotations(object):
"""A dictionary-like object containing the annotations, keyed by name."""
def __init__(self, operation_queue, blip):
self._operation_queue = operation_queue
self._blip = blip
self._store = {}
def __contains__(self, what):
if isinstance(what, Annotation):
what = what.name
return what in self._store
def _add_internal(self, name, value, start, end):
"""Internal add annotation does not send out operations."""
if name in self._store:
# TODO: use bisect to make this more efficient.
new_list = []
for existing in self._store[name]:
if start > existing.end or end < existing.start:
new_list.append(existing)
else:
if existing.value == value:
# merge the annotations:
start = min(existing.start, start)
end = max(existing.end, end)
else:
# chop the bits off the existing annotation
if existing.start < start:
new_list.append(Annotation(
existing.name, existing.value, existing.start, start))
if existing.end > end:
new_list.append(Annotation(
existing.name, existing.value, existing.end, end))
new_list.append(Annotation(name, value, start, end))
self._store[name] = new_list
else:
self._store[name] = [Annotation(name, value, start, end)]
def _delete_internal(self, name, start=0, end=-1):
"""Remove the passed annotaion from the internal representation."""
if not name in self._store:
return
if end < 0:
end = len(self._blip) + end
new_list = []
for a in self._store[name]:
if start > a.end or end < a.start:
new_list.append(a)
elif start < a.start and end > a.end:
continue
else:
if a.start < start:
new_list.append(Annotation(name, a.value, a.start, start))
if a.end > end:
new_list.append(Annotation(name, a.value, end, a.end))
if new_list:
self._store[name] = new_list
else:
del self._store[name]
def _shift(self, where, inc):
"""Shift annotation by 'inc' if it (partly) overlaps with 'where'."""
for annotations in self._store.values():
for annotation in annotations:
annotation._shift(where, inc)
# Merge fragmented annotations that should be contiguous, for example:
# Annotation('foo', 'bar', 1, 2) and Annotation('foo', 'bar', 2, 3).
for name, annotations in self._store.items():
new_list = []
for i, annotation in enumerate(annotations):
name = annotation.name
value = annotation.value
start = annotation.start
end = annotation.end
# Find the last end index.
for j, next_annotation in enumerate(annotations[i + 1:]):
# Not contiguous, skip.
if (end < next_annotation.start):
break
# Contiguous, merge.
if (end == next_annotation.start and value == next_annotation.value):
end = next_annotation.end
del annotations[j]
new_list.append(Annotation(name, value, start, end))
self._store[name] = new_list
def __len__(self):
return len(self._store)
def __getitem__(self, key):
return self._store[key]
def __iter__(self):
for l in self._store.values():
for ann in l:
yield ann
def names(self):
"""Return the names of the annotations in the store."""
return self._store.keys()
def serialize(self):
"""Return a list of the serialized annotations."""
res = []
for v in self._store.values():
res += [a.serialize() for a in v]
return res
class Blips(object):
"""A dictionary-like object containing the blips, keyed on blip ID."""
def __init__(self, blips):
self._blips = blips
def __getitem__(self, blip_id):
return self._blips[blip_id]
def __iter__(self):
return self._blips.__iter__()
def __len__(self):
return len(self._blips)
def _add(self, ablip):
self._blips[ablip.blip_id] = ablip
def _remove_with_id(self, blip_id):
del_blip = self._blips[blip_id]
if del_blip:
# Remove the reference to this blip from its parent.
parent_blip = self._blips[blip_id].parent_blip
if parent_blip:
parent_blip._child_blip_ids.remove(blip_id)
del self._blips[blip_id]
def get(self, blip_id, default_value=None):
"""Retrieves a blip.
Returns:
A Blip object. If none found for the ID, it returns None,
or if default_value is specified, it returns that.
"""
return self._blips.get(blip_id, default_value)
def serialize(self):
"""Serializes the blips.
Returns:
A dict of serialized blips.
"""
res = {}
for blip_id, item in self._blips.items():
res[blip_id] = item.serialize()
return res
class BlipRefs(object):
"""Represents a set of references to contents in a blip.
For example, a BlipRefs instance can represent the results
of a search, an explicitly set range, a regular expression,
or refer to the entire blip. BlipRefs are used to express
operations on a blip in a consistent way that can easily
be transfered to the server.
The typical way of creating a BlipRefs object is to use
selector methods on the Blip object. Developers will not
usually instantiate a BlipRefs object directly.
"""
DELETE = 'DELETE'
REPLACE = 'REPLACE'
INSERT = 'INSERT'
INSERT_AFTER = 'INSERT_AFTER'
ANNOTATE = 'ANNOTATE'
CLEAR_ANNOTATION = 'CLEAR_ANNOTATION'
UPDATE_ELEMENT = 'UPDATE_ELEMENT'
def __init__(self, blip, maxres=1):
self._blip = blip
self._maxres = maxres
@classmethod
def all(cls, blip, findwhat, maxres=-1, **restrictions):
"""Construct an instance representing the search for text or elements."""
obj = cls(blip, maxres)
obj._findwhat = findwhat
obj._restrictions = restrictions
obj._hits = lambda: obj._find(findwhat, maxres, **restrictions)
if findwhat is None:
# No findWhat, take the entire blip
obj._params = {}
else:
query = {'maxRes': maxres}
if isinstance(findwhat, basestring):
query['textMatch'] = findwhat
else:
query['elementMatch'] = findwhat.class_type
query['restrictions'] = restrictions
obj._params = {'modifyQuery': query}
return obj
@classmethod
def range(cls, blip, begin, end):
"""Constructs an instance representing an explicitly set range."""
obj = cls(blip)
obj._begin = begin
obj._end = end
obj._hits = lambda: [(begin, end)]
obj._params = {'range': {'start': begin, 'end': end}}
return obj
def _elem_matches(self, elem, clz, **restrictions):
if not isinstance(elem, clz):
return False
for key, val in restrictions.items():
if getattr(elem, key) != val:
return False
return True
def _find(self, what, maxres=-1, **restrictions):
"""Iterates where 'what' occurs in the associated blip.
What can be either a string or a class reference.
Examples:
self._find('hello') will return the first occurence of the word hello
self._find(element.Gadget, url='http://example.com/gadget.xml')
will return the first gadget that has as url example.com.
Args:
what: what to search for. Can be a class or a string. The class
should be an element from element.py
maxres: number of results to return at most, or <= 0 for all.
restrictions: if what specifies a class, further restrictions
of the found instances.
Yields:
Tuples indicating the range of the matches. For a one
character/element match at position x, (x, x+1) is yielded.
"""
blip = self._blip
if what is None:
yield 0, len(blip)
raise StopIteration
if isinstance(what, basestring):
idx = blip._content.find(what)
count = 0
while idx != -1:
yield idx, idx + len(what)
count += 1
if count == maxres:
raise StopIteration
idx = blip._content.find(what, idx + len(what))
else:
count = 0
for idx, el in blip._elements.items():
if self._elem_matches(el, what, **restrictions):
yield idx, idx + 1
count += 1
if count == maxres:
raise StopIteration
def _execute(self, modify_how, what, bundled_annotations=None):
"""Executes this BlipRefs object.
Args:
modify_how: What to do. Any of the operation declared at the top.
what: Depending on the operation. For delete, has to be None.
For the others it is a singleton, a list or a function returning
what to do; for ANNOTATE tuples of (key, value), for the others
either string or elements.
If what is a function, it takes three parameters, the content of
the blip, the beginning of the matching range and the end.
bundled_annotations: Annotations to apply immediately.
Raises:
IndexError when trying to access content outside of the blip.
ValueError when called with the wrong values.
Returns:
self for chainability.
"""
blip = self._blip
if modify_how != BlipRefs.DELETE:
if type(what) != list:
what = [what]
next_index = 0
matched = []
# updated_elements is used to store the element type of the
# element to update
updated_elements = []
# For now, if we find one markup, we'll use it everywhere.
next = None
hit_found = False
for start, end in self._hits():
hit_found = True
if start < 0:
start += len(blip)
if end == 0:
end += len(blip)
if end < 0:
end += len(blip)
if len(blip) == 0:
if start != 0 or end != 0:
raise IndexError('Start and end have to be 0 for empty document')
elif start < 0 or end < 1 or start >= len(blip) or end > len(blip):
raise IndexError('Position outside the document')
if modify_how == BlipRefs.DELETE:
for i in range(start, end):
if i in blip._elements:
del blip._elements[i]
blip._delete_annotations(start, end)
blip._shift(end, start - end)
blip._content = blip._content[:start] + blip._content[end:]
else:
if callable(what):
next = what(blip._content, start, end)
matched.append(next)
else:
next = what[next_index]
next_index = (next_index + 1) % len(what)
if isinstance(next, str):
next = util.force_unicode(next)
if modify_how == BlipRefs.ANNOTATE:
key, value = next
blip.annotations._add_internal(key, value, start, end)
elif modify_how == BlipRefs.CLEAR_ANNOTATION:
blip.annotations._delete_internal(next, start, end)
elif modify_how == BlipRefs.UPDATE_ELEMENT:
el = blip._elements.get(start)
if not element:
raise ValueError('No element found at index %s' % start)
# the passing around of types this way feels a bit dirty:
updated_elements.append(element.Element.from_json({'type': el.type,
'properties': next}))
for k, b in next.items():
setattr(el, k, b)
else:
if modify_how == BlipRefs.INSERT:
end = start
elif modify_how == BlipRefs.INSERT_AFTER:
start = end
elif modify_how == BlipRefs.REPLACE:
pass
else:
raise ValueError('Unexpected modify_how: ' + modify_how)
if isinstance(next, element.Element):
text = ' '
else:
text = next
# in the case of a replace, and the replacement text is shorter,
# delete the delta.
if start != end and len(text) < end - start:
blip._delete_annotations(start + len(text), end)
blip._shift(end, len(text) + start - end)
blip._content = blip._content[:start] + text + blip._content[end:]
if bundled_annotations:
end_annotation = start + len(text)
blip._delete_annotations(start, end_annotation)
for key, value in bundled_annotations:
blip.annotations._add_internal(key, value, start, end_annotation)
if isinstance(next, element.Element):
blip._elements[start] = next
# No match found, return immediately without generating op.
if not hit_found:
return
operation = blip._operation_queue.document_modify(blip.wave_id,
blip.wavelet_id,
blip.blip_id)
for param, value in self._params.items():
operation.set_param(param, value)
modify_action = {'modifyHow': modify_how}
if modify_how == BlipRefs.DELETE:
pass
elif modify_how == BlipRefs.UPDATE_ELEMENT:
modify_action['elements'] = updated_elements
elif (modify_how == BlipRefs.REPLACE or
modify_how == BlipRefs.INSERT or
modify_how == BlipRefs.INSERT_AFTER):
if callable(what):
what = matched
if what:
if not isinstance(next, element.Element):
modify_action['values'] = [util.force_unicode(value) for value in what]
else:
modify_action['elements'] = what
elif modify_how == BlipRefs.ANNOTATE:
modify_action['values'] = [x[1] for x in what]
modify_action['annotationKey'] = what[0][0]
elif modify_how == BlipRefs.CLEAR_ANNOTATION:
modify_action['annotationKey'] = what[0]
if bundled_annotations:
modify_action['bundledAnnotations'] = [
{'key': key, 'value': value} for key, value in bundled_annotations]
operation.set_param('modifyAction', modify_action)
return self
def insert(self, what, bundled_annotations=None):
"""Inserts what at the matched positions."""
return self._execute(
BlipRefs.INSERT, what, bundled_annotations=bundled_annotations)
def insert_after(self, what, bundled_annotations=None):
"""Inserts what just after the matched positions."""
return self._execute(
BlipRefs.INSERT_AFTER, what, bundled_annotations=bundled_annotations)
def replace(self, what, bundled_annotations=None):
"""Replaces the matched positions with what."""
return self._execute(
BlipRefs.REPLACE, what, bundled_annotations=bundled_annotations)
def delete(self):
"""Deletes the content at the matched positions."""
return self._execute(BlipRefs.DELETE, None)
def annotate(self, name, value=None):
"""Annotates the content at the matched positions.
You can either specify both name and value to set the
same annotation, or supply as the first parameter something
that yields name/value pairs. The name and value should both be strings.
"""
if value is None:
what = name
else:
what = (name, value)
return self._execute(BlipRefs.ANNOTATE, what)
def clear_annotation(self, name):
"""Clears the annotation at the matched positions."""
return self._execute(BlipRefs.CLEAR_ANNOTATION, name)
def update_element(self, new_values):
"""Update an existing element with a set of new values."""
return self._execute(BlipRefs.UPDATE_ELEMENT, new_values)
def __nonzero__(self):
"""Return whether we have a value."""
for start, end in self._hits():
return True
return False
def value(self):
"""Convenience method to convert a BlipRefs to value of its first match."""
for start, end in self._hits():
if end - start == 1 and start in self._blip._elements:
return self._blip._elements[start]
else:
return self._blip.text[start:end]
raise ValueError('BlipRefs has no values')
def __getattr__(self, attribute):
"""Mirror the getattr of value().
This allows for clever things like
first(IMAGE).url
or
blip.annotate_with(key, value).upper()
"""
return getattr(self.value(), attribute)
def __radd__(self, other):
"""Make it possible to add this to a string."""
return other + self.value()
def __cmp__(self, other):
"""Support comparision with target."""
return cmp(self.value(), other)
def __iter__(self):
for start_end in self._hits():
yield start_end
class Blip(object):
"""Models a single blip instance.
Blips are essentially the documents that make up a conversation. Blips can
live in a hierarchy of blips. A root blip has no parent blip id, but all
blips have the ids of the wave and wavelet that they are associated with.
Blips also contain annotations, content and elements, which are accessed via
the Document object.
"""
def __init__(self, json, other_blips, operation_queue):
"""Inits this blip with JSON data.
Args:
json: JSON data dictionary from Wave server.
other_blips: A dictionary like object that can be used to resolve
ids of blips to blips.
operation_queue: an OperationQueue object to store generated operations
in.
"""
self._blip_id = json.get('blipId')
self._operation_queue = operation_queue
self._child_blip_ids = set(json.get('childBlipIds', []))
self._content = json.get('content', '')
self._contributors = set(json.get('contributors', []))
self._creator = json.get('creator')
self._last_modified_time = json.get('lastModifiedTime', 0)
self._version = json.get('version', 0)
self._parent_blip_id = json.get('parentBlipId')
self._wave_id = json.get('waveId')
self._wavelet_id = json.get('waveletId')
if isinstance(other_blips, Blips):
self._other_blips = other_blips
else:
self._other_blips = Blips(other_blips)
self._annotations = Annotations(operation_queue, self)
for annjson in json.get('annotations', []):
r = annjson['range']
self._annotations._add_internal(annjson['name'],
annjson['value'],
r['start'],
r['end'])
self._elements = {}
json_elements = json.get('elements', {})
for elem in json_elements:
self._elements[int(elem)] = element.Element.from_json(json_elements[elem])
self.raw_data = json
@property
def blip_id(self):
"""The id of this blip."""
return self._blip_id
@property
def wave_id(self):
"""The id of the wave that this blip belongs to."""
return self._wave_id
@property
def wavelet_id(self):
"""The id of the wavelet that this blip belongs to."""
return self._wavelet_id
@property
def child_blip_ids(self):
"""The set of the ids of this blip's children."""
return self._child_blip_ids
@property
def child_blips(self):
"""The set of blips that are children of this blip."""
return set([self._other_blips[blid_id] for blid_id in self._child_blip_ids
if blid_id in self._other_blips])
@property
def contributors(self):
"""The set of participant ids that contributed to this blip."""
return self._contributors
@property
def creator(self):
"""The id of the participant that created this blip."""
return self._creator
@property
def last_modified_time(self):
"""The time in seconds since epoch when this blip was last modified."""
return self._last_modified_time
@property
def version(self):
"""The version of this blip."""
return self._version
@property
def parent_blip_id(self):
"""The parent blip_id or None if this is the root blip."""
return self._parent_blip_id
@property
def parent_blip(self):
"""The parent blip or None if it is the root."""
# if parent_blip_id is None, get will also return None
return self._other_blips.get(self._parent_blip_id)
@property
def inline_blip_offset(self):
"""The offset in the parent if this blip is inline or -1 if not.
If the parent is not in the context, this function will always
return -1 since it can't determine the inline blip status.
"""
parent = self.parent_blip
if not parent:
return -1
for offset, el in parent._elements.items():
if el.type == element.Element.INLINE_BLIP_TYPE and el.id == self.blip_id:
return offset
return -1
def is_root(self):
"""Returns whether this is the root blip of a wavelet."""
return self._parent_blip_id is None
@property
def annotations(self):
"""The annotations for this document."""
return self._annotations
@property
def elements(self):
"""Returns a list of elements for this document.
The elements of a blip are things like forms elements and gadgets
that cannot be expressed as plain text. In the text of the blip, you'll
typically find a space as a place holder for the element.
If you want to retrieve the element at a particular index in the blip, use
blip[index].value().
"""
return self._elements.values()
def __len__(self):
return len(self._content)
def __getitem__(self, item):
"""returns a BlipRefs for the given slice."""
if isinstance(item, slice):
if item.step:
raise errors.Error('Step not supported for blip slices')
return self.range(item.start, item.stop)
else:
return self.at(item)
def __setitem__(self, item, value):
"""short cut for self.range/at().replace(value)."""
self.__getitem__(item).replace(value)
def __delitem__(self, item):
"""short cut for self.range/at().delete()."""
self.__getitem__(item).delete()
def _shift(self, where, inc):
"""Move element and annotations after 'where' up by 'inc'."""
new_elements = {}
for idx, el in self._elements.items():
if idx >= where:
idx += inc
new_elements[idx] = el
self._elements = new_elements
self._annotations._shift(where, inc)
def _delete_annotations(self, start, end):
"""Delete all annotations between 'start' and 'end'."""
for annotation_name in self._annotations.names():
self._annotations._delete_internal(annotation_name, start, end)
def all(self, findwhat=None, maxres=-1, **restrictions):
"""Returns a BlipRefs object representing all results for the search.
If searching for an element, the restrictions can be used to specify
additional element properties to filter on, like the url of a Gadget.
"""
return BlipRefs.all(self, findwhat, maxres, **restrictions)
def first(self, findwhat=None, **restrictions):
"""Returns a BlipRefs object representing the first result for the search.
If searching for an element, the restrictions can be used to specify
additional element properties to filter on, like the url of a Gadget.
"""
return BlipRefs.all(self, findwhat, 1, **restrictions)
def at(self, index):
"""Returns a BlipRefs object representing a 1-character range."""
return BlipRefs.range(self, index, index + 1)
def range(self, start, end):
"""Returns a BlipRefs object representing the range."""
return BlipRefs.range(self, start, end)
def serialize(self):
"""Return a dictionary representation of this blip ready for json."""
return {'blipId': self._blip_id,
'childBlipIds': list(self._child_blip_ids),
'content': self._content,
'creator': self._creator,
'contributors': list(self._contributors),
'lastModifiedTime': self._last_modified_time,
'version': self._version,
'parentBlipId': self._parent_blip_id,
'waveId': self._wave_id,
'waveletId': self._wavelet_id,
'annotations': self._annotations.serialize(),
'elements': dict([(index, e.serialize())
for index, e in self._elements.items()])
}
def proxy_for(self, proxy_for_id):
"""Return a view on this blip that will proxy for the specified id.
A shallow copy of the current blip is returned with the proxy_for_id
set. Any modifications made to this copy will be done using the
proxy_for_id, i.e. the robot+<proxy_for_id>@appspot.com address will
be used.
"""
operation_queue = self._operation_queue.proxy_for(proxy_for_id)
res = Blip(json={},
other_blips={},
operation_queue=operation_queue)
res._blip_id = self._blip_id
res._child_blip_ids = self._child_blip_ids
res._content = self._content
res._contributors = self._contributors
res._creator = self._creator
res._last_modified_time = self._last_modified_time
res._version = self._version
res._parent_blip_id = self._parent_blip_id
res._wave_id = self._wave_id
res._wavelet_id = self._wavelet_id
res._other_blips = self._other_blips
res._annotations = self._annotations
res._elements = self._elements
res.raw_data = self.raw_data
return res
@property
def text(self):
"""Returns the raw text content of this document."""
return self._content
def find(self, what, **restrictions):
"""Iterate to matching bits of contents.
Yield either elements or pieces of text.
"""
br = BlipRefs.all(self, what, **restrictions)
for start, end in br._hits():
if end - start == 1 and start in self._elements:
yield self._elements[start]
else:
yield self._content[start:end]
raise StopIteration
def append(self, what, bundled_annotations=None):
"""Convenience method covering a common pattern."""
return BlipRefs.all(self, findwhat=None).insert_after(
what, bundled_annotations=bundled_annotations)
def reply(self):
"""Create and return a reply to this blip."""
blip_data = self._operation_queue.blip_create_child(self.wave_id,
self.wavelet_id,
self.blip_id)
new_blip = Blip(blip_data, self._other_blips, self._operation_queue)
self._other_blips._add(new_blip)
return new_blip
def append_markup(self, markup):
"""Interpret the markup text as xhtml and append the result to the doc.
Args:
markup: The markup'ed text to append.
"""
markup = util.force_unicode(markup)
self._operation_queue.document_append_markup(self.wave_id,
self.wavelet_id,
self.blip_id,
markup)
self._content += util.parse_markup(markup)
def insert_inline_blip(self, position):
"""Inserts an inline blip into this blip at a specific position.
Args:
position: Position to insert the blip at. This has to be greater than 0.
Returns:
The JSON data of the blip that was created.
"""
if position <= 0:
raise IndexError(('Illegal inline blip position: %d. Position has to ' +
'be greater than 0.') % position)
blip_data = self._operation_queue.document_inline_blip_insert(
self.wave_id,
self.wavelet_id,
self.blip_id,
position)
new_blip = Blip(blip_data, self._other_blips, self._operation_queue)
self._other_blips._add(new_blip)
return new_blip
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Elements are non-text bits living in blips like images, gadgets etc.
This module defines the Element class and the derived classes.
"""
import base64
import logging
import sys
import util
class Element(object):
"""Elements are non-text content within a document.
These are generally abstracted from the Robot. Although a Robot can query the
properties of an element it can only interact with the specific types that
the element represents.
Properties of elements are both accessible directly (image.url) and through
the properties dictionary (image.properties['url']). In general Element
should not be instantiated by robots, but rather rely on the derived classes.
"""
# INLINE_BLIP_TYPE is not a separate type since it shouldn't be instantiated,
# only be used for introspection
INLINE_BLIP_TYPE = "INLINE_BLIP"
def __init__(self, element_type, **properties):
"""Initializes self with the specified type and any properties.
Args:
element_type: string typed member of ELEMENT_TYPE
properties: either a dictionary of initial properties, or a dictionary
with just one member properties that is itself a dictionary of
properties. This allows us to both use
e = Element(atype, prop1=val1, prop2=prop2...)
and
e = Element(atype, properties={prop1:val1, prop2:prop2..})
"""
if len(properties) == 1 and 'properties' in properties:
properties = properties['properties']
self._type = element_type
# as long as the operation_queue of an element in None, it is
# unattached. After an element is acquired by a blip, the blip
# will set the operation_queue to make sure all changes to the
# element are properly send to the server.
self._operation_queue = None
self._properties = properties.copy()
@property
def type(self):
"""The type of this element."""
return self._type
@classmethod
def from_json(cls, json):
"""Class method to instantiate an Element based on a json string."""
etype = json['type']
props = json['properties'].copy()
element_class = ALL.get(etype)
if not element_class:
# Unknown type. Server could be newer than we are
return Element(element_type=etype, properties=props)
return element_class.from_props(props)
def get(self, key, default=None):
"""Standard get interface."""
return self._properties.get(key, default)
def __getattr__(self, key):
return self._properties[key]
def serialize(self):
"""Custom serializer for Elements."""
return util.serialize({'properties': util.non_none_dict(self._properties),
'type': self._type})
class Input(Element):
"""A single-line input element."""
class_type = 'INPUT'
def __init__(self, name, value=''):
super(Input, self).__init__(Input.class_type,
name=name,
value=value,
default_value=value)
@classmethod
def from_props(cls, props):
return Input(name=props.get('name'), value=props.get('value'))
class Check(Element):
"""A checkbox element."""
class_type = 'CHECK'
def __init__(self, name, value=''):
super(Check, self).__init__(Check.class_type,
name=name, value=value, default_value=value)
@classmethod
def from_props(cls, props):
return Check(name=props.get('name'), value=props.get('value'))
class Button(Element):
"""A button element."""
class_type = 'BUTTON'
def __init__(self, name, value):
super(Button, self).__init__(Button.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return Button(name=props.get('name'), value=props.get('value'))
class Label(Element):
"""A label element."""
class_type = 'LABEL'
def __init__(self, label_for, caption):
super(Label, self).__init__(Label.class_type,
name=label_for, value=caption)
@classmethod
def from_props(cls, props):
return Label(label_for=props.get('name'), caption=props.get('value'))
class RadioButton(Element):
"""A radio button element."""
class_type = 'RADIO_BUTTON'
def __init__(self, name, group):
super(RadioButton, self).__init__(RadioButton.class_type,
name=name, value=group)
@classmethod
def from_props(cls, props):
return RadioButton(name=props.get('name'), group=props.get('value'))
class RadioButtonGroup(Element):
"""A group of radio buttons."""
class_type = 'RADIO_BUTTON_GROUP'
def __init__(self, name, value):
super(RadioButtonGroup, self).__init__(RadioButtonGroup.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return RadioButtonGroup(name=props.get('name'), value=props.get('value'))
class Password(Element):
"""A password element."""
class_type = 'PASSWORD'
def __init__(self, name, value):
super(Password, self).__init__(Password.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return Password(name=props.get('name'), value=props.get('value'))
class TextArea(Element):
"""A text area element."""
class_type = 'TEXTAREA'
def __init__(self, name, value):
super(TextArea, self).__init__(TextArea.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return TextArea(name=props.get('name'), value=props.get('value'))
class Line(Element):
"""A line element.
Note that Lines are represented in the text as newlines.
"""
class_type = 'LINE'
# Possible line types:
#: Designates line as H1, largest heading.
TYPE_H1 = 'h1'
#: Designates line as H2 heading.
TYPE_H2 = 'h2'
#: Designates line as H3 heading.
TYPE_H3 = 'h3'
#: Designates line as H4 heading.
TYPE_H4 = 'h4'
#: Designates line as H5, smallest heading.
TYPE_H5 = 'h5'
#: Designates line as a bulleted list item.
TYPE_LI = 'li'
# Possible values for align
#: Sets line alignment to left.
ALIGN_LEFT = 'l'
#: Sets line alignment to right.
ALIGN_RIGHT = 'r'
#: Sets line alignment to centered.
ALIGN_CENTER = 'c'
#: Sets line alignment to justified.
ALIGN_JUSTIFIED = 'j'
def __init__(self,
line_type=None,
indent=None,
alignment=None,
direction=None):
super(Line, self).__init__(Line.class_type,
lineType=line_type,
indent=indent,
alignment=alignment,
direction=direction)
@classmethod
def from_props(cls, props):
return Line(line_type=props.get('lineType'),
indent=props.get('indent'),
alignment=props.get('alignment'),
direction=props.get('direction'))
class Gadget(Element):
"""A gadget element."""
class_type = 'GADGET'
def __init__(self, url, props=None):
if props is None:
props = {}
props['url'] = url
super(Gadget, self).__init__(Gadget.class_type, properties=props)
@classmethod
def from_props(cls, props):
return Gadget(props.get('url'), props)
def serialize(self):
"""Gadgets allow for None values."""
return {'properties': self._properties, 'type': self._type}
def keys(self):
"""Get the valid keys for this gadget."""
return [x for x in self._properties.keys() if x != 'url']
class Installer(Element):
"""An installer element."""
class_type = 'INSTALLER'
def __init__(self, manifest):
super(Installer, self).__init__(Installer.class_type, manifest=manifest)
@classmethod
def from_props(cls, props):
return Installer(props.get('manifest'))
class Image(Element):
"""An image element."""
class_type = 'IMAGE'
def __init__(self, url='', width=None, height=None,
attachmentId=None, caption=None):
super(Image, self).__init__(Image.class_type, url=url, width=width,
height=height, attachmentId=attachmentId, caption=caption)
@classmethod
def from_props(cls, props):
props = dict([(key.encode('utf-8'), value)
for key, value in props.items()])
return apply(Image, [], props)
class Attachment(Element):
"""An attachment element.
To create a new attachment, caption and data are needed.
mimeType, attachmentId and attachmentUrl are sent via events.
"""
class_type = 'ATTACHMENT'
def __init__(self, caption=None, data=None, mimeType=None, attachmentId=None,
attachmentUrl=None):
Attachment.originalData = data
super(Attachment, self).__init__(Attachment.class_type, caption=caption,
data=data, mimeType=mimeType, attachmentId=attachmentId,
attachmentUrl=attachmentUrl)
def __getattr__(self, key):
if key and key == 'data':
return Attachment.originalData
return super(Attachment, self).__getattr__(key)
@classmethod
def from_props(cls, props):
props = dict([(key.encode('utf-8'), value)
for key, value in props.items()])
return apply(Attachment, [], props)
def serialize(self):
"""Serializes the attachment object into JSON.
The attachment data is base64 encoded.
"""
if self.data:
self._properties['data'] = base64.encodestring(self.data)
return super(Attachment, self).serialize()
def is_element(cls):
"""Returns whether the passed class is an element."""
try:
if not issubclass(cls, Element):
return False
h = hasattr(cls, 'class_type')
return hasattr(cls, 'class_type')
except TypeError:
return False
ALL = dict([(item.class_type, item) for item in globals().copy().values()
if is_element(item)])
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the element module."""
import base64
import unittest
import element
import util
class TestElement(unittest.TestCase):
"""Tests for the element.Element class."""
def testProperties(self):
el = element.Element(element.Gadget.class_type,
key='value')
self.assertEquals('value', el.key)
def testFormElement(self):
el = element.Input('input')
self.assertEquals(element.Input.class_type, el.type)
self.assertEquals(el.value, '')
self.assertEquals(el.name, 'input')
def testImage(self):
image = element.Image('http://test.com/image.png', width=100, height=100)
self.assertEquals(element.Image.class_type, image.type)
self.assertEquals(image.url, 'http://test.com/image.png')
self.assertEquals(image.width, 100)
self.assertEquals(image.height, 100)
def testAttachment(self):
attachment = element.Attachment(caption='My Favorite', data='SomefakeData')
self.assertEquals(element.Attachment.class_type, attachment.type)
self.assertEquals(attachment.caption, 'My Favorite')
self.assertEquals(attachment.data, 'SomefakeData')
def testGadget(self):
gadget = element.Gadget('http://test.com/gadget.xml')
self.assertEquals(element.Gadget.class_type, gadget.type)
self.assertEquals(gadget.url, 'http://test.com/gadget.xml')
def testInstaller(self):
installer = element.Installer('http://test.com/installer.xml')
self.assertEquals(element.Installer.class_type, installer.type)
self.assertEquals(installer.manifest, 'http://test.com/installer.xml')
def testSerialize(self):
image = element.Image('http://test.com/image.png', width=100, height=100)
s = util.serialize(image)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 3)
self.assertEquals(props['url'], 'http://test.com/image.png')
self.assertEquals(props['width'], 100)
self.assertEquals(props['height'], 100)
def testSerializeAttachment(self):
attachment = element.Attachment(caption='My Favorite', data='SomefakeData')
s = util.serialize(attachment)
k = s.keys()
k.sort()
# we should really have two things to serialize
props = s['properties']
self.assertEquals(len(props), 2)
self.assertEquals(props['caption'], 'My Favorite')
self.assertEquals(props['data'], base64.encodestring('SomefakeData'))
self.assertEquals(attachment.data, 'SomefakeData')
def testSerializeLine(self):
line = element.Line(element.Line.TYPE_H1, alignment=element.Line.ALIGN_LEFT)
s = util.serialize(line)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 2)
self.assertEquals(props['alignment'], 'l')
self.assertEquals(props['lineType'], 'h1')
def testSerializeGadget(self):
gadget = element.Gadget('http://test.com', {'prop1': 'a', 'prop_cap': None})
s = util.serialize(gadget)
k = s.keys()
k.sort()
# we should really only have three things to serialize
props = s['properties']
self.assertEquals(len(props), 3)
self.assertEquals(props['url'], 'http://test.com')
self.assertEquals(props['prop1'], 'a')
self.assertEquals(props['prop_cap'], None)
def testGadgetElementFromJson(self):
url = 'http://www.foo.com/gadget.xml'
json = {
'type': element.Gadget.class_type,
'properties': {
'url': url,
}
}
gadget = element.Element.from_json(json)
self.assertEquals(element.Gadget.class_type, gadget.type)
self.assertEquals(url, gadget.url)
def testImageElementFromJson(self):
url = 'http://www.foo.com/image.png'
width = '32'
height = '32'
attachment_id = '2'
caption = 'Test Image'
json = {
'type': element.Image.class_type,
'properties': {
'url': url,
'width': width,
'height': height,
'attachmentId': attachment_id,
'caption': caption,
}
}
image = element.Element.from_json(json)
self.assertEquals(element.Image.class_type, image.type)
self.assertEquals(url, image.url)
self.assertEquals(width, image.width)
self.assertEquals(height, image.height)
self.assertEquals(attachment_id, image.attachmentId)
self.assertEquals(caption, image.caption)
def testAttachmentElementFromJson(self):
caption = 'fake caption'
data = 'fake data'
mime_type = 'fake mime'
attachment_id = 'fake id'
attachment_url = 'fake URL'
json = {
'type': element.Attachment.class_type,
'properties': {
'caption': caption,
'data': data,
'mimeType': mime_type,
'attachmentId': attachment_id,
'attachmentUrl': attachment_url,
}
}
attachment = element.Element.from_json(json)
self.assertEquals(element.Attachment.class_type, attachment.type)
self.assertEquals(caption, attachment.caption)
self.assertEquals(data, attachment.data)
self.assertEquals(mime_type, attachment.mimeType)
self.assertEquals(attachment_id, attachment.attachmentId)
self.assertEquals(attachment_url, attachment.attachmentUrl)
def testFormElementFromJson(self):
name = 'button'
value = 'value'
default_value = 'foo'
json = {
'type': element.Label.class_type,
'properties': {
'name': name,
'value': value,
'defaultValue': default_value,
}
}
el = element.Element.from_json(json)
self.assertEquals(element.Label.class_type, el.type)
self.assertEquals(name, el.name)
self.assertEquals(value, el.value)
def testCanInstantiate(self):
bag = [element.Check(name='check', value='value'),
element.Button(name='button', value='caption'),
element.Input(name='input', value='caption'),
element.Label(label_for='button', caption='caption'),
element.RadioButton(name='name', group='group'),
element.RadioButtonGroup(name='name', value='value'),
element.Password(name='name', value='geheim'),
element.TextArea(name='name', value='\n\n\n'),
element.Installer(manifest='test.com/installer.xml'),
element.Line(line_type='type',
indent='3',
alignment='r',
direction='d'),
element.Gadget(url='test.com/gadget.xml',
props={'key1': 'val1', 'key2': 'val2'}),
element.Image(url='test.com/image.png', width=100, height=200),
element.Attachment(caption='fake caption', data='fake data')]
types_constructed = set([type(x) for x in bag])
types_required = set(element.ALL.values())
missing_required = types_constructed.difference(types_required)
self.assertEquals(missing_required, set())
missing_constructed = types_required.difference(types_constructed)
self.assertEquals(missing_constructed, set())
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Defines classes that are needed to model a wavelet."""
import blip
import errors
import util
class DataDocs(object):
"""Class modeling a bunch of data documents in pythonic way."""
def __init__(self, init_docs, wave_id, wavelet_id, operation_queue):
self._docs = init_docs
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __iter__(self):
return self._docs.__iter__()
def __contains__(self, key):
return key in self._docs
def __delitem__(self, key):
if not key in self._docs:
return
self._operation_queue.wavelet_datadoc_set(
self._wave_id, self._wavelet_id, key, None)
del self._docs[key]
def __getitem__(self, key):
return self._docs[key]
def __setitem__(self, key, value):
self._operation_queue.wavelet_datadoc_set(
self._wave_id, self._wavelet_id, key, value)
if value is None and key in self._docs:
del self._docs[key]
else:
self._docs[key] = value
def __len__(self):
return len(self._docs)
def keys(self):
return self._docs.keys()
def serialize(self):
"""Returns a dictionary of the data documents."""
return self._docs
class Participants(object):
"""Class modelling a set of participants in pythonic way."""
#: Designates full access (read/write) role.
ROLE_FULL = "FULL"
#: Designates read-only role.
ROLE_READ_ONLY = "READ_ONLY"
def __init__(self, participants, roles, wave_id, wavelet_id, operation_queue):
self._participants = set(participants)
self._roles = roles.copy()
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __contains__(self, participant):
return participant in self._participants
def __len__(self):
return len(self._participants)
def __iter__(self):
return self._participants.__iter__()
def add(self, participant_id):
"""Adds a participant by their ID (address)."""
self._operation_queue.wavelet_add_participant(
self._wave_id, self._wavelet_id, participant_id)
self._participants.add(participant_id)
def get_role(self, participant_id):
"""Return the role for the given participant_id."""
return self._roles.get(participant_id, Participants.ROLE_FULL)
def set_role(self, participant_id, role):
"""Sets the role for the given participant_id."""
if role != Participants.ROLE_FULL and role != Participants.ROLE_READ_ONLY:
raise ValueError(role + ' is not a valid role')
self._operation_queue.wavelet_modify_participant_role(
self._wave_id, self._wavelet_id, participant_id, role)
self._roles[participant_id] = role
def serialize(self):
"""Returns a list of the participants."""
return list(self._participants)
class Tags(object):
"""Class modelling a list of tags."""
def __init__(self, tags, wave_id, wavelet_id, operation_queue):
self._tags = list(tags)
self._wave_id = wave_id
self._wavelet_id = wavelet_id
self._operation_queue = operation_queue
def __getitem__(self, index):
return self._tags[index]
def __len__(self):
return len(self._tags)
def __iter__(self):
return self._tags.__iter__()
def append(self, tag):
"""Appends a tag if it doesn't already exist."""
tag = util.force_unicode(tag)
if tag in self._tags:
return
self._operation_queue.wavelet_modify_tag(
self._wave_id, self._wavelet_id, tag)
self._tags.append(tag)
def remove(self, tag):
"""Removes a tag if it exists."""
tag = util.force_unicode(tag)
if not tag in self._tags:
return
self._operation_queue.wavelet_modify_tag(
self._wave_id, self._wavelet_id, tag, modify_how='remove')
self._tags.remove(tag)
def serialize(self):
"""Returns a list of tags."""
return list(self._tags)
class Wavelet(object):
"""Models a single wavelet.
A single wavelet is composed of metadata, participants, and its blips.
To guarantee that all blips are available, specify Context.ALL for events.
"""
def __init__(self, json, blips, robot, operation_queue):
"""Inits this wavelet with JSON data.
Args:
json: JSON data dictionary from Wave server.
blips: a dictionary object that can be used to resolve blips.
robot: the robot owning this wavelet.
operation_queue: an OperationQueue object to be used to
send any generated operations to.
"""
self._robot = robot
self._operation_queue = operation_queue
self._wave_id = json.get('waveId')
self._wavelet_id = json.get('waveletId')
self._creator = json.get('creator')
self._creation_time = json.get('creationTime', 0)
self._data_documents = DataDocs(json.get('dataDocuments', {}),
self._wave_id,
self._wavelet_id,
operation_queue)
self._last_modified_time = json.get('lastModifiedTime')
self._participants = Participants(json.get('participants', []),
json.get('participantRoles', {}),
self._wave_id,
self._wavelet_id,
operation_queue)
self._title = json.get('title', '')
self._tags = Tags(json.get('tags', []),
self._wave_id,
self._wavelet_id,
operation_queue)
self._raw_data = json
self._blips = blip.Blips(blips)
self._root_blip_id = json.get('rootBlipId')
if self._root_blip_id and self._root_blip_id in self._blips:
self._root_blip = self._blips[self._root_blip_id]
else:
self._root_blip = None
self._robot_address = None
@property
def wavelet_id(self):
"""Returns this wavelet's id."""
return self._wavelet_id
@property
def wave_id(self):
"""Returns this wavelet's parent wave id."""
return self._wave_id
@property
def creator(self):
"""Returns the participant id of the creator of this wavelet."""
return self._creator
@property
def creation_time(self):
"""Returns the time that this wavelet was first created in milliseconds."""
return self._creation_time
@property
def data_documents(self):
"""Returns the data documents for this wavelet based on key name."""
return self._data_documents
@property
def domain(self):
"""Return the domain that wavelet belongs to."""
p = self._wave_id.find('!')
if p == -1:
return None
else:
return self._wave_id[:p]
@property
def last_modified_time(self):
"""Returns the time that this wavelet was last modified in ms."""
return self._last_modified_time
@property
def participants(self):
"""Returns a set of participants on this wavelet."""
return self._participants
@property
def tags(self):
"""Returns a list of tags for this wavelet."""
return self._tags
@property
def robot(self):
"""The robot that owns this wavelet."""
return self._robot
def _get_title(self):
return self._title
def _set_title(self, title):
title = util.force_unicode(title)
if title.find('\n') != -1:
raise errors.Error('Wavelet title should not contain a newline ' +
'character. Specified: ' + title)
self._operation_queue.wavelet_set_title(self.wave_id, self.wavelet_id,
title)
self._title = title
# Adjust the content of the root blip, if it is available in the context.
if self._root_blip:
content = '\n'
splits = self._root_blip._content.split('\n', 2)
if len(splits) == 3:
content += splits[2]
self._root_blip._content = '\n' + title + content
#: Returns or sets the wavelet's title.
title = property(_get_title, _set_title,
doc='Get or set the title of the wavelet.')
def _get_robot_address(self):
return self._robot_address
def _set_robot_address(self, address):
if self._robot_address:
raise errors.Error('robot address already set')
self._robot_address = address
robot_address = property(_get_robot_address, _set_robot_address,
doc='Get or set the address of the current robot.')
@property
def root_blip(self):
"""Returns this wavelet's root blip."""
return self._root_blip
@property
def blips(self):
"""Returns the blips for this wavelet."""
return self._blips
def get_operation_queue(self):
"""Returns the OperationQueue for this wavelet."""
return self._operation_queue
def serialize(self):
"""Return a dict of the wavelet properties."""
return {'waveId': self._wave_id,
'waveletId': self._wavelet_id,
'creator': self._creator,
'creationTime': self._creation_time,
'dataDocuments': self._data_documents.serialize(),
'lastModifiedTime': self._last_modified_time,
'participants': self._participants.serialize(),
'title': self._title,
'blips': self._blips.serialize(),
'rootBlipId': self._root_blip_id
}
def proxy_for(self, proxy_for_id):
"""Return a view on this wavelet that will proxy for the specified id.
A shallow copy of the current wavelet is returned with the proxy_for_id
set. Any modifications made to this copy will be done using the
proxy_for_id, i.e. the robot+<proxy_for_id>@appspot.com address will
be used.
If the wavelet was retrieved using the Active Robot API, that is
by fetch_wavelet, then the address of the robot must be added to the
wavelet by setting wavelet.robot_address before calling proxy_for().
"""
self.add_proxying_participant(proxy_for_id)
operation_queue = self.get_operation_queue().proxy_for(proxy_for_id)
res = Wavelet(json={},
blips={},
robot=self.robot,
operation_queue=operation_queue)
res._wave_id = self._wave_id
res._wavelet_id = self._wavelet_id
res._creator = self._creator
res._creation_time = self._creation_time
res._data_documents = self._data_documents
res._last_modified_time = self._last_modified_time
res._participants = self._participants
res._title = self._title
res._raw_data = self._raw_data
res._blips = self._blips
res._root_blip = self._root_blip
return res
def add_proxying_participant(self, id):
"""Ads a proxying participant to the wave.
Proxying participants are of the form robot+proxy@domain.com. This
convenience method constructs this id and then calls participants.add.
"""
if not self.robot_address:
raise errors.Error(
'Need a robot address to add a proxying for participant')
robotid, domain = self.robot_address.split('@', 1)
if '#' in robotid:
robotid, version = robotid.split('#')
else:
version = None
if '+' in robotid:
newid = robotid.split('+', 1)[0] + '+' + id
else:
newid = robotid + '+' + id
if version:
newid += '#' + version
newid += '@' + domain
self.participants.add(newid)
def submit_with(self, other_wavelet):
"""Submit this wavelet when the passed other wavelet is submited.
wavelets constructed outside of the event callback need to
be either explicitly submited using robot.submit(wavelet) or be
associated with a different wavelet that will be submited or
is part of the event callback.
"""
other_wavelet._operation_queue.copy_operations(self._operation_queue)
self._operation_queue = other_wavelet._operation_queue
def reply(self, initial_content=None):
"""Replies to the conversation in this wavelet.
Args:
initial_content: If set, start with this (string) content.
Returns:
A transient version of the blip that contains the reply.
"""
if not initial_content:
initial_content = u'\n'
initial_content = util.force_unicode(initial_content)
blip_data = self._operation_queue.wavelet_append_blip(
self.wave_id, self.wavelet_id, initial_content)
instance = blip.Blip(blip_data, self._blips, self._operation_queue)
self._blips._add(instance)
return instance
def delete(self, todelete):
"""Remove a blip from this wavelet.
Args:
todelete: either a blip or a blip id to be removed.
"""
if isinstance(todelete, blip.Blip):
blip_id = todelete.blip_id
else:
blip_id = todelete
self._operation_queue.blip_delete(self.wave_id, self.wavelet_id, blip_id)
self._blips._remove_with_id(blip_id)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Elements are non-text bits living in blips like images, gadgets etc.
This module defines the Element class and the derived classes.
"""
import base64
import logging
import sys
import util
class Element(object):
"""Elements are non-text content within a document.
These are generally abstracted from the Robot. Although a Robot can query the
properties of an element it can only interact with the specific types that
the element represents.
Properties of elements are both accessible directly (image.url) and through
the properties dictionary (image.properties['url']). In general Element
should not be instantiated by robots, but rather rely on the derived classes.
"""
# INLINE_BLIP_TYPE is not a separate type since it shouldn't be instantiated,
# only be used for introspection
INLINE_BLIP_TYPE = "INLINE_BLIP"
def __init__(self, element_type, **properties):
"""Initializes self with the specified type and any properties.
Args:
element_type: string typed member of ELEMENT_TYPE
properties: either a dictionary of initial properties, or a dictionary
with just one member properties that is itself a dictionary of
properties. This allows us to both use
e = Element(atype, prop1=val1, prop2=prop2...)
and
e = Element(atype, properties={prop1:val1, prop2:prop2..})
"""
if len(properties) == 1 and 'properties' in properties:
properties = properties['properties']
self._type = element_type
# as long as the operation_queue of an element in None, it is
# unattached. After an element is acquired by a blip, the blip
# will set the operation_queue to make sure all changes to the
# element are properly send to the server.
self._operation_queue = None
self._properties = properties.copy()
@property
def type(self):
"""The type of this element."""
return self._type
@classmethod
def from_json(cls, json):
"""Class method to instantiate an Element based on a json string."""
etype = json['type']
props = json['properties'].copy()
element_class = ALL.get(etype)
if not element_class:
# Unknown type. Server could be newer than we are
return Element(element_type=etype, properties=props)
return element_class.from_props(props)
def get(self, key, default=None):
"""Standard get interface."""
return self._properties.get(key, default)
def __getattr__(self, key):
return self._properties[key]
def serialize(self):
"""Custom serializer for Elements."""
return util.serialize({'properties': util.non_none_dict(self._properties),
'type': self._type})
class Input(Element):
"""A single-line input element."""
class_type = 'INPUT'
def __init__(self, name, value=''):
super(Input, self).__init__(Input.class_type,
name=name,
value=value,
default_value=value)
@classmethod
def from_props(cls, props):
return Input(name=props.get('name'), value=props.get('value'))
class Check(Element):
"""A checkbox element."""
class_type = 'CHECK'
def __init__(self, name, value=''):
super(Check, self).__init__(Check.class_type,
name=name, value=value, default_value=value)
@classmethod
def from_props(cls, props):
return Check(name=props.get('name'), value=props.get('value'))
class Button(Element):
"""A button element."""
class_type = 'BUTTON'
def __init__(self, name, value):
super(Button, self).__init__(Button.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return Button(name=props.get('name'), value=props.get('value'))
class Label(Element):
"""A label element."""
class_type = 'LABEL'
def __init__(self, label_for, caption):
super(Label, self).__init__(Label.class_type,
name=label_for, value=caption)
@classmethod
def from_props(cls, props):
return Label(label_for=props.get('name'), caption=props.get('value'))
class RadioButton(Element):
"""A radio button element."""
class_type = 'RADIO_BUTTON'
def __init__(self, name, group):
super(RadioButton, self).__init__(RadioButton.class_type,
name=name, value=group)
@classmethod
def from_props(cls, props):
return RadioButton(name=props.get('name'), group=props.get('value'))
class RadioButtonGroup(Element):
"""A group of radio buttons."""
class_type = 'RADIO_BUTTON_GROUP'
def __init__(self, name, value):
super(RadioButtonGroup, self).__init__(RadioButtonGroup.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return RadioButtonGroup(name=props.get('name'), value=props.get('value'))
class Password(Element):
"""A password element."""
class_type = 'PASSWORD'
def __init__(self, name, value):
super(Password, self).__init__(Password.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return Password(name=props.get('name'), value=props.get('value'))
class TextArea(Element):
"""A text area element."""
class_type = 'TEXTAREA'
def __init__(self, name, value):
super(TextArea, self).__init__(TextArea.class_type,
name=name, value=value)
@classmethod
def from_props(cls, props):
return TextArea(name=props.get('name'), value=props.get('value'))
class Line(Element):
"""A line element.
Note that Lines are represented in the text as newlines.
"""
class_type = 'LINE'
# Possible line types:
#: Designates line as H1, largest heading.
TYPE_H1 = 'h1'
#: Designates line as H2 heading.
TYPE_H2 = 'h2'
#: Designates line as H3 heading.
TYPE_H3 = 'h3'
#: Designates line as H4 heading.
TYPE_H4 = 'h4'
#: Designates line as H5, smallest heading.
TYPE_H5 = 'h5'
#: Designates line as a bulleted list item.
TYPE_LI = 'li'
# Possible values for align
#: Sets line alignment to left.
ALIGN_LEFT = 'l'
#: Sets line alignment to right.
ALIGN_RIGHT = 'r'
#: Sets line alignment to centered.
ALIGN_CENTER = 'c'
#: Sets line alignment to justified.
ALIGN_JUSTIFIED = 'j'
def __init__(self,
line_type=None,
indent=None,
alignment=None,
direction=None):
super(Line, self).__init__(Line.class_type,
lineType=line_type,
indent=indent,
alignment=alignment,
direction=direction)
@classmethod
def from_props(cls, props):
return Line(line_type=props.get('lineType'),
indent=props.get('indent'),
alignment=props.get('alignment'),
direction=props.get('direction'))
class Gadget(Element):
"""A gadget element."""
class_type = 'GADGET'
def __init__(self, url, props=None):
if props is None:
props = {}
props['url'] = url
super(Gadget, self).__init__(Gadget.class_type, properties=props)
@classmethod
def from_props(cls, props):
return Gadget(props.get('url'), props)
def serialize(self):
"""Gadgets allow for None values."""
return {'properties': self._properties, 'type': self._type}
def keys(self):
"""Get the valid keys for this gadget."""
return [x for x in self._properties.keys() if x != 'url']
class Installer(Element):
"""An installer element."""
class_type = 'INSTALLER'
def __init__(self, manifest):
super(Installer, self).__init__(Installer.class_type, manifest=manifest)
@classmethod
def from_props(cls, props):
return Installer(props.get('manifest'))
class Image(Element):
"""An image element."""
class_type = 'IMAGE'
def __init__(self, url='', width=None, height=None,
attachmentId=None, caption=None):
super(Image, self).__init__(Image.class_type, url=url, width=width,
height=height, attachmentId=attachmentId, caption=caption)
@classmethod
def from_props(cls, props):
props = dict([(key.encode('utf-8'), value)
for key, value in props.items()])
return apply(Image, [], props)
class Attachment(Element):
"""An attachment element.
To create a new attachment, caption and data are needed.
mimeType, attachmentId and attachmentUrl are sent via events.
"""
class_type = 'ATTACHMENT'
def __init__(self, caption=None, data=None, mimeType=None, attachmentId=None,
attachmentUrl=None):
Attachment.originalData = data
super(Attachment, self).__init__(Attachment.class_type, caption=caption,
data=data, mimeType=mimeType, attachmentId=attachmentId,
attachmentUrl=attachmentUrl)
def __getattr__(self, key):
if key and key == 'data':
return Attachment.originalData
return super(Attachment, self).__getattr__(key)
@classmethod
def from_props(cls, props):
props = dict([(key.encode('utf-8'), value)
for key, value in props.items()])
return apply(Attachment, [], props)
def serialize(self):
"""Serializes the attachment object into JSON.
The attachment data is base64 encoded.
"""
if self.data:
self._properties['data'] = base64.encodestring(self.data)
return super(Attachment, self).serialize()
def is_element(cls):
"""Returns whether the passed class is an element."""
try:
if not issubclass(cls, Element):
return False
h = hasattr(cls, 'class_type')
return hasattr(cls, 'class_type')
except TypeError:
return False
ALL = dict([(item.class_type, item) for item in globals().copy().values()
if is_element(item)])
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Script to run all unit tests in this package."""
import blip_test
import element_test
import module_test_runner
import ops_test
import robot_test
import util_test
import wavelet_test
def RunUnitTests():
"""Runs all registered unit tests."""
test_runner = module_test_runner.ModuleTestRunner()
test_runner.modules = [
blip_test,
element_test,
ops_test,
robot_test,
util_test,
wavelet_test,
]
test_runner.RunAllTests()
if __name__ == "__main__":
RunUnitTests()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""A module to run wave robots on app engine."""
import logging
import sys
import events
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class CapabilitiesHandler(webapp.RequestHandler):
"""Handler to forward a request ot a handler of a robot."""
def __init__(self, method, contenttype):
"""Initializes this handler with a specific robot."""
self._method = method
self._contenttype = contenttype
def get(self):
"""Handles HTTP GET request."""
self.response.headers['Content-Type'] = self._contenttype
self.response.out.write(self._method())
class ProfileHandler(webapp.RequestHandler):
"""Handler to forward a request ot a handler of a robot."""
def __init__(self, method, contenttype):
"""Initializes this handler with a specific robot."""
self._method = method
self._contenttype = contenttype
def get(self):
"""Handles HTTP GET request."""
self.response.headers['Content-Type'] = self._contenttype
# Respond with proxied profile if name specified
if self.request.get('name'):
self.response.out.write(self._method(self.request.get('name')))
else:
self.response.out.write(self._method())
class RobotEventHandler(webapp.RequestHandler):
"""Handler for the dispatching of events to various handlers to a robot.
This handler only responds to post events with a JSON post body. Its primary
task is to separate out the context data from the events in the post body
and dispatch all events in order. Once all events have been dispatched
it serializes the context data and its associated operations as a response.
"""
def __init__(self, robot):
"""Initializes self with a specific robot."""
self._robot = robot
def get(self):
"""Handles the get event for debugging.
This is useful for debugging but since event bundles tend to be
rather big it often won't fit for more complex requests.
"""
ops = self.request.get('events')
if ops:
self.request.body = events
self.post()
def post(self):
"""Handles HTTP POST requests."""
json_body = self.request.body
if not json_body:
# TODO(davidbyttow): Log error?
return
# Redirect stdout to stderr while executing handlers. This way, any stray
# "print" statements in bot code go to the error logs instead of breaking
# the JSON response sent to the HTTP channel.
saved_stdout, sys.stdout = sys.stdout, sys.stderr
json_body = unicode(json_body, 'utf8')
logging.info('Incoming: %s', json_body)
json_response = self._robot.process_events(json_body)
logging.info('Outgoing: %s', json_response)
sys.stdout = saved_stdout
# Build the response.
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write(json_response.encode('utf-8'))
def operation_error_handler(event, wavelet):
"""Default operation error handler, logging what went wrong."""
if isinstance(event, events.OperationError):
logging.error('Previously operation failed: id=%s, message: %s',
event.operation_id, event.error_message)
def appengine_post(url, data, headers):
result = urlfetch.fetch(
method='POST',
url=url,
payload=data,
headers=headers,
deadline=10)
return result.status_code, result.content
class RobotVerifyTokenHandler(webapp.RequestHandler):
"""Handler for the token_verify request."""
def __init__(self, robot):
"""Initializes self with a specific robot."""
self._robot = robot
def get(self):
"""Handles the get event for debugging. Ops usually too long."""
token, st = self._robot.get_verification_token_info()
logging.info('token=' + token)
if token is None:
self.error(404)
self.response.out.write('No token set')
return
if not st is None:
if self.request.get('st') != st:
self.response.out.write('Invalid st value passed')
return
self.response.out.write(token)
def create_robot_webapp(robot, debug=False, extra_handlers=None):
"""Returns an instance of webapp.WSGIApplication with robot handlers."""
if not extra_handlers:
extra_handlers = []
return webapp.WSGIApplication([('.*/_wave/capabilities.xml',
lambda: CapabilitiesHandler(
robot.capabilities_xml,
'application/xml')),
('.*/_wave/robot/profile',
lambda: ProfileHandler(
robot.profile_json,
'application/json')),
('.*/_wave/robot/jsonrpc',
lambda: RobotEventHandler(robot)),
('.*/_wave/verify_token',
lambda: RobotVerifyTokenHandler(robot)),
] + extra_handlers,
debug=debug)
def run(robot, debug=False, log_errors=True, extra_handlers=None):
"""Sets up the webapp handlers for this robot and starts listening.
A robot is typically setup in the following steps:
1. Instantiate and define robot.
2. Register various handlers that it is interested in.
3. Call Run, which will setup the handlers for the app.
For example:
robot = Robot('Terminator',
image_url='http://www.sky.net/models/t800.png',
profile_url='http://www.sky.net/models/t800.html')
robot.register_handler(WAVELET_PARTICIPANTS_CHANGED, KillParticipant)
run(robot)
Args:
robot: the robot to run. This robot is modified to use app engines
urlfetch for posting http.
debug: Optional variable that defaults to False and is passed through
to the webapp application to determine if it should show debug info.
log_errors: Optional flag that defaults to True and determines whether
a default handlers to catch errors should be setup that uses the
app engine logging to log errors.
extra_handlers: Optional list of tuples that are passed to the webapp
to install more handlers. For example, passing
[('/about', AboutHandler),] would install an extra about handler
for the robot.
"""
# App Engine expects to construct a class with no arguments, so we
# pass a lambda that constructs the appropriate handler with
# arguments from the enclosing scope.
if log_errors:
robot.register_handler(events.OperationError, operation_error_handler)
robot.http_post = appengine_post
app = create_robot_webapp(robot, debug, extra_handlers)
run_wsgi_app(app)
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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.
"""Unit tests for the blip module."""
import unittest
import blip
import element
import ops
import simplejson
TEST_BLIP_DATA = {
'childBlipIds': [],
'content': '\nhello world!\nanother line',
'contributors': ['robot@test.com', 'user@test.com'],
'creator': 'user@test.com',
'lastModifiedTime': 1000,
'parentBlipId': None,
'annotations': [{'range': {'start': 2, 'end': 3},
'name': 'key', 'value': 'val'}],
'waveId': 'test.com!w+g3h3im',
'waveletId': 'test.com!root+conv',
'elements':{'14':{'type':'GADGET','properties':{'url':'http://a/b.xml'}}},
}
CHILD_BLIP_ID = 'b+42'
ROOT_BLIP_ID = 'b+43'
class TestBlip(unittest.TestCase):
"""Tests the primary data structures for the wave model."""
def assertBlipStartswith(self, expected, totest):
actual = totest.text[:len(expected)]
self.assertEquals(expected, actual)
def new_blip(self, **args):
"""Create a blip for testing."""
data = TEST_BLIP_DATA.copy()
data.update(args)
res = blip.Blip(data, self.all_blips, self.operation_queue)
self.all_blips[res.blip_id] = res
return res
def setUp(self):
self.all_blips = {}
self.operation_queue = ops.OperationQueue()
def testBlipProperties(self):
root = self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID])
child = self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
self.assertEquals(ROOT_BLIP_ID, root.blip_id)
self.assertEquals(set([CHILD_BLIP_ID]), root.child_blip_ids)
self.assertEquals(set(TEST_BLIP_DATA['contributors']), root.contributors)
self.assertEquals(TEST_BLIP_DATA['creator'], root.creator)
self.assertEquals(TEST_BLIP_DATA['content'], root.text)
self.assertEquals(TEST_BLIP_DATA['lastModifiedTime'],
root.last_modified_time)
self.assertEquals(TEST_BLIP_DATA['parentBlipId'], root.parent_blip_id)
self.assertEquals(TEST_BLIP_DATA['waveId'], root.wave_id)
self.assertEquals(TEST_BLIP_DATA['waveletId'], root.wavelet_id)
self.assertEquals(TEST_BLIP_DATA['content'][3], root[3])
self.assertEquals(element.Gadget.class_type, root[14].type)
self.assertEquals('http://a/b.xml', root[14].url)
self.assertEquals('a', root.text[14])
self.assertEquals(len(TEST_BLIP_DATA['content']), len(root))
self.assertTrue(root.is_root())
self.assertFalse(child.is_root())
self.assertEquals(root, child.parent_blip)
def testBlipSerialize(self):
root = self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID])
serialized = root.serialize()
unserialized = blip.Blip(serialized, self.all_blips, self.operation_queue)
self.assertEquals(root.blip_id, unserialized.blip_id)
self.assertEquals(root.child_blip_ids, unserialized.child_blip_ids)
self.assertEquals(root.contributors, unserialized.contributors)
self.assertEquals(root.creator, unserialized.creator)
self.assertEquals(root.text, unserialized.text)
self.assertEquals(root.last_modified_time, unserialized.last_modified_time)
self.assertEquals(root.parent_blip_id, unserialized.parent_blip_id)
self.assertEquals(root.wave_id, unserialized.wave_id)
self.assertEquals(root.wavelet_id, unserialized.wavelet_id)
self.assertTrue(unserialized.is_root())
def testDocumentOperations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
newlines = [x for x in blip.find('\n')]
self.assertEquals(2, len(newlines))
blip.first('world').replace('jupiter')
bits = blip.text.split('\n')
self.assertEquals(3, len(bits))
self.assertEquals('hello jupiter!', bits[1])
blip.range(2, 5).delete()
self.assertBlipStartswith('\nho jupiter', blip)
blip.first('ho').insert_after('la')
self.assertBlipStartswith('\nhola jupiter', blip)
blip.at(3).insert(' ')
self.assertBlipStartswith('\nho la jupiter', blip)
def testElementHandling(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
url = 'http://www.test.com/image.png'
org_len = len(blip)
blip.append(element.Image(url=url))
elems = [elem for elem in blip.find(element.Image, url=url)]
self.assertEquals(1, len(elems))
elem = elems[0]
self.assertTrue(isinstance(elem, element.Image))
blip.at(1).insert('twelve chars')
self.assertTrue(blip.text.startswith('\ntwelve charshello'))
elem = blip[org_len + 12].value()
self.assertTrue(isinstance(elem, element.Image))
blip.first('twelve ').delete()
self.assertTrue(blip.text.startswith('\nchars'))
elem = blip[org_len + 12 - len('twelve ')].value()
self.assertTrue(isinstance(elem, element.Image))
blip.first('chars').replace(element.Image(url=url))
elems = [elem for elem in blip.find(element.Image, url=url)]
self.assertEquals(2, len(elems))
self.assertTrue(blip.text.startswith('\n hello'))
elem = blip[1].value()
self.assertTrue(isinstance(elem, element.Image))
def testAnnotationHandling(self):
key = 'style/fontWeight'
def get_bold():
for an in blip.annotations[key]:
if an.value == 'bold':
return an
return None
json = ('[{"range":{"start":3,"end":6},"name":"%s","value":"bold"}]'
% key)
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json))
self.assertEquals(1, len(blip.annotations))
self.assertNotEqual(None, get_bold().value)
self.assertTrue(key in blip.annotations)
# extend the bold annotation by adding:
blip.range(5, 8).annotate(key, 'bold')
self.assertEquals(1, len(blip.annotations))
self.assertEquals(8, get_bold().end)
# clip by adding a same keyed:
blip[4:12].annotate(key, 'italic')
self.assertEquals(2, len(blip.annotations[key]))
self.assertEquals(4, get_bold().end)
# now split the italic one:
blip.range(6, 7).clear_annotation(key)
self.assertEquals(3, len(blip.annotations[key]))
# test names and iteration
self.assertEquals(1, len(blip.annotations.names()))
self.assertEquals(3, len([x for x in blip.annotations]))
blip[3: 5].annotate('foo', 'bar')
self.assertEquals(2, len(blip.annotations.names()))
self.assertEquals(4, len([x for x in blip.annotations]))
blip[3: 5].clear_annotation('foo')
# clear the whole thing
blip.all().clear_annotation(key)
# getting to the key should now throw an exception
self.assertRaises(KeyError, blip.annotations.__getitem__, key)
def testBlipOperations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEquals(1, len(self.all_blips))
otherblip = blip.reply()
otherblip.append('hello world')
self.assertEquals('hello world', otherblip.text)
self.assertEquals(blip.blip_id, otherblip.parent_blip_id)
self.assertEquals(2, len(self.all_blips))
inline = blip.insert_inline_blip(3)
self.assertEquals(blip.blip_id, inline.parent_blip_id)
self.assertEquals(3, len(self.all_blips))
def testInsertInlineBlipCantInsertAtTheBeginning(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEquals(1, len(self.all_blips))
self.assertRaises(IndexError, blip.insert_inline_blip, 0)
self.assertEquals(1, len(self.all_blips))
def testDocumentModify(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('a text with text and then some text')
blip[7].insert('text ')
blip.all('text').replace('thing')
self.assertEquals('a thing thing with thing and then some thing',
blip.text)
def testIteration(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('aaa 012 aaa 345 aaa 322')
count = 0
prev = -1
for start, end in blip.all('aaa'):
count += 1
self.assertTrue(prev < start)
prev = start
self.assertEquals(3, count)
def testBlipRefValue(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
content = blip.text
content = content[:4] + content[5:]
del blip[4]
self.assertEquals(content, blip.text)
content = content[:2] + content[3:]
del blip[2:3]
self.assertEquals(content, blip.text)
blip[2:3] = 'bike'
content = content[:2] + 'bike' + content[3:]
self.assertEquals(content, blip.text)
url = 'http://www.test.com/image.png'
blip.append(element.Image(url=url))
self.assertEqual(url, blip.first(element.Image).url)
url2 = 'http://www.test.com/another.png'
blip[-1].update_element({'url': url2})
self.assertEqual(url2, blip.first(element.Image).url)
self.assertTrue(blip[3:5] == blip.text[3:5])
blip.append('geheim')
self.assertTrue(blip.first('geheim'))
self.assertFalse(blip.first(element.Button))
blip.append(element.Button(name='test1', value='Click'))
button = blip.first(element.Button)
button.update_element({'name': 'test2'})
self.assertEqual('test2', button.name)
def testReplace(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
blip.all().replace('\nxxxx')
blip.all('yyy').replace('zzz')
self.assertEqual('\nxxxx', blip.text)
def testDeleteRangeThatSpansAcrossAnnotationEndPoint(self):
json = ('[{"range":{"start":1,"end":3},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).delete()
self.assertEqual('\nF bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(2, blip.annotations['style'][0].end)
def testInsertBeforeAnnotationStartPoint(self):
json = ('[{"range":{"start":4,"end":9},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.at(4).insert('d and')
self.assertEqual('\nFood and bar.', blip.text)
self.assertEqual(9, blip.annotations['style'][0].start)
self.assertEqual(14, blip.annotations['style'][0].end)
def testDeleteRangeInsideAnnotation(self):
json = ('[{"range":{"start":1,"end":5},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).delete()
self.assertEqual('\nF bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(3, blip.annotations['style'][0].end)
def testReplaceInsideAnnotation(self):
json = ('[{"range":{"start":1,"end":5},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 4).replace('ooo')
self.assertEqual('\nFooo bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(6, blip.annotations['style'][0].end)
blip.range(2, 5).replace('o')
self.assertEqual('\nFo bar.', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(4, blip.annotations['style'][0].end)
def testReplaceSpanAnnotation(self):
json = ('[{"range":{"start":1,"end":4},"name":"style","value":"bold"}]')
blip = self.new_blip(blipId=ROOT_BLIP_ID,
annotations=simplejson.loads(json),
content='\nFoo bar.')
blip.range(2, 9).replace('')
self.assertEqual('\nF', blip.text)
self.assertEqual(1, blip.annotations['style'][0].start)
self.assertEqual(2, blip.annotations['style'][0].end)
def testSearchWithNoMatchShouldNotGenerateOperation(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID)
self.assertEqual(-1, blip.text.find(':('))
self.assertEqual(0, len(self.operation_queue))
blip.all(':(').replace(':)')
self.assertEqual(0, len(self.operation_queue))
def testBlipsRemoveWithId(self):
blip_dict = {
ROOT_BLIP_ID: self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID]),
CHILD_BLIP_ID: self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
}
blips = blip.Blips(blip_dict)
blips._remove_with_id(CHILD_BLIP_ID)
self.assertEqual(1, len(blips))
self.assertEqual(0, len(blips[ROOT_BLIP_ID].child_blip_ids))
def testAppendMarkup(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID, content='\nFoo bar.')
markup = '<p><span>markup<span> content</p>'
blip.append_markup(markup)
self.assertEqual(1, len(self.operation_queue))
self.assertEqual('\nFoo bar.\nmarkup content', blip.text)
def testBundledAnnotations(self):
blip = self.new_blip(blipId=ROOT_BLIP_ID, content='\nFoo bar.')
blip.append('not bold')
blip.append('bold', bundled_annotations=[('style/fontWeight', 'bold')])
self.assertEqual(2, len(blip.annotations))
self.assertEqual('bold', blip.annotations['style/fontWeight'][0].value)
def testInlineBlipOffset(self):
offset = 14
self.new_blip(blipId=ROOT_BLIP_ID,
childBlipIds=[CHILD_BLIP_ID],
elements={str(offset):
{'type': element.Element.INLINE_BLIP_TYPE,
'properties': {'id': CHILD_BLIP_ID}}})
child = self.new_blip(blipId=CHILD_BLIP_ID,
parentBlipId=ROOT_BLIP_ID)
self.assertEqual(offset, child.inline_blip_offset)
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Support for operations that can be applied to the server.
Contains classes and utilities for creating operations that are to be
applied on the server.
"""
import errors
import random
import util
import sys
PROTOCOL_VERSION = '0.21'
# Operation Types
WAVELET_APPEND_BLIP = 'wavelet.appendBlip'
WAVELET_SET_TITLE = 'wavelet.setTitle'
WAVELET_ADD_PARTICIPANT = 'wavelet.participant.add'
WAVELET_DATADOC_SET = 'wavelet.datadoc.set'
WAVELET_MODIFY_TAG = 'wavelet.modifyTag'
WAVELET_MODIFY_PARTICIPANT_ROLE = 'wavelet.modifyParticipantRole'
BLIP_CREATE_CHILD = 'blip.createChild'
BLIP_DELETE = 'blip.delete'
DOCUMENT_APPEND_MARKUP = 'document.appendMarkup'
DOCUMENT_INLINE_BLIP_INSERT = 'document.inlineBlip.insert'
DOCUMENT_MODIFY = 'document.modify'
ROBOT_CREATE_WAVELET = 'robot.createWavelet'
ROBOT_FETCH_WAVE = 'robot.fetchWave'
ROBOT_NOTIFY_CAPABILITIES_HASH = 'robot.notifyCapabilitiesHash'
class Operation(object):
"""Represents a generic operation applied on the server.
This operation class contains data that is filled in depending on the
operation type.
It can be used directly, but doing so will not result
in local, transient reflection of state on the blips. In other words,
creating a 'delete blip' operation will not remove the blip from the local
context for the duration of this session. It is better to use the OpBased
model classes directly instead.
"""
def __init__(self, method, opid, params):
"""Initializes this operation with contextual data.
Args:
method: Method to call or type of operation.
opid: The id of the operation. Any callbacks will refer to these.
params: An operation type dependent dictionary
"""
self.method = method
self.id = opid
self.params = params
def __str__(self):
return '%s[%s]%s' % (self.method, self.id, str(self.params))
def set_param(self, param, value):
self.params[param] = value
return self
def serialize(self, method_prefix=''):
"""Serialize the operation.
Args:
method_prefix: prefixed for each method name to allow for specifying
a namespace.
Returns:
a dict representation of the operation.
"""
if method_prefix and not method_prefix.endswith('.'):
method_prefix += '.'
return {'method': method_prefix + self.method,
'id': self.id,
'params': util.serialize(self.params)}
def set_optional(self, param, value):
"""Sets an optional parameter.
If value is None or "", this is a no op. Otherwise it calls
set_param.
"""
if value == '' or value is None:
return self
else:
return self.set_param(param, value)
class OperationQueue(object):
"""Wraps the queuing of operations using easily callable functions.
The operation queue wraps single operations as functions and queues the
resulting operations in-order. Typically there shouldn't be a need to
call this directly unless operations are needed on entities outside
of the scope of the robot. For example, to modify a blip that
does not exist in the current context, you might specify the wave, wavelet
and blip id to generate an operation.
Any calls to this will not be reflected in the robot in any way.
For example, calling wavelet_append_blip will not result in a new blip
being added to the robot, only an operation to be applied on the
server.
"""
# Some class global counters:
_next_operation_id = 1
def __init__(self, proxy_for_id=None):
self.__pending = []
self._capability_hash = 0
self._proxy_for_id = proxy_for_id
def _new_blipdata(self, wave_id, wavelet_id, initial_content='',
parent_blip_id=None):
"""Creates JSON of the blip used for this session."""
temp_blip_id = 'TBD_%s_%s' % (wavelet_id,
hex(random.randint(0, sys.maxint)))
return {'waveId': wave_id,
'waveletId': wavelet_id,
'blipId': temp_blip_id,
'content': initial_content,
'parentBlipId': parent_blip_id}
def _new_waveletdata(self, domain, participants):
"""Creates an ephemeral WaveletData instance used for this session.
Args:
domain: the domain to create the data for.
participants initially on the wavelet
Returns:
Blipdata (for the rootblip), WaveletData.
"""
wave_id = domain + '!TBD_%s' % hex(random.randint(0, sys.maxint))
wavelet_id = domain + '!conv+root'
root_blip_data = self._new_blipdata(wave_id, wavelet_id)
participants = set(participants)
wavelet_data = {'waveId': wave_id,
'waveletId': wavelet_id,
'rootBlipId': root_blip_data['blipId'],
'participants': participants}
return root_blip_data, wavelet_data
def __len__(self):
return len(self.__pending)
def __iter__(self):
return self.__pending.__iter__()
def clear(self):
self.__pending = []
def proxy_for(self, proxy):
"""Return a view of this operation queue with the proxying for set to proxy.
This method returns a new instance of an operation queue that shares the
operation list, but has a different proxying_for_id set so the robot using
this new queue will send out operations with the proxying_for field set.
"""
res = OperationQueue()
res.__pending = self.__pending
res._capability_hash = self._capability_hash
res._proxy_for_id = proxy
return res
def set_capability_hash(self, capability_hash):
self._capability_hash = capability_hash
def serialize(self):
first = Operation(ROBOT_NOTIFY_CAPABILITIES_HASH,
'0',
{'capabilitiesHash': self._capability_hash,
'protocolVersion': PROTOCOL_VERSION})
operations = [first] + self.__pending
res = util.serialize(operations)
return res
def copy_operations(self, other_queue):
"""Copy the pending operations from other_queue into this one."""
for op in other_queue:
self.__pending.append(op)
def new_operation(self, method, wave_id, wavelet_id, props=None, **kwprops):
"""Creates and adds a new operation to the operation list."""
if props is None:
props = {}
props.update(kwprops)
props['waveId'] = wave_id
props['waveletId'] = wavelet_id
if self._proxy_for_id:
props['proxyingFor'] = self._proxy_for_id
operation = Operation(method,
'op%s' % OperationQueue._next_operation_id,
props)
self.__pending.append(operation)
OperationQueue._next_operation_id += 1
return operation
def wavelet_append_blip(self, wave_id, wavelet_id, initial_content=''):
"""Appends a blip to a wavelet.
Args:
wave_id: The wave id owning the containing wavelet.
wavelet_id: The wavelet id that this blip should be appended to.
initial_content: optionally the content to start with
Returns:
JSON representing the information of the new blip.
"""
blip_data = self._new_blipdata(wave_id, wavelet_id, initial_content)
self.new_operation(WAVELET_APPEND_BLIP, wave_id,
wavelet_id, blipData=blip_data)
return blip_data
def wavelet_add_participant(self, wave_id, wavelet_id, participant_id):
"""Adds a participant to a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
participant_id: Id of the participant to add.
Returns:
data for the root_blip, wavelet
"""
return self.new_operation(WAVELET_ADD_PARTICIPANT, wave_id, wavelet_id,
participantId=participant_id)
def wavelet_datadoc_set(self, wave_id, wavelet_id, name, data):
"""Sets a key/value pair on the data document of a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
name: The key name for this data.
data: The value of the data to set.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_DATADOC_SET, wave_id, wavelet_id,
datadocName=name, datadocValue=data)
def robot_create_wavelet(self, domain, participants=None, message=''):
"""Creates a new wavelet.
Args:
domain: the domain to create the wave in
participants: initial participants on this wavelet or None if none
message: an optional payload that is returned with the corresponding
event.
Returns:
data for the root_blip, wavelet
"""
if participants is None:
participants = []
blip_data, wavelet_data = self._new_waveletdata(domain, participants)
op = self.new_operation(ROBOT_CREATE_WAVELET,
wave_id=wavelet_data['waveId'],
wavelet_id=wavelet_data['waveletId'],
waveletData=wavelet_data)
op.set_optional('message', message)
return blip_data, wavelet_data
def robot_fetch_wave(self, wave_id, wavelet_id):
"""Requests a snapshot of the specified wave.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(ROBOT_FETCH_WAVE, wave_id, wavelet_id)
def wavelet_set_title(self, wave_id, wavelet_id, title):
"""Sets the title of a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
title: The title to set.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_SET_TITLE, wave_id, wavelet_id,
waveletTitle=title)
def wavelet_modify_participant_role(
self, wave_id, wavelet_id, participant_id, role):
"""Modify the role of a participant on a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
participant_id: Id of the participant to add.
role: the new roles
Returns:
data for the root_blip, wavelet
"""
return self.new_operation(WAVELET_MODIFY_PARTICIPANT_ROLE, wave_id,
wavelet_id, participantId=participant_id,
participantRole=role)
def wavelet_modify_tag(self, wave_id, wavelet_id, tag, modify_how=None):
"""Modifies a tag in a wavelet.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
tag: The tag (a string).
modify_how: (optional) how to apply the tag. The default is to add
the tag. Specify 'remove' to remove. Specify None or 'add' to
add.
Returns:
The operation created.
"""
return self.new_operation(WAVELET_MODIFY_TAG, wave_id, wavelet_id,
name=tag).set_optional("modify_how", modify_how)
def blip_create_child(self, wave_id, wavelet_id, blip_id):
"""Creates a child blip of another blip.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
JSON of blip for which further operations can be applied.
"""
blip_data = self._new_blipdata(wave_id, wavelet_id, parent_blip_id=blip_id)
self.new_operation(BLIP_CREATE_CHILD, wave_id, wavelet_id,
blipId=blip_id,
blipData=blip_data)
return blip_data
def blip_delete(self, wave_id, wavelet_id, blip_id):
"""Deletes the specified blip.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(BLIP_DELETE, wave_id, wavelet_id, blipId=blip_id)
def document_append_markup(self, wave_id, wavelet_id, blip_id, content):
"""Appends content with markup to a document.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
content: The markup content to append.
Returns:
The operation created.
"""
return self.new_operation(DOCUMENT_APPEND_MARKUP, wave_id, wavelet_id,
blipId=blip_id, content=content)
def document_modify(self, wave_id, wavelet_id, blip_id):
"""Creates and queues a document modify operation
The returned operation still needs to be filled with details before
it makes sense.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
Returns:
The operation created.
"""
return self.new_operation(DOCUMENT_MODIFY,
wave_id,
wavelet_id,
blipId=blip_id)
def document_inline_blip_insert(self, wave_id, wavelet_id, blip_id, position):
"""Inserts an inline blip at a specific location.
Args:
wave_id: The wave id owning that this operation is applied to.
wavelet_id: The wavelet id that this operation is applied to.
blip_id: The blip id that this operation is applied to.
position: The position in the document to insert the blip.
Returns:
JSON data for the blip that was created for further operations.
"""
inline_blip_data = self._new_blipdata(wave_id, wavelet_id)
inline_blip_data['parentBlipId'] = blip_id
self.new_operation(DOCUMENT_INLINE_BLIP_INSERT, wave_id, wavelet_id,
blipId=blip_id,
index=position,
blipData=inline_blip_data)
return inline_blip_data
| Python |
#!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Tests for google3.walkabout.externalagents.api.commandline_robot_runner."""
__author__ = 'douwe@google.com (Douwe Osinga)'
import StringIO
from google3.pyglib import app
from google3.pyglib import flags
from google3.testing.pybase import googletest
from google3.walkabout.externalagents.api import commandline_robot_runner
from google3.walkabout.externalagents.api import events
FLAGS = flags.FLAGS
BLIP_JSON = ('{"wdykLROk*13":'
'{"lastModifiedTime":1242079608457,'
'"contributors":["someguy@test.com"],'
'"waveletId":"test.com!conv+root",'
'"waveId":"test.com!wdykLROk*11",'
'"parentBlipId":null,'
'"version":3,'
'"creator":"someguy@test.com",'
'"content":"\\nContent!",'
'"blipId":"wdykLROk*13",'
'"annotations":[{"range":{"start":0,"end":1},'
'"name":"user/e/otherguy@test.com","value":"Other"}],'
'"elements":{},'
'"childBlipIds":[]}'
'}')
WAVELET_JSON = ('{"lastModifiedTime":1242079611003,'
'"title":"A title",'
'"waveletId":"test.com!conv+root",'
'"rootBlipId":"wdykLROk*13",'
'"dataDocuments":null,'
'"creationTime":1242079608457,'
'"waveId":"test.com!wdykLROk*11",'
'"participants":["someguy@test.com","monty@appspot.com"],'
'"creator":"someguy@test.com",'
'"version":5}')
EVENTS_JSON = ('[{"timestamp":1242079611003,'
'"modifiedBy":"someguy@test.com",'
'"properties":{"participantsRemoved":[],'
'"participantsAdded":["monty@appspot.com"]},'
'"type":"WAVELET_PARTICIPANTS_CHANGED"}]')
TEST_JSON = '{"blips":%s,"wavelet":%s,"events":%s}' % (
BLIP_JSON, WAVELET_JSON, EVENTS_JSON)
class CommandlineRobotRunnerTest(googletest.TestCase):
def testSimpleFlow(self):
FLAGS.eventdef_wavelet_participants_changed = 'x'
flag = 'eventdef_' + events.WaveletParticipantsChanged.type.lower()
setattr(FLAGS, flag, 'w.title="New title!"')
input_stream = StringIO.StringIO(TEST_JSON)
output_stream = StringIO.StringIO()
commandline_robot_runner.run_bot(input_stream, output_stream)
res = output_stream.getvalue()
self.assertTrue('wavelet.setTitle' in res)
def main(unused_argv):
googletest.main()
if __name__ == '__main__':
app.run()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Unit tests for the ops module."""
import unittest
import ops
class TestOperation(unittest.TestCase):
"""Test case for Operation class."""
def testFields(self):
op = ops.Operation(ops.WAVELET_SET_TITLE, 'opid02',
{'waveId': 'wavelet-id',
'title': 'a title'})
self.assertEqual(ops.WAVELET_SET_TITLE, op.method)
self.assertEqual('opid02', op.id)
self.assertEqual(2, len(op.params))
def testConstructModifyTag(self):
q = ops.OperationQueue()
op = q.wavelet_modify_tag('waveid', 'waveletid', 'tag')
self.assertEqual(3, len(op.params))
op = q.wavelet_modify_tag(
'waveid', 'waveletid', 'tag', modify_how='remove')
self.assertEqual(4, len(op.params))
def testConstructRobotFetchWave(self):
q = ops.OperationQueue('proxyid')
op = q.robot_fetch_wave('wave1', 'wavelet1')
self.assertEqual(3, len(op.params))
self.assertEqual('proxyid', op.params['proxyingFor'])
self.assertEqual('wave1', op.params['waveId'])
self.assertEqual('wavelet1', op.params['waveletId'])
class TestOperationQueue(unittest.TestCase):
"""Test case for OperationQueue class."""
def testSerialize(self):
q = ops.OperationQueue()
q.set_capability_hash('hash')
op = q.wavelet_modify_tag('waveid', 'waveletid', 'tag')
json = q.serialize()
self.assertEqual(2, len(json))
self.assertEqual('robot.notifyCapabilitiesHash', json[0]['method'])
self.assertEqual('hash', json[0]['params']['capabilitiesHash'])
self.assertEqual(ops.PROTOCOL_VERSION, json[0]['params']['protocolVersion'])
self.assertEqual('wavelet.modifyTag', json[1]['method'])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright (C) 2009 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 library containing various helpers used by the API."""
import re
CUSTOM_SERIALIZE_METHOD_NAME = 'serialize'
MARKUP_RE = re.compile(r'<([^>]*?)>')
def force_unicode(object):
""" Return the Unicode string version of object, with UTF-8 encoding. """
if isinstance(object, unicode):
return object
return unicode(str(object), 'utf-8')
def parse_markup(markup):
"""Parses a bit of markup into robot compatible text.
For now this is a rough approximation.
"""
def replace_tag(group):
if not group.groups:
return ''
tag = group.groups()[0].split(' ', 1)[0]
if (tag == 'p' or tag == 'br'):
return '\n'
return ''
return MARKUP_RE.sub(replace_tag, markup)
def is_iterable(inst):
"""Returns whether or not this is a list, tuple, set or dict .
Note that this does not return true for strings.
"""
return hasattr(inst, '__iter__')
def is_dict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems')
def is_user_defined_new_style_class(obj):
"""Returns whether or not the specified instance is a user-defined type."""
return type(obj).__module__ != '__builtin__'
def lower_camel_case(s):
"""Converts a string to lower camel case.
Examples:
foo => foo
foo_bar => fooBar
foo__bar => fooBar
foo_bar_baz => fooBarBaz
Args:
s: The string to convert to lower camel case.
Returns:
The lower camel cased string.
"""
return reduce(lambda a, b: a + (a and b.capitalize() or b), s.split('_'))
def non_none_dict(d):
"""return a copy of the dictionary without none values."""
return dict([a for a in d.items() if not a[1] is None])
def _serialize_attributes(obj):
"""Serializes attributes of an instance.
Iterates all attributes of an object and invokes serialize if they are
public and not callable.
Args:
obj: The instance to serialize.
Returns:
The serialized object.
"""
data = {}
for attr_name in dir(obj):
if attr_name.startswith('_'):
continue
attr = getattr(obj, attr_name)
if attr is None or callable(attr):
continue
# Looks okay, serialize it.
data[lower_camel_case(attr_name)] = serialize(attr)
return data
def _serialize_dict(d):
"""Invokes serialize on all of its key/value pairs.
Args:
d: The dict instance to serialize.
Returns:
The serialized dict.
"""
data = {}
for k, v in d.items():
data[lower_camel_case(k)] = serialize(v)
return data
def serialize(obj):
"""Serializes any instance.
If this is a user-defined instance
type, it will first check for a custom Serialize() function and use that
if it exists. Otherwise, it will invoke serialize all of its public
attributes. Lists and dicts are serialized trivially.
Args:
obj: The instance to serialize.
Returns:
The serialized object.
"""
if is_user_defined_new_style_class(obj):
if obj and hasattr(obj, CUSTOM_SERIALIZE_METHOD_NAME):
method = getattr(obj, CUSTOM_SERIALIZE_METHOD_NAME)
if callable(method):
return method()
return _serialize_attributes(obj)
elif is_dict(obj):
return _serialize_dict(obj)
elif is_iterable(obj):
return [serialize(v) for v in obj]
return obj
class StringEnum(object):
"""Enum like class that is configured with a list of values.
This class effectively implements an enum for Elements, except for that
the actual values of the enums will be the string values.
"""
def __init__(self, *values):
for name in values:
setattr(self, name, name)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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.
"""Module defines the ModuleTestRunnerClass."""
import unittest
class ModuleTestRunner(object):
"""Responsible for executing all test cases in a list of modules."""
def __init__(self, module_list=None, module_test_settings=None):
self.modules = module_list or []
self.settings = module_test_settings or {}
def RunAllTests(self):
"""Executes all tests present in the list of modules."""
runner = unittest.TextTestRunner()
for module in self.modules:
for setting, value in self.settings.iteritems():
try:
setattr(module, setting, value)
except AttributeError:
print '\nError running ' + str(setting)
print '\nRunning all tests in module', module.__name__
runner.run(unittest.defaultTestLoader.loadTestsFromModule(module))
| 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.