code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from assigned_cases_model import AssignedCasesModel
from case import Case
from list_people import get_name_for_email
| Python |
import logging
from PyQt4 import QtCore
from fogmini import global_objects
from fogmini.utils import get_config_value
from case import Case
from list_people import get_name_for_email
class AssignedCasesModel(QtCore.QAbstractListModel):
def __init__(self, *args, **kwargs):
QtCore.QAbstractListModel.__init__(self, *args, **kwargs)
self._data = None
global_objects.app.login_successful.connect(self.get_assigned_cases)
def index(self, row, column, parent):
return self.createIndex(row, column)
def parent(self):
return QtCore.QModelIndex()
def data(self, index, role):
if role in [QtCore.Qt.DisplayRole, QtCore.Qt.EditRole]:
return self._data[index.row()]
else:
return QtCore.QVariant()
def rowCount(self, parent):
if self._data is None:
return 0
else:
return len(self._data)
def headerData(self, section, orientation, role):
return "Case Name"
def get_assigned_cases(self):
name = get_name_for_email(get_config_value("username", "").toString())
logging.getLogger("AssignedCasesModel").debug("Getting cases assigned to %s." % (name, ))
cases = Case.search(q='assignedto:"%s"' % (name, ))
print cases
self._data = ["%s: %s" % (case.id, case.title) for case in cases]
| Python |
import sys
from PyQt4 import QtCore, QtGui
from fogmini import global_objects
from fogmini.application import FogMiniApplication
from fogmini.login import login
from fogmini.tray_icon import SystemTrayIcon
def main():
global_objects.app = FogMiniApplication(sys.argv)
base_widget = QtGui.QWidget()
global_objects.tray = SystemTrayIcon(base_widget)
global_objects.tray.show()
# Delay the login to give the system tray icon time to appear.
QtCore.QTimer.singleShot(1000, login)
sys.exit(global_objects.app.exec_())
| Python |
import os.path
from PyQt4 import QtGui
import fogmini
from fogmini import global_objects
from fogmini.api.fogbugz import FogBugzAPIError
from fogmini.dialogs import LoginDetails
from fogmini.tray_menu import TrayMenu
base_path = os.path.dirname(fogmini.__file__)
class SystemTrayIcon(QtGui.QSystemTrayIcon):
def __init__(self, parent):
QtGui.QSystemTrayIcon.__init__(self, QtGui.QIcon(QtGui.QPixmap(os.path.join(base_path, "logo.gif"))), parent)
self.menu = TrayMenu()
self.setContextMenu(self.menu)
self.activated.connect(self.activated_slot)
global_objects.app.login_successful.connect(self.login_successful)
self.show()
def activated_slot(self, activation_reason):
if activation_reason == 3:
# Left click
ld = LoginDetails()
ld.exec_()
#elif activation_reason == 1:
# self.menu.populate()
def login_successful(self):
self.showMessage("Login Successful", "You have been successfully authenticated with FogBugz.", 5000)
| Python |
from PyQt4 import QtCore, QtGui
class FogMiniApplication(QtGui.QApplication):
login_successful = QtCore.pyqtSignal()
| Python |
from fogmini import global_objects
from fogmini.api.fogbugz import FogBugz
from fogmini.utils import get_config_value, set_config_value
def login():
base_url = get_config_value("base_url", "").toString()
if base_url == "":
global_objects.tray.showMessage("Settings Required", "Left click on the FogBugz icon to enter your login details.")
else:
username = get_config_value("username", "").toString()
password = get_config_value("password", "").toString()
global_objects.fb = FogBugz(unicode(base_url))
global_objects.fb.logon(username, password)
global_objects.app.login_successful.emit()
| Python |
from login import LoginDetails
| Python |
from PyQt4 import QtGui
from fogmini.login import login
from fogmini.utils import get_config_value, set_config_value
class LoginDetails(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
layout = QtGui.QFormLayout()
self.host_name = QtGui.QLineEdit(get_config_value("base_url", "http://example.fogbugz.com").toString(), self)
layout.addRow("Host Name", self.host_name)
self.username = QtGui.QLineEdit(get_config_value("username", "").toString(), self)
layout.addRow("Username", self.username)
self.password = QtGui.QLineEdit(get_config_value("password", "").toString(), self)
layout.addRow("Password", self.password)
self.button_box = QtGui.QDialogButtonBox()
self.button_box.addButton("Log In", 0)
self.button_box.addButton("Cancel", 1)
layout.addRow(self.button_box)
self.button_box.accepted.connect(self.accept)
self.button_box.rejected.connect(self.reject)
self.setLayout(layout)
self.resize(300, 100)
def accept(self):
set_config_value("base_url", self.host_name.text())
set_config_value("username", self.username.text())
set_config_value("password", self.password.text())
login()
QtGui.QDialog.accept()
| Python |
from PyQt4 import QtGui
from fogmini.data import AssignedCasesModel, Case
class TrayMenu(QtGui.QMenu):
def __init__(self, *args, **kwargs):
QtGui.QMenu.__init__(self, *args, **kwargs)
self.aboutToShow.connect(self.populate)
def populate(self):
self.clear()
startWorkLabelAction = QtGui.QWidgetAction(self)
startWorkLabelAction.setDefaultWidget(QtGui.QLabel("Start Working On:"))
startWorkLabel = self.addAction(startWorkLabelAction)
startWorkEditAction = StartWorkWidgetAction(self)
startWorkEdit = self.addAction(startWorkEditAction)
self.addSeparator()
exitAction = self.addAction("Exit")
exitAction.triggered.connect(self.exit)
def exit(self):
QtGui.QApplication.quit()
class StartWorkWidgetAction(QtGui.QWidgetAction):
def createWidget(self, parent):
lineedit = QtGui.QLineEdit(parent)
lineedit.model = AssignedCasesModel()
lineedit.completer = QtGui.QCompleter(lineedit.model, lineedit)
lineedit.setCompleter(lineedit.completer)
lineedit.editingFinished.connect(self.start_working(lineedit))
return lineedit
def start_working(self, lineedit):
def f():
lineedit.completer.popup().setVisible(False)
global_objects.tray.contextMenu().setVisible(False)
bugname = lineedit.text()
if ":" in bugname:
bugname = bugname.split(":")[0]
try:
global_objects.fb.startWork(ixbug=bugname)
except FogBugzAPIError, e:
global_objects.tray.showMessage("Can't Start Working", unicode(e), 5000)
else:
case = Case.search(q=str(bugname))
global_objects.tray.showMessage("Started Working", "Working on %s (%i)" % (case.title, case.id), 5000)
return f
| Python |
from config import get_config_value, set_config_value
| Python |
from PyQt4 import QtCore
CONFIG = None
def _load_config():
"""Load the config object."""
global CONFIG # pylint: disable-msg=W0603
CONFIG = QtCore.QSettings("Andrew Wilkinson", "DjangoDE")
def get_config_value(key, default=None):
"""Get the value from settings that was stored with key."""
if CONFIG is None:
_load_config()
return CONFIG.value(key, default)
def set_config_value(key, value):
"""Save a value into the configuration."""
if CONFIG is None:
_load_config()
CONFIG.setValue(key, value)
| Python |
#!/usr/bin/python -S
import os
import sys
import commands
program_name = sys.argv[1]
candidates = sorted([x.strip() for x in commands.getoutput(""" wmctrl -l -x | awk -v win="%s" 'tolower($0) ~ win {print $1;}' """ % (program_name, )).split("\n") if x !=''])
out_file = file("/home/soma/debug.txt", "a")
print candidates
if candidates :
active_window_string = commands.getoutput("""xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)" """)
active_window_string = active_window_string[active_window_string.find("#")+4:].strip()
active_window = "0x" + "0" * (8-len(active_window_string)) + active_window_string
out_file.write("\n")
out_file.write(",".join(candidates))
out_file.write("\n")
out_file.write( active_window)
out_file.write("\n")
next_window = None
if active_window not in candidates:
out_file.write("Not In")
next_window = candidates[0]
else:
out_file.write("In")
next_window = candidates[ (candidates.index(active_window)+1) % len(candidates)]
os.system(""" wmctrl -i -a "%s" """ % (next_window,) )
else :
out_file.write("Starting")
os.system("%s &" % (program_name,))
out_file.close()
| Python |
#!/usr/bin/python -S
import os
import sys
import commands
program_name = sys.argv[1]
candidates = sorted([x.strip() for x in commands.getoutput(""" wmctrl -l -x | awk -v win="%s" 'tolower($0) ~ win {print $1;}' """ % (program_name, )).split("\n") if x !=''])
out_file = file("/home/soma/debug.txt", "a")
print candidates
if candidates :
active_window_string = commands.getoutput("""xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)" """)
active_window_string = active_window_string[active_window_string.find("#")+4:].strip()
active_window = "0x" + "0" * (8-len(active_window_string)) + active_window_string
out_file.write("\n")
out_file.write(",".join(candidates))
out_file.write("\n")
out_file.write( active_window)
out_file.write("\n")
next_window = None
if active_window not in candidates:
out_file.write("Not In")
next_window = candidates[0]
else:
out_file.write("In")
next_window = candidates[ (candidates.index(active_window)+1) % len(candidates)]
os.system(""" wmctrl -i -a "%s" """ % (next_window,) )
else :
out_file.write("Starting")
os.system("%s &" % (program_name,))
out_file.close()
| Python |
#!/usr/bin/env python
import os
import sys
import json
import csv
from bs4 import BeautifulSoup
from aisikl.app import Application, assert_ops
from fladgejt.login import create_client
from fladgejt.helpers import find_option, find_row
from console import settings
def prihlas_sa():
username = os.environ['AIS_USERNAME']
password = os.environ['AIS_PASSWORD']
client = create_client(settings.servers[0], dict(type='cosignpassword', username=username, password=password))
if os.environ.get('AIS_VERBOSE'): client.context.print_logs = True
return client
def otvor_reporty(client):
url = '/ais/servlets/WebUIServlet?appClassName=ais.gui.rp.zs.RPZS003App&kodAplikacie=RPZS003&uiLang=SK'
app, ops = Application.open(client.context, url)
app.awaited_open_main_dialog(ops)
return app
def spusti_report(client, app, vrchol_stromu, kod_zostavy, parametre, vystupny_format):
# selectnem vrchol v strome vlavo
app.d.dzTree.select(vrchol_stromu)
# v tabulke vyberiem riadok s danym kodom
app.d.sysTable.select(find_row(app.d.sysTable.all_rows(), kod=kod_zostavy))
# v menu stlacim "Spustenie"
with app.collect_operations() as ops:
app.d.sysSpustenieAction.execute()
if not parametre:
app.awaited_open_dialog(ops)
else:
assert_ops(ops, 'openDialog', 'openDialog')
app.open_dialog(*ops[0].args)
app.open_dialog(*ops[1].args)
# v dialogu nastavim parametre
for index, (label, value) in enumerate(parametre):
label_id = 'inputLabel' + str(index+1)
input_id = 'inputTextField' + str(index+1)
if app.d.components[label_id].text != label:
raise AISBehaviorError('%s mal byt %r' % (label_id, label))
app.d.components[input_id].write(value)
if 'inputLabel' + str(len(parametre)+1) in app.d.components:
raise AISBehaviorError('Zostava ma privela parametrov')
# stlacim OK, dialog sa zavrie
with app.collect_operations() as ops:
app.d.enterButton.click()
app.awaited_close_dialog(ops)
# nastavim format vystupu
app.d.vystupComboBox.select(find_option(app.d.vystupComboBox.options, title=vystupny_format))
# NESTLACAM OK, TYM SA DIALOG ZAVRIE
# (for fun si najdi v mailinglistoch ako na to Vinko pravidelne kazdy rok nadava)
# miesto toho v menu stlacim "Ulozit ako"
with app.collect_operations() as ops:
app.d.ulozitAkoAction.execute()
response = app.awaited_shell_exec(ops)
# nakoniec ten dialog mozem zavriet (a pouzijem X v rohu, ako kulturny clovek)
with app.collect_operations() as ops:
app.d.click_close_button()
app.awaited_close_dialog(ops)
return response
def html_to_csv(client, text, output_filename):
client.context.log('import', 'Parsing exported HTML')
soup = BeautifulSoup(text)
client.context.log('import', 'Parsed HTML data')
table = soup.find_all('table')[-1]
data = []
for tr in table.find_all('tr', recursive=False):
row = [' '.join(td.get_text().split())
for td in tr.find_all(['th', 'td'])]
data.append(row)
client.context.log('import', 'Extracted table values')
with open(output_filename, 'w', encoding='utf8', newline='') as f:
csvwriter = csv.writer(f, delimiter=';', lineterminator='\n')
csvwriter.writerows(data)
client.context.log('import', 'Wrote CSV output')
def export_ucitel_predmet(args):
akademicky_rok, fakulta, output_filename = args
client = prihlas_sa()
app = otvor_reporty(client)
parametre = [
('Akademický rok', akademicky_rok),
('Fakulta', fakulta),
]
response = spusti_report(client, app, 'nR0/ST/11', 'UNIBA03', parametre, 'html')
response.encoding = 'cp1250'
html_to_csv(client, response.text, output_filename)
def export_pocet_studentov(args):
akademicky_rok, fakulta, semester, typ, output_filename = args
if typ != 'faculty' and typ != 'all':
raise Exception("typ musi byt faculty alebo all")
client = prihlas_sa()
app = otvor_reporty(client)
parametre = [
('Akademický rok', akademicky_rok),
('Smester', semester),
('Predmety z fakulty', fakulta),
('Študenti z fakulty', fakulta if typ == 'faculty' else '%'),
]
response = spusti_report(client, app, 'nR0/RH/5', 'ZAPSTU', parametre, 'tbl')
response.encoding = 'cp1250'
with open(output_filename, 'w', encoding='utf8') as f:
f.write(response.text)
def export_predmet_katedra(args):
akademicky_rok, fakulta, semester, output_filename = args
client = prihlas_sa()
app = client._open_register_predmetov()
app.d.fakultaUniverzitaComboBox.select(find_option(app.d.fakultaUniverzitaComboBox.options, id=fakulta))
app.d.akRokComboBox.select(find_option(app.d.akRokComboBox.options, id=akademicky_rok))
app.d.semesterComboBox.select(find_option(app.d.semesterComboBox.options, id=semester))
app.d.zobrazitPredmetyButton.click()
with app.collect_operations() as ops:
app.d.exportButton.click()
with app.collect_operations() as ops2:
app.awaited_abort_box(ops)
with app.collect_operations() as ops3:
app.awaited_abort_box(ops2)
response = app.awaited_shell_exec(ops3)
response.encoding = 'utf8'
html_to_csv(client, response.text, output_filename)
commands = {
'ucitel-predmet': export_ucitel_predmet,
'pocet-studentov': export_pocet_studentov,
'predmet-katedra': export_predmet_katedra,
}
if __name__ == '__main__':
command, *args = sys.argv[1:]
if command not in commands: raise Exception(list(commands.keys()))
commands[command](args)
| Python |
#!/usr/bin/python
import sys;
root_dict = {}
x = sys.stdin.read()
for file in x.rstrip().split(' '):
path_components = file.split('/');
current_dict = root_dict;
for path_segment in path_components:
path_segment = path_segment.replace(".", "_").replace("-","_");
if path_segment not in current_dict:
current_dict[path_segment]={}
current_dict = current_dict[path_segment]
def print_dict(level, dictionary, path):
for key in dictionary.keys():
if dictionary[key].keys():
print "".rjust(level*4), "subgraph", "cluster"+path+"_"+key, "{"
print "".rjust(level*4), " color=blue"
print "".rjust(level*4), " label=\"",key,"\""
print_dict(level+1, dictionary[key], path+"_"+key)
print "".rjust(level*4), "}"
else:
print "".rjust(level*4), key.replace("_php","")
print_dict(0, root_dict, "");
| Python |
import os
import sys
import json
from os.path import join, dirname, abspath
anketa_root = join(dirname(abspath(__file__)), '../../..')
votr_root = join(anketa_root, 'vendor/svt/votr')
sys.path.insert(0, votr_root)
# --------------------------------------------------
def main():
from fladgejt.login import create_client
json_input = json.load(sys.stdin)
fakulta = json_input['fakulta']
semestre = json_input['semestre']
relevantne_roky = [ak_rok for ak_rok, sem in semestre]
client = create_client(json_input['server'], json_input['params'])
# full_name = client.get_full_name() # TODO
is_student = False
subjects = []
if client.get_som_student():
studia = client.get_studia()
for studium in studia:
if fakulta and studium.organizacna_jednotka != fakulta: continue # TODO: pouzivat zapisny_list.organizacna_jednotka, ked bude v REST API
for zapisny_list in client.get_zapisne_listy(studium.studium_key):
if zapisny_list.akademicky_rok not in relevantne_roky: continue
is_student = True
for predmet in client.get_hodnotenia(zapisny_list.zapisny_list_key)[0]:
if [zapisny_list.akademicky_rok, predmet.semester] not in semestre: continue
subjects.append(dict(
skratka=predmet.skratka,
nazov=predmet.nazov,
semester=predmet.semester,
akRok=zapisny_list.akademicky_rok,
rokStudia=zapisny_list.rocnik,
studijnyProgram=dict(skratka=studium.sp_skratka, nazov=studium.sp_popis),
))
client.logout()
result = {}
# result['full_name'] = full_name
result['is_student'] = is_student
result['subjects'] = subjects
print(json.dumps(result))
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
import codecs
import re
import jinja2
import markdown
def process_slides():
with codecs.open('../../presentation-output.html', 'w', encoding='utf8') as outfile:
md = codecs.open('slides.md', encoding='utf8').read()
md_slides = md.split('\n---\n')
print 'Compiled %s slides.' % len(md_slides)
slides = []
# Process each slide separately.
for md_slide in md_slides:
slide = {}
sections = md_slide.split('\n\n')
# Extract metadata at the beginning of the slide (look for key: value)
# pairs.
metadata_section = sections[0]
metadata = parse_metadata(metadata_section)
slide.update(metadata)
remainder_index = metadata and 1 or 0
# Get the content from the rest of the slide.
content_section = '\n\n'.join(sections[remainder_index:])
html = markdown.markdown(content_section)
slide['content'] = postprocess_html(html, metadata)
slides.append(slide)
template = jinja2.Template(open('base.html').read())
outfile.write(template.render(locals()))
def parse_metadata(section):
"""Given the first part of a slide, returns metadata associated with it."""
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
val = line[colon_index + 1:].strip()
metadata[key] = val
return metadata
def postprocess_html(html, metadata):
"""Returns processed HTML to fit into the slide template format."""
if metadata.get('build_lists') and metadata['build_lists'] == 'true':
html = html.replace('<ul>', '<ul class="build">')
html = html.replace('<ol>', '<ol class="build">')
return html
if __name__ == '__main__':
process_slides()
| Python |
#!/usr/bin/env python
# This script will convert all TABs to SPACEs in the Fog root directory
# and all sub-directories (recursive).
#
# Converted sequences:
# - The \r\n sequence is converted to \n (To UNIX line-ending).
# - The \t (TAB) sequence is converted to TAB_REPLACEMENT which should
# be two spaces.
#
# Affected files:
# - *.cmake
# - *.cpp
# - *.h
import os
TAB_REPLACEMENT = " "
for root, dirs, files in os.walk("../"):
for f in files:
if f.lower().endswith(".cpp") or f.lower().endswith(".h") or f.lower().endswith(".cmake") or f.lower().endswith(".txt"):
path = os.path.join(root, f)
fh = open(path, "rb")
data = fh.read()
fh.close()
fixed = False
if "\r" in data:
print "Fixing \\r\\n in: " + path
data = data.replace("\r", "")
fixed = True
if "\t" in data:
print "Fixing TABs in: " + path
data = data.replace("\t", TAB_REPLACEMENT)
fixed = True
if fixed:
fh = open(path, "wb")
fh.truncate()
fh.write(data)
fh.close()
| Python |
#!/usr/bin/env python
# This script will convert all TABs to SPACEs in the Fog root directory
# and all sub-directories (recursive).
#
# Converted sequences:
# - The \r\n sequence is converted to \n (To UNIX line-ending).
# - The \t (TAB) sequence is converted to TAB_REPLACEMENT which should
# be two spaces.
#
# Affected files:
# - *.cmake
# - *.cpp
# - *.h
import os
TAB_REPLACEMENT = " "
for root, dirs, files in os.walk("../"):
for f in files:
if f.lower().endswith(".cpp") or f.lower().endswith(".h") or f.lower().endswith(".cmake") or f.lower().endswith(".txt"):
path = os.path.join(root, f)
fh = open(path, "rb")
data = fh.read()
fh.close()
fixed = False
if "\r" in data:
print "Fixing \\r\\n in: " + path
data = data.replace("\r", "")
fixed = True
if "\t" in data:
print "Fixing TABs in: " + path
data = data.replace("\t", TAB_REPLACEMENT)
fixed = True
if fixed:
fh = open(path, "wb")
fh.truncate()
fh.write(data)
fh.close()
| Python |
#!/usr/bin/env python
# This script will convert all TABs to SPACEs in the Fog root directory
# and all sub-directories (recursive).
#
# Converted sequences:
# - The \r\n sequence is converted to \n (To UNIX line-ending).
# - The \t (TAB) sequence is converted to TAB_REPLACEMENT which should
# be two spaces.
#
# Affected files:
# - *.cmake
# - *.cpp
# - *.h
import os
TAB_REPLACEMENT = " "
for root, dirs, files in os.walk("../Src"):
for f in files:
path = os.path.join(root, f)
# Remove the stupid "._" files created by MAC.
if (len(f) > 2 and f[0] == u'.' and f[1] == u'_') or file == u".DS_Store":
print "Removing file: " + path
os.remove(path)
continue
if f.lower().endswith(".cpp") or f.lower().endswith(".h") or f.lower().endswith(".cmake") or f.lower().endswith(".txt"):
fh = open(path, "rb")
data = fh.read()
fh.close()
fixed = False
if " \n" in data:
print "Fixing space before \\n in: " + path
while True:
oldl = len(data)
data = data.replace(" \n", "\n")
if oldl == len(data): break;
fixed = True
if "\r" in data:
print "Fixing \\r\\n in: " + path
data = data.replace("\r", "")
fixed = True
if "\t" in data:
print "Fixing TABs in: " + path
data = data.replace("\t", TAB_REPLACEMENT)
fixed = True
if fixed:
fh = open(path, "wb")
fh.truncate()
fh.write(data)
fh.close()
| Python |
#!/usr/bin/env python
# Unicode Reports:
#
# http://www.unicode.org/reports/tr44/
# (Unicode Character Database)
# =============================================================================
# generate-unicode.py - Generate unicode tables, based on Unicode 6.0.
#
# This script must be modified when new unicode standard is released. Currently
# it's tuned for Unicode 6.0, and it is possible to regenerate tables when only
# small additions are done to the UCD, but when enums are added, or some rules
# changed, it's needed to review the unicode reports and to modify the code. If
# there is something not expected in the unicode database then fatal error
# exception should be raised.
# =============================================================================
import os
# -----------------------------------------------------------------------------
# [UCD-Helpers]
# -----------------------------------------------------------------------------
def log(str):
print(str)
# Convert integer to string representing unicode code-point "U+cp".
def ucd(cp):
if cp <= 0xFFFF:
return "U+%04X" % cp
else:
return "U+%06X" % cp
def uch(cp):
if cp <= 0xFFFF:
return "0x%04X" % cp
else:
return "0x%06X" % cp
def Literal(ch):
if ch == 0:
return "\\'"
else:
return "'" + ch + "'"
# Convert cp to UTF-16 surrogate pair.
def SurrogatePairOf(cp):
assert cp >= 0x10000
return (55232 + (cp >> 10), 56320 + (cp & 0x03FF))
# Align a to n.
def Align(a, n):
while (a % n) != 0:
a += 1
return a
# Split data using ';' as a separator and strip all leading/trailing whitespaces.
def SplitData(line):
data = line.split(';')
for i in xrange(len(data)):
data[i] = data[i].strip()
return data
def GetCharRange(item):
if ".." in item:
items = item.split("..")
first = int(items[0], 16)
last = int(items[1], 16)
return (first, last)
else:
code = int(item, 16)
return (code, code)
# Line iterator, all comments and empty lines are removed.
def LineIterator(file):
while True:
line = file.readline()
if len(line) == 0:
break
pos = line.find("#")
if pos != -1:
line = line[0:pos]
line = line.strip(" \t\r\n")
if len(line) != 0:
yield line
def DownloadFile(url, targetName):
import urllib
dirName = os.path.dirname(targetName)
if not os.path.isdir(dirName):
os.makedirs(dirName)
urllib.urlretrieve(url, targetName)
# -----------------------------------------------------------------------------
# [UCD-Files]
# -----------------------------------------------------------------------------
# The UCD files needed to run this script, downloaded on-demand.
UCD_FILES = [
"ucd/auxiliary/GraphemeBreakProperty.txt",
"ucd/auxiliary/SentenceBreakProperty.txt",
"ucd/auxiliary/WordBreakProperty.txt",
"ucd/ArabicShaping.txt",
"ucd/BidiMirroring.txt",
"ucd/Blocks.txt",
"ucd/CaseFolding.txt",
"ucd/CompositionExclusions.txt",
"ucd/DerivedAge.txt",
"ucd/DerivedNormalizationProps.txt",
"ucd/EastAsianWidth.txt",
"ucd/LineBreak.txt",
"ucd/NormalizationCorrections.txt",
"ucd/PropertyValueAliases.txt",
"ucd/Scripts.txt",
"ucd/ScriptExtensions.txt",
"ucd/SpecialCasing.txt",
"ucd/UnicodeData.txt"
]
# Unicode version.
UCD_VERSION="6.1.0"
# Local directory to store the files.
UCD_DIRECTORY = "tmp/"
# URL where to download if the files are missing (when check-outed).
UCD_PUBLIC_URL = "http://www.unicode.org/Public/" + UCD_VERSION
def PrepareFiles():
log("-- Checking for unicode files")
for name in UCD_FILES:
targetName = UCD_DIRECTORY + name
try:
f = open(targetName, 'rb')
f.close()
except:
log(" " + name + ": Not found, starting download...")
DownloadFile(UCD_PUBLIC_URL + "/" + name, targetName)
log(" " + name + ": Downloaded.")
# -----------------------------------------------------------------------------
# [UCD-Constants]
# -----------------------------------------------------------------------------
MAX_CODE_POINT = 0x10FFFF
NUM_CODE_POINTS = MAX_CODE_POINT + 1
# 17 bits, see Fog::CharProperty.
MAX_PAIRED_DIFF = 2**16 - 1
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# The data index in UnicodeData.txt file, entries separated by ;
UCD_VALUE = 0
UCD_NAME = 1
UCD_CATEGORY = 2
UCD_COMBINING_CLASS = 3
UCD_BIDI = 4
UCD_DECOMPOSITION = 5
UCD_DECIMAL_DIGIT_VALUE = 6
UCD_DIGIT_VALUE = 7
UCD_NUMERIC_VALUE = 8
UCD_MIRRORED = 9
UCD_OLD_NAME = 10
UCD_COMMENT = 11
UCD_UPPERCASE = 12
UCD_LOWERCASE = 13
UCD_TITLECASE = 14
# Enumeration, mapping between the Unicode string name, internal ID value,
# and Fog constant name (without the "CHAR_XXX_" prefix).
class Enum(object):
def __init__(self, name, default, data, alt={}):
self._name = name
self._map = {}
self._arr = []
self._default = default
for i in xrange(len(data)):
item = data[i]
self._map[item[0]] = i
self._arr.append(item[1])
# Alternative map.
for key in alt:
self.addAlias(key, self._map[alt[key]])
# Get id value from a given key.
def get(self, key):
if isinstance(key, int):
return self._arr[key]
if not key:
return self._default
if key in self._map:
return self._map[key]
raise KeyError(self._name + " - There is no key " + key)
# Translate the id value to a Fog-Enum value.
def fog(self, id):
return self._arr[id]
def count(self):
return len(self._arr)
def addAlias(self, key, value):
self._map[key] = value
def generateEnum(self):
s = ""
for i in xrange(len(self._arr)):
s += " " + self._name + "_" + self._arr[i] + " = " + str(i)
s += ",\n"
s += "\n"
s += " " + self._name + "_COUNT" + " = " + str(len(self._arr)) + "\n"
return s
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# Bidi.
CHAR_BIDI = Enum(name="BIDI", default=0,
data=[
["EN" , "EN" ],
["ES" , "ES" ],
["ET" , "ET" ],
["AN" , "AN" ],
["AL" , "AL" ],
["WS" , "WS" ],
["CS" , "CS" ],
["B" , "B" ],
["S" , "S" ],
["L" , "L" ],
["LRE" , "LRE" ],
["LRO" , "LRO" ],
["R" , "R" ],
["RLE" , "RLE" ],
["RLO" , "RLO" ],
["PDF" , "PDF" ],
["NSM" , "NSM" ],
["BN" , "BN" ],
["ON" , "ON" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# Unicode character categories.
CHAR_CATEGORY = Enum(name="CATEGORY", default=0,
data=[
["" , "NONE" ],
["Lu" , "LU" ],
["Ll" , "LL" ],
["Lt" , "LT" ],
["Lm" , "LM" ],
["Lo" , "LO" ],
["Nd" , "ND" ],
["Nl" , "NL" ],
["No" , "NO" ],
["Mc" , "MC" ],
["Me" , "ME" ],
["Mn" , "MN" ],
["Zs" , "ZS" ],
["Zl" , "ZL" ],
["Zp" , "ZP" ],
["Cc" , "CC" ],
["Cf" , "CF" ],
["Cs" , "CS" ],
["Co" , "CO" ],
["Cn" , "CN" ],
["Pc" , "PC" ],
["Pd" , "PD" ],
["Ps" , "PS" ],
["Pe" , "PE" ],
["Pi" , "PI" ],
["Pf" , "PF" ],
["Po" , "PO" ],
["Sm" , "SM" ],
["Sc" , "SC" ],
["Sk" , "SK" ],
["So" , "SO" ]
]
)
CHAR_CASE_FOLDING = Enum(name="CASE_FOLDING", default=0,
data=[
["" , "NONE" ],
["F" , "FULL" ],
["S" , "SIMPLE" ],
["C" , "COMMON" ],
["T" , "SPECIAL" ]
]
)
# Decomposition.
CHAR_DECOMPOSITION = Enum(name="DECOMPOSITION", default=0,
data=[
["" , "NONE" ],
["<canonical>" , "CANONICAL" ],
["<font>" , "FONT" ],
["<noBreak>" , "NOBREAK" ],
# Arabic.
["<initial>" , "INITIAL" ],
["<medial>" , "MEDIAL" ],
["<final>" , "FINAL" ],
["<isolated>" , "ISOLATED" ],
# Script form
["<circle>" , "CIRCLE" ],
["<super>" , "SUPER" ],
["<sub>" , "SUB" ],
["<vertical>" , "VERTICAL" ],
["<wide>" , "WIDE" ],
["<narrow>" , "NARROW" ],
["<small>" , "SMALL" ],
["<square>" , "SQUARE" ],
["<fraction>" , "FRACTION" ],
["<compat>" , "COMPAT" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/GraphemeBreakProperty.txt
#
# Grapheme break properties.
CHAR_GRAPHEME_BREAK = Enum(name="GRAPHEME_BREAK", default=0,
data=[
["" , "XX" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Control" , "CN" ],
["Extend" , "EX" ],
["Prepend" , "PP" ],
["SpacingMark" , "SM" ],
# Hungul jamo (L/V/T) and syllable (LV/LVT).
["L" , "L" ],
["V" , "V" ],
["T" , "T" ],
["LV" , "LV" ],
["LVT" , "LVT" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/WordBreakProperty.txt
#
# Work break properties.
CHAR_WORD_BREAK = Enum(name="WORD_BREAK", default=0,
data=[
["" , "OTHER" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Newline" , "NL" ],
["Extend" , "EXTEND" ],
["Format" , "FO" ],
["Katakana" , "KA" ],
["ALetter" , "LE" ],
["MidLetter" , "ML" ],
["MidNum" , "MN" ],
["MidNumLet" , "MB" ],
["Numeric" , "NU" ],
["ExtendNumLet" , "EX" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/SentenceBreakProperty.txt
#
# Sentence break properties.
CHAR_SENTENCE_BREAK = Enum(name="SENTENCE_BREAK", default=0,
data=[
["Other" , "XX" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Extend" , "EX" ],
["Sep" , "SE" ],
["Format" , "FO" ],
["Sp" , "SP" ],
["Lower" , "LO" ],
["Upper" , "UP" ],
["OLetter" , "LE" ],
["Numeric" , "NU" ],
["ATerm" , "AT" ],
["STerm" , "ST" ],
["Close" , "CL" ],
["SContinue" , "SC" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/LineBreak.txt
#
# Line break properties.
CHAR_LINE_BREAK = Enum(name="LINE_BREAK", default=16,
data=[
["BK" , "BK" ],
["CR" , "CR" ],
["LF" , "LF" ],
["CM" , "CM" ],
["SG" , "SG" ],
["GL" , "GL" ],
["CB" , "CB" ],
["SP" , "SP" ],
["ZW" , "ZW" ],
["NL" , "NL" ],
["WJ" , "WJ" ],
["JL" , "JL" ],
["JV" , "JV" ],
["JT" , "JT" ],
["H2" , "H2" ],
["H3" , "H3" ],
["XX" , "XX" ],
["OP" , "OP" ],
["CL" , "CL" ],
["CP" , "CP" ],
["QU" , "QU" ],
["NS" , "NS" ],
["EX" , "EX" ],
["SY" , "SY" ],
["IS" , "IS" ],
["PR" , "PR" ],
["PO" , "PO" ],
["NU" , "NU" ],
["AL" , "AL" ],
["ID" , "ID" ],
["IN" , "IN" ],
["HY" , "HY" ],
["BB" , "BB" ],
["BA" , "BA" ],
["SA" , "SA" ],
["AI" , "AI" ],
["B2" , "B2" ],
# New in Unicode 6.1.0
["HL" , "HL" ],
["CJ" , "CJ" ]
]
)
# Joining.
CHAR_JOINING = Enum(name="JOINING", default=0,
data=[
["U" , "U" ],
["L" , "L" ],
["R" , "R" ],
["D" , "D" ],
["C" , "C" ],
["T" , "T" ]
]
)
CHAR_EAW = Enum(name="CHAR_EAW", default=0,
data=[
["A" , "A" ],
["N" , "N" ],
["F" , "F" ],
["H" , "H" ],
["Na" , "NA" ],
["W" , "W" ]
]
)
# Map type (Fog-Framework specific optimization).
CHAR_MAPPING = Enum(name="CHAR_MAPPING", default=0,
data=[
["None" , "NONE" ],
["Uppercase" , "LOWERCASE" ],
["Lowercase" , "UPPERCASE" ],
["Mirror" , "MIRROR" ],
["Digit" , "DIGIT" ],
["Special" , "SPECIAL" ]
]
)
CHAR_QUICK_CHECK = Enum(name="CHAR_QUICK_CHECK", default=0,
data=[
["No" , "NO" ],
["Yes" , "YES" ],
["Maybe" , "MAYBE" ]
],
alt={
"N": "No",
"Y": "Yes",
"M": "Maybe"
}
)
CHAR_VERSION = Enum(name="CHAR_VERSION", default=0,
# Normal map, used by DerivedAge.txt.
data=[
["" , "UNASSIGNED" ],
["1.1" , "V1_1" ],
["2.0" , "V2_0" ],
["2.1" , "V2_1" ],
["3.0" , "V3_0" ],
["3.1" , "V3_1" ],
["3.2" , "V3_2" ],
["4.0" , "V4_0" ],
["4.1" , "V4_1" ],
["5.0" , "V5_0" ],
["5.1" , "V5_1" ],
["5.2" , "V5_2" ],
["6.0" , "V6_0" ],
["6.1" , "V6_1" ]
],
# Alternative map, used by NormalizationCorrections.txt.
alt={
"3.2.0": "3.2",
"4.0.0": "4.0"
}
)
TEXT_SCRIPT = Enum(name="TEXT_SCRIPT", default=0,
data=[
["Unknown" , "UNKNOWN" ],
["Common" , "COMMON" ],
["Inherited" , "INHERITED" ],
["Latin" , "LATIN" ],
["Arabic" , "ARABIC" ],
["Armenian" , "ARMENIAN" ],
["Avestan" , "AVESTAN" ],
["Balinese" , "BALINESE" ],
["Bamum" , "BAMUM" ],
["Batak" , "BATAK" ],
["Bengali" , "BENGALI" ],
["Bopomofo" , "BOPOMOFO" ],
["Brahmi" , "BRAHMI" ],
["Braille" , "BRAILLE" ],
["Buginese" , "BUGINESE" ],
["Buhid" , "BUHID" ],
["Canadian_Aboriginal" , "CANADIAN_ABORIGINAL" ],
["Carian" , "CARIAN" ],
["Chakma" , "CHAKMA" ],
["Cham" , "CHAM" ],
["Cherokee" , "CHEROKEE" ],
["Coptic" , "COPTIC" ],
["Cuneiform" , "CUNEIFORM" ],
["Cypriot" , "CYPRIOT" ],
["Cyrillic" , "CYRILLIC" ],
["Devanagari" , "DEVANAGARI" ],
["Deseret" , "DESERET" ],
["Egyptian_Hieroglyphs" , "EGYPTIAN_HIEROGLYPHS" ],
["Ethiopic" , "ETHIOPIC" ],
["Georgian" , "GEORGIAN" ],
["Glagolitic" , "GLAGOLITIC" ],
["Gothic" , "GOTHIC" ],
["Greek" , "GREEK" ],
["Gujarati" , "GUJARATI" ],
["Gurmukhi" , "GURMUKHI" ],
["Han" , "HAN" ],
["Hangul" , "HANGUL" ],
["Hanunoo" , "HANUNOO" ],
["Hebrew" , "HEBREW" ],
["Hiragana" , "HIRAGANA" ],
["Imperial_Aramaic" , "IMPERIAL_ARAMAIC" ],
["Inscriptional_Pahlavi" , "INSCRIPTIONAL_PAHLAVI"],
["Inscriptional_Parthian", "INSCRIPTIONAL_PARTHIAN"],
["Javanese" , "JAVANESE" ],
["Kaithi" , "KAITHI" ],
["Kannada" , "KANNADA" ],
["Katakana" , "KATAKANA" ],
["Kayah_Li" , "KAYAH_LI" ],
["Kharoshthi" , "KHAROSHTHI" ],
["Khmer" , "KHMER" ],
["Lao" , "LAO" ],
["Lepcha" , "LEPCHA" ],
["Limbu" , "LIMBU" ],
["Linear_B" , "LINEAR_B" ],
["Lisu" , "LISU" ],
["Lycian" , "LYCIAN" ],
["Lydian" , "LYDIAN" ],
["Malayalam" , "MALAYALAM" ],
["Mandaic" , "MANDAIC" ],
["Meetei_Mayek" , "MEETEI_MAYEK" ],
["Meroitic_Cursive" , "MEROITIC_CURSIVE" ],
["Meroitic_Hieroglyphs" , "MEROITIC_HIEROGLYPHS" ],
["Miao" , "MIAO" ],
["Mongolian" , "MONGOLIAN" ],
["Myanmar" , "MAYANMAR" ],
["New_Tai_Lue" , "NEW_TAI_LUE" ],
["Nko" , "NKO" ],
["Ogham" , "OGHAM" ],
["Ol_Chiki" , "OL_CHIKI" ],
["Old_Italic" , "OLD_ITALIC" ],
["Old_Persian" , "OLD_PERSIAN" ],
["Old_South_Arabian" , "OLD_SOUTH_ARABIAN" ],
["Old_Turkic" , "OLD_TURKIC" ],
["Oriya" , "ORIYA" ],
["Osmanya" , "OSMANYA" ],
["Phags_Pa" , "PHAGS_PA" ],
["Phoenician" , "PHOENICIAN" ],
["Rejang" , "REJANG" ],
["Runic" , "RUNIC" ],
["Samaritan" , "SAMARITAN" ],
["Saurashtra" , "SAURASHTRA" ],
["Sharada" , "SHARADA" ],
["Shavian" , "SHAVIAN" ],
["Sinhala" , "SINHALA" ],
["Sora_Sompeng" , "SORA_SOMPENG" ],
["Sundanese" , "SUNDANESE" ],
["Syloti_Nagri" , "SYLOTI_NAGRI" ],
["Syriac" , "SYRIAC" ],
["Tagalog" , "TAGALOG" ],
["Tagbanwa" , "TAGBANWA" ],
["Tai_Le" , "TAI_LE" ],
["Tai_Tham" , "TAI_THAM" ],
["Tai_Viet" , "TAI_VIET" ],
["Takri" , "TAKRI" ],
["Tamil" , "TAMIL" ],
["Telugu" , "TELUGU" ],
["Thaana" , "THAANA" ],
["Thai" , "THAI" ],
["Tibetan" , "TIBETAN" ],
["Tifinagh" , "TIFINAGH" ],
["Ugaritic" , "UGARITIC" ],
["Vai" , "VAI" ],
["Yi" , "YI" ]
]
)
TEXT_SCRIPT_ISO15924_FROM = {}
TEXT_SCRIPT_ISO15924_TO = {}
COMPOSITION_ID_HANGUL = 0xFF
# -----------------------------------------------------------------------------
# [UCD-CharProperty]
# -----------------------------------------------------------------------------
class CharProperty(object):
used = 0
codePoint = 0
name = ""
category = CHAR_CATEGORY.get("")
combiningClass = 0
bidi = CHAR_BIDI.get("L")
joining = CHAR_JOINING.get("U")
digitValue = -1
decompositionType = CHAR_DECOMPOSITION.get("")
decompositionData = None
compositionExclusion = False
nfdQC = CHAR_QUICK_CHECK.get("Yes")
nfcQC = CHAR_QUICK_CHECK.get("Yes")
nfkdQC = CHAR_QUICK_CHECK.get("Yes")
nfkcQC = CHAR_QUICK_CHECK.get("Yes")
fullCaseFolding = None
simpleCaseFolding = 0
specialCaseFolding = 0
graphemeBreak = CHAR_GRAPHEME_BREAK.get("")
wordBreak = CHAR_WORD_BREAK.get("")
sentenceBreak = CHAR_SENTENCE_BREAK.get("")
lineBreak = CHAR_LINE_BREAK.get("")
lowercase = 0
uppercase = 0
titlecase = 0
mirror = 0
hasComposition = 0
compositionId = 0
script = TEXT_SCRIPT.get("")
eaw = CHAR_EAW.get("")
version = CHAR_VERSION.get("")
# Fog-specific memory optimization.
mapping = CHAR_MAPPING.get("None")
def __init__(self, **kw):
self.decompositionData = []
self.fullCaseFolding = []
for prop in kw:
setattr(self, prop, kw[prop])
# Get the difference between the code-point and uppercase.
@property
def upperdiff(self):
if self.uppercase != 0:
return self.uppercase - self.codePoint
else:
return 0
# Get the difference between the code-point and lowercase.
@property
def lowerdiff(self):
if self.lowercase != 0:
return self.lowercase - self.codePoint
else:
return 0
# Get the difference between the code-point and titlecase.
@property
def titlediff(self):
if self.titlecase != 0:
return self.titlecase - self.codePoint
else:
return 0
# Get the difference between the code-point and mirrored one.
@property
def mirrordiff(self):
if self.mirror != 0:
return self.mirror - self.codePoint
else:
return 0
@property
def isSpace(self):
return self.category == CHAR_CATEGORY.get("Zs") or \
self.category == CHAR_CATEGORY.get("Zl") or \
self.category == CHAR_CATEGORY.get("Zp") or \
(self.codePoint >= 9 and self.codePoint <= 13)
# -----------------------------------------------------------------------------
# [UCD-BlockProperty]
# -----------------------------------------------------------------------------
class BlockProperty(object):
def __init__(self, **kw):
self.first = 0
self.last = 0
self.name = ""
for prop in kw:
setattr(self, prop, kw[prop])
# -----------------------------------------------------------------------------
# [UCD-NormalizationCorrection]
# -----------------------------------------------------------------------------
class NormalizationCorrection(object):
def __init__(self, **kw):
self.code = 0
self.original = 0
self.corrected = 0
self.version = CHAR_VERSION.get("")
for prop in kw:
setattr(self, prop, kw[prop])
# -----------------------------------------------------------------------------
# [UCD-Globals (Data readed from UCD)]
# -----------------------------------------------------------------------------
# Character to CharacterProperty mapping.
CharList = []
# Block list (from ucd/Blocks.txt").
BlockList = []
# Normalization corrections.
NormalizationCorrectionsList = []
def PrepareTables():
log("-- Preparing...")
for i in xrange(NUM_CODE_POINTS):
CharList.append(CharProperty(codePoint=i))
# -----------------------------------------------------------------------------
# [UCD-CompositionPair]
# -----------------------------------------------------------------------------
class CompositionPair(object):
def __init__(self, a, b, ab):
self.a = a
self.b = b
self.ab = ab
# -----------------------------------------------------------------------------
# [UCD-Read]
# -----------------------------------------------------------------------------
def ReadPropertyValueAliases():
log("-- Read ucd/PropertyValueAliases.txt")
f = open(UCD_DIRECTORY + "ucd/PropertyValueAliases.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
# Just for safety
if len(data) < 3:
continue
property = data[0]
name = data[2]
aliases = [data[1]]
if len(data) > 3:
for i in xrange(3, len(data)):
aliases.append(data[i])
# Sentence break aliases
if property == "SB":
for alias in aliases:
CHAR_SENTENCE_BREAK.addAlias(alias, CHAR_SENTENCE_BREAK.get(name))
# Script aliases.
if property == "sc":
# Ignore these.
if name == "Katakana_Or_Hiragana":
continue
textScript = TEXT_SCRIPT.get(name)
for alias in aliases:
TEXT_SCRIPT.addAlias(alias, textScript)
for alias in aliases:
TEXT_SCRIPT_ISO15924_FROM[alias] = textScript
if not str(textScript) in TEXT_SCRIPT_ISO15924_TO:
TEXT_SCRIPT_ISO15924_TO[str(textScript)] = alias
f.close()
def ReadUnicodeData():
log("-- Read ucd/UnicodeData.txt")
f = open(UCD_DIRECTORY + "ucd/UnicodeData.txt", 'r')
first = -1
last = -1
for line in LineIterator(f):
data = SplitData(line)
code = int(data[UCD_VALUE], 16)
name = data[UCD_NAME]
# Parse a single code-point or range of code-points.
if name.startswith("<") and name.find("First") != -1:
first = code
last = -1
continue
if name.startswith("<") and name.find("Last") != -1:
assert(first != -1)
last = code
else:
first = code
last = code
# Process the character (or range).
for code in xrange(first, last+1):
c = CharList[code]
c.used = 1
c.category = CHAR_CATEGORY.get(data[UCD_CATEGORY])
c.combiningClass = int(data[UCD_COMBINING_CLASS])
# Bidi-category.
if data[UCD_BIDI]:
c.bidi = CHAR_BIDI.get(data[UCD_BIDI])
else:
# Default BIDI property is related to the code-point.
#
# The unassigned code points that default to AL are in the ranges:
# [\u0600-\u07BF \uFB50-\uFDFF \uFE70-\uFEFF]
# - minus noncharacter code points.
if code >= 0x00000600 and code <= 0x000007BF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0000FB50 and code <= 0x0000FDFF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0000FE70 and code <= 0x0000FEFF: c.bidi = CHAR_BIDI.get("AL")
# The unassigned code points that default to R are in the ranges:
# [\u0590-\u05FF \u07C0-\u08FF \uFB1D-\uFB4F \U00010800-\U00010FFF \U0001E800-\U0001EFFF]
if code >= 0x00000590 and code <= 0x000005FF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x000007C0 and code <= 0x000008FF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x0000FB1D and code <= 0x0000FB4F: c.bidi = CHAR_BIDI.get("R")
if code >= 0x00010800 and code <= 0x00010FFF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x0001E800 and code <= 0x0001EFFF: c.bidi = CHAR_BIDI.get("R")
# ----------------------------------------------------------------------
# Changed in Unicode 6.1.0 - U+08A0..U+08FF and U+1EE00..U+1EEFF changed
# from R to AL.
# ----------------------------------------------------------------------
if code >= 0x000008A0 and code <= 0x000008FF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0001EE00 and code <= 0x0001EEFF: c.bidi = CHAR_BIDI.get("AL")
# Digit value.
if len(data[UCD_DIGIT_VALUE]):
c.digitValue = int(data[UCD_DIGIT_VALUE], 10)
# Uppercase/Lowercase/Titlecase - Assign the case change only if it
# differs to the original code-point.
if data[UCD_TITLECASE] == "":
# If the TITLECASE is NULL, it has the value UPPERCASE.
data[UCD_TITLECASE] = data[UCD_UPPERCASE]
if data[UCD_UPPERCASE] and int(data[UCD_UPPERCASE], 16) != code:
c.uppercase = int(data[UCD_UPPERCASE], 16)
if data[UCD_LOWERCASE] and int(data[UCD_LOWERCASE], 16) != code:
c.lowercase = int(data[UCD_LOWERCASE], 16)
if data[UCD_TITLECASE] and int(data[UCD_TITLECASE], 16) != code:
c.titlecase = int(data[UCD_TITLECASE], 16)
# Joining (from Unicode 6.0):
# - Those that not explicitly listed that are of General Category Mn, Me, or Cf
# have joining type T.
# - All others not explicitly listed have joining type U.
if c.category == CHAR_CATEGORY.get("Mn") or c.category == CHAR_CATEGORY.get("Me") or c.category == CHAR_CATEGORY.get("Cf"):
c.joining = CHAR_JOINING.get("T")
else:
c.joining = CHAR_JOINING.get("U")
# Decomposition.
if data[UCD_DECOMPOSITION]:
dec = data[UCD_DECOMPOSITION].split(' ')
# Parse <decompositionType>.
if dec[0].startswith('<'):
c.decompositionType = CHAR_DECOMPOSITION.get(dec[0])
dec = dec[1:]
else:
c.decompositionType = CHAR_DECOMPOSITION.get("<canonical>")
# Decomposition character list.
for d in dec:
c.decompositionData.append(int(d, 16))
# Set has-composition flag to the first canonically decomposed
# character.
if c.decompositionType == CHAR_DECOMPOSITION.get("<canonical>") and len(c.decompositionData) == 2:
CharList[c.decompositionData[0]].hasComposition = 1
f.close()
def ReadXBreakHelper(fileName, propertyName, MAP):
log("-- Read " + fileName)
f = open(UCD_DIRECTORY + fileName, 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
for code in xrange(first, last + 1):
c = CharList[code]
setattr(c, propertyName, MAP.get(data[1]))
f.close()
def ReadLineBreak():
ReadXBreakHelper("ucd/LineBreak.txt", "lineBreak", CHAR_LINE_BREAK)
def ReadGraphemeBreak():
ReadXBreakHelper("ucd/auxiliary/GraphemeBreakProperty.txt", "graphemeBreak", CHAR_GRAPHEME_BREAK)
def ReadSentenceBreak():
ReadXBreakHelper("ucd/auxiliary/SentenceBreakProperty.txt", "sentenceBreak", CHAR_SENTENCE_BREAK)
def ReadWordBreak():
ReadXBreakHelper("ucd/auxiliary/WordBreakProperty.txt", "wordBreak", CHAR_WORD_BREAK)
def ReadArabicShaping():
log("-- Read ucd/ArabicShaping.txt")
f = open(UCD_DIRECTORY + "ucd/ArabicShaping.txt", 'rb')
# Note: Code points that are not explicitly listed in this file are
# either of joining type T or U:
#
# - Those that not explicitly listed that are of General Category Mn, Me, or Cf
# have joining type T.
# - All others not explicitly listed have joining type U.
#
# Note: U is default when CharProperty is created, need to setup the "T" joining
# only.
for code in xrange(NUM_CODE_POINTS):
c = CharList[code]
if c.category == CHAR_CATEGORY.get("Mn") or \
c.category == CHAR_CATEGORY.get("Me") or \
c.category == CHAR_CATEGORY.get("Cf"): c.joining = CHAR_JOINING.get("T")
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
c = CharList[code]
c.joining = CHAR_JOINING.get(data[2])
f.close()
def ReadBidiMirroring():
log("-- Read ucd/BidiMirroring.txt")
f = open(UCD_DIRECTORY + "ucd/BidiMirroring.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
c = CharList[code]
c.mirror = int(data[1], 16)
f.close()
def ReadCaseFolding():
log("-- Read ucd/CaseFolding.txt")
f = open(UCD_DIRECTORY + "ucd/CaseFolding.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
status = data[1]
mapping = data[2].split(' ')
for i in xrange(len(mapping)):
mapping[i] = int(mapping[i].strip(), 16)
c = CharList[code]
# "C" - Common case-folding ("S" and "F" shared).
if status == "C":
assert len(mapping) == 1
c.simpleCaseFolding = mapping[0]
c.fullCaseFolding = mapping
# "F" - Full case-folding.
if status == "F":
c.fullCaseFolding = mapping
# "S" - Simple case-folding.
if status == "S":
c.simpleCaseFolding = mapping[0]
# "T" - Special case-folding.
if status == "T":
c.specialCaseFolding = mapping[0]
f.close()
def ReadSpecialCasing():
log("-- Read ucd/SpecialCasing.txt")
f = open(UCD_DIRECTORY + "ucd/SpecialCasing.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
# TODO
# TODO
# TODO
# TODO
# TODO
# TODO
f.close()
def ReadDerivedAge():
log("-- Read ucd/DerivedAge.txt")
f = open(UCD_DIRECTORY + "ucd/DerivedAge.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
version = CHAR_VERSION.get(data[1])
for code in xrange(first, last + 1):
c = CharList[code]
c.version = version
f.close()
def ReadDerivedNormalizationProps():
log("-- Read ucd/DerivedNormalizationProps.txt")
f = open(UCD_DIRECTORY + "ucd/DerivedNormalizationProps.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
for code in xrange(first, last + 1):
c = CharList[code]
prop = data[1]
# FullCompositionExclusion.
if prop == "Full_Composition_Exclusion":
c.compositionExclusion = True
# Quick-Check.
if prop == "NFD_QC":
c.nfdQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFC_QC":
c.nfcQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFKD_QC":
c.nfkdQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFKC_QC":
c.nfkcQC = CHAR_QUICK_CHECK.get(data[2])
f.close()
def ReadNormalizationCorrections():
log("-- Read ucd/NormalizationCorrections.txt")
f = open(UCD_DIRECTORY + "ucd/NormalizationCorrections.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
orig = int(data[1], 16)
corrected = int(data[2], 16)
version = CHAR_VERSION.get(data[3])
item = NormalizationCorrection(
code=code,
original=orig,
corrected=corrected,
version=version)
NormalizationCorrectionsList.append(item)
f.close()
def ReadEastAsianWidth():
log("-- Read ucd/EastAsianWidth.txt")
f = open(UCD_DIRECTORY + "ucd/EastAsianWidth.txt", 'rb')
# The unassigned code points that default to "W" include ranges in the
# following blocks:
# CJK Unified Ideographs Extension A: U+3400..U+4DBF
# CJK Unified Ideographs: U+4E00..U+9FFF
# CJK Compatibility Ideographs: U+F900..U+FAFF
# CJK Unified Ideographs Extension B: U+20000..U+2A6DF
# CJK Unified Ideographs Extension C: U+2A700..U+2B73F
# CJK Unified Ideographs Extension D: U+2B740..U+2B81F
# CJK Compatibility Ideographs Supplement: U+2F800..U+2FA1F
# and any other reserved code points on
# Planes 2 and 3: U+20000..U+2FFFD
# U+30000..U+3FFFD
W = CHAR_EAW.get("W")
for code in xrange(0x003400, 0x004DBF+1): CharList[code].eaw = W
for code in xrange(0x004E00, 0x009FFF+1): CharList[code].eaw = W
for code in xrange(0x00F900, 0x00FAFF+1): CharList[code].eaw = W
for code in xrange(0x020000, 0x02A6DF+1): CharList[code].eaw = W
for code in xrange(0x02A700, 0x02B73F+1): CharList[code].eaw = W
for code in xrange(0x02B740, 0x02B81F+1): CharList[code].eaw = W
for code in xrange(0x02F800, 0x02FA1F+1): CharList[code].eaw = W
for code in xrange(0x020000, 0x02FFFD+1): CharList[code].eaw = W
for code in xrange(0x030000, 0x03FFFD+1): CharList[code].eaw = W
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
eaw = CHAR_EAW.get(data[1])
for code in xrange(first, last + 1):
c = CharList[code]
c.eaw = eaw
f.close()
def ReadScriptsHelper(fileName):
log("-- Read " + fileName)
f = open(UCD_DIRECTORY + fileName, 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
script = data[1]
for code in xrange(first, last + 1):
c = CharList[code]
c.script = TEXT_SCRIPT.get(script)
# TODO
# TODO
# TODO
# TODO
# TODO
# TODO
f.close()
def ReadScripts():
ReadScriptsHelper("ucd/Scripts.txt")
# ReadScriptsHelper("ucd/ScriptExtensions.txt")
def ReadBlocks():
log("-- Read ucd/Blocks.txt")
f = open(UCD_DIRECTORY + "ucd/Blocks.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
name = data[1]
BlockList.append(BlockProperty(first=first, last=last, name=name))
f.close()
# -----------------------------------------------------------------------------
# [UCD-Check]
# -----------------------------------------------------------------------------
def Check():
log("-- Checking data")
maxCombiningClass = 0
maxDecompositionChar = 0
maxSimpleCaseFolding = 0
maxSpecialCaseFolding = 0
maxFullCaseFolding = 0
maxSpace = 0
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if maxCombiningClass < c.combiningClass:
maxCombiningClass = c.combiningClass
if c.decompositionData:
for d in c.decompositionData:
if maxDecompositionChar < d:
maxDecompositionChar = d
if c.simpleCaseFolding:
if maxSimpleCaseFolding < c.simpleCaseFolding:
maxSimpleCaseFolding = c.simpleCaseFolding
if c.specialCaseFolding:
if maxSpecialCaseFolding < c.specialCaseFolding:
maxSpecialCaseFolding = c.specialCaseFolding
if c.fullCaseFolding:
for d in c.fullCaseFolding:
if maxFullCaseFolding < d:
maxFullCaseFolding = d
if c.isSpace:
if maxSpace < i:
maxSpace = i
# Check whether the uppercase, lowercase, titlecase and mirror mapping
# doesn't exceed our limit (in this case Fog-API must be changed).
if c.uppercase:
if abs(c.uppercase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and uppercase " + ucd(c.uppercase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.uppercase >=0x10000) or \
(c.codePoint >=0x10000 and c.uppercase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and uppercase character " + ucd(c.uppercase) + "are in different plane (BMP/SMP combination)")
if c.lowercase:
if abs(c.lowercase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and lowercase " + ucd(c.lowercase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.lowercase >=0x10000) or \
(c.codePoint >=0x10000 and c.lowercase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and lowercase character " + ucd(c.lowercase) + "are in different plane (BMP/SMP combination)")
if c.titlecase != 0:
if abs(c.titlecase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and titlecase " + ucd(c.titlecase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.titlecase >=0x10000) or \
(c.codePoint >=0x10000 and c.titlecase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and titlecase character " + ucd(c.titlecase) + "are in different plane (BMP/SMP combination)")
if c.mirror != 0:
if abs(c.mirror - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and mirrored " + ucd(c.mirror) + " characters are too far.")
if (c.codePoint < 0x10000 and c.mirror >=0x10000) or \
(c.codePoint >=0x10000 and c.mirror < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and mirror character " + ucd(c.mirror) + "are in different plane (BMP/SMP combination)")
# Check if our assumption that "mirrored/digit character never has lowercase,
# uppercase, or titlecase variant" is valid.
if c.uppercase + c.lowercase + c.titlecase != 0 and (c.mirror != 0 or c.digitValue != -1):
log("** FATAL: " + ucd(c.codePoint) + " - contains both, case and mirror mapping.")
# Check another assumption that there is no character that maps to all
# three categories (uppercase, lowercase, and titlecase). Mapping to itself
# is never used.
if c.uppercase != 0 and c.lowercase != 0 and c.titlecase != 0:
log("** FATAL: " + ucd(c.codePoint) + " - contains upper("+ucd(c.uppercase)+")+lower(" + ucd(c.lowercase) + ")+title(" + ucd(c.titlecase) + ") mapping.")
log(" MAX COMBINING CLASS : " + str(maxCombiningClass))
log(" MAX DECOMPOSED CHAR : " + str(maxDecompositionChar))
log(" MAX SIMPLE-CASE-FOLDING : " + str(maxSimpleCaseFolding))
log(" MAX SPECIAL-CASE-FOLDING: " + str(maxSpecialCaseFolding))
log(" MAX FULL-CASE-FOLDING : " + str(maxFullCaseFolding))
log(" MAX SPACE : " + str(maxSpace))
def PrintTitleCase():
log("-- Printing all titlecases characters")
chars = {}
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if c.category == CHAR_CATEGORY.get("Lt"):
chars[c.codePoint] = True
for c in chars:
c = CharList[c]
log(" TC=" + ucd(c.codePoint) + " LC=" + ucd(c.lowercase) + " UC=" + ucd(c.uppercase))
# -----------------------------------------------------------------------------
# [UCD-Generate]
# -----------------------------------------------------------------------------
class Code(object):
def __init__(self):
# Use python list instead of string concatenation, it's many
# times faster when concatenating a very large string.
self.OffsetDecl = []
self.OffsetRows = []
self.PropertyClass = []
self.PropertyDecl = []
self.PropertyRows = []
self.SpecialClass = []
self.SpecialDecl = []
self.SpecialRows = []
self.InfoClass = []
self.InfoDecl = []
self.InfoRows = []
self.DecompositionDecl = []
self.DecompositionData = []
self.CompositionDecl = []
self.CompositionIndex = []
self.CompositionData = []
self.MethodsInline = []
self.TextScriptEnum = []
self.NormalizationCorrectionsDecl = []
self.NormalizationCorrectionsData = []
self.Iso15924Decl = []
self.Iso15924Data_From = []
self.Iso15924Data_To = []
Code = Code()
# Please update when needed.
SIZE_OF_OFFSET_ROW = 1 # If number of blocks is smaller than 256, otherwise 2
SIZE_OF_PROPERTY_ROW = 8
SIZE_OF_INFO_ROW = 8
SIZE_OF_SPECIAL_ROW = 36
SIZE_OF_NORMALIZATION_CORRECTION_ROW = 16
SIZE_OF_COMPOSITION_ID_TO_INDEX_ROW = 2
SIZE_OF_COMPOSITION_ROW = 8
# Generator configuration (and some constants).
OUTPUT_BLOCK_SIZE = 128
# Whether to only test generator (output to stdout instead of writing to .h/.cpp).
TEST_ONLY = False
# The comment to include in auto-generated code.
AUTOGENERATED_BEGIN = "// --- Auto-generated by generate-unicode.py (Unicode " + UCD_VERSION + ") ---"
AUTOGENERATED_END = "// --- Auto-generated by generate-unicode.py (Unicode " + UCD_VERSION + ") ---"
def GenerateEnums():
log("-- Generating enums")
# Generate TEXT_SCRIPT enum.
Code.TextScriptEnum.append(" " + AUTOGENERATED_BEGIN + "\n")
Code.TextScriptEnum.append("\n" + TEXT_SCRIPT.generateEnum() + "\n")
Code.TextScriptEnum.append(" " + AUTOGENERATED_END + "\n")
def GenerateComposition():
log("-- Generating composition tables")
pairs = []
pairs.append(CompositionPair(0, 0, 0))
maxChar = 0
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
# Generate composition pair.
if c.compositionExclusion == False and \
c.decompositionType == CHAR_DECOMPOSITION.get("<canonical>") and \
len(c.decompositionData) == 2:
pair = CompositionPair(c.decompositionData[0], c.decompositionData[1], i)
if pair.a > maxChar: maxChar = pair.a
if pair.b > maxChar: maxChar = pair.b
if pair.ab > maxChar: maxChar = pair.ab
pairs.append(pair)
pairs.sort(key=lambda x: (long(x.b) << 32) + long(x.a))
pairs.append(CompositionPair(0, 0, 0))
count = len(pairs)
idToIndex = []
uniqueBDict = {}
for i in xrange(count):
pair = pairs[i]
c = CharList[pair.b]
if c.codePoint == 0:
continue
if not pair.b in uniqueBDict:
uniqueBDict[pair.b] = len(idToIndex)
idToIndex.append(i)
c.compositionId = uniqueBDict[pair.b]
# Terminate the idToIndex array so it's possible to use idToIndex[i+1] to
# get the length of A+B list where B is constant.
idToIndex.append(count)
uniqueBKeys = len(uniqueBDict)
log(" Unique Combiners: " + str(uniqueBKeys))
Code.CompositionDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.CompositionDecl.append(" //! @brief Composition id to composition data index mapping.\n")
Code.CompositionDecl.append(" uint16_t compositionIdToIndex[" + str(Align(uniqueBKeys, 4)) + "];\n")
Code.CompositionDecl.append("\n")
Code.CompositionDecl.append(" //! @brief Composition data.\n")
Code.CompositionDecl.append(" CharComposition compositionData[" + str(count) + "];\n")
Code.CompositionDecl.append("\n")
Code.CompositionDecl.append(" " + AUTOGENERATED_END + "\n")
Code.CompositionIndex.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(uniqueBKeys):
Code.CompositionIndex.append(" " + str(idToIndex[i]))
if i != uniqueBKeys - 1:
Code.CompositionIndex.append(",\n")
else:
Code.CompositionIndex.append("\n")
Code.CompositionIndex.append("\n")
Code.CompositionIndex.append(" " + AUTOGENERATED_END + "\n")
Code.CompositionData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(count):
pair = pairs[i]
Code.CompositionData.append(" { " + uch(pair.a) + ", " + uch(pair.b) + ", " + uch(pair.ab) + " }")
if i != count - 1:
Code.CompositionData.append(",\n")
else:
Code.CompositionData.append("\n")
Code.CompositionData.append("\n")
Code.CompositionData.append(" " + AUTOGENERATED_END + "\n")
log(" COMPOSITION ID: " + str(uniqueBKeys) + \
" (" + str(uniqueBKeys * SIZE_OF_COMPOSITION_ID_TO_INDEX_ROW) + " bytes)")
log(" COMPOSITION : " + str(count) + \
" (" + str(count * SIZE_OF_COMPOSITION_ROW) + " bytes)")
def GenerateSpecial():
log("-- Generating special characters info (ligatures, case-folding, ...)")
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if c.titlecase == 0 and ((c.lowercase == 0 and c.mirror == 0) or \
(c.uppercase == 0 and c.mirror == 0) or \
(c.lowercase == 0 and c.uppercase == 0)):
# Mark character as not special. This means that CHAR_MAPPING must contain one
# of NONE, LOWERCASE, UPPERCASE or MIRROR.
if c.uppercase != 0:
c.mapping = CHAR_MAPPING.get("Uppercase")
elif c.lowercase != 0:
c.mapping = CHAR_MAPPING.get("Lowercase")
elif c.mirror != 0:
c.mapping = CHAR_MAPPING.get("Mirror")
elif c.digitValue != -1:
c.mapping = CHAR_MAPPING.get("Digit")
else:
# Special (complex) character mapping.
c.mapping = CHAR_MAPPING.get("Special")
def GenerateClasses():
pass
def GenerateNormalizationCorrections():
log("-- Generating normalization corrections")
count = len(NormalizationCorrectionsList)
Code.NormalizationCorrectionsDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.NormalizationCorrectionsDecl.append(" //! @brief Unicode normalization corrections.\n")
Code.NormalizationCorrectionsDecl.append(" CharNormalizationCorrection normalizationCorrections[" + str(count) + "];\n")
Code.NormalizationCorrectionsDecl.append("\n")
Code.NormalizationCorrectionsDecl.append(" " + AUTOGENERATED_END + "\n")
Code.NormalizationCorrectionsData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(count):
nc = NormalizationCorrectionsList[i]
Code.NormalizationCorrectionsData.append(" { " + \
uch(nc.code) + ", " + uch(nc.original) + ", " + uch(nc.corrected) + ", " + "CHAR_UNICODE_" + CHAR_VERSION.fog(nc.version) + " }")
if i != count - 1:
Code.NormalizationCorrectionsData.append(",\n")
else:
Code.NormalizationCorrectionsData.append("\n")
Code.NormalizationCorrectionsData.append("\n")
Code.NormalizationCorrectionsData.append(" " + AUTOGENERATED_END + "\n")
log(" NORM_CORR ROWS: " + str(count) + \
" (" + str(count * SIZE_OF_NORMALIZATION_CORRECTION_ROW) + " bytes)")
def GenerateIso15924Names():
# Generate ISO15924 names.
textScriptCount = TEXT_SCRIPT.count()
iso15924Keys = TEXT_SCRIPT_ISO15924_FROM.keys()
iso15924Keys.sort()
iso15924Count = len(iso15924Keys)
Code.Iso15924Decl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.Iso15924Decl.append(" //! @brief ISO-15924 From TEXT_SCRIPT.\n")
Code.Iso15924Decl.append(" uint32_t iso15924FromTextScript[" + str(textScriptCount) + "];\n")
Code.Iso15924Decl.append("\n")
Code.Iso15924Decl.append(" //! @brief TEXT_SCRIPT from ISO-15924.\n")
Code.Iso15924Decl.append(" CharISO15924Data textScriptFromIso15924[" + str(iso15924Count) + "];\n")
Code.Iso15924Decl.append("\n")
Code.Iso15924Decl.append(" " + AUTOGENERATED_END + "\n")
Code.Iso15924Data_From.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(textScriptCount):
iso15924Name = TEXT_SCRIPT_ISO15924_TO[str(i)]
assert(len(iso15924Name) == 4)
# Replace Zzzz with NULL.
if iso15924Name == "Zzzz":
Code.Iso15924Data_From.append(" 0")
else:
Code.Iso15924Data_From.append(" FOG_ISO15924_NAME(" + \
Literal(iso15924Name[0]) + ", " + \
Literal(iso15924Name[1]) + ", " + \
Literal(iso15924Name[2]) + ", " + \
Literal(iso15924Name[3]) + ")")
if i != textScriptCount - 1:
Code.Iso15924Data_From.append(",\n")
else:
Code.Iso15924Data_From.append("\n")
Code.Iso15924Data_From.append("\n")
Code.Iso15924Data_From.append(" " + AUTOGENERATED_END + "\n")
Code.Iso15924Data_To.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(iso15924Count):
iso15924Name = iso15924Keys[i]
assert(len(iso15924Name) == 4)
Code.Iso15924Data_To.append(" { ")
Code.Iso15924Data_To.append("FOG_ISO15924_NAME(" + \
Literal(iso15924Name[0]) + ", " + \
Literal(iso15924Name[1]) + ", " + \
Literal(iso15924Name[2]) + ", " + \
Literal(iso15924Name[3]) + ")")
Code.Iso15924Data_To.append(", ")
Code.Iso15924Data_To.append("TEXT_SCRIPT_" + TEXT_SCRIPT.fog(TEXT_SCRIPT.get(iso15924Name)))
Code.Iso15924Data_To.append(" }")
if i != iso15924Count - 1:
Code.Iso15924Data_To.append(",\n")
else:
Code.Iso15924Data_To.append("\n")
Code.Iso15924Data_To.append("\n")
Code.Iso15924Data_To.append(" " + AUTOGENERATED_END + "\n")
def GenerateTable():
global SIZE_OF_OFFSET_ROW
log("-- Generating tables")
rowBlockHash = {}
rowBlockList = []
rowBlockData = ""
rowBlockFirst = -1
specialHash = {}
specialList = []
offsetList = []
decompositionHash = {}
decompositionList = []
decompositionList.append(0)
maxDecompositionLength = 0
infoHash = {}
infoList = []
def GetOffsetShift(val):
result = -1
while val:
result += 1
val = val >> 1
return result
def GetOffsetMask(val):
return val - 1
# ---------------------------------------------------------------------------
# Headers.
# ---------------------------------------------------------------------------
Code.PropertyClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" // First 32-bit packed int.\n" + \
" // - uint32_t _infoIndex : 12;\n" + \
" // - uint32_t _mappingType : 3;\n" + \
" // - int32_t _mappingData : 17;\n" + \
" // Needed to pack to a signle integer, because of different types used.\n" + \
" int32_t _infoAndMapping;\n" + \
"\n" + \
" // Second 32-bit packed int.\n" + \
" uint32_t _category : 5;\n" + \
" uint32_t _space : 1;\n" + \
" uint32_t _hasComposition : 1;\n" + \
" uint32_t _decompositionType : 5;\n" + \
" uint32_t _decompositionIndex : 15;\n" + \
" uint32_t _unused : 5;\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
Code.InfoClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" // First 32-bit packed int.\n" + \
" uint32_t _combiningClass : 8;\n" + \
" uint32_t _script : 8;\n" + \
" uint32_t _unicodeVersion : 4;\n" + \
" uint32_t _graphemeBreak : 4;\n" + \
" uint32_t _wordBreak : 4;\n" + \
" uint32_t _sentenceBreak : 4;\n" + \
"\n" + \
" // Second 32-bit packed int.\n" + \
" uint32_t _lineBreak : 6;\n" + \
" uint32_t _bidi : 5;\n" + \
" uint32_t _joining : 3;\n" + \
" uint32_t _eaw : 3;\n" + \
" uint32_t _compositionExclusion : 1;\n"+ \
" uint32_t _nfdQC : 1;\n" + \
" uint32_t _nfcQC : 2;\n" + \
" uint32_t _nfkdQC : 1;\n" + \
" uint32_t _nfkcQC : 2;\n" + \
" uint32_t _compositionId : 8;\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
Code.SpecialClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" int32_t _upperCaseDiff : 22;\n" + \
" int32_t _unused0 : 10;\n" + \
"\n" + \
" int32_t _lowerCaseDiff : 22;\n" + \
" int32_t _unused1 : 10;\n" + \
"\n" + \
" int32_t _titleCaseDiff : 22;\n" + \
" int32_t _unused2 : 10;\n" + \
"\n" + \
" int32_t _mirrorDiff : 22;\n" + \
" int32_t _digitValue : 10;\n" + \
"\n" + \
" uint32_t _simpleCaseFolding;\n" + \
" uint32_t _specialCaseFolding;\n" + \
" uint32_t _fullCaseFolding[3];\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
# ---------------------------------------------------------------------------
# Collect info and generate data which will be used to generate tables.
# ---------------------------------------------------------------------------
class RowBlock(object):
def __init__(self, offset):
self.offset = offset
self.count = 1
self.chars = []
for i in xrange(NUM_CODE_POINTS):
if rowBlockFirst == -1:
rowBlockFirst = i
rowBlockData = ""
c = CharList[i]
# Info.
s = " _CHAR_INFO("
s += str(c.combiningClass) + ", " # CombiningClass
s += TEXT_SCRIPT.fog(c.script) + ", " # Script
s += CHAR_VERSION.fog(c.version) + ", " # UnicodeVersion
s += CHAR_GRAPHEME_BREAK.fog(c.graphemeBreak) + ", " # GraphemeBreak
s += CHAR_WORD_BREAK.fog(c.wordBreak) + ", " # WordBreak
s += CHAR_SENTENCE_BREAK.fog(c.sentenceBreak) + ", " # SentenceBreak
s += CHAR_LINE_BREAK.fog(c.lineBreak) + ", " # LineBreak
s += CHAR_BIDI.fog(c.bidi) + ", " # Bidi
s += CHAR_JOINING.fog(c.joining) + ", " # Joining
s += CHAR_EAW.fog(c.eaw) + ", " # East-Asian Width.
s += str(int(c.compositionExclusion)) + ", " # CompositionExclusion.
s += CHAR_QUICK_CHECK.fog(c.nfdQC) + ", " # NFD_QC.
s += CHAR_QUICK_CHECK.fog(c.nfcQC) + ", " # NFC_QC.
s += CHAR_QUICK_CHECK.fog(c.nfkdQC) + ", " # NFKD_QC.
s += CHAR_QUICK_CHECK.fog(c.nfkcQC) + ", " # NFKC_QC.
s += str(c.compositionId) # CompositionId
s += ")"
if not s in infoHash:
infoHash[s] = len(infoList)
infoList.append(s)
infoIndex = infoHash[s]
# Decomposition data.
decompositionDataIndex = 0
decompositionDataLength = 0
s = ""
if len(c.decompositionData) > 0:
dt = [0]
for cp in c.decompositionData:
if cp > 0x10000:
dt.extend(SurrogatePairOf(cp))
else:
dt.append(cp)
dt[0] = len(dt) - 1
if len(dt) > maxDecompositionLength:
maxDecompositionLength = len(dt)
s += ", ".join([str(item) for item in dt])
if not s in decompositionHash:
decompositionHash[s] = len(decompositionList)
decompositionList.extend(dt)
decompositionDataIndex = decompositionHash[s]
decompositionDataLength = len(dt)
# Mapping.
mappingConstant = 0
if c.mapping == CHAR_MAPPING.get("Uppercase"):
mappingConstant = c.upperdiff
if c.mapping == CHAR_MAPPING.get("Lowercase"):
mappingConstant = c.lowerdiff
if c.mapping == CHAR_MAPPING.get("Mirror"):
mappingConstant = c.mirrordiff
if c.mapping == CHAR_MAPPING.get("Digit"):
mappingConstant = c.digitValue
if c.mapping == CHAR_MAPPING.get("Special"):
s = " " + "{ "
# UpperCaseDiff/Unused0.
s += str(c.upperdiff) + ", "
s += "0, "
# LowerCaseDiff/Unused1.
s += str(c.lowerdiff) + ", "
s += "0, "
# TitleCaseDiff/Unused2.
s += str(c.titlediff) + ", "
s += "0, "
# MirrorDiff/DigitValue.
s += str(c.mirrordiff) + ", "
s += str(c.digitValue) + ", "
# SimpleCaseFolding+FullCaseFolding.
s += uch(c.simpleCaseFolding) + ", "
s += uch(c.specialCaseFolding) + ", "
s += "{ "
if c.fullCaseFolding:
s += ", ".join([uch(t) for t in c.fullCaseFolding])
else:
s += "0x0000"
s += " } "
s += "}"
if s in specialHash:
mappingConstant = specialHash[s]
else:
mappingConstant = len(specialList)
specialHash[s] = mappingConstant
specialList.append(s)
s = " _CHAR_PROPERTY("
s += str(infoIndex) + ", " # Info Index.
s += CHAR_MAPPING.fog(c.mapping) + ", " # MappingType.
s += str(mappingConstant) + ", " # MappingData.
s += CHAR_CATEGORY.fog(c.category) + ", " # Category.
s += str(int(c.isSpace)) + ", " # Space.
s += str(c.hasComposition) + ", " # HasComposition.
s += CHAR_DECOMPOSITION.fog(c.decompositionType) + ", " # DecompositionType.
s += str(decompositionDataIndex) # DecompositionIndex.
s += ")"
rowBlockData += s
if i == rowBlockFirst + OUTPUT_BLOCK_SIZE - 1:
if not rowBlockData in rowBlockHash:
rowBlockHash[rowBlockData] = RowBlock(len(rowBlockList))
rowBlockList.append(rowBlockData)
else:
rowBlockHash[rowBlockData].count += 1
rowBlockHash[rowBlockData].chars.append(rowBlockFirst)
rowBlockFirst = -1
offsetList.append(rowBlockHash[rowBlockData].offset)
else:
rowBlockData += ",\n"
# If number of row-blocks exceeded 255 then uint16_t must be
# used as an insex. It's larger, this is reason why the code
# is tuned to output data in uint8_t.
if len(rowBlockList) > 255:
SIZE_OF_OFFSET_ROW = 2
# ---------------------------------------------------------------------------
# Generate info table.
# ---------------------------------------------------------------------------
numInfoRows = len(infoList)
Code.InfoDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.InfoDecl.append(" //! @brief Character info data (see @ref CharProperty::infoIndex).\n")
Code.InfoDecl.append(" CharInfo info[" + str(numInfoRows) + "];\n\n")
Code.InfoDecl.append(" " + AUTOGENERATED_END + "\n")
Code.InfoRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.InfoRows.append("" + \
"# define _CHAR_INFO(_CombiningClass_, _Script_, _Version_, _GB_, _WB_, _SB_, _LB_, _Bidi_, _Joining_, _EAW_, _CompositionExclusion_, _NFDQC_, _NFCQC_, _NFKDQC_, _NFKCQC_, _CompositionId_) \\\n" + \
" { \\\n" + \
" _CombiningClass_, \\\n" + \
" TEXT_SCRIPT_##_Script_, \\\n" + \
" CHAR_UNICODE_##_Version_, \\\n" + \
" CHAR_GRAPHEME_BREAK_##_GB_, \\\n" + \
" CHAR_WORD_BREAK_##_WB_, \\\n" + \
" CHAR_SENTENCE_BREAK_##_SB_, \\\n" + \
" CHAR_LINE_BREAK_##_LB_, \\\n" + \
" CHAR_BIDI_##_Bidi_, \\\n" + \
" CHAR_JOINING_##_Joining_, \\\n" + \
" CHAR_EAW_##_EAW_, \\\n" + \
" _CompositionExclusion_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFDQC_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFCQC_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFKDQC_,\\\n" + \
" CHAR_QUICK_CHECK_##_NFKCQC_,\\\n" + \
" _CompositionId_ \\\n" + \
" }\n"
)
for i in xrange(numInfoRows):
Code.InfoRows.append(infoList[i])
if i != numInfoRows-1:
Code.InfoRows.append(",\n")
else:
Code.InfoRows.append("\n")
Code.InfoRows.append("# undef _CHAR_INFO\n")
Code.InfoRows.append("\n")
Code.InfoRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate offset table.
# ---------------------------------------------------------------------------
numOffsetRows = NUM_CODE_POINTS / OUTPUT_BLOCK_SIZE
if SIZE_OF_OFFSET_ROW == 1:
dataType = "uint8_t"
else:
dataType = "uint16_t"
Code.OffsetDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.OffsetDecl.append(" //! @brief Offset to the property block, see @c getCharProperty().\n")
Code.OffsetDecl.append(" " + dataType + " offset[" + str(numOffsetRows) + "];\n\n")
Code.OffsetDecl.append(" " + AUTOGENERATED_END + "\n")
Code.OffsetRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(len(offsetList)):
Code.OffsetRows.append(" " + str(offsetList[i]))
if i != len(offsetList) - 1:
Code.OffsetRows.append(",")
else:
Code.OffsetRows.append(" ")
Code.OffsetRows.append(" // " + ucd(i * OUTPUT_BLOCK_SIZE) + ".." + ucd((i + 1) * OUTPUT_BLOCK_SIZE - 1))
Code.OffsetRows.append("\n")
Code.OffsetRows.append("\n")
Code.OffsetRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate property table.
# ---------------------------------------------------------------------------
numPropertyRows = len(rowBlockList) * OUTPUT_BLOCK_SIZE
Code.PropertyDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.PropertyDecl.append(" //! @brief Unicode character properties, see @c getCharProperty().\n")
Code.PropertyDecl.append(" CharProperty property[" + str(numPropertyRows) + "];\n\n")
Code.PropertyDecl.append(" " + AUTOGENERATED_END + "\n")
Code.PropertyRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.PropertyRows.append("" + \
"# define _CHAR_PROPERTY(_InfoIndex_, _MappingType_, _MappingData_, _Category_, _Space_, _HasComposition_, _DecompositionType_, _DecompositionIndex_) \\\n" + \
" { \\\n" + \
" ((int32_t)(_InfoIndex_)) | \\\n" + \
" ((int32_t)(CHAR_MAPPING_##_MappingType_) << 12) | \\\n" + \
" ((int32_t)(_MappingData_) << 15), \\\n" + \
" \\\n" + \
" CHAR_CATEGORY_##_Category_, \\\n" + \
" _Space_, \\\n" + \
" _HasComposition_, \\\n" + \
" CHAR_DECOMPOSITION_##_DecompositionType_, \\\n" + \
" _DecompositionIndex_ \\\n" + \
" }\n"
)
Code.PropertyRows.append("\n")
for i in xrange(len(rowBlockList)):
rowBlockData = rowBlockList[i]
# Print Range/Blocks comment (informative)
chars = rowBlockHash[rowBlockData].chars
first = -1
for j in xrange(len(chars)):
code = chars[j]
if first == -1:
first = code
end = code + OUTPUT_BLOCK_SIZE
if j != len(chars) - 1 and chars[j+1] == end:
continue
Code.PropertyRows.append(" // Range : " + ucd(first) + ".." + ucd(end - 1) + "\n")
first = -1
if rowBlockHash[rowBlockData].count > 1:
Code.PropertyRows.append(" // Blocks: " + str(rowBlockHash[rowBlockData].count) + "\n")
Code.PropertyRows.append(rowBlockData)
if i < len(rowBlockList) - 1:
Code.PropertyRows.append(",\n")
else:
Code.PropertyRows.append("\n")
Code.PropertyRows.append("# undef _CHAR_PROPERTY\n")
Code.PropertyRows.append("\n")
Code.PropertyRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate special table.
# ---------------------------------------------------------------------------
numSpecialRows = len(specialList)
Code.SpecialDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.SpecialDecl.append(" //! @brief Unicode special properties.\n")
Code.SpecialDecl.append(" CharSpecial special[" + str(numSpecialRows) + "];\n\n")
Code.SpecialDecl.append(" " + AUTOGENERATED_END + "\n")
Code.SpecialRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(len(specialList)):
Code.SpecialRows.append(specialList[i])
if i != len(specialList) - 1:
Code.SpecialRows.append(",")
Code.SpecialRows.append("\n")
Code.SpecialRows.append("\n")
Code.SpecialRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate decomposition table.
# ---------------------------------------------------------------------------
Code.DecompositionDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.DecompositionDecl.append(" //! @brief Decomposition data.\n")
Code.DecompositionDecl.append(" uint16_t decomposition[" + str(len(decompositionList)) + "];\n\n")
Code.DecompositionDecl.append(" " + AUTOGENERATED_END + "\n")
Code.DecompositionData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.DecompositionData.append(" ")
for i in xrange(len(decompositionList)):
Code.DecompositionData.append(uch(decompositionList[i]))
if i != len(decompositionList) - 1:
Code.DecompositionData.append(",")
if (i > 1) and (i % 8 == 7):
Code.DecompositionData.append("\n ")
else:
Code.DecompositionData.append(" ")
Code.DecompositionData.append("\n")
Code.DecompositionData.append("\n")
Code.DecompositionData.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate methods
# ---------------------------------------------------------------------------
Code.MethodsInline.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.MethodsInline.append(" enum\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" PO_BLOCK_SIZE = " + str(OUTPUT_BLOCK_SIZE) + ",\n")
Code.MethodsInline.append(" PO_OFFSET_SHIFT = " + str(GetOffsetShift(OUTPUT_BLOCK_SIZE)) + ",\n")
Code.MethodsInline.append(" PO_OFFSET_MASK = " + str(GetOffsetMask(OUTPUT_BLOCK_SIZE)) + "\n")
Code.MethodsInline.append(" };\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS2(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return offset[ucs2 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs2 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS2Unsafe(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return offset[ucs2 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs2 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS4(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" // We assign invalid characters to NULL.\n")
Code.MethodsInline.append(" if (ucs4 > UNICODE_MAX)\n")
Code.MethodsInline.append(" ucs4 = 0; \n")
Code.MethodsInline.append("\n")
Code.MethodsInline.append(" return offset[ucs4 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs4 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS4Unsafe(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" // Caller must ensure that ucs4 is in valid range.\n")
Code.MethodsInline.append(" FOG_ASSERT(ucs4 <= UNICODE_MAX);\n")
Code.MethodsInline.append("\n")
Code.MethodsInline.append(" return offset[ucs4 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs4 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS2(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS2(ucs2)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS2Unsafe(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS2Unsafe(ucs2)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS4(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS4(ucs4)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS4Unsafe(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS4Unsafe(ucs4)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Log
# ---------------------------------------------------------------------------
#log("".join(Code.OffsetRows))
#log("".join(Code.PropertyRows))
#log("".join(Code.SpecialRows))
log(" OFFSET-ROWS : " + str(numOffsetRows) + \
" (" + str(numOffsetRows * SIZE_OF_OFFSET_ROW) + " bytes)")
log(" CHAR-ROWS : " + str(numPropertyRows) + \
" (" + str(len(rowBlockList)) + " blocks, " + str(numPropertyRows * SIZE_OF_PROPERTY_ROW) + " bytes)")
log(" INFO-ROWS : " + str(numInfoRows) + \
" (" + str(numInfoRows * SIZE_OF_INFO_ROW) + " bytes)")
log(" SPECIAL-ROWS : " + str(numSpecialRows) + \
" (" + str(numSpecialRows * SIZE_OF_SPECIAL_ROW) + " bytes)")
log(" DECOMPOSITION : " + str(len(decompositionList)) + \
" (" + str(2 * len(decompositionList)) + " bytes, max length=" + str(maxDecompositionLength - 1) + ")")
log("")
s = " BLOCK LIST : "
for row in rowBlockList:
s += str(rowBlockHash[row].count) + " "
log(s)
def WriteDataToFile(name, m):
log("-- Processing file " + name)
name = "../" + name
file = open(name, 'rb')
data = file.read()
file.close()
for key in m:
log(" - Replacing " + key)
beginMark = "${" + key + ":BEGIN}"
endMark = "${" + key + ":END}"
beginMarkIndex = data.find(beginMark)
endMarkIndex = data.find(endMark)
beginMarkIndex = data.find('\n', beginMarkIndex) + 1
endMarkIndex = data.rfind('\n', 0, endMarkIndex) + 1
assert beginMarkIndex != -1
assert endMarkIndex != -1
assert beginMarkIndex <= endMarkIndex
data = data[:beginMarkIndex] + m[key] + data[endMarkIndex:]
if TEST_ONLY:
log("-- Output file " + name)
log(data)
else:
log("-- Writing file " + name)
file = open(name, 'wb')
file.truncate()
file.write(data)
file.close()
def Write():
WriteDataToFile("Src/Fog/Core/Tools/CharData.h", {
"CHAR_OFFSET_DECL" : "".join(Code.OffsetDecl),
"CHAR_PROPERTY_CLASS" : "".join(Code.PropertyClass),
"CHAR_PROPERTY_DECL" : "".join(Code.PropertyDecl),
"CHAR_INFO_CLASS" : "".join(Code.InfoClass),
"CHAR_INFO_DECL" : "".join(Code.InfoDecl),
"CHAR_SPECIAL_CLASS" : "".join(Code.SpecialClass),
"CHAR_SPECIAL_DECL" : "".join(Code.SpecialDecl),
"CHAR_DECOMPOSITION_DECL" : "".join(Code.DecompositionDecl),
"CHAR_COMPOSITION_DECL" : "".join(Code.CompositionDecl),
"CHAR_METHODS_INLINE" : "".join(Code.MethodsInline),
"CHAR_NORMALIZATION_CORRECTIONS_DECL": "".join(Code.NormalizationCorrectionsDecl),
"CHAR_ISO15924_DECL" : "".join(Code.Iso15924Decl)
})
WriteDataToFile("Src/Fog/Core/Tools/CharData.cpp", {
"CHAR_OFFSET_DATA" : "".join(Code.OffsetRows),
"CHAR_PROPERTY_DATA" : "".join(Code.PropertyRows),
"CHAR_INFO_DATA" : "".join(Code.InfoRows),
"CHAR_SPECIAL_DATA" : "".join(Code.SpecialRows),
"CHAR_DECOMPOSITION_DATA" : "".join(Code.DecompositionData),
"CHAR_COMPOSITION_INDEX" : "".join(Code.CompositionIndex),
"CHAR_COMPOSITION_DATA" : "".join(Code.CompositionData),
"CHAR_NORMALIZATION_CORRECTIONS_DATA": "".join(Code.NormalizationCorrectionsData),
"CHAR_ISO15924_DATA_FROM" : "".join(Code.Iso15924Data_From),
"CHAR_ISO15924_DATA_TO" : "".join(Code.Iso15924Data_To)
})
WriteDataToFile("Src/Fog/Core/Global/EnumCore.h", {
"TEXT_SCRIPT_ENUM" : "".join(Code.TextScriptEnum)
})
# -----------------------------------------------------------------------------
# [UCD-Main]
# -----------------------------------------------------------------------------
def main():
PrepareFiles()
PrepareTables()
ReadPropertyValueAliases()
ReadUnicodeData()
ReadLineBreak()
ReadGraphemeBreak()
ReadSentenceBreak()
ReadWordBreak()
ReadArabicShaping()
ReadBidiMirroring()
ReadCaseFolding()
ReadSpecialCasing()
ReadDerivedAge()
ReadDerivedNormalizationProps()
ReadNormalizationCorrections()
ReadEastAsianWidth()
ReadScripts()
ReadBlocks()
Check()
PrintTitleCase()
GenerateEnums()
GenerateComposition()
GenerateSpecial()
GenerateClasses()
GenerateNormalizationCorrections()
GenerateIso15924Names()
GenerateTable()
Write()
log("-- All done, quitting...")
main()
| Python |
#!/usr/bin/env python
# Unicode Reports:
#
# http://www.unicode.org/reports/tr44/
# (Unicode Character Database)
# =============================================================================
# generate-unicode.py - Generate unicode tables, based on Unicode 6.0.
#
# This script must be modified when new unicode standard is released. Currently
# it's tuned for Unicode 6.0, and it is possible to regenerate tables when only
# small additions are done to the UCD, but when enums are added, or some rules
# changed, it's needed to review the unicode reports and to modify the code. If
# there is something not expected in the unicode database then fatal error
# exception should be raised.
# =============================================================================
import os
# -----------------------------------------------------------------------------
# [UCD-Helpers]
# -----------------------------------------------------------------------------
def log(str):
print(str)
# Convert integer to string representing unicode code-point "U+cp".
def ucd(cp):
if cp <= 0xFFFF:
return "U+%04X" % cp
else:
return "U+%06X" % cp
def uch(cp):
if cp <= 0xFFFF:
return "0x%04X" % cp
else:
return "0x%06X" % cp
def Literal(ch):
if ch == 0:
return "\\'"
else:
return "'" + ch + "'"
# Convert cp to UTF-16 surrogate pair.
def SurrogatePairOf(cp):
assert cp >= 0x10000
return (55232 + (cp >> 10), 56320 + (cp & 0x03FF))
# Align a to n.
def Align(a, n):
while (a % n) != 0:
a += 1
return a
# Split data using ';' as a separator and strip all leading/trailing whitespaces.
def SplitData(line):
data = line.split(';')
for i in xrange(len(data)):
data[i] = data[i].strip()
return data
def GetCharRange(item):
if ".." in item:
items = item.split("..")
first = int(items[0], 16)
last = int(items[1], 16)
return (first, last)
else:
code = int(item, 16)
return (code, code)
# Line iterator, all comments and empty lines are removed.
def LineIterator(file):
while True:
line = file.readline()
if len(line) == 0:
break
pos = line.find("#")
if pos != -1:
line = line[0:pos]
line = line.strip(" \t\r\n")
if len(line) != 0:
yield line
def DownloadFile(url, targetName):
import urllib
dirName = os.path.dirname(targetName)
if not os.path.isdir(dirName):
os.makedirs(dirName)
urllib.urlretrieve(url, targetName)
# -----------------------------------------------------------------------------
# [UCD-Files]
# -----------------------------------------------------------------------------
# The UCD files needed to run this script, downloaded on-demand.
UCD_FILES = [
"ucd/auxiliary/GraphemeBreakProperty.txt",
"ucd/auxiliary/SentenceBreakProperty.txt",
"ucd/auxiliary/WordBreakProperty.txt",
"ucd/ArabicShaping.txt",
"ucd/BidiMirroring.txt",
"ucd/Blocks.txt",
"ucd/CaseFolding.txt",
"ucd/CompositionExclusions.txt",
"ucd/DerivedAge.txt",
"ucd/DerivedNormalizationProps.txt",
"ucd/EastAsianWidth.txt",
"ucd/LineBreak.txt",
"ucd/NormalizationCorrections.txt",
"ucd/PropertyValueAliases.txt",
"ucd/Scripts.txt",
"ucd/ScriptExtensions.txt",
"ucd/SpecialCasing.txt",
"ucd/UnicodeData.txt"
]
# Unicode version.
UCD_VERSION="6.1.0"
# Local directory to store the files.
UCD_DIRECTORY = "tmp/"
# URL where to download if the files are missing (when check-outed).
UCD_PUBLIC_URL = "http://www.unicode.org/Public/" + UCD_VERSION
def PrepareFiles():
log("-- Checking for unicode files")
for name in UCD_FILES:
targetName = UCD_DIRECTORY + name
try:
f = open(targetName, 'rb')
f.close()
except:
log(" " + name + ": Not found, starting download...")
DownloadFile(UCD_PUBLIC_URL + "/" + name, targetName)
log(" " + name + ": Downloaded.")
# -----------------------------------------------------------------------------
# [UCD-Constants]
# -----------------------------------------------------------------------------
MAX_CODE_POINT = 0x10FFFF
NUM_CODE_POINTS = MAX_CODE_POINT + 1
# 17 bits, see Fog::CharProperty.
MAX_PAIRED_DIFF = 2**16 - 1
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# The data index in UnicodeData.txt file, entries separated by ;
UCD_VALUE = 0
UCD_NAME = 1
UCD_CATEGORY = 2
UCD_COMBINING_CLASS = 3
UCD_BIDI = 4
UCD_DECOMPOSITION = 5
UCD_DECIMAL_DIGIT_VALUE = 6
UCD_DIGIT_VALUE = 7
UCD_NUMERIC_VALUE = 8
UCD_MIRRORED = 9
UCD_OLD_NAME = 10
UCD_COMMENT = 11
UCD_UPPERCASE = 12
UCD_LOWERCASE = 13
UCD_TITLECASE = 14
# Enumeration, mapping between the Unicode string name, internal ID value,
# and Fog constant name (without the "CHAR_XXX_" prefix).
class Enum(object):
def __init__(self, name, default, data, alt={}):
self._name = name
self._map = {}
self._arr = []
self._default = default
for i in xrange(len(data)):
item = data[i]
self._map[item[0]] = i
self._arr.append(item[1])
# Alternative map.
for key in alt:
self.addAlias(key, self._map[alt[key]])
# Get id value from a given key.
def get(self, key):
if isinstance(key, int):
return self._arr[key]
if not key:
return self._default
if key in self._map:
return self._map[key]
raise KeyError(self._name + " - There is no key " + key)
# Translate the id value to a Fog-Enum value.
def fog(self, id):
return self._arr[id]
def count(self):
return len(self._arr)
def addAlias(self, key, value):
self._map[key] = value
def generateEnum(self):
s = ""
for i in xrange(len(self._arr)):
s += " " + self._name + "_" + self._arr[i] + " = " + str(i)
s += ",\n"
s += "\n"
s += " " + self._name + "_COUNT" + " = " + str(len(self._arr)) + "\n"
return s
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# Bidi.
CHAR_BIDI = Enum(name="BIDI", default=0,
data=[
["EN" , "EN" ],
["ES" , "ES" ],
["ET" , "ET" ],
["AN" , "AN" ],
["AL" , "AL" ],
["WS" , "WS" ],
["CS" , "CS" ],
["B" , "B" ],
["S" , "S" ],
["L" , "L" ],
["LRE" , "LRE" ],
["LRO" , "LRO" ],
["R" , "R" ],
["RLE" , "RLE" ],
["RLO" , "RLO" ],
["PDF" , "PDF" ],
["NSM" , "NSM" ],
["BN" , "BN" ],
["ON" , "ON" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt
#
# Unicode character categories.
CHAR_CATEGORY = Enum(name="CATEGORY", default=0,
data=[
["" , "NONE" ],
["Lu" , "LU" ],
["Ll" , "LL" ],
["Lt" , "LT" ],
["Lm" , "LM" ],
["Lo" , "LO" ],
["Nd" , "ND" ],
["Nl" , "NL" ],
["No" , "NO" ],
["Mc" , "MC" ],
["Me" , "ME" ],
["Mn" , "MN" ],
["Zs" , "ZS" ],
["Zl" , "ZL" ],
["Zp" , "ZP" ],
["Cc" , "CC" ],
["Cf" , "CF" ],
["Cs" , "CS" ],
["Co" , "CO" ],
["Cn" , "CN" ],
["Pc" , "PC" ],
["Pd" , "PD" ],
["Ps" , "PS" ],
["Pe" , "PE" ],
["Pi" , "PI" ],
["Pf" , "PF" ],
["Po" , "PO" ],
["Sm" , "SM" ],
["Sc" , "SC" ],
["Sk" , "SK" ],
["So" , "SO" ]
]
)
CHAR_CASE_FOLDING = Enum(name="CASE_FOLDING", default=0,
data=[
["" , "NONE" ],
["F" , "FULL" ],
["S" , "SIMPLE" ],
["C" , "COMMON" ],
["T" , "SPECIAL" ]
]
)
# Decomposition.
CHAR_DECOMPOSITION = Enum(name="DECOMPOSITION", default=0,
data=[
["" , "NONE" ],
["<canonical>" , "CANONICAL" ],
["<font>" , "FONT" ],
["<noBreak>" , "NOBREAK" ],
# Arabic.
["<initial>" , "INITIAL" ],
["<medial>" , "MEDIAL" ],
["<final>" , "FINAL" ],
["<isolated>" , "ISOLATED" ],
# Script form
["<circle>" , "CIRCLE" ],
["<super>" , "SUPER" ],
["<sub>" , "SUB" ],
["<vertical>" , "VERTICAL" ],
["<wide>" , "WIDE" ],
["<narrow>" , "NARROW" ],
["<small>" , "SMALL" ],
["<square>" , "SQUARE" ],
["<fraction>" , "FRACTION" ],
["<compat>" , "COMPAT" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/GraphemeBreakProperty.txt
#
# Grapheme break properties.
CHAR_GRAPHEME_BREAK = Enum(name="GRAPHEME_BREAK", default=0,
data=[
["" , "XX" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Control" , "CN" ],
["Extend" , "EX" ],
["Prepend" , "PP" ],
["SpacingMark" , "SM" ],
# Hungul jamo (L/V/T) and syllable (LV/LVT).
["L" , "L" ],
["V" , "V" ],
["T" , "T" ],
["LV" , "LV" ],
["LVT" , "LVT" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/WordBreakProperty.txt
#
# Work break properties.
CHAR_WORD_BREAK = Enum(name="WORD_BREAK", default=0,
data=[
["" , "OTHER" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Newline" , "NL" ],
["Extend" , "EXTEND" ],
["Format" , "FO" ],
["Katakana" , "KA" ],
["ALetter" , "LE" ],
["MidLetter" , "ML" ],
["MidNum" , "MN" ],
["MidNumLet" , "MB" ],
["Numeric" , "NU" ],
["ExtendNumLet" , "EX" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/auxiliary/SentenceBreakProperty.txt
#
# Sentence break properties.
CHAR_SENTENCE_BREAK = Enum(name="SENTENCE_BREAK", default=0,
data=[
["Other" , "XX" ],
["CR" , "CR" ],
["LF" , "LF" ],
["Extend" , "EX" ],
["Sep" , "SE" ],
["Format" , "FO" ],
["Sp" , "SP" ],
["Lower" , "LO" ],
["Upper" , "UP" ],
["OLetter" , "LE" ],
["Numeric" , "NU" ],
["ATerm" , "AT" ],
["STerm" , "ST" ],
["Close" , "CL" ],
["SContinue" , "SC" ]
]
)
# http://www.unicode.org/Public/6.0.0/ucd/LineBreak.txt
#
# Line break properties.
CHAR_LINE_BREAK = Enum(name="LINE_BREAK", default=16,
data=[
["BK" , "BK" ],
["CR" , "CR" ],
["LF" , "LF" ],
["CM" , "CM" ],
["SG" , "SG" ],
["GL" , "GL" ],
["CB" , "CB" ],
["SP" , "SP" ],
["ZW" , "ZW" ],
["NL" , "NL" ],
["WJ" , "WJ" ],
["JL" , "JL" ],
["JV" , "JV" ],
["JT" , "JT" ],
["H2" , "H2" ],
["H3" , "H3" ],
["XX" , "XX" ],
["OP" , "OP" ],
["CL" , "CL" ],
["CP" , "CP" ],
["QU" , "QU" ],
["NS" , "NS" ],
["EX" , "EX" ],
["SY" , "SY" ],
["IS" , "IS" ],
["PR" , "PR" ],
["PO" , "PO" ],
["NU" , "NU" ],
["AL" , "AL" ],
["ID" , "ID" ],
["IN" , "IN" ],
["HY" , "HY" ],
["BB" , "BB" ],
["BA" , "BA" ],
["SA" , "SA" ],
["AI" , "AI" ],
["B2" , "B2" ],
# New in Unicode 6.1.0
["HL" , "HL" ],
["CJ" , "CJ" ]
]
)
# Joining.
CHAR_JOINING = Enum(name="JOINING", default=0,
data=[
["U" , "U" ],
["L" , "L" ],
["R" , "R" ],
["D" , "D" ],
["C" , "C" ],
["T" , "T" ]
]
)
CHAR_EAW = Enum(name="CHAR_EAW", default=0,
data=[
["A" , "A" ],
["N" , "N" ],
["F" , "F" ],
["H" , "H" ],
["Na" , "NA" ],
["W" , "W" ]
]
)
# Map type (Fog-Framework specific optimization).
CHAR_MAPPING = Enum(name="CHAR_MAPPING", default=0,
data=[
["None" , "NONE" ],
["Uppercase" , "LOWERCASE" ],
["Lowercase" , "UPPERCASE" ],
["Mirror" , "MIRROR" ],
["Digit" , "DIGIT" ],
["Special" , "SPECIAL" ]
]
)
CHAR_QUICK_CHECK = Enum(name="CHAR_QUICK_CHECK", default=0,
data=[
["No" , "NO" ],
["Yes" , "YES" ],
["Maybe" , "MAYBE" ]
],
alt={
"N": "No",
"Y": "Yes",
"M": "Maybe"
}
)
CHAR_VERSION = Enum(name="CHAR_VERSION", default=0,
# Normal map, used by DerivedAge.txt.
data=[
["" , "UNASSIGNED" ],
["1.1" , "V1_1" ],
["2.0" , "V2_0" ],
["2.1" , "V2_1" ],
["3.0" , "V3_0" ],
["3.1" , "V3_1" ],
["3.2" , "V3_2" ],
["4.0" , "V4_0" ],
["4.1" , "V4_1" ],
["5.0" , "V5_0" ],
["5.1" , "V5_1" ],
["5.2" , "V5_2" ],
["6.0" , "V6_0" ],
["6.1" , "V6_1" ]
],
# Alternative map, used by NormalizationCorrections.txt.
alt={
"3.2.0": "3.2",
"4.0.0": "4.0"
}
)
TEXT_SCRIPT = Enum(name="TEXT_SCRIPT", default=0,
data=[
["Unknown" , "UNKNOWN" ],
["Common" , "COMMON" ],
["Inherited" , "INHERITED" ],
["Latin" , "LATIN" ],
["Arabic" , "ARABIC" ],
["Armenian" , "ARMENIAN" ],
["Avestan" , "AVESTAN" ],
["Balinese" , "BALINESE" ],
["Bamum" , "BAMUM" ],
["Batak" , "BATAK" ],
["Bengali" , "BENGALI" ],
["Bopomofo" , "BOPOMOFO" ],
["Brahmi" , "BRAHMI" ],
["Braille" , "BRAILLE" ],
["Buginese" , "BUGINESE" ],
["Buhid" , "BUHID" ],
["Canadian_Aboriginal" , "CANADIAN_ABORIGINAL" ],
["Carian" , "CARIAN" ],
["Chakma" , "CHAKMA" ],
["Cham" , "CHAM" ],
["Cherokee" , "CHEROKEE" ],
["Coptic" , "COPTIC" ],
["Cuneiform" , "CUNEIFORM" ],
["Cypriot" , "CYPRIOT" ],
["Cyrillic" , "CYRILLIC" ],
["Devanagari" , "DEVANAGARI" ],
["Deseret" , "DESERET" ],
["Egyptian_Hieroglyphs" , "EGYPTIAN_HIEROGLYPHS" ],
["Ethiopic" , "ETHIOPIC" ],
["Georgian" , "GEORGIAN" ],
["Glagolitic" , "GLAGOLITIC" ],
["Gothic" , "GOTHIC" ],
["Greek" , "GREEK" ],
["Gujarati" , "GUJARATI" ],
["Gurmukhi" , "GURMUKHI" ],
["Han" , "HAN" ],
["Hangul" , "HANGUL" ],
["Hanunoo" , "HANUNOO" ],
["Hebrew" , "HEBREW" ],
["Hiragana" , "HIRAGANA" ],
["Imperial_Aramaic" , "IMPERIAL_ARAMAIC" ],
["Inscriptional_Pahlavi" , "INSCRIPTIONAL_PAHLAVI"],
["Inscriptional_Parthian", "INSCRIPTIONAL_PARTHIAN"],
["Javanese" , "JAVANESE" ],
["Kaithi" , "KAITHI" ],
["Kannada" , "KANNADA" ],
["Katakana" , "KATAKANA" ],
["Kayah_Li" , "KAYAH_LI" ],
["Kharoshthi" , "KHAROSHTHI" ],
["Khmer" , "KHMER" ],
["Lao" , "LAO" ],
["Lepcha" , "LEPCHA" ],
["Limbu" , "LIMBU" ],
["Linear_B" , "LINEAR_B" ],
["Lisu" , "LISU" ],
["Lycian" , "LYCIAN" ],
["Lydian" , "LYDIAN" ],
["Malayalam" , "MALAYALAM" ],
["Mandaic" , "MANDAIC" ],
["Meetei_Mayek" , "MEETEI_MAYEK" ],
["Meroitic_Cursive" , "MEROITIC_CURSIVE" ],
["Meroitic_Hieroglyphs" , "MEROITIC_HIEROGLYPHS" ],
["Miao" , "MIAO" ],
["Mongolian" , "MONGOLIAN" ],
["Myanmar" , "MAYANMAR" ],
["New_Tai_Lue" , "NEW_TAI_LUE" ],
["Nko" , "NKO" ],
["Ogham" , "OGHAM" ],
["Ol_Chiki" , "OL_CHIKI" ],
["Old_Italic" , "OLD_ITALIC" ],
["Old_Persian" , "OLD_PERSIAN" ],
["Old_South_Arabian" , "OLD_SOUTH_ARABIAN" ],
["Old_Turkic" , "OLD_TURKIC" ],
["Oriya" , "ORIYA" ],
["Osmanya" , "OSMANYA" ],
["Phags_Pa" , "PHAGS_PA" ],
["Phoenician" , "PHOENICIAN" ],
["Rejang" , "REJANG" ],
["Runic" , "RUNIC" ],
["Samaritan" , "SAMARITAN" ],
["Saurashtra" , "SAURASHTRA" ],
["Sharada" , "SHARADA" ],
["Shavian" , "SHAVIAN" ],
["Sinhala" , "SINHALA" ],
["Sora_Sompeng" , "SORA_SOMPENG" ],
["Sundanese" , "SUNDANESE" ],
["Syloti_Nagri" , "SYLOTI_NAGRI" ],
["Syriac" , "SYRIAC" ],
["Tagalog" , "TAGALOG" ],
["Tagbanwa" , "TAGBANWA" ],
["Tai_Le" , "TAI_LE" ],
["Tai_Tham" , "TAI_THAM" ],
["Tai_Viet" , "TAI_VIET" ],
["Takri" , "TAKRI" ],
["Tamil" , "TAMIL" ],
["Telugu" , "TELUGU" ],
["Thaana" , "THAANA" ],
["Thai" , "THAI" ],
["Tibetan" , "TIBETAN" ],
["Tifinagh" , "TIFINAGH" ],
["Ugaritic" , "UGARITIC" ],
["Vai" , "VAI" ],
["Yi" , "YI" ]
]
)
TEXT_SCRIPT_ISO15924_FROM = {}
TEXT_SCRIPT_ISO15924_TO = {}
COMPOSITION_ID_HANGUL = 0xFF
# -----------------------------------------------------------------------------
# [UCD-CharProperty]
# -----------------------------------------------------------------------------
class CharProperty(object):
used = 0
codePoint = 0
name = ""
category = CHAR_CATEGORY.get("")
combiningClass = 0
bidi = CHAR_BIDI.get("L")
joining = CHAR_JOINING.get("U")
digitValue = -1
decompositionType = CHAR_DECOMPOSITION.get("")
decompositionData = None
compositionExclusion = False
nfdQC = CHAR_QUICK_CHECK.get("Yes")
nfcQC = CHAR_QUICK_CHECK.get("Yes")
nfkdQC = CHAR_QUICK_CHECK.get("Yes")
nfkcQC = CHAR_QUICK_CHECK.get("Yes")
fullCaseFolding = None
simpleCaseFolding = 0
specialCaseFolding = 0
graphemeBreak = CHAR_GRAPHEME_BREAK.get("")
wordBreak = CHAR_WORD_BREAK.get("")
sentenceBreak = CHAR_SENTENCE_BREAK.get("")
lineBreak = CHAR_LINE_BREAK.get("")
lowercase = 0
uppercase = 0
titlecase = 0
mirror = 0
hasComposition = 0
compositionId = 0
script = TEXT_SCRIPT.get("")
eaw = CHAR_EAW.get("")
version = CHAR_VERSION.get("")
# Fog-specific memory optimization.
mapping = CHAR_MAPPING.get("None")
def __init__(self, **kw):
self.decompositionData = []
self.fullCaseFolding = []
for prop in kw:
setattr(self, prop, kw[prop])
# Get the difference between the code-point and uppercase.
@property
def upperdiff(self):
if self.uppercase != 0:
return self.uppercase - self.codePoint
else:
return 0
# Get the difference between the code-point and lowercase.
@property
def lowerdiff(self):
if self.lowercase != 0:
return self.lowercase - self.codePoint
else:
return 0
# Get the difference between the code-point and titlecase.
@property
def titlediff(self):
if self.titlecase != 0:
return self.titlecase - self.codePoint
else:
return 0
# Get the difference between the code-point and mirrored one.
@property
def mirrordiff(self):
if self.mirror != 0:
return self.mirror - self.codePoint
else:
return 0
@property
def isSpace(self):
return self.category == CHAR_CATEGORY.get("Zs") or \
self.category == CHAR_CATEGORY.get("Zl") or \
self.category == CHAR_CATEGORY.get("Zp") or \
(self.codePoint >= 9 and self.codePoint <= 13)
# -----------------------------------------------------------------------------
# [UCD-BlockProperty]
# -----------------------------------------------------------------------------
class BlockProperty(object):
def __init__(self, **kw):
self.first = 0
self.last = 0
self.name = ""
for prop in kw:
setattr(self, prop, kw[prop])
# -----------------------------------------------------------------------------
# [UCD-NormalizationCorrection]
# -----------------------------------------------------------------------------
class NormalizationCorrection(object):
def __init__(self, **kw):
self.code = 0
self.original = 0
self.corrected = 0
self.version = CHAR_VERSION.get("")
for prop in kw:
setattr(self, prop, kw[prop])
# -----------------------------------------------------------------------------
# [UCD-Globals (Data readed from UCD)]
# -----------------------------------------------------------------------------
# Character to CharacterProperty mapping.
CharList = []
# Block list (from ucd/Blocks.txt").
BlockList = []
# Normalization corrections.
NormalizationCorrectionsList = []
def PrepareTables():
log("-- Preparing...")
for i in xrange(NUM_CODE_POINTS):
CharList.append(CharProperty(codePoint=i))
# -----------------------------------------------------------------------------
# [UCD-CompositionPair]
# -----------------------------------------------------------------------------
class CompositionPair(object):
def __init__(self, a, b, ab):
self.a = a
self.b = b
self.ab = ab
# -----------------------------------------------------------------------------
# [UCD-Read]
# -----------------------------------------------------------------------------
def ReadPropertyValueAliases():
log("-- Read ucd/PropertyValueAliases.txt")
f = open(UCD_DIRECTORY + "ucd/PropertyValueAliases.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
# Just for safety
if len(data) < 3:
continue
property = data[0]
name = data[2]
aliases = [data[1]]
if len(data) > 3:
for i in xrange(3, len(data)):
aliases.append(data[i])
# Sentence break aliases
if property == "SB":
for alias in aliases:
CHAR_SENTENCE_BREAK.addAlias(alias, CHAR_SENTENCE_BREAK.get(name))
# Script aliases.
if property == "sc":
# Ignore these.
if name == "Katakana_Or_Hiragana":
continue
textScript = TEXT_SCRIPT.get(name)
for alias in aliases:
TEXT_SCRIPT.addAlias(alias, textScript)
for alias in aliases:
TEXT_SCRIPT_ISO15924_FROM[alias] = textScript
if not str(textScript) in TEXT_SCRIPT_ISO15924_TO:
TEXT_SCRIPT_ISO15924_TO[str(textScript)] = alias
f.close()
def ReadUnicodeData():
log("-- Read ucd/UnicodeData.txt")
f = open(UCD_DIRECTORY + "ucd/UnicodeData.txt", 'r')
first = -1
last = -1
for line in LineIterator(f):
data = SplitData(line)
code = int(data[UCD_VALUE], 16)
name = data[UCD_NAME]
# Parse a single code-point or range of code-points.
if name.startswith("<") and name.find("First") != -1:
first = code
last = -1
continue
if name.startswith("<") and name.find("Last") != -1:
assert(first != -1)
last = code
else:
first = code
last = code
# Process the character (or range).
for code in xrange(first, last+1):
c = CharList[code]
c.used = 1
c.category = CHAR_CATEGORY.get(data[UCD_CATEGORY])
c.combiningClass = int(data[UCD_COMBINING_CLASS])
# Bidi-category.
if data[UCD_BIDI]:
c.bidi = CHAR_BIDI.get(data[UCD_BIDI])
else:
# Default BIDI property is related to the code-point.
#
# The unassigned code points that default to AL are in the ranges:
# [\u0600-\u07BF \uFB50-\uFDFF \uFE70-\uFEFF]
# - minus noncharacter code points.
if code >= 0x00000600 and code <= 0x000007BF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0000FB50 and code <= 0x0000FDFF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0000FE70 and code <= 0x0000FEFF: c.bidi = CHAR_BIDI.get("AL")
# The unassigned code points that default to R are in the ranges:
# [\u0590-\u05FF \u07C0-\u08FF \uFB1D-\uFB4F \U00010800-\U00010FFF \U0001E800-\U0001EFFF]
if code >= 0x00000590 and code <= 0x000005FF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x000007C0 and code <= 0x000008FF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x0000FB1D and code <= 0x0000FB4F: c.bidi = CHAR_BIDI.get("R")
if code >= 0x00010800 and code <= 0x00010FFF: c.bidi = CHAR_BIDI.get("R")
if code >= 0x0001E800 and code <= 0x0001EFFF: c.bidi = CHAR_BIDI.get("R")
# ----------------------------------------------------------------------
# Changed in Unicode 6.1.0 - U+08A0..U+08FF and U+1EE00..U+1EEFF changed
# from R to AL.
# ----------------------------------------------------------------------
if code >= 0x000008A0 and code <= 0x000008FF: c.bidi = CHAR_BIDI.get("AL")
if code >= 0x0001EE00 and code <= 0x0001EEFF: c.bidi = CHAR_BIDI.get("AL")
# Digit value.
if len(data[UCD_DIGIT_VALUE]):
c.digitValue = int(data[UCD_DIGIT_VALUE], 10)
# Uppercase/Lowercase/Titlecase - Assign the case change only if it
# differs to the original code-point.
if data[UCD_TITLECASE] == "":
# If the TITLECASE is NULL, it has the value UPPERCASE.
data[UCD_TITLECASE] = data[UCD_UPPERCASE]
if data[UCD_UPPERCASE] and int(data[UCD_UPPERCASE], 16) != code:
c.uppercase = int(data[UCD_UPPERCASE], 16)
if data[UCD_LOWERCASE] and int(data[UCD_LOWERCASE], 16) != code:
c.lowercase = int(data[UCD_LOWERCASE], 16)
if data[UCD_TITLECASE] and int(data[UCD_TITLECASE], 16) != code:
c.titlecase = int(data[UCD_TITLECASE], 16)
# Joining (from Unicode 6.0):
# - Those that not explicitly listed that are of General Category Mn, Me, or Cf
# have joining type T.
# - All others not explicitly listed have joining type U.
if c.category == CHAR_CATEGORY.get("Mn") or c.category == CHAR_CATEGORY.get("Me") or c.category == CHAR_CATEGORY.get("Cf"):
c.joining = CHAR_JOINING.get("T")
else:
c.joining = CHAR_JOINING.get("U")
# Decomposition.
if data[UCD_DECOMPOSITION]:
dec = data[UCD_DECOMPOSITION].split(' ')
# Parse <decompositionType>.
if dec[0].startswith('<'):
c.decompositionType = CHAR_DECOMPOSITION.get(dec[0])
dec = dec[1:]
else:
c.decompositionType = CHAR_DECOMPOSITION.get("<canonical>")
# Decomposition character list.
for d in dec:
c.decompositionData.append(int(d, 16))
# Set has-composition flag to the first canonically decomposed
# character.
if c.decompositionType == CHAR_DECOMPOSITION.get("<canonical>") and len(c.decompositionData) == 2:
CharList[c.decompositionData[0]].hasComposition = 1
f.close()
def ReadXBreakHelper(fileName, propertyName, MAP):
log("-- Read " + fileName)
f = open(UCD_DIRECTORY + fileName, 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
for code in xrange(first, last + 1):
c = CharList[code]
setattr(c, propertyName, MAP.get(data[1]))
f.close()
def ReadLineBreak():
ReadXBreakHelper("ucd/LineBreak.txt", "lineBreak", CHAR_LINE_BREAK)
def ReadGraphemeBreak():
ReadXBreakHelper("ucd/auxiliary/GraphemeBreakProperty.txt", "graphemeBreak", CHAR_GRAPHEME_BREAK)
def ReadSentenceBreak():
ReadXBreakHelper("ucd/auxiliary/SentenceBreakProperty.txt", "sentenceBreak", CHAR_SENTENCE_BREAK)
def ReadWordBreak():
ReadXBreakHelper("ucd/auxiliary/WordBreakProperty.txt", "wordBreak", CHAR_WORD_BREAK)
def ReadArabicShaping():
log("-- Read ucd/ArabicShaping.txt")
f = open(UCD_DIRECTORY + "ucd/ArabicShaping.txt", 'rb')
# Note: Code points that are not explicitly listed in this file are
# either of joining type T or U:
#
# - Those that not explicitly listed that are of General Category Mn, Me, or Cf
# have joining type T.
# - All others not explicitly listed have joining type U.
#
# Note: U is default when CharProperty is created, need to setup the "T" joining
# only.
for code in xrange(NUM_CODE_POINTS):
c = CharList[code]
if c.category == CHAR_CATEGORY.get("Mn") or \
c.category == CHAR_CATEGORY.get("Me") or \
c.category == CHAR_CATEGORY.get("Cf"): c.joining = CHAR_JOINING.get("T")
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
c = CharList[code]
c.joining = CHAR_JOINING.get(data[2])
f.close()
def ReadBidiMirroring():
log("-- Read ucd/BidiMirroring.txt")
f = open(UCD_DIRECTORY + "ucd/BidiMirroring.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
c = CharList[code]
c.mirror = int(data[1], 16)
f.close()
def ReadCaseFolding():
log("-- Read ucd/CaseFolding.txt")
f = open(UCD_DIRECTORY + "ucd/CaseFolding.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
status = data[1]
mapping = data[2].split(' ')
for i in xrange(len(mapping)):
mapping[i] = int(mapping[i].strip(), 16)
c = CharList[code]
# "C" - Common case-folding ("S" and "F" shared).
if status == "C":
assert len(mapping) == 1
c.simpleCaseFolding = mapping[0]
c.fullCaseFolding = mapping
# "F" - Full case-folding.
if status == "F":
c.fullCaseFolding = mapping
# "S" - Simple case-folding.
if status == "S":
c.simpleCaseFolding = mapping[0]
# "T" - Special case-folding.
if status == "T":
c.specialCaseFolding = mapping[0]
f.close()
def ReadSpecialCasing():
log("-- Read ucd/SpecialCasing.txt")
f = open(UCD_DIRECTORY + "ucd/SpecialCasing.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
# TODO
# TODO
# TODO
# TODO
# TODO
# TODO
f.close()
def ReadDerivedAge():
log("-- Read ucd/DerivedAge.txt")
f = open(UCD_DIRECTORY + "ucd/DerivedAge.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
version = CHAR_VERSION.get(data[1])
for code in xrange(first, last + 1):
c = CharList[code]
c.version = version
f.close()
def ReadDerivedNormalizationProps():
log("-- Read ucd/DerivedNormalizationProps.txt")
f = open(UCD_DIRECTORY + "ucd/DerivedNormalizationProps.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
for code in xrange(first, last + 1):
c = CharList[code]
prop = data[1]
# FullCompositionExclusion.
if prop == "Full_Composition_Exclusion":
c.compositionExclusion = True
# Quick-Check.
if prop == "NFD_QC":
c.nfdQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFC_QC":
c.nfcQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFKD_QC":
c.nfkdQC = CHAR_QUICK_CHECK.get(data[2])
if prop == "NFKC_QC":
c.nfkcQC = CHAR_QUICK_CHECK.get(data[2])
f.close()
def ReadNormalizationCorrections():
log("-- Read ucd/NormalizationCorrections.txt")
f = open(UCD_DIRECTORY + "ucd/NormalizationCorrections.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
code = int(data[0], 16)
orig = int(data[1], 16)
corrected = int(data[2], 16)
version = CHAR_VERSION.get(data[3])
item = NormalizationCorrection(
code=code,
original=orig,
corrected=corrected,
version=version)
NormalizationCorrectionsList.append(item)
f.close()
def ReadEastAsianWidth():
log("-- Read ucd/EastAsianWidth.txt")
f = open(UCD_DIRECTORY + "ucd/EastAsianWidth.txt", 'rb')
# The unassigned code points that default to "W" include ranges in the
# following blocks:
# CJK Unified Ideographs Extension A: U+3400..U+4DBF
# CJK Unified Ideographs: U+4E00..U+9FFF
# CJK Compatibility Ideographs: U+F900..U+FAFF
# CJK Unified Ideographs Extension B: U+20000..U+2A6DF
# CJK Unified Ideographs Extension C: U+2A700..U+2B73F
# CJK Unified Ideographs Extension D: U+2B740..U+2B81F
# CJK Compatibility Ideographs Supplement: U+2F800..U+2FA1F
# and any other reserved code points on
# Planes 2 and 3: U+20000..U+2FFFD
# U+30000..U+3FFFD
W = CHAR_EAW.get("W")
for code in xrange(0x003400, 0x004DBF+1): CharList[code].eaw = W
for code in xrange(0x004E00, 0x009FFF+1): CharList[code].eaw = W
for code in xrange(0x00F900, 0x00FAFF+1): CharList[code].eaw = W
for code in xrange(0x020000, 0x02A6DF+1): CharList[code].eaw = W
for code in xrange(0x02A700, 0x02B73F+1): CharList[code].eaw = W
for code in xrange(0x02B740, 0x02B81F+1): CharList[code].eaw = W
for code in xrange(0x02F800, 0x02FA1F+1): CharList[code].eaw = W
for code in xrange(0x020000, 0x02FFFD+1): CharList[code].eaw = W
for code in xrange(0x030000, 0x03FFFD+1): CharList[code].eaw = W
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
eaw = CHAR_EAW.get(data[1])
for code in xrange(first, last + 1):
c = CharList[code]
c.eaw = eaw
f.close()
def ReadScriptsHelper(fileName):
log("-- Read " + fileName)
f = open(UCD_DIRECTORY + fileName, 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
script = data[1]
for code in xrange(first, last + 1):
c = CharList[code]
c.script = TEXT_SCRIPT.get(script)
# TODO
# TODO
# TODO
# TODO
# TODO
# TODO
f.close()
def ReadScripts():
ReadScriptsHelper("ucd/Scripts.txt")
# ReadScriptsHelper("ucd/ScriptExtensions.txt")
def ReadBlocks():
log("-- Read ucd/Blocks.txt")
f = open(UCD_DIRECTORY + "ucd/Blocks.txt", 'rb')
for line in LineIterator(f):
data = SplitData(line)
first, last = GetCharRange(data[0])
name = data[1]
BlockList.append(BlockProperty(first=first, last=last, name=name))
f.close()
# -----------------------------------------------------------------------------
# [UCD-Check]
# -----------------------------------------------------------------------------
def Check():
log("-- Checking data")
maxCombiningClass = 0
maxDecompositionChar = 0
maxSimpleCaseFolding = 0
maxSpecialCaseFolding = 0
maxFullCaseFolding = 0
maxSpace = 0
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if maxCombiningClass < c.combiningClass:
maxCombiningClass = c.combiningClass
if c.decompositionData:
for d in c.decompositionData:
if maxDecompositionChar < d:
maxDecompositionChar = d
if c.simpleCaseFolding:
if maxSimpleCaseFolding < c.simpleCaseFolding:
maxSimpleCaseFolding = c.simpleCaseFolding
if c.specialCaseFolding:
if maxSpecialCaseFolding < c.specialCaseFolding:
maxSpecialCaseFolding = c.specialCaseFolding
if c.fullCaseFolding:
for d in c.fullCaseFolding:
if maxFullCaseFolding < d:
maxFullCaseFolding = d
if c.isSpace:
if maxSpace < i:
maxSpace = i
# Check whether the uppercase, lowercase, titlecase and mirror mapping
# doesn't exceed our limit (in this case Fog-API must be changed).
if c.uppercase:
if abs(c.uppercase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and uppercase " + ucd(c.uppercase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.uppercase >=0x10000) or \
(c.codePoint >=0x10000 and c.uppercase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and uppercase character " + ucd(c.uppercase) + "are in different plane (BMP/SMP combination)")
if c.lowercase:
if abs(c.lowercase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and lowercase " + ucd(c.lowercase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.lowercase >=0x10000) or \
(c.codePoint >=0x10000 and c.lowercase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and lowercase character " + ucd(c.lowercase) + "are in different plane (BMP/SMP combination)")
if c.titlecase != 0:
if abs(c.titlecase - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and titlecase " + ucd(c.titlecase) + " characters are too far.")
if (c.codePoint < 0x10000 and c.titlecase >=0x10000) or \
(c.codePoint >=0x10000 and c.titlecase < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and titlecase character " + ucd(c.titlecase) + "are in different plane (BMP/SMP combination)")
if c.mirror != 0:
if abs(c.mirror - i) > MAX_PAIRED_DIFF:
log("** FATAL: " + ucd(c.codePoint) + " and mirrored " + ucd(c.mirror) + " characters are too far.")
if (c.codePoint < 0x10000 and c.mirror >=0x10000) or \
(c.codePoint >=0x10000 and c.mirror < 0x10000):
log("** FATAL: Code point " + ucd(c.codePoint) + " and mirror character " + ucd(c.mirror) + "are in different plane (BMP/SMP combination)")
# Check if our assumption that "mirrored/digit character never has lowercase,
# uppercase, or titlecase variant" is valid.
if c.uppercase + c.lowercase + c.titlecase != 0 and (c.mirror != 0 or c.digitValue != -1):
log("** FATAL: " + ucd(c.codePoint) + " - contains both, case and mirror mapping.")
# Check another assumption that there is no character that maps to all
# three categories (uppercase, lowercase, and titlecase). Mapping to itself
# is never used.
if c.uppercase != 0 and c.lowercase != 0 and c.titlecase != 0:
log("** FATAL: " + ucd(c.codePoint) + " - contains upper("+ucd(c.uppercase)+")+lower(" + ucd(c.lowercase) + ")+title(" + ucd(c.titlecase) + ") mapping.")
log(" MAX COMBINING CLASS : " + str(maxCombiningClass))
log(" MAX DECOMPOSED CHAR : " + str(maxDecompositionChar))
log(" MAX SIMPLE-CASE-FOLDING : " + str(maxSimpleCaseFolding))
log(" MAX SPECIAL-CASE-FOLDING: " + str(maxSpecialCaseFolding))
log(" MAX FULL-CASE-FOLDING : " + str(maxFullCaseFolding))
log(" MAX SPACE : " + str(maxSpace))
def PrintTitleCase():
log("-- Printing all titlecases characters")
chars = {}
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if c.category == CHAR_CATEGORY.get("Lt"):
chars[c.codePoint] = True
for c in chars:
c = CharList[c]
log(" TC=" + ucd(c.codePoint) + " LC=" + ucd(c.lowercase) + " UC=" + ucd(c.uppercase))
# -----------------------------------------------------------------------------
# [UCD-Generate]
# -----------------------------------------------------------------------------
class Code(object):
def __init__(self):
# Use python list instead of string concatenation, it's many
# times faster when concatenating a very large string.
self.OffsetDecl = []
self.OffsetRows = []
self.PropertyClass = []
self.PropertyDecl = []
self.PropertyRows = []
self.SpecialClass = []
self.SpecialDecl = []
self.SpecialRows = []
self.InfoClass = []
self.InfoDecl = []
self.InfoRows = []
self.DecompositionDecl = []
self.DecompositionData = []
self.CompositionDecl = []
self.CompositionIndex = []
self.CompositionData = []
self.MethodsInline = []
self.TextScriptEnum = []
self.NormalizationCorrectionsDecl = []
self.NormalizationCorrectionsData = []
self.Iso15924Decl = []
self.Iso15924Data_From = []
self.Iso15924Data_To = []
Code = Code()
# Please update when needed.
SIZE_OF_OFFSET_ROW = 1 # If number of blocks is smaller than 256, otherwise 2
SIZE_OF_PROPERTY_ROW = 8
SIZE_OF_INFO_ROW = 8
SIZE_OF_SPECIAL_ROW = 36
SIZE_OF_NORMALIZATION_CORRECTION_ROW = 16
SIZE_OF_COMPOSITION_ID_TO_INDEX_ROW = 2
SIZE_OF_COMPOSITION_ROW = 8
# Generator configuration (and some constants).
OUTPUT_BLOCK_SIZE = 128
# Whether to only test generator (output to stdout instead of writing to .h/.cpp).
TEST_ONLY = False
# The comment to include in auto-generated code.
AUTOGENERATED_BEGIN = "// --- Auto-generated by generate-unicode.py (Unicode " + UCD_VERSION + ") ---"
AUTOGENERATED_END = "// --- Auto-generated by generate-unicode.py (Unicode " + UCD_VERSION + ") ---"
def GenerateEnums():
log("-- Generating enums")
# Generate TEXT_SCRIPT enum.
Code.TextScriptEnum.append(" " + AUTOGENERATED_BEGIN + "\n")
Code.TextScriptEnum.append("\n" + TEXT_SCRIPT.generateEnum() + "\n")
Code.TextScriptEnum.append(" " + AUTOGENERATED_END + "\n")
def GenerateComposition():
log("-- Generating composition tables")
pairs = []
pairs.append(CompositionPair(0, 0, 0))
maxChar = 0
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
# Generate composition pair.
if c.compositionExclusion == False and \
c.decompositionType == CHAR_DECOMPOSITION.get("<canonical>") and \
len(c.decompositionData) == 2:
pair = CompositionPair(c.decompositionData[0], c.decompositionData[1], i)
if pair.a > maxChar: maxChar = pair.a
if pair.b > maxChar: maxChar = pair.b
if pair.ab > maxChar: maxChar = pair.ab
pairs.append(pair)
pairs.sort(key=lambda x: (long(x.b) << 32) + long(x.a))
pairs.append(CompositionPair(0, 0, 0))
count = len(pairs)
idToIndex = []
uniqueBDict = {}
for i in xrange(count):
pair = pairs[i]
c = CharList[pair.b]
if c.codePoint == 0:
continue
if not pair.b in uniqueBDict:
uniqueBDict[pair.b] = len(idToIndex)
idToIndex.append(i)
c.compositionId = uniqueBDict[pair.b]
# Terminate the idToIndex array so it's possible to use idToIndex[i+1] to
# get the length of A+B list where B is constant.
idToIndex.append(count)
uniqueBKeys = len(uniqueBDict)
log(" Unique Combiners: " + str(uniqueBKeys))
Code.CompositionDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.CompositionDecl.append(" //! @brief Composition id to composition data index mapping.\n")
Code.CompositionDecl.append(" uint16_t compositionIdToIndex[" + str(Align(uniqueBKeys, 4)) + "];\n")
Code.CompositionDecl.append("\n")
Code.CompositionDecl.append(" //! @brief Composition data.\n")
Code.CompositionDecl.append(" CharComposition compositionData[" + str(count) + "];\n")
Code.CompositionDecl.append("\n")
Code.CompositionDecl.append(" " + AUTOGENERATED_END + "\n")
Code.CompositionIndex.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(uniqueBKeys):
Code.CompositionIndex.append(" " + str(idToIndex[i]))
if i != uniqueBKeys - 1:
Code.CompositionIndex.append(",\n")
else:
Code.CompositionIndex.append("\n")
Code.CompositionIndex.append("\n")
Code.CompositionIndex.append(" " + AUTOGENERATED_END + "\n")
Code.CompositionData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(count):
pair = pairs[i]
Code.CompositionData.append(" { " + uch(pair.a) + ", " + uch(pair.b) + ", " + uch(pair.ab) + " }")
if i != count - 1:
Code.CompositionData.append(",\n")
else:
Code.CompositionData.append("\n")
Code.CompositionData.append("\n")
Code.CompositionData.append(" " + AUTOGENERATED_END + "\n")
log(" COMPOSITION ID: " + str(uniqueBKeys) + \
" (" + str(uniqueBKeys * SIZE_OF_COMPOSITION_ID_TO_INDEX_ROW) + " bytes)")
log(" COMPOSITION : " + str(count) + \
" (" + str(count * SIZE_OF_COMPOSITION_ROW) + " bytes)")
def GenerateSpecial():
log("-- Generating special characters info (ligatures, case-folding, ...)")
for i in xrange(NUM_CODE_POINTS):
c = CharList[i]
if c.titlecase == 0 and ((c.lowercase == 0 and c.mirror == 0) or \
(c.uppercase == 0 and c.mirror == 0) or \
(c.lowercase == 0 and c.uppercase == 0)):
# Mark character as not special. This means that CHAR_MAPPING must contain one
# of NONE, LOWERCASE, UPPERCASE or MIRROR.
if c.uppercase != 0:
c.mapping = CHAR_MAPPING.get("Uppercase")
elif c.lowercase != 0:
c.mapping = CHAR_MAPPING.get("Lowercase")
elif c.mirror != 0:
c.mapping = CHAR_MAPPING.get("Mirror")
elif c.digitValue != -1:
c.mapping = CHAR_MAPPING.get("Digit")
else:
# Special (complex) character mapping.
c.mapping = CHAR_MAPPING.get("Special")
def GenerateClasses():
pass
def GenerateNormalizationCorrections():
log("-- Generating normalization corrections")
count = len(NormalizationCorrectionsList)
Code.NormalizationCorrectionsDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.NormalizationCorrectionsDecl.append(" //! @brief Unicode normalization corrections.\n")
Code.NormalizationCorrectionsDecl.append(" CharNormalizationCorrection normalizationCorrections[" + str(count) + "];\n")
Code.NormalizationCorrectionsDecl.append("\n")
Code.NormalizationCorrectionsDecl.append(" " + AUTOGENERATED_END + "\n")
Code.NormalizationCorrectionsData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(count):
nc = NormalizationCorrectionsList[i]
Code.NormalizationCorrectionsData.append(" { " + \
uch(nc.code) + ", " + uch(nc.original) + ", " + uch(nc.corrected) + ", " + "CHAR_UNICODE_" + CHAR_VERSION.fog(nc.version) + " }")
if i != count - 1:
Code.NormalizationCorrectionsData.append(",\n")
else:
Code.NormalizationCorrectionsData.append("\n")
Code.NormalizationCorrectionsData.append("\n")
Code.NormalizationCorrectionsData.append(" " + AUTOGENERATED_END + "\n")
log(" NORM_CORR ROWS: " + str(count) + \
" (" + str(count * SIZE_OF_NORMALIZATION_CORRECTION_ROW) + " bytes)")
def GenerateIso15924Names():
# Generate ISO15924 names.
textScriptCount = TEXT_SCRIPT.count()
iso15924Keys = TEXT_SCRIPT_ISO15924_FROM.keys()
iso15924Keys.sort()
iso15924Count = len(iso15924Keys)
Code.Iso15924Decl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.Iso15924Decl.append(" //! @brief ISO-15924 From TEXT_SCRIPT.\n")
Code.Iso15924Decl.append(" uint32_t iso15924FromTextScript[" + str(textScriptCount) + "];\n")
Code.Iso15924Decl.append("\n")
Code.Iso15924Decl.append(" //! @brief TEXT_SCRIPT from ISO-15924.\n")
Code.Iso15924Decl.append(" CharISO15924Data textScriptFromIso15924[" + str(iso15924Count) + "];\n")
Code.Iso15924Decl.append("\n")
Code.Iso15924Decl.append(" " + AUTOGENERATED_END + "\n")
Code.Iso15924Data_From.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(textScriptCount):
iso15924Name = TEXT_SCRIPT_ISO15924_TO[str(i)]
assert(len(iso15924Name) == 4)
# Replace Zzzz with NULL.
if iso15924Name == "Zzzz":
Code.Iso15924Data_From.append(" 0")
else:
Code.Iso15924Data_From.append(" FOG_ISO15924_NAME(" + \
Literal(iso15924Name[0]) + ", " + \
Literal(iso15924Name[1]) + ", " + \
Literal(iso15924Name[2]) + ", " + \
Literal(iso15924Name[3]) + ")")
if i != textScriptCount - 1:
Code.Iso15924Data_From.append(",\n")
else:
Code.Iso15924Data_From.append("\n")
Code.Iso15924Data_From.append("\n")
Code.Iso15924Data_From.append(" " + AUTOGENERATED_END + "\n")
Code.Iso15924Data_To.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(iso15924Count):
iso15924Name = iso15924Keys[i]
assert(len(iso15924Name) == 4)
Code.Iso15924Data_To.append(" { ")
Code.Iso15924Data_To.append("FOG_ISO15924_NAME(" + \
Literal(iso15924Name[0]) + ", " + \
Literal(iso15924Name[1]) + ", " + \
Literal(iso15924Name[2]) + ", " + \
Literal(iso15924Name[3]) + ")")
Code.Iso15924Data_To.append(", ")
Code.Iso15924Data_To.append("TEXT_SCRIPT_" + TEXT_SCRIPT.fog(TEXT_SCRIPT.get(iso15924Name)))
Code.Iso15924Data_To.append(" }")
if i != iso15924Count - 1:
Code.Iso15924Data_To.append(",\n")
else:
Code.Iso15924Data_To.append("\n")
Code.Iso15924Data_To.append("\n")
Code.Iso15924Data_To.append(" " + AUTOGENERATED_END + "\n")
def GenerateTable():
global SIZE_OF_OFFSET_ROW
log("-- Generating tables")
rowBlockHash = {}
rowBlockList = []
rowBlockData = ""
rowBlockFirst = -1
specialHash = {}
specialList = []
offsetList = []
decompositionHash = {}
decompositionList = []
decompositionList.append(0)
maxDecompositionLength = 0
infoHash = {}
infoList = []
def GetOffsetShift(val):
result = -1
while val:
result += 1
val = val >> 1
return result
def GetOffsetMask(val):
return val - 1
# ---------------------------------------------------------------------------
# Headers.
# ---------------------------------------------------------------------------
Code.PropertyClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" // First 32-bit packed int.\n" + \
" // - uint32_t _infoIndex : 12;\n" + \
" // - uint32_t _mappingType : 3;\n" + \
" // - int32_t _mappingData : 17;\n" + \
" // Needed to pack to a signle integer, because of different types used.\n" + \
" int32_t _infoAndMapping;\n" + \
"\n" + \
" // Second 32-bit packed int.\n" + \
" uint32_t _category : 5;\n" + \
" uint32_t _space : 1;\n" + \
" uint32_t _hasComposition : 1;\n" + \
" uint32_t _decompositionType : 5;\n" + \
" uint32_t _decompositionIndex : 15;\n" + \
" uint32_t _unused : 5;\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
Code.InfoClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" // First 32-bit packed int.\n" + \
" uint32_t _combiningClass : 8;\n" + \
" uint32_t _script : 8;\n" + \
" uint32_t _unicodeVersion : 4;\n" + \
" uint32_t _graphemeBreak : 4;\n" + \
" uint32_t _wordBreak : 4;\n" + \
" uint32_t _sentenceBreak : 4;\n" + \
"\n" + \
" // Second 32-bit packed int.\n" + \
" uint32_t _lineBreak : 6;\n" + \
" uint32_t _bidi : 5;\n" + \
" uint32_t _joining : 3;\n" + \
" uint32_t _eaw : 3;\n" + \
" uint32_t _compositionExclusion : 1;\n"+ \
" uint32_t _nfdQC : 1;\n" + \
" uint32_t _nfcQC : 2;\n" + \
" uint32_t _nfkdQC : 1;\n" + \
" uint32_t _nfkcQC : 2;\n" + \
" uint32_t _compositionId : 8;\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
Code.SpecialClass.append("" + \
" " + AUTOGENERATED_BEGIN + "\n" + \
"\n" + \
" int32_t _upperCaseDiff : 22;\n" + \
" int32_t _unused0 : 10;\n" + \
"\n" + \
" int32_t _lowerCaseDiff : 22;\n" + \
" int32_t _unused1 : 10;\n" + \
"\n" + \
" int32_t _titleCaseDiff : 22;\n" + \
" int32_t _unused2 : 10;\n" + \
"\n" + \
" int32_t _mirrorDiff : 22;\n" + \
" int32_t _digitValue : 10;\n" + \
"\n" + \
" uint32_t _simpleCaseFolding;\n" + \
" uint32_t _specialCaseFolding;\n" + \
" uint32_t _fullCaseFolding[3];\n" + \
"\n" + \
" " + AUTOGENERATED_END + "\n" + \
""
)
# ---------------------------------------------------------------------------
# Collect info and generate data which will be used to generate tables.
# ---------------------------------------------------------------------------
class RowBlock(object):
def __init__(self, offset):
self.offset = offset
self.count = 1
self.chars = []
for i in xrange(NUM_CODE_POINTS):
if rowBlockFirst == -1:
rowBlockFirst = i
rowBlockData = ""
c = CharList[i]
# Info.
s = " _CHAR_INFO("
s += str(c.combiningClass) + ", " # CombiningClass
s += TEXT_SCRIPT.fog(c.script) + ", " # Script
s += CHAR_VERSION.fog(c.version) + ", " # UnicodeVersion
s += CHAR_GRAPHEME_BREAK.fog(c.graphemeBreak) + ", " # GraphemeBreak
s += CHAR_WORD_BREAK.fog(c.wordBreak) + ", " # WordBreak
s += CHAR_SENTENCE_BREAK.fog(c.sentenceBreak) + ", " # SentenceBreak
s += CHAR_LINE_BREAK.fog(c.lineBreak) + ", " # LineBreak
s += CHAR_BIDI.fog(c.bidi) + ", " # Bidi
s += CHAR_JOINING.fog(c.joining) + ", " # Joining
s += CHAR_EAW.fog(c.eaw) + ", " # East-Asian Width.
s += str(int(c.compositionExclusion)) + ", " # CompositionExclusion.
s += CHAR_QUICK_CHECK.fog(c.nfdQC) + ", " # NFD_QC.
s += CHAR_QUICK_CHECK.fog(c.nfcQC) + ", " # NFC_QC.
s += CHAR_QUICK_CHECK.fog(c.nfkdQC) + ", " # NFKD_QC.
s += CHAR_QUICK_CHECK.fog(c.nfkcQC) + ", " # NFKC_QC.
s += str(c.compositionId) # CompositionId
s += ")"
if not s in infoHash:
infoHash[s] = len(infoList)
infoList.append(s)
infoIndex = infoHash[s]
# Decomposition data.
decompositionDataIndex = 0
decompositionDataLength = 0
s = ""
if len(c.decompositionData) > 0:
dt = [0]
for cp in c.decompositionData:
if cp > 0x10000:
dt.extend(SurrogatePairOf(cp))
else:
dt.append(cp)
dt[0] = len(dt) - 1
if len(dt) > maxDecompositionLength:
maxDecompositionLength = len(dt)
s += ", ".join([str(item) for item in dt])
if not s in decompositionHash:
decompositionHash[s] = len(decompositionList)
decompositionList.extend(dt)
decompositionDataIndex = decompositionHash[s]
decompositionDataLength = len(dt)
# Mapping.
mappingConstant = 0
if c.mapping == CHAR_MAPPING.get("Uppercase"):
mappingConstant = c.upperdiff
if c.mapping == CHAR_MAPPING.get("Lowercase"):
mappingConstant = c.lowerdiff
if c.mapping == CHAR_MAPPING.get("Mirror"):
mappingConstant = c.mirrordiff
if c.mapping == CHAR_MAPPING.get("Digit"):
mappingConstant = c.digitValue
if c.mapping == CHAR_MAPPING.get("Special"):
s = " " + "{ "
# UpperCaseDiff/Unused0.
s += str(c.upperdiff) + ", "
s += "0, "
# LowerCaseDiff/Unused1.
s += str(c.lowerdiff) + ", "
s += "0, "
# TitleCaseDiff/Unused2.
s += str(c.titlediff) + ", "
s += "0, "
# MirrorDiff/DigitValue.
s += str(c.mirrordiff) + ", "
s += str(c.digitValue) + ", "
# SimpleCaseFolding+FullCaseFolding.
s += uch(c.simpleCaseFolding) + ", "
s += uch(c.specialCaseFolding) + ", "
s += "{ "
if c.fullCaseFolding:
s += ", ".join([uch(t) for t in c.fullCaseFolding])
else:
s += "0x0000"
s += " } "
s += "}"
if s in specialHash:
mappingConstant = specialHash[s]
else:
mappingConstant = len(specialList)
specialHash[s] = mappingConstant
specialList.append(s)
s = " _CHAR_PROPERTY("
s += str(infoIndex) + ", " # Info Index.
s += CHAR_MAPPING.fog(c.mapping) + ", " # MappingType.
s += str(mappingConstant) + ", " # MappingData.
s += CHAR_CATEGORY.fog(c.category) + ", " # Category.
s += str(int(c.isSpace)) + ", " # Space.
s += str(c.hasComposition) + ", " # HasComposition.
s += CHAR_DECOMPOSITION.fog(c.decompositionType) + ", " # DecompositionType.
s += str(decompositionDataIndex) # DecompositionIndex.
s += ")"
rowBlockData += s
if i == rowBlockFirst + OUTPUT_BLOCK_SIZE - 1:
if not rowBlockData in rowBlockHash:
rowBlockHash[rowBlockData] = RowBlock(len(rowBlockList))
rowBlockList.append(rowBlockData)
else:
rowBlockHash[rowBlockData].count += 1
rowBlockHash[rowBlockData].chars.append(rowBlockFirst)
rowBlockFirst = -1
offsetList.append(rowBlockHash[rowBlockData].offset)
else:
rowBlockData += ",\n"
# If number of row-blocks exceeded 255 then uint16_t must be
# used as an insex. It's larger, this is reason why the code
# is tuned to output data in uint8_t.
if len(rowBlockList) > 255:
SIZE_OF_OFFSET_ROW = 2
# ---------------------------------------------------------------------------
# Generate info table.
# ---------------------------------------------------------------------------
numInfoRows = len(infoList)
Code.InfoDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.InfoDecl.append(" //! @brief Character info data (see @ref CharProperty::infoIndex).\n")
Code.InfoDecl.append(" CharInfo info[" + str(numInfoRows) + "];\n\n")
Code.InfoDecl.append(" " + AUTOGENERATED_END + "\n")
Code.InfoRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.InfoRows.append("" + \
"# define _CHAR_INFO(_CombiningClass_, _Script_, _Version_, _GB_, _WB_, _SB_, _LB_, _Bidi_, _Joining_, _EAW_, _CompositionExclusion_, _NFDQC_, _NFCQC_, _NFKDQC_, _NFKCQC_, _CompositionId_) \\\n" + \
" { \\\n" + \
" _CombiningClass_, \\\n" + \
" TEXT_SCRIPT_##_Script_, \\\n" + \
" CHAR_UNICODE_##_Version_, \\\n" + \
" CHAR_GRAPHEME_BREAK_##_GB_, \\\n" + \
" CHAR_WORD_BREAK_##_WB_, \\\n" + \
" CHAR_SENTENCE_BREAK_##_SB_, \\\n" + \
" CHAR_LINE_BREAK_##_LB_, \\\n" + \
" CHAR_BIDI_##_Bidi_, \\\n" + \
" CHAR_JOINING_##_Joining_, \\\n" + \
" CHAR_EAW_##_EAW_, \\\n" + \
" _CompositionExclusion_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFDQC_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFCQC_, \\\n" + \
" CHAR_QUICK_CHECK_##_NFKDQC_,\\\n" + \
" CHAR_QUICK_CHECK_##_NFKCQC_,\\\n" + \
" _CompositionId_ \\\n" + \
" }\n"
)
for i in xrange(numInfoRows):
Code.InfoRows.append(infoList[i])
if i != numInfoRows-1:
Code.InfoRows.append(",\n")
else:
Code.InfoRows.append("\n")
Code.InfoRows.append("# undef _CHAR_INFO\n")
Code.InfoRows.append("\n")
Code.InfoRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate offset table.
# ---------------------------------------------------------------------------
numOffsetRows = NUM_CODE_POINTS / OUTPUT_BLOCK_SIZE
if SIZE_OF_OFFSET_ROW == 1:
dataType = "uint8_t"
else:
dataType = "uint16_t"
Code.OffsetDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.OffsetDecl.append(" //! @brief Offset to the property block, see @c getCharProperty().\n")
Code.OffsetDecl.append(" " + dataType + " offset[" + str(numOffsetRows) + "];\n\n")
Code.OffsetDecl.append(" " + AUTOGENERATED_END + "\n")
Code.OffsetRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(len(offsetList)):
Code.OffsetRows.append(" " + str(offsetList[i]))
if i != len(offsetList) - 1:
Code.OffsetRows.append(",")
else:
Code.OffsetRows.append(" ")
Code.OffsetRows.append(" // " + ucd(i * OUTPUT_BLOCK_SIZE) + ".." + ucd((i + 1) * OUTPUT_BLOCK_SIZE - 1))
Code.OffsetRows.append("\n")
Code.OffsetRows.append("\n")
Code.OffsetRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate property table.
# ---------------------------------------------------------------------------
numPropertyRows = len(rowBlockList) * OUTPUT_BLOCK_SIZE
Code.PropertyDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.PropertyDecl.append(" //! @brief Unicode character properties, see @c getCharProperty().\n")
Code.PropertyDecl.append(" CharProperty property[" + str(numPropertyRows) + "];\n\n")
Code.PropertyDecl.append(" " + AUTOGENERATED_END + "\n")
Code.PropertyRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.PropertyRows.append("" + \
"# define _CHAR_PROPERTY(_InfoIndex_, _MappingType_, _MappingData_, _Category_, _Space_, _HasComposition_, _DecompositionType_, _DecompositionIndex_) \\\n" + \
" { \\\n" + \
" ((int32_t)(_InfoIndex_)) | \\\n" + \
" ((int32_t)(CHAR_MAPPING_##_MappingType_) << 12) | \\\n" + \
" ((int32_t)(_MappingData_) << 15), \\\n" + \
" \\\n" + \
" CHAR_CATEGORY_##_Category_, \\\n" + \
" _Space_, \\\n" + \
" _HasComposition_, \\\n" + \
" CHAR_DECOMPOSITION_##_DecompositionType_, \\\n" + \
" _DecompositionIndex_ \\\n" + \
" }\n"
)
Code.PropertyRows.append("\n")
for i in xrange(len(rowBlockList)):
rowBlockData = rowBlockList[i]
# Print Range/Blocks comment (informative)
chars = rowBlockHash[rowBlockData].chars
first = -1
for j in xrange(len(chars)):
code = chars[j]
if first == -1:
first = code
end = code + OUTPUT_BLOCK_SIZE
if j != len(chars) - 1 and chars[j+1] == end:
continue
Code.PropertyRows.append(" // Range : " + ucd(first) + ".." + ucd(end - 1) + "\n")
first = -1
if rowBlockHash[rowBlockData].count > 1:
Code.PropertyRows.append(" // Blocks: " + str(rowBlockHash[rowBlockData].count) + "\n")
Code.PropertyRows.append(rowBlockData)
if i < len(rowBlockList) - 1:
Code.PropertyRows.append(",\n")
else:
Code.PropertyRows.append("\n")
Code.PropertyRows.append("# undef _CHAR_PROPERTY\n")
Code.PropertyRows.append("\n")
Code.PropertyRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate special table.
# ---------------------------------------------------------------------------
numSpecialRows = len(specialList)
Code.SpecialDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.SpecialDecl.append(" //! @brief Unicode special properties.\n")
Code.SpecialDecl.append(" CharSpecial special[" + str(numSpecialRows) + "];\n\n")
Code.SpecialDecl.append(" " + AUTOGENERATED_END + "\n")
Code.SpecialRows.append(" " + AUTOGENERATED_BEGIN + "\n\n")
for i in xrange(len(specialList)):
Code.SpecialRows.append(specialList[i])
if i != len(specialList) - 1:
Code.SpecialRows.append(",")
Code.SpecialRows.append("\n")
Code.SpecialRows.append("\n")
Code.SpecialRows.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate decomposition table.
# ---------------------------------------------------------------------------
Code.DecompositionDecl.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.DecompositionDecl.append(" //! @brief Decomposition data.\n")
Code.DecompositionDecl.append(" uint16_t decomposition[" + str(len(decompositionList)) + "];\n\n")
Code.DecompositionDecl.append(" " + AUTOGENERATED_END + "\n")
Code.DecompositionData.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.DecompositionData.append(" ")
for i in xrange(len(decompositionList)):
Code.DecompositionData.append(uch(decompositionList[i]))
if i != len(decompositionList) - 1:
Code.DecompositionData.append(",")
if (i > 1) and (i % 8 == 7):
Code.DecompositionData.append("\n ")
else:
Code.DecompositionData.append(" ")
Code.DecompositionData.append("\n")
Code.DecompositionData.append("\n")
Code.DecompositionData.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Generate methods
# ---------------------------------------------------------------------------
Code.MethodsInline.append(" " + AUTOGENERATED_BEGIN + "\n\n")
Code.MethodsInline.append(" enum\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" PO_BLOCK_SIZE = " + str(OUTPUT_BLOCK_SIZE) + ",\n")
Code.MethodsInline.append(" PO_OFFSET_SHIFT = " + str(GetOffsetShift(OUTPUT_BLOCK_SIZE)) + ",\n")
Code.MethodsInline.append(" PO_OFFSET_MASK = " + str(GetOffsetMask(OUTPUT_BLOCK_SIZE)) + "\n")
Code.MethodsInline.append(" };\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS2(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return offset[ucs2 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs2 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS2Unsafe(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return offset[ucs2 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs2 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS4(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" // We assign invalid characters to NULL.\n")
Code.MethodsInline.append(" if (ucs4 > UNICODE_MAX)\n")
Code.MethodsInline.append(" ucs4 = 0; \n")
Code.MethodsInline.append("\n")
Code.MethodsInline.append(" return offset[ucs4 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs4 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE uint32_t getPropertyIndexUCS4Unsafe(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" // Caller must ensure that ucs4 is in valid range.\n")
Code.MethodsInline.append(" FOG_ASSERT(ucs4 <= UNICODE_MAX);\n")
Code.MethodsInline.append("\n")
Code.MethodsInline.append(" return offset[ucs4 >> PO_OFFSET_SHIFT] * PO_BLOCK_SIZE + (ucs4 & PO_OFFSET_MASK);\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS2(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS2(ucs2)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS2Unsafe(uint32_t ucs2) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS2Unsafe(ucs2)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS4(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS4(ucs4)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" FOG_INLINE const CharProperty& getPropertyUCS4Unsafe(uint32_t ucs4) const\n")
Code.MethodsInline.append(" {\n")
Code.MethodsInline.append(" return property[getPropertyIndexUCS4Unsafe(ucs4)];\n")
Code.MethodsInline.append(" }\n\n")
Code.MethodsInline.append(" " + AUTOGENERATED_END + "\n")
# ---------------------------------------------------------------------------
# Log
# ---------------------------------------------------------------------------
#log("".join(Code.OffsetRows))
#log("".join(Code.PropertyRows))
#log("".join(Code.SpecialRows))
log(" OFFSET-ROWS : " + str(numOffsetRows) + \
" (" + str(numOffsetRows * SIZE_OF_OFFSET_ROW) + " bytes)")
log(" CHAR-ROWS : " + str(numPropertyRows) + \
" (" + str(len(rowBlockList)) + " blocks, " + str(numPropertyRows * SIZE_OF_PROPERTY_ROW) + " bytes)")
log(" INFO-ROWS : " + str(numInfoRows) + \
" (" + str(numInfoRows * SIZE_OF_INFO_ROW) + " bytes)")
log(" SPECIAL-ROWS : " + str(numSpecialRows) + \
" (" + str(numSpecialRows * SIZE_OF_SPECIAL_ROW) + " bytes)")
log(" DECOMPOSITION : " + str(len(decompositionList)) + \
" (" + str(2 * len(decompositionList)) + " bytes, max length=" + str(maxDecompositionLength - 1) + ")")
log("")
s = " BLOCK LIST : "
for row in rowBlockList:
s += str(rowBlockHash[row].count) + " "
log(s)
def WriteDataToFile(name, m):
log("-- Processing file " + name)
name = "../" + name
file = open(name, 'rb')
data = file.read()
file.close()
for key in m:
log(" - Replacing " + key)
beginMark = "${" + key + ":BEGIN}"
endMark = "${" + key + ":END}"
beginMarkIndex = data.find(beginMark)
endMarkIndex = data.find(endMark)
beginMarkIndex = data.find('\n', beginMarkIndex) + 1
endMarkIndex = data.rfind('\n', 0, endMarkIndex) + 1
assert beginMarkIndex != -1
assert endMarkIndex != -1
assert beginMarkIndex <= endMarkIndex
data = data[:beginMarkIndex] + m[key] + data[endMarkIndex:]
if TEST_ONLY:
log("-- Output file " + name)
log(data)
else:
log("-- Writing file " + name)
file = open(name, 'wb')
file.truncate()
file.write(data)
file.close()
def Write():
WriteDataToFile("Src/Fog/Core/Tools/CharData.h", {
"CHAR_OFFSET_DECL" : "".join(Code.OffsetDecl),
"CHAR_PROPERTY_CLASS" : "".join(Code.PropertyClass),
"CHAR_PROPERTY_DECL" : "".join(Code.PropertyDecl),
"CHAR_INFO_CLASS" : "".join(Code.InfoClass),
"CHAR_INFO_DECL" : "".join(Code.InfoDecl),
"CHAR_SPECIAL_CLASS" : "".join(Code.SpecialClass),
"CHAR_SPECIAL_DECL" : "".join(Code.SpecialDecl),
"CHAR_DECOMPOSITION_DECL" : "".join(Code.DecompositionDecl),
"CHAR_COMPOSITION_DECL" : "".join(Code.CompositionDecl),
"CHAR_METHODS_INLINE" : "".join(Code.MethodsInline),
"CHAR_NORMALIZATION_CORRECTIONS_DECL": "".join(Code.NormalizationCorrectionsDecl),
"CHAR_ISO15924_DECL" : "".join(Code.Iso15924Decl)
})
WriteDataToFile("Src/Fog/Core/Tools/CharData.cpp", {
"CHAR_OFFSET_DATA" : "".join(Code.OffsetRows),
"CHAR_PROPERTY_DATA" : "".join(Code.PropertyRows),
"CHAR_INFO_DATA" : "".join(Code.InfoRows),
"CHAR_SPECIAL_DATA" : "".join(Code.SpecialRows),
"CHAR_DECOMPOSITION_DATA" : "".join(Code.DecompositionData),
"CHAR_COMPOSITION_INDEX" : "".join(Code.CompositionIndex),
"CHAR_COMPOSITION_DATA" : "".join(Code.CompositionData),
"CHAR_NORMALIZATION_CORRECTIONS_DATA": "".join(Code.NormalizationCorrectionsData),
"CHAR_ISO15924_DATA_FROM" : "".join(Code.Iso15924Data_From),
"CHAR_ISO15924_DATA_TO" : "".join(Code.Iso15924Data_To)
})
WriteDataToFile("Src/Fog/Core/Global/EnumCore.h", {
"TEXT_SCRIPT_ENUM" : "".join(Code.TextScriptEnum)
})
# -----------------------------------------------------------------------------
# [UCD-Main]
# -----------------------------------------------------------------------------
def main():
PrepareFiles()
PrepareTables()
ReadPropertyValueAliases()
ReadUnicodeData()
ReadLineBreak()
ReadGraphemeBreak()
ReadSentenceBreak()
ReadWordBreak()
ReadArabicShaping()
ReadBidiMirroring()
ReadCaseFolding()
ReadSpecialCasing()
ReadDerivedAge()
ReadDerivedNormalizationProps()
ReadNormalizationCorrections()
ReadEastAsianWidth()
ReadScripts()
ReadBlocks()
Check()
PrintTitleCase()
GenerateEnums()
GenerateComposition()
GenerateSpecial()
GenerateClasses()
GenerateNormalizationCorrections()
GenerateIso15924Names()
GenerateTable()
Write()
log("-- All done, quitting...")
main()
| Python |
#!/usr/bin/env python
# This script will convert all TABs to SPACEs in the Fog root directory
# and all sub-directories (recursive).
#
# Converted sequences:
# - The \r\n sequence is converted to \n (To UNIX line-ending).
# - The \t (TAB) sequence is converted to TAB_REPLACEMENT which should
# be two spaces.
#
# Affected files:
# - *.cmake
# - *.cpp
# - *.h
import os
TAB_REPLACEMENT = " "
for root, dirs, files in os.walk("../Src"):
for f in files:
path = os.path.join(root, f)
# Remove the stupid "._" files created by MAC.
if (len(f) > 2 and f[0] == u'.' and f[1] == u'_') or file == u".DS_Store":
print "Removing file: " + path
os.remove(path)
continue
if f.lower().endswith(".cpp") or f.lower().endswith(".h") or f.lower().endswith(".cmake") or f.lower().endswith(".txt"):
fh = open(path, "rb")
data = fh.read()
fh.close()
fixed = False
if " \n" in data:
print "Fixing space before \\n in: " + path
while True:
oldl = len(data)
data = data.replace(" \n", "\n")
if oldl == len(data): break;
fixed = True
if "\r" in data:
print "Fixing \\r\\n in: " + path
data = data.replace("\r", "")
fixed = True
if "\t" in data:
print "Fixing TABs in: " + path
data = data.replace("\t", TAB_REPLACEMENT)
fixed = True
if fixed:
fh = open(path, "wb")
fh.truncate()
fh.write(data)
fh.close()
| Python |
#Just a utility I used to rename the files once they've been exported.
import os,json
l = json.load(open(input("list> ")))
os.chdir(input("directory> "))
for f in os.listdir(os.getcwd()):
try:os.rename(f,l[int(f[:f.rfind('.')].lower())-1])
except:continue | Python |
# > Logic only. Program this as if it were multiplayer.
# That's why we don't need to import OS or JSON
# Because we won't be loading any of our own data,
# Right?
import math
def get_nature_multiplier(nature,stat):
if stat==nature['dec']:return 0.9
elif stat==nature['inc']:return 1.1
else:return 1
def calculate_stat(pokemon,species,nature,stat_name):
stat_name=stat_name.lower()
#I haven't dumped the ev values yet, I don't think.
#ret=pokemon['iv'][stat_name]+(2*species['stats'][stat_name])+(species['ev'][stat_name]/4)
#use v- this -v for the time being, instead. ( it's a minimal effect anyways. )
ret=pokemon['iv'][stat_name]+(2*species['stats'][stat_name])
if stat_name=='hp':ret=floor((ret+100)*pokemon['level']/100)+10
else:ret=floor(((ret*pokemon['level']/100)+5)*get_nature_multiplier(nature,stat_name))
return ret
class StatSet:
def __init__(self,p,s,n):
self.vals=dict([(stat_name,{'val':calculate_stat(p,s,n,stat_name),'level':1}) for stat_name in s['stats'].keys()])
def adjust_level(self,s,l):
if l in [a for a in self.levels.keys()]:self.vals[s]['level']+=l
def __getitem__(self,stat):return floor(self.vals[stat]['val']*self.levels[self.vals[stat]['level']])
class TurnDelegate: #This is more accurate, I believe. Battle should be a task, should it not?
def __init__(self):
self.trainers = []
self.teams = {}
def join(self, trainer, tname):
assert self.complies_with_rules(trainer)
assert trainer not in self.trainers # No double-joining
self.trainers.append(trainer)
self.teams[trainer] = tname
def turn_of(self):
return self.trainers[0]
def rotate(self):
self.trainers.append(self.trainers.pop(0))
def complies_with_rules(self, trainer):
return True
def flee(self, stack):
raise NotImplementedError()
| Python |
from bottle import route, run, request,template,static_file,response
from data import *
from os import getcwd,path
import json
DATA_TYPES=['species','moves','abilities','info','trainers','saves']
data=dict([(type,load_data(type)) for type in DATA_TYPES])
data['data-types']=data#Lol. YAY RECURSION?
def ret_dict(a,b,c=False):return json.dumps(a[b.lower if c else b] if b else [i for i in a.keys()])
def is_ajax(a):return a.headers.get('X-Requested-With')=='XMLHttpRequest'
@route('/js/<filename>')
def get_js(filename):return static_file(filename,root=path.join(getcwd(),'js'),mimetype='application/javascript')
@route('/css/<filename>')
def get_css(filename):return static_file(filename,root=path.join(getcwd(),'css'))
@route('/')
@route('/data/<a_type>')
@route('/data/<a_type>/<a_id>')
def index(a_type=None,a_id=None):
if is_ajax(request):
response.set_header('Content-Type','text/json')
return ret_dict(data[a_type],a_id)
else:return template('index',type=a_type,id=a_id)
if __name__=="__main__":run(host='localhost',port=8080,debug=True,reloader=True) | Python |
#!/usr/bin/python3
import os,sys
from inspect import getmembers
def class_list(t,m=None):
m=m or sys.modules[__name__]
for name,obj in getmembers(m,inspect.isclass):
if issubclass(obj,t) and obj is not t:yield obj
def dir_name(a=None):
if not a:a=os.getcwd()
return a[a.rfind(os.path.sep)+1:]
def list_files(d,k=False):
for fn in os.listdir(d):
if fn[-1]=='~':continue
if k:yield (os.path.join(d,fn),fn[:fn.rfind('.')])
else:yield os.path.join(d,fn)
def load_dict(d,cb,*ar,open_mode='r',**kw):
return dict([(k,cb(open(fn,open_mode),*ar,**kw)) for fn,k in list_files(d,True)])
| Python |
from engine import Engine,Task,ThreadedTask,Runner
import pygame,textwrap
def combine(a,b,c):return [c(a[i],b[i]) for i in range(0,len(a))]
def trykey(a,b,c):
try:return a[b]
except KeyError:return c
def sidechain(f,o,*args,**kwargs):
f(o,*args,**kwargs)
return o
def transparent(surf, colorkey=[0,0]):
surf.set_alpha(None)
surf.set_colorkey(surf.get_at(colorkey)[:3] if len(colorkey)== 2 else colorkey[:3])
def flatten(l):return [item for sublist in l for item in sublist]
load_trans_image = lambda fileobj: sidechain(transparent,pygame.image.load(fileobj))
load_font = lambda fileobj: Font(pygame.image.load(fileobj))
class Font:
def __init__(self, surf,**kw): # rename src to surf
w,h=trykey(kw,'wide',16),trykey(kw,'high',16)
assert w*h==256
self.src = sidechain( transparent, surf)
self.char_width = self.src.get_width()//w
self.char_height = self.src.get_height()//h
# Ensure a consistent char-width/height.
assert surf.get_width()%self.char_width==0 and surf.get_height()%self.char_height==0
def trim_width(self,w):return w-(w%self.char_width)
def render_lines(self,width,*lines):
assert width%self.char_width==0
width//=self.char_width
def render_section(line):
def render_surface(text):
pos=[0,0]
s=pygame.Surface((len(text)*self.char_width,self.char_height))
s.fill((255,0,255))
for c in text:
num_code=ord(c)
src_pos=[0,0,1,1]
src_pos[0]=num_code%16
src_pos[1]=(num_code-src_pos[0])//16
src_pos=[src_pos[0]*self.char_width,src_pos[1]*self.char_height]
src_pos+=[self.char_width,self.char_height]
s.blit(self.src,pos,src_pos)
pos[0]+=self.char_width
return sidechain(transparent,s,(255,0,255))
return [render_surface(l) for l in textwrap.wrap(line,width)]
lines=flatten([line.split('\n') for line in lines])
return flatten([render_section(section) for section in lines])
def render(self, width, text):
assert width%self.char_width == 0
rows=self.render_lines(width,*text.split('\n'))
ret = pygame.Surface((width*self.char_width, len(rows)*self.char_height))
ret.fill((255,0,255))
pos = [0,0]
for row in rows:
ret.blit(row,pos)
pos[1] += row.get_height()
return sidechain(transparent,ret,(255,0,255))
class AnimatedMap:
def __init__(self,rate,m,accelerate_rate=1):
self.steps,self.pos=m,0
self.timer=Period(rate)
self.accelerate,self.accelerate_rate=False,accelerate_rate
def reset(self):self.pos=0
@property
def complete(self):return self.pos>=len(self.steps)
@property
def value(self):
if self.timer.elapsed:
self.pos+=self.accelerate_rate if self.accelerate else 1
self.accelerate=False
return self.steps[-1] if self.complete else self.steps[self.pos]
def AnimationFromGenerator(rate,r):
return AnimatedMap(rate,[frame for frame in r])
class Period:
def __init__(self,rate,start=False):
self.timer=pygame.time.Clock()
self._elapsed_,self.rate=rate if start else 0,rate
def reset(self):
self._elapsed_=0
self.timer.tick()
def elapse(self):
self._elapsed_=self.rate
self.timer.tick()
@property
def elapsed(self):
self._elapsed_+=self.timer.tick()
if self._elapsed_>=self.rate:
self._elapsed_=0
return True
return False
class FrameLimiter:
def __init__(self,rate):
self.clock=pygame.time.Clock()
self.rate=rate
def __call__(self):return self.clock.tick(self.rate)
class SDLEngine(Engine):
def __init__(self,name=None,resolution=(640,480),frame_rate=30):
Engine.__init__(self)
self.resolution,self.surf=resolution,None
self.name=name or type(self).__name__
self.connect_signal('frame',pygame.display.flip,FrameLimiter(frame_rate),self.broadcast_events)
self.connect_signal('start',self.prepare_screen)
self.connect_signal(pygame.QUIT,self.quit_event)
self.connect_signal('stop',pygame.quit)
def quit_event(self,event):self.stop()
def prepare_screen(self):
pygame.display.init()
self.surf=pygame.display.set_mode(self.resolution)
pygame.display.set_caption(self.name)
def broadcast_events(self):
for event in pygame.event.get():
self.process_signal(event.type,event)
for task in self.tasks[:]:
task.process_signal(event.type,event)
if __name__=="__main__":
class PaintScreen(Task):
def __init__(self,engine):
Task.__init__(self,engine)
self.connect_signal('frame',self.paint)
self.color_timer=Period(10)
self._color_=[0]*3
@property
def color(self):
if self.color_timer.elapsed:
def wrap(n,m):return n if n<=m else 0
self._color_=[wrap(self._color_[0]+1,255)]*3
return self._color_
def set_delegates(self):self.delegates=[self.paint]
def paint(self):self.engine.surf.fill(self.color)
class SDLDemo(SDLEngine):
def __init__(self):
SDLEngine.__init__(self)
self.connect_signal('start',PaintScreen(self).start)
Runner(SDLDemo())() | Python |
#!/usr/bin/python3
import os,sys
from inspect import getmembers
def class_list(t,m=None):
m=m or sys.modules[__name__]
for name,obj in getmembers(m,inspect.isclass):
if issubclass(obj,t) and obj is not t:yield obj
def dir_name(a=None):
if not a:a=os.getcwd()
return a[a.rfind(os.path.sep)+1:]
def list_files(d,k=False):
for fn in os.listdir(d):
if fn[-1]=='~':continue
if k:yield (os.path.join(d,fn),fn[:fn.rfind('.')])
else:yield os.path.join(d,fn)
def load_dict(d,cb,*ar,open_mode='r',**kw):
return dict([(k,cb(open(fn,open_mode),*ar,**kw)) for fn,k in list_files(d,True)])
| Python |
#!/usr/bin/python3.2
# coding: utf-8
from __future__ import division, print_function, unicode_literals
import pygame
import json
from engine import *
from data import *
import tile_rpg
def mix(a,b,c):return [c(a[i],b[i]) for i in range(0,len(a))]
def max(a,b):return a if a>b else b
def min(a,b):return a if a<b else b
def or_none_key(a,k):
if k in a.keys():return a[k]
return None
def surf_slice(s,r):
ret=pygame.Surface(r[2:])
ret.blit(s,[0]*2,r)
return ret
class RosterView(Task):
padding=5
seperation=10
c=pygame.time.Clock()
input_fr=100
animate_fr=100
animation_duration=750
def __init__(self,game,trainer_card):
Task.__init__(self,game)
self.stats={}
for status in ['normal','none','paralyzed','poison','burn']:
self.stats[status]=sidechain(transparent,game.graphics[key_from_path('ball_stats',status)].copy())
self.card=trainer_card
self.party=[trainer_card['storage'][id] for id in trainer_card['roster']]
self.bg=game.pictures['rosterviewbg'].copy()
self.cursor_gfx=game.pictures['ball_cursor']
l=[p for p in self.party]+[None]*(6-len(self.party))
self.items=[self.make_item(pkmn) for pkmn in l]
self.threads=[self.paint_bg,self.move,self.paint_items]
self.cursor=0
self.time_elapsed=0
self.item_opacity=0
self.alpha_step=int(self.animate_fr/self.animation_duration*255)
def paint_bg(self):
ball_position=[20,270]
self.game.surf.blit(self.bg,(0,0))
pk_list=[pk for pk in self.party]+([None]*(6-len(self.party)))
status_list=[(or_none_key(pkmn,'status') or 'normal') if pkmn else 'none' for pkmn in pk_list]
for i,status in enumerate(status_list):
if i==self.cursor:
self.game.surf.blit(self.cursor_gfx,mix(ball_position,(12,12),lambda a,b:a-b))
self.game.surf.blit(self.stats[status],ball_position)
ball_position[0]+=48
def paint_items(self):
default=[20,20]
position=default[:]
surf_list=[item['inactive'] for item in self.items[:self.cursor]]
surf_list=surf_list+[self.items[self.cursor]['active']]
surf_list=surf_list+[item['inactive'] for item in self.items[self.cursor+1:]]
h_limit=default[1]
h_limit+=3*(surf_list[0].get_height()+self.padding)
for surf in surf_list:
self.game.surf.blit(surf,position)
position[1]+=surf.get_height()+self.padding
if position[1]+surf.get_height() > h_limit:
position[1]=default[1]
position[0]+=self.seperation+surf.get_width()
def move(self):
upper_bound=len(self.party)
self.time_elapsed+=self.c.tick()
if self.time_elapsed>=self.input_fr:
for k,v in {pygame.K_UP:-1,pygame.K_DOWN:1}.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.time_elapsed=0
if pygame.K_RETURN in self.game.just_pressed:
self.threads=[self.paint_bg,self.scroll,self.paint_summary]
elif pygame.K_BACKSPACE in self.game.just_pressed:
self.terminate()
def scroll(self):
upper_bound=len(self.party)
self.time_elapsed+=self.c.tick()
if self.time_elapsed>=self.input_fr:
for k,v in {pygame.K_LEFT:-1,pygame.K_RIGHT:1}.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.time_elapsed=0
if pygame.K_BACKSPACE in self.game.just_pressed:
self.threads=[self.paint_bg,self.move,self.paint_items]
def paint_summary(self):
sprite_dimensions=[96,96]
padding=[2,4]
pos=[20,40]
col=(255,0,0)
r=pos+mix(mix(padding,[2,2],lambda a,b:a*b),sprite_dimensions,lambda a,b:a+b)
self.game.surf.fill(col,r)
r=mix(pos,padding,lambda a,b:a+b)
pos=[96,0]+sprite_dimensions
self.game.surf.blit(self.game.sprites[key_from_path('pokemon',self.party[self.cursor]['species'])],r,pos)
def make_item(self,data):
r={}
r['active']=self.game.pictures['rosterviewhl'].copy()
r['inactive']=self.game.pictures['rosterviewpk'].copy()
if data:
ICON_POS=(5,10)
TEXT_POS=(40,5)
r['icon']=self.game.sprites[key_from_path('pokemon','icons',data['species'])].copy()
r['sprite']=sidechain(transparent,self.game.sprites[key_from_path('pokemon',data['species'])].copy())
language='English'
text=data['name'] or self.game.pkdx[data['species']]['name'][language]
w=r['inactive'].get_width()-TEXT_POS[0]
w-=w%16
r['text']=self.game.fonts[self.game.font_table['main']].render(w,text)
r['active'].blit(r['icon'],ICON_POS)
r['inactive'].blit(r['icon'],ICON_POS)
r['active'].blit(r['text'],TEXT_POS)
r['inactive'].blit(r['text'],TEXT_POS)
for surf in [r[k] for k in ['active','inactive']]:transparent(surf)
return r
class PokedexView(Task):
def __init__(self,game,card):
Task.__init__(self,game)
self.species,self.card=[],card
pkdx=card['pokedex']
l=[k for k in card['pokedex'].keys()]
for id,species in game.pkdx.items():
self.species.append({'type':pkdx[id]if id in l else -1,'id':id,'info':species})
self.threads=[self.once]
def once(self):
for species in self.species:
if species['type']==-1:print("???")
elif species['type']==0:print("Seen:",species['info']['name'][self.card['language']])
elif species['type']==1:print("Caught:",species['info']['name'][self.card['language']])
self.terminate()
class OverworldMenu(Task):
width=195
border_width=5
bg_color=(40,50,100,180)
border_color=(240,245,255)
icon_size=[32,32]
icon_rotate_r=(-30.0,30.0)
icon_rotate_i=0.0
rot_dir=2.0
ir_rate=10
ir_elapse=0
irt=pygame.time.Clock()
item_padding=16
adjust_cursor=(32,0)
items=[
'pkdx',
'roster',
'bag',
'card',
'settings',
'cancel'
]
key_mappings={
pygame.K_UP:-1,
pygame.K_DOWN:1
}
ct=pygame.time.Clock()
cfr=150
ct_elapse=0
def __init__(self,game,save):
Task.__init__(self,game)
height=game.surf.get_height()
self.save=save
self.open=False
self.icon_rotated=self.icon_rotate_i
self.cursor=0
item_values={
'pkdx':'Pokedex',
'roster':'Roster',
'bag':'Bag',
'card':save['card']['name'],
'settings':'Options',
'cancel':'Cancel'
}
for i in range(0,len(self.items)):
text=self.items[i][:]
self.items[i]={
'text':text,
'surf':game.fonts[game.font_table['menu']].render(self.width-(self.width%16),item_values[text])
}
self.bg=pygame.Surface((self.width+self.border_width,height),flags=pygame.SRCALPHA)
self.bg.fill(self.bg_color,(self.border_width,0,self.width,height))
pygame.draw.rect(self.bg,self.border_color,(0,0,self.border_width,height))
self.pos=(game.surf.get_width()-self.width-self.border_width,0)
self.threads=[self.paint_bg,self.paint_items,self.close_ctl,self.cur_ctl,self.sel_ctl]
aicon_src=[self.icon_size[0],0]
iicon_src=[0,0]
if self.save['card']['gender']=='f':
aicon_src[0]+=self.icon_size[0]
iicon_src[0]+=self.icon_size[0]
self.aicon_src,self.iicon_src=aicon_src,iicon_src
def paint_bg(self):self.game.surf.blit(self.bg,self.pos,None,pygame.BLEND_RGBA_ADD)
def hide_menu(self):
self.open=False
self.threads=[self.paint_bg,self.paint_items,self.close_ctl,self.cur_ctl,self.sel_ctl]
def close_ctl(self):
if pygame.K_BACKSPACE in self.game.just_pressed:self.hide_menu()
def cur_ctl(self):
self.ct_elapse+=self.ct.tick()
upper_bound=len(self.items)
if self.ct_elapse>=self.cfr:
for k,v in self.key_mappings.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.ct_elapse=0
self.icon_rotated=self.icon_rotate_i
def paint_items(self):
pos=[self.game.surf.get_width()-self.width+self.border_width,0]
self.ir_elapse+=self.irt.tick()
if self.ir_elapse>=self.ir_rate:
self.ir_elapse=0
self.icon_rotated+=self.rot_dir
if self.icon_rotated>=self.icon_rotate_r[1] or self.icon_rotated<=self.icon_rotate_r[0]:self.rot_dir*=-1
for surf,text in [(a['surf'],a['text']) for a in self.items]:
active=surf is self.items[self.cursor]['surf']
i_src=(self.aicon_src if active else self.iicon_src)+self.icon_size
icon=surf_slice(self.game.sprites[key_from_path('menu',text)],i_src)
transparent(icon)
if active:icon=pygame.transform.rotate(icon,self.icon_rotated)
transparent(icon)
pos[1]+=self.item_padding
sh,ih=surf.get_height(),self.icon_size[1]
h=max(sh,ih)
if ih>=sh:
t_pos=mix(pos,(icon.get_width(),int((ih-sh)/2)),lambda a,b:a+b)
self.game.surf.blit(icon,pos)
self.game.surf.blit(surf,t_pos)
else:
t_pos=mix(pos,(icon.get_width(),0),lambda a,b:a+b)
i_pos=mix(pos,(0,0),lambda a,b:a+b)
self.game.surf.blit(icon,pos)
self.game.surf.blit(surf,t_pos)
pos[1]+=h
def sel_ctl(self):
if pygame.K_RETURN in self.game.just_pressed:
v=self.items[self.cursor]['text'].lower()
if v=='cancel':
self.hide_menu()
elif v=='roster':
self.game.register_task(Callback(self,RosterView(self.game,self.save['card'])))
elif v=='pkdx':
self.game.register_task(Callback(self,PokedexView(self.game,self.save['card'])))
class Overworld(Task):
def __init__(self,game,save):
Task.__init__(self,game)
self.threads=[self.paint_bg,self.open_menu]
self.player_data=save
self.menu=OverworldMenu(game,save)
def open_menu(self):
if self.menu.open:self.menu()
else: self.menu.open=pygame.K_RETURN in self.game.just_pressed
def paint_bg(self):self.game.surf.fill([self.frame%256]*3)
class Intro(Task):
def __init__(self, game):
Task.__init__(self, game)
self.bg = game.pictures["titlescreen"]
self.b_bg = self.bg.convert_alpha()
self.f_bg = self.bg.convert_alpha()
self.threads = [self.paint, self.check_keys]
self.menu = tile_rpg.Menu(game, 80, [(save['card']['name'],save) for save in game.saves.values()]+[("Cancel",None)])
def paint(self):self.game.surf.blit(self.bg, (0, 0))
def check_keys(self):
if pygame.K_RETURN in self.game.just_pressed:
self.menu.reset()
self.threads = [ self.paint, self.menu, self.load_games]
self.game.just_pressed = []
def load_games(self):
if not self.menu.open:
if self.menu.value is not None:
ow=Overworld(self.game, self.menu.value)
self.game.register_task(FadeOut(self.game,25,ow,5,(255,255,255)))
self.terminate()
else:
self.menu.open = False
self.threads = [ self.paint, self.check_keys]
class PyPokemon(Game):
maps = Cache("maps", json.load)
tilesets = Cache("tilesets",load_trans_image,['r+b'])
sprites = Cache("sprites", load_trans_image,['r+b'])
pkdx = load_data('species', json.load)
saves = load_data('saves', json.load)
info = load_data("info", json.load)
graphics = Cache("graphics",load_trans_image,['r+b'])
pictures = Cache("images", pygame.image.load,['r+b'])
fonts = load_data("fonts", load_font,'r+b')
tileset_data = Cache("tilesets data",json.load)
npc_types=Cache("trainers")
res,center=(480,320),(480/16/2,320/16/2)
def __init__(self):
Game.__init__(self, self.res)
self.font_table = { 'main':'rainhearts', 'menu':'fontwestern'}
self.register_task(Intro(self))
if __name__ == "__main__": run(PyPokemon())
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies other than the
Python Standard Library.
Homepage and documentation: http://bottlepy.org/
Copyright (c) 2011, Marcel Hellkamp.
License: MIT (see LICENSE for details)
"""
from __future__ import with_statement
__author__ = 'Marcel Hellkamp'
__version__ = '0.11.dev'
__license__ = 'MIT'
# The gevent server adapter needs to patch some modules before they are imported
# This is why we parse the commandline parameters here but handle them later
if __name__ == '__main__':
from optparse import OptionParser
_cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app")
_opt = _cmd_parser.add_option
_opt("--version", action="store_true", help="show version number.")
_opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
_opt("-s", "--server", default='wsgiref', help="use SERVER as backend.")
_opt("-p", "--plugin", action="append", help="install additional plugin/s.")
_opt("--debug", action="store_true", help="start server in debug mode.")
_opt("--reload", action="store_true", help="auto-reload on file changes.")
_cmd_options, _cmd_args = _cmd_parser.parse_args()
if _cmd_options.server and _cmd_options.server.startswith('gevent'):
import gevent.monkey; gevent.monkey.patch_all()
import base64, cgi, email.utils, functools, hmac, imp, itertools, mimetypes,\
os, re, subprocess, sys, tempfile, threading, time, urllib, warnings
from datetime import date as datedate, datetime, timedelta
from tempfile import TemporaryFile
from traceback import format_exc, print_exc
try: from json import dumps as json_dumps, loads as json_lds
except ImportError: # pragma: no cover
try: from simplejson import dumps as json_dumps, loads as json_lds
except ImportError:
try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds
except ImportError:
def json_dumps(data):
raise ImportError("JSON support requires Python 2.6 or simplejson.")
json_lds = json_dumps
# We now try to fix 2.5/2.6/3.1/3.2 incompatibilities.
# It ain't pretty but it works... Sorry for the mess.
py = sys.version_info
py3k = py >= (3,0,0)
py25 = py < (2,6,0)
# Workaround for the missing "as" keyword in py3k.
def _e(): return sys.exc_info()[1]
# Workaround for the "print is a keyword/function" dilemma.
_stdout, _stderr = sys.stdout.write, sys.stderr.write
# Lots of stdlib and builtin differences.
if py3k:
import http.client as httplib
import _thread as thread
from urllib.parse import urljoin, parse_qsl, SplitResult as UrlSplitResult
from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
from http.cookies import SimpleCookie
from collections import MutableMapping as DictMixin
import pickle
from io import BytesIO
basestring = str
unicode = str
json_loads = lambda s: json_lds(touni(s))
callable = lambda x: hasattr(x, '__call__')
imap = map
else: # 2.x
import httplib
import thread
from urlparse import urljoin, SplitResult as UrlSplitResult
from urllib import urlencode, quote as urlquote, unquote as urlunquote
from Cookie import SimpleCookie
from itertools import imap
import cPickle as pickle
from StringIO import StringIO as BytesIO
if py25:
msg = "Python 2.5 support may be dropped in future versions of Bottle."
warnings.warn(msg, DeprecationWarning)
from cgi import parse_qsl
from UserDict import DictMixin
def next(it): return it.next()
bytes = str
else: # 2.6, 2.7
from urlparse import parse_qsl
from collections import MutableMapping as DictMixin
json_loads = json_lds
# Some helpers for string/byte handling
def tob(s, enc='utf8'):
return s.encode(enc) if isinstance(s, unicode) else bytes(s)
def touni(s, enc='utf8', err='strict'):
return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
tonat = touni if py3k else tob
# 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense).
# 3.1 needs a workaround.
NCTextIOWrapper = None
if (3,0,0) < py < (3,2,0):
from io import TextIOWrapper
class NCTextIOWrapper(TextIOWrapper):
def close(self): pass # Keep wrapped buffer open.
# A bug in functools causes it to break if the wrapper is an instance method
def update_wrapper(wrapper, wrapped, *a, **ka):
try: functools.update_wrapper(wrapper, wrapped, *a, **ka)
except AttributeError: pass
# These helpers are used at module level and need to be defined first.
# And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
def depr(message):
warnings.warn(message, DeprecationWarning, stacklevel=3)
def makelist(data): # This is just to handy
if isinstance(data, (tuple, list, set, dict)): return list(data)
elif data: return [data]
else: return []
class DictProperty(object):
''' Property that maps to a key in a local dict-like attribute. '''
def __init__(self, attr, key=None, read_only=False):
self.attr, self.key, self.read_only = attr, key, read_only
def __call__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter, self.key = func, self.key or func.__name__
return self
def __get__(self, obj, cls):
if obj is None: return self
key, storage = self.key, getattr(obj, self.attr)
if key not in storage: storage[key] = self.getter(obj)
return storage[key]
def __set__(self, obj, value):
if self.read_only: raise AttributeError("Read-Only property.")
getattr(obj, self.attr)[self.key] = value
def __delete__(self, obj):
if self.read_only: raise AttributeError("Read-Only property.")
del getattr(obj, self.attr)[self.key]
class cached_property(object):
''' A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property. '''
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
if obj is None: return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
class lazy_attribute(object):
''' A property that caches itself to the class object. '''
def __init__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter = func
def __get__(self, obj, cls):
value = self.getter(cls)
setattr(cls, self.__name__, value)
return value
###############################################################################
# Exceptions and Events ########################################################
###############################################################################
class BottleException(Exception):
""" A base class for exceptions used by bottle. """
pass
#TODO: This should subclass BaseRequest
class HTTPResponse(BottleException):
""" Used to break execution and immediately finish the response """
def __init__(self, output='', status=200, header=None):
super(BottleException, self).__init__("HTTP Response %d" % status)
self.status = int(status)
self.output = output
self.headers = HeaderDict(header) if header else None
def apply(self, response):
if self.headers:
for key, value in self.headers.allitems():
response.headers[key] = value
response.status = self.status
class HTTPError(HTTPResponse):
""" Used to generate an error page """
def __init__(self, code=500, output='Unknown Error', exception=None,
traceback=None, header=None):
super(HTTPError, self).__init__(output, code, header)
self.exception = exception
self.traceback = traceback
def __repr__(self):
return tonat(template(ERROR_PAGE_TEMPLATE, e=self))
###############################################################################
# Routing ######################################################################
###############################################################################
class RouteError(BottleException):
""" This is a base class for all routing related exceptions """
class RouteReset(BottleException):
""" If raised by a plugin or request handler, the route is reset and all
plugins are re-applied. """
class RouterUnknownModeError(RouteError): pass
class RouteSyntaxError(RouteError):
""" The route parser found something not supported by this router """
class RouteBuildError(RouteError):
""" The route could not been built """
class Router(object):
''' A Router is an ordered collection of route->target pairs. It is used to
efficiently match WSGI requests against a number of routes and return
the first target that satisfies the request. The target may be anything,
usually a string, ID or callable object. A route consists of a path-rule
and a HTTP method.
The path-rule is either a static path (e.g. `/contact`) or a dynamic
path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
and details on the matching order are described in docs:`routing`.
'''
default_pattern = '[^/]+'
default_filter = 're'
#: Sorry for the mess. It works. Trust me.
rule_syntax = re.compile('(\\\\*)'\
'(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'\
'|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'\
'(?::((?:\\\\.|[^\\\\>]+)+)?)?)?>))')
def __init__(self, strict=False):
self.rules = {} # A {rule: Rule} mapping
self.builder = {} # A rule/name->build_info mapping
self.static = {} # Cache for static routes: {path: {method: target}}
self.dynamic = [] # Cache for dynamic routes. See _compile()
#: If true, static routes are no longer checked first.
self.strict_order = strict
self.filters = {'re': self.re_filter, 'int': self.int_filter,
'float': self.float_filter, 'path': self.path_filter}
def re_filter(self, conf):
return conf or self.default_pattern, None, None
def int_filter(self, conf):
return r'-?\d+', int, lambda x: str(int(x))
def float_filter(self, conf):
return r'-?[\d.]+', float, lambda x: str(float(x))
def path_filter(self, conf):
return r'.+?', None, None
def add_filter(self, name, func):
''' Add a filter. The provided function is called with the configuration
string as parameter and must return a (regexp, to_python, to_url) tuple.
The first element is a string, the last two are callables or None. '''
self.filters[name] = func
def parse_rule(self, rule):
''' Parses a rule into a (name, filter, conf) token stream. If mode is
None, name contains a static rule part. '''
offset, prefix = 0, ''
for match in self.rule_syntax.finditer(rule):
prefix += rule[offset:match.start()]
g = match.groups()
if len(g[0])%2: # Escaped wildcard
prefix += match.group(0)[len(g[0]):]
offset = match.end()
continue
if prefix: yield prefix, None, None
name, filtr, conf = g[1:4] if not g[2] is None else g[4:7]
if not filtr: filtr = self.default_filter
yield name, filtr, conf or None
offset, prefix = match.end(), ''
if offset <= len(rule) or prefix:
yield prefix+rule[offset:], None, None
def add(self, rule, method, target, name=None):
''' Add a new route or replace the target for an existing route. '''
if rule in self.rules:
self.rules[rule][method] = target
if name: self.builder[name] = self.builder[rule]
return
target = self.rules[rule] = {method: target}
# Build pattern and other structures for dynamic routes
anons = 0 # Number of anonymous wildcards
pattern = '' # Regular expression pattern
filters = [] # Lists of wildcard input filters
builder = [] # Data structure for the URL builder
is_static = True
for key, mode, conf in self.parse_rule(rule):
if mode:
is_static = False
mask, in_filter, out_filter = self.filters[mode](conf)
if key:
pattern += '(?P<%s>%s)' % (key, mask)
else:
pattern += '(?:%s)' % mask
key = 'anon%d' % anons; anons += 1
if in_filter: filters.append((key, in_filter))
builder.append((key, out_filter or str))
elif key:
pattern += re.escape(key)
builder.append((None, key))
self.builder[rule] = builder
if name: self.builder[name] = builder
if is_static and not self.strict_order:
self.static[self.build(rule)] = target
return
def fpat_sub(m):
return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern)
try:
re_match = re.compile('^(%s)$' % pattern).match
except re.error:
raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e()))
def match(path):
""" Return an url-argument dictionary. """
url_args = re_match(path).groupdict()
for name, wildcard_filter in filters:
try:
url_args[name] = wildcard_filter(url_args[name])
except ValueError:
raise HTTPError(400, 'Path has wrong format.')
return url_args
try:
combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern)
self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
self.dynamic[-1][1].append((match, target))
except (AssertionError, IndexError): # AssertionError: Too many groups
self.dynamic.append((re.compile('(^%s$)' % flat_pattern),
[(match, target)]))
return match
def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except KeyError:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0])
def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
path, targets, urlargs = environ['PATH_INFO'] or '/', None, {}
if path in self.static:
targets = self.static[path]
else:
for combined, rules in self.dynamic:
match = combined.match(path)
if not match: continue
getargs, targets = rules[match.lastindex - 1]
urlargs = getargs(path) if getargs else {}
break
if not targets:
raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO']))
method = environ['REQUEST_METHOD'].upper()
if method in targets:
return targets[method], urlargs
if method == 'HEAD' and 'GET' in targets:
return targets['GET'], urlargs
if 'ANY' in targets:
return targets['ANY'], urlargs
allowed = [verb for verb in targets if verb != 'ANY']
if 'GET' in allowed and 'HEAD' not in allowed:
allowed.append('HEAD')
raise HTTPError(405, "Method not allowed.",
header=[('Allow',",".join(allowed))])
class Route(object):
''' This class wraps a route callback along with route specific metadata and
configuration and applies Plugins on demand. It is also responsible for
turing an URL path rule into a regular expression usable by the Router.
'''
def __init__(self, app, rule, method, callback, name=None,
plugins=None, skiplist=None, **config):
#: The application this route is installed to.
self.app = app
#: The path-rule string (e.g. ``/wiki/:page``).
self.rule = rule
#: The HTTP method as a string (e.g. ``GET``).
self.method = method
#: The original callback with no plugins applied. Useful for introspection.
self.callback = callback
#: The name of the route (if specified) or ``None``.
self.name = name or None
#: A list of route-specific plugins (see :meth:`Bottle.route`).
self.plugins = plugins or []
#: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
self.skiplist = skiplist or []
#: Additional keyword arguments passed to the :meth:`Bottle.route`
#: decorator are stored in this dictionary. Used for route-specific
#: plugin configuration and meta-data.
self.config = ConfigDict(config)
def __call__(self, *a, **ka):
depr("Some APIs changed to return Route() instances instead of"\
" callables. Make sure to use the Route.call method and not to"\
" call Route instances directly.")
return self.call(*a, **ka)
@cached_property
def call(self):
''' The route callback with all plugins applied. This property is
created on demand and then cached to speed up subsequent requests.'''
return self._make_callback()
def reset(self):
''' Forget any cached values. The next time :attr:`call` is accessed,
all plugins are re-applied. '''
self.__dict__.pop('call', None)
def prepare(self):
''' Do all on-demand work immediately (useful for debugging).'''
self.call
@property
def _context(self):
depr('Switch to Plugin API v2 and access the Route object directly.')
return dict(rule=self.rule, method=self.method, callback=self.callback,
name=self.name, app=self.app, config=self.config,
apply=self.plugins, skip=self.skiplist)
def all_plugins(self):
''' Yield all Plugins affecting this route. '''
unique = set()
for p in reversed(self.app.plugins + self.plugins):
if True in self.skiplist: break
name = getattr(p, 'name', False)
if name and (name in self.skiplist or name in unique): continue
if p in self.skiplist or type(p) in self.skiplist: continue
if name: unique.add(name)
yield p
def _make_callback(self):
callback = self.callback
for plugin in self.all_plugins():
try:
if hasattr(plugin, 'apply'):
api = getattr(plugin, 'api', 1)
context = self if api > 1 else self._context
callback = plugin.apply(callback, context)
else:
callback = plugin(callback)
except RouteReset: # Try again with changed configuration.
return self._make_callback()
if not callback is self.callback:
update_wrapper(callback, self.callback)
return callback
def __repr__(self):
return '<%s %r %r>' % (self.method, self.rule, self.callback)
###############################################################################
# Application Object ###########################################################
###############################################################################
class Bottle(object):
""" Each Bottle object represents a single, distinct web application and
consists of routes, callbacks, plugins and configuration. Instances are
callable WSGI applications. """
def __init__(self, catchall=True, autojson=True, config=None):
self.routes = [] # List of installed :class:`Route` instances.
self.router = Router() # Maps requests to :class:`Route` instances.
self.plugins = [] # List of installed plugins.
self.error_handler = {}
self.config = ConfigDict(config or {})
#: If true, most exceptions are catched and returned as :exc:`HTTPError`
self.catchall = catchall
#: An instance of :class:`HooksPlugin`. Empty by default.
self.hooks = HooksPlugin()
self.install(self.hooks)
if autojson:
self.install(JSONPlugin())
self.install(TemplatePlugin())
def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :class:`Bottle` or a WSGI application.
All other parameters are passed to the underlying :meth:`route` call.
'''
if isinstance(app, basestring):
prefix, app = app, prefix
depr('Parameter order of Bottle.mount() changed.') # 0.10
parts = [p for p in prefix.split('/') if p]
if not parts: raise ValueError('Empty path prefix.')
path_depth = len(parts)
options.setdefault('skip', True)
options.setdefault('method', 'ANY')
@self.route('/%s/:#.*#' % '/'.join(parts), **options)
def mountpoint():
try:
request.path_shift(path_depth)
rs = BaseResponse([], 200)
def start_response(status, header):
rs.status = status
for name, value in header: rs.add_header(name, value)
return rs.body.append
rs.body = itertools.chain(rs.body, app(request.environ, start_response))
return HTTPResponse(rs.body, rs.status_code, rs.headers)
finally:
request.path_shift(-path_depth)
if not prefix.endswith('/'):
self.route('/' + '/'.join(parts), callback=mountpoint, **options)
def merge(self, routes):
''' Merge the routes of another :cls:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle):
routes = routes.routes
for route in routes:
self.add_route(route)
def install(self, plugin):
''' Add a plugin to the list of plugins and prepare it for being
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API.
'''
if hasattr(plugin, 'setup'): plugin.setup(self)
if not callable(plugin) and not hasattr(plugin, 'apply'):
raise TypeError("Plugins must be callable or implement .apply()")
self.plugins.append(plugin)
self.reset()
return plugin
def uninstall(self, plugin):
''' Uninstall plugins. Pass an instance to remove a specific plugin, a type
object to remove all plugins that match that type, a string to remove
all plugins with a matching ``name`` attribute or ``True`` to remove all
plugins. Return the list of removed plugins. '''
removed, remove = [], plugin
for i, plugin in list(enumerate(self.plugins))[::-1]:
if remove is True or remove is plugin or remove is type(plugin) \
or getattr(plugin, 'name', True) == remove:
removed.append(plugin)
del self.plugins[i]
if hasattr(plugin, 'close'): plugin.close()
if removed: self.reset()
return removed
def run(self, **kwargs):
''' Calls :func:`run` with the same parameters. '''
run(self, **kwargs)
def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.routes
elif isinstance(route, Route): routes = [route]
else: routes = [self.routes[route]]
for route in routes: route.reset()
if DEBUG:
for route in routes: route.prepare()
self.hooks.trigger('app_reset')
def close(self):
''' Close the application and all installed plugins. '''
for plugin in self.plugins:
if hasattr(plugin, 'close'): plugin.close()
self.stopped = True
def match(self, environ):
""" Search for a matching route and return a (:class:`Route` , urlargs)
tuple. The second value is a dictionary with parameters extracted
from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
return self.router.match(environ)
def get_url(self, routename, **kargs):
""" Return a string that matches a named route """
scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
location = self.router.build(routename, **kargs).lstrip('/')
return urljoin(urljoin('/', scriptname), location)
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare()
def route(self, path=None, method='GET', callback=None, name=None,
apply=None, skip=None, **config):
""" A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path or a list of paths to listen to. If no
path is specified, it is automatically generated from the
signature of the function.
:param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
methods to listen to. (default: `GET`)
:param callback: An optional shortcut to avoid the decorator
syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
:param name: The name for this route. (default: None)
:param apply: A decorator or plugin or a list of plugins. These are
applied to the route callback in addition to installed plugins.
:param skip: A list of plugins, plugin classes or names. Matching
plugins are not installed to this route. ``True`` skips all.
Any additional keyword arguments are stored as route-specific
configuration and passed to plugins (see :meth:`Plugin.apply`).
"""
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
def decorator(callback):
# TODO: Documentation and tests
if isinstance(callback, basestring): callback = load(callback)
for rule in makelist(path) or yieldroutes(callback):
for verb in makelist(method):
verb = verb.upper()
route = Route(self, rule, verb, callback, name=name,
plugins=plugins, skiplist=skiplist, **config)
self.add_route(route)
return callback
return decorator(callback) if callback else decorator
def get(self, path=None, method='GET', **options):
""" Equals :meth:`route`. """
return self.route(path, method, **options)
def post(self, path=None, method='POST', **options):
""" Equals :meth:`route` with a ``POST`` method parameter. """
return self.route(path, method, **options)
def put(self, path=None, method='PUT', **options):
""" Equals :meth:`route` with a ``PUT`` method parameter. """
return self.route(path, method, **options)
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options)
def error(self, code=500):
""" Decorator: Register an output handler for a HTTP error code"""
def wrapper(handler):
self.error_handler[int(code)] = handler
return handler
return wrapper
def hook(self, name):
""" Return a decorator that attaches a callback to a hook. Three hooks
are currently implemented:
- before_request: Executed once before each request
- after_request: Executed once after each request
- app_reset: Called whenever :meth:`reset` is called.
"""
def wrapper(func):
self.hooks.add(name, func)
return func
return wrapper
def handle(self, path, method='GET'):
""" (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
well and returned as :exc:`HTTPError` instances (500).
"""
depr("This method will change semantics in 0.10. Try to avoid it.")
if isinstance(path, dict):
return self._handle(path)
return self._handle({'PATH_INFO': path, 'REQUEST_METHOD': method.upper()})
def _handle(self, environ):
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind()
route, args = self.router.match(environ)
environ['route.handle'] = environ['bottle.route'] = route
environ['route.url_args'] = args
return route.call(**args)
except HTTPResponse:
return _e()
except RouteReset:
route.reset()
return self._handle(environ)
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
stacktrace = format_exc(10)
environ['wsgi.errors'].write(stacktrace)
return HTTPError(500, "Internal Server Error", _e(), stacktrace)
def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty output is done here
if not out:
response['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. Mixed lists are NOT supported
if isinstance(out, (tuple, list))\
and isinstance(out[0], (bytes, unicode)):
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
# Encode unicode strings
if isinstance(out, unicode):
out = out.encode(response.charset)
# Byte Strings are just returned
if isinstance(out, bytes):
response['Content-Length'] = len(out)
return [out]
# HTTPError or HTTPException (recursive, because they may wrap anything)
# TODO: Handle these explicitly in handle() or make them iterable.
if isinstance(out, HTTPError):
out.apply(response)
out = self.error_handler.get(out.status, repr)(out)
if isinstance(out, HTTPResponse):
depr('Error handlers must not return :exc:`HTTPResponse`.') #0.9
return self._cast(out)
if isinstance(out, HTTPResponse):
out.apply(response)
return self._cast(out.output)
# File-like objects.
if hasattr(out, 'read'):
if 'wsgi.file_wrapper' in request.environ:
return request.environ['wsgi.file_wrapper'](out)
elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
return WSGIFileWrapper(out)
# Handle Iterables. We peek into them to detect their inner type.
try:
out = iter(out)
first = next(out)
while not first:
first = next(out)
except StopIteration:
return self._cast('')
except HTTPResponse:
first = _e()
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
first = HTTPError(500, 'Unhandled exception', _e(), format_exc(10))
# These are the inner types allowed in iterator or generator objects.
if isinstance(first, HTTPResponse):
return self._cast(first)
if isinstance(first, bytes):
return itertools.chain([first], out)
if isinstance(first, unicode):
return imap(lambda x: x.encode(response.charset),
itertools.chain([first], out))
return self._cast(HTTPError(500, 'Unsupported response type: %s'\
% type(first)))
def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or request.method == 'HEAD':
if hasattr(out, 'close'): out.close()
out = []
if isinstance(response._status_line, unicode):
response._status_line = str(response._status_line)
start_response(response._status_line, list(response.iter_headers()))
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
err = '<h1>Critical error while processing request: %s</h1>' \
% html_escape(environ.get('PATH_INFO', '/'))
if DEBUG:
err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
'<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
% (html_escape(repr(_e())), html_escape(format_exc(10)))
environ['wsgi.errors'].write(err)
headers = [('Content-Type', 'text/html; charset=UTF-8')]
start_response('500 INTERNAL SERVER ERROR', headers)
return [tob(err)]
def __call__(self, environ, start_response):
''' Each instance of :class:'Bottle' is a WSGI application. '''
return self.wsgi(environ, start_response)
###############################################################################
# HTTP and WSGI Tools ##########################################################
###############################################################################
class BaseRequest(object):
""" A wrapper for WSGI environment dictionaries that adds a lot of
convenient access methods and properties. Most of them are read-only."""
#: Maximum size of memory buffer for :attr:`body` in bytes.
MEMFILE_MAX = 102400
#: Maximum number pr GET or POST parameters per request
MAX_PARAMS = 100
def __init__(self, environ):
""" Wrap a WSGI environ dictionary. """
#: The wrapped WSGI environ dictionary. This is the only real attribute.
#: All other attributes actually are read-only properties.
self.environ = environ
environ['bottle.request'] = self
@DictProperty('environ', 'bottle.app', read_only=True)
def app(self):
''' Bottle application handling this request. '''
raise AttributeError('This request is not connected to an application.')
@property
def path(self):
''' The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
broken clients and avoid the "empty path" edge case). '''
return '/' + self.environ.get('PATH_INFO','').lstrip('/')
@property
def method(self):
''' The ``REQUEST_METHOD`` value as an uppercase string. '''
return self.environ.get('REQUEST_METHOD', 'GET').upper()
@DictProperty('environ', 'bottle.request.headers', read_only=True)
def headers(self):
''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
HTTP request headers. '''
return WSGIHeaderDict(self.environ)
def get_header(self, name, default=None):
''' Return the value of a request header, or a given default value. '''
return self.headers.get(name, default)
@DictProperty('environ', 'bottle.request.cookies', read_only=True)
def cookies(self):
""" Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
decoded. Use :meth:`get_cookie` if you expect signed cookies. """
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
cookies = list(cookies.values())[:self.MAX_PARAMS]
return FormsDict((c.key, c.value) for c in cookies)
def get_cookie(self, key, default=None, secret=None):
""" Return the content of a cookie. To read a `Signed Cookie`, the
`secret` must match the one used to create the cookie (see
:meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
cookie or wrong signature), return a default value. """
value = self.cookies.get(key)
if secret and value:
dec = cookie_decode(value, secret) # (key, value) tuple or None
return dec[1] if dec and dec[0] == key else default
return value or default
@DictProperty('environ', 'bottle.request.query', read_only=True)
def query(self):
''' The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`. '''
pairs = parse_qsl(self.query_string, keep_blank_values=True)
get = self.environ['bottle.get'] = FormsDict()
for key, value in pairs[:self.MAX_PARAMS]:
get[key] = value
return get
@DictProperty('environ', 'bottle.request.forms', read_only=True)
def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = FormsDict()
for name, item in self.POST.allitems():
if not hasattr(item, 'filename'):
forms[name] = item
return forms
@DictProperty('environ', 'bottle.request.params', read_only=True)
def params(self):
""" A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. """
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.allitems():
params[key] = value
return params
@DictProperty('environ', 'bottle.request.files', read_only=True)
def files(self):
""" File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise None; this is the client
side filename, *not* the file name on which it is stored (that's
a temporary file you don't deal with)
file
The file(-like) object from which you can read the data.
value
The value as a *string*; for file uploads, this transparently
reads the file every time you request the value. Do not do this
on big files.
"""
files = FormsDict()
for name, item in self.POST.allitems():
if hasattr(item, 'filename'):
files[name] = item
return files
@DictProperty('environ', 'bottle.request.json', read_only=True)
def json(self):
''' If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
if 'application/json' in self.environ.get('CONTENT_TYPE', '') \
and 0 < self.content_length < self.MEMFILE_MAX:
return json_loads(self.body.read(self.MEMFILE_MAX))
return None
@DictProperty('environ', 'bottle.request.body', read_only=True)
def _body(self):
maxread = max(0, self.content_length)
stream = self.environ['wsgi.input']
body = BytesIO() if maxread < self.MEMFILE_MAX else TemporaryFile(mode='w+b')
while maxread > 0:
part = stream.read(min(maxread, self.MEMFILE_MAX))
if not part: break
body.write(part)
maxread -= len(part)
self.environ['wsgi.input'] = body
body.seek(0)
return body
@property
def body(self):
""" The HTTP request body as a seek-able file-like object. Depending on
:attr:`MEMFILE_MAX`, this is either a temporary file or a
:class:`io.BytesIO` instance. Accessing this property for the first
time reads and replaces the ``wsgi.input`` environ variable.
Subsequent accesses just do a `seek(0)` on the file object. """
self._body.seek(0)
return self._body
#: An alias for :attr:`query`.
GET = query
@DictProperty('environ', 'bottle.request.post', read_only=True)
def POST(self):
""" The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
"""
post = FormsDict()
safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
if key in self.environ: safe_env[key] = self.environ[key]
if NCTextIOWrapper:
fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
else:
fb = self.body
data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
for item in (data.list or [])[:self.MAX_PARAMS]:
post[item.name] = item if item.filename else item.value
return post
@property
def COOKIES(self):
''' Alias for :attr:`cookies` (deprecated). '''
depr('BaseRequest.COOKIES was renamed to BaseRequest.cookies (lowercase).')
return self.cookies
@property
def url(self):
""" The full request URI including hostname and scheme. If your app
lives behind a reverse proxy or load balancer and you get confusing
results, make sure that the ``X-Forwarded-Host`` header is set
correctly. """
return self.urlparts.geturl()
@DictProperty('environ', 'bottle.request.urlparts', read_only=True)
def urlparts(self):
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. '''
env = self.environ
http = env.get('wsgi.url_scheme', 'http')
host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')
if not host:
# HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
host = env.get('SERVER_NAME', '127.0.0.1')
port = env.get('SERVER_PORT')
if port and port != ('80' if http == 'http' else '443'):
host += ':' + port
path = urlquote(self.fullpath)
return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')
@property
def fullpath(self):
""" Request path including :attr:`script_name` (if present). """
return urljoin(self.script_name, self.path.lstrip('/'))
@property
def query_string(self):
""" The raw :attr:`query` part of the URL (everything in between ``?``
and ``#``) as a string. """
return self.environ.get('QUERY_STRING', '')
@property
def script_name(self):
''' The initial portion of the URL's `path` that was removed by a higher
level (server or routing middleware) before the application was
called. This script path is returned with leading and tailing
slashes. '''
script_name = self.environ.get('SCRIPT_NAME', '').strip('/')
return '/' + script_name + '/' if script_name else '/'
def path_shift(self, shift=1):
''' Shift path segments from :attr:`path` to :attr:`script_name` and
vice versa.
:param shift: The number of path segments to shift. May be negative
to change the shift direction. (default: 1)
'''
script = self.environ.get('SCRIPT_NAME','/')
self['SCRIPT_NAME'], self['PATH_INFO'] = path_shift(script, self.path, shift)
@property
def content_length(self):
''' The request body length as an integer. The client is responsible to
set this header. Otherwise, the real length of the body is unknown
and -1 is returned. In this case, :attr:`body` will be empty. '''
return int(self.environ.get('CONTENT_LENGTH') or -1)
@property
def is_xhr(self):
''' True if the request was triggered by a XMLHttpRequest. This only
works with JavaScript libraries that support the `X-Requested-With`
header (most of the popular libraries do). '''
requested_with = self.environ.get('HTTP_X_REQUESTED_WITH','')
return requested_with.lower() == 'xmlhttprequest'
@property
def is_ajax(self):
''' Alias for :attr:`is_xhr`. "Ajax" is not the right term. '''
return self.is_xhr
@property
def auth(self):
""" HTTP authentication data as a (user, password) tuple. This
implementation currently supports basic (not digest) authentication
only. If the authentication happened at a higher level (e.g. in the
front web-server or a middleware), the password field is None, but
the user field is looked up from the ``REMOTE_USER`` environ
variable. On any errors, None is returned. """
basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION',''))
if basic: return basic
ruser = self.environ.get('REMOTE_USER')
if ruser: return (ruser, None)
return None
@property
def remote_route(self):
""" A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. """
proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
if proxy: return [ip.strip() for ip in proxy.split(',')]
remote = self.environ.get('REMOTE_ADDR')
return [remote] if remote else []
@property
def remote_addr(self):
""" The client IP as a string. Note that this information can be forged
by malicious clients. """
route = self.remote_route
return route[0] if route else None
def copy(self):
""" Return a new :class:`Request` with a shallow :attr:`environ` copy. """
return Request(self.environ.copy())
def get(self, value, default=None): return self.environ.get(value, default)
def __getitem__(self, key): return self.environ[key]
def __delitem__(self, key): self[key] = ""; del(self.environ[key])
def __iter__(self): return iter(self.environ)
def __len__(self): return len(self.environ)
def keys(self): return self.environ.keys()
def __setitem__(self, key, value):
""" Change an environ value and clear all caches that depend on it. """
if self.environ.get('bottle.request.readonly'):
raise KeyError('The environ dictionary is read-only.')
self.environ[key] = value
todelete = ()
if key == 'wsgi.input':
todelete = ('body', 'forms', 'files', 'params', 'post', 'json')
elif key == 'QUERY_STRING':
todelete = ('query', 'params')
elif key.startswith('HTTP_'):
todelete = ('headers', 'cookies')
for key in todelete:
self.environ.pop('bottle.request.'+key, None)
def __repr__(self):
return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)
def _hkey(s):
return s.title().replace('_','-')
class HeaderProperty(object):
def __init__(self, name, reader=None, writer=str, default=''):
self.name, self.reader, self.writer, self.default = name, reader, writer, default
self.__doc__ = 'Current value of the %r header.' % name.title()
def __get__(self, obj, cls):
if obj is None: return self
value = obj.headers.get(self.name)
return self.reader(value) if (value and self.reader) else (value or self.default)
def __set__(self, obj, value):
if self.writer: value = self.writer(value)
obj.headers[self.name] = value
def __delete__(self, obj):
if self.name in obj.headers:
del obj.headers[self.name]
class BaseResponse(object):
""" Storage class for a response body as well as headers and cookies.
This class does support dict-like case-insensitive item-access to
headers, but is NOT a dict. Most notably, iterating over a response
yields parts of the body and not the headers.
"""
default_status = 200
default_content_type = 'text/html; charset=UTF-8'
# Header blacklist for specific response codes
# (rfc2616 section 10.2.3 and 10.3.5)
bad_headers = {
204: set(('Content-Type',)),
304: set(('Allow', 'Content-Encoding', 'Content-Language',
'Content-Length', 'Content-Range', 'Content-Type',
'Content-Md5', 'Last-Modified'))}
def __init__(self, body='', status=None, **headers):
self._status_line = None
self._status_code = None
self._cookies = None
self._headers = {'Content-Type': [self.default_content_type]}
self.body = body
self.status = status or self.default_status
if headers:
for name, value in headers.items():
self[name] = value
def copy(self):
''' Returns a copy of self. '''
copy = Response()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
return copy
def __iter__(self):
return iter(self.body)
def close(self):
if hasattr(self.body, 'close'):
self.body.close()
@property
def status_line(self):
''' The HTTP status line as a string (e.g. ``404 Not Found``).'''
return self._status_line
@property
def status_code(self):
''' The HTTP status code as an integer (e.g. 404).'''
return self._status_code
def _set_status(self, status):
if isinstance(status, int):
code, status = status, _HTTP_STATUS_LINES.get(status)
elif ' ' in status:
status = status.strip()
code = int(status.split()[0])
else:
raise ValueError('String status line without a reason phrase.')
if not 100 <= code <= 999: raise ValueError('Status code out of range.')
self._status_code = code
self._status_line = status or ('%d Unknown' % code)
def _get_status(self):
return self._status_line
status = property(_get_status, _set_status, None,
''' A writeable property to change the HTTP response status. It accepts
either a numeric code (100-999) or a string with a custom reason
phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
:data:`status_code` are updated accordingly. The return value is
always a status string. ''')
del _get_status, _set_status
@property
def headers(self):
''' An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers. '''
self.__dict__['headers'] = hdict = HeaderDict()
hdict.dict = self._headers
return hdict
def __contains__(self, name): return _hkey(name) in self._headers
def __delitem__(self, name): del self._headers[_hkey(name)]
def __getitem__(self, name): return self._headers[_hkey(name)][-1]
def __setitem__(self, name, value): self._headers[_hkey(name)] = [str(value)]
def get_header(self, name, default=None):
''' Return the value of a previously defined header. If there is no
header with that name, return a default value. '''
return self._headers.get(_hkey(name), [default])[-1]
def set_header(self, name, value, append=False):
''' Create a new response header, replacing any previously defined
headers with the same name. '''
if append:
self.add_header(name, value)
else:
self._headers[_hkey(name)] = [str(value)]
def add_header(self, name, value):
''' Add an additional response header, not removing duplicates. '''
self._headers.setdefault(_hkey(name), []).append(str(value))
def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
headers = self._headers.items()
bad_headers = self.bad_headers.get(self._status_code)
if bad_headers:
headers = [h for h in headers if h[0] not in bad_headers]
for name, values in headers:
for value in values:
yield name, value
if self._cookies:
for c in self._cookies.values():
yield 'Set-Cookie', c.OutputString()
def wsgiheader(self):
depr('The wsgiheader method is deprecated. See headerlist.') #0.10
return self.headerlist
@property
def headerlist(self):
''' WSGI conform list of (header, value) tuples. '''
return list(self.iter_headers())
content_type = HeaderProperty('Content-Type')
content_length = HeaderProperty('Content-Length', reader=int)
@property
def charset(self):
""" Return the charset specified in the content-type header (default: utf8). """
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return 'UTF-8'
@property
def COOKIES(self):
""" A dict-like SimpleCookie instance. This should not be used directly.
See :meth:`set_cookie`. """
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10
if not self._cookies:
self._cookies = SimpleCookie()
return self._cookies
def set_cookie(self, name, value, secret=None, **options):
''' Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:param secret: a signature key required for signed cookies.
Additionally, this method accepts all RFC 2109 attributes that are
supported by :class:`cookie.Morsel`, including:
:param max_age: maximum age in seconds. (default: None)
:param expires: a datetime object or UNIX timestamp. (default: None)
:param domain: the domain that is allowed to read the cookie.
(default: current domain)
:param path: limits the cookie to a given path (default: current path)
:param secure: limit the cookie to HTTPS connections (default: off).
:param httponly: prevents client-side javascript to read this cookie
(default: off, requires Python 2.6 or newer).
If neither `expires` nor `max_age` is set (default), the cookie will
expire at the end of the browser session (as soon as the browser
window is closed).
Signed cookies may store any pickle-able object and are
cryptographically signed to prevent manipulation. Keep in mind that
cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see
the content) and not copy-protected (the client can restore an old
cookie). The main intention is to make pickling and unpickling
save, not to store secret information at client side.
'''
if not self._cookies:
self._cookies = SimpleCookie()
if secret:
value = touni(cookie_encode((name, value), secret))
elif not isinstance(value, basestring):
raise TypeError('Secret key missing for non-string Cookie.')
if len(value) > 4096: raise ValueError('Cookie value to long.')
self._cookies[name] = value
for key, value in options.items():
if key == 'max_age':
if isinstance(value, timedelta):
value = value.seconds + value.days * 24 * 3600
if key == 'expires':
if isinstance(value, (datedate, datetime)):
value = value.timetuple()
elif isinstance(value, (int, float)):
value = time.gmtime(value)
value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
self._cookies[name][key.replace('_', '-')] = value
def delete_cookie(self, key, **kwargs):
''' Delete a cookie. Be sure to use the same `domain` and `path`
settings as used to create the cookie. '''
kwargs['max_age'] = -1
kwargs['expires'] = 0
self.set_cookie(key, '', **kwargs)
def __repr__(self):
out = ''
for name, value in self.headerlist:
out += '%s: %s\n' % (name.title(), value.strip())
return out
#: Thread-local storage for :class:`LocalRequest` and :class:`LocalResponse`
#: attributes.
_lctx = threading.local()
def local_property(name, doc=None):
return property(
lambda self: getattr(_lctx, name),
lambda self, value: setattr(_lctx, name, value),
lambda self: delattr(_lctx, name),
doc or ('Thread-local property stored in :data:`_lctx.%s` ' % name)
)
class LocalRequest(BaseRequest):
''' A thread-local subclass of :class:`BaseRequest` with a different
set of attribues for each thread. There is usually only one global
instance of this class (:data:`request`). If accessed during a
request/response cycle, this instance always refers to the *current*
request (even on a multithreaded server). '''
def __init__(self): pass
bind = BaseRequest.__init__
environ = local_property('request_environ')
class LocalResponse(BaseResponse):
''' A thread-local subclass of :class:`BaseResponse` with a different
set of attribues for each thread. There is usually only one global
instance of this class (:data:`response`). Its attributes are used
to build the HTTP response at the end of the request/response cycle.
'''
def __init__(self): pass
bind = BaseResponse.__init__
_status_line = local_property('response_status_line')
_status_code = local_property('response_status_code')
_cookies = local_property('response_cookies')
_headers = local_property('response_headers')
body = local_property('response_body')
Response = LocalResponse # BC 0.9
Request = LocalRequest # BC 0.9
###############################################################################
# Plugins ######################################################################
###############################################################################
class PluginError(BottleException): pass
class JSONPlugin(object):
name = 'json'
api = 2
def __init__(self, json_dumps=json_dumps):
self.json_dumps = json_dumps
def apply(self, callback, context):
dumps = self.json_dumps
if not dumps: return callback
def wrapper(*a, **ka):
rv = callback(*a, **ka)
if isinstance(rv, dict):
#Attempt to serialize, raises exception on failure
json_response = dumps(rv)
#Set content type only if serialization succesful
response.content_type = 'application/json'
return json_response
return rv
return wrapper
class HooksPlugin(object):
name = 'hooks'
api = 2
_names = 'before_request', 'after_request', 'app_reset'
def __init__(self):
self.hooks = dict((name, []) for name in self._names)
self.app = None
def _empty(self):
return not (self.hooks['before_request'] or self.hooks['after_request'])
def setup(self, app):
self.app = app
def add(self, name, func):
''' Attach a callback to a hook. '''
was_empty = self._empty()
self.hooks.setdefault(name, []).append(func)
if self.app and was_empty and not self._empty(): self.app.reset()
def remove(self, name, func):
''' Remove a callback from a hook. '''
was_empty = self._empty()
if name in self.hooks and func in self.hooks[name]:
self.hooks[name].remove(func)
if self.app and not was_empty and self._empty(): self.app.reset()
def trigger(self, name, *a, **ka):
''' Trigger a hook and return a list of results. '''
hooks = self.hooks[name]
if ka.pop('reversed', False): hooks = hooks[::-1]
return [hook(*a, **ka) for hook in hooks]
def apply(self, callback, context):
if self._empty(): return callback
def wrapper(*a, **ka):
self.trigger('before_request')
rv = callback(*a, **ka)
self.trigger('after_request', reversed=True)
return rv
return wrapper
class TemplatePlugin(object):
''' This plugin applies the :func:`view` decorator to all routes with a
`template` config parameter. If the parameter is a tuple, the second
element must be a dict with additional options (e.g. `template_engine`)
or default variables for the template. '''
name = 'template'
api = 2
def apply(self, callback, route):
conf = route.config.get('template')
if isinstance(conf, (tuple, list)) and len(conf) == 2:
return view(conf[0], **conf[1])(callback)
elif isinstance(conf, str) and 'template_opts' in route.config:
depr('The `template_opts` parameter is deprecated.') #0.9
return view(conf, **route.config['template_opts'])(callback)
elif isinstance(conf, str):
return view(conf)(callback)
else:
return callback
#: Not a plugin, but part of the plugin API. TODO: Find a better place.
class _ImportRedirect(object):
def __init__(self, name, impmask):
''' Create a virtual package that redirects imports (see PEP 302). '''
self.name = name
self.impmask = impmask
self.module = sys.modules.setdefault(name, imp.new_module(name))
self.module.__dict__.update({'__file__': __file__, '__path__': [],
'__all__': [], '__loader__': self})
sys.meta_path.append(self)
def find_module(self, fullname, path=None):
if '.' not in fullname: return
packname, modname = fullname.rsplit('.', 1)
if packname != self.name: return
return self
def load_module(self, fullname):
if fullname in sys.modules: return sys.modules[fullname]
packname, modname = fullname.rsplit('.', 1)
realname = self.impmask % modname
__import__(realname)
module = sys.modules[fullname] = sys.modules[realname]
setattr(self.module, modname, module)
module.__loader__ = self
return module
###############################################################################
# Common Utilities #############################################################
###############################################################################
class MultiDict(DictMixin):
""" This dict stores multiple values per key, but behaves exactly like a
normal dict in that it returns only the newest value for any given key.
There are special methods available to access the full list of values.
"""
def __init__(self, *a, **k):
self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
def __len__(self): return len(self.dict)
def __iter__(self): return iter(self.dict)
def __contains__(self, key): return key in self.dict
def __delitem__(self, key): del self.dict[key]
def __getitem__(self, key): return self.dict[key][-1]
def __setitem__(self, key, value): self.append(key, value)
def keys(self): return self.dict.keys()
if py3k:
def values(self): return (v[-1] for v in self.dict.values())
def items(self): return ((k, v[-1]) for k, v in self.dict.items())
def allitems(self):
return ((k, v) for k, vl in self.dict.items() for v in vl)
iterkeys = keys
itervalues = values
iteritems = items
iterallitems = allitems
else:
def values(self): return [v[-1] for v in self.dict.values()]
def items(self): return [(k, v[-1]) for k, v in self.dict.items()]
def iterkeys(self): return self.dict.iterkeys()
def itervalues(self): return (v[-1] for v in self.dict.itervalues())
def iteritems(self):
return ((k, v[-1]) for k, v in self.dict.iteritems())
def iterallitems(self):
return ((k, v) for k, vl in self.dict.iteritems() for v in vl)
def allitems(self):
return [(k, v) for k, vl in self.dict.iteritems() for v in vl]
def get(self, key, default=None, index=-1, type=None):
''' Return the most recent value for a key.
:param default: The default value to be returned if the key is not
present or the type conversion fails.
:param index: An index for the list of available values.
:param type: If defined, this callable is used to cast the value
into a specific type. Exception are suppressed and result in
the default value to be returned.
'''
try:
val = self.dict[key][index]
return type(val) if type else val
except Exception:
pass
return default
def append(self, key, value):
''' Add a new value to the list of values for this key. '''
self.dict.setdefault(key, []).append(value)
def replace(self, key, value):
''' Replace the list of values with a single value. '''
self.dict[key] = [value]
def getall(self, key):
''' Return a (possibly empty) list of values for a key. '''
return self.dict.get(key) or []
#: Aliases for WTForms to mimic other multi-dict APIs (Django)
getone = get
getlist = getall
class FormsDict(MultiDict):
''' This :class:`MultiDict` subclass is used to store request form data.
Additionally to the normal dict-like item access methods (which return
unmodified data as native strings), this container also supports
attribute-like access to its values. Attributes are automatically de-
or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing
attributes default to an empty string. '''
#: Encoding used for attribute values.
input_encoding = 'utf8'
#: If true (default), unicode strings are first encoded with `latin1`
#: and then decoded to match :attr:`input_encoding`.
recode_unicode = True
def _fix(self, s, encoding=None):
if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI
s = s.encode('latin1')
if isinstance(s, bytes): # Python 2 WSGI
return s.decode(encoding or self.input_encoding)
return s
def decode(self, encoding=None):
''' Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. '''
copy = FormsDict()
enc = copy.input_encoding = encoding or self.input_encoding
copy.recode_unicode = False
for key, value in self.allitems():
copy.append(self._fix(key, enc), self._fix(value, enc))
return copy
def getunicode(self, name, default=None, encoding=None):
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default
def __getattr__(self, name, default=unicode()):
return self.getunicode(name, default=default)
class HeaderDict(MultiDict):
""" A case-insensitive version of :class:`MultiDict` that defaults to
replace the old value instead of appending it. """
def __init__(self, *a, **ka):
self.dict = {}
if a or ka: self.update(*a, **ka)
def __contains__(self, key): return _hkey(key) in self.dict
def __delitem__(self, key): del self.dict[_hkey(key)]
def __getitem__(self, key): return self.dict[_hkey(key)][-1]
def __setitem__(self, key, value): self.dict[_hkey(key)] = [str(value)]
def append(self, key, value):
self.dict.setdefault(_hkey(key), []).append(str(value))
def replace(self, key, value): self.dict[_hkey(key)] = [str(value)]
def getall(self, key): return self.dict.get(_hkey(key)) or []
def get(self, key, default=None, index=-1):
return MultiDict.get(self, _hkey(key), default, index)
def filter(self, names):
for name in [_hkey(n) for n in names]:
if name in self.dict:
del self.dict[name]
class WSGIHeaderDict(DictMixin):
''' This dict-like class wraps a WSGI environ dict and provides convenient
access to HTTP_* fields. Keys and values are native strings
(2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI
environment contains non-native string values, these are de- or encoded
using a lossless 'latin1' character set.
The API will remain stable even on changes to the relevant PEPs.
Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one
that uses non-native strings.)
'''
#: List of keys that do not have a 'HTTP_' prefix.
cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')
def __init__(self, environ):
self.environ = environ
def _ekey(self, key):
''' Translate header field name to CGI/WSGI environ key. '''
key = key.replace('-','_').upper()
if key in self.cgikeys:
return key
return 'HTTP_' + key
def raw(self, key, default=None):
''' Return the header value as is (may be bytes or unicode). '''
return self.environ.get(self._ekey(key), default)
def __getitem__(self, key):
return tonat(self.environ[self._ekey(key)], 'latin1')
def __setitem__(self, key, value):
raise TypeError("%s is read-only." % self.__class__)
def __delitem__(self, key):
raise TypeError("%s is read-only." % self.__class__)
def __iter__(self):
for key in self.environ:
if key[:5] == 'HTTP_':
yield key[5:].replace('_', '-').title()
elif key in self.cgikeys:
yield key.replace('_', '-').title()
def keys(self): return [x for x in self]
def __len__(self): return len(self.keys())
def __contains__(self, key): return self._ekey(key) in self.environ
class ConfigDict(dict):
''' A dict-subclass with some extras: You can access keys like attributes.
Uppercase attributes create new ConfigDicts and act as name-spaces.
Other missing attributes return None. Calling a ConfigDict updates its
values and returns itself.
>>> cfg = ConfigDict()
>>> cfg.Namespace.value = 5
>>> cfg.OtherNamespace(a=1, b=2)
>>> cfg
{'Namespace': {'value': 5}, 'OtherNamespace': {'a': 1, 'b': 2}}
'''
def __getattr__(self, key):
if key not in self and key[0].isupper():
self[key] = ConfigDict()
return self.get(key)
def __setattr__(self, key, value):
if hasattr(dict, key):
raise AttributeError('Read-only attribute.')
if key in self and self[key] and isinstance(self[key], ConfigDict):
raise AttributeError('Non-empty namespace attribute.')
self[key] = value
def __delattr__(self, key):
if key in self: del self[key]
def __call__(self, *a, **ka):
for key, value in dict(*a, **ka).items(): setattr(self, key, value)
return self
class AppStack(list):
""" A stack-like list. Calling it returns the head of the stack. """
def __call__(self):
""" Return the current default application. """
return self[-1]
def push(self, value=None):
""" Add a new :class:`Bottle` instance to the stack """
if not isinstance(value, Bottle):
value = Bottle()
self.append(value)
return value
class WSGIFileWrapper(object):
def __init__(self, fp, buffer_size=1024*64):
self.fp, self.buffer_size = fp, buffer_size
for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'):
if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))
def __iter__(self):
buff, read = self.buffer_size, self.read
while True:
part = read(buff)
if not part: return
yield part
###############################################################################
# Application Helper ###########################################################
###############################################################################
def abort(code=500, text='Unknown Error: Application stopped.'):
""" Aborts execution and causes a HTTP error. """
raise HTTPError(code, text)
def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if code is None:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
location = urljoin(request.url, url)
raise HTTPResponse("", status=code, header=dict(Location=location))
def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part
def static_file(filename, root, mimetype='auto', download=False):
""" Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 401 or 404. Set Content-Type, Content-Encoding,
Content-Length and Last-Modified header. Obey If-Modified-Since header
and HEAD requests.
"""
root = os.path.abspath(root) + os.sep
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
header = dict()
if not filename.startswith(root):
return HTTPError(403, "Access denied.")
if not os.path.exists(filename) or not os.path.isfile(filename):
return HTTPError(404, "File does not exist.")
if not os.access(filename, os.R_OK):
return HTTPError(403, "You do not have permission to access this file.")
if mimetype == 'auto':
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype: header['Content-Type'] = mimetype
if encoding: header['Content-Encoding'] = encoding
elif mimetype:
header['Content-Type'] = mimetype
if download:
download = os.path.basename(filename if download == True else download)
header['Content-Disposition'] = 'attachment; filename="%s"' % download
stats = os.stat(filename)
header['Content-Length'] = clen = stats.st_size
lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
header['Last-Modified'] = lm
ims = request.environ.get('HTTP_IF_MODIFIED_SINCE')
if ims:
ims = parse_date(ims.split(";")[0].strip())
if ims is not None and ims >= int(stats.st_mtime):
header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
return HTTPResponse(status=304, header=header)
body = '' if request.method == 'HEAD' else open(filename, 'rb')
header["Accept-Ranges"] = "bytes"
ranges = request.environ.get('HTTP_RANGE')
if 'HTTP_RANGE' in request.environ:
ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen))
if not ranges:
return HTTPError(416, "Requested Range Not Satisfiable")
offset, end = ranges[0]
header["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen)
header["Content-Length"] = str(end-offset)
if body: body = _file_iter_range(body, offset, end-offset)
return HTTPResponse(body, header=header, status=206)
return HTTPResponse(body, header=header)
###############################################################################
# HTTP Utilities and MISC (TODO) ###############################################
###############################################################################
def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
DEBUG = bool(mode)
def parse_date(ims):
""" Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, ValueError, IndexError, OverflowError):
return None
def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd
except (KeyError, ValueError):
return None
def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, end in ranges:
try:
if not start: # bytes=-100 -> last 100 bytes
start, end = max(0, maxlen-int(end)), maxlen
elif not end: # bytes=100- -> all but the first 99 bytes
start, end = int(start), maxlen
else: # bytes=100-200 -> bytes 100-200 (inclusive)
start, end = int(start), min(int(end)+1, maxlen)
if 0 <= start < end <= maxlen:
yield start, end
except ValueError:
pass
def _lscmp(a, b):
''' Compares two strings in a cryptographically save way:
Runtime is not affected by length of common prefix. '''
return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b)
def cookie_encode(data, key):
''' Encode and sign a pickle-able object. Return a (byte) string '''
msg = base64.b64encode(pickle.dumps(data, -1))
sig = base64.b64encode(hmac.new(tob(key), msg).digest())
return tob('!') + sig + tob('?') + msg
def cookie_decode(data, key):
''' Verify and decode an encoded string. Return an object or None.'''
data = tob(data)
if cookie_is_encoded(data):
sig, msg = data.split(tob('?'), 1)
if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())):
return pickle.loads(base64.b64decode(msg))
return None
def cookie_is_encoded(data):
''' Return True if the argument looks like a encoded cookie.'''
return bool(data.startswith(tob('!')) and tob('?') in data)
def html_escape(string):
''' Escape HTML special characters ``&<>`` and quotes ``'"``. '''
return string.replace('&','&').replace('<','<').replace('>','>')\
.replace('"','"').replace("'",''')
def html_quote(string):
''' Escape and quote a string to be used as an HTTP attribute.'''
return '"%s"' % html_escape(string).replace('\n','%#10;')\
.replace('\r',' ').replace('\t','	')
def yieldroutes(func):
""" Return a generator for routes that match the signature (name, args)
of the func parameter. This may yield more than one route if the function
takes optional keyword arguments. The output is best described by example::
a() -> '/a'
b(x, y) -> '/b/:x/:y'
c(x, y=5) -> '/c/:x' and '/c/:x/:y'
d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
"""
import inspect # Expensive module. Only import if necessary.
path = '/' + func.__name__.replace('__','/').lstrip('/')
spec = inspect.getargspec(func)
argc = len(spec[0]) - len(spec[3] or [])
path += ('/:%s' * argc) % tuple(spec[0][:argc])
yield path
for arg in spec[0][argc:]:
path += '/:%s' % arg
yield path
def path_shift(script_name, path_info, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift. May be negative to
change the shift direction. (default: 1)
'''
if shift == 0: return script_name, path_info
pathlist = path_info.strip('/').split('/')
scriptlist = script_name.strip('/').split('/')
if pathlist and pathlist[0] == '': pathlist = []
if scriptlist and scriptlist[0] == '': scriptlist = []
if shift > 0 and shift <= len(pathlist):
moved = pathlist[:shift]
scriptlist = scriptlist + moved
pathlist = pathlist[shift:]
elif shift < 0 and shift >= -len(scriptlist):
moved = scriptlist[shift:]
pathlist = moved + pathlist
scriptlist = scriptlist[:shift]
else:
empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
raise AssertionError("Cannot shift. Nothing left from %s" % empty)
new_script_name = '/' + '/'.join(scriptlist)
new_path_info = '/' + '/'.join(pathlist)
if path_info.endswith('/') and pathlist: new_path_info += '/'
return new_script_name, new_path_info
def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
depr('Use route wildcard filters instead.')
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kargs):
for key, value in vkargs.items():
if key not in kargs:
abort(403, 'Missing parameter: %s' % key)
try:
kargs[key] = value(kargs[key])
except ValueError:
abort(403, 'Wrong parameter format for: %s' % key)
return func(*args, **kargs)
return wrapper
return decorator
def auth_basic(check, realm="private", text="Access denied"):
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or not check(user, password):
response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return HTTPError(401, text)
return func(*a, **ka)
return wrapper
return decorator
# Shortcuts for common Bottle methods.
# They all refer to the current default application.
def make_default_app_wrapper(name):
''' Return a callable that relays calls to the current default app. '''
@functools.wraps(getattr(Bottle, name))
def wrapper(*a, **ka):
return getattr(app(), name)(*a, **ka)
return wrapper
route = make_default_app_wrapper('route')
get = make_default_app_wrapper('get')
post = make_default_app_wrapper('post')
put = make_default_app_wrapper('put')
delete = make_default_app_wrapper('delete')
error = make_default_app_wrapper('error')
mount = make_default_app_wrapper('mount')
hook = make_default_app_wrapper('hook')
install = make_default_app_wrapper('install')
uninstall = make_default_app_wrapper('uninstall')
url = make_default_app_wrapper('get_url')
###############################################################################
# Server Adapter ###############################################################
###############################################################################
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port = int(port)
def run(self, handler): # pragma: no cover
pass
def __repr__(self):
args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()])
return "%s(%s)" % (self.__class__.__name__, args)
class CGIServer(ServerAdapter):
quiet = True
def run(self, handler): # pragma: no cover
from wsgiref.handlers import CGIHandler
def fixed_environ(environ, start_response):
environ.setdefault('PATH_INFO', '')
return handler(environ, start_response)
CGIHandler().run(fixed_environ)
class FlupFCGIServer(ServerAdapter):
def run(self, handler): # pragma: no cover
import flup.server.fcgi
self.options.setdefault('bindAddress', (self.host, self.port))
flup.server.fcgi.WSGIServer(handler, **self.options).run()
class WSGIRefServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw): pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.serve_forever()
class CherryPyServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from cherrypy import wsgiserver
server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
try:
server.start()
finally:
server.stop()
class PasteServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from paste import httpserver
if not self.quiet:
from paste.translogger import TransLogger
handler = TransLogger(handler)
httpserver.serve(handler, host=self.host, port=str(self.port),
**self.options)
class MeinheldServer(ServerAdapter):
def run(self, handler):
from meinheld import server
server.listen((self.host, self.port))
server.run(handler)
class FapwsServer(ServerAdapter):
""" Extremely fast webserver using libev. See http://www.fapws.org/ """
def run(self, handler): # pragma: no cover
import fapws._evwsgi as evwsgi
from fapws import base, config
port = self.port
if float(config.SERVER_IDENT[-2:]) > 0.4:
# fapws3 silently changed its API in 0.5
port = str(port)
evwsgi.start(self.host, port)
# fapws3 never releases the GIL. Complain upstream. I tried. No luck.
if 'BOTTLE_CHILD' in os.environ and not self.quiet:
_stderr("WARNING: Auto-reloading does not work with Fapws3.\n")
_stderr(" (Fapws3 breaks python thread support)\n")
evwsgi.set_base_module(base)
def app(environ, start_response):
environ['wsgi.multiprocess'] = False
return handler(environ, start_response)
evwsgi.wsgi_cb(('', app))
evwsgi.run()
class TornadoServer(ServerAdapter):
""" The super hyped asynchronous server by facebook. Untested. """
def run(self, handler): # pragma: no cover
import tornado.wsgi, tornado.httpserver, tornado.ioloop
container = tornado.wsgi.WSGIContainer(handler)
server = tornado.httpserver.HTTPServer(container)
server.listen(port=self.port)
tornado.ioloop.IOLoop.instance().start()
class AppEngineServer(ServerAdapter):
""" Adapter for Google App Engine. """
quiet = True
def run(self, handler):
from google.appengine.ext.webapp import util
# A main() function in the handler script enables 'App Caching'.
# Lets makes sure it is there. This _really_ improves performance.
module = sys.modules.get('__main__')
if module and not hasattr(module, 'main'):
module.main = lambda: util.run_wsgi_app(handler)
util.run_wsgi_app(handler)
class TwistedServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from twisted.web import server, wsgi
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
thread_pool = ThreadPool()
thread_pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
reactor.listenTCP(self.port, factory, interface=self.host)
reactor.run()
class DieselServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
class GeventServer(ServerAdapter):
""" Untested. Options:
* `monkey` (default: True) fixes the stdlib to use greenthreads.
* `fast` (default: False) uses libevent's http server, but has some
issues: No streaming, no pipelining, no SSL.
"""
def run(self, handler):
from gevent import wsgi as wsgi_fast, pywsgi, monkey, local
if self.options.get('monkey', True):
if not threading.local is local.local: monkey.patch_all()
wsgi = wsgi_fast if self.options.get('fast') else pywsgi
wsgi.WSGIServer((self.host, self.port), handler).serve_forever()
class GunicornServer(ServerAdapter):
""" Untested. See http://gunicorn.org/configure.html for options. """
def run(self, handler):
from gunicorn.app.base import Application
config = {'bind': "%s:%d" % (self.host, int(self.port))}
config.update(self.options)
class GunicornApplication(Application):
def init(self, parser, opts, args):
return config
def load(self):
return handler
GunicornApplication().run()
class EventletServer(ServerAdapter):
""" Untested """
def run(self, handler):
from eventlet import wsgi, listen
try:
wsgi.server(listen((self.host, self.port)), handler,
log_output=(not self.quiet))
except TypeError:
# Fallback, if we have old version of eventlet
wsgi.server(listen((self.host, self.port)), handler)
class RocketServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from rocket import Rocket
server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
server.start()
class BjoernServer(ServerAdapter):
""" Fast server written in C: https://github.com/jonashaag/bjoern """
def run(self, handler):
from bjoern import run
run(handler, self.host, self.port)
class AutoServer(ServerAdapter):
""" Untested. """
adapters = [PasteServer, TwistedServer, CherryPyServer, WSGIRefServer]
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except ImportError:
pass
server_names = {
'cgi': CGIServer,
'flup': FlupFCGIServer,
'wsgiref': WSGIRefServer,
'cherrypy': CherryPyServer,
'paste': PasteServer,
'fapws3': FapwsServer,
'tornado': TornadoServer,
'gae': AppEngineServer,
'twisted': TwistedServer,
'diesel': DieselServer,
'meinheld': MeinheldServer,
'gunicorn': GunicornServer,
'eventlet': EventletServer,
'gevent': GeventServer,
'rocket': RocketServer,
'bjoern' : BjoernServer,
'auto': AutoServer,
}
###############################################################################
# Application Control ##########################################################
###############################################################################
def load(target, **namespace):
""" Import a module or fetch an object from a module.
* ``package.module`` returns `module` as a module object.
* ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
* ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
The last form accepts not only function calls, but any type of
expression. Keyword arguments passed to this function are available as
local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
"""
module, target = target.split(":", 1) if ':' in target else (target, None)
if module not in sys.modules: __import__(module)
if not target: return sys.modules[module]
if target.isalnum(): return getattr(sys.modules[module], target)
package_name = module.split('.')[0]
namespace[package_name] = sys.modules[package_name]
return eval('%s.%s' % (module, target), namespace)
def load_app(target):
""" Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter. """
global NORUN; NORUN, nr_old = True, NORUN
try:
tmp = default_app.push() # Create a new "default application"
rv = load(target) # Import the target module
return rv if callable(rv) else tmp
finally:
default_app.remove(tmp) # Remove the temporary added default application
NORUN = nr_old
_debug = debug
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=False, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter.
"""
if NORUN: return
if reloader and not os.environ.get('BOTTLE_CHILD'):
try:
lockfile = None
fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
except KeyboardInterrupt:
pass
finally:
if os.path.exists(lockfile):
os.unlink(lockfile)
return
try:
_debug(debug)
app = app or default_app()
if isinstance(app, basestring):
app = load_app(app)
if not callable(app):
raise ValueError("Application is not callable: %r" % app)
for plugin in plugins or []:
app.install(plugin)
if server in server_names:
server = server_names.get(server)
if isinstance(server, basestring):
server = load(server)
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise ValueError("Unknown or unsupported server: %r" % server)
server.quiet = server.quiet or quiet
if not server.quiet:
_stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
_stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
_stderr("Hit Ctrl-C to quit.\n\n")
if reloader:
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
with bgcheck:
server.run(app)
if bgcheck.status == 'reload':
sys.exit(3)
else:
server.run(app)
except KeyboardInterrupt:
pass
except (SystemExit, MemoryError):
raise
except:
if not reloader: raise
if not getattr(server, 'quiet', quiet):
print_exc()
time.sleep(interval)
sys.exit(3)
class FileCheckerThread(threading.Thread):
''' Interrupt main-thread as soon as a changed module file is detected,
the lockfile gets deleted or gets to old. '''
def __init__(self, lockfile, interval):
threading.Thread.__init__(self)
self.lockfile, self.interval = lockfile, interval
#: Is one of 'reload', 'error' or 'exit'
self.status = None
def run(self):
exists = os.path.exists
mtime = lambda path: os.stat(path).st_mtime
files = dict()
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '')
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
def __enter__(self):
self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.status: self.status = 'exit' # silent exit
self.join()
return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
###############################################################################
# Template Adapters ############################################################
###############################################################################
class TemplateError(HTTPError):
def __init__(self, message):
HTTPError.__init__(self, 500, message)
class BaseTemplate(object):
""" Base class and minimal API for template adapters """
extensions = ['tpl','html','thtml','stpl']
settings = {} #used in prepare()
defaults = {} #used in render()
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
""" Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
"""
self.name = name
self.source = source.read() if hasattr(source, 'read') else source
self.filename = source.filename if hasattr(source, 'filename') else None
self.lookup = [os.path.abspath(x) for x in lookup]
self.encoding = encoding
self.settings = self.settings.copy() # Copy from class variable
self.settings.update(settings) # Apply
if not self.source and self.name:
self.filename = self.search(self.name, self.lookup)
if not self.filename:
raise TemplateError('Template %s not found.' % repr(name))
if not self.source and not self.filename:
raise TemplateError('No template specified.')
self.prepare(**self.settings)
@classmethod
def search(cls, name, lookup=[]):
""" Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. """
if os.path.isfile(name): return name
for spath in lookup:
fname = os.path.join(spath, name)
if os.path.isfile(fname):
return fname
for ext in cls.extensions:
if os.path.isfile('%s.%s' % (fname, ext)):
return '%s.%s' % (fname, ext)
@classmethod
def global_config(cls, key, *args):
''' This reads or sets the global settings stored in class.settings. '''
if args:
cls.settings = cls.settings.copy() # Make settings local to class
cls.settings[key] = args[0]
else:
return cls.settings[key]
def prepare(self, **options):
""" Run preparations (parsing, caching, ...).
It should be possible to call this again to refresh a template or to
update settings.
"""
raise NotImplementedError
def render(self, *args, **kwargs):
""" Render the template with the specified local variables and return
a single byte or unicode string. If it is a byte string, the encoding
must match self.encoding. This method must be thread-safe!
Local variables may be provided in dictionaries (*args)
or directly, as keywords (**kwargs).
"""
raise NotImplementedError
class MakoTemplate(BaseTemplate):
def prepare(self, **options):
from mako.template import Template
from mako.lookup import TemplateLookup
options.update({'input_encoding':self.encoding})
options.setdefault('format_exceptions', bool(DEBUG))
lookup = TemplateLookup(directories=self.lookup, **options)
if self.source:
self.tpl = Template(self.source, lookup=lookup, **options)
else:
self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
_defaults = self.defaults.copy()
_defaults.update(kwargs)
return self.tpl.render(**_defaults)
class CheetahTemplate(BaseTemplate):
def prepare(self, **options):
from Cheetah.Template import Template
self.context = threading.local()
self.context.vars = {}
options['searchList'] = [self.context.vars]
if self.source:
self.tpl = Template(source=self.source, **options)
else:
self.tpl = Template(file=self.filename, **options)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
self.context.vars.update(self.defaults)
self.context.vars.update(kwargs)
out = str(self.tpl)
self.context.vars.clear()
return out
class Jinja2Template(BaseTemplate):
def prepare(self, filters=None, tests=None, **kwargs):
from jinja2 import Environment, FunctionLoader
if 'prefix' in kwargs: # TODO: to be removed after a while
raise RuntimeError('The keyword argument `prefix` has been removed. '
'Use the full jinja2 environment name line_statement_prefix instead.')
self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
if filters: self.env.filters.update(filters)
if tests: self.env.tests.update(tests)
if self.source:
self.tpl = self.env.from_string(self.source)
else:
self.tpl = self.env.get_template(self.filename)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
_defaults = self.defaults.copy()
_defaults.update(kwargs)
return self.tpl.render(**_defaults)
def loader(self, name):
fname = self.search(name, self.lookup)
if not fname: return
with open(fname, "rb") as f:
return f.read().decode(self.encoding)
class SimpleTALTemplate(BaseTemplate):
''' Deprecated, do not use. '''
def prepare(self, **options):
depr('The SimpleTAL template handler is deprecated'\
' and will be removed in 0.12')
from simpletal import simpleTAL
if self.source:
self.tpl = simpleTAL.compileHTMLTemplate(self.source)
else:
with open(self.filename, 'rb') as fp:
self.tpl = simpleTAL.compileHTMLTemplate(tonat(fp.read()))
def render(self, *args, **kwargs):
from simpletal import simpleTALES
for dictarg in args: kwargs.update(dictarg)
context = simpleTALES.Context()
for k,v in self.defaults.items():
context.addGlobal(k, v)
for k,v in kwargs.items():
context.addGlobal(k, v)
output = StringIO()
self.tpl.expand(context, output)
return output.getvalue()
class SimpleTemplate(BaseTemplate):
blocks = ('if', 'elif', 'else', 'try', 'except', 'finally', 'for', 'while',
'with', 'def', 'class')
dedent_blocks = ('elif', 'else', 'except', 'finally')
@lazy_attribute
def re_pytokens(cls):
''' This matches comments and all kinds of quoted strings but does
NOT match comments (#...) within quoted strings. (trust me) '''
return re.compile(r'''
(''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types)
|'(?:[^\\']|\\.)+?' # Single quotes (')
|"(?:[^\\"]|\\.)+?" # Double quotes (")
|'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (')
|"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (")
|\#.* # Comments
)''', re.VERBOSE)
def prepare(self, escape_func=html_escape, noescape=False, **kwargs):
self.cache = {}
enc = self.encoding
self._str = lambda x: touni(x, enc)
self._escape = lambda x: escape_func(touni(x, enc))
if noescape:
self._str, self._escape = self._escape, self._str
@classmethod
def split_comment(cls, code):
""" Removes comments (#...) from python code. """
if '#' not in code: return code
#: Remove comments only (leave quoted strings as they are)
subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0)
return re.sub(cls.re_pytokens, subf, code)
@cached_property
def co(self):
return compile(self.code, self.filename or '<string>', 'exec')
@cached_property
def code(self):
stack = [] # Current Code indentation
lineno = 0 # Current line of code
ptrbuffer = [] # Buffer for printable strings and token tuple instances
codebuffer = [] # Buffer for generated python code
multiline = dedent = oneline = False
template = self.source or open(self.filename, 'rb').read()
def yield_tokens(line):
for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)):
if i % 2:
if part.startswith('!'): yield 'RAW', part[1:]
else: yield 'CMD', part
else: yield 'TXT', part
def flush(): # Flush the ptrbuffer
if not ptrbuffer: return
cline = ''
for line in ptrbuffer:
for token, value in line:
if token == 'TXT': cline += repr(value)
elif token == 'RAW': cline += '_str(%s)' % value
elif token == 'CMD': cline += '_escape(%s)' % value
cline += ', '
cline = cline[:-2] + '\\\n'
cline = cline[:-2]
if cline[:-1].endswith('\\\\\\\\\\n'):
cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr'
cline = '_printlist([' + cline + '])'
del ptrbuffer[:] # Do this before calling code() again
code(cline)
def code(stmt):
for line in stmt.splitlines():
codebuffer.append(' ' * len(stack) + line.strip())
for line in template.splitlines(True):
lineno += 1
line = touni(line, self.encoding)
sline = line.lstrip()
if lineno <= 2:
m = re.match(r"%\s*#.*coding[:=]\s*([-\w.]+)", sline)
if m: self.encoding = m.group(1)
if m: line = line.replace('coding','coding (removed)')
if sline and sline[0] == '%' and sline[:2] != '%%':
line = line.split('%',1)[1].lstrip() # Full line following the %
cline = self.split_comment(line).strip()
cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0]
flush() # You are actually reading this? Good luck, it's a mess :)
if cmd in self.blocks or multiline:
cmd = multiline or cmd
dedent = cmd in self.dedent_blocks # "else:"
if dedent and not oneline and not multiline:
cmd = stack.pop()
code(line)
oneline = not cline.endswith(':') # "if 1: pass"
multiline = cmd if cline.endswith('\\') else False
if not oneline and not multiline:
stack.append(cmd)
elif cmd == 'end' and stack:
code('#end(%s) %s' % (stack.pop(), line.strip()[3:]))
elif cmd == 'include':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1]))
elif p:
code("_=_include(%s, _stdout)" % repr(p[0]))
else: # Empty %include -> reverse of %rebase
code("_printlist(_base)")
elif cmd == 'rebase':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1]))
elif p:
code("globals()['_rebase']=(%s, {})" % repr(p[0]))
else:
code(line)
else: # Line starting with text (not '%') or '%%' (escaped)
if line.strip().startswith('%%'):
line = line.replace('%%', '%', 1)
ptrbuffer.append(yield_tokens(line))
flush()
return '\n'.join(codebuffer) + '\n'
def subtemplate(self, _name, _stdout, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
if _name not in self.cache:
self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
return self.cache[_name].execute(_stdout, kwargs)
def execute(self, _stdout, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
env = self.defaults.copy()
env.update({'_stdout': _stdout, '_printlist': _stdout.extend,
'_include': self.subtemplate, '_str': self._str,
'_escape': self._escape, 'get': env.get,
'setdefault': env.setdefault, 'defined': env.__contains__})
env.update(kwargs)
eval(self.co, env)
if '_rebase' in env:
subtpl, rargs = env['_rebase']
rargs['_base'] = _stdout[:] #copy stdout
del _stdout[:] # clear stdout
return self.subtemplate(subtpl,_stdout,rargs)
return env
def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
for dictarg in args: kwargs.update(dictarg)
stdout = []
self.execute(stdout, kwargs)
return ''.join(stdout)
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings: TEMPLATES[tpl].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tpl]:
abort(500, 'Template (%s) not found' % tpl)
for dictarg in args[1:]: kwargs.update(dictarg)
return TEMPLATES[tpl].render(kwargs)
mako_template = functools.partial(template, template_adapter=MakoTemplate)
cheetah_template = functools.partial(template, template_adapter=CheetahTemplate)
jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
simpletal_template = functools.partial(template, template_adapter=SimpleTALTemplate)
def view(tpl_name, **defaults):
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result as is.
This includes returning a HTTPResponse(dict) to get,
for instance, JSON with autojson or other castfilters.
'''
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if isinstance(result, (dict, DictMixin)):
tplvars = defaults.copy()
tplvars.update(result)
return template(tpl_name, **tplvars)
return result
return wrapper
return decorator
mako_view = functools.partial(view, template_adapter=MakoTemplate)
cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
simpletal_view = functools.partial(view, template_adapter=SimpleTALTemplate)
###############################################################################
# Constants and Globals ########################################################
###############################################################################
TEMPLATE_PATH = ['./', './views/']
TEMPLATES = {}
DEBUG = False
NORUN = False # If set, run() does nothing. Used by load_app()
#: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
HTTP_CODES = httplib.responses
HTTP_CODES[418] = "I'm a teapot" # RFC 2324
HTTP_CODES[428] = "Precondition Required"
HTTP_CODES[429] = "Too Many Requests"
HTTP_CODES[431] = "Request Header Fields Too Large"
HTTP_CODES[511] = "Network Authentication Required"
_HTTP_STATUS_LINES = dict((k, '%d %s'%(k,v)) for (k,v) in HTTP_CODES.items())
#: The default template used for error pages. Override with @error()
ERROR_PAGE_TEMPLATE = """
%try:
%from bottle import DEBUG, HTTP_CODES, request, touni
%status_name = HTTP_CODES.get(e.status, 'Unknown').title()
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error {{e.status}}: {{status_name}}</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error {{e.status}}: {{status_name}}</h1>
<p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
caused an error:</p>
<pre>{{e.output}}</pre>
%if DEBUG and e.exception:
<h2>Exception:</h2>
<pre>{{repr(e.exception)}}</pre>
%end
%if DEBUG and e.traceback:
<h2>Traceback:</h2>
<pre>{{e.traceback}}</pre>
%end
</body>
</html>
%except ImportError:
<b>ImportError:</b> Could not generate the error page. Please add bottle to
the import path.
%end
"""
#: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
#: request callback, this instance always refers to the *current* request
#: (even on a multithreaded server).
request = LocalRequest()
#: A thread-safe instance of :class:`LocalResponse`. It is used to change the
#: HTTP response for the *current* request.
response = LocalResponse()
#: A thread-safe namespace. Not used by Bottle.
local = threading.local()
# Initialize app stack (create first empty Bottle app)
# BC: 0.6.4 and needed for run()
app = default_app = AppStack()
app.push()
#: A virtual package that redirects import statements.
#: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
ext = _ImportRedirect(__name__+'.ext', 'bottle_%s').module
if __name__ == '__main__':
opt, args, parser = _cmd_options, _cmd_args, _cmd_parser
if opt.version:
_stdout('Bottle %s\n'%__version__)
sys.exit(0)
if not args:
parser.print_help()
_stderr('\nError: No application specified.\n')
sys.exit(1)
sys.path.insert(0, '.')
sys.modules.setdefault('bottle', sys.modules['__main__'])
host, port = (opt.bind or 'localhost'), 8080
if ':' in host:
host, port = host.rsplit(':', 1)
run(args[0], host=host, port=port, server=opt.server,
reloader=opt.reload, plugins=opt.plugin, debug=opt.debug)
# THE END
| Python |
#This script is designed to combine sprites from multiple sources into one image
#Designed for a directory structure.
#Also make sure your sources are consistent in dimensions
import os
import pygame
pygame.init()
def load_dir(dir): return [pygame.image.load(os.path.join(dir,f)) for f in os.listdir(dir)]
sources={}
while True:
src=input("source directory>")
if 'cancel'==src.lower() and len(sources.keys())>1:break
sources[src]=load_dir(src)
while True:
try:os.chdir(input("output directory>"));break
except:continue
imgs=sorted([ sources[key] for key in sources.keys()],key=lambda l:len(l))
assert len(imgs)>1
assert len(imgs[0])>1
spr_size=[imgs[0][0].get_width()*len(imgs),imgs[-1][-1].get_height()]
num_sprites=len(imgs[0])
for i in range(0,num_sprites):
exp=pygame.Surface(spr_size,pygame.SRCALPHA)
exp.fill((255,0,255))
pos=[0,0]
for spr in [img[i] for img in imgs]:
exp.blit(spr,pos)
pos[0]+=spr.get_width()
pygame.image.save(exp,"{:0>4}.png".format(i))
| Python |
#!/usr/bin/python3.2
# coding: utf-8
from __future__ import division, print_function, unicode_literals
import pygame
import json
from engine import *
from data import *
import tile_rpg
def mix(a,b,c):return [c(a[i],b[i]) for i in range(0,len(a))]
def max(a,b):return a if a>b else b
def min(a,b):return a if a<b else b
def or_none_key(a,k):
if k in a.keys():return a[k]
return None
def surf_slice(s,r):
ret=pygame.Surface(r[2:])
ret.blit(s,[0]*2,r)
return ret
class RosterView(Task):
padding=5
seperation=10
c=pygame.time.Clock()
input_fr=100
animate_fr=100
animation_duration=750
def __init__(self,game,trainer_card):
Task.__init__(self,game)
self.stats={}
for status in ['normal','none','paralyzed','poison','burn']:
self.stats[status]=sidechain(transparent,game.graphics[key_from_path('ball_stats',status)].copy())
self.card=trainer_card
self.party=[trainer_card['storage'][id] for id in trainer_card['roster']]
self.bg=game.pictures['rosterviewbg'].copy()
self.cursor_gfx=game.pictures['ball_cursor']
l=[p for p in self.party]+[None]*(6-len(self.party))
self.items=[self.make_item(pkmn) for pkmn in l]
self.threads=[self.paint_bg,self.move,self.paint_items]
self.cursor=0
self.time_elapsed=0
self.item_opacity=0
self.alpha_step=int(self.animate_fr/self.animation_duration*255)
def paint_bg(self):
ball_position=[20,270]
self.game.surf.blit(self.bg,(0,0))
pk_list=[pk for pk in self.party]+([None]*(6-len(self.party)))
status_list=[(or_none_key(pkmn,'status') or 'normal') if pkmn else 'none' for pkmn in pk_list]
for i,status in enumerate(status_list):
if i==self.cursor:
self.game.surf.blit(self.cursor_gfx,mix(ball_position,(12,12),lambda a,b:a-b))
self.game.surf.blit(self.stats[status],ball_position)
ball_position[0]+=48
def paint_items(self):
default=[20,20]
position=default[:]
surf_list=[item['inactive'] for item in self.items[:self.cursor]]
surf_list=surf_list+[self.items[self.cursor]['active']]
surf_list=surf_list+[item['inactive'] for item in self.items[self.cursor+1:]]
h_limit=default[1]
h_limit+=3*(surf_list[0].get_height()+self.padding)
for surf in surf_list:
self.game.surf.blit(surf,position)
position[1]+=surf.get_height()+self.padding
if position[1]+surf.get_height() > h_limit:
position[1]=default[1]
position[0]+=self.seperation+surf.get_width()
def move(self):
upper_bound=len(self.party)
self.time_elapsed+=self.c.tick()
if self.time_elapsed>=self.input_fr:
for k,v in {pygame.K_UP:-1,pygame.K_DOWN:1}.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.time_elapsed=0
if pygame.K_RETURN in self.game.just_pressed:
self.threads=[self.paint_bg,self.scroll,self.paint_summary]
elif pygame.K_BACKSPACE in self.game.just_pressed:
self.terminate()
def scroll(self):
upper_bound=len(self.party)
self.time_elapsed+=self.c.tick()
if self.time_elapsed>=self.input_fr:
for k,v in {pygame.K_LEFT:-1,pygame.K_RIGHT:1}.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.time_elapsed=0
if pygame.K_BACKSPACE in self.game.just_pressed:
self.threads=[self.paint_bg,self.move,self.paint_items]
def paint_summary(self):
sprite_dimensions=[96,96]
padding=[2,4]
pos=[20,40]
col=(255,0,0)
r=pos+mix(mix(padding,[2,2],lambda a,b:a*b),sprite_dimensions,lambda a,b:a+b)
self.game.surf.fill(col,r)
r=mix(pos,padding,lambda a,b:a+b)
pos=[96,0]+sprite_dimensions
self.game.surf.blit(self.game.sprites[key_from_path('pokemon',self.party[self.cursor]['species'])],r,pos)
def make_item(self,data):
r={}
r['active']=self.game.pictures['rosterviewhl'].copy()
r['inactive']=self.game.pictures['rosterviewpk'].copy()
if data:
ICON_POS=(5,10)
TEXT_POS=(40,5)
r['icon']=self.game.sprites[key_from_path('pokemon','icons',data['species'])].copy()
r['sprite']=sidechain(transparent,self.game.sprites[key_from_path('pokemon',data['species'])].copy())
language='English'
text=data['name'] or self.game.pkdx[data['species']]['name'][language]
w=r['inactive'].get_width()-TEXT_POS[0]
w-=w%16
r['text']=self.game.fonts[self.game.font_table['main']].render(w,text)
r['active'].blit(r['icon'],ICON_POS)
r['inactive'].blit(r['icon'],ICON_POS)
r['active'].blit(r['text'],TEXT_POS)
r['inactive'].blit(r['text'],TEXT_POS)
for surf in [r[k] for k in ['active','inactive']]:transparent(surf)
return r
class PokedexView(Task):
def __init__(self,game,card):
Task.__init__(self,game)
self.species,self.card=[],card
pkdx=card['pokedex']
l=[k for k in card['pokedex'].keys()]
for id,species in game.pkdx.items():
self.species.append({'type':pkdx[id]if id in l else -1,'id':id,'info':species})
self.threads=[self.once]
def once(self):
for species in self.species:
if species['type']==-1:print("???")
elif species['type']==0:print("Seen:",species['info']['name'][self.card['language']])
elif species['type']==1:print("Caught:",species['info']['name'][self.card['language']])
self.terminate()
class OverworldMenu(Task):
width=195
border_width=5
bg_color=(40,50,100,180)
border_color=(240,245,255)
icon_size=[32,32]
icon_rotate_r=(-30.0,30.0)
icon_rotate_i=0.0
rot_dir=2.0
ir_rate=10
ir_elapse=0
irt=pygame.time.Clock()
item_padding=16
adjust_cursor=(32,0)
items=[
'pkdx',
'roster',
'bag',
'card',
'settings',
'cancel'
]
key_mappings={
pygame.K_UP:-1,
pygame.K_DOWN:1
}
ct=pygame.time.Clock()
cfr=150
ct_elapse=0
def __init__(self,game,save):
Task.__init__(self,game)
height=game.surf.get_height()
self.save=save
self.open=False
self.icon_rotated=self.icon_rotate_i
self.cursor=0
item_values={
'pkdx':'Pokedex',
'roster':'Roster',
'bag':'Bag',
'card':save['card']['name'],
'settings':'Options',
'cancel':'Cancel'
}
for i in range(0,len(self.items)):
text=self.items[i][:]
self.items[i]={
'text':text,
'surf':game.fonts[game.font_table['menu']].render(self.width-(self.width%16),item_values[text])
}
self.bg=pygame.Surface((self.width+self.border_width,height),flags=pygame.SRCALPHA)
self.bg.fill(self.bg_color,(self.border_width,0,self.width,height))
pygame.draw.rect(self.bg,self.border_color,(0,0,self.border_width,height))
self.pos=(game.surf.get_width()-self.width-self.border_width,0)
self.threads=[self.paint_bg,self.paint_items,self.close_ctl,self.cur_ctl,self.sel_ctl]
aicon_src=[self.icon_size[0],0]
iicon_src=[0,0]
if self.save['card']['gender']=='f':
aicon_src[0]+=self.icon_size[0]
iicon_src[0]+=self.icon_size[0]
self.aicon_src,self.iicon_src=aicon_src,iicon_src
def paint_bg(self):self.game.surf.blit(self.bg,self.pos,None,pygame.BLEND_RGBA_ADD)
def hide_menu(self):
self.open=False
self.threads=[self.paint_bg,self.paint_items,self.close_ctl,self.cur_ctl,self.sel_ctl]
def close_ctl(self):
if pygame.K_BACKSPACE in self.game.just_pressed:self.hide_menu()
def cur_ctl(self):
self.ct_elapse+=self.ct.tick()
upper_bound=len(self.items)
if self.ct_elapse>=self.cfr:
for k,v in self.key_mappings.items():
if self.game.pressed[k]:
self.cursor+=v
while self.cursor>=upper_bound:self.cursor-=upper_bound
while self.cursor<0:self.cursor+=upper_bound
self.ct_elapse=0
self.icon_rotated=self.icon_rotate_i
def paint_items(self):
pos=[self.game.surf.get_width()-self.width+self.border_width,0]
self.ir_elapse+=self.irt.tick()
if self.ir_elapse>=self.ir_rate:
self.ir_elapse=0
self.icon_rotated+=self.rot_dir
if self.icon_rotated>=self.icon_rotate_r[1] or self.icon_rotated<=self.icon_rotate_r[0]:self.rot_dir*=-1
for surf,text in [(a['surf'],a['text']) for a in self.items]:
active=surf is self.items[self.cursor]['surf']
i_src=(self.aicon_src if active else self.iicon_src)+self.icon_size
icon=surf_slice(self.game.sprites[key_from_path('menu',text)],i_src)
transparent(icon)
if active:icon=pygame.transform.rotate(icon,self.icon_rotated)
transparent(icon)
pos[1]+=self.item_padding
sh,ih=surf.get_height(),self.icon_size[1]
h=max(sh,ih)
if ih>=sh:
t_pos=mix(pos,(icon.get_width(),int((ih-sh)/2)),lambda a,b:a+b)
self.game.surf.blit(icon,pos)
self.game.surf.blit(surf,t_pos)
else:
t_pos=mix(pos,(icon.get_width(),0),lambda a,b:a+b)
i_pos=mix(pos,(0,0),lambda a,b:a+b)
self.game.surf.blit(icon,pos)
self.game.surf.blit(surf,t_pos)
pos[1]+=h
def sel_ctl(self):
if pygame.K_RETURN in self.game.just_pressed:
v=self.items[self.cursor]['text'].lower()
if v=='cancel':
self.hide_menu()
elif v=='roster':
self.game.register_task(Callback(self,RosterView(self.game,self.save['card'])))
elif v=='pkdx':
self.game.register_task(Callback(self,PokedexView(self.game,self.save['card'])))
class Overworld(Task):
def __init__(self,game,save):
Task.__init__(self,game)
self.threads=[self.paint_bg,self.open_menu]
self.player_data=save
self.menu=OverworldMenu(game,save)
def open_menu(self):
if self.menu.open:self.menu()
else: self.menu.open=pygame.K_RETURN in self.game.just_pressed
def paint_bg(self):self.game.surf.fill([self.frame%256]*3)
class Intro(Task):
def __init__(self, game):
Task.__init__(self, game)
self.bg = game.pictures["titlescreen"]
self.b_bg = self.bg.convert_alpha()
self.f_bg = self.bg.convert_alpha()
self.threads = [self.paint, self.check_keys]
self.menu = tile_rpg.Menu(game, 80, [(save['card']['name'],save) for save in game.saves.values()]+[("Cancel",None)])
def paint(self):self.game.surf.blit(self.bg, (0, 0))
def check_keys(self):
if pygame.K_RETURN in self.game.just_pressed:
self.menu.reset()
self.threads = [ self.paint, self.menu, self.load_games]
self.game.just_pressed = []
def load_games(self):
if not self.menu.open:
if self.menu.value is not None:
ow=Overworld(self.game, self.menu.value)
self.game.register_task(FadeOut(self.game,25,ow,5,(255,255,255)))
self.terminate()
else:
self.menu.open = False
self.threads = [ self.paint, self.check_keys]
class PyPokemon(Game):
maps = Cache("maps", json.load)
tilesets = Cache("tilesets",load_trans_image,['r+b'])
sprites = Cache("sprites", load_trans_image,['r+b'])
pkdx = load_data('species', json.load)
saves = load_data('saves', json.load)
info = load_data("info", json.load)
graphics = Cache("graphics",load_trans_image,['r+b'])
pictures = Cache("images", pygame.image.load,['r+b'])
fonts = load_data("fonts", load_font,'r+b')
tileset_data = Cache("tilesets data",json.load)
npc_types=Cache("trainers")
res,center=(480,320),(480/16/2,320/16/2)
def __init__(self):
Game.__init__(self, self.res)
self.font_table = { 'main':'rainhearts', 'menu':'fontwestern'}
self.register_task(Intro(self))
if __name__ == "__main__": run(PyPokemon())
| Python |
#Script used to Convert a spritesheet
#Into several sprite files
#Into their own directory
import os
import pygame
pygame.init()
src=None
while not src:
try:src=pygame.image.load(input("input filename> "))
except:pass
name=input("output directory> ")
try:os.mkdir(name)
except:pass
try:os.chdir(name)
except:pass
spr_size,pos,cur=[int(input("Sprite width> ")),int(input("Sprite height>"))],[0]*2,0
if spr_size[1]<0:spr_size[1]=spr_size[0]
while pos[1]<src.get_height():
cur+=1
export=pygame.Surface(spr_size,pygame.SRCALPHA)
export.fill((255,0,255,1))
export.blit(src,(0,0),pos+spr_size)
pygame.image.save(export,"{:0>4}.png".format(cur))
pos[0]+=spr_size[0]
if pos[0]>=src.get_width():pos=[0,pos[1]+spr_size[1]]
| Python |
import pygame
import random
random.seed()
from engine import*
def mix(a,b,c):return [c(a[i],b[i]) for i in range(0,len(a))]
def lookup(a, x, y, w, h, z):
if 0 <= x < w and 0 <= y < h:return a[x+y*w]
return z
def dualiter(w, h):
for y in range(h):
for x in range(w):yield x, y
class NPC(Task,pygame.Surface):
move_down = 0
move_up = 1
move_left = 2
move_right = 3
walk_frame = 0
faceing = 0
transport_mode = 0
layer = 0
frame_rate=100
def __init__(self, game, npc_type,gender=None):
data=game.npc_types[key_from_path(npc_type)]
Task.__init__(self, game)
self.timer = pygame.time.Clock()
self.movement_timer=pygame.time.Clock()
self.data=data
self.gender = gender or random.choice(['m','f'])
self.name = random.choice(data['names'][self.gender])
self.win,self.loose=data['win'],data['loose']
self.input_rate,self.input_elapsed=int(data['movement']*1000),0#Convert data['movement'] from seconds to milliseconds
self.type=data['name']
self.src = self.game.sprites[key_from_path("NPC","{}_{}".format(self.gender,self.type))]
assert self.src.get_height()%9 == 0 and self.src.get_width()%16 == 0 and self.src.get_width()>=16
pygame.Surface.__init__(self,(self.src.get_width(), self.src.get_height()//9))
transparent(self,(255,0,255))
self.src_frame = [0, 0, self.get_width(), self.get_height()]
self.threads=[self.check_moving,self.generate_movement]
self.pos=[0]*6
self.ow=None
self.update()
def generate_movement(self):
if self.input_rate>0:
self.input_elapsed+=self.movement_timer.tick()
if self.input_elapsed>=self.input_rate:
while self.input_elapsed>=self.input_rate:self.input_elapsed-=self.input_rate
self.get_movement()
def get_movement(self):
if random.choice(([True]*random.randint(1,5))+([False]*random.randint(1,5))):
self.set_faceing(random.choice([self.move_left,self.move_right,self.move_up,self.move_down]))
if random.choice(([True]*random.randint(4,10))+([False]*random.randint(3,7))):
self.move(self.faceing)
def check_moving(self):
if self.is_moving():self.threads=[self.time_movement,self.generate_movement]
def progress_step(self):
self.steps-=1
dir = self.faceing
if dir==self.move_up:self.pos[5]-=1
elif dir==self.move_left:self.pos[4]-=1
elif dir==self.move_right:self.pos[4]+=1
else:self.pos[5]+=1
if not self.can_move():self.steps=0
self.set_faceing(self.faceing)
def set_faceing(self,dir):
self.faceing=dir
self.walk_frame=-1
self.src_frame[1]=(self.faceing if self.faceing!=self.move_right else self.move_left)*self.get_height()
self.dest = [self.pos[4]*16-int((self.get_width()-16)/2),self.pos[5]*16-(self.get_height()-16)]
self.paint()
if self.is_moving():self.update()
def move(self, dir):
if dir!=self.faceing and not self.is_moving():self.set_faceing(dir)
elif self.can_move():self.steps+=1
def can_move(self):
pos = self.pos[-3:]
dir = self.faceing
map=self.ow.map.map
if dir == self.move_right:pos[1]+=1
elif dir == self.move_left:pos[1]-=1
elif dir == self.move_up:pos[2]-=1
else:pos[2]+=1
if pos[1] < 0 or pos[1] >= map.struct.size[0]:return False
elif pos[2] < 0 or pos[2] >= map.struct.size[1]:return False
if len([a for a in self.ow.NPCs+[self.ow.player] if a.pos[4]==pos[1] and a.pos[5]==pos[2]])>0:return False
if map.movement_type(*pos) != self.transport_mode: return False
return True
def paint(self):
self.fill(self.get_colorkey())
if self.faceing==self.move_right:
self.blit(pygame.transform.flip(self.src,True,False),(0,0),self.src_frame)
else:self.blit(self.src,(0,0),self.src_frame)
def walk(self):
dir = self.faceing
self.walk_frame+=1
if self.walk_frame>=2:self.progress_step()
else:
if dir==self.move_right:self.src_frame[1]=3+self.move_left*2+self.walk_frame
else:self.src_frame[1]=3+dir*2+self.walk_frame
self.src_frame[1]*=self.get_height()
self.paint()
if dir==self.move_left:self.dest[0]-=5
elif dir==self.move_right:self.dest[0]+=5
elif dir==self.move_up:self.dest[1]-=5
elif dir==self.move_down:self.dest[1]+=5
def is_moving(self):return self.steps>0
def update(self):
self.steps=0
self.time_elapsed=0
self.set_faceing(self.faceing)
def time_movement(self):
if self.is_moving():
self.time_elapsed+=self.timer.tick()
if self.time_elapsed>=self.frame_rate:
while self.time_elapsed>=self.frame_rate:self.time_elapsed-=self.frame_rate
self.walk()
else:self.threads=[self.check_moving,self.generate_movement]
class Menu(Task,pygame.Surface):
h_padding, w_padding = 2,4
cursor = 0
pos = 0
value = None
def __init__(self, prev, width, items):
Task.__init__(self,prev)
self.open = False
font = self.game.fonts[ self.game.font_table['menu']]
self.items = items
self.items_surf = [font.render(width, label) for label, data in self.items]
height = sum([item.get_height() for item in self.items_surf])
self.threads = [self.show, self.paint]
pygame.Surface.__init__(self,(width+(2*self.w_padding),height+self.h_padding))
self.update()
def reset(self):
self.open = True
self.threads = [self.show,self.paint]
self.pos = 0
self.value = None
def update(self):
self.fill((255,255,255))
pos = [self.w_padding, 0, self.get_width(), 0]
for indice, item in enumerate(self.items_surf):
pos[3] = item.get_height()
if indice == self.cursor:self.fill((255,0,255), pos)
self.blit(item,pos)
pos[1]+= item.get_height()
def paint(self): self.game.surf.blit(self, (0, self.pos-self.get_height()))
def show(self):
max=self.get_height()
if self.pos < max: self.pos += 4
if self.pos>=max:
self.pos=self.get_height()
self.threads = [ self.handle_input, self.paint]
def hide(self):
if 0 < self.pos: self.pos -= 4
else:
self.open=False
self.threads = [ self.handle_input, self.paint]
def handle_input(self):
if pygame.K_BACKSPACE in self.game.just_pressed:
self.threads = [ self.hide, self.paint]
elif pygame.K_DOWN in self.game.just_pressed:
self.cursor = 0 if self.cursor == len( self.items) else self.cursor + 1
self.update()
elif pygame.K_UP in self.game.just_pressed:
self.cursor = len(self.items) -1 if self.cursor == 0 else self.cursor - 1
self.update()
elif pygame.K_RETURN in self.game.just_pressed:
self.value = self.items[self.cursor][1]
self.threads = [ self.hide, self.paint]
self.game.just_pressed = []
class Map:
def __init__(self,ts_db,ts_dat_db,data):
self.struct = Struct(data if isinstance(data,dict) else game.maps[data])
self.tileset = {'img':ts_db[self.struct.tileset],'dat':ts_dat_db[self.struct.tileset]}
self.tile_frame = 0
self.num_frames = int(self.tileset['img'].get_width()/16)
def movement_type(self,z,x,y):return self.tileset['dat'][self.struct.data[z][y*self.struct.size[0]+x]]
def adjust_tile_frame(self,n_frame):
self.tile_frame+=n_frame
while self.tile_frame>=self.num_frames:self.tile_frame-=self.num_frames
def get_tile(self,x,y):return self.struct.data[0][y*self.struct.size[0]+x]
def render(self):
w = self.struct.size[0]*16
ret = pygame.Surface((w,self.struct.size[1]*16))
for layer in self.struct.data:
dest = [0,0]
for tile in [[self.tile_frame*16,t_number*16,(self.tile_frame+1)*16,(t_number+1)*16] for t_number in layer]:
ret.blit(self.tileset['img'],dest,tile)
dest[0]+=16
if dest[0]>=w:dest=[0,dest[1]+16]
return ret
def adjust_size(self,w,h,t=0):
size = [self.struct.size[0]+w,self.struct.size[1]+h]
assert size[0]>0 and size[1]>0
if w!=0:
self.struct.data[0]=[lookup(self.struct.data[0],x,y,self.struct.size[0],self.struct.size[1],t) for x, y in dualiter(*size)]
if h<0:
self.struct.data[0]=self.struct.data[0][:(self.struct.size[1]+h)*self.struct.size[0]]
elif h>0:
self.struct.data[0]=self.struct.data[0]+[t]*self.struct.size[0]
self.struct.size=size
class MapViewer(Task,pygame.Surface):
frame_rate = 800
c = pygame.time.Clock()
def __init__(self,game,map_obj,width=None,target=None):
Task.__init__(self,game)
pygame.Surface.__init__(self,(width or game.surf.get_width(),game.surf.get_height()))
self.map,self.target = map_obj,target or game.surf
self.center = [int(self.get_width()/2),int(self.get_height()/2)]
self.camera = [int(self.map.struct.size[0]/2),int(self.map.struct.size[1]/2)]
self.time_elapsed=0
self.pos=[0,0]
self.threads=[self.update,self.paint]
self.map_dest=[(self.center[0]-self.camera[0])*16,(self.center[1]-self.camera[1])*16]
def set_camera(self,cam,check=False):
img=self.map.render()
if check:
if cam[0]<0 or cam[0]>=img.get_width():cam[0]=self.camera[0]
if cam[1]<0 or cam[1]>=img.get_height():cam[1]=self.camera[1]
self.camera = cam
self.map_dest=mix(self.center,self.camera,lambda a,b:a-b)
self.fill([255]*3)
self.blit(img,self.map_dest)
def adjust_camera(self,x,y,check=False):
img=self.map.render()
cam=[self.camera[0]+x,self.camera[1]+y]
if check:
if cam[0]<0 or cam[0]>=img.get_width():cam[0]=self.camera[0]
if cam[1]<0 or cam[1]>=img.get_height():cam[1]=self.camera[1]
self.camera = cam
self.map_dest=mix(self.center,self.camera,lambda a,b:a-b)
self.fill([255]*3)
self.blit(img,self.map_dest)
def set_tile(self,x,y,tile):
try:
self.map.struct.data[0][y*self.map.struct.size[0]+x]=tile
self.paint_map()
except:pass
def paint_map(self):
while self.time_elapsed>=self.frame_rate:self.time_elapsed-=self.frame_rate
self.fill([255]*3)
self.blit(self.map.render(),self.map_dest)
def update(self):
self.time_elapsed+=self.c.tick()
if self.time_elapsed >= self.frame_rate:
self.map.adjust_tile_frame(1)
self.paint_map()
def paint(self): self.target.blit(self,self.pos) | Python |
from engine import Task,ThreadedTask,Runner,EventHandler
from sdlengine import Period,load_font,Period,AnimationFromGenerator,SDLEngine as Engine,load_trans_image,transparent
from threading import Thread
from integrate import load_dict
import pygame,os,json
from data import Cache
from math import floor
import random;random.seed()
GLOBAL_DEBUG=True
#GLOBAL_DEBUG=False
def combine(a,b,c):return [c(a[i],b[i]) for i in range(0,len(a))]
def sizedrangepoint(l,m,p):return l[p+1-m:p+1] if p+1>=m else l[:p+1]
def formula(r,a):
for i in r:yield a(i)
def quit_on_backspace(o):return (lambda ev:o.stop() if ev.key==pygame.K_BACKSPACE else None)
def trykey(o,k,d):
try:return o[k]
except (KeyError,IndexError):return d
def trykeys(o,*k,d=None):
for key in k:
try:return o[key]
except(KeyError,IndexError):pass
return d
def listdir(path):
return [ fn for v in [[ os.path.join(*b) for b in [ (a[0], c) for c in a[2]]] for a in [ [r,d,f] for r,d,f in os.walk(path)]] for fn in v]
def fn_tokey(fn):return fn[:fn.rfind('.')].lower()
def ensure_list(a):return a if hasattr(a,'__len__') else [a]
def symmetrical(a):
r=[i for i in a]
return r+r[::-1]
def padding(container,padding,position):
inner,outer=combine(container,padding,lambda a,b:a-(2*b)),container
return (position+outer),(combine(position,padding,lambda a,b:a+b)+inner)
def link_tasks(o,*t):
for task in t:
o.connect_signal('start',task.start)
o.connect_signal('stop',task.stop)
class OwnedTimer(Task):
def __init__(self,owner,rate,engine=None):
Task.__init__(self,engine or owner.engine)
self.timer=Period(rate)
self.connect_signal('start',self.timer.reset)
self.connect_signal('post-elapse',self.timer.reset)
self.connect_signal('frame',lambda:self.elapse() if self.timer.elapsed else None)
link_tasks(owner,self)
@EventHandler.Signal('elapse')
def elapse(self):self.timer.reset()
class FlowControl(Task):
def __init__(self,engine,end,*intros):
Task.__init__(self,engine)
self.connect_signal('start',intros[0].start)
for i in range(0,len(intros)):
intros[i].connect_signal('stop',trykey(intros,i+1,end).start)
end.connect_signal('start',self.stop)
class MultiLauncher(EventHandler):
def __init__(self,*tasks):
EventHandler.__init__(self)
self.connect_signal('start',*[t.start for t in tasks])
self.connect_signal('start',self.stop)
@property
def running(self):return False
class ScreenItem(pygame.Surface,Task):
def __init__(self,engine,dimensions,flags=0,position=[0,0],frame=None,bf=0):
Task.__init__(self,engine)
pygame.Surface.__init__(self,dimensions,flags)
self.blit_flags,self.blit_frame,self.blit_position=bf,frame,position
self.connect_signal('frame',self.paint)
self.connect_signal('start',self.update)
self.fill((255,0,255))
transparent(self)
@EventHandler.Signal('paint')
def update(self):pass
def paint(self):self.engine.surf.blit(self,self.blit_position,self.blit_frame,self.blit_flags)
class ScreenItemCopy(ScreenItem):
def __init__(self,engine,surf,size=None,position=[0,0],frame=None,bf=0):
ScreenItem.__init__(self,engine,size or surf.get_size(),surf.get_flags(),position,frame,bf)
self.connect_signal('paint',lambda:self.blit(self.__source_surface__,(0,0)))
self.__source_surface__=surf
class TextBox(ScreenItem):
main_line=0
lines_displayed=3
padding=[10,5]
def __init__(self,engine,text):
font=engine.textbox_font
screen=engine.resolution[:]
total_size=[screen[0],font.char_height*self.lines_displayed+self.padding[1]*2]
ScreenItem.__init__(self,engine,total_size,position=(0,screen[1]-total_size[1]))
self.text_area=combine(self.padding+total_size,[0,0]+self.padding,lambda a,b:a-(2*b))
self.text_lines=font.render_lines(font.trim_width(self.text_area[2]),text)
self.width_step=None
self.connect_signal('paint',lambda:self.fill([255]*3),lambda:self.fill([0]*3,self.text_area))
self.__revealed_area__=[0,0,0,font.char_height]
self.connect_signal('start',self.reset_position)
self.connect_signal('frame',self.paint_text)
self.connect_signal(pygame.KEYDOWN,self.on_keydown)
@property
def is_done(self):
return self.main_line>=len(self.text_lines)
@property
def active_lines(self):
return sizedrangepoint(self.text_lines,self.lines_displayed,self.main_line)
@property
def waiting_for_key(self):
if self.is_done:return True
return self.width_step.complete
def reset_position(self):
self.main_line=-1
self.advance_line()
@EventHandler.Signal('advance-line')
def advance_line(self):
self.__revealed_area__[2]=0
self.main_line+=1
if self.main_line>=len(self.text_lines):
self.stop()
else:
self.width_step=AnimationFromGenerator(10,range(0,self.text_lines[self.main_line].get_width(),2))
self.width_step.accelerate_rate=4
def line_area(self,line):
if line is self.text_lines[self.main_line]:
self.__revealed_area__[2]=self.width_step.value
return self.__revealed_area__
return [0,0]+[line.get_width(),line.get_height()]
def on_keydown(self,event):
if self.waiting_for_key and event.key==pygame.K_RETURN:
self.advance_line()
elif event.key==pygame.K_SPACE:
self.width_step.accelerate=True
def paint_text(self):
pos=self.text_area[:2]
for line,rect in [(surf,self.line_area(surf)) for surf in self.active_lines]:
self.blit(line,pos,rect)
pos[1]+=line.get_height()
class Menu(EventHandler):
def __init__(self,items):
EventHandler.__init__(self)
self.__pos__,self.items,self.value=0,tuple(items),None
self.connect_signal('select',self.stop)
self.connect_signal('start',self.reset)
def reset(self):self.value=None
@EventHandler.Signal('select')
def select(self):self.value=self.items[self.position]
@EventHandler.Signal('go-up')
def go_up(self):self.position-=1
@EventHandler.Signal('go-down')
def go_down(self):self.position+=1
@property
def running(self):return self.value is not None
@property
def position(self):return self.__pos__
@position.setter
@EventHandler.Signal('position-change')
def position(self,value):
self.__pos__=value
il=len(self.items)
while self.__pos__>=il:self.__pos__-=il
while self.__pos__<0:self.__pos__+=il
class TrainerCardView(ScreenItem):
def __init__(self,engine,card):
self.card=card
ScreenItem.__init__(self,engine,engine.resolution)
self.connect_signal(pygame.KEYDOWN,quit_on_backspace(self))
self.connect_signal('paint',lambda:self.fill((200,200,225)))
self.connect_signal('post-paint',self.paint_fields)
def paint_fields(self):
card=self.card
font=self.engine.main_font
sprite='trainer::'+card['class'].lower()
sprite=trykeys(self.engine.sprites,sprite,sprite+"::"+card['gender'])
self.blit(sprite,(0,0))
field_width=300
field_pos=[sprite.get_width(),0]
fields=[
card['name'],
"Class: "+card['class'].title(),
"Pokedex: "+str(len(card['pokedex'])),
"Money: $"+str(card['money'])
]
for field in fields:
surf=font.render_lines(font.trim_width(field_width),field)[0]
self.blit(surf,field_pos)
field_pos[1]+=surf.get_height()+5#5=padding between fields.
emblem_pos,emblem_padding=[0,sprite.get_height()],8
for emblem in ["rosario"]*20 if GLOBAL_DEBUG else card['emblems']:
surf=self.engine.sprites['emblems::'+emblem]
self.blit(surf,emblem_pos)
emblem_pos[0]+=surf.get_width()+emblem_padding
if emblem_pos[0]+surf.get_width()>=self.get_width():
emblem_pos=[0,emblem_pos[1]+surf.get_height()+emblem_padding]
class BagView(ScreenItem):
def __init__(self,engine,card):
ScreenItem.__init__(self,engine,engine.resolution)
font=engine.main_font
field_width=font.trim_width(200)
def create_item(name,quantity):
return {
'name':name,
'quantity':quantity,
'icon':trykey(engine.sprites,'item::'+name,engine.sprites['item::none']),
'text':font.render_lines(field_width,name+" x"+str(quantity))[0]
}
items=[create_item(name,card['bag'][name]) for name in card['bag']]
self.menu=Menu(items)
self.connect_signal("post-paint",self.paint_items)
self.connect_signal(pygame.KEYDOWN,quit_on_backspace(self))
@property
def viewable_items(self):return self.menu.items
def paint_items(self):
pos=[0,0]
for item in self.viewable_items:
ih,th=item['icon'].get_height(),item['text'].get_height()
if ih>th:
self.blit(item['icon'],pos)
self.blit(item['text'],(pos[0]+item['icon'].get_width(),pos[1]+(ih-th)//2))
pos[1]+=ih
else:
self.blit(item['icon'],(pos[0],(th-ih)//2))
self.blit(item['text'],(pos[0]+item['icon'].get_width(),pos[1]))
pos[1]+=th
class RosterView(ScreenItemCopy):
def __init__(self,engine,trainer_card):
ScreenItemCopy.__init__(self,engine,engine.pictures['rosterviewbg'])
self.card=trainer_card
self.party=[trainer_card['storage'][id] for id in trainer_card['roster']]
def get_name(d):
return trykey(d,'name',False) or trykey(d,'species','???')
self.menu=Menu([get_name(pkmn) for pkmn in self.party])
self.active_bg,self.inactive_bg=self.engine.pictures['rosterviewhl'],self.engine.pictures['rosterviewpk']
self.cursor=self.engine.pictures['ball_cursor']
transparent(self.active_bg)
transparent(self.inactive_bg)
font=self.engine.main_font
def create_item(name):
def get_pk(n):
for pk in self.party:
if get_name(pk)==n:return pk
pk=get_pk(name)
r={'icon':None,'text':font.render_lines(font.trim_width(self.active_bg.get_width()),name)[0],'pokemon':pk}
ico_key=trykey(pk,'species','???')
if 'form' in pk:ico_key+='::'+pk['form']
r['icon']=self.engine.sprites['pokemon::icons::'+ico_key]
return r
self.items=[create_item(name) for name in self.menu.items]
self.menu.connect_signal('post-position-change',lambda val:self.update())
self.connect_signal(pygame.KEYDOWN,self.move)
self.connect_signal('post-paint',self.paint_pokemon,self.paint_cursor)
def move(self,event):
if event.key==pygame.K_UP:self.menu.go_up()
elif event.key==pygame.K_RIGHT:self.menu.position+=3
elif event.key==pygame.K_DOWN:self.menu.go_down()
elif event.key==pygame.K_LEFT:self.menu.position-=3
elif event.key==pygame.K_RETURN:self.menu.select()
elif event.key==pygame.K_BACKSPACE:self.stop()
def paint_cursor(self):
def paint_item(item,p):
padding=[11,11]
status='ball_stats::'+((trykey(item['pokemon'],'status',None) or 'normal') if item else 'none')
if item==self.items[self.menu.position]:
self.blit(self.cursor,p)
self.blit(self.engine.graphics[status],combine(p,padding,lambda a,b:a+b))
p[0]+=self.cursor.get_width()
return p
pos=[20,270]
for item in self.items[:]+([None]*(6-len(self.items))):
pos=paint_item(item,pos)
def paint_pokemon(self):
item_padding=[14,8]
icon_pos=[10,20]
key_point=238
def paint_item(item,bg,p):
self.blit(bg,p)
if item:
ico_pos=combine(p,icon_pos,lambda a,b:a+b)
self.blit(item['icon'],ico_pos)
self.blit(item['text'],combine(ico_pos,[item['icon'].get_width()+5,0],lambda a,b:a+b))
p[1]+=self.inactive_bg.get_height()+item_padding[1]
if p[1]+self.inactive_bg.get_height()>=key_point:
p[0]+=self.inactive_bg.get_width()+item_padding[0]
p[1]=self.blit_position[1]+item_padding[1]*2
return p
pos=item_padding[:]
l=[self.inactive_bg]*self.menu.position
l.extend([self.active_bg])
l.extend([self.inactive_bg]*(len(self.items)-1-self.menu.position))
l=[(self.items[i],l[i]) for i in range(0,len(l))]
for item,bg in l:
pos=paint_item(item,bg,pos)
class Pokedex(ScreenItem):
viewable=9*6
def __init__(self,engine,card):
ScreenItem.__init__(self,engine,engine.resolution)
pkdx=self.engine.pkdx
known_species=sorted([k for k in card['pokedex'].keys()],key=lambda sp:pkdx[sp]['id'])
species_list=[None]*pkdx[known_species[-1]]['id']
for species in known_species:
species_list[pkdx[species]['id']-1]=species
self.menu=Menu(species_list)
def create_item(species_name):
return {
'surf':self.engine.sprites['pokemon::icons::'+species_name],
'key':species_name,
'species':pkdx[species_name],
'seen':card['pokedex'][species_name]
}
self.items=dict([(species,create_item(species)) for species in species_list if species])
self.items[None]={'surf':self.engine.sprites['pokemon::icons::none']}
self.menu.connect_signal('post-position-change',lambda ev:self.update())
self.connect_signal(pygame.KEYDOWN,self.exit_gaurd,self.move_cursor)
self.connect_signal('post-paint',self.paint_items)
@EventHandler.Signal('paint')
def update(self):self.fill((230,230,230))
@property
def viewable_items(self):
items=self.menu.items
l=len(items)
p=self.menu.position
m=Pokedex.viewable
if l-p-m>=0:
return items[p:p+m]
else:
return items[p:]+items[:m-(l-p)]
def exit_gaurd(self,event):self.stop() if event.key==pygame.K_BACKSPACE else None
def move_cursor(self,event):
mappings={
pygame.K_RIGHT:1,
pygame.K_LEFT:-1,
pygame.K_UP:-9,
pygame.K_DOWN:9
}
if event.key in mappings:
self.menu.position+=mappings[event.key]
def paint_items(self):
padding,default_pos=[8,8],[0,0]
pos=default_pos[:]
active_bg,inactive_bg,cursor_bg=pygame.Surface((48,48)),pygame.Surface((48,48)),pygame.Surface((48,48))
cursor_bg.fill((200,200,250))
active_bg.fill((200,100,140))
inactive_bg.fill((200,200,200))
once=False
def paint_item(item,bg,pos):
self.blit(bg,pos)
self.blit(item['surf'],combine(pos,padding,lambda a,b:a+b))
for item in self.viewable_items:
data=self.items[item]
bg=active_bg if data.get('seen',0)==1 else inactive_bg
bg=bg if once else cursor_bg
paint_item(data,bg,pos)
w=max(bg.get_width(),data['surf'].get_width()+2*padding[0])
pos[0]+=w
if pos[0]+w>=self.get_width():
pos[1]+=max(bg.get_height(),data['surf'].get_height()+2*padding[1])
pos[0]=default_pos[0]
once=True
class OverWorldMenu(ScreenItem):
icon_rotate_range=range(0,30,1)
icon_size=[32,32]
icon_rotate_rate=5
width=195
border_width=5
bg_color=(40,50,100,180)
border_color=(240,245,255)
menu_items=('pkdx','roster','bag','card','settings','cancel')
def __init__(self,engine,save):
Task.__init__(self,engine)
height=self.engine.resolution[1]
font,width=self.engine.main_font,self.engine.main_font.trim_width(self.width)
def set_bg():
w=self.width+self.border_width
ScreenItem.__init__(self,engine,(w,height),pygame.SRCALPHA,(engine.resolution[0]-w,0))
self.fill(self.bg_color,(self.border_width,0,self.width,height))
pygame.draw.rect(self,self.border_color,(0,0,self.border_width,height))
icon_source=([0,0] if save['card'].get('gender','m')=='m' else [self.icon_size[0],0])+self.icon_size
def create_item(item):
item_values={
'pkdx':'Pokedex',
'roster':'Roster',
'bag':'Bag',
'card':save['card']['name'],
'settings':'Options',
'cancel':'Cancel'
}
ico,a_ico=pygame.Surface(self.icon_size),pygame.Surface(self.icon_size)
ico.blit(self.engine.sprites["menu::"+item],(0,0),icon_source)
a_ico.blit(self.engine.sprites["menu::"+item],(0,0),combine(icon_source,[self.icon_size[0],0,0,0],lambda a,b:a+b))
transparent(ico)
transparent(a_ico)
return {
'surf':font.render_lines(width,item_values[item])[0],
'icon':ico,
'active_icon':a_ico,
'val':item
}
set_bg()
self.save=save
self.items=[create_item(item) for item in self.menu_items]
self.menu=Menu(self.menu_items)
self.icon_rotation=AnimationFromGenerator(self.icon_rotate_rate,symmetrical(self.icon_rotate_range))
self.connect_signal('frame',self.paint_items)
self.connect_signal(pygame.KEYDOWN,self.handle_key)
self.menu.connect_signal('post-select',self.respond)
self.menu.connect_signal('position-change',lambda val:self.icon_rotation.reset())
def handle_key(self,event):
k=event.key
if k==pygame.K_UP:self.menu.go_up()
elif k==pygame.K_DOWN:self.menu.go_down()
elif k==pygame.K_RETURN:self.menu.select()
elif k==pygame.K_BACKSPACE:self.stop()
def paint_items(self):
pos=list(self.blit_position)
pos[0]+=self.border_width
for item in self.items:
ico,s=None,item['surf']
if item['val']==self.menu.items[self.menu.position]:
if self.icon_rotation.complete:self.icon_rotation.reset()
ico=pygame.transform.rotate(item['active_icon'],self.icon_rotation.value)
else:ico=item['icon']
self.engine.surf.blit(ico,pos)
self.engine.surf.blit(s,combine(combine(pos,[ico.get_width(),5],lambda a,b:a+b),[0,ico.get_height()-s.get_height()],lambda a,b:a+(b//2)))
pos[1]+=max([ico.get_height(),s.get_height()])
@EventHandler.Signal('callback')
def callback(self,t):
t.connect_signal('stop',self.start)
t.connect_signal('start',self.stop)
t.start()
def respond(self):
response=self.menu.value
if response=='cancel':
self.stop()
elif response=='roster':
self.callback(RosterView(self.engine,self.save['card']))
elif response=='card':
self.callback(TrainerCardView(self.engine,self.save['card']))
elif response=='bag':
self.callback(BagView(self.engine,self.save['card']))
elif response=='pkdx':
self.callback(Pokedex(self.engine,self.save['card']))
elif response=='settings':
print("OPTIONSPAGE")
class FlashScreen(Task):
def __init__(self,engine):
Task.__init__(self,engine)
self.color=[0]*3
self.connect_signal('frame',self.update_color)
self.connect_signal('frame',lambda:self.engine.surf.fill(self.color))
def update_color(self):
nc=self.color[0]+1
if nc>=256:self.color=[0]*3
else:self.color=[nc]*3
class SaveLoader(ThreadedTask):
def __init__(self,engine):
ThreadedTask.__init__(self,engine)
self.saves,self.save=engine.saves,None
self.connect_signal('frame',self.select_save)
def select_save(self):
saves=[]
i=1
for save in self.engine.saves.values():
saves.append((i,save['card']['name'],save))
i+=1
def get_save(v):
if isinstance(v,str):v=v.lower()
for save in saves:
if v==save[0] or v in save[1].lower():
return save[2]
return None
def print_saves():print(*[("{:3}:\t{}".format(*save[:2])) for save in saves],sep='\n')
def parse_int(s):
try:return int(s)
except:return s
if not GLOBAL_DEBUG:#For now, I just want to auto-load the first save in the list.
while True:
print_saves()
self.save=get_save(parse_int(input("> ")))
if self.save:break
else:self.save=get_save(1)
self.stop()
class Tileset(ScreenItem):
tile_width=16
tile_height=16
update_frequency=1000
def __init__(self,engine,source,m_perm):
ScreenItem.__init__(self,engine,(Tileset.tile_width,source.get_height()),frame=[0,0,Tileset.tile_width,source.get_height()])
self.src,self.moves=source,m_perm
self.connect_signal('paint',self.update_rect)
self.disconnect_signal('frame',self.paint)#Don't paint the tileset onto the screen.
self.timer=OwnedTimer(self,Tileset.update_frequency)
self.timer.connect_signal('elapse',self.update)
def update_rect(self):
self.blit_frame[0]+=Tileset.tile_width#Advance the tile-frame via x-position
if self.blit_frame[0]>=self.src.get_width():#If this is the last frame...
self.blit_frame[0]=0#Reset to the first-frame.
self.blit(self.src,(0,0),self.blit_frame)
def paint_tile(self,target,tile,pos):
target.blit(self,pos,[0,tile*Tileset.tile_height,Tileset.tile_width,Tileset.tile_height])
def tile_permissions(self,tile):return self.moves[tile]
class NPC(ScreenItemCopy):
frame_maps={
'look down':0,
'look up':1,
'look left':2,
'look right':-2,
'walk down a':3,
'walk down b':4,
'walk up a':5,
'walk up b':6,
'walk left a':7,
'walk left b':8,
'walk right a':-7,
'walk right b':-8,
}
dir_mappings={
'left':(0,[-1,0]),
'right':(0,[1,0]),
'up':(1,[0,-1]),
'down':(1,[0,1])
}
step_speed=100
def __init__(self,engine,map_view,npc_class,gender='m'):
spr=trykeys(engine.sprites,"NPC::"+npc_class,"NPC::"+npc_class+"::"+gender)
ScreenItemCopy.__init__(self,engine,spr,frame=[0,0,spr.get_width(),spr.get_height()//9])
w_adjustment = floor((map_view.tileset.tile_width-self.blit_frame[2])/2.0)
h_adjustment = map_view.tileset.tile_height-self.blit_frame[3]
self.default_adjustment=(w_adjustment,h_adjustment)
self.adjustment=list(self.default_adjustment)
self.map_view = map_view
self.steps,self.flip,self.timer,self.npc_class=[],False,None,npc_class
self.step_frame=0
self.timer=OwnedTimer(self,self.step_speed)
self.timer.connect_signal('elapse',self.play_step)
def paint(self):
self.engine.surf.blit(self,self.blit_pos,self.blit_frame,self.blit_flags)
@EventHandler.Signal('set-frame')
def set_frame(self,fr):
if isinstance(fr,str):
fr=NPC.frame_maps[fr]
self.src_frame[1]=abs(fr*self.get_height())
self.flip=fr<0
@property
def blit_pos(self):
r=[self.blit_position[0]*self.map_view.tileset.tile_width,self.blit_position[1]*self.map_view.tileset.tile_height]
r[0]+=self.adjustment[0]+self.map_view.blit_position[0]
r[1]+=self.adjustment[1]+self.map_view.blit_position[1]
return r
@EventHandler.Signal('add-step')
def move(self,dir):
if not self.timer.running:
self.timer.start()
self.steps.append(dir)
def play_step(self):
if len(self.steps)>0:
self.adjustment=combine(self.adjustment,self.dir_mappings[self.steps[0]][1],lambda a,b:a+b*4)
self.step_frame+=1
if self.step_frame>=4:
self.advance_steps()
@EventHandler.Signal('step-complete')
def advance_steps(self):
self.blit_position=combine(self.blit_position,self.dir_mappings[self.steps[0]][1],lambda a,b:a+b)
self.adjustment=list(self.default_adjustment)
self.steps=self.steps[1:]
self.step_frame=0;
if len(self.steps)<1:
self.timer.stop()
class NPCManager(Task):
update_frequency=500
def __init__(self,engine,mapview):
Task.__init__(self,engine)
self.npcs=[]
self.map_view=mapview
self.timer=OwnedTimer(self,NPCManager.update_frequency)
self.timer.connect_signal('elapse',self.move_npcs,self.paint_npcs)
self.map_view.connect_signal('post-paint',self.paint_npcs)
self.connect_signal('start',self.start_npcs)
self.paused=False
def start_npcs(self):
for npc in self.npcs:
if not npc.running:
npc.start()
def move_npcs(self):
if self.paused:return
for npc in self.npcs:
if random.choice([True]*5 + [False]*2):
npc.move(random.choice(['left','right','up','down']))
def paint_npcs(self):
for npc in self.npcs:
npc.paint()
class Camera(Task):
def __init__(self,engine,view_size,total_size):
Task.__init__(self,engine)
self.center_field=combine(total_size,(2,2),lambda a,b:a//b)
self.__pos__=[0,0]
self.center()
def center(self):self.set_position(self.center_field[0],self.center_field[1])
@property
def position(self):return combine(self.center_field,self.__pos__,lambda a,b:a-b)
def adjust(self,x,y):self.set_position(*combine(self.__pos__,[x,y],lambda a,b:a+b))
@EventHandler.Signal('position-changed')
def set_position(self,x,y):self.__pos__=[x,y]
class MapRenderer(ScreenItem):
def __init__(self,engine,mapp):
self.map_data=mapp
size=self.map_data['size']
self.width=size[0]
self.height=size[1]
self.layers=len(self.map_data['data'])
self.tileset=Tileset(engine,engine.tilesets[mapp['tileset']],engine.tileset_data[mapp['tileset']])
size=combine(size,[self.tileset.tile_width,self.tileset.tile_height],lambda a,b:a*b)
ScreenItem.__init__(self,engine,size)
self.connect_signal('start',self.tileset.start,lambda:self.camera.adjust(0,0))
self.connect_signal('stop',self.tileset.stop)
self.tileset.connect_signal('post-paint',self.update)
self.connect_signal('paint',self.build_map)
self.connect_signal(pygame.KEYDOWN,self.move_map)
self.connect_signal('frame',self.paint_middle)
self.camera=Camera(engine,engine.resolution,self.get_size())
self.camera.connect_signal('post-position-changed',self.adjust_rect)
def block_input(self):self.disconnect_signal(self.move_map)
def open_input(self):self.connect_signal(pygame.KEYDOWN,self.move_map)
def move_map(self,event):
key_mappings={
pygame.K_UP:[0,-16],
pygame.K_DOWN:[0,16],
pygame.K_RIGHT:[16,0],
pygame.K_LEFT:[-16,0]
}
self.camera.adjust(*key_mappings.get(event.key,[0,0]))
def adjust_rect(self,x,y):
self.blit_position=self.camera.position[:]
def paint_middle(self):
s=pygame.Surface((16,16))
s.fill((255,0,0))
self.engine.surf.blit(s,self.camera.position)
def build_map(self):
tileset=self.tileset
width_step=tileset.tile_width
height_step=tileset.tile_height
for layer in self.map_data['data']:
pos=[0,0]
for tile in layer:
tileset.paint_tile(self,tile,pos)
pos[0]+=width_step
if pos[0]>=self.get_width():
pos[1]+=height_step
pos[0]=0
class OverWorld(Task):
def __init__(self,engine,save):
Task.__init__(self,engine)
self.save=save
self.menu=OverWorldMenu(self.engine,save)
self.map_render=MapRenderer(self.engine,engine.maps['::'.join(self.save['location'][:-3])])
self.npcs=NPCManager(engine,self.map_render)
self.menu.connect_signal('callback',self.stop_bg)
self.bg=FlashScreen(engine)
link_tasks(self,self.bg,self.map_render,self.npcs)
self.connect_signal(pygame.KEYDOWN,self.launch_menu)
self.menu.connect_signal('start',lambda:self.map_render.block_input())
self.menu.connect_signal('stop',lambda:self.map_render.open_input())
self.npcs.npcs.append(NPC(engine,self.map_render,'ace'))
def stop_bg(self,task):
task.connect_signal('start',self.stop)
task.connect_signal('stop',self.start)
def launch_menu(self,event):
if event.key==pygame.K_BACKSPACE and self.menu.running:
self.menu.stop()
elif event.key==pygame.K_RETURN and not self.menu.running:
self.menu.start()
class TitleScreen(ScreenItemCopy):
def __init__(self,engine):
ScreenItemCopy.__init__(self,engine,engine.pictures['titlescreen'])
self.save_loader=SaveLoader(self.engine)
self.connect_signal('start',self.save_loader.start)
self.connect_signal('paint',lambda:self.engine.surf.fill((0,0,0)))
self.connect_signal('frame',self.launch_overworld)
def launch_overworld(self):
if not self.save_loader.running:
OverWorld(self.engine,self.save_loader.save).start()
self.stop()#m4n4phyPromo
class PkEngine(Engine):
fonts=load_dict('fonts',load_font,open_mode='rb')
sprites=Cache('sprites',load_trans_image,['rb'])
tilesets=Cache('tilesets',pygame.image.load,['rb'])
graphics=Cache('graphics',pygame.image.load,['rb'])
pictures=Cache('images',pygame.image.load,['rb'])
maps=Cache('maps',json.load)
pkdx=Cache('species',json.load)
items=Cache('items',json.load)
saves=Cache('saves',json.load)
info=Cache('info',json.load)
tileset_data=Cache('tilesets data',json.load)
npc_types=Cache('trainers',json.load)
def __init__(self):
Engine.__init__(self,resolution=(480,320))
self.fonts = load_dict('fonts',load_font,open_mode='rb')
self.main_font=self.fonts['fontWestern']
self.textbox_font=self.fonts['dp-light']
credits = ['PyPK!']
if not GLOBAL_DEBUG:
credits=['Python Pokemon!\nWritten by Full Metal','Built using pygame for Python 3.2 and 2.7']
self.credits=[TextBox(self,c) for c in credits]
self.connect_signal('start',self.launch_tasks)
def launch_tasks(self):FlowControl(self,TitleScreen(self),*self.credits).start()
if __name__=="__main__":
Runner(PkEngine())() | Python |
import pickle
import json
import os
def sidechain(func, data, *args, **kw):
func(data, *args, **kw)
return data
def listdir(path):
return [ fn for v in [[ os.path.join(*b) for b in [ (a[0], c) for c in a[2]]] for a in [ [r,d,f] for r,d,f in os.walk(path)]] for fn in v]
def filename_from_key(key):return os.sep.join(key.split("::"))
def key_name( fn,dir): return fn[len(dir):fn.rfind('.')].replace(os.sep,"::").lower()[2:]
def key_from_path(*items): return "::".join(items).lower()
class Struct:
def __init__(self,dat): self.__dict__.update([(key, Struct(val) if isinstance(val,dict) else val) for key,val in dat.items()])
load_struct = lambda fileobj: Struct(json.load(fileobj))
def save_data( dir, data,saver=json.dump,ext='.json',mode='w'):
for key,obj in data.items():saver(obj,open(os.path.join(os.getcwd(),dir,filename_from_key(key)+ext),mode))
#A solution to pre-loading vs cache-ing.
#The load time for parsing all of this JSON
#Stuff was about to kill me. o_O
class Cache:
def __init__(self,directory,opener=json.load,mode=['r'],oargs=[]):
self.opener=opener
self.dir=directory
self.open_args=mode
self.opener_args=oargs
self.objects={}
self.files={}
path=os.path.join(os.getcwd(),self.dir)
for fn in listdir(path):
key=key_name(fn,path)
self.files[key],self.objects[key]=fn,None
def load_all(self):return [self[key] for key in self.objects.keys()]
def keys(self):return self.objects.keys()
def items(self):self.load_all();return self.objects.items()
def values(self):self.load_all();return self.objects.values()
def __getitem__(self,*items):
item=key_from_path(*items)
if self.objects[item] is None:
f=open(self.files[item],*self.open_args) if len(self.open_args)>0 else open(self.files[item])
self.objects[item]=self.opener(f,*self.opener_args) if len(self.opener_args)>0 else self.opener(f)
return self.objects[item]
def load_data( dir,opener=json.load,mode='r'):
ret = {}
err = []
for fn in listdir(os.path.join(os.getcwd(),dir)):
try:
ret[key_name(fn,os.path.join(os.getcwd(),dir))] = opener(open(fn,mode))
except:
err.append(key_name(fn,os.path.join(os.getcwd(),dir)))
if len(err)>0:
print("These items couldn't be loaded:")
for i in err:print("\t{}".format(i))
return ret
| Python |
from __future__ import print_function
from threading import Thread
def trykey(o,k,d):
try:return o[k]
except KeyError:return d
class Runner:
def __init__(self,task):self.task=task
def __call__(self):
t=self.task
t.process_signal('start')
while t.running:
try:t.process_signal('frame')
except Exception as e:
print("Exception occured in",type(t).__name__)
raise e
class EventHandler:
class Signal:
def __init__(self,sig):self.signal=sig
def __call__(self,func):
def wrap(obj,*args,**kwargs):
obj.process_signal(self.signal,*args,**kwargs)
func(obj,*args,**kwargs)
obj.process_signal('post-'+self.signal,*args,**kwargs)
return wrap
def __init__(self):self.events={}
@property
def running(self):return True
@Signal('start')
def start(self):pass
@Signal('stop')
def stop(self):pass
def connect_signal(self,event,*handler):
if event not in self.events:
self.events[event]=[h for h in handler]
else:self.events[event].extend([h for h in handler if h not in self.events[event]])
def disconnect_signal(self,*handlers,event=None):
if event:
for handler in handlers:
if handler in self.events[event]:
self.events[event].remove(handler)
else:
for listener in self.events.values():
for handler in handlers:
if handler in listener:listener.remove(handler)
def process_signal(self,event,*args,**kwargs):
for handler in trykey(self.events,event,[]):handler(*args,**kwargs)
class Task(EventHandler):
def __init__(self,engine,name=None):
EventHandler.__init__(self)
self.engine=engine
@property
def running(self):return self in self.engine.tasks
@EventHandler.Signal('frame')
def frame(self):pass
def run(self):
try:self.frame()
except Exception as e:
print("Exception occured in",type(self).__name__)
raise e
def stop(self):
EventHandler.stop(self)
self.engine.stop_task(self)
def start(self):
EventHandler.start(self)
self.engine.start_task(self)
class ThreadedTask(Task):
def __init__(self,engine,daemon=False):
Task.__init__(self,engine)
self.daemon=daemon
def run(self):pass#Engines will call this method. Taskrunner calls frame directly.
def start(self):
Task.start(self)
nname="{}::{}".format(*[type(o).__name__ for o in [self.engine,self]])
t=Thread(name=nname,target=Runner(self))
#t.daemon=self.daemon
t.start()
class TaskDelegate(EventHandler):
def __init__(self):
EventHandler.__init__(self)
self.tasks=[]
def kill_tasks(self):
for t in self.tasks[:]:t.stop()
self.tasks=[]
def sub_tasks(self):
for task in self.tasks[:]:task.run()
def start_task(self,task):
self.process_signal('start-task',task)
if task not in self.tasks:
self.tasks.append(task)
def stop_task(self,task):
self.process_signal('stop-task',task)
if task in self.tasks:
self.tasks.remove(task)
def frame(self):
Task.frame(self)
self.sub_tasks()
@property
def running(self):return len(self.tasks)>0
class Engine(TaskDelegate):
def __init__(self):
TaskDelegate.__init__(self)
self.connect_signal('frame',self.sub_tasks)
self.connect_signal('stop',self.kill_tasks)
if __name__=="__main__":
from time import clock as ticks
from threading import Thread
class Timer:
def __init__(self,taskdel):
self.timers={}
taskdel.connect_signal('start-task',self.set_timer)
taskdel.connect_signal('stop-task',self.check_timer)
def set_timer(self,task):
self.timers[task]=ticks()
def check_timer(self,task):
print(type(task).__name__,"took",ticks()-self.timers[task],"seconds.")
class Wait(ThreadedTask):
def __init__(self,engine,time):
ThreadedTask.__init__(self,engine)
self.connect_signal('frame',self.check)
self.connect_signal('start',self.reset_time)
self.destination,self.time=time,0
def reset_time(self):self.time=ticks()+self.destination
def check(self):self.stop() if ticks()>=self.time else None
class PalindromeSolver(ThreadedTask):
def __init__(self,engine,num_digits,bottom):
Task.__init__(self,engine)
self.bottom=bottom-1
self.largest=0
self.top=10**num_digits
self.num_digits=num_digits
self.left,self.right=self.top,self.top
self.connect_signal('frame',self.check)
self.connect_signal('frame',self.update)
self.connect_signal('stop',self.output_largest)
def check(self):
def half(l,s):return l[len(l)//2:] if s else l[:len(l)//2]
def is_palindrome(l):return half(l,False)==half(l,True)[::-1]
v=self.left*self.right
if v%10 and v>self.largest:
if is_palindrome(str(v)):
self.largest=v
def update(self):
self.right-=1
if self.right<=self.bottom:
self.left-=1
if self.left<=self.bottom:
self.stop()
return
self.right=self.top
def output_largest(self):
print("The largest palindrome formed by the product of two,",self.num_digits,"digit numbers is",self.largest)
class EulerSeven(Engine):
def __init__(self):
Engine.__init__(self)
self.connect_signal('start',self.initial_tasks)
def initial_tasks(self):
PalindromeSolver(self,3,100).start()
class TimedEulerSeven(Engine):
def __init__(self):
Engine.__init__(self)
Timer(self)
self.connect_signal('start',PalindromeSolver(self,3,100).start)
self.connect_signal('start',Wait(self,2).start)
Thread(target=Runner(EulerSeven())).start()
Thread(target=Runner(TimedEulerSeven())).start() | Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template engines - all in a single file and with no dependencies other than the
Python Standard Library.
Homepage and documentation: http://bottlepy.org/
Copyright (c) 2011, Marcel Hellkamp.
License: MIT (see LICENSE for details)
"""
from __future__ import with_statement
__author__ = 'Marcel Hellkamp'
__version__ = '0.11.dev'
__license__ = 'MIT'
# The gevent server adapter needs to patch some modules before they are imported
# This is why we parse the commandline parameters here but handle them later
if __name__ == '__main__':
from optparse import OptionParser
_cmd_parser = OptionParser(usage="usage: %prog [options] package.module:app")
_opt = _cmd_parser.add_option
_opt("--version", action="store_true", help="show version number.")
_opt("-b", "--bind", metavar="ADDRESS", help="bind socket to ADDRESS.")
_opt("-s", "--server", default='wsgiref', help="use SERVER as backend.")
_opt("-p", "--plugin", action="append", help="install additional plugin/s.")
_opt("--debug", action="store_true", help="start server in debug mode.")
_opt("--reload", action="store_true", help="auto-reload on file changes.")
_cmd_options, _cmd_args = _cmd_parser.parse_args()
if _cmd_options.server and _cmd_options.server.startswith('gevent'):
import gevent.monkey; gevent.monkey.patch_all()
import base64, cgi, email.utils, functools, hmac, imp, itertools, mimetypes,\
os, re, subprocess, sys, tempfile, threading, time, urllib, warnings
from datetime import date as datedate, datetime, timedelta
from tempfile import TemporaryFile
from traceback import format_exc, print_exc
try: from json import dumps as json_dumps, loads as json_lds
except ImportError: # pragma: no cover
try: from simplejson import dumps as json_dumps, loads as json_lds
except ImportError:
try: from django.utils.simplejson import dumps as json_dumps, loads as json_lds
except ImportError:
def json_dumps(data):
raise ImportError("JSON support requires Python 2.6 or simplejson.")
json_lds = json_dumps
# We now try to fix 2.5/2.6/3.1/3.2 incompatibilities.
# It ain't pretty but it works... Sorry for the mess.
py = sys.version_info
py3k = py >= (3,0,0)
py25 = py < (2,6,0)
# Workaround for the missing "as" keyword in py3k.
def _e(): return sys.exc_info()[1]
# Workaround for the "print is a keyword/function" dilemma.
_stdout, _stderr = sys.stdout.write, sys.stderr.write
# Lots of stdlib and builtin differences.
if py3k:
import http.client as httplib
import _thread as thread
from urllib.parse import urljoin, parse_qsl, SplitResult as UrlSplitResult
from urllib.parse import urlencode, quote as urlquote, unquote as urlunquote
from http.cookies import SimpleCookie
from collections import MutableMapping as DictMixin
import pickle
from io import BytesIO
basestring = str
unicode = str
json_loads = lambda s: json_lds(touni(s))
callable = lambda x: hasattr(x, '__call__')
imap = map
else: # 2.x
import httplib
import thread
from urlparse import urljoin, SplitResult as UrlSplitResult
from urllib import urlencode, quote as urlquote, unquote as urlunquote
from Cookie import SimpleCookie
from itertools import imap
import cPickle as pickle
from StringIO import StringIO as BytesIO
if py25:
msg = "Python 2.5 support may be dropped in future versions of Bottle."
warnings.warn(msg, DeprecationWarning)
from cgi import parse_qsl
from UserDict import DictMixin
def next(it): return it.next()
bytes = str
else: # 2.6, 2.7
from urlparse import parse_qsl
from collections import MutableMapping as DictMixin
json_loads = json_lds
# Some helpers for string/byte handling
def tob(s, enc='utf8'):
return s.encode(enc) if isinstance(s, unicode) else bytes(s)
def touni(s, enc='utf8', err='strict'):
return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)
tonat = touni if py3k else tob
# 3.2 fixes cgi.FieldStorage to accept bytes (which makes a lot of sense).
# 3.1 needs a workaround.
NCTextIOWrapper = None
if (3,0,0) < py < (3,2,0):
from io import TextIOWrapper
class NCTextIOWrapper(TextIOWrapper):
def close(self): pass # Keep wrapped buffer open.
# A bug in functools causes it to break if the wrapper is an instance method
def update_wrapper(wrapper, wrapped, *a, **ka):
try: functools.update_wrapper(wrapper, wrapped, *a, **ka)
except AttributeError: pass
# These helpers are used at module level and need to be defined first.
# And yes, I know PEP-8, but sometimes a lower-case classname makes more sense.
def depr(message):
warnings.warn(message, DeprecationWarning, stacklevel=3)
def makelist(data): # This is just to handy
if isinstance(data, (tuple, list, set, dict)): return list(data)
elif data: return [data]
else: return []
class DictProperty(object):
''' Property that maps to a key in a local dict-like attribute. '''
def __init__(self, attr, key=None, read_only=False):
self.attr, self.key, self.read_only = attr, key, read_only
def __call__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter, self.key = func, self.key or func.__name__
return self
def __get__(self, obj, cls):
if obj is None: return self
key, storage = self.key, getattr(obj, self.attr)
if key not in storage: storage[key] = self.getter(obj)
return storage[key]
def __set__(self, obj, value):
if self.read_only: raise AttributeError("Read-Only property.")
getattr(obj, self.attr)[self.key] = value
def __delete__(self, obj):
if self.read_only: raise AttributeError("Read-Only property.")
del getattr(obj, self.attr)[self.key]
class cached_property(object):
''' A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property. '''
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
if obj is None: return self
value = obj.__dict__[self.func.__name__] = self.func(obj)
return value
class lazy_attribute(object):
''' A property that caches itself to the class object. '''
def __init__(self, func):
functools.update_wrapper(self, func, updated=[])
self.getter = func
def __get__(self, obj, cls):
value = self.getter(cls)
setattr(cls, self.__name__, value)
return value
###############################################################################
# Exceptions and Events ########################################################
###############################################################################
class BottleException(Exception):
""" A base class for exceptions used by bottle. """
pass
#TODO: This should subclass BaseRequest
class HTTPResponse(BottleException):
""" Used to break execution and immediately finish the response """
def __init__(self, output='', status=200, header=None):
super(BottleException, self).__init__("HTTP Response %d" % status)
self.status = int(status)
self.output = output
self.headers = HeaderDict(header) if header else None
def apply(self, response):
if self.headers:
for key, value in self.headers.allitems():
response.headers[key] = value
response.status = self.status
class HTTPError(HTTPResponse):
""" Used to generate an error page """
def __init__(self, code=500, output='Unknown Error', exception=None,
traceback=None, header=None):
super(HTTPError, self).__init__(output, code, header)
self.exception = exception
self.traceback = traceback
def __repr__(self):
return tonat(template(ERROR_PAGE_TEMPLATE, e=self))
###############################################################################
# Routing ######################################################################
###############################################################################
class RouteError(BottleException):
""" This is a base class for all routing related exceptions """
class RouteReset(BottleException):
""" If raised by a plugin or request handler, the route is reset and all
plugins are re-applied. """
class RouterUnknownModeError(RouteError): pass
class RouteSyntaxError(RouteError):
""" The route parser found something not supported by this router """
class RouteBuildError(RouteError):
""" The route could not been built """
class Router(object):
''' A Router is an ordered collection of route->target pairs. It is used to
efficiently match WSGI requests against a number of routes and return
the first target that satisfies the request. The target may be anything,
usually a string, ID or callable object. A route consists of a path-rule
and a HTTP method.
The path-rule is either a static path (e.g. `/contact`) or a dynamic
path that contains wildcards (e.g. `/wiki/<page>`). The wildcard syntax
and details on the matching order are described in docs:`routing`.
'''
default_pattern = '[^/]+'
default_filter = 're'
#: Sorry for the mess. It works. Trust me.
rule_syntax = re.compile('(\\\\*)'\
'(?:(?::([a-zA-Z_][a-zA-Z_0-9]*)?()(?:#(.*?)#)?)'\
'|(?:<([a-zA-Z_][a-zA-Z_0-9]*)?(?::([a-zA-Z_]*)'\
'(?::((?:\\\\.|[^\\\\>]+)+)?)?)?>))')
def __init__(self, strict=False):
self.rules = {} # A {rule: Rule} mapping
self.builder = {} # A rule/name->build_info mapping
self.static = {} # Cache for static routes: {path: {method: target}}
self.dynamic = [] # Cache for dynamic routes. See _compile()
#: If true, static routes are no longer checked first.
self.strict_order = strict
self.filters = {'re': self.re_filter, 'int': self.int_filter,
'float': self.float_filter, 'path': self.path_filter}
def re_filter(self, conf):
return conf or self.default_pattern, None, None
def int_filter(self, conf):
return r'-?\d+', int, lambda x: str(int(x))
def float_filter(self, conf):
return r'-?[\d.]+', float, lambda x: str(float(x))
def path_filter(self, conf):
return r'.+?', None, None
def add_filter(self, name, func):
''' Add a filter. The provided function is called with the configuration
string as parameter and must return a (regexp, to_python, to_url) tuple.
The first element is a string, the last two are callables or None. '''
self.filters[name] = func
def parse_rule(self, rule):
''' Parses a rule into a (name, filter, conf) token stream. If mode is
None, name contains a static rule part. '''
offset, prefix = 0, ''
for match in self.rule_syntax.finditer(rule):
prefix += rule[offset:match.start()]
g = match.groups()
if len(g[0])%2: # Escaped wildcard
prefix += match.group(0)[len(g[0]):]
offset = match.end()
continue
if prefix: yield prefix, None, None
name, filtr, conf = g[1:4] if not g[2] is None else g[4:7]
if not filtr: filtr = self.default_filter
yield name, filtr, conf or None
offset, prefix = match.end(), ''
if offset <= len(rule) or prefix:
yield prefix+rule[offset:], None, None
def add(self, rule, method, target, name=None):
''' Add a new route or replace the target for an existing route. '''
if rule in self.rules:
self.rules[rule][method] = target
if name: self.builder[name] = self.builder[rule]
return
target = self.rules[rule] = {method: target}
# Build pattern and other structures for dynamic routes
anons = 0 # Number of anonymous wildcards
pattern = '' # Regular expression pattern
filters = [] # Lists of wildcard input filters
builder = [] # Data structure for the URL builder
is_static = True
for key, mode, conf in self.parse_rule(rule):
if mode:
is_static = False
mask, in_filter, out_filter = self.filters[mode](conf)
if key:
pattern += '(?P<%s>%s)' % (key, mask)
else:
pattern += '(?:%s)' % mask
key = 'anon%d' % anons; anons += 1
if in_filter: filters.append((key, in_filter))
builder.append((key, out_filter or str))
elif key:
pattern += re.escape(key)
builder.append((None, key))
self.builder[rule] = builder
if name: self.builder[name] = builder
if is_static and not self.strict_order:
self.static[self.build(rule)] = target
return
def fpat_sub(m):
return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
flat_pattern = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, pattern)
try:
re_match = re.compile('^(%s)$' % pattern).match
except re.error:
raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, _e()))
def match(path):
""" Return an url-argument dictionary. """
url_args = re_match(path).groupdict()
for name, wildcard_filter in filters:
try:
url_args[name] = wildcard_filter(url_args[name])
except ValueError:
raise HTTPError(400, 'Path has wrong format.')
return url_args
try:
combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, flat_pattern)
self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
self.dynamic[-1][1].append((match, target))
except (AssertionError, IndexError): # AssertionError: Too many groups
self.dynamic.append((re.compile('(^%s$)' % flat_pattern),
[(match, target)]))
return match
def build(self, _name, *anons, **query):
''' Build an URL by filling the wildcards in a rule. '''
builder = self.builder.get(_name)
if not builder: raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons): query['anon%d'%i] = value
url = ''.join([f(query.pop(n)) if n else f for (n,f) in builder])
return url if not query else url+'?'+urlencode(query)
except KeyError:
raise RouteBuildError('Missing URL argument: %r' % _e().args[0])
def match(self, environ):
''' Return a (target, url_agrs) tuple or raise HTTPError(400/404/405). '''
path, targets, urlargs = environ['PATH_INFO'] or '/', None, {}
if path in self.static:
targets = self.static[path]
else:
for combined, rules in self.dynamic:
match = combined.match(path)
if not match: continue
getargs, targets = rules[match.lastindex - 1]
urlargs = getargs(path) if getargs else {}
break
if not targets:
raise HTTPError(404, "Not found: " + repr(environ['PATH_INFO']))
method = environ['REQUEST_METHOD'].upper()
if method in targets:
return targets[method], urlargs
if method == 'HEAD' and 'GET' in targets:
return targets['GET'], urlargs
if 'ANY' in targets:
return targets['ANY'], urlargs
allowed = [verb for verb in targets if verb != 'ANY']
if 'GET' in allowed and 'HEAD' not in allowed:
allowed.append('HEAD')
raise HTTPError(405, "Method not allowed.",
header=[('Allow',",".join(allowed))])
class Route(object):
''' This class wraps a route callback along with route specific metadata and
configuration and applies Plugins on demand. It is also responsible for
turing an URL path rule into a regular expression usable by the Router.
'''
def __init__(self, app, rule, method, callback, name=None,
plugins=None, skiplist=None, **config):
#: The application this route is installed to.
self.app = app
#: The path-rule string (e.g. ``/wiki/:page``).
self.rule = rule
#: The HTTP method as a string (e.g. ``GET``).
self.method = method
#: The original callback with no plugins applied. Useful for introspection.
self.callback = callback
#: The name of the route (if specified) or ``None``.
self.name = name or None
#: A list of route-specific plugins (see :meth:`Bottle.route`).
self.plugins = plugins or []
#: A list of plugins to not apply to this route (see :meth:`Bottle.route`).
self.skiplist = skiplist or []
#: Additional keyword arguments passed to the :meth:`Bottle.route`
#: decorator are stored in this dictionary. Used for route-specific
#: plugin configuration and meta-data.
self.config = ConfigDict(config)
def __call__(self, *a, **ka):
depr("Some APIs changed to return Route() instances instead of"\
" callables. Make sure to use the Route.call method and not to"\
" call Route instances directly.")
return self.call(*a, **ka)
@cached_property
def call(self):
''' The route callback with all plugins applied. This property is
created on demand and then cached to speed up subsequent requests.'''
return self._make_callback()
def reset(self):
''' Forget any cached values. The next time :attr:`call` is accessed,
all plugins are re-applied. '''
self.__dict__.pop('call', None)
def prepare(self):
''' Do all on-demand work immediately (useful for debugging).'''
self.call
@property
def _context(self):
depr('Switch to Plugin API v2 and access the Route object directly.')
return dict(rule=self.rule, method=self.method, callback=self.callback,
name=self.name, app=self.app, config=self.config,
apply=self.plugins, skip=self.skiplist)
def all_plugins(self):
''' Yield all Plugins affecting this route. '''
unique = set()
for p in reversed(self.app.plugins + self.plugins):
if True in self.skiplist: break
name = getattr(p, 'name', False)
if name and (name in self.skiplist or name in unique): continue
if p in self.skiplist or type(p) in self.skiplist: continue
if name: unique.add(name)
yield p
def _make_callback(self):
callback = self.callback
for plugin in self.all_plugins():
try:
if hasattr(plugin, 'apply'):
api = getattr(plugin, 'api', 1)
context = self if api > 1 else self._context
callback = plugin.apply(callback, context)
else:
callback = plugin(callback)
except RouteReset: # Try again with changed configuration.
return self._make_callback()
if not callback is self.callback:
update_wrapper(callback, self.callback)
return callback
def __repr__(self):
return '<%s %r %r>' % (self.method, self.rule, self.callback)
###############################################################################
# Application Object ###########################################################
###############################################################################
class Bottle(object):
""" Each Bottle object represents a single, distinct web application and
consists of routes, callbacks, plugins and configuration. Instances are
callable WSGI applications. """
def __init__(self, catchall=True, autojson=True, config=None):
self.routes = [] # List of installed :class:`Route` instances.
self.router = Router() # Maps requests to :class:`Route` instances.
self.plugins = [] # List of installed plugins.
self.error_handler = {}
self.config = ConfigDict(config or {})
#: If true, most exceptions are catched and returned as :exc:`HTTPError`
self.catchall = catchall
#: An instance of :class:`HooksPlugin`. Empty by default.
self.hooks = HooksPlugin()
self.install(self.hooks)
if autojson:
self.install(JSONPlugin())
self.install(TemplatePlugin())
def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :class:`Bottle` or a WSGI application.
All other parameters are passed to the underlying :meth:`route` call.
'''
if isinstance(app, basestring):
prefix, app = app, prefix
depr('Parameter order of Bottle.mount() changed.') # 0.10
parts = [p for p in prefix.split('/') if p]
if not parts: raise ValueError('Empty path prefix.')
path_depth = len(parts)
options.setdefault('skip', True)
options.setdefault('method', 'ANY')
@self.route('/%s/:#.*#' % '/'.join(parts), **options)
def mountpoint():
try:
request.path_shift(path_depth)
rs = BaseResponse([], 200)
def start_response(status, header):
rs.status = status
for name, value in header: rs.add_header(name, value)
return rs.body.append
rs.body = itertools.chain(rs.body, app(request.environ, start_response))
return HTTPResponse(rs.body, rs.status_code, rs.headers)
finally:
request.path_shift(-path_depth)
if not prefix.endswith('/'):
self.route('/' + '/'.join(parts), callback=mountpoint, **options)
def merge(self, routes):
''' Merge the routes of another :cls:`Bottle` application or a list of
:class:`Route` objects into this application. The routes keep their
'owner', meaning that the :data:`Route.app` attribute is not
changed. '''
if isinstance(routes, Bottle):
routes = routes.routes
for route in routes:
self.add_route(route)
def install(self, plugin):
''' Add a plugin to the list of plugins and prepare it for being
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API.
'''
if hasattr(plugin, 'setup'): plugin.setup(self)
if not callable(plugin) and not hasattr(plugin, 'apply'):
raise TypeError("Plugins must be callable or implement .apply()")
self.plugins.append(plugin)
self.reset()
return plugin
def uninstall(self, plugin):
''' Uninstall plugins. Pass an instance to remove a specific plugin, a type
object to remove all plugins that match that type, a string to remove
all plugins with a matching ``name`` attribute or ``True`` to remove all
plugins. Return the list of removed plugins. '''
removed, remove = [], plugin
for i, plugin in list(enumerate(self.plugins))[::-1]:
if remove is True or remove is plugin or remove is type(plugin) \
or getattr(plugin, 'name', True) == remove:
removed.append(plugin)
del self.plugins[i]
if hasattr(plugin, 'close'): plugin.close()
if removed: self.reset()
return removed
def run(self, **kwargs):
''' Calls :func:`run` with the same parameters. '''
run(self, **kwargs)
def reset(self, route=None):
''' Reset all routes (force plugins to be re-applied) and clear all
caches. If an ID or route object is given, only that specific route
is affected. '''
if route is None: routes = self.routes
elif isinstance(route, Route): routes = [route]
else: routes = [self.routes[route]]
for route in routes: route.reset()
if DEBUG:
for route in routes: route.prepare()
self.hooks.trigger('app_reset')
def close(self):
''' Close the application and all installed plugins. '''
for plugin in self.plugins:
if hasattr(plugin, 'close'): plugin.close()
self.stopped = True
def match(self, environ):
""" Search for a matching route and return a (:class:`Route` , urlargs)
tuple. The second value is a dictionary with parameters extracted
from the URL. Raise :exc:`HTTPError` (404/405) on a non-match."""
return self.router.match(environ)
def get_url(self, routename, **kargs):
""" Return a string that matches a named route """
scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/'
location = self.router.build(routename, **kargs).lstrip('/')
return urljoin(urljoin('/', scriptname), location)
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare()
def route(self, path=None, method='GET', callback=None, name=None,
apply=None, skip=None, **config):
""" A decorator to bind a function to a request URL. Example::
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
The ``:name`` part is a wildcard. See :class:`Router` for syntax
details.
:param path: Request path or a list of paths to listen to. If no
path is specified, it is automatically generated from the
signature of the function.
:param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of
methods to listen to. (default: `GET`)
:param callback: An optional shortcut to avoid the decorator
syntax. ``route(..., callback=func)`` equals ``route(...)(func)``
:param name: The name for this route. (default: None)
:param apply: A decorator or plugin or a list of plugins. These are
applied to the route callback in addition to installed plugins.
:param skip: A list of plugins, plugin classes or names. Matching
plugins are not installed to this route. ``True`` skips all.
Any additional keyword arguments are stored as route-specific
configuration and passed to plugins (see :meth:`Plugin.apply`).
"""
if callable(path): path, callback = None, path
plugins = makelist(apply)
skiplist = makelist(skip)
def decorator(callback):
# TODO: Documentation and tests
if isinstance(callback, basestring): callback = load(callback)
for rule in makelist(path) or yieldroutes(callback):
for verb in makelist(method):
verb = verb.upper()
route = Route(self, rule, verb, callback, name=name,
plugins=plugins, skiplist=skiplist, **config)
self.add_route(route)
return callback
return decorator(callback) if callback else decorator
def get(self, path=None, method='GET', **options):
""" Equals :meth:`route`. """
return self.route(path, method, **options)
def post(self, path=None, method='POST', **options):
""" Equals :meth:`route` with a ``POST`` method parameter. """
return self.route(path, method, **options)
def put(self, path=None, method='PUT', **options):
""" Equals :meth:`route` with a ``PUT`` method parameter. """
return self.route(path, method, **options)
def delete(self, path=None, method='DELETE', **options):
""" Equals :meth:`route` with a ``DELETE`` method parameter. """
return self.route(path, method, **options)
def error(self, code=500):
""" Decorator: Register an output handler for a HTTP error code"""
def wrapper(handler):
self.error_handler[int(code)] = handler
return handler
return wrapper
def hook(self, name):
""" Return a decorator that attaches a callback to a hook. Three hooks
are currently implemented:
- before_request: Executed once before each request
- after_request: Executed once after each request
- app_reset: Called whenever :meth:`reset` is called.
"""
def wrapper(func):
self.hooks.add(name, func)
return func
return wrapper
def handle(self, path, method='GET'):
""" (deprecated) Execute the first matching route callback and return
the result. :exc:`HTTPResponse` exceptions are catched and returned.
If :attr:`Bottle.catchall` is true, other exceptions are catched as
well and returned as :exc:`HTTPError` instances (500).
"""
depr("This method will change semantics in 0.10. Try to avoid it.")
if isinstance(path, dict):
return self._handle(path)
return self._handle({'PATH_INFO': path, 'REQUEST_METHOD': method.upper()})
def _handle(self, environ):
try:
environ['bottle.app'] = self
request.bind(environ)
response.bind()
route, args = self.router.match(environ)
environ['route.handle'] = environ['bottle.route'] = route
environ['route.url_args'] = args
return route.call(**args)
except HTTPResponse:
return _e()
except RouteReset:
route.reset()
return self._handle(environ)
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
stacktrace = format_exc(10)
environ['wsgi.errors'].write(stacktrace)
return HTTPError(500, "Internal Server Error", _e(), stacktrace)
def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty output is done here
if not out:
response['Content-Length'] = 0
return []
# Join lists of byte or unicode strings. Mixed lists are NOT supported
if isinstance(out, (tuple, list))\
and isinstance(out[0], (bytes, unicode)):
out = out[0][0:0].join(out) # b'abc'[0:0] -> b''
# Encode unicode strings
if isinstance(out, unicode):
out = out.encode(response.charset)
# Byte Strings are just returned
if isinstance(out, bytes):
response['Content-Length'] = len(out)
return [out]
# HTTPError or HTTPException (recursive, because they may wrap anything)
# TODO: Handle these explicitly in handle() or make them iterable.
if isinstance(out, HTTPError):
out.apply(response)
out = self.error_handler.get(out.status, repr)(out)
if isinstance(out, HTTPResponse):
depr('Error handlers must not return :exc:`HTTPResponse`.') #0.9
return self._cast(out)
if isinstance(out, HTTPResponse):
out.apply(response)
return self._cast(out.output)
# File-like objects.
if hasattr(out, 'read'):
if 'wsgi.file_wrapper' in request.environ:
return request.environ['wsgi.file_wrapper'](out)
elif hasattr(out, 'close') or not hasattr(out, '__iter__'):
return WSGIFileWrapper(out)
# Handle Iterables. We peek into them to detect their inner type.
try:
out = iter(out)
first = next(out)
while not first:
first = next(out)
except StopIteration:
return self._cast('')
except HTTPResponse:
first = _e()
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
first = HTTPError(500, 'Unhandled exception', _e(), format_exc(10))
# These are the inner types allowed in iterator or generator objects.
if isinstance(first, HTTPResponse):
return self._cast(first)
if isinstance(first, bytes):
return itertools.chain([first], out)
if isinstance(first, unicode):
return imap(lambda x: x.encode(response.charset),
itertools.chain([first], out))
return self._cast(HTTPError(500, 'Unsupported response type: %s'\
% type(first)))
def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or request.method == 'HEAD':
if hasattr(out, 'close'): out.close()
out = []
if isinstance(response._status_line, unicode):
response._status_line = str(response._status_line)
start_response(response._status_line, list(response.iter_headers()))
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception:
if not self.catchall: raise
err = '<h1>Critical error while processing request: %s</h1>' \
% html_escape(environ.get('PATH_INFO', '/'))
if DEBUG:
err += '<h2>Error:</h2>\n<pre>\n%s\n</pre>\n' \
'<h2>Traceback:</h2>\n<pre>\n%s\n</pre>\n' \
% (html_escape(repr(_e())), html_escape(format_exc(10)))
environ['wsgi.errors'].write(err)
headers = [('Content-Type', 'text/html; charset=UTF-8')]
start_response('500 INTERNAL SERVER ERROR', headers)
return [tob(err)]
def __call__(self, environ, start_response):
''' Each instance of :class:'Bottle' is a WSGI application. '''
return self.wsgi(environ, start_response)
###############################################################################
# HTTP and WSGI Tools ##########################################################
###############################################################################
class BaseRequest(object):
""" A wrapper for WSGI environment dictionaries that adds a lot of
convenient access methods and properties. Most of them are read-only."""
#: Maximum size of memory buffer for :attr:`body` in bytes.
MEMFILE_MAX = 102400
#: Maximum number pr GET or POST parameters per request
MAX_PARAMS = 100
def __init__(self, environ):
""" Wrap a WSGI environ dictionary. """
#: The wrapped WSGI environ dictionary. This is the only real attribute.
#: All other attributes actually are read-only properties.
self.environ = environ
environ['bottle.request'] = self
@DictProperty('environ', 'bottle.app', read_only=True)
def app(self):
''' Bottle application handling this request. '''
raise AttributeError('This request is not connected to an application.')
@property
def path(self):
''' The value of ``PATH_INFO`` with exactly one prefixed slash (to fix
broken clients and avoid the "empty path" edge case). '''
return '/' + self.environ.get('PATH_INFO','').lstrip('/')
@property
def method(self):
''' The ``REQUEST_METHOD`` value as an uppercase string. '''
return self.environ.get('REQUEST_METHOD', 'GET').upper()
@DictProperty('environ', 'bottle.request.headers', read_only=True)
def headers(self):
''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
HTTP request headers. '''
return WSGIHeaderDict(self.environ)
def get_header(self, name, default=None):
''' Return the value of a request header, or a given default value. '''
return self.headers.get(name, default)
@DictProperty('environ', 'bottle.request.cookies', read_only=True)
def cookies(self):
""" Cookies parsed into a :class:`FormsDict`. Signed cookies are NOT
decoded. Use :meth:`get_cookie` if you expect signed cookies. """
cookies = SimpleCookie(self.environ.get('HTTP_COOKIE',''))
cookies = list(cookies.values())[:self.MAX_PARAMS]
return FormsDict((c.key, c.value) for c in cookies)
def get_cookie(self, key, default=None, secret=None):
""" Return the content of a cookie. To read a `Signed Cookie`, the
`secret` must match the one used to create the cookie (see
:meth:`BaseResponse.set_cookie`). If anything goes wrong (missing
cookie or wrong signature), return a default value. """
value = self.cookies.get(key)
if secret and value:
dec = cookie_decode(value, secret) # (key, value) tuple or None
return dec[1] if dec and dec[0] == key else default
return value or default
@DictProperty('environ', 'bottle.request.query', read_only=True)
def query(self):
''' The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`. '''
pairs = parse_qsl(self.query_string, keep_blank_values=True)
get = self.environ['bottle.get'] = FormsDict()
for key, value in pairs[:self.MAX_PARAMS]:
get[key] = value
return get
@DictProperty('environ', 'bottle.request.forms', read_only=True)
def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = FormsDict()
for name, item in self.POST.allitems():
if not hasattr(item, 'filename'):
forms[name] = item
return forms
@DictProperty('environ', 'bottle.request.params', read_only=True)
def params(self):
""" A :class:`FormsDict` with the combined values of :attr:`query` and
:attr:`forms`. File uploads are stored in :attr:`files`. """
params = FormsDict()
for key, value in self.query.allitems():
params[key] = value
for key, value in self.forms.allitems():
params[key] = value
return params
@DictProperty('environ', 'bottle.request.files', read_only=True)
def files(self):
""" File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise None; this is the client
side filename, *not* the file name on which it is stored (that's
a temporary file you don't deal with)
file
The file(-like) object from which you can read the data.
value
The value as a *string*; for file uploads, this transparently
reads the file every time you request the value. Do not do this
on big files.
"""
files = FormsDict()
for name, item in self.POST.allitems():
if hasattr(item, 'filename'):
files[name] = item
return files
@DictProperty('environ', 'bottle.request.json', read_only=True)
def json(self):
''' If the ``Content-Type`` header is ``application/json``, this
property holds the parsed content of the request body. Only requests
smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
exhaustion. '''
if 'application/json' in self.environ.get('CONTENT_TYPE', '') \
and 0 < self.content_length < self.MEMFILE_MAX:
return json_loads(self.body.read(self.MEMFILE_MAX))
return None
@DictProperty('environ', 'bottle.request.body', read_only=True)
def _body(self):
maxread = max(0, self.content_length)
stream = self.environ['wsgi.input']
body = BytesIO() if maxread < self.MEMFILE_MAX else TemporaryFile(mode='w+b')
while maxread > 0:
part = stream.read(min(maxread, self.MEMFILE_MAX))
if not part: break
body.write(part)
maxread -= len(part)
self.environ['wsgi.input'] = body
body.seek(0)
return body
@property
def body(self):
""" The HTTP request body as a seek-able file-like object. Depending on
:attr:`MEMFILE_MAX`, this is either a temporary file or a
:class:`io.BytesIO` instance. Accessing this property for the first
time reads and replaces the ``wsgi.input`` environ variable.
Subsequent accesses just do a `seek(0)` on the file object. """
self._body.seek(0)
return self._body
#: An alias for :attr:`query`.
GET = query
@DictProperty('environ', 'bottle.request.post', read_only=True)
def POST(self):
""" The values of :attr:`forms` and :attr:`files` combined into a single
:class:`FormsDict`. Values are either strings (form values) or
instances of :class:`cgi.FieldStorage` (file uploads).
"""
post = FormsDict()
safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi
for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'):
if key in self.environ: safe_env[key] = self.environ[key]
if NCTextIOWrapper:
fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n')
else:
fb = self.body
data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True)
for item in (data.list or [])[:self.MAX_PARAMS]:
post[item.name] = item if item.filename else item.value
return post
@property
def COOKIES(self):
''' Alias for :attr:`cookies` (deprecated). '''
depr('BaseRequest.COOKIES was renamed to BaseRequest.cookies (lowercase).')
return self.cookies
@property
def url(self):
""" The full request URI including hostname and scheme. If your app
lives behind a reverse proxy or load balancer and you get confusing
results, make sure that the ``X-Forwarded-Host`` header is set
correctly. """
return self.urlparts.geturl()
@DictProperty('environ', 'bottle.request.urlparts', read_only=True)
def urlparts(self):
''' The :attr:`url` string as an :class:`urlparse.SplitResult` tuple.
The tuple contains (scheme, host, path, query_string and fragment),
but the fragment is always empty because it is not visible to the
server. '''
env = self.environ
http = env.get('wsgi.url_scheme', 'http')
host = env.get('HTTP_X_FORWARDED_HOST') or env.get('HTTP_HOST')
if not host:
# HTTP 1.1 requires a Host-header. This is for HTTP/1.0 clients.
host = env.get('SERVER_NAME', '127.0.0.1')
port = env.get('SERVER_PORT')
if port and port != ('80' if http == 'http' else '443'):
host += ':' + port
path = urlquote(self.fullpath)
return UrlSplitResult(http, host, path, env.get('QUERY_STRING'), '')
@property
def fullpath(self):
""" Request path including :attr:`script_name` (if present). """
return urljoin(self.script_name, self.path.lstrip('/'))
@property
def query_string(self):
""" The raw :attr:`query` part of the URL (everything in between ``?``
and ``#``) as a string. """
return self.environ.get('QUERY_STRING', '')
@property
def script_name(self):
''' The initial portion of the URL's `path` that was removed by a higher
level (server or routing middleware) before the application was
called. This script path is returned with leading and tailing
slashes. '''
script_name = self.environ.get('SCRIPT_NAME', '').strip('/')
return '/' + script_name + '/' if script_name else '/'
def path_shift(self, shift=1):
''' Shift path segments from :attr:`path` to :attr:`script_name` and
vice versa.
:param shift: The number of path segments to shift. May be negative
to change the shift direction. (default: 1)
'''
script = self.environ.get('SCRIPT_NAME','/')
self['SCRIPT_NAME'], self['PATH_INFO'] = path_shift(script, self.path, shift)
@property
def content_length(self):
''' The request body length as an integer. The client is responsible to
set this header. Otherwise, the real length of the body is unknown
and -1 is returned. In this case, :attr:`body` will be empty. '''
return int(self.environ.get('CONTENT_LENGTH') or -1)
@property
def is_xhr(self):
''' True if the request was triggered by a XMLHttpRequest. This only
works with JavaScript libraries that support the `X-Requested-With`
header (most of the popular libraries do). '''
requested_with = self.environ.get('HTTP_X_REQUESTED_WITH','')
return requested_with.lower() == 'xmlhttprequest'
@property
def is_ajax(self):
''' Alias for :attr:`is_xhr`. "Ajax" is not the right term. '''
return self.is_xhr
@property
def auth(self):
""" HTTP authentication data as a (user, password) tuple. This
implementation currently supports basic (not digest) authentication
only. If the authentication happened at a higher level (e.g. in the
front web-server or a middleware), the password field is None, but
the user field is looked up from the ``REMOTE_USER`` environ
variable. On any errors, None is returned. """
basic = parse_auth(self.environ.get('HTTP_AUTHORIZATION',''))
if basic: return basic
ruser = self.environ.get('REMOTE_USER')
if ruser: return (ruser, None)
return None
@property
def remote_route(self):
""" A list of all IPs that were involved in this request, starting with
the client IP and followed by zero or more proxies. This does only
work if all proxies support the ```X-Forwarded-For`` header. Note
that this information can be forged by malicious clients. """
proxy = self.environ.get('HTTP_X_FORWARDED_FOR')
if proxy: return [ip.strip() for ip in proxy.split(',')]
remote = self.environ.get('REMOTE_ADDR')
return [remote] if remote else []
@property
def remote_addr(self):
""" The client IP as a string. Note that this information can be forged
by malicious clients. """
route = self.remote_route
return route[0] if route else None
def copy(self):
""" Return a new :class:`Request` with a shallow :attr:`environ` copy. """
return Request(self.environ.copy())
def get(self, value, default=None): return self.environ.get(value, default)
def __getitem__(self, key): return self.environ[key]
def __delitem__(self, key): self[key] = ""; del(self.environ[key])
def __iter__(self): return iter(self.environ)
def __len__(self): return len(self.environ)
def keys(self): return self.environ.keys()
def __setitem__(self, key, value):
""" Change an environ value and clear all caches that depend on it. """
if self.environ.get('bottle.request.readonly'):
raise KeyError('The environ dictionary is read-only.')
self.environ[key] = value
todelete = ()
if key == 'wsgi.input':
todelete = ('body', 'forms', 'files', 'params', 'post', 'json')
elif key == 'QUERY_STRING':
todelete = ('query', 'params')
elif key.startswith('HTTP_'):
todelete = ('headers', 'cookies')
for key in todelete:
self.environ.pop('bottle.request.'+key, None)
def __repr__(self):
return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)
def _hkey(s):
return s.title().replace('_','-')
class HeaderProperty(object):
def __init__(self, name, reader=None, writer=str, default=''):
self.name, self.reader, self.writer, self.default = name, reader, writer, default
self.__doc__ = 'Current value of the %r header.' % name.title()
def __get__(self, obj, cls):
if obj is None: return self
value = obj.headers.get(self.name)
return self.reader(value) if (value and self.reader) else (value or self.default)
def __set__(self, obj, value):
if self.writer: value = self.writer(value)
obj.headers[self.name] = value
def __delete__(self, obj):
if self.name in obj.headers:
del obj.headers[self.name]
class BaseResponse(object):
""" Storage class for a response body as well as headers and cookies.
This class does support dict-like case-insensitive item-access to
headers, but is NOT a dict. Most notably, iterating over a response
yields parts of the body and not the headers.
"""
default_status = 200
default_content_type = 'text/html; charset=UTF-8'
# Header blacklist for specific response codes
# (rfc2616 section 10.2.3 and 10.3.5)
bad_headers = {
204: set(('Content-Type',)),
304: set(('Allow', 'Content-Encoding', 'Content-Language',
'Content-Length', 'Content-Range', 'Content-Type',
'Content-Md5', 'Last-Modified'))}
def __init__(self, body='', status=None, **headers):
self._status_line = None
self._status_code = None
self._cookies = None
self._headers = {'Content-Type': [self.default_content_type]}
self.body = body
self.status = status or self.default_status
if headers:
for name, value in headers.items():
self[name] = value
def copy(self):
''' Returns a copy of self. '''
copy = Response()
copy.status = self.status
copy._headers = dict((k, v[:]) for (k, v) in self._headers.items())
return copy
def __iter__(self):
return iter(self.body)
def close(self):
if hasattr(self.body, 'close'):
self.body.close()
@property
def status_line(self):
''' The HTTP status line as a string (e.g. ``404 Not Found``).'''
return self._status_line
@property
def status_code(self):
''' The HTTP status code as an integer (e.g. 404).'''
return self._status_code
def _set_status(self, status):
if isinstance(status, int):
code, status = status, _HTTP_STATUS_LINES.get(status)
elif ' ' in status:
status = status.strip()
code = int(status.split()[0])
else:
raise ValueError('String status line without a reason phrase.')
if not 100 <= code <= 999: raise ValueError('Status code out of range.')
self._status_code = code
self._status_line = status or ('%d Unknown' % code)
def _get_status(self):
return self._status_line
status = property(_get_status, _set_status, None,
''' A writeable property to change the HTTP response status. It accepts
either a numeric code (100-999) or a string with a custom reason
phrase (e.g. "404 Brain not found"). Both :data:`status_line` and
:data:`status_code` are updated accordingly. The return value is
always a status string. ''')
del _get_status, _set_status
@property
def headers(self):
''' An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers. '''
self.__dict__['headers'] = hdict = HeaderDict()
hdict.dict = self._headers
return hdict
def __contains__(self, name): return _hkey(name) in self._headers
def __delitem__(self, name): del self._headers[_hkey(name)]
def __getitem__(self, name): return self._headers[_hkey(name)][-1]
def __setitem__(self, name, value): self._headers[_hkey(name)] = [str(value)]
def get_header(self, name, default=None):
''' Return the value of a previously defined header. If there is no
header with that name, return a default value. '''
return self._headers.get(_hkey(name), [default])[-1]
def set_header(self, name, value, append=False):
''' Create a new response header, replacing any previously defined
headers with the same name. '''
if append:
self.add_header(name, value)
else:
self._headers[_hkey(name)] = [str(value)]
def add_header(self, name, value):
''' Add an additional response header, not removing duplicates. '''
self._headers.setdefault(_hkey(name), []).append(str(value))
def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
headers = self._headers.items()
bad_headers = self.bad_headers.get(self._status_code)
if bad_headers:
headers = [h for h in headers if h[0] not in bad_headers]
for name, values in headers:
for value in values:
yield name, value
if self._cookies:
for c in self._cookies.values():
yield 'Set-Cookie', c.OutputString()
def wsgiheader(self):
depr('The wsgiheader method is deprecated. See headerlist.') #0.10
return self.headerlist
@property
def headerlist(self):
''' WSGI conform list of (header, value) tuples. '''
return list(self.iter_headers())
content_type = HeaderProperty('Content-Type')
content_length = HeaderProperty('Content-Length', reader=int)
@property
def charset(self):
""" Return the charset specified in the content-type header (default: utf8). """
if 'charset=' in self.content_type:
return self.content_type.split('charset=')[-1].split(';')[0].strip()
return 'UTF-8'
@property
def COOKIES(self):
""" A dict-like SimpleCookie instance. This should not be used directly.
See :meth:`set_cookie`. """
depr('The COOKIES dict is deprecated. Use `set_cookie()` instead.') # 0.10
if not self._cookies:
self._cookies = SimpleCookie()
return self._cookies
def set_cookie(self, name, value, secret=None, **options):
''' Create a new cookie or replace an old one. If the `secret` parameter is
set, create a `Signed Cookie` (described below).
:param name: the name of the cookie.
:param value: the value of the cookie.
:param secret: a signature key required for signed cookies.
Additionally, this method accepts all RFC 2109 attributes that are
supported by :class:`cookie.Morsel`, including:
:param max_age: maximum age in seconds. (default: None)
:param expires: a datetime object or UNIX timestamp. (default: None)
:param domain: the domain that is allowed to read the cookie.
(default: current domain)
:param path: limits the cookie to a given path (default: current path)
:param secure: limit the cookie to HTTPS connections (default: off).
:param httponly: prevents client-side javascript to read this cookie
(default: off, requires Python 2.6 or newer).
If neither `expires` nor `max_age` is set (default), the cookie will
expire at the end of the browser session (as soon as the browser
window is closed).
Signed cookies may store any pickle-able object and are
cryptographically signed to prevent manipulation. Keep in mind that
cookies are limited to 4kb in most browsers.
Warning: Signed cookies are not encrypted (the client can still see
the content) and not copy-protected (the client can restore an old
cookie). The main intention is to make pickling and unpickling
save, not to store secret information at client side.
'''
if not self._cookies:
self._cookies = SimpleCookie()
if secret:
value = touni(cookie_encode((name, value), secret))
elif not isinstance(value, basestring):
raise TypeError('Secret key missing for non-string Cookie.')
if len(value) > 4096: raise ValueError('Cookie value to long.')
self._cookies[name] = value
for key, value in options.items():
if key == 'max_age':
if isinstance(value, timedelta):
value = value.seconds + value.days * 24 * 3600
if key == 'expires':
if isinstance(value, (datedate, datetime)):
value = value.timetuple()
elif isinstance(value, (int, float)):
value = time.gmtime(value)
value = time.strftime("%a, %d %b %Y %H:%M:%S GMT", value)
self._cookies[name][key.replace('_', '-')] = value
def delete_cookie(self, key, **kwargs):
''' Delete a cookie. Be sure to use the same `domain` and `path`
settings as used to create the cookie. '''
kwargs['max_age'] = -1
kwargs['expires'] = 0
self.set_cookie(key, '', **kwargs)
def __repr__(self):
out = ''
for name, value in self.headerlist:
out += '%s: %s\n' % (name.title(), value.strip())
return out
#: Thread-local storage for :class:`LocalRequest` and :class:`LocalResponse`
#: attributes.
_lctx = threading.local()
def local_property(name, doc=None):
return property(
lambda self: getattr(_lctx, name),
lambda self, value: setattr(_lctx, name, value),
lambda self: delattr(_lctx, name),
doc or ('Thread-local property stored in :data:`_lctx.%s` ' % name)
)
class LocalRequest(BaseRequest):
''' A thread-local subclass of :class:`BaseRequest` with a different
set of attribues for each thread. There is usually only one global
instance of this class (:data:`request`). If accessed during a
request/response cycle, this instance always refers to the *current*
request (even on a multithreaded server). '''
def __init__(self): pass
bind = BaseRequest.__init__
environ = local_property('request_environ')
class LocalResponse(BaseResponse):
''' A thread-local subclass of :class:`BaseResponse` with a different
set of attribues for each thread. There is usually only one global
instance of this class (:data:`response`). Its attributes are used
to build the HTTP response at the end of the request/response cycle.
'''
def __init__(self): pass
bind = BaseResponse.__init__
_status_line = local_property('response_status_line')
_status_code = local_property('response_status_code')
_cookies = local_property('response_cookies')
_headers = local_property('response_headers')
body = local_property('response_body')
Response = LocalResponse # BC 0.9
Request = LocalRequest # BC 0.9
###############################################################################
# Plugins ######################################################################
###############################################################################
class PluginError(BottleException): pass
class JSONPlugin(object):
name = 'json'
api = 2
def __init__(self, json_dumps=json_dumps):
self.json_dumps = json_dumps
def apply(self, callback, context):
dumps = self.json_dumps
if not dumps: return callback
def wrapper(*a, **ka):
rv = callback(*a, **ka)
if isinstance(rv, dict):
#Attempt to serialize, raises exception on failure
json_response = dumps(rv)
#Set content type only if serialization succesful
response.content_type = 'application/json'
return json_response
return rv
return wrapper
class HooksPlugin(object):
name = 'hooks'
api = 2
_names = 'before_request', 'after_request', 'app_reset'
def __init__(self):
self.hooks = dict((name, []) for name in self._names)
self.app = None
def _empty(self):
return not (self.hooks['before_request'] or self.hooks['after_request'])
def setup(self, app):
self.app = app
def add(self, name, func):
''' Attach a callback to a hook. '''
was_empty = self._empty()
self.hooks.setdefault(name, []).append(func)
if self.app and was_empty and not self._empty(): self.app.reset()
def remove(self, name, func):
''' Remove a callback from a hook. '''
was_empty = self._empty()
if name in self.hooks and func in self.hooks[name]:
self.hooks[name].remove(func)
if self.app and not was_empty and self._empty(): self.app.reset()
def trigger(self, name, *a, **ka):
''' Trigger a hook and return a list of results. '''
hooks = self.hooks[name]
if ka.pop('reversed', False): hooks = hooks[::-1]
return [hook(*a, **ka) for hook in hooks]
def apply(self, callback, context):
if self._empty(): return callback
def wrapper(*a, **ka):
self.trigger('before_request')
rv = callback(*a, **ka)
self.trigger('after_request', reversed=True)
return rv
return wrapper
class TemplatePlugin(object):
''' This plugin applies the :func:`view` decorator to all routes with a
`template` config parameter. If the parameter is a tuple, the second
element must be a dict with additional options (e.g. `template_engine`)
or default variables for the template. '''
name = 'template'
api = 2
def apply(self, callback, route):
conf = route.config.get('template')
if isinstance(conf, (tuple, list)) and len(conf) == 2:
return view(conf[0], **conf[1])(callback)
elif isinstance(conf, str) and 'template_opts' in route.config:
depr('The `template_opts` parameter is deprecated.') #0.9
return view(conf, **route.config['template_opts'])(callback)
elif isinstance(conf, str):
return view(conf)(callback)
else:
return callback
#: Not a plugin, but part of the plugin API. TODO: Find a better place.
class _ImportRedirect(object):
def __init__(self, name, impmask):
''' Create a virtual package that redirects imports (see PEP 302). '''
self.name = name
self.impmask = impmask
self.module = sys.modules.setdefault(name, imp.new_module(name))
self.module.__dict__.update({'__file__': __file__, '__path__': [],
'__all__': [], '__loader__': self})
sys.meta_path.append(self)
def find_module(self, fullname, path=None):
if '.' not in fullname: return
packname, modname = fullname.rsplit('.', 1)
if packname != self.name: return
return self
def load_module(self, fullname):
if fullname in sys.modules: return sys.modules[fullname]
packname, modname = fullname.rsplit('.', 1)
realname = self.impmask % modname
__import__(realname)
module = sys.modules[fullname] = sys.modules[realname]
setattr(self.module, modname, module)
module.__loader__ = self
return module
###############################################################################
# Common Utilities #############################################################
###############################################################################
class MultiDict(DictMixin):
""" This dict stores multiple values per key, but behaves exactly like a
normal dict in that it returns only the newest value for any given key.
There are special methods available to access the full list of values.
"""
def __init__(self, *a, **k):
self.dict = dict((k, [v]) for (k, v) in dict(*a, **k).items())
def __len__(self): return len(self.dict)
def __iter__(self): return iter(self.dict)
def __contains__(self, key): return key in self.dict
def __delitem__(self, key): del self.dict[key]
def __getitem__(self, key): return self.dict[key][-1]
def __setitem__(self, key, value): self.append(key, value)
def keys(self): return self.dict.keys()
if py3k:
def values(self): return (v[-1] for v in self.dict.values())
def items(self): return ((k, v[-1]) for k, v in self.dict.items())
def allitems(self):
return ((k, v) for k, vl in self.dict.items() for v in vl)
iterkeys = keys
itervalues = values
iteritems = items
iterallitems = allitems
else:
def values(self): return [v[-1] for v in self.dict.values()]
def items(self): return [(k, v[-1]) for k, v in self.dict.items()]
def iterkeys(self): return self.dict.iterkeys()
def itervalues(self): return (v[-1] for v in self.dict.itervalues())
def iteritems(self):
return ((k, v[-1]) for k, v in self.dict.iteritems())
def iterallitems(self):
return ((k, v) for k, vl in self.dict.iteritems() for v in vl)
def allitems(self):
return [(k, v) for k, vl in self.dict.iteritems() for v in vl]
def get(self, key, default=None, index=-1, type=None):
''' Return the most recent value for a key.
:param default: The default value to be returned if the key is not
present or the type conversion fails.
:param index: An index for the list of available values.
:param type: If defined, this callable is used to cast the value
into a specific type. Exception are suppressed and result in
the default value to be returned.
'''
try:
val = self.dict[key][index]
return type(val) if type else val
except Exception:
pass
return default
def append(self, key, value):
''' Add a new value to the list of values for this key. '''
self.dict.setdefault(key, []).append(value)
def replace(self, key, value):
''' Replace the list of values with a single value. '''
self.dict[key] = [value]
def getall(self, key):
''' Return a (possibly empty) list of values for a key. '''
return self.dict.get(key) or []
#: Aliases for WTForms to mimic other multi-dict APIs (Django)
getone = get
getlist = getall
class FormsDict(MultiDict):
''' This :class:`MultiDict` subclass is used to store request form data.
Additionally to the normal dict-like item access methods (which return
unmodified data as native strings), this container also supports
attribute-like access to its values. Attributes are automatically de-
or recoded to match :attr:`input_encoding` (default: 'utf8'). Missing
attributes default to an empty string. '''
#: Encoding used for attribute values.
input_encoding = 'utf8'
#: If true (default), unicode strings are first encoded with `latin1`
#: and then decoded to match :attr:`input_encoding`.
recode_unicode = True
def _fix(self, s, encoding=None):
if isinstance(s, unicode) and self.recode_unicode: # Python 3 WSGI
s = s.encode('latin1')
if isinstance(s, bytes): # Python 2 WSGI
return s.decode(encoding or self.input_encoding)
return s
def decode(self, encoding=None):
''' Returns a copy with all keys and values de- or recoded to match
:attr:`input_encoding`. Some libraries (e.g. WTForms) want a
unicode dictionary. '''
copy = FormsDict()
enc = copy.input_encoding = encoding or self.input_encoding
copy.recode_unicode = False
for key, value in self.allitems():
copy.append(self._fix(key, enc), self._fix(value, enc))
return copy
def getunicode(self, name, default=None, encoding=None):
try:
return self._fix(self[name], encoding)
except (UnicodeError, KeyError):
return default
def __getattr__(self, name, default=unicode()):
return self.getunicode(name, default=default)
class HeaderDict(MultiDict):
""" A case-insensitive version of :class:`MultiDict` that defaults to
replace the old value instead of appending it. """
def __init__(self, *a, **ka):
self.dict = {}
if a or ka: self.update(*a, **ka)
def __contains__(self, key): return _hkey(key) in self.dict
def __delitem__(self, key): del self.dict[_hkey(key)]
def __getitem__(self, key): return self.dict[_hkey(key)][-1]
def __setitem__(self, key, value): self.dict[_hkey(key)] = [str(value)]
def append(self, key, value):
self.dict.setdefault(_hkey(key), []).append(str(value))
def replace(self, key, value): self.dict[_hkey(key)] = [str(value)]
def getall(self, key): return self.dict.get(_hkey(key)) or []
def get(self, key, default=None, index=-1):
return MultiDict.get(self, _hkey(key), default, index)
def filter(self, names):
for name in [_hkey(n) for n in names]:
if name in self.dict:
del self.dict[name]
class WSGIHeaderDict(DictMixin):
''' This dict-like class wraps a WSGI environ dict and provides convenient
access to HTTP_* fields. Keys and values are native strings
(2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI
environment contains non-native string values, these are de- or encoded
using a lossless 'latin1' character set.
The API will remain stable even on changes to the relevant PEPs.
Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one
that uses non-native strings.)
'''
#: List of keys that do not have a 'HTTP_' prefix.
cgikeys = ('CONTENT_TYPE', 'CONTENT_LENGTH')
def __init__(self, environ):
self.environ = environ
def _ekey(self, key):
''' Translate header field name to CGI/WSGI environ key. '''
key = key.replace('-','_').upper()
if key in self.cgikeys:
return key
return 'HTTP_' + key
def raw(self, key, default=None):
''' Return the header value as is (may be bytes or unicode). '''
return self.environ.get(self._ekey(key), default)
def __getitem__(self, key):
return tonat(self.environ[self._ekey(key)], 'latin1')
def __setitem__(self, key, value):
raise TypeError("%s is read-only." % self.__class__)
def __delitem__(self, key):
raise TypeError("%s is read-only." % self.__class__)
def __iter__(self):
for key in self.environ:
if key[:5] == 'HTTP_':
yield key[5:].replace('_', '-').title()
elif key in self.cgikeys:
yield key.replace('_', '-').title()
def keys(self): return [x for x in self]
def __len__(self): return len(self.keys())
def __contains__(self, key): return self._ekey(key) in self.environ
class ConfigDict(dict):
''' A dict-subclass with some extras: You can access keys like attributes.
Uppercase attributes create new ConfigDicts and act as name-spaces.
Other missing attributes return None. Calling a ConfigDict updates its
values and returns itself.
>>> cfg = ConfigDict()
>>> cfg.Namespace.value = 5
>>> cfg.OtherNamespace(a=1, b=2)
>>> cfg
{'Namespace': {'value': 5}, 'OtherNamespace': {'a': 1, 'b': 2}}
'''
def __getattr__(self, key):
if key not in self and key[0].isupper():
self[key] = ConfigDict()
return self.get(key)
def __setattr__(self, key, value):
if hasattr(dict, key):
raise AttributeError('Read-only attribute.')
if key in self and self[key] and isinstance(self[key], ConfigDict):
raise AttributeError('Non-empty namespace attribute.')
self[key] = value
def __delattr__(self, key):
if key in self: del self[key]
def __call__(self, *a, **ka):
for key, value in dict(*a, **ka).items(): setattr(self, key, value)
return self
class AppStack(list):
""" A stack-like list. Calling it returns the head of the stack. """
def __call__(self):
""" Return the current default application. """
return self[-1]
def push(self, value=None):
""" Add a new :class:`Bottle` instance to the stack """
if not isinstance(value, Bottle):
value = Bottle()
self.append(value)
return value
class WSGIFileWrapper(object):
def __init__(self, fp, buffer_size=1024*64):
self.fp, self.buffer_size = fp, buffer_size
for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'):
if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr))
def __iter__(self):
buff, read = self.buffer_size, self.read
while True:
part = read(buff)
if not part: return
yield part
###############################################################################
# Application Helper ###########################################################
###############################################################################
def abort(code=500, text='Unknown Error: Application stopped.'):
""" Aborts execution and causes a HTTP error. """
raise HTTPError(code, text)
def redirect(url, code=None):
""" Aborts execution and causes a 303 or 302 redirect, depending on
the HTTP protocol version. """
if code is None:
code = 303 if request.get('SERVER_PROTOCOL') == "HTTP/1.1" else 302
location = urljoin(request.url, url)
raise HTTPResponse("", status=code, header=dict(Location=location))
def _file_iter_range(fp, offset, bytes, maxread=1024*1024):
''' Yield chunks from a range in a file. No chunk is bigger than maxread.'''
fp.seek(offset)
while bytes > 0:
part = fp.read(min(bytes, maxread))
if not part: break
bytes -= len(part)
yield part
def static_file(filename, root, mimetype='auto', download=False):
""" Open a file in a safe way and return :exc:`HTTPResponse` with status
code 200, 305, 401 or 404. Set Content-Type, Content-Encoding,
Content-Length and Last-Modified header. Obey If-Modified-Since header
and HEAD requests.
"""
root = os.path.abspath(root) + os.sep
filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
header = dict()
if not filename.startswith(root):
return HTTPError(403, "Access denied.")
if not os.path.exists(filename) or not os.path.isfile(filename):
return HTTPError(404, "File does not exist.")
if not os.access(filename, os.R_OK):
return HTTPError(403, "You do not have permission to access this file.")
if mimetype == 'auto':
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype: header['Content-Type'] = mimetype
if encoding: header['Content-Encoding'] = encoding
elif mimetype:
header['Content-Type'] = mimetype
if download:
download = os.path.basename(filename if download == True else download)
header['Content-Disposition'] = 'attachment; filename="%s"' % download
stats = os.stat(filename)
header['Content-Length'] = clen = stats.st_size
lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
header['Last-Modified'] = lm
ims = request.environ.get('HTTP_IF_MODIFIED_SINCE')
if ims:
ims = parse_date(ims.split(";")[0].strip())
if ims is not None and ims >= int(stats.st_mtime):
header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
return HTTPResponse(status=304, header=header)
body = '' if request.method == 'HEAD' else open(filename, 'rb')
header["Accept-Ranges"] = "bytes"
ranges = request.environ.get('HTTP_RANGE')
if 'HTTP_RANGE' in request.environ:
ranges = list(parse_range_header(request.environ['HTTP_RANGE'], clen))
if not ranges:
return HTTPError(416, "Requested Range Not Satisfiable")
offset, end = ranges[0]
header["Content-Range"] = "bytes %d-%d/%d" % (offset, end-1, clen)
header["Content-Length"] = str(end-offset)
if body: body = _file_iter_range(body, offset, end-offset)
return HTTPResponse(body, header=header, status=206)
return HTTPResponse(body, header=header)
###############################################################################
# HTTP Utilities and MISC (TODO) ###############################################
###############################################################################
def debug(mode=True):
""" Change the debug level.
There is only one debug level supported at the moment."""
global DEBUG
DEBUG = bool(mode)
def parse_date(ims):
""" Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone
except (TypeError, ValueError, IndexError, OverflowError):
return None
def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':',1)
return user, pwd
except (KeyError, ValueError):
return None
def parse_range_header(header, maxlen=0):
''' Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive.'''
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, end in ranges:
try:
if not start: # bytes=-100 -> last 100 bytes
start, end = max(0, maxlen-int(end)), maxlen
elif not end: # bytes=100- -> all but the first 99 bytes
start, end = int(start), maxlen
else: # bytes=100-200 -> bytes 100-200 (inclusive)
start, end = int(start), min(int(end)+1, maxlen)
if 0 <= start < end <= maxlen:
yield start, end
except ValueError:
pass
def _lscmp(a, b):
''' Compares two strings in a cryptographically save way:
Runtime is not affected by length of common prefix. '''
return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b)
def cookie_encode(data, key):
''' Encode and sign a pickle-able object. Return a (byte) string '''
msg = base64.b64encode(pickle.dumps(data, -1))
sig = base64.b64encode(hmac.new(tob(key), msg).digest())
return tob('!') + sig + tob('?') + msg
def cookie_decode(data, key):
''' Verify and decode an encoded string. Return an object or None.'''
data = tob(data)
if cookie_is_encoded(data):
sig, msg = data.split(tob('?'), 1)
if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg).digest())):
return pickle.loads(base64.b64decode(msg))
return None
def cookie_is_encoded(data):
''' Return True if the argument looks like a encoded cookie.'''
return bool(data.startswith(tob('!')) and tob('?') in data)
def html_escape(string):
''' Escape HTML special characters ``&<>`` and quotes ``'"``. '''
return string.replace('&','&').replace('<','<').replace('>','>')\
.replace('"','"').replace("'",''')
def html_quote(string):
''' Escape and quote a string to be used as an HTTP attribute.'''
return '"%s"' % html_escape(string).replace('\n','%#10;')\
.replace('\r',' ').replace('\t','	')
def yieldroutes(func):
""" Return a generator for routes that match the signature (name, args)
of the func parameter. This may yield more than one route if the function
takes optional keyword arguments. The output is best described by example::
a() -> '/a'
b(x, y) -> '/b/:x/:y'
c(x, y=5) -> '/c/:x' and '/c/:x/:y'
d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
"""
import inspect # Expensive module. Only import if necessary.
path = '/' + func.__name__.replace('__','/').lstrip('/')
spec = inspect.getargspec(func)
argc = len(spec[0]) - len(spec[3] or [])
path += ('/:%s' * argc) % tuple(spec[0][:argc])
yield path
for arg in spec[0][argc:]:
path += '/:%s' % arg
yield path
def path_shift(script_name, path_info, shift=1):
''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa.
:return: The modified paths.
:param script_name: The SCRIPT_NAME path.
:param script_name: The PATH_INFO path.
:param shift: The number of path fragments to shift. May be negative to
change the shift direction. (default: 1)
'''
if shift == 0: return script_name, path_info
pathlist = path_info.strip('/').split('/')
scriptlist = script_name.strip('/').split('/')
if pathlist and pathlist[0] == '': pathlist = []
if scriptlist and scriptlist[0] == '': scriptlist = []
if shift > 0 and shift <= len(pathlist):
moved = pathlist[:shift]
scriptlist = scriptlist + moved
pathlist = pathlist[shift:]
elif shift < 0 and shift >= -len(scriptlist):
moved = scriptlist[shift:]
pathlist = moved + pathlist
scriptlist = scriptlist[:shift]
else:
empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO'
raise AssertionError("Cannot shift. Nothing left from %s" % empty)
new_script_name = '/' + '/'.join(scriptlist)
new_path_info = '/' + '/'.join(pathlist)
if path_info.endswith('/') and pathlist: new_path_info += '/'
return new_script_name, new_path_info
def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
depr('Use route wildcard filters instead.')
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kargs):
for key, value in vkargs.items():
if key not in kargs:
abort(403, 'Missing parameter: %s' % key)
try:
kargs[key] = value(kargs[key])
except ValueError:
abort(403, 'Wrong parameter format for: %s' % key)
return func(*args, **kargs)
return wrapper
return decorator
def auth_basic(check, realm="private", text="Access denied"):
''' Callback decorator to require HTTP auth (basic).
TODO: Add route(check_auth=...) parameter. '''
def decorator(func):
def wrapper(*a, **ka):
user, password = request.auth or (None, None)
if user is None or not check(user, password):
response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return HTTPError(401, text)
return func(*a, **ka)
return wrapper
return decorator
# Shortcuts for common Bottle methods.
# They all refer to the current default application.
def make_default_app_wrapper(name):
''' Return a callable that relays calls to the current default app. '''
@functools.wraps(getattr(Bottle, name))
def wrapper(*a, **ka):
return getattr(app(), name)(*a, **ka)
return wrapper
route = make_default_app_wrapper('route')
get = make_default_app_wrapper('get')
post = make_default_app_wrapper('post')
put = make_default_app_wrapper('put')
delete = make_default_app_wrapper('delete')
error = make_default_app_wrapper('error')
mount = make_default_app_wrapper('mount')
hook = make_default_app_wrapper('hook')
install = make_default_app_wrapper('install')
uninstall = make_default_app_wrapper('uninstall')
url = make_default_app_wrapper('get_url')
###############################################################################
# Server Adapter ###############################################################
###############################################################################
class ServerAdapter(object):
quiet = False
def __init__(self, host='127.0.0.1', port=8080, **config):
self.options = config
self.host = host
self.port = int(port)
def run(self, handler): # pragma: no cover
pass
def __repr__(self):
args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()])
return "%s(%s)" % (self.__class__.__name__, args)
class CGIServer(ServerAdapter):
quiet = True
def run(self, handler): # pragma: no cover
from wsgiref.handlers import CGIHandler
def fixed_environ(environ, start_response):
environ.setdefault('PATH_INFO', '')
return handler(environ, start_response)
CGIHandler().run(fixed_environ)
class FlupFCGIServer(ServerAdapter):
def run(self, handler): # pragma: no cover
import flup.server.fcgi
self.options.setdefault('bindAddress', (self.host, self.port))
flup.server.fcgi.WSGIServer(handler, **self.options).run()
class WSGIRefServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw): pass
self.options['handler_class'] = QuietHandler
srv = make_server(self.host, self.port, handler, **self.options)
srv.serve_forever()
class CherryPyServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from cherrypy import wsgiserver
server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
try:
server.start()
finally:
server.stop()
class PasteServer(ServerAdapter):
def run(self, handler): # pragma: no cover
from paste import httpserver
if not self.quiet:
from paste.translogger import TransLogger
handler = TransLogger(handler)
httpserver.serve(handler, host=self.host, port=str(self.port),
**self.options)
class MeinheldServer(ServerAdapter):
def run(self, handler):
from meinheld import server
server.listen((self.host, self.port))
server.run(handler)
class FapwsServer(ServerAdapter):
""" Extremely fast webserver using libev. See http://www.fapws.org/ """
def run(self, handler): # pragma: no cover
import fapws._evwsgi as evwsgi
from fapws import base, config
port = self.port
if float(config.SERVER_IDENT[-2:]) > 0.4:
# fapws3 silently changed its API in 0.5
port = str(port)
evwsgi.start(self.host, port)
# fapws3 never releases the GIL. Complain upstream. I tried. No luck.
if 'BOTTLE_CHILD' in os.environ and not self.quiet:
_stderr("WARNING: Auto-reloading does not work with Fapws3.\n")
_stderr(" (Fapws3 breaks python thread support)\n")
evwsgi.set_base_module(base)
def app(environ, start_response):
environ['wsgi.multiprocess'] = False
return handler(environ, start_response)
evwsgi.wsgi_cb(('', app))
evwsgi.run()
class TornadoServer(ServerAdapter):
""" The super hyped asynchronous server by facebook. Untested. """
def run(self, handler): # pragma: no cover
import tornado.wsgi, tornado.httpserver, tornado.ioloop
container = tornado.wsgi.WSGIContainer(handler)
server = tornado.httpserver.HTTPServer(container)
server.listen(port=self.port)
tornado.ioloop.IOLoop.instance().start()
class AppEngineServer(ServerAdapter):
""" Adapter for Google App Engine. """
quiet = True
def run(self, handler):
from google.appengine.ext.webapp import util
# A main() function in the handler script enables 'App Caching'.
# Lets makes sure it is there. This _really_ improves performance.
module = sys.modules.get('__main__')
if module and not hasattr(module, 'main'):
module.main = lambda: util.run_wsgi_app(handler)
util.run_wsgi_app(handler)
class TwistedServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from twisted.web import server, wsgi
from twisted.python.threadpool import ThreadPool
from twisted.internet import reactor
thread_pool = ThreadPool()
thread_pool.start()
reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
reactor.listenTCP(self.port, factory, interface=self.host)
reactor.run()
class DieselServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from diesel.protocols.wsgi import WSGIApplication
app = WSGIApplication(handler, port=self.port)
app.run()
class GeventServer(ServerAdapter):
""" Untested. Options:
* `monkey` (default: True) fixes the stdlib to use greenthreads.
* `fast` (default: False) uses libevent's http server, but has some
issues: No streaming, no pipelining, no SSL.
"""
def run(self, handler):
from gevent import wsgi as wsgi_fast, pywsgi, monkey, local
if self.options.get('monkey', True):
if not threading.local is local.local: monkey.patch_all()
wsgi = wsgi_fast if self.options.get('fast') else pywsgi
wsgi.WSGIServer((self.host, self.port), handler).serve_forever()
class GunicornServer(ServerAdapter):
""" Untested. See http://gunicorn.org/configure.html for options. """
def run(self, handler):
from gunicorn.app.base import Application
config = {'bind': "%s:%d" % (self.host, int(self.port))}
config.update(self.options)
class GunicornApplication(Application):
def init(self, parser, opts, args):
return config
def load(self):
return handler
GunicornApplication().run()
class EventletServer(ServerAdapter):
""" Untested """
def run(self, handler):
from eventlet import wsgi, listen
try:
wsgi.server(listen((self.host, self.port)), handler,
log_output=(not self.quiet))
except TypeError:
# Fallback, if we have old version of eventlet
wsgi.server(listen((self.host, self.port)), handler)
class RocketServer(ServerAdapter):
""" Untested. """
def run(self, handler):
from rocket import Rocket
server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler })
server.start()
class BjoernServer(ServerAdapter):
""" Fast server written in C: https://github.com/jonashaag/bjoern """
def run(self, handler):
from bjoern import run
run(handler, self.host, self.port)
class AutoServer(ServerAdapter):
""" Untested. """
adapters = [PasteServer, TwistedServer, CherryPyServer, WSGIRefServer]
def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except ImportError:
pass
server_names = {
'cgi': CGIServer,
'flup': FlupFCGIServer,
'wsgiref': WSGIRefServer,
'cherrypy': CherryPyServer,
'paste': PasteServer,
'fapws3': FapwsServer,
'tornado': TornadoServer,
'gae': AppEngineServer,
'twisted': TwistedServer,
'diesel': DieselServer,
'meinheld': MeinheldServer,
'gunicorn': GunicornServer,
'eventlet': EventletServer,
'gevent': GeventServer,
'rocket': RocketServer,
'bjoern' : BjoernServer,
'auto': AutoServer,
}
###############################################################################
# Application Control ##########################################################
###############################################################################
def load(target, **namespace):
""" Import a module or fetch an object from a module.
* ``package.module`` returns `module` as a module object.
* ``pack.mod:name`` returns the module variable `name` from `pack.mod`.
* ``pack.mod:func()`` calls `pack.mod.func()` and returns the result.
The last form accepts not only function calls, but any type of
expression. Keyword arguments passed to this function are available as
local variables. Example: ``import_string('re:compile(x)', x='[a-z]')``
"""
module, target = target.split(":", 1) if ':' in target else (target, None)
if module not in sys.modules: __import__(module)
if not target: return sys.modules[module]
if target.isalnum(): return getattr(sys.modules[module], target)
package_name = module.split('.')[0]
namespace[package_name] = sys.modules[package_name]
return eval('%s.%s' % (module, target), namespace)
def load_app(target):
""" Load a bottle application from a module and make sure that the import
does not affect the current default application, but returns a separate
application object. See :func:`load` for the target parameter. """
global NORUN; NORUN, nr_old = True, NORUN
try:
tmp = default_app.push() # Create a new "default application"
rv = load(target) # Import the target module
return rv if callable(rv) else tmp
finally:
default_app.remove(tmp) # Remove the temporary added default application
NORUN = nr_old
_debug = debug
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=False, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter.
"""
if NORUN: return
if reloader and not os.environ.get('BOTTLE_CHILD'):
try:
lockfile = None
fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
except KeyboardInterrupt:
pass
finally:
if os.path.exists(lockfile):
os.unlink(lockfile)
return
try:
_debug(debug)
app = app or default_app()
if isinstance(app, basestring):
app = load_app(app)
if not callable(app):
raise ValueError("Application is not callable: %r" % app)
for plugin in plugins or []:
app.install(plugin)
if server in server_names:
server = server_names.get(server)
if isinstance(server, basestring):
server = load(server)
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise ValueError("Unknown or unsupported server: %r" % server)
server.quiet = server.quiet or quiet
if not server.quiet:
_stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
_stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
_stderr("Hit Ctrl-C to quit.\n\n")
if reloader:
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
with bgcheck:
server.run(app)
if bgcheck.status == 'reload':
sys.exit(3)
else:
server.run(app)
except KeyboardInterrupt:
pass
except (SystemExit, MemoryError):
raise
except:
if not reloader: raise
if not getattr(server, 'quiet', quiet):
print_exc()
time.sleep(interval)
sys.exit(3)
class FileCheckerThread(threading.Thread):
''' Interrupt main-thread as soon as a changed module file is detected,
the lockfile gets deleted or gets to old. '''
def __init__(self, lockfile, interval):
threading.Thread.__init__(self)
self.lockfile, self.interval = lockfile, interval
#: Is one of 'reload', 'error' or 'exit'
self.status = None
def run(self):
exists = os.path.exists
mtime = lambda path: os.stat(path).st_mtime
files = dict()
for module in list(sys.modules.values()):
path = getattr(module, '__file__', '')
if path[-4:] in ('.pyo', '.pyc'): path = path[:-1]
if path and exists(path): files[path] = mtime(path)
while not self.status:
if not exists(self.lockfile)\
or mtime(self.lockfile) < time.time() - self.interval - 5:
self.status = 'error'
thread.interrupt_main()
for path, lmtime in list(files.items()):
if not exists(path) or mtime(path) > lmtime:
self.status = 'reload'
thread.interrupt_main()
break
time.sleep(self.interval)
def __enter__(self):
self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.status: self.status = 'exit' # silent exit
self.join()
return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)
###############################################################################
# Template Adapters ############################################################
###############################################################################
class TemplateError(HTTPError):
def __init__(self, message):
HTTPError.__init__(self, 500, message)
class BaseTemplate(object):
""" Base class and minimal API for template adapters """
extensions = ['tpl','html','thtml','stpl']
settings = {} #used in prepare()
defaults = {} #used in render()
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
""" Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
"""
self.name = name
self.source = source.read() if hasattr(source, 'read') else source
self.filename = source.filename if hasattr(source, 'filename') else None
self.lookup = [os.path.abspath(x) for x in lookup]
self.encoding = encoding
self.settings = self.settings.copy() # Copy from class variable
self.settings.update(settings) # Apply
if not self.source and self.name:
self.filename = self.search(self.name, self.lookup)
if not self.filename:
raise TemplateError('Template %s not found.' % repr(name))
if not self.source and not self.filename:
raise TemplateError('No template specified.')
self.prepare(**self.settings)
@classmethod
def search(cls, name, lookup=[]):
""" Search name in all directories specified in lookup.
First without, then with common extensions. Return first hit. """
if os.path.isfile(name): return name
for spath in lookup:
fname = os.path.join(spath, name)
if os.path.isfile(fname):
return fname
for ext in cls.extensions:
if os.path.isfile('%s.%s' % (fname, ext)):
return '%s.%s' % (fname, ext)
@classmethod
def global_config(cls, key, *args):
''' This reads or sets the global settings stored in class.settings. '''
if args:
cls.settings = cls.settings.copy() # Make settings local to class
cls.settings[key] = args[0]
else:
return cls.settings[key]
def prepare(self, **options):
""" Run preparations (parsing, caching, ...).
It should be possible to call this again to refresh a template or to
update settings.
"""
raise NotImplementedError
def render(self, *args, **kwargs):
""" Render the template with the specified local variables and return
a single byte or unicode string. If it is a byte string, the encoding
must match self.encoding. This method must be thread-safe!
Local variables may be provided in dictionaries (*args)
or directly, as keywords (**kwargs).
"""
raise NotImplementedError
class MakoTemplate(BaseTemplate):
def prepare(self, **options):
from mako.template import Template
from mako.lookup import TemplateLookup
options.update({'input_encoding':self.encoding})
options.setdefault('format_exceptions', bool(DEBUG))
lookup = TemplateLookup(directories=self.lookup, **options)
if self.source:
self.tpl = Template(self.source, lookup=lookup, **options)
else:
self.tpl = Template(uri=self.name, filename=self.filename, lookup=lookup, **options)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
_defaults = self.defaults.copy()
_defaults.update(kwargs)
return self.tpl.render(**_defaults)
class CheetahTemplate(BaseTemplate):
def prepare(self, **options):
from Cheetah.Template import Template
self.context = threading.local()
self.context.vars = {}
options['searchList'] = [self.context.vars]
if self.source:
self.tpl = Template(source=self.source, **options)
else:
self.tpl = Template(file=self.filename, **options)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
self.context.vars.update(self.defaults)
self.context.vars.update(kwargs)
out = str(self.tpl)
self.context.vars.clear()
return out
class Jinja2Template(BaseTemplate):
def prepare(self, filters=None, tests=None, **kwargs):
from jinja2 import Environment, FunctionLoader
if 'prefix' in kwargs: # TODO: to be removed after a while
raise RuntimeError('The keyword argument `prefix` has been removed. '
'Use the full jinja2 environment name line_statement_prefix instead.')
self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
if filters: self.env.filters.update(filters)
if tests: self.env.tests.update(tests)
if self.source:
self.tpl = self.env.from_string(self.source)
else:
self.tpl = self.env.get_template(self.filename)
def render(self, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
_defaults = self.defaults.copy()
_defaults.update(kwargs)
return self.tpl.render(**_defaults)
def loader(self, name):
fname = self.search(name, self.lookup)
if not fname: return
with open(fname, "rb") as f:
return f.read().decode(self.encoding)
class SimpleTALTemplate(BaseTemplate):
''' Deprecated, do not use. '''
def prepare(self, **options):
depr('The SimpleTAL template handler is deprecated'\
' and will be removed in 0.12')
from simpletal import simpleTAL
if self.source:
self.tpl = simpleTAL.compileHTMLTemplate(self.source)
else:
with open(self.filename, 'rb') as fp:
self.tpl = simpleTAL.compileHTMLTemplate(tonat(fp.read()))
def render(self, *args, **kwargs):
from simpletal import simpleTALES
for dictarg in args: kwargs.update(dictarg)
context = simpleTALES.Context()
for k,v in self.defaults.items():
context.addGlobal(k, v)
for k,v in kwargs.items():
context.addGlobal(k, v)
output = StringIO()
self.tpl.expand(context, output)
return output.getvalue()
class SimpleTemplate(BaseTemplate):
blocks = ('if', 'elif', 'else', 'try', 'except', 'finally', 'for', 'while',
'with', 'def', 'class')
dedent_blocks = ('elif', 'else', 'except', 'finally')
@lazy_attribute
def re_pytokens(cls):
''' This matches comments and all kinds of quoted strings but does
NOT match comments (#...) within quoted strings. (trust me) '''
return re.compile(r'''
(''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types)
|'(?:[^\\']|\\.)+?' # Single quotes (')
|"(?:[^\\"]|\\.)+?" # Double quotes (")
|'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (')
|"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (")
|\#.* # Comments
)''', re.VERBOSE)
def prepare(self, escape_func=html_escape, noescape=False, **kwargs):
self.cache = {}
enc = self.encoding
self._str = lambda x: touni(x, enc)
self._escape = lambda x: escape_func(touni(x, enc))
if noescape:
self._str, self._escape = self._escape, self._str
@classmethod
def split_comment(cls, code):
""" Removes comments (#...) from python code. """
if '#' not in code: return code
#: Remove comments only (leave quoted strings as they are)
subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0)
return re.sub(cls.re_pytokens, subf, code)
@cached_property
def co(self):
return compile(self.code, self.filename or '<string>', 'exec')
@cached_property
def code(self):
stack = [] # Current Code indentation
lineno = 0 # Current line of code
ptrbuffer = [] # Buffer for printable strings and token tuple instances
codebuffer = [] # Buffer for generated python code
multiline = dedent = oneline = False
template = self.source or open(self.filename, 'rb').read()
def yield_tokens(line):
for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)):
if i % 2:
if part.startswith('!'): yield 'RAW', part[1:]
else: yield 'CMD', part
else: yield 'TXT', part
def flush(): # Flush the ptrbuffer
if not ptrbuffer: return
cline = ''
for line in ptrbuffer:
for token, value in line:
if token == 'TXT': cline += repr(value)
elif token == 'RAW': cline += '_str(%s)' % value
elif token == 'CMD': cline += '_escape(%s)' % value
cline += ', '
cline = cline[:-2] + '\\\n'
cline = cline[:-2]
if cline[:-1].endswith('\\\\\\\\\\n'):
cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr'
cline = '_printlist([' + cline + '])'
del ptrbuffer[:] # Do this before calling code() again
code(cline)
def code(stmt):
for line in stmt.splitlines():
codebuffer.append(' ' * len(stack) + line.strip())
for line in template.splitlines(True):
lineno += 1
line = touni(line, self.encoding)
sline = line.lstrip()
if lineno <= 2:
m = re.match(r"%\s*#.*coding[:=]\s*([-\w.]+)", sline)
if m: self.encoding = m.group(1)
if m: line = line.replace('coding','coding (removed)')
if sline and sline[0] == '%' and sline[:2] != '%%':
line = line.split('%',1)[1].lstrip() # Full line following the %
cline = self.split_comment(line).strip()
cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0]
flush() # You are actually reading this? Good luck, it's a mess :)
if cmd in self.blocks or multiline:
cmd = multiline or cmd
dedent = cmd in self.dedent_blocks # "else:"
if dedent and not oneline and not multiline:
cmd = stack.pop()
code(line)
oneline = not cline.endswith(':') # "if 1: pass"
multiline = cmd if cline.endswith('\\') else False
if not oneline and not multiline:
stack.append(cmd)
elif cmd == 'end' and stack:
code('#end(%s) %s' % (stack.pop(), line.strip()[3:]))
elif cmd == 'include':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1]))
elif p:
code("_=_include(%s, _stdout)" % repr(p[0]))
else: # Empty %include -> reverse of %rebase
code("_printlist(_base)")
elif cmd == 'rebase':
p = cline.split(None, 2)[1:]
if len(p) == 2:
code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1]))
elif p:
code("globals()['_rebase']=(%s, {})" % repr(p[0]))
else:
code(line)
else: # Line starting with text (not '%') or '%%' (escaped)
if line.strip().startswith('%%'):
line = line.replace('%%', '%', 1)
ptrbuffer.append(yield_tokens(line))
flush()
return '\n'.join(codebuffer) + '\n'
def subtemplate(self, _name, _stdout, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
if _name not in self.cache:
self.cache[_name] = self.__class__(name=_name, lookup=self.lookup)
return self.cache[_name].execute(_stdout, kwargs)
def execute(self, _stdout, *args, **kwargs):
for dictarg in args: kwargs.update(dictarg)
env = self.defaults.copy()
env.update({'_stdout': _stdout, '_printlist': _stdout.extend,
'_include': self.subtemplate, '_str': self._str,
'_escape': self._escape, 'get': env.get,
'setdefault': env.setdefault, 'defined': env.__contains__})
env.update(kwargs)
eval(self.co, env)
if '_rebase' in env:
subtpl, rargs = env['_rebase']
rargs['_base'] = _stdout[:] #copy stdout
del _stdout[:] # clear stdout
return self.subtemplate(subtpl,_stdout,rargs)
return env
def render(self, *args, **kwargs):
""" Render the template using keyword arguments as local variables. """
for dictarg in args: kwargs.update(dictarg)
stdout = []
self.execute(stdout, kwargs)
return ''.join(stdout)
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings: TEMPLATES[tpl].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tpl]:
abort(500, 'Template (%s) not found' % tpl)
for dictarg in args[1:]: kwargs.update(dictarg)
return TEMPLATES[tpl].render(kwargs)
mako_template = functools.partial(template, template_adapter=MakoTemplate)
cheetah_template = functools.partial(template, template_adapter=CheetahTemplate)
jinja2_template = functools.partial(template, template_adapter=Jinja2Template)
simpletal_template = functools.partial(template, template_adapter=SimpleTALTemplate)
def view(tpl_name, **defaults):
''' Decorator: renders a template for a handler.
The handler can control its behavior like that:
- return a dict of template vars to fill out the template
- return something other than a dict and the view decorator will not
process the template, but return the handler result as is.
This includes returning a HTTPResponse(dict) to get,
for instance, JSON with autojson or other castfilters.
'''
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if isinstance(result, (dict, DictMixin)):
tplvars = defaults.copy()
tplvars.update(result)
return template(tpl_name, **tplvars)
return result
return wrapper
return decorator
mako_view = functools.partial(view, template_adapter=MakoTemplate)
cheetah_view = functools.partial(view, template_adapter=CheetahTemplate)
jinja2_view = functools.partial(view, template_adapter=Jinja2Template)
simpletal_view = functools.partial(view, template_adapter=SimpleTALTemplate)
###############################################################################
# Constants and Globals ########################################################
###############################################################################
TEMPLATE_PATH = ['./', './views/']
TEMPLATES = {}
DEBUG = False
NORUN = False # If set, run() does nothing. Used by load_app()
#: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found')
HTTP_CODES = httplib.responses
HTTP_CODES[418] = "I'm a teapot" # RFC 2324
HTTP_CODES[428] = "Precondition Required"
HTTP_CODES[429] = "Too Many Requests"
HTTP_CODES[431] = "Request Header Fields Too Large"
HTTP_CODES[511] = "Network Authentication Required"
_HTTP_STATUS_LINES = dict((k, '%d %s'%(k,v)) for (k,v) in HTTP_CODES.items())
#: The default template used for error pages. Override with @error()
ERROR_PAGE_TEMPLATE = """
%try:
%from bottle import DEBUG, HTTP_CODES, request, touni
%status_name = HTTP_CODES.get(e.status, 'Unknown').title()
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Error {{e.status}}: {{status_name}}</title>
<style type="text/css">
html {background-color: #eee; font-family: sans;}
body {background-color: #fff; border: 1px solid #ddd;
padding: 15px; margin: 15px;}
pre {background-color: #eee; border: 1px solid #ddd; padding: 5px;}
</style>
</head>
<body>
<h1>Error {{e.status}}: {{status_name}}</h1>
<p>Sorry, the requested URL <tt>{{repr(request.url)}}</tt>
caused an error:</p>
<pre>{{e.output}}</pre>
%if DEBUG and e.exception:
<h2>Exception:</h2>
<pre>{{repr(e.exception)}}</pre>
%end
%if DEBUG and e.traceback:
<h2>Traceback:</h2>
<pre>{{e.traceback}}</pre>
%end
</body>
</html>
%except ImportError:
<b>ImportError:</b> Could not generate the error page. Please add bottle to
the import path.
%end
"""
#: A thread-safe instance of :class:`LocalRequest`. If accessed from within a
#: request callback, this instance always refers to the *current* request
#: (even on a multithreaded server).
request = LocalRequest()
#: A thread-safe instance of :class:`LocalResponse`. It is used to change the
#: HTTP response for the *current* request.
response = LocalResponse()
#: A thread-safe namespace. Not used by Bottle.
local = threading.local()
# Initialize app stack (create first empty Bottle app)
# BC: 0.6.4 and needed for run()
app = default_app = AppStack()
app.push()
#: A virtual package that redirects import statements.
#: Example: ``import bottle.ext.sqlite`` actually imports `bottle_sqlite`.
ext = _ImportRedirect(__name__+'.ext', 'bottle_%s').module
if __name__ == '__main__':
opt, args, parser = _cmd_options, _cmd_args, _cmd_parser
if opt.version:
_stdout('Bottle %s\n'%__version__)
sys.exit(0)
if not args:
parser.print_help()
_stderr('\nError: No application specified.\n')
sys.exit(1)
sys.path.insert(0, '.')
sys.modules.setdefault('bottle', sys.modules['__main__'])
host, port = (opt.bind or 'localhost'), 8080
if ':' in host:
host, port = host.rsplit(':', 1)
run(args[0], host=host, port=port, server=opt.server,
reloader=opt.reload, plugins=opt.plugin, debug=opt.debug)
# THE END
| Python |
import json
import os
import pygame
from data import *
from engine import *
import tile_rpg
if __name__ == "__main__":
def mix(a,b,func=lambda a,b:a+b):
l = len(a)
assert l==len(b)
return [ func(a[i],b[i]) for i in range(0,l)]
def render_palette(src,width):
pos=[0,0]
num_per_row = int(width/16)
num_tiles = len(src['dat'])
if num_tiles%num_per_row: t_height = int((num_tiles-(num_tiles%num_per_row))/num_per_row)+1
else: t_height = int(num_tiles/num_per_row)
ret = pygame.Surface((num_per_row*16,t_height*16))
width = num_per_row*16
for tile in [[0,i*16,16,16] for i in range(0,num_tiles)]:
ret.blit(src['img'],pos,tile)
pos[0]+=16
if pos[0]>=width:pos=[0,pos[1]+16]
return ret
def get_tile_rect(pal,tn):
t_p_r = int(pal.get_width()/16)
y = int(tn/t_p_r)
x = (tn - t_p_r*y)
return [x*16,y*16,16,16]
def get_tile_num(pal,pos,max):
ret = pos[1]*int(pal.get_width()/16)+pos[0]
assert ret<max
return ret
class Editor(Task):
def __init__(self,game,map):
Task.__init__(self,game)
viewer_width = 480
self.viewer = tile_rpg.MapViewer(game,map,viewer_width)
self.viewer.set_camera([240,game.surf.get_height()//2])
self.palette = render_palette(self.viewer.map.tileset,game.res[0]-viewer_width)
self.clear = Clear(game)
self.threads=[self.clear,self.viewer,self.input,self.paint_palette,self.cur]
self.tile = 0
self.cursor_loc = 0
self.open_map=None
def input_resize(self):
c = pygame.mouse.get_pos()
if c[0] < self.viewer.get_width():
try:
if self.game.pressed[pygame.K_k]:
self.viewer.map.adjust_size(1,0,self.tile)
self.viewer.paint_map()
elif self.game.pressed[pygame.K_l]:
self.viewer.map.adjust_size(-1,0,self.tile)
self.viewer.paint_map()
if self.game.pressed[pygame.K_j]:
self.viewer.map.adjust_size(0,1,self.tile)
self.viewer.paint_map()
elif self.game.pressed[pygame.K_u]:
self.viewer.map.adjust_size(0,-1,self.tile)
self.viewer.paint_map()
except:pass
if pygame.K_RETURN in self.game.just_pressed:
self.threads=[self.clear,self.viewer,self.input,self.paint_palette,self.cur]
def on_terminate(self): self.viewer.map.struct = self.viewer.map.struct.__dict__
def input(self):
c = pygame.mouse.get_pos()
self.cursor_loc = 0
if c[0] < self.viewer.get_width():
self.cursor = [int((c[0]-self.viewer.map_dest[0])/16),int((c[1]-self.viewer.map_dest[1])/16)]
if self.game.pressed[pygame.K_UP]:self.viewer.adjust_camera(0,-16,True)
elif self.game.pressed[pygame.K_DOWN]:self.viewer.adjust_camera(0,16,True)
if self.game.pressed[pygame.K_LEFT]:self.viewer.adjust_camera(-16,0,True)
elif self.game.pressed[pygame.K_RIGHT]:self.viewer.adjust_camera(16,0,True)
if pygame.K_r in self.game.just_pressed:
self.threads=[self.viewer,self.input_resize]
if self.cursor[0]>=0 and self.cursor[0]<=self.viewer.map.struct.size[0]-1 and self.cursor[1]>=0 and self.cursor[1]<=self.viewer.map.struct.size[1]-1:
self.cursor_loc = 1
if self.game.mouse[0]:self.viewer.set_tile(self.cursor[0],self.cursor[1],self.tile)
elif self.game.mouse[2]:self.tile=self.viewer.map.get_tile(*self.cursor)
elif c[1]<self.palette.get_height():
self.cursor = [int((c[0]-self.viewer.get_width())/16),int(c[1]/16)]
if self.game.just_clicked[0]:
try:
self.tile=get_tile_num(self.palette,self.cursor,len(self.viewer.map.tileset['dat']))
except:pass
self.cursor_loc = 2
def paint_palette(self):self.game.surf.blit(self.palette,[self.viewer.get_width(),0])
def cur(self):
if self.cursor_loc == 1:
self.game.surf.blit(self.palette,mix(self.viewer.map_dest,mix(self.cursor,[16]*2,lambda a,b:a*b)),get_tile_rect(self.palette,self.tile))
elif self.cursor_loc == 2:
pygame.draw.rect(self.game.surf,(255,0,0),[self.viewer.get_width()+self.cursor[0]*16,self.cursor[1]*16,16,16],1)
return
rel_rect = get_tile_rect(self.palette,self.tile)
rel_rect[0]+=self.viewer.get_width()
pygame.draw.rect(self.game.surf,(255,0,0),rel_rect,2)
def paint_tile_cur(self):pass
class Main(Task):
def __init__(self,game):
Task.__init__(self,game)
self.menu = tile_rpg.Menu(game,game.res[0],[(key,key) for key,obj in game.maps.items()])
self.editor,self.map = None, None
self.threads = [ self.clear, self.menu, self.check_menu]
def clear(self):self.game.surf.fill([0]*3)
def check_menu(self):
if not self.menu.open:
if self.menu.value is not None:
self.open_map = self.menu.value
map = tile_rpg.Map(self.game.tilesets,self.game.tileset_data,self.game.maps[self.menu.value])
self.editor = Editor(self.game,map)
self.threads = [ self.editor, self.input]
self.menu.reset()
def input(self):
if pygame.K_ESCAPE in self.game.just_pressed:
self.editor.terminate()
self.game.maps[self.open_map] = self.editor.viewer.map.struct
self.editor=None
self.open_map=None
self.threads=[self.clear,self.menu,self.check_menu]
def on_terminate(self):
if self.open_map:
self.editor.terminate()
self.game.maps[self.open_map] = self.editor.viewer.map.struct
class MapEditor(Game):
maps = load_data("maps", json.load)
tilesets = load_data("tilesets",load_trans_image,'r+b')
fonts = load_data("fonts", load_font,'r+b')
tileset_data = load_data("tilesets data",json.load)
res = (640,480)
def __init__(self):
Game.__init__(self, self.res)
self.center = (int(self.res[0]/16/2),int(self.res[1]/16/2))
self.font_table = { 'main':'fontwestern', 'menu':'fontwestern'}
self.register_task(Main(self))
def on_terminate(self):save_data("maps",self.maps)
run(MapEditor())
| Python |
#!/usr/bin/python
#
# Script to generate distorted text images for a captcha system.
#
# Copyright (C) 2005 Neil Harris
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# http://www.gnu.org/copyleft/gpl.html
#
# Further tweaks by Brion Vibber <brion@pobox.com>:
# 2006-01-26: Add command-line options for the various parameters
# 2007-02-19: Add --dirs param for hash subdirectory splits
# Tweaks by Greg Sabino Mullane <greg@turnstep.com>:
# 2008-01-06: Add regex check to skip words containing other than a-z
import random
import math
import hashlib
from optparse import OptionParser
import os
import sys
import re
try:
import Image
import ImageFont
import ImageDraw
import ImageEnhance
import ImageOps
except:
sys.exit("This script requires the Python Imaging Library - http://www.pythonware.com/products/pil/")
nonalpha = re.compile('[^a-z]') # regex to test for suitability of words
# Does X-axis wobbly copy, sandwiched between two rotates
def wobbly_copy(src, wob, col, scale, ang):
x, y = src.size
f = random.uniform(4*scale, 5*scale)
p = random.uniform(0, math.pi*2)
rr = ang+random.uniform(-30, 30) # vary, but not too much
int_d = Image.new('RGB', src.size, 0) # a black rectangle
rot = src.rotate(rr, Image.BILINEAR)
# Do a cheap bounding-box op here to try to limit work below
bbx = rot.getbbox()
if bbx == None:
return src
else:
l, t, r, b= bbx
# and only do lines with content on
for i in range(t, b+1):
# Drop a scan line in
xoff = int(math.sin(p+(i*f/y))*wob)
xoff += int(random.uniform(-wob*0.5, wob*0.5))
int_d.paste(rot.crop((0, i, x, i+1)), (xoff, i))
# try to stop blurring from building up
int_d = int_d.rotate(-rr, Image.BILINEAR)
enh = ImageEnhance.Sharpness(int_d)
return enh.enhance(2)
def gen_captcha(text, fontname, fontsize, file_name):
"""Generate a captcha image"""
# white text on a black background
bgcolor = 0x0
fgcolor = 0xffffff
# create a font object
font = ImageFont.truetype(fontname,fontsize)
# determine dimensions of the text
dim = font.getsize(text)
# create a new image significantly larger that the text
edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1])
im = Image.new('RGB', (edge, edge), bgcolor)
d = ImageDraw.Draw(im)
x, y = im.size
# add the text to the image
d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor)
k = 3
wob = 0.20*dim[1]/k
rot = 45
# Apply lots of small stirring operations, rather than a few large ones
# in order to get some uniformity of treatment, whilst
# maintaining randomness
for i in range(k):
im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0)
im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45)
im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90)
rot += 30
# now get the bounding box of the nonzero parts of the image
bbox = im.getbbox()
bord = min(dim[0], dim[1])/4 # a bit of a border
im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord))
# and turn into black on white
im = ImageOps.invert(im)
# save the image, in format determined from filename
im.save(file_name)
def gen_subdir(basedir, md5hash, levels):
"""Generate a subdirectory path out of the first _levels_
characters of _hash_, and ensure the directories exist
under _basedir_."""
subdir = None
for i in range(0, levels):
char = md5hash[i]
if subdir:
subdir = os.path.join(subdir, char)
else:
subdir = char
fulldir = os.path.join(basedir, subdir)
if not os.path.exists(fulldir):
os.mkdir(fulldir)
return subdir
def try_pick_word(words, blacklist, verbose, nwords, min_length, max_length):
if words is not None:
word = words[random.randint(0,len(words)-1)]
while nwords > 1:
word2 = words[random.randint(0,len(words)-1)]
word = word + word2
nwords = nwords - 1
else:
word = ''
max_length = max_length if max_length > 0 else 10
for i in range(0, random.randint(min_length, max_length)):
word = word + chr(97 + random.randint(0,25))
if verbose:
print "word is %s" % word
if len(word) < min_length:
if verbose:
print "skipping word pair '%s' because it has fewer than %d characters" % (word, min_length)
return None
if max_length > 0 and len(word) > max_length:
if verbose:
print "skipping word pair '%s' because it has more than %d characters" % (word, max_length)
return None
if nonalpha.search(word):
if verbose:
print "skipping word pair '%s' because it contains non-alphabetic characters" % word
return None
for naughty in blacklist:
if naughty in word:
if verbose:
print "skipping word pair '%s' because it contains blacklisted word '%s'" % (word, naughty)
return None
return word
def pick_word(words, blacklist, verbose, nwords, min_length, max_length):
for x in range(1000): # If we can't find a valid combination in 1000 tries, just give up
word = try_pick_word(words, blacklist, verbose, nwords, min_length, max_length)
if word:
return word
sys.exit("Unable to find valid word combinations")
def read_wordlist(filename):
f = open(filename)
words = [x.strip().lower() for x in f.readlines()]
f.close()
return words
if __name__ == '__main__':
"""This grabs random words from the dictionary 'words' (one
word per line) and generates a captcha image for each one,
with a keyed salted hash of the correct answer in the filename.
To check a reply, hash it in the same way with the same salt and
secret key, then compare with the hash value given.
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
parser = OptionParser()
parser.add_option("--wordlist", help="A list of words (required)", metavar="WORDS.txt")
parser.add_option("--random", help="Use random charcters instead of a wordlist", action="store_true")
parser.add_option("--key", help="The passphrase set as $wgCaptchaSecret (required)", metavar="KEY")
parser.add_option("--output", help="The directory to put the images in - $wgCaptchaDirectory (required)", metavar="DIR")
parser.add_option("--font", help="The font to use (required)", metavar="FONT.ttf")
parser.add_option("--font-size", help="The font size (default 40)", metavar="N", type='int', default=40)
parser.add_option("--count", help="The maximum number of images to make (default 20)", metavar="N", type='int', default=20)
parser.add_option("--blacklist", help="A blacklist of words that should not be used", metavar="FILE", default=os.path.join(script_dir, "blacklist"))
parser.add_option("--fill", help="Fill the output directory to contain N files, overrides count, cannot be used with --dirs", metavar="N", type='int')
parser.add_option("--dirs", help="Put the images into subdirectories N levels deep - $wgCaptchaDirectoryLevels", metavar="N", type='int')
parser.add_option("--verbose", "-v", help="Show debugging information", action='store_true')
parser.add_option("--number-words", help="Number of words from the wordlist which make a captcha challenge (default 2)", type='int', default=2)
parser.add_option("--min-length", help="Minimum length for a captcha challenge", type='int', default=1)
parser.add_option("--max-length", help="Maximum length for a captcha challenge", type='int', default=-1)
opts, args = parser.parse_args()
if opts.wordlist:
wordlist = opts.wordlist
elif opts.random:
wordlist = None
else:
sys.exit("Need to specify a wordlist")
if opts.key:
key = opts.key
else:
sys.exit("Need to specify a key")
if opts.output:
output = opts.output
else:
sys.exit("Need to specify an output directory")
if opts.font and os.path.exists(opts.font):
font = opts.font
else:
sys.exit("Need to specify the location of a font")
blacklist = read_wordlist(opts.blacklist)
count = opts.count
fill = opts.fill
dirs = opts.dirs
verbose = opts.verbose
fontsize = opts.font_size
if fill:
count = max(0, fill - len(os.listdir(output)))
words = None
if wordlist:
words = read_wordlist(wordlist)
words = [x for x in words
if len(x) in (4,5) and x[0] != "f"
and x[0] != x[1] and x[-1] != x[-2]]
for i in range(count):
word = pick_word(words, blacklist, verbose, opts.number_words, opts.min_length, opts.max_length)
salt = "%08x" % random.randrange(2**32)
# 64 bits of hash is plenty for this purpose
md5hash = hashlib.md5(key+salt+word+key+salt).hexdigest()[:16]
filename = "image_%s_%s.png" % (salt, md5hash)
if dirs:
subdir = gen_subdir(output, md5hash, dirs)
filename = os.path.join(subdir, filename)
if verbose:
print filename
gen_captcha(word, font, fontsize, os.path.join(output, filename))
| Python |
#!/usr/bin/python
#
# Script to generate distorted text images for a captcha system.
#
# Copyright (C) 2005 Neil Harris
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
# http://www.gnu.org/copyleft/gpl.html
#
# Further tweaks by Brion Vibber <brion@pobox.com>:
# 2006-01-26: Add command-line options for the various parameters
# 2007-02-19: Add --dirs param for hash subdirectory splits
# Tweaks by Greg Sabino Mullane <greg@turnstep.com>:
# 2008-01-06: Add regex check to skip words containing other than a-z
import random
import math
import hashlib
from optparse import OptionParser
import os
import sys
import re
try:
import Image
import ImageFont
import ImageDraw
import ImageEnhance
import ImageOps
except:
sys.exit("This script requires the Python Imaging Library - http://www.pythonware.com/products/pil/")
nonalpha = re.compile('[^a-z]') # regex to test for suitability of words
# Does X-axis wobbly copy, sandwiched between two rotates
def wobbly_copy(src, wob, col, scale, ang):
x, y = src.size
f = random.uniform(4*scale, 5*scale)
p = random.uniform(0, math.pi*2)
rr = ang+random.uniform(-30, 30) # vary, but not too much
int_d = Image.new('RGB', src.size, 0) # a black rectangle
rot = src.rotate(rr, Image.BILINEAR)
# Do a cheap bounding-box op here to try to limit work below
bbx = rot.getbbox()
if bbx == None:
return src
else:
l, t, r, b= bbx
# and only do lines with content on
for i in range(t, b+1):
# Drop a scan line in
xoff = int(math.sin(p+(i*f/y))*wob)
xoff += int(random.uniform(-wob*0.5, wob*0.5))
int_d.paste(rot.crop((0, i, x, i+1)), (xoff, i))
# try to stop blurring from building up
int_d = int_d.rotate(-rr, Image.BILINEAR)
enh = ImageEnhance.Sharpness(int_d)
return enh.enhance(2)
def gen_captcha(text, fontname, fontsize, file_name):
"""Generate a captcha image"""
# white text on a black background
bgcolor = 0x0
fgcolor = 0xffffff
# create a font object
font = ImageFont.truetype(fontname,fontsize)
# determine dimensions of the text
dim = font.getsize(text)
# create a new image significantly larger that the text
edge = max(dim[0], dim[1]) + 2*min(dim[0], dim[1])
im = Image.new('RGB', (edge, edge), bgcolor)
d = ImageDraw.Draw(im)
x, y = im.size
# add the text to the image
d.text((x/2-dim[0]/2, y/2-dim[1]/2), text, font=font, fill=fgcolor)
k = 3
wob = 0.20*dim[1]/k
rot = 45
# Apply lots of small stirring operations, rather than a few large ones
# in order to get some uniformity of treatment, whilst
# maintaining randomness
for i in range(k):
im = wobbly_copy(im, wob, bgcolor, i*2+3, rot+0)
im = wobbly_copy(im, wob, bgcolor, i*2+1, rot+45)
im = wobbly_copy(im, wob, bgcolor, i*2+2, rot+90)
rot += 30
# now get the bounding box of the nonzero parts of the image
bbox = im.getbbox()
bord = min(dim[0], dim[1])/4 # a bit of a border
im = im.crop((bbox[0]-bord, bbox[1]-bord, bbox[2]+bord, bbox[3]+bord))
# and turn into black on white
im = ImageOps.invert(im)
# save the image, in format determined from filename
im.save(file_name)
def gen_subdir(basedir, md5hash, levels):
"""Generate a subdirectory path out of the first _levels_
characters of _hash_, and ensure the directories exist
under _basedir_."""
subdir = None
for i in range(0, levels):
char = md5hash[i]
if subdir:
subdir = os.path.join(subdir, char)
else:
subdir = char
fulldir = os.path.join(basedir, subdir)
if not os.path.exists(fulldir):
os.mkdir(fulldir)
return subdir
def try_pick_word(words, blacklist, verbose, nwords, min_length, max_length):
if words is not None:
word = words[random.randint(0,len(words)-1)]
while nwords > 1:
word2 = words[random.randint(0,len(words)-1)]
word = word + word2
nwords = nwords - 1
else:
word = ''
max_length = max_length if max_length > 0 else 10
for i in range(0, random.randint(min_length, max_length)):
word = word + chr(97 + random.randint(0,25))
if verbose:
print "word is %s" % word
if len(word) < min_length:
if verbose:
print "skipping word pair '%s' because it has fewer than %d characters" % (word, min_length)
return None
if max_length > 0 and len(word) > max_length:
if verbose:
print "skipping word pair '%s' because it has more than %d characters" % (word, max_length)
return None
if nonalpha.search(word):
if verbose:
print "skipping word pair '%s' because it contains non-alphabetic characters" % word
return None
for naughty in blacklist:
if naughty in word:
if verbose:
print "skipping word pair '%s' because it contains blacklisted word '%s'" % (word, naughty)
return None
return word
def pick_word(words, blacklist, verbose, nwords, min_length, max_length):
for x in range(1000): # If we can't find a valid combination in 1000 tries, just give up
word = try_pick_word(words, blacklist, verbose, nwords, min_length, max_length)
if word:
return word
sys.exit("Unable to find valid word combinations")
def read_wordlist(filename):
f = open(filename)
words = [x.strip().lower() for x in f.readlines()]
f.close()
return words
if __name__ == '__main__':
"""This grabs random words from the dictionary 'words' (one
word per line) and generates a captcha image for each one,
with a keyed salted hash of the correct answer in the filename.
To check a reply, hash it in the same way with the same salt and
secret key, then compare with the hash value given.
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
parser = OptionParser()
parser.add_option("--wordlist", help="A list of words (required)", metavar="WORDS.txt")
parser.add_option("--random", help="Use random charcters instead of a wordlist", action="store_true")
parser.add_option("--key", help="The passphrase set as $wgCaptchaSecret (required)", metavar="KEY")
parser.add_option("--output", help="The directory to put the images in - $wgCaptchaDirectory (required)", metavar="DIR")
parser.add_option("--font", help="The font to use (required)", metavar="FONT.ttf")
parser.add_option("--font-size", help="The font size (default 40)", metavar="N", type='int', default=40)
parser.add_option("--count", help="The maximum number of images to make (default 20)", metavar="N", type='int', default=20)
parser.add_option("--blacklist", help="A blacklist of words that should not be used", metavar="FILE", default=os.path.join(script_dir, "blacklist"))
parser.add_option("--fill", help="Fill the output directory to contain N files, overrides count, cannot be used with --dirs", metavar="N", type='int')
parser.add_option("--dirs", help="Put the images into subdirectories N levels deep - $wgCaptchaDirectoryLevels", metavar="N", type='int')
parser.add_option("--verbose", "-v", help="Show debugging information", action='store_true')
parser.add_option("--number-words", help="Number of words from the wordlist which make a captcha challenge (default 2)", type='int', default=2)
parser.add_option("--min-length", help="Minimum length for a captcha challenge", type='int', default=1)
parser.add_option("--max-length", help="Maximum length for a captcha challenge", type='int', default=-1)
opts, args = parser.parse_args()
if opts.wordlist:
wordlist = opts.wordlist
elif opts.random:
wordlist = None
else:
sys.exit("Need to specify a wordlist")
if opts.key:
key = opts.key
else:
sys.exit("Need to specify a key")
if opts.output:
output = opts.output
else:
sys.exit("Need to specify an output directory")
if opts.font and os.path.exists(opts.font):
font = opts.font
else:
sys.exit("Need to specify the location of a font")
blacklist = read_wordlist(opts.blacklist)
count = opts.count
fill = opts.fill
dirs = opts.dirs
verbose = opts.verbose
fontsize = opts.font_size
if fill:
count = max(0, fill - len(os.listdir(output)))
words = None
if wordlist:
words = read_wordlist(wordlist)
words = [x for x in words
if len(x) in (4,5) and x[0] != "f"
and x[0] != x[1] and x[-1] != x[-2]]
for i in range(count):
word = pick_word(words, blacklist, verbose, opts.number_words, opts.min_length, opts.max_length)
salt = "%08x" % random.randrange(2**32)
# 64 bits of hash is plenty for this purpose
md5hash = hashlib.md5(key+salt+word+key+salt).hexdigest()[:16]
filename = "image_%s_%s.png" % (salt, md5hash)
if dirs:
subdir = gen_subdir(output, md5hash, dirs)
filename = os.path.join(subdir, filename)
if verbose:
print filename
gen_captcha(word, font, fontsize, os.path.join(output, filename))
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author Philip
import tarfile as tf
import zipfile as zf
import os, re, shutil, sys, platform
pyversion = platform.python_version()
islinux = platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
open = codecs.open
_unichr = unichr
if sys.maxunicode < 0x10000:
def unichr(i):
if i < 0x10000:
return _unichr(i)
else:
return _unichr( 0xD7C0 + ( i>>10 ) ) + _unichr( 0xDC00 + ( i & 0x3FF ) )
elif pyversion[:2] == '3.':
import urllib.request as urllib_request
unichr = chr
def unichr2( *args ):
return [unichr( int( i.split('<')[0][2:], 16 ) ) for i in args]
def unichr3( *args ):
return [unichr( int( i[2:7], 16 ) ) for i in args if i[2:7]]
# DEFINE
UNIHAN_VER = '6.2.0'
SF_MIRROR = 'dfn'
SCIM_TABLES_VER = '0.5.11'
SCIM_PINYIN_VER = '0.5.92'
LIBTABE_VER = '0.2.3'
# END OF DEFINE
def download( url, dest ):
if os.path.isfile( dest ):
print( 'File %s is up to date.' % dest )
return
global islinux
if islinux:
# we use wget instead urlretrieve under Linux,
# because wget could display details like download progress
os.system( 'wget %s -O %s' % ( url, dest ) )
else:
print( 'Downloading from [%s] ...' % url )
urllib_request.urlretrieve( url, dest )
print( 'Download complete.\n' )
return
def uncompress( fp, member, encoding = 'U8' ):
name = member.rsplit( '/', 1 )[-1]
print( 'Extracting %s ...' % name )
fp.extract( member )
shutil.move( member, name )
if '/' in member:
shutil.rmtree( member.split( '/', 1 )[0] )
return open( name, 'rb', encoding, 'ignore' )
unzip = lambda path, member, encoding = 'U8': \
uncompress( zf.ZipFile( path ), member, encoding )
untargz = lambda path, member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark ):
start = True
continue
elif endmark and line.startswith( endmark ):
break
if start and not line.startswith( '#' ):
elems = line.split()
if len( elems ) < 2:
continue
elif len( elems[0] ) > 1 and \
len( elems[pos] ) > 1: # words only
mlist.add( elems[pos] )
return mlist
def tablesParser( path, name ):
""" Read file from scim-tables and parse it. """
global SCIM_TABLES_VER
src = 'scim-tables-%s/tables/zh/%s' % ( SCIM_TABLES_VER, name )
fp = untargz( path, src, 'U8' )
return parserCore( fp, 1, 'BEGIN_TABLE', 'END_TABLE' )
ezbigParser = lambda path: tablesParser( path, 'EZ-Big.txt.in' )
wubiParser = lambda path: tablesParser( path, 'Wubi.txt.in' )
zrmParser = lambda path: tablesParser( path, 'Ziranma.txt.in' )
def phraseParser( path ):
""" Read phrase_lib.txt and parse it. """
global SCIM_PINYIN_VER
src = 'scim-pinyin-%s/data/phrase_lib.txt' % SCIM_PINYIN_VER
dst = 'phrase_lib.txt'
fp = untargz( path, src, 'U8' )
return parserCore( fp, 0 )
def tsiParser( path ):
""" Read tsi.src and parse it. """
src = 'libtabe/tsi-src/tsi.src'
dst = 'tsi.src'
fp = untargz( path, src, 'big5hkscs' )
return parserCore( fp, 0 )
def unihanParser( path ):
""" Read Unihan_Variants.txt and parse it. """
fp = unzip( path, 'Unihan_Variants.txt', 'U8' )
t2s = dict()
s2t = dict()
for line in fp:
if line.startswith( '#' ):
continue
else:
elems = line.split()
if len( elems ) < 3:
continue
type = elems.pop( 1 )
elems = unichr2( *elems )
if type == 'kTraditionalVariant':
s2t[elems[0]] = elems[1:]
elif type == 'kSimplifiedVariant':
t2s[elems[0]] = elems[1:]
fp.close()
return ( t2s, s2t )
def applyExcludes( mlist, path ):
""" Apply exclude rules from path to mlist. """
excludes = open( path, 'rb', 'U8' ).read().split()
excludes = [word.split( '#' )[0].strip() for word in excludes]
excludes = '|'.join( excludes )
excptn = re.compile( '.*(?:%s).*' % excludes )
diff = [mword for mword in mlist if excptn.search( mword )]
mlist.difference_update( diff )
return mlist
def charManualTable( path ):
fp = open( path, 'rb', 'U8' )
ret = {}
for line in fp:
elems = line.split( '#' )[0].split( '|' )
elems = unichr3( *elems )
if len( elems ) > 1:
ret[elems[0]] = elems[1:]
return ret
def toManyRules( src_table ):
tomany = set()
for ( f, t ) in src_table.iteritems():
for i in range( 1, len( t ) ):
tomany.add( t[i] )
return tomany
def removeRules( path, table ):
fp = open( path, 'rb', 'U8' )
texc = list()
for line in fp:
elems = line.split( '=>' )
f = t = elems[0].strip()
if len( elems ) == 2:
t = elems[1].strip()
f = f.strip('"').strip("'")
t = t.strip('"').strip("'")
if f:
try:
table.pop( f )
except:
pass
if t:
texc.append( t )
texcptn = re.compile( '^(?:%s)$' % '|'.join( texc ) )
for (tmp_f, tmp_t) in table.copy().iteritems():
if texcptn.match( tmp_t ):
table.pop( tmp_f )
return table
def customRules( path ):
fp = open( path, 'rb', 'U8' )
ret = dict()
for line in fp:
elems = line.split( '#' )[0].split()
if len( elems ) > 1:
ret[elems[0]] = elems[1]
return ret
def dictToSortedList( src_table, pos ):
return sorted( src_table.items(), key = lambda m: m[pos] )
def translate( text, conv_table ):
i = 0
while i < len( text ):
for j in range( len( text ) - i, 0, -1 ):
f = text[i:][:j]
t = conv_table.get( f )
if t:
text = text[:i] + t + text[i:][j:]
i += len(t) - 1
break
i += 1
return text
def manualWordsTable( path, conv_table, reconv_table ):
fp = open( path, 'rb', 'U8' )
reconv_table = {}
wordlist = [line.split( '#' )[0].strip() for line in fp]
wordlist = list( set( wordlist ) )
wordlist.sort( key = len, reverse = True )
while wordlist:
word = wordlist.pop()
new_word = translate( word, conv_table )
rcv_word = translate( word, reconv_table )
if word != rcv_word:
reconv_table[word] = word
reconv_table[new_word] = word
return reconv_table
def defaultWordsTable( src_wordlist, src_tomany, char_conv_table, char_reconv_table ):
wordlist = list( src_wordlist )
wordlist.sort( key = len, reverse = True )
word_conv_table = {}
word_reconv_table = {}
conv_table = char_conv_table.copy()
reconv_table = char_reconv_table.copy()
tomanyptn = re.compile( '(?:%s)' % '|'.join( src_tomany ) )
while wordlist:
conv_table.update( word_conv_table )
reconv_table.update( word_reconv_table )
word = wordlist.pop()
new_word_len = word_len = len( word )
while new_word_len == word_len:
add = False
test_word = translate( word, reconv_table )
new_word = translate( word, conv_table )
if not reconv_table.get( new_word ) \
and ( test_word != word \
or ( tomanyptn.search( word ) \
and word != translate( new_word, reconv_table ) ) ):
word_conv_table[word] = new_word
word_reconv_table[new_word] = word
try:
word = wordlist.pop()
except IndexError:
break
new_word_len = len(word)
return word_reconv_table
def PHPArray( table ):
lines = ['\'%s\' => \'%s\',' % (f, t) for (f, t) in table if f and t]
return '\n'.join(lines)
def main():
#Get Unihan.zip:
url = 'http://www.unicode.org/Public/%s/ucd/Unihan.zip' % UNIHAN_VER
han_dest = 'Unihan.zip'
download( url, han_dest )
# Get scim-tables-$(SCIM_TABLES_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-tables-%s.tar.gz' % ( SF_MIRROR, SCIM_TABLES_VER )
tbe_dest = 'scim-tables-%s.tar.gz' % SCIM_TABLES_VER
download( url, tbe_dest )
# Get scim-pinyin-$(SCIM_PINYIN_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-pinyin-%s.tar.gz' % ( SF_MIRROR, SCIM_PINYIN_VER )
pyn_dest = 'scim-pinyin-%s.tar.gz' % SCIM_PINYIN_VER
download( url, pyn_dest )
# Get libtabe-$(LIBTABE_VER).tgz:
url = 'http://%s.dl.sourceforge.net/sourceforge/libtabe/libtabe-%s.tgz' % ( SF_MIRROR, LIBTABE_VER )
lbt_dest = 'libtabe-%s.tgz' % LIBTABE_VER
download( url, lbt_dest )
# Unihan.txt
( t2s_1tomany, s2t_1tomany ) = unihanParser( han_dest )
t2s_1tomany.update( charManualTable( 'trad2simp.manual' ) )
s2t_1tomany.update( charManualTable( 'simp2trad.manual' ) )
t2s_1to1 = dict( [( f, t[0] ) for ( f, t ) in t2s_1tomany.iteritems()] )
s2t_1to1 = dict( [( f, t[0] ) for ( f, t ) in s2t_1tomany.iteritems()] )
s_tomany = toManyRules( t2s_1tomany )
t_tomany = toManyRules( s2t_1tomany )
# noconvert rules
t2s_1to1 = removeRules( 'trad2simp_noconvert.manual', t2s_1to1 )
s2t_1to1 = removeRules( 'simp2trad_noconvert.manual', s2t_1to1 )
# the supper set for word to word conversion
t2s_1to1_supp = t2s_1to1.copy()
s2t_1to1_supp = s2t_1to1.copy()
t2s_1to1_supp.update( customRules( 'trad2simp_supp_set.manual' ) )
s2t_1to1_supp.update( customRules( 'simp2trad_supp_set.manual' ) )
# word to word manual rules
t2s_word2word_manual = manualWordsTable( 'simpphrases.manual', s2t_1to1_supp, t2s_1to1_supp )
t2s_word2word_manual.update( customRules( 'toSimp.manual' ) )
s2t_word2word_manual = manualWordsTable( 'tradphrases.manual', t2s_1to1_supp, s2t_1to1_supp )
s2t_word2word_manual.update( customRules( 'toTrad.manual' ) )
# word to word rules from input methods
t_wordlist = set()
s_wordlist = set()
t_wordlist.update( ezbigParser( tbe_dest ),
tsiParser( lbt_dest ) )
s_wordlist.update( wubiParser( tbe_dest ),
zrmParser( tbe_dest ),
phraseParser( pyn_dest ) )
# exclude
s_wordlist = applyExcludes( s_wordlist, 'simpphrases_exclude.manual' )
t_wordlist = applyExcludes( t_wordlist, 'tradphrases_exclude.manual' )
s2t_supp = s2t_1to1_supp.copy()
s2t_supp.update( s2t_word2word_manual )
t2s_supp = t2s_1to1_supp.copy()
t2s_supp.update( t2s_word2word_manual )
# parse list to dict
t2s_word2word = defaultWordsTable( s_wordlist, s_tomany, s2t_1to1_supp, t2s_supp )
t2s_word2word.update( t2s_word2word_manual )
s2t_word2word = defaultWordsTable( t_wordlist, t_tomany, t2s_1to1_supp, s2t_supp )
s2t_word2word.update( s2t_word2word_manual )
# Final tables
# sorted list toHans
t2s_1to1 = dict( [( f, t ) for ( f, t ) in t2s_1to1.iteritems() if f != t] )
toHans = dictToSortedList( t2s_1to1, 0 ) + dictToSortedList( t2s_word2word, 1 )
# sorted list toHant
s2t_1to1 = dict( [( f, t ) for ( f, t ) in s2t_1to1.iteritems() if f != t] )
toHant = dictToSortedList( s2t_1to1, 0 ) + dictToSortedList( s2t_word2word, 1 )
# sorted list toCN
toCN = dictToSortedList( customRules( 'toCN.manual' ), 1 )
# sorted list toHK
toHK = dictToSortedList( customRules( 'toHK.manual' ), 1 )
# sorted list toSG
toSG = dictToSortedList( customRules( 'toSG.manual' ), 1 )
# sorted list toTW
toTW = dictToSortedList( customRules( 'toTW.manual' ), 1 )
# Get PHP Array
php = '''<?php
/**
* Simplified / Traditional Chinese conversion tables
*
* Automatically generated using code and data in includes/zhtable/
* Do not modify directly!
*
* @file
*/
$zh2Hant = array(\n'''
php += PHPArray( toHant ) \
+ '\n);\n\n$zh2Hans = array(\n' \
+ PHPArray( toHans ) \
+ '\n);\n\n$zh2TW = array(\n' \
+ PHPArray( toTW ) \
+ '\n);\n\n$zh2HK = array(\n' \
+ PHPArray( toHK ) \
+ '\n);\n\n$zh2CN = array(\n' \
+ PHPArray( toCN ) \
+ '\n);\n\n$zh2SG = array(\n' \
+ PHPArray( toSG ) \
+ '\n);\n'
f = open( os.path.join( '..', '..', '..', 'includes', 'ZhConversion.php' ), 'wb', encoding = 'utf8' )
print ('Writing ZhConversion.php ... ')
f.write( php )
f.close()
# Remove temporary files
print ('Deleting temporary files ... ')
os.remove('EZ-Big.txt.in')
os.remove('phrase_lib.txt')
os.remove('tsi.src')
os.remove('Unihan_Variants.txt')
os.remove('Wubi.txt.in')
os.remove('Ziranma.txt.in')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author Philip
import tarfile as tf
import zipfile as zf
import os, re, shutil, sys, platform
pyversion = platform.python_version()
islinux = platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
open = codecs.open
_unichr = unichr
if sys.maxunicode < 0x10000:
def unichr(i):
if i < 0x10000:
return _unichr(i)
else:
return _unichr( 0xD7C0 + ( i>>10 ) ) + _unichr( 0xDC00 + ( i & 0x3FF ) )
elif pyversion[:2] == '3.':
import urllib.request as urllib_request
unichr = chr
def unichr2( *args ):
return [unichr( int( i.split('<')[0][2:], 16 ) ) for i in args]
def unichr3( *args ):
return [unichr( int( i[2:7], 16 ) ) for i in args if i[2:7]]
# DEFINE
UNIHAN_VER = '6.2.0'
SF_MIRROR = 'dfn'
SCIM_TABLES_VER = '0.5.11'
SCIM_PINYIN_VER = '0.5.92'
LIBTABE_VER = '0.2.3'
# END OF DEFINE
def download( url, dest ):
if os.path.isfile( dest ):
print( 'File %s is up to date.' % dest )
return
global islinux
if islinux:
# we use wget instead urlretrieve under Linux,
# because wget could display details like download progress
os.system( 'wget %s -O %s' % ( url, dest ) )
else:
print( 'Downloading from [%s] ...' % url )
urllib_request.urlretrieve( url, dest )
print( 'Download complete.\n' )
return
def uncompress( fp, member, encoding = 'U8' ):
name = member.rsplit( '/', 1 )[-1]
print( 'Extracting %s ...' % name )
fp.extract( member )
shutil.move( member, name )
if '/' in member:
shutil.rmtree( member.split( '/', 1 )[0] )
return open( name, 'rb', encoding, 'ignore' )
unzip = lambda path, member, encoding = 'U8': \
uncompress( zf.ZipFile( path ), member, encoding )
untargz = lambda path, member, encoding = 'U8': \
uncompress( tf.open( path, 'r:gz' ), member, encoding )
def parserCore( fp, pos, beginmark = None, endmark = None ):
if beginmark and endmark:
start = False
else: start = True
mlist = set()
for line in fp:
if beginmark and line.startswith( beginmark ):
start = True
continue
elif endmark and line.startswith( endmark ):
break
if start and not line.startswith( '#' ):
elems = line.split()
if len( elems ) < 2:
continue
elif len( elems[0] ) > 1 and \
len( elems[pos] ) > 1: # words only
mlist.add( elems[pos] )
return mlist
def tablesParser( path, name ):
""" Read file from scim-tables and parse it. """
global SCIM_TABLES_VER
src = 'scim-tables-%s/tables/zh/%s' % ( SCIM_TABLES_VER, name )
fp = untargz( path, src, 'U8' )
return parserCore( fp, 1, 'BEGIN_TABLE', 'END_TABLE' )
ezbigParser = lambda path: tablesParser( path, 'EZ-Big.txt.in' )
wubiParser = lambda path: tablesParser( path, 'Wubi.txt.in' )
zrmParser = lambda path: tablesParser( path, 'Ziranma.txt.in' )
def phraseParser( path ):
""" Read phrase_lib.txt and parse it. """
global SCIM_PINYIN_VER
src = 'scim-pinyin-%s/data/phrase_lib.txt' % SCIM_PINYIN_VER
dst = 'phrase_lib.txt'
fp = untargz( path, src, 'U8' )
return parserCore( fp, 0 )
def tsiParser( path ):
""" Read tsi.src and parse it. """
src = 'libtabe/tsi-src/tsi.src'
dst = 'tsi.src'
fp = untargz( path, src, 'big5hkscs' )
return parserCore( fp, 0 )
def unihanParser( path ):
""" Read Unihan_Variants.txt and parse it. """
fp = unzip( path, 'Unihan_Variants.txt', 'U8' )
t2s = dict()
s2t = dict()
for line in fp:
if line.startswith( '#' ):
continue
else:
elems = line.split()
if len( elems ) < 3:
continue
type = elems.pop( 1 )
elems = unichr2( *elems )
if type == 'kTraditionalVariant':
s2t[elems[0]] = elems[1:]
elif type == 'kSimplifiedVariant':
t2s[elems[0]] = elems[1:]
fp.close()
return ( t2s, s2t )
def applyExcludes( mlist, path ):
""" Apply exclude rules from path to mlist. """
excludes = open( path, 'rb', 'U8' ).read().split()
excludes = [word.split( '#' )[0].strip() for word in excludes]
excludes = '|'.join( excludes )
excptn = re.compile( '.*(?:%s).*' % excludes )
diff = [mword for mword in mlist if excptn.search( mword )]
mlist.difference_update( diff )
return mlist
def charManualTable( path ):
fp = open( path, 'rb', 'U8' )
ret = {}
for line in fp:
elems = line.split( '#' )[0].split( '|' )
elems = unichr3( *elems )
if len( elems ) > 1:
ret[elems[0]] = elems[1:]
return ret
def toManyRules( src_table ):
tomany = set()
for ( f, t ) in src_table.iteritems():
for i in range( 1, len( t ) ):
tomany.add( t[i] )
return tomany
def removeRules( path, table ):
fp = open( path, 'rb', 'U8' )
texc = list()
for line in fp:
elems = line.split( '=>' )
f = t = elems[0].strip()
if len( elems ) == 2:
t = elems[1].strip()
f = f.strip('"').strip("'")
t = t.strip('"').strip("'")
if f:
try:
table.pop( f )
except:
pass
if t:
texc.append( t )
texcptn = re.compile( '^(?:%s)$' % '|'.join( texc ) )
for (tmp_f, tmp_t) in table.copy().iteritems():
if texcptn.match( tmp_t ):
table.pop( tmp_f )
return table
def customRules( path ):
fp = open( path, 'rb', 'U8' )
ret = dict()
for line in fp:
elems = line.split( '#' )[0].split()
if len( elems ) > 1:
ret[elems[0]] = elems[1]
return ret
def dictToSortedList( src_table, pos ):
return sorted( src_table.items(), key = lambda m: m[pos] )
def translate( text, conv_table ):
i = 0
while i < len( text ):
for j in range( len( text ) - i, 0, -1 ):
f = text[i:][:j]
t = conv_table.get( f )
if t:
text = text[:i] + t + text[i:][j:]
i += len(t) - 1
break
i += 1
return text
def manualWordsTable( path, conv_table, reconv_table ):
fp = open( path, 'rb', 'U8' )
reconv_table = {}
wordlist = [line.split( '#' )[0].strip() for line in fp]
wordlist = list( set( wordlist ) )
wordlist.sort( key = len, reverse = True )
while wordlist:
word = wordlist.pop()
new_word = translate( word, conv_table )
rcv_word = translate( word, reconv_table )
if word != rcv_word:
reconv_table[word] = word
reconv_table[new_word] = word
return reconv_table
def defaultWordsTable( src_wordlist, src_tomany, char_conv_table, char_reconv_table ):
wordlist = list( src_wordlist )
wordlist.sort( key = len, reverse = True )
word_conv_table = {}
word_reconv_table = {}
conv_table = char_conv_table.copy()
reconv_table = char_reconv_table.copy()
tomanyptn = re.compile( '(?:%s)' % '|'.join( src_tomany ) )
while wordlist:
conv_table.update( word_conv_table )
reconv_table.update( word_reconv_table )
word = wordlist.pop()
new_word_len = word_len = len( word )
while new_word_len == word_len:
add = False
test_word = translate( word, reconv_table )
new_word = translate( word, conv_table )
if not reconv_table.get( new_word ) \
and ( test_word != word \
or ( tomanyptn.search( word ) \
and word != translate( new_word, reconv_table ) ) ):
word_conv_table[word] = new_word
word_reconv_table[new_word] = word
try:
word = wordlist.pop()
except IndexError:
break
new_word_len = len(word)
return word_reconv_table
def PHPArray( table ):
lines = ['\'%s\' => \'%s\',' % (f, t) for (f, t) in table if f and t]
return '\n'.join(lines)
def main():
#Get Unihan.zip:
url = 'http://www.unicode.org/Public/%s/ucd/Unihan.zip' % UNIHAN_VER
han_dest = 'Unihan.zip'
download( url, han_dest )
# Get scim-tables-$(SCIM_TABLES_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-tables-%s.tar.gz' % ( SF_MIRROR, SCIM_TABLES_VER )
tbe_dest = 'scim-tables-%s.tar.gz' % SCIM_TABLES_VER
download( url, tbe_dest )
# Get scim-pinyin-$(SCIM_PINYIN_VER).tar.gz:
url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-pinyin-%s.tar.gz' % ( SF_MIRROR, SCIM_PINYIN_VER )
pyn_dest = 'scim-pinyin-%s.tar.gz' % SCIM_PINYIN_VER
download( url, pyn_dest )
# Get libtabe-$(LIBTABE_VER).tgz:
url = 'http://%s.dl.sourceforge.net/sourceforge/libtabe/libtabe-%s.tgz' % ( SF_MIRROR, LIBTABE_VER )
lbt_dest = 'libtabe-%s.tgz' % LIBTABE_VER
download( url, lbt_dest )
# Unihan.txt
( t2s_1tomany, s2t_1tomany ) = unihanParser( han_dest )
t2s_1tomany.update( charManualTable( 'trad2simp.manual' ) )
s2t_1tomany.update( charManualTable( 'simp2trad.manual' ) )
t2s_1to1 = dict( [( f, t[0] ) for ( f, t ) in t2s_1tomany.iteritems()] )
s2t_1to1 = dict( [( f, t[0] ) for ( f, t ) in s2t_1tomany.iteritems()] )
s_tomany = toManyRules( t2s_1tomany )
t_tomany = toManyRules( s2t_1tomany )
# noconvert rules
t2s_1to1 = removeRules( 'trad2simp_noconvert.manual', t2s_1to1 )
s2t_1to1 = removeRules( 'simp2trad_noconvert.manual', s2t_1to1 )
# the supper set for word to word conversion
t2s_1to1_supp = t2s_1to1.copy()
s2t_1to1_supp = s2t_1to1.copy()
t2s_1to1_supp.update( customRules( 'trad2simp_supp_set.manual' ) )
s2t_1to1_supp.update( customRules( 'simp2trad_supp_set.manual' ) )
# word to word manual rules
t2s_word2word_manual = manualWordsTable( 'simpphrases.manual', s2t_1to1_supp, t2s_1to1_supp )
t2s_word2word_manual.update( customRules( 'toSimp.manual' ) )
s2t_word2word_manual = manualWordsTable( 'tradphrases.manual', t2s_1to1_supp, s2t_1to1_supp )
s2t_word2word_manual.update( customRules( 'toTrad.manual' ) )
# word to word rules from input methods
t_wordlist = set()
s_wordlist = set()
t_wordlist.update( ezbigParser( tbe_dest ),
tsiParser( lbt_dest ) )
s_wordlist.update( wubiParser( tbe_dest ),
zrmParser( tbe_dest ),
phraseParser( pyn_dest ) )
# exclude
s_wordlist = applyExcludes( s_wordlist, 'simpphrases_exclude.manual' )
t_wordlist = applyExcludes( t_wordlist, 'tradphrases_exclude.manual' )
s2t_supp = s2t_1to1_supp.copy()
s2t_supp.update( s2t_word2word_manual )
t2s_supp = t2s_1to1_supp.copy()
t2s_supp.update( t2s_word2word_manual )
# parse list to dict
t2s_word2word = defaultWordsTable( s_wordlist, s_tomany, s2t_1to1_supp, t2s_supp )
t2s_word2word.update( t2s_word2word_manual )
s2t_word2word = defaultWordsTable( t_wordlist, t_tomany, t2s_1to1_supp, s2t_supp )
s2t_word2word.update( s2t_word2word_manual )
# Final tables
# sorted list toHans
t2s_1to1 = dict( [( f, t ) for ( f, t ) in t2s_1to1.iteritems() if f != t] )
toHans = dictToSortedList( t2s_1to1, 0 ) + dictToSortedList( t2s_word2word, 1 )
# sorted list toHant
s2t_1to1 = dict( [( f, t ) for ( f, t ) in s2t_1to1.iteritems() if f != t] )
toHant = dictToSortedList( s2t_1to1, 0 ) + dictToSortedList( s2t_word2word, 1 )
# sorted list toCN
toCN = dictToSortedList( customRules( 'toCN.manual' ), 1 )
# sorted list toHK
toHK = dictToSortedList( customRules( 'toHK.manual' ), 1 )
# sorted list toSG
toSG = dictToSortedList( customRules( 'toSG.manual' ), 1 )
# sorted list toTW
toTW = dictToSortedList( customRules( 'toTW.manual' ), 1 )
# Get PHP Array
php = '''<?php
/**
* Simplified / Traditional Chinese conversion tables
*
* Automatically generated using code and data in includes/zhtable/
* Do not modify directly!
*
* @file
*/
$zh2Hant = array(\n'''
php += PHPArray( toHant ) \
+ '\n);\n\n$zh2Hans = array(\n' \
+ PHPArray( toHans ) \
+ '\n);\n\n$zh2TW = array(\n' \
+ PHPArray( toTW ) \
+ '\n);\n\n$zh2HK = array(\n' \
+ PHPArray( toHK ) \
+ '\n);\n\n$zh2CN = array(\n' \
+ PHPArray( toCN ) \
+ '\n);\n\n$zh2SG = array(\n' \
+ PHPArray( toSG ) \
+ '\n);\n'
f = open( os.path.join( '..', '..', '..', 'includes', 'ZhConversion.php' ), 'wb', encoding = 'utf8' )
print ('Writing ZhConversion.php ... ')
f.write( php )
f.close()
# Remove temporary files
print ('Deleting temporary files ... ')
os.remove('EZ-Big.txt.in')
os.remove('phrase_lib.txt')
os.remove('tsi.src')
os.remove('Unihan_Variants.txt')
os.remove('Wubi.txt.in')
os.remove('Ziranma.txt.in')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
#
# Copyright 2007 Google Inc. All Rights Reserved.
"""CSS Lexical Grammar rules.
CSS lexical grammar from http://www.w3.org/TR/CSS21/grammar.html
"""
__author__ = ['elsigh@google.com (Lindsey Simon)',
'msamuel@google.com (Mike Samuel)']
# public symbols
__all__ = [ "NEWLINE", "HEX", "NON_ASCII", "UNICODE", "ESCAPE", "NMSTART", "NMCHAR", "STRING1", "STRING2", "IDENT", "NAME", "HASH", "NUM", "STRING", "URL", "SPACE", "WHITESPACE", "COMMENT", "QUANTITY", "PUNC" ]
# The comments below are mostly copied verbatim from the grammar.
# "@import" {return IMPORT_SYM;}
# "@page" {return PAGE_SYM;}
# "@media" {return MEDIA_SYM;}
# "@charset" {return CHARSET_SYM;}
KEYWORD = r'(?:\@(?:import|page|media|charset))'
# nl \n|\r\n|\r|\f ; a newline
NEWLINE = r'\n|\r\n|\r|\f'
# h [0-9a-f] ; a hexadecimal digit
HEX = r'[0-9a-f]'
# nonascii [\200-\377]
NON_ASCII = r'[\200-\377]'
# unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])?
UNICODE = r'(?:(?:\\' + HEX + r'{1,6})(?:\r\n|[ \t\r\n\f])?)'
# escape {unicode}|\\[^\r\n\f0-9a-f]
ESCAPE = r'(?:' + UNICODE + r'|\\[^\r\n\f0-9a-f])'
# nmstart [_a-z]|{nonascii}|{escape}
NMSTART = r'(?:[_a-z]|' + NON_ASCII + r'|' + ESCAPE + r')'
# nmchar [_a-z0-9-]|{nonascii}|{escape}
NMCHAR = r'(?:[_a-z0-9-]|' + NON_ASCII + r'|' + ESCAPE + r')'
# ident -?{nmstart}{nmchar}*
IDENT = r'-?' + NMSTART + NMCHAR + '*'
# name {nmchar}+
NAME = NMCHAR + r'+'
# hash
HASH = r'#' + NAME
# string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\" ; "string"
STRING1 = r'"(?:[^\"\\]|\\.)*"'
# string2 \'([^\n\r\f\\']|\\{nl}|{escape})*\' ; 'string'
STRING2 = r"'(?:[^\'\\]|\\.)*'"
# string {string1}|{string2}
STRING = '(?:' + STRING1 + r'|' + STRING2 + ')'
# num [0-9]+|[0-9]*"."[0-9]+
NUM = r'(?:[0-9]*\.[0-9]+|[0-9]+)'
# s [ \t\r\n\f]
SPACE = r'[ \t\r\n\f]'
# w {s}*
WHITESPACE = '(?:' + SPACE + r'*)'
# url special chars
URL_SPECIAL_CHARS = r'[!#$%&*-~]'
# url chars ({url_special_chars}|{nonascii}|{escape})*
URL_CHARS = r'(?:%s|%s|%s)*' % (URL_SPECIAL_CHARS, NON_ASCII, ESCAPE)
# url
URL = r'url\(%s(%s|%s)%s\)' % (WHITESPACE, STRING, URL_CHARS, WHITESPACE)
# comments
# see http://www.w3.org/TR/CSS21/grammar.html
COMMENT = r'/\*[^*]*\*+([^/*][^*]*\*+)*/'
# {E}{M} {return EMS;}
# {E}{X} {return EXS;}
# {P}{X} {return LENGTH;}
# {C}{M} {return LENGTH;}
# {M}{M} {return LENGTH;}
# {I}{N} {return LENGTH;}
# {P}{T} {return LENGTH;}
# {P}{C} {return LENGTH;}
# {D}{E}{G} {return ANGLE;}
# {R}{A}{D} {return ANGLE;}
# {G}{R}{A}{D} {return ANGLE;}
# {M}{S} {return TIME;}
# {S} {return TIME;}
# {H}{Z} {return FREQ;}
# {K}{H}{Z} {return FREQ;}
# % {return PERCENTAGE;}
UNIT = r'(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)'
# {num}{UNIT|IDENT} {return NUMBER;}
QUANTITY = '%s(?:%s%s|%s)?' % (NUM, WHITESPACE, UNIT, IDENT)
# "<!--" {return CDO;}
# "-->" {return CDC;}
# "~=" {return INCLUDES;}
# "|=" {return DASHMATCH;}
# {w}"{" {return LBRACE;}
# {w}"+" {return PLUS;}
# {w}">" {return GREATER;}
# {w}"," {return COMMA;}
PUNC = r'<!--|-->|~=|\|=|[\{\+>,:;]'
| Python |
#!/usr/bin/python
#
# Copyright 2008 Google Inc. All Rights Reserved.
"""Converts a LeftToRight Cascading Style Sheet into a RightToLeft one.
This is a utility script for replacing "left" oriented things in a CSS file
like float, padding, margin with "right" oriented values.
It also does the opposite.
The goal is to be able to conditionally serve one large, cat'd, compiled CSS
file appropriate for LeftToRight oriented languages and RightToLeft ones.
This utility will hopefully help your structural layout done in CSS in
terms of its RTL compatibility. It will not help with some of the more
complicated bidirectional text issues.
"""
__author__ = 'elsigh@google.com (Lindsey Simon)'
__version__ = '0.1'
import logging
import re
import sys
import getopt
import os
import csslex
logging.getLogger().setLevel(logging.INFO)
# Global for the command line flags.
SWAP_LTR_RTL_IN_URL_DEFAULT = False
SWAP_LEFT_RIGHT_IN_URL_DEFAULT = False
FLAGS = {'swap_ltr_rtl_in_url': SWAP_LTR_RTL_IN_URL_DEFAULT,
'swap_left_right_in_url': SWAP_LEFT_RIGHT_IN_URL_DEFAULT}
# Generic token delimiter character.
TOKEN_DELIMITER = '~'
# This is a temporary match token we use when swapping strings.
TMP_TOKEN = '%sTMP%s' % (TOKEN_DELIMITER, TOKEN_DELIMITER)
# Token to be used for joining lines.
TOKEN_LINES = '%sJ%s' % (TOKEN_DELIMITER, TOKEN_DELIMITER)
# Global constant text strings for CSS value matches.
LTR = 'ltr'
RTL = 'rtl'
LEFT = 'left'
RIGHT = 'right'
# This is a lookbehind match to ensure that we don't replace instances
# of our string token (left, rtl, etc...) if there's a letter in front of it.
# Specifically, this prevents replacements like 'background: url(bright.png)'.
LOOKBEHIND_NOT_LETTER = r'(?<![a-zA-Z])'
# This is a lookahead match to make sure we don't replace left and right
# in actual classnames, so that we don't break the HTML/CSS dependencies.
# Read literally, it says ignore cases where the word left, for instance, is
# directly followed by valid classname characters and a curly brace.
# ex: .column-left {float: left} will become .column-left {float: right}
LOOKAHEAD_NOT_OPEN_BRACE = (r'(?!(?:%s|%s|%s|#|\:|\.|\,|\+|>)*?{)' %
(csslex.NMCHAR, TOKEN_LINES, csslex.SPACE))
# These two lookaheads are to test whether or not we are within a
# background: url(HERE) situation.
# Ref: http://www.w3.org/TR/CSS21/syndata.html#uri
VALID_AFTER_URI_CHARS = r'[\'\"]?%s' % csslex.WHITESPACE
LOOKAHEAD_NOT_CLOSING_PAREN = r'(?!%s?%s\))' % (csslex.URL_CHARS,
VALID_AFTER_URI_CHARS)
LOOKAHEAD_FOR_CLOSING_PAREN = r'(?=%s?%s\))' % (csslex.URL_CHARS,
VALID_AFTER_URI_CHARS)
# Compile a regex to swap left and right values in 4 part notations.
# We need to match negatives and decimal numeric values.
# ex. 'margin: .25em -2px 3px 0' becomes 'margin: .25em 0 3px -2px'.
POSSIBLY_NEGATIVE_QUANTITY = r'((?:-?%s)|(?:inherit|auto))' % csslex.QUANTITY
POSSIBLY_NEGATIVE_QUANTITY_SPACE = r'%s%s%s' % (POSSIBLY_NEGATIVE_QUANTITY,
csslex.SPACE,
csslex.WHITESPACE)
FOUR_NOTATION_QUANTITY_RE = re.compile(r'%s%s%s%s' %
(POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY),
re.I)
COLOR = r'(%s|%s)' % (csslex.NAME, csslex.HASH)
COLOR_SPACE = r'%s%s' % (COLOR, csslex.SPACE)
FOUR_NOTATION_COLOR_RE = re.compile(r'(-color%s:%s)%s%s%s(%s)' %
(csslex.WHITESPACE,
csslex.WHITESPACE,
COLOR_SPACE,
COLOR_SPACE,
COLOR_SPACE,
COLOR),
re.I)
# Compile the cursor resize regexes
CURSOR_EAST_RE = re.compile(LOOKBEHIND_NOT_LETTER + '([ns]?)e-resize')
CURSOR_WEST_RE = re.compile(LOOKBEHIND_NOT_LETTER + '([ns]?)w-resize')
# Matches the condition where we need to replace the horizontal component
# of a background-position value when expressed in horizontal percentage.
# Had to make two regexes because in the case of position-x there is only
# one quantity, and otherwise we don't want to match and change cases with only
# one quantity.
BG_HORIZONTAL_PERCENTAGE_RE = re.compile(r'background(-position)?(%s:%s)'
'([^%%]*?)(%s)%%'
'(%s(?:%s|%s))' % (csslex.WHITESPACE,
csslex.WHITESPACE,
csslex.NUM,
csslex.WHITESPACE,
csslex.QUANTITY,
csslex.IDENT))
BG_HORIZONTAL_PERCENTAGE_X_RE = re.compile(r'background-position-x(%s:%s)'
'(%s)%%' % (csslex.WHITESPACE,
csslex.WHITESPACE,
csslex.NUM))
# Matches the opening of a body selector.
BODY_SELECTOR = r'body%s{%s' % (csslex.WHITESPACE, csslex.WHITESPACE)
# Matches anything up until the closing of a selector.
CHARS_WITHIN_SELECTOR = r'[^\}]*?'
# Matches the direction property in a selector.
DIRECTION_RE = r'direction%s:%s' % (csslex.WHITESPACE, csslex.WHITESPACE)
# These allow us to swap "ltr" with "rtl" and vice versa ONLY within the
# body selector and on the same line.
BODY_DIRECTION_LTR_RE = re.compile(r'(%s)(%s)(%s)(ltr)' %
(BODY_SELECTOR, CHARS_WITHIN_SELECTOR,
DIRECTION_RE),
re.I)
BODY_DIRECTION_RTL_RE = re.compile(r'(%s)(%s)(%s)(rtl)' %
(BODY_SELECTOR, CHARS_WITHIN_SELECTOR,
DIRECTION_RE),
re.I)
# Allows us to swap "direction:ltr" with "direction:rtl" and
# vice versa anywhere in a line.
DIRECTION_LTR_RE = re.compile(r'%s(ltr)' % DIRECTION_RE)
DIRECTION_RTL_RE = re.compile(r'%s(rtl)' % DIRECTION_RE)
# We want to be able to switch left with right and vice versa anywhere
# we encounter left/right strings, EXCEPT inside the background:url(). The next
# two regexes are for that purpose. We have alternate IN_URL versions of the
# regexes compiled in case the user passes the flag that they do
# actually want to have left and right swapped inside of background:urls.
LEFT_RE = re.compile('%s(%s)%s%s' % (LOOKBEHIND_NOT_LETTER,
LEFT,
LOOKAHEAD_NOT_CLOSING_PAREN,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
RIGHT_RE = re.compile('%s(%s)%s%s' % (LOOKBEHIND_NOT_LETTER,
RIGHT,
LOOKAHEAD_NOT_CLOSING_PAREN,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
LEFT_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
LEFT,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
RIGHT_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
RIGHT,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
LTR_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
LTR,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
RTL_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
RTL,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
COMMENT_RE = re.compile('(%s)' % csslex.COMMENT, re.I)
NOFLIP_TOKEN = r'\@noflip'
# The NOFLIP_TOKEN inside of a comment. For now, this requires that comments
# be in the input, which means users of a css compiler would have to run
# this script first if they want this functionality.
NOFLIP_ANNOTATION = r'/\*%s%s%s\*/' % (csslex.WHITESPACE,
NOFLIP_TOKEN,
csslex. WHITESPACE)
# After a NOFLIP_ANNOTATION, and within a class selector, we want to be able
# to set aside a single rule not to be flipped. We can do this by matching
# our NOFLIP annotation and then using a lookahead to make sure there is not
# an opening brace before the match.
NOFLIP_SINGLE_RE = re.compile(r'(%s%s[^;}]+;?)' % (NOFLIP_ANNOTATION,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
# After a NOFLIP_ANNOTATION, we want to grab anything up until the next } which
# means the entire following class block. This will prevent all of its
# declarations from being flipped.
NOFLIP_CLASS_RE = re.compile(r'(%s%s})' % (NOFLIP_ANNOTATION,
CHARS_WITHIN_SELECTOR),
re.I)
class Tokenizer:
"""Replaces any CSS comments with string tokens and vice versa."""
def __init__(self, token_re, token_string):
"""Constructor for the Tokenizer.
Args:
token_re: A regex for the string to be replace by a token.
token_string: The string to put between token delimiters when tokenizing.
"""
logging.debug('Tokenizer::init token_string=%s' % token_string)
self.token_re = token_re
self.token_string = token_string
self.originals = []
def Tokenize(self, line):
"""Replaces any string matching token_re in line with string tokens.
By passing a function as an argument to the re.sub line below, we bypass
the usual rule where re.sub will only replace the left-most occurrence of
a match by calling the passed in function for each occurrence.
Args:
line: A line to replace token_re matches in.
Returns:
line: A line with token_re matches tokenized.
"""
line = self.token_re.sub(self.TokenizeMatches, line)
logging.debug('Tokenizer::Tokenize returns: %s' % line)
return line
def DeTokenize(self, line):
"""Replaces tokens with the original string.
Args:
line: A line with tokens.
Returns:
line with any tokens replaced by the original string.
"""
# Put all of the comments back in by their comment token.
for i, original in enumerate(self.originals):
token = '%s%s_%s%s' % (TOKEN_DELIMITER, self.token_string, i + 1,
TOKEN_DELIMITER)
line = line.replace(token, original)
logging.debug('Tokenizer::DeTokenize i:%s w/%s' % (i, token))
logging.debug('Tokenizer::DeTokenize returns: %s' % line)
return line
def TokenizeMatches(self, m):
"""Replaces matches with tokens and stores the originals.
Args:
m: A match object.
Returns:
A string token which replaces the CSS comment.
"""
logging.debug('Tokenizer::TokenizeMatches %s' % m.group(1))
self.originals.append(m.group(1))
return '%s%s_%s%s' % (TOKEN_DELIMITER,
self.token_string,
len(self.originals),
TOKEN_DELIMITER)
def FixBodyDirectionLtrAndRtl(line):
"""Replaces ltr with rtl and vice versa ONLY in the body direction.
Args:
line: A string to replace instances of ltr with rtl.
Returns:
line with direction: ltr and direction: rtl swapped only in body selector.
line = FixBodyDirectionLtrAndRtl('body { direction:ltr }')
line will now be 'body { direction:rtl }'.
"""
line = BODY_DIRECTION_LTR_RE.sub('\\1\\2\\3%s' % TMP_TOKEN, line)
line = BODY_DIRECTION_RTL_RE.sub('\\1\\2\\3%s' % LTR, line)
line = line.replace(TMP_TOKEN, RTL)
logging.debug('FixBodyDirectionLtrAndRtl returns: %s' % line)
return line
def FixLeftAndRight(line):
"""Replaces left with right and vice versa in line.
Args:
line: A string in which to perform the replacement.
Returns:
line with left and right swapped. For example:
line = FixLeftAndRight('padding-left: 2px; margin-right: 1px;')
line will now be 'padding-right: 2px; margin-left: 1px;'.
"""
line = LEFT_RE.sub(TMP_TOKEN, line)
line = RIGHT_RE.sub(LEFT, line)
line = line.replace(TMP_TOKEN, RIGHT)
logging.debug('FixLeftAndRight returns: %s' % line)
return line
def FixLeftAndRightInUrl(line):
"""Replaces left with right and vice versa ONLY within background urls.
Args:
line: A string in which to replace left with right and vice versa.
Returns:
line with left and right swapped in the url string. For example:
line = FixLeftAndRightInUrl('background:url(right.png)')
line will now be 'background:url(left.png)'.
"""
line = LEFT_IN_URL_RE.sub(TMP_TOKEN, line)
line = RIGHT_IN_URL_RE.sub(LEFT, line)
line = line.replace(TMP_TOKEN, RIGHT)
logging.debug('FixLeftAndRightInUrl returns: %s' % line)
return line
def FixLtrAndRtlInUrl(line):
"""Replaces ltr with rtl and vice versa ONLY within background urls.
Args:
line: A string in which to replace ltr with rtl and vice versa.
Returns:
line with left and right swapped. For example:
line = FixLtrAndRtlInUrl('background:url(rtl.png)')
line will now be 'background:url(ltr.png)'.
"""
line = LTR_IN_URL_RE.sub(TMP_TOKEN, line)
line = RTL_IN_URL_RE.sub(LTR, line)
line = line.replace(TMP_TOKEN, RTL)
logging.debug('FixLtrAndRtlInUrl returns: %s' % line)
return line
def FixCursorProperties(line):
"""Fixes directional CSS cursor properties.
Args:
line: A string to fix CSS cursor properties in.
Returns:
line reformatted with the cursor properties substituted. For example:
line = FixCursorProperties('cursor: ne-resize')
line will now be 'cursor: nw-resize'.
"""
line = CURSOR_EAST_RE.sub('\\1' + TMP_TOKEN, line)
line = CURSOR_WEST_RE.sub('\\1e-resize', line)
line = line.replace(TMP_TOKEN, 'w-resize')
logging.debug('FixCursorProperties returns: %s' % line)
return line
def FixFourPartNotation(line):
"""Fixes the second and fourth positions in 4 part CSS notation.
Args:
line: A string to fix 4 part CSS notation in.
Returns:
line reformatted with the 4 part notations swapped. For example:
line = FixFourPartNotation('padding: 1px 2px 3px 4px')
line will now be 'padding: 1px 4px 3px 2px'.
"""
line = FOUR_NOTATION_QUANTITY_RE.sub('\\1 \\4 \\3 \\2', line)
line = FOUR_NOTATION_COLOR_RE.sub('\\1\\2 \\5 \\4 \\3', line)
logging.debug('FixFourPartNotation returns: %s' % line)
return line
def FixBackgroundPosition(line):
"""Fixes horizontal background percentage values in line.
Args:
line: A string to fix horizontal background position values in.
Returns:
line reformatted with the 4 part notations swapped.
"""
line = BG_HORIZONTAL_PERCENTAGE_RE.sub(CalculateNewBackgroundPosition, line)
line = BG_HORIZONTAL_PERCENTAGE_X_RE.sub(CalculateNewBackgroundPositionX,
line)
logging.debug('FixBackgroundPosition returns: %s' % line)
return line
def CalculateNewBackgroundPosition(m):
"""Fixes horizontal background-position percentages.
This function should be used as an argument to re.sub since it needs to
perform replacement specific calculations.
Args:
m: A match object.
Returns:
A string with the horizontal background position percentage fixed.
BG_HORIZONTAL_PERCENTAGE_RE.sub(FixBackgroundPosition,
'background-position: 75% 50%')
will return 'background-position: 25% 50%'.
"""
# The flipped value is the offset from 100%
new_x = str(100-int(m.group(4)))
# Since m.group(1) may very well be None type and we need a string..
if m.group(1):
position_string = m.group(1)
else:
position_string = ''
return 'background%s%s%s%s%%%s' % (position_string, m.group(2), m.group(3),
new_x, m.group(5))
def CalculateNewBackgroundPositionX(m):
"""Fixes percent based background-position-x.
This function should be used as an argument to re.sub since it needs to
perform replacement specific calculations.
Args:
m: A match object.
Returns:
A string with the background-position-x percentage fixed.
BG_HORIZONTAL_PERCENTAGE_X_RE.sub(CalculateNewBackgroundPosition,
'background-position-x: 75%')
will return 'background-position-x: 25%'.
"""
# The flipped value is the offset from 100%
new_x = str(100-int(m.group(2)))
return 'background-position-x%s%s%%' % (m.group(1), new_x)
def ChangeLeftToRightToLeft(lines,
swap_ltr_rtl_in_url=None,
swap_left_right_in_url=None):
"""Turns lines into a stream and runs the fixing functions against it.
Args:
lines: An list of CSS lines.
swap_ltr_rtl_in_url: Overrides this flag if param is set.
swap_left_right_in_url: Overrides this flag if param is set.
Returns:
The same lines, but with left and right fixes.
"""
global FLAGS
# Possibly override flags with params.
logging.debug('ChangeLeftToRightToLeft swap_ltr_rtl_in_url=%s, '
'swap_left_right_in_url=%s' % (swap_ltr_rtl_in_url,
swap_left_right_in_url))
if swap_ltr_rtl_in_url is None:
swap_ltr_rtl_in_url = FLAGS['swap_ltr_rtl_in_url']
if swap_left_right_in_url is None:
swap_left_right_in_url = FLAGS['swap_left_right_in_url']
# Turns the array of lines into a single line stream.
logging.debug('LINES COUNT: %s' % len(lines))
line = TOKEN_LINES.join(lines)
# Tokenize any single line rules with the /* noflip */ annotation.
noflip_single_tokenizer = Tokenizer(NOFLIP_SINGLE_RE, 'NOFLIP_SINGLE')
line = noflip_single_tokenizer.Tokenize(line)
# Tokenize any class rules with the /* noflip */ annotation.
noflip_class_tokenizer = Tokenizer(NOFLIP_CLASS_RE, 'NOFLIP_CLASS')
line = noflip_class_tokenizer.Tokenize(line)
# Tokenize the comments so we can preserve them through the changes.
comment_tokenizer = Tokenizer(COMMENT_RE, 'C')
line = comment_tokenizer.Tokenize(line)
# Here starteth the various left/right orientation fixes.
line = FixBodyDirectionLtrAndRtl(line)
if swap_left_right_in_url:
line = FixLeftAndRightInUrl(line)
if swap_ltr_rtl_in_url:
line = FixLtrAndRtlInUrl(line)
line = FixLeftAndRight(line)
line = FixCursorProperties(line)
line = FixFourPartNotation(line)
line = FixBackgroundPosition(line)
# DeTokenize the single line noflips.
line = noflip_single_tokenizer.DeTokenize(line)
# DeTokenize the class-level noflips.
line = noflip_class_tokenizer.DeTokenize(line)
# DeTokenize the comments.
line = comment_tokenizer.DeTokenize(line)
# Rejoin the lines back together.
lines = line.split(TOKEN_LINES)
return lines
def usage():
"""Prints out usage information."""
print 'Usage:'
print ' ./cssjanus.py < file.css > file-rtl.css'
print 'Flags:'
print ' --swap_left_right_in_url: Fixes "left"/"right" string within urls.'
print ' Ex: ./cssjanus.py --swap_left_right_in_url < file.css > file_rtl.css'
print ' --swap_ltr_rtl_in_url: Fixes "ltr"/"rtl" string within urls.'
print ' Ex: ./cssjanus --swap_ltr_rtl_in_url < file.css > file_rtl.css'
def setflags(opts):
"""Parse the passed in command line arguments and set the FLAGS global.
Args:
opts: getopt iterable intercepted from argv.
"""
global FLAGS
# Parse the arguments.
for opt, arg in opts:
logging.debug('opt: %s, arg: %s' % (opt, arg))
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-d", "--debug"):
logging.getLogger().setLevel(logging.DEBUG)
elif opt == '--swap_ltr_rtl_in_url':
FLAGS['swap_ltr_rtl_in_url'] = True
elif opt == '--swap_left_right_in_url':
FLAGS['swap_left_right_in_url'] = True
def main(argv):
"""Sends stdin lines to ChangeLeftToRightToLeft and writes to stdout."""
# Define the flags.
try:
opts, args = getopt.getopt(argv, 'hd', ['help', 'debug',
'swap_left_right_in_url',
'swap_ltr_rtl_in_url'])
except getopt.GetoptError:
usage()
sys.exit(2)
# Parse and set the flags.
setflags(opts)
# Call the main routine with all our functionality.
fixed_lines = ChangeLeftToRightToLeft(sys.stdin.readlines())
sys.stdout.write(''.join(fixed_lines))
if __name__ == '__main__':
main(sys.argv[1:])
| Python |
#!/usr/bin/python
#
# Copyright 2007 Google Inc. All Rights Reserved.
"""CSS Lexical Grammar rules.
CSS lexical grammar from http://www.w3.org/TR/CSS21/grammar.html
"""
__author__ = ['elsigh@google.com (Lindsey Simon)',
'msamuel@google.com (Mike Samuel)']
# public symbols
__all__ = [ "NEWLINE", "HEX", "NON_ASCII", "UNICODE", "ESCAPE", "NMSTART", "NMCHAR", "STRING1", "STRING2", "IDENT", "NAME", "HASH", "NUM", "STRING", "URL", "SPACE", "WHITESPACE", "COMMENT", "QUANTITY", "PUNC" ]
# The comments below are mostly copied verbatim from the grammar.
# "@import" {return IMPORT_SYM;}
# "@page" {return PAGE_SYM;}
# "@media" {return MEDIA_SYM;}
# "@charset" {return CHARSET_SYM;}
KEYWORD = r'(?:\@(?:import|page|media|charset))'
# nl \n|\r\n|\r|\f ; a newline
NEWLINE = r'\n|\r\n|\r|\f'
# h [0-9a-f] ; a hexadecimal digit
HEX = r'[0-9a-f]'
# nonascii [\200-\377]
NON_ASCII = r'[\200-\377]'
# unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])?
UNICODE = r'(?:(?:\\' + HEX + r'{1,6})(?:\r\n|[ \t\r\n\f])?)'
# escape {unicode}|\\[^\r\n\f0-9a-f]
ESCAPE = r'(?:' + UNICODE + r'|\\[^\r\n\f0-9a-f])'
# nmstart [_a-z]|{nonascii}|{escape}
NMSTART = r'(?:[_a-z]|' + NON_ASCII + r'|' + ESCAPE + r')'
# nmchar [_a-z0-9-]|{nonascii}|{escape}
NMCHAR = r'(?:[_a-z0-9-]|' + NON_ASCII + r'|' + ESCAPE + r')'
# ident -?{nmstart}{nmchar}*
IDENT = r'-?' + NMSTART + NMCHAR + '*'
# name {nmchar}+
NAME = NMCHAR + r'+'
# hash
HASH = r'#' + NAME
# string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\" ; "string"
STRING1 = r'"(?:[^\"\\]|\\.)*"'
# string2 \'([^\n\r\f\\']|\\{nl}|{escape})*\' ; 'string'
STRING2 = r"'(?:[^\'\\]|\\.)*'"
# string {string1}|{string2}
STRING = '(?:' + STRING1 + r'|' + STRING2 + ')'
# num [0-9]+|[0-9]*"."[0-9]+
NUM = r'(?:[0-9]*\.[0-9]+|[0-9]+)'
# s [ \t\r\n\f]
SPACE = r'[ \t\r\n\f]'
# w {s}*
WHITESPACE = '(?:' + SPACE + r'*)'
# url special chars
URL_SPECIAL_CHARS = r'[!#$%&*-~]'
# url chars ({url_special_chars}|{nonascii}|{escape})*
URL_CHARS = r'(?:%s|%s|%s)*' % (URL_SPECIAL_CHARS, NON_ASCII, ESCAPE)
# url
URL = r'url\(%s(%s|%s)%s\)' % (WHITESPACE, STRING, URL_CHARS, WHITESPACE)
# comments
# see http://www.w3.org/TR/CSS21/grammar.html
COMMENT = r'/\*[^*]*\*+([^/*][^*]*\*+)*/'
# {E}{M} {return EMS;}
# {E}{X} {return EXS;}
# {P}{X} {return LENGTH;}
# {C}{M} {return LENGTH;}
# {M}{M} {return LENGTH;}
# {I}{N} {return LENGTH;}
# {P}{T} {return LENGTH;}
# {P}{C} {return LENGTH;}
# {D}{E}{G} {return ANGLE;}
# {R}{A}{D} {return ANGLE;}
# {G}{R}{A}{D} {return ANGLE;}
# {M}{S} {return TIME;}
# {S} {return TIME;}
# {H}{Z} {return FREQ;}
# {K}{H}{Z} {return FREQ;}
# % {return PERCENTAGE;}
UNIT = r'(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)'
# {num}{UNIT|IDENT} {return NUMBER;}
QUANTITY = '%s(?:%s%s|%s)?' % (NUM, WHITESPACE, UNIT, IDENT)
# "<!--" {return CDO;}
# "-->" {return CDC;}
# "~=" {return INCLUDES;}
# "|=" {return DASHMATCH;}
# {w}"{" {return LBRACE;}
# {w}"+" {return PLUS;}
# {w}">" {return GREATER;}
# {w}"," {return COMMA;}
PUNC = r'<!--|-->|~=|\|=|[\{\+>,:;]'
| Python |
#!/usr/bin/python
#
# Copyright 2008 Google Inc. All Rights Reserved.
"""Converts a LeftToRight Cascading Style Sheet into a RightToLeft one.
This is a utility script for replacing "left" oriented things in a CSS file
like float, padding, margin with "right" oriented values.
It also does the opposite.
The goal is to be able to conditionally serve one large, cat'd, compiled CSS
file appropriate for LeftToRight oriented languages and RightToLeft ones.
This utility will hopefully help your structural layout done in CSS in
terms of its RTL compatibility. It will not help with some of the more
complicated bidirectional text issues.
"""
__author__ = 'elsigh@google.com (Lindsey Simon)'
__version__ = '0.1'
import logging
import re
import sys
import getopt
import os
import csslex
logging.getLogger().setLevel(logging.INFO)
# Global for the command line flags.
SWAP_LTR_RTL_IN_URL_DEFAULT = False
SWAP_LEFT_RIGHT_IN_URL_DEFAULT = False
FLAGS = {'swap_ltr_rtl_in_url': SWAP_LTR_RTL_IN_URL_DEFAULT,
'swap_left_right_in_url': SWAP_LEFT_RIGHT_IN_URL_DEFAULT}
# Generic token delimiter character.
TOKEN_DELIMITER = '~'
# This is a temporary match token we use when swapping strings.
TMP_TOKEN = '%sTMP%s' % (TOKEN_DELIMITER, TOKEN_DELIMITER)
# Token to be used for joining lines.
TOKEN_LINES = '%sJ%s' % (TOKEN_DELIMITER, TOKEN_DELIMITER)
# Global constant text strings for CSS value matches.
LTR = 'ltr'
RTL = 'rtl'
LEFT = 'left'
RIGHT = 'right'
# This is a lookbehind match to ensure that we don't replace instances
# of our string token (left, rtl, etc...) if there's a letter in front of it.
# Specifically, this prevents replacements like 'background: url(bright.png)'.
LOOKBEHIND_NOT_LETTER = r'(?<![a-zA-Z])'
# This is a lookahead match to make sure we don't replace left and right
# in actual classnames, so that we don't break the HTML/CSS dependencies.
# Read literally, it says ignore cases where the word left, for instance, is
# directly followed by valid classname characters and a curly brace.
# ex: .column-left {float: left} will become .column-left {float: right}
LOOKAHEAD_NOT_OPEN_BRACE = (r'(?!(?:%s|%s|%s|#|\:|\.|\,|\+|>)*?{)' %
(csslex.NMCHAR, TOKEN_LINES, csslex.SPACE))
# These two lookaheads are to test whether or not we are within a
# background: url(HERE) situation.
# Ref: http://www.w3.org/TR/CSS21/syndata.html#uri
VALID_AFTER_URI_CHARS = r'[\'\"]?%s' % csslex.WHITESPACE
LOOKAHEAD_NOT_CLOSING_PAREN = r'(?!%s?%s\))' % (csslex.URL_CHARS,
VALID_AFTER_URI_CHARS)
LOOKAHEAD_FOR_CLOSING_PAREN = r'(?=%s?%s\))' % (csslex.URL_CHARS,
VALID_AFTER_URI_CHARS)
# Compile a regex to swap left and right values in 4 part notations.
# We need to match negatives and decimal numeric values.
# ex. 'margin: .25em -2px 3px 0' becomes 'margin: .25em 0 3px -2px'.
POSSIBLY_NEGATIVE_QUANTITY = r'((?:-?%s)|(?:inherit|auto))' % csslex.QUANTITY
POSSIBLY_NEGATIVE_QUANTITY_SPACE = r'%s%s%s' % (POSSIBLY_NEGATIVE_QUANTITY,
csslex.SPACE,
csslex.WHITESPACE)
FOUR_NOTATION_QUANTITY_RE = re.compile(r'%s%s%s%s' %
(POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY_SPACE,
POSSIBLY_NEGATIVE_QUANTITY),
re.I)
COLOR = r'(%s|%s)' % (csslex.NAME, csslex.HASH)
COLOR_SPACE = r'%s%s' % (COLOR, csslex.SPACE)
FOUR_NOTATION_COLOR_RE = re.compile(r'(-color%s:%s)%s%s%s(%s)' %
(csslex.WHITESPACE,
csslex.WHITESPACE,
COLOR_SPACE,
COLOR_SPACE,
COLOR_SPACE,
COLOR),
re.I)
# Compile the cursor resize regexes
CURSOR_EAST_RE = re.compile(LOOKBEHIND_NOT_LETTER + '([ns]?)e-resize')
CURSOR_WEST_RE = re.compile(LOOKBEHIND_NOT_LETTER + '([ns]?)w-resize')
# Matches the condition where we need to replace the horizontal component
# of a background-position value when expressed in horizontal percentage.
# Had to make two regexes because in the case of position-x there is only
# one quantity, and otherwise we don't want to match and change cases with only
# one quantity.
BG_HORIZONTAL_PERCENTAGE_RE = re.compile(r'background(-position)?(%s:%s)'
'([^%%]*?)(%s)%%'
'(%s(?:%s|%s))' % (csslex.WHITESPACE,
csslex.WHITESPACE,
csslex.NUM,
csslex.WHITESPACE,
csslex.QUANTITY,
csslex.IDENT))
BG_HORIZONTAL_PERCENTAGE_X_RE = re.compile(r'background-position-x(%s:%s)'
'(%s)%%' % (csslex.WHITESPACE,
csslex.WHITESPACE,
csslex.NUM))
# Matches the opening of a body selector.
BODY_SELECTOR = r'body%s{%s' % (csslex.WHITESPACE, csslex.WHITESPACE)
# Matches anything up until the closing of a selector.
CHARS_WITHIN_SELECTOR = r'[^\}]*?'
# Matches the direction property in a selector.
DIRECTION_RE = r'direction%s:%s' % (csslex.WHITESPACE, csslex.WHITESPACE)
# These allow us to swap "ltr" with "rtl" and vice versa ONLY within the
# body selector and on the same line.
BODY_DIRECTION_LTR_RE = re.compile(r'(%s)(%s)(%s)(ltr)' %
(BODY_SELECTOR, CHARS_WITHIN_SELECTOR,
DIRECTION_RE),
re.I)
BODY_DIRECTION_RTL_RE = re.compile(r'(%s)(%s)(%s)(rtl)' %
(BODY_SELECTOR, CHARS_WITHIN_SELECTOR,
DIRECTION_RE),
re.I)
# Allows us to swap "direction:ltr" with "direction:rtl" and
# vice versa anywhere in a line.
DIRECTION_LTR_RE = re.compile(r'%s(ltr)' % DIRECTION_RE)
DIRECTION_RTL_RE = re.compile(r'%s(rtl)' % DIRECTION_RE)
# We want to be able to switch left with right and vice versa anywhere
# we encounter left/right strings, EXCEPT inside the background:url(). The next
# two regexes are for that purpose. We have alternate IN_URL versions of the
# regexes compiled in case the user passes the flag that they do
# actually want to have left and right swapped inside of background:urls.
LEFT_RE = re.compile('%s(%s)%s%s' % (LOOKBEHIND_NOT_LETTER,
LEFT,
LOOKAHEAD_NOT_CLOSING_PAREN,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
RIGHT_RE = re.compile('%s(%s)%s%s' % (LOOKBEHIND_NOT_LETTER,
RIGHT,
LOOKAHEAD_NOT_CLOSING_PAREN,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
LEFT_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
LEFT,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
RIGHT_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
RIGHT,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
LTR_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
LTR,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
RTL_IN_URL_RE = re.compile('%s(%s)%s' % (LOOKBEHIND_NOT_LETTER,
RTL,
LOOKAHEAD_FOR_CLOSING_PAREN),
re.I)
COMMENT_RE = re.compile('(%s)' % csslex.COMMENT, re.I)
NOFLIP_TOKEN = r'\@noflip'
# The NOFLIP_TOKEN inside of a comment. For now, this requires that comments
# be in the input, which means users of a css compiler would have to run
# this script first if they want this functionality.
NOFLIP_ANNOTATION = r'/\*%s%s%s\*/' % (csslex.WHITESPACE,
NOFLIP_TOKEN,
csslex. WHITESPACE)
# After a NOFLIP_ANNOTATION, and within a class selector, we want to be able
# to set aside a single rule not to be flipped. We can do this by matching
# our NOFLIP annotation and then using a lookahead to make sure there is not
# an opening brace before the match.
NOFLIP_SINGLE_RE = re.compile(r'(%s%s[^;}]+;?)' % (NOFLIP_ANNOTATION,
LOOKAHEAD_NOT_OPEN_BRACE),
re.I)
# After a NOFLIP_ANNOTATION, we want to grab anything up until the next } which
# means the entire following class block. This will prevent all of its
# declarations from being flipped.
NOFLIP_CLASS_RE = re.compile(r'(%s%s})' % (NOFLIP_ANNOTATION,
CHARS_WITHIN_SELECTOR),
re.I)
class Tokenizer:
"""Replaces any CSS comments with string tokens and vice versa."""
def __init__(self, token_re, token_string):
"""Constructor for the Tokenizer.
Args:
token_re: A regex for the string to be replace by a token.
token_string: The string to put between token delimiters when tokenizing.
"""
logging.debug('Tokenizer::init token_string=%s' % token_string)
self.token_re = token_re
self.token_string = token_string
self.originals = []
def Tokenize(self, line):
"""Replaces any string matching token_re in line with string tokens.
By passing a function as an argument to the re.sub line below, we bypass
the usual rule where re.sub will only replace the left-most occurrence of
a match by calling the passed in function for each occurrence.
Args:
line: A line to replace token_re matches in.
Returns:
line: A line with token_re matches tokenized.
"""
line = self.token_re.sub(self.TokenizeMatches, line)
logging.debug('Tokenizer::Tokenize returns: %s' % line)
return line
def DeTokenize(self, line):
"""Replaces tokens with the original string.
Args:
line: A line with tokens.
Returns:
line with any tokens replaced by the original string.
"""
# Put all of the comments back in by their comment token.
for i, original in enumerate(self.originals):
token = '%s%s_%s%s' % (TOKEN_DELIMITER, self.token_string, i + 1,
TOKEN_DELIMITER)
line = line.replace(token, original)
logging.debug('Tokenizer::DeTokenize i:%s w/%s' % (i, token))
logging.debug('Tokenizer::DeTokenize returns: %s' % line)
return line
def TokenizeMatches(self, m):
"""Replaces matches with tokens and stores the originals.
Args:
m: A match object.
Returns:
A string token which replaces the CSS comment.
"""
logging.debug('Tokenizer::TokenizeMatches %s' % m.group(1))
self.originals.append(m.group(1))
return '%s%s_%s%s' % (TOKEN_DELIMITER,
self.token_string,
len(self.originals),
TOKEN_DELIMITER)
def FixBodyDirectionLtrAndRtl(line):
"""Replaces ltr with rtl and vice versa ONLY in the body direction.
Args:
line: A string to replace instances of ltr with rtl.
Returns:
line with direction: ltr and direction: rtl swapped only in body selector.
line = FixBodyDirectionLtrAndRtl('body { direction:ltr }')
line will now be 'body { direction:rtl }'.
"""
line = BODY_DIRECTION_LTR_RE.sub('\\1\\2\\3%s' % TMP_TOKEN, line)
line = BODY_DIRECTION_RTL_RE.sub('\\1\\2\\3%s' % LTR, line)
line = line.replace(TMP_TOKEN, RTL)
logging.debug('FixBodyDirectionLtrAndRtl returns: %s' % line)
return line
def FixLeftAndRight(line):
"""Replaces left with right and vice versa in line.
Args:
line: A string in which to perform the replacement.
Returns:
line with left and right swapped. For example:
line = FixLeftAndRight('padding-left: 2px; margin-right: 1px;')
line will now be 'padding-right: 2px; margin-left: 1px;'.
"""
line = LEFT_RE.sub(TMP_TOKEN, line)
line = RIGHT_RE.sub(LEFT, line)
line = line.replace(TMP_TOKEN, RIGHT)
logging.debug('FixLeftAndRight returns: %s' % line)
return line
def FixLeftAndRightInUrl(line):
"""Replaces left with right and vice versa ONLY within background urls.
Args:
line: A string in which to replace left with right and vice versa.
Returns:
line with left and right swapped in the url string. For example:
line = FixLeftAndRightInUrl('background:url(right.png)')
line will now be 'background:url(left.png)'.
"""
line = LEFT_IN_URL_RE.sub(TMP_TOKEN, line)
line = RIGHT_IN_URL_RE.sub(LEFT, line)
line = line.replace(TMP_TOKEN, RIGHT)
logging.debug('FixLeftAndRightInUrl returns: %s' % line)
return line
def FixLtrAndRtlInUrl(line):
"""Replaces ltr with rtl and vice versa ONLY within background urls.
Args:
line: A string in which to replace ltr with rtl and vice versa.
Returns:
line with left and right swapped. For example:
line = FixLtrAndRtlInUrl('background:url(rtl.png)')
line will now be 'background:url(ltr.png)'.
"""
line = LTR_IN_URL_RE.sub(TMP_TOKEN, line)
line = RTL_IN_URL_RE.sub(LTR, line)
line = line.replace(TMP_TOKEN, RTL)
logging.debug('FixLtrAndRtlInUrl returns: %s' % line)
return line
def FixCursorProperties(line):
"""Fixes directional CSS cursor properties.
Args:
line: A string to fix CSS cursor properties in.
Returns:
line reformatted with the cursor properties substituted. For example:
line = FixCursorProperties('cursor: ne-resize')
line will now be 'cursor: nw-resize'.
"""
line = CURSOR_EAST_RE.sub('\\1' + TMP_TOKEN, line)
line = CURSOR_WEST_RE.sub('\\1e-resize', line)
line = line.replace(TMP_TOKEN, 'w-resize')
logging.debug('FixCursorProperties returns: %s' % line)
return line
def FixFourPartNotation(line):
"""Fixes the second and fourth positions in 4 part CSS notation.
Args:
line: A string to fix 4 part CSS notation in.
Returns:
line reformatted with the 4 part notations swapped. For example:
line = FixFourPartNotation('padding: 1px 2px 3px 4px')
line will now be 'padding: 1px 4px 3px 2px'.
"""
line = FOUR_NOTATION_QUANTITY_RE.sub('\\1 \\4 \\3 \\2', line)
line = FOUR_NOTATION_COLOR_RE.sub('\\1\\2 \\5 \\4 \\3', line)
logging.debug('FixFourPartNotation returns: %s' % line)
return line
def FixBackgroundPosition(line):
"""Fixes horizontal background percentage values in line.
Args:
line: A string to fix horizontal background position values in.
Returns:
line reformatted with the 4 part notations swapped.
"""
line = BG_HORIZONTAL_PERCENTAGE_RE.sub(CalculateNewBackgroundPosition, line)
line = BG_HORIZONTAL_PERCENTAGE_X_RE.sub(CalculateNewBackgroundPositionX,
line)
logging.debug('FixBackgroundPosition returns: %s' % line)
return line
def CalculateNewBackgroundPosition(m):
"""Fixes horizontal background-position percentages.
This function should be used as an argument to re.sub since it needs to
perform replacement specific calculations.
Args:
m: A match object.
Returns:
A string with the horizontal background position percentage fixed.
BG_HORIZONTAL_PERCENTAGE_RE.sub(FixBackgroundPosition,
'background-position: 75% 50%')
will return 'background-position: 25% 50%'.
"""
# The flipped value is the offset from 100%
new_x = str(100-int(m.group(4)))
# Since m.group(1) may very well be None type and we need a string..
if m.group(1):
position_string = m.group(1)
else:
position_string = ''
return 'background%s%s%s%s%%%s' % (position_string, m.group(2), m.group(3),
new_x, m.group(5))
def CalculateNewBackgroundPositionX(m):
"""Fixes percent based background-position-x.
This function should be used as an argument to re.sub since it needs to
perform replacement specific calculations.
Args:
m: A match object.
Returns:
A string with the background-position-x percentage fixed.
BG_HORIZONTAL_PERCENTAGE_X_RE.sub(CalculateNewBackgroundPosition,
'background-position-x: 75%')
will return 'background-position-x: 25%'.
"""
# The flipped value is the offset from 100%
new_x = str(100-int(m.group(2)))
return 'background-position-x%s%s%%' % (m.group(1), new_x)
def ChangeLeftToRightToLeft(lines,
swap_ltr_rtl_in_url=None,
swap_left_right_in_url=None):
"""Turns lines into a stream and runs the fixing functions against it.
Args:
lines: An list of CSS lines.
swap_ltr_rtl_in_url: Overrides this flag if param is set.
swap_left_right_in_url: Overrides this flag if param is set.
Returns:
The same lines, but with left and right fixes.
"""
global FLAGS
# Possibly override flags with params.
logging.debug('ChangeLeftToRightToLeft swap_ltr_rtl_in_url=%s, '
'swap_left_right_in_url=%s' % (swap_ltr_rtl_in_url,
swap_left_right_in_url))
if swap_ltr_rtl_in_url is None:
swap_ltr_rtl_in_url = FLAGS['swap_ltr_rtl_in_url']
if swap_left_right_in_url is None:
swap_left_right_in_url = FLAGS['swap_left_right_in_url']
# Turns the array of lines into a single line stream.
logging.debug('LINES COUNT: %s' % len(lines))
line = TOKEN_LINES.join(lines)
# Tokenize any single line rules with the /* noflip */ annotation.
noflip_single_tokenizer = Tokenizer(NOFLIP_SINGLE_RE, 'NOFLIP_SINGLE')
line = noflip_single_tokenizer.Tokenize(line)
# Tokenize any class rules with the /* noflip */ annotation.
noflip_class_tokenizer = Tokenizer(NOFLIP_CLASS_RE, 'NOFLIP_CLASS')
line = noflip_class_tokenizer.Tokenize(line)
# Tokenize the comments so we can preserve them through the changes.
comment_tokenizer = Tokenizer(COMMENT_RE, 'C')
line = comment_tokenizer.Tokenize(line)
# Here starteth the various left/right orientation fixes.
line = FixBodyDirectionLtrAndRtl(line)
if swap_left_right_in_url:
line = FixLeftAndRightInUrl(line)
if swap_ltr_rtl_in_url:
line = FixLtrAndRtlInUrl(line)
line = FixLeftAndRight(line)
line = FixCursorProperties(line)
line = FixFourPartNotation(line)
line = FixBackgroundPosition(line)
# DeTokenize the single line noflips.
line = noflip_single_tokenizer.DeTokenize(line)
# DeTokenize the class-level noflips.
line = noflip_class_tokenizer.DeTokenize(line)
# DeTokenize the comments.
line = comment_tokenizer.DeTokenize(line)
# Rejoin the lines back together.
lines = line.split(TOKEN_LINES)
return lines
def usage():
"""Prints out usage information."""
print 'Usage:'
print ' ./cssjanus.py < file.css > file-rtl.css'
print 'Flags:'
print ' --swap_left_right_in_url: Fixes "left"/"right" string within urls.'
print ' Ex: ./cssjanus.py --swap_left_right_in_url < file.css > file_rtl.css'
print ' --swap_ltr_rtl_in_url: Fixes "ltr"/"rtl" string within urls.'
print ' Ex: ./cssjanus --swap_ltr_rtl_in_url < file.css > file_rtl.css'
def setflags(opts):
"""Parse the passed in command line arguments and set the FLAGS global.
Args:
opts: getopt iterable intercepted from argv.
"""
global FLAGS
# Parse the arguments.
for opt, arg in opts:
logging.debug('opt: %s, arg: %s' % (opt, arg))
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-d", "--debug"):
logging.getLogger().setLevel(logging.DEBUG)
elif opt == '--swap_ltr_rtl_in_url':
FLAGS['swap_ltr_rtl_in_url'] = True
elif opt == '--swap_left_right_in_url':
FLAGS['swap_left_right_in_url'] = True
def main(argv):
"""Sends stdin lines to ChangeLeftToRightToLeft and writes to stdout."""
# Define the flags.
try:
opts, args = getopt.getopt(argv, 'hd', ['help', 'debug',
'swap_left_right_in_url',
'swap_ltr_rtl_in_url'])
except getopt.GetoptError:
usage()
sys.exit(2)
# Parse and set the flags.
setflags(opts)
# Call the main routine with all our functionality.
fixed_lines = ChangeLeftToRightToLeft(sys.stdin.readlines())
sys.stdout.write(''.join(fixed_lines))
if __name__ == '__main__':
main(sys.argv[1:])
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@gmail.com
#Ver:0.2
import urllib
import urllib2
import sys,re
import binascii
import hashlib
import socket
import os
import time
import exceptions
import logging
from hashlib import md5
from hashlib import sha1
from uuid import uuid1
from threading import RLock
from threading import Thread
from select import select
from Queue import Queue
from copy import copy
FetionOnline = "400"
FetionBusy = "600"
FetionAway = "100"
FetionHidden = "0"
FetionOffline = "365"
FetionVer = "2008"
#"SIPP" USED IN HTTP CONNECTION
FetionSIPP= "SIPP"
FetionNavURL = "nav.fetion.com.cn"
FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx"
FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="3.5.2540" platform="W6.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /><services version="0" /></config>"""
FetionLoginXML = """<args><device type="PC" version="1" client-version="3.5.2540" /><caps value="simple-im;im-session;temp-group;personal-group;im-relay;xeno-im;direct-sms;sms2fetion" /><events value="contact;permission;system-message;personal-group;compact" /><user-info attributes="all" /><presence><basic value="%s" desc="" /></presence></args>"""
proxy_info = False
d_print = ''
#uncomment below line if you need proxy
"""
proxy_info = {'user' : '',
'pass' : '',
'host' : '218.249.83.87',
'port' : 8080
}
"""
class PyFetionException(Exception):
"""Base class for all exceptions
"""
def __init__(self, code, msg):
self.args = (code,msg)
class PyFetionSocketError(PyFetionException):
"""any socket error"""
def __init__(self,e,msg=''):
if msg:
self.args = (e,msg)
self.code = e
self.msg = msg
elif type(e) is int:
self.args = (e,socket.errorTab[e])
self.code = e
self.msg = socket.errorTab[e]
else:
args = e.args
d_print(('args',),locals())
try:
self.args = (e.errno,msg)
msg = socket.errorTab[e.errno]
self.code = e.errno
except:
msg = e
self.msg = msg
class PyFetionAuthError(PyFetionException):
"""Authentication error.
Your password error.
"""
class PyFetionSupportError(PyFetionException):
"""Support error.
Your phone number don't support fetion.
"""
class PyFetionRegisterError(PyFetionException):
"""RegisterError.
"""
class SIPC():
global FetionVer
global FetionSIPP
global FetionLoginXML
_header = ''
#body = ''
_content = ''
code = ''
ver = "SIP-C/2.0"
Q = 1
I = 1
queue = Queue()
def __init__(self,args=[]):
self.__seq = 1
if args:
[self.sid, self._domain,self.login_type, self._http_tunnel,\
self._ssic, self._sipc_proxy, self.presence, self._lock] = args
if self.login_type == "HTTP":
guid = str(uuid1())
self.__exheaders = {
'Cookie':'ssic=%s' % self._ssic,
'Content-Type':'application/oct-stream',
'Pragma':'xz4BBcV%s' % guid,
}
else:
self.__tcp_init()
def init_ack(self,type):
self._content = "%s 200 OK\r\n" % self.ver
self._header = [('F',self.sid),
('I',self.I),
('Q','%s %s' % (self.Q,type)),
]
def init(self,type):
self._content = '%s %s %s\r\n' % (type,self._domain,self.ver)
self._header = [('F',self.sid),
('I',self.I),
('Q','%s %s' % (self.Q,type)),
]
def recv(self,timeout=False):
if self.login_type == "HTTP":
time.sleep(10)
return self.get_offline_msg()
pass
else:
if timeout:
infd,outfd,errfd = select([self.__sock,],[],[],timeout)
else:
infd,outfd,errfd = select([self.__sock,],[],[])
if len(infd) != 0:
ret = self.__tcp_recv()
num = len(ret)
d_print(('num',),locals())
if num == 0:
return ret
if num == 1:
return ret[0]
for r in ret:
self.queue.put(r)
d_print(('r',),locals())
if not self.queue.empty():
return self.queue.get()
else:
return "TimeOut"
def get_code(self,response):
cmd = ''
try:
self.code =int(re.search("%s (\d{3})" % self.ver,response).group(1))
self.msg =re.search("%s \d{3} (.*)\r" % self.ver,response).group(1)
except AttributeError,e:
try:
cmd = re.search("(.+?) %s" % self.ver,response).group(1)
d_print(('cmd',),locals())
except AttributeError,e:
pass
return cmd
return self.code
def get(self,cmd,arg,*extra):
body = ''
if extra:
body = extra[0]
if cmd == "REG":
body = FetionLoginXML % self.presence
self.init('R')
if arg == 1:
pass
if arg == 2:
nonce = re.search('nonce="(.*)"',extra[0]).group(1)
cnonce = self.__get_cnonce()
if FetionVer == "2008":
response=self.__get_response_sha1(nonce,cnonce)
elif FetionVer == "2006":
response=self.__get_response_md5(nonce,cnonce)
salt = self.__get_salt()
d_print(('nonce','cnonce','response','salt'),locals())
#If this step failed try to uncomment this lines
#del self._header[2]
#self._header.insert(2,('Q','2 R'))
if FetionVer == "2008":
self._header.insert(3,('A','Digest algorithm="SHA1-sess",response="%s",cnonce="%s",salt="%s",ssic="%s"' % (response,cnonce,salt,self._ssic)))
elif FetionVer == "2006":
self._header.insert(3,('A','Digest response="%s",cnonce="%s"' % (response,cnonce)))
#If register successful 200 code get
if arg == 3:
return self.code
if cmd == "CatMsg":
self.init('M')
self._header.append(('T',arg))
self._header.append(('C','text/plain'))
self._header.append(('K','SaveHistory'))
self._header.append(('N',cmd))
if cmd == "SendMsg":
self.init('M')
self._header.append(('C','text/plain'))
self._header.append(('K','SaveHistory'))
if cmd == "SendSMS":
self.init('M')
self._header.append(('T',arg))
self._header.append(('N',cmd))
if cmd == "SendCatSMS":
self.init('M')
self._header.append(('T',arg))
self._header.append(('N',cmd))
if cmd == "NUDGE":
self.init('IN')
self._header.append(('T',arg))
body = "<is-composing><state>nudge</state></is-composing>"
if cmd == "ALIVE":
self.init('R')
if cmd == "DEAD":
self.init('R')
self._header.append(('X','0'))
if cmd == "ACK":
body = ''
if arg == 'M':
self.Q = extra[1]
self.I = extra[2]
self.init_ack(arg)
del self._header[0]
self._header.insert(0,('F',extra[0]))
if cmd == "IN":
body ="<is-composing><state>fetion-show:\xe5\x9b\xa70x000101010000010001000000000000010000000</state></is-composing>"
self.init('IN')
self._header.insert(3,('T',arg))
if cmd == "BYE":
body = ''
self.init('B')
if cmd == "SetPresence":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><presence><basic value="%s" /></presence></args>' % arg
if cmd == "PGPresence":
self.init('SUB')
self._header.append(('N',cmd))
self._header.append(('X','0'))
body = '<args><subscription><groups /></subscription></args>'
if cmd == "PGSetPresence":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><groups /></args>'
if cmd == "compactlist":
self.init('SUB')
self._header.append(('N',cmd))
body = '<args><subscription><contacts><contact uri="%s" type="3" />'% arg
for i in extra[0]:
body += '<contact uri="%s" type="3" />' % i
body += '</contacts></subscription></args>'
if cmd == "StartChat":
if arg == '':
self.init('S')
self._header.append(('N',cmd))
else:
self.init('R')
self._header.append(('A','TICKS auth="%s"' % arg))
self._header.append(('K','text/html-fragment'))
self._header.append(('K','multiparty'))
self._header.append(('K','nudge'))
self._header.append(('K','share-background'))
self._header.append(('K','fetion-show'))
if cmd == "InviteBuddy":
self.init('S')
self._header.append(('N',cmd))
body = '<args><contacts><contact uri="%s" /></contacts></args>'%arg
if cmd == "PGGetGroupList":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><group-list version="1" attributes="name;identity" /></args>'
if cmd == "SSSetScheduleSms":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><schedule-sms send-time="%s"><message>%s</message><receivers><receiver uri="%s" /></receivers></schedule-sms></args>' % (extra[0],arg,extra[1])
if cmd == "GetOfflineMessages":
self.init('S')
self._header.insert(3,('N',cmd))
if cmd == "INFO":
self.init('S')
self._header.insert(3,('N',arg))
if arg == "GetPersonalInfo":
body = '<args><personal attributes="all" /><services version="" attributes="all" /><config attributes="all" /><quota attributes="all" /></args>'
elif arg == "GetContactList":
body = '<args><contacts><buddy-lists /><buddies attributes="all" /><mobile-buddies attributes="all" /><chat-friends /><blacklist /><allow-list /></contacts></args>'
elif arg == "GetContactsInfo":
body = '<args><contacts attributes="all">'
for i in extra[0]:
body += '<contact uri="%s" />' % i
body += '</contacts></args>'
elif arg == "AddBuddy":
tag = "sip"
if len(extra[0]) == 11:
tag = "tel"
body = '<args><contacts><buddies><buddy uri="%s:%s" buddy-lists="" desc="%s" addbuddy-phrase-id="0" /></buddies></contacts></args>' % (tag,extra[0],extra[1])
elif arg == "AddMobileBuddy":
body = '<args><contacts><mobile-buddies><mobile-buddy uri="tel:%s" buddy-lists="1" desc="%s" invite="0" /></mobile-buddies></contacts></args>' % (extra[0],extra[1])
elif arg == "DeleteBuddy":
body = '<args><contacts><buddies><buddy uri="%s" /></buddies></contacts></args>' % extra[0]
#general SIPC info
if len(body) != 0:
self._header.append(('L',len(body)))
for k in self._header:
self._content = self._content + k[0] + ": " + str(k[1]) + "\r\n"
self._content+="\r\n"
self._content+= body
if self.login_type == "HTTP":
#IN TCP CONNECTION "SIPP" SHOULD NOT BEEN SEND
self._content+= FetionSIPP
return self._content
def ack(self):
"""ack message from server"""
content = self._content
d_print(('content',),locals())
self.__tcp_send(content)
def send(self):
content = self._content
response = ''
if self._lock:
d_print("acquire lock ")
self._lock.acquire()
d_print("acquire lock ok ")
d_print(('content',),locals())
if self.login_type == "HTTP":
#First time t SHOULD SET AS 'i'
#Otherwise 405 code get
if self.__seq == 1:
t = 'i'
else:
t = 's'
url = self._http_tunnel+"?t=%s&i=%s" % (t,self.__seq)
ret = http_send(url,content,self.__exheaders)
if not ret:
raise PyFetionSocketError(405,'http stoped')
response = ret.read()
self.__seq+=1
response = self.__sendSIPP()
i = 0
while response == FetionSIPP and i < 5:
response = self.__sendSIPP()
i += 1
ret = self.__split(response)
num = len(ret)
d_print(('num',),locals())
for rs in ret:
code = self.get_code(rs)
d_print(('rs',),locals())
try:
int(code)
d_print(('code',),locals())
response = rs
except exceptions.ValueError:
self.queue.put(rs)
continue
else:
self.__tcp_send(content)
while response is '':
try:
ret = self.__tcp_recv()
except socket.error,e:
raise PyFetionSocketError(e)
num = len(ret)
d_print(('num',),locals())
for rs in ret:
code = self.get_code(rs)
d_print(('rs',),locals())
try:
int(code)
d_print(('code',),locals())
response = rs
except exceptions.ValueError:
self.queue.put(rs)
continue
if self._lock:
self._lock.release()
d_print("release lock")
return response
def __sendSIPP(self):
body = FetionSIPP
url = self._http_tunnel+"?t=s&i=%s" % self.__seq
ret = http_send(url,body,self.__exheaders)
if not ret:
raise PyFetionSocketError(405,'Http error')
response = ret.read()
d_print(('response',),locals())
self.__seq+=1
return response
def __tcp_init(self):
try:
self.__sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
s = None
raise PyFetionSocketError(e)
(host,port) = tuple(self._sipc_proxy.split(":"))
port = int(port)
try:
self.__sock.connect((host,port))
except socket.error,e:
self.__sock.close()
raise PyFetionSocketError(e)
def close(self):
self.__sock.close()
def __tcp_send(self,msg):
try:
self.__sock.send(msg)
except socket.error,e:
self.__sock.close()
raise PyFetionSocketError(e)
def __tcp_recv(self):
"""read bs bytes first,if there's still more data, read left data.
get length from header :
L: 1022
"""
total_data = []
bs = 1024
try:
data = self.__sock.recv(bs)
total_data.append(data)
while True and data:
if not re.search("L: (\d+)",data) and not data[-4:] == '\r\n\r\n':
data = self.__sock.recv(bs)
total_data.append(data)
elif not re.search("L: (\d+)",data) and data[-4:] == '\r\n\r\n':
return total_data
else:
break
while re.search("L: (\d+)",data):
n = len(data)
L = int(re.findall("L: (\d+)",data)[-1])
p = data.rfind('\r\n\r\n')
abc = data
data = ''
p1 = data.rfind(str(L))
if p < p1:
d_print("rn before L")
left = L + n - (p1 + len(str(L))) + 4
else:
left = L - (n - p -4)
if left == L:
d_print("It happened!")
break
d_print(('n','L','p','left',),locals())
#if more bytes then last L
#come across another command: BN etc.
#read until another L come
if left < 0:
d_print(('abc',),locals())
d = ''
left = 0
while True:
d = self.__sock.recv(bs)
data += d
if re.search("L: (\d+)",d):
break
d_print("read left bytes")
d_print(('data',),locals())
total_data.append(data)
#read left bytes in last L
while left:
data = self.__sock.recv(left)
n = len(data)
left = left - n
if not data:
break
total_data.append(data)
except socket.error,e:
#self.__sock.close()
raise PyFetionSocketError(e)
return self.__split(''.join(total_data))
#return ''.join(total_data)
def __split(self,data):
c = []
d = []
#remove string "SIPP"
if self.login_type == "HTTP":
data = data[:-4]
L = re.findall("L: (\d+)",data)
L = [int(i) for i in L]
d_print(('data',),locals())
b = data.split('\r\n\r\n')
for i in range(len(b)):
if b[i].startswith(self.ver) and "L:" not in b[i]:
d.append(b[i]+'\r\n\r\n')
del b[i]
break
c.append(b[0])
d_print(('L','b',),locals())
for i in range(0,len(L)):
c.append(b[i+1][:L[i]])
c.append(b[i+1][L[i]:])
d_print(('c',),locals())
#remove last empty string
if c[-1] == '':
c.pop()
c.reverse()
while c:
s = c.pop()
s += '\r\n\r\n'
if c:
s += c.pop()
d.append(s)
d_print(('d',),locals())
return d
def __get_salt(self):
return self.__hash_passwd()[:8]
def __get_cnonce(self):
return md5(str(uuid1())).hexdigest().upper()
def __get_response_md5(self,nonce,cnonce):
#nonce = "3D8348924962579418512B8B3966294E"
#cnonce= "9E169DCA9CBD85F1D1A89A893E00917E"
key = md5("%s:%s:%s" % (self.sid,self._domain,self.passwd)).digest()
h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper()
h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper()
response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper()
#d_print(('nonce','cnonce','key','h1','h2','response'),locals())
return response
def __get_response_sha1(self,nonce,cnonce):
#nonce = "3D8348924962579418512B8B3966294E"
#cnonce= "9E169DCA9CBD85F1D1A89A893E00917E"
hash_passwd = self.__hash_passwd()
hash_passwd_str = binascii.unhexlify(hash_passwd[8:])
key = sha1("%s:%s:%s" % (self.sid,self._domain,hash_passwd_str)).digest()
h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper()
h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper()
response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper()
return response
def __hash_passwd(self):
#salt = '%s%s%s%s' % (chr(0x77), chr(0x7A), chr(0x6D), chr(0x03))
salt = 'wzm\x03'
src = salt+sha1(self.passwd).digest()
return "777A6D03"+sha1(src).hexdigest().upper()
def http_send(url,body='',exheaders='',login=False):
global proxy_info
conn = ''
headers = {
'User-Agent':'IIC2.0/PC 3.2.0540',
}
headers.update(exheaders)
if proxy_info:
proxy_support = urllib2.ProxyHandler(\
{"http":"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support)
else:
opener = urllib2.build_opener()
urllib2.install_opener(opener)
request = urllib2.Request(url,headers=headers,data=body)
#add retry for GAE.
#PyFetion will get 405 code sometimes, we should re-send the request.
retry = 5
while retry:
try:
conn = urllib2.urlopen(request)
except urllib2.URLError, e:
if hasattr(e,'code'):
code = e.code
msg = e.read()
else:
code = e.reason.errno
msg = e.reason.strerror
d_print(('code','msg'),locals())
if code == 401 or code == 400:
if login:
raise PyFetionAuthError(code,msg)
if code == 404 or code == 500:
raise PyFetionSupportError(code,msg)
if code == 405:
retry = retry - 1
continue
raise PyFetionSocketError(code,msg)
break
return conn
class on_cmd_I(Thread,SIPC):
#if there is invitation SIP method [I]
def __init__(self,fetion,response,args):
self.fetion = fetion
self.response = response
self.args = args
self.begin = time.time()
self.Q = 4
self.I = 4
self.from_uri = ''
Thread.__init__(self)
def run(self):
running = True
try:
self.from_uri = re.findall('F: (.*)',self.response)[0]
credential = re.findall('credential="(.+?)"',self.response)[0]
sipc_proxy = re.findall('address="(.+?);',self.response)[0]
except:
d_print("find tag error")
return
self.from_uri = self.from_uri.rstrip()
self.fetion._ack('I',self.from_uri)
self.args[5] = sipc_proxy
#no lock
self.args[7] = None
#SIPC(self.args)
SIPC.__init__(self,self.args)
self.get("StartChat",credential)
response = self.send()
self.deal_msg(response)
while running:
if not self.queue.empty():
response = self.queue.get()
else:
response = self.recv()
if len(response) == 0:
d_print("User Left converstion")
self.fetion.session.pop(self.from_uri)
return
self.deal_msg(response)
#self._bye()
def deal_msg(self,response):
try:
Q = re.findall('Q: (-?\d+) M',response)
I = re.findall('I: (-?\d+)',response)
except:
d_print("NO Q")
return False
for i in range(len(Q)):
self.Q = Q[i]
self.fetion.queue.put(response)
self._ack('M')
self._ack('IN')
return True
def _ack(self,cmd):
"""ack message from uri"""
self.get("ACK",cmd,self.from_uri,self.Q,self.I)
self.response = self.ack()
self.deal_msg(self.response)
def _send_msg(self,msg):
msg = msg.replace('<','<')
self.get("SendMsg",'',msg)
self.send()
def _bye(self):
"""say bye to this session"""
self.get("BYE",'')
self.send()
class PyFetion(SIPC):
__log = ''
__sipc_url = ''
_ssic = ''
_lock = RLock()
_sipc_proxy = ''
_domain = ''
_http_tunnel = ''
mobile_no = ''
passwd = ''
queue = Queue()
sid = ''
login_type = ''
receving = False
presence = ''
debug = False
contactlist = {}
grouplist = {}
session = {}
def __init__(self,mobile_no,passwd,login_type="TCP",debug=False):
self.mobile_no = mobile_no
self.passwd = passwd
self.login_type = login_type
if debug == True:
logging.basicConfig(level=logging.DEBUG,format='%(message)s')
self.__log = logging
elif debug == "FILE":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(thread)d %(message)s',
filename='./PyFetion.log',
filemode='w')
self.__log = logging
global d_print
#replace global function with self method
d_print = self.__print
self.__sipc_url = "https://uid.fetion.com.cn/ssiportal/SSIAppSignIn.aspx"
self._sipc_proxy = "221.176.31.45:8080"
self._http_tunnel= "http://221.176.31.45/ht/sd.aspx"
#uncomment this line for getting configuration from server everytime
#It's very slow sometimes, so default use fixed configuration
#self.__set_system_config()
def login(self,presence=FetionOnline):
if not self.__get_uri():
return False
self.presence = presence
try:
self.__register(self._ssic,self._domain)
except PyFetionRegisterError,e:
d_print("Register Failed!")
return False
#self.get_personal_info()
if not self.get_contactlist():
d_print("get contactlist error")
return False
self.get("compactlist",self.__uri,self.contactlist.keys())
response = self.send()
code = self.get_code(response)
if code != 200:
return False
#self.get("PGGetGroupList",self.__uri)
#response = self.send()
self.get_offline_msg()
self.receving = True
return True
def logout(self):
self.get("DEAD",'')
self.send()
self.receving = False
def start_chat(self,who):
self.get("StartChat",'')
response = self.send()
try:
credential = re.findall('credential="(.+?)"',response)[0]
sipc_proxy = re.findall('address="(.+?);',response)[0]
except:
d_print("find tag error")
return False
args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,sipc_proxy,self.presence,None]
_SIPC = SIPC(args)
_SIPC.get("StartChat",credential)
response = _SIPC.send()
_SIPC.get("InviteBuddy",who)
response = _SIPC.send()
code = _SIPC.get_code(response)
if code != 200:
return False
response = _SIPC.recv()
try:
type = re.findall('<event type="(.+?)"',response)[0]
except :
return False
if type == "UserEntered":
return FetionHidden
elif type == "UserFailed":
return FetionOnline
def set_presence(self,presence):
"""set status of fetion"""
if self.presence == presence:
return True
self.get("SetPresence",presence)
response = self.send()
code = self.get_code(response)
if code == 200:
self.presence = presence
d_print("set presence ok.")
return True
return False
#self.get("PGSetPresence",presence)
#response = self.send()
def get_offline_msg(self):
"""get offline message from server"""
self.get("GetOfflineMessages",'')
response = self.send()
return response
def add(self,who):
"""add friend who should be mobile number or fetion number"""
my_info = self.get_info()
try:
#nick_name = re.findall('nickname="(.*?)" ',my_info)[0]
nick_name = my_info[0]
except IndexError:
nick_name = " "
#code = self._add(who,nick_name,"AddMobileBuddy")
code = self._add(who,nick_name)
if code == 522:
code = self._add(who,nick_name,"AddMobileBuddy")
if code == 404 or code == 400 :
d_print("Not Found")
return False
if code == 521:
d_print("Aleady added.")
return True
if code == 200:
return True
return False
def delete(self,who):
if who.isdigit() and len(who) == 11:
who = "tel:" + who
else:
who = self.get_uri(who)
if not who:
return False
self.get("INFO","DeleteBuddy",who)
response = self.send()
code = self.get_code(response)
if code == 404 or code == 400 :
d_print("Not Found")
return False
if code == 200:
return True
return False
def _add(self,who,nick_name,type="AddBuddy"):
self.get("INFO",type,who,nick_name)
response = self.send()
code = self.get_code(response)
return code
def get_personal_info(self):
"""get detail information of me"""
self.get("INFO","GetPersonalInfo")
response = self.send()
nickname = re.findall('nickname="(.+?)"',response)[0]
impresa = re.findall('impresa="(.+?)"',response)[0]
#mobile = re.findall('mobile-no="(^1[35]\d{9})"',response)[0]
mobile = re.findall('mobile-no="(.+?)"',response)[0]
name = re.findall(' name="(.+?)"',response)[0]
gender = re.findall('gender="([01])"',response)[0]
fetion_number = re.findall('user-id="(\d{9})"',response)[0]
#email = re.findall('personal-email="(.+?)"',response)[0]
response = []
response.append(nickname)
response.append(impresa)
response.append(mobile)
response.append(name)
response.append(fetion_number)
#response.append(gender)
#response.append(email)
return response
def get_info(self,who=None):
"""get contact info.
who should be uri. string or list
"""
alluri = []
if who == None:
return self.get_personal_info()
if type(who) is not list:
alluri.append(who)
else:
alluri = who
self.get("INFO","GetContactsInfo",alluri)
response = self.send()
return response
def set_info(self,info):
contacts = re.findall('<contact (.+?)</contact>',info)
contacts += re.findall('<presence (.+?)</presence>',info)
for contact in contacts:
#print contacts
uri = ''
nickname = ''
mobile_no = ''
try:
(uri,mobile_no,nickname) = re.findall('uri="(.+?)".+?mobile-no="(.*?)".+?nickname="(.*?)"',contact)[0]
except:
try:
(uri,nickname) = re.findall('uri="(.+?)".+?nickname="(.*?)"',contact)[0]
except:
continue
#print uri,nickname,mobile_no
if uri == self.__uri:
continue
if self.contactlist[uri][0] == '':
self.contactlist[uri][0] = nickname
if self.contactlist[uri][1] == '':
self.contactlist[uri][1] = mobile_no
def get_contactlist(self):
"""get contact list
contactlist is a dict:
{uri:[name,mobile-no,status,type,group-id]}
"""
buddy_list = ''
allow_list = ''
chat_friends = ''
need_info = []
self.get("INFO","GetContactList")
response = self.send()
code = self.get_code(response)
if code != 200:
return False
try:
d = re.findall('<buddy-lists>(.*?)<allow-list>',response)[0]
#No buddy here
except:
return True
try:
buddy_list = re.findall('uri="(.+?)" user-id="\d+" local-name="(.*?)" buddy-lists="(.*?)"',d)
self.grouplist = re.findall('id="(\d+)" name="(.*?)"',d)
except:
return False
try:
d = re.findall('<chat-friends>(.*?)</chat-friends>',d)[0]
chat_friends = re.findall('uri="(.+?)" user-id="\d+"',d)
except:
pass
for uri in chat_friends:
if uri not in self.contactlist:
l = ['']*5
need_info.append(uri)
self.contactlist[uri] = l
self.contactlist[uri][0] = ''
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][3] = 'A'
#buddy_list [(uri,local_name),...]
for p in buddy_list:
l = ['']*5
#set uri
self.contactlist[p[0]] = l
#set local-name
self.contactlist[p[0]][0] = p[1]
#set default status
self.contactlist[p[0]][2] = FetionHidden
#self.contactlist[p[0]][2] = FetionOffline
#set group id here!
self.contactlist[p[0]][4] = p[2]
if p[0].startswith("tel"):
self.contactlist[p[0]][3] = 'T'
self.contactlist[p[0]][2] = FetionHidden
#set mobile_no
self.contactlist[p[0]][1] = p[0][4:]
#if no local-name use mobile-no as name
if p[1] == '':
self.contactlist[p[0]][0] = self.contactlist[p[0]][1]
else:
self.contactlist[p[0]][3] = 'B'
if self.contactlist[p[0]][0] == '':
need_info.append(p[0])
"""
try:
s = re.findall('<allow-list>(.+?)</allow-list>',response)[0]
allow_list = re.findall('uri="(.+?)"',s)
except:
pass
#allow_list [uri,...]
for uri in allow_list:
if uri not in self.contactlist:
l = ['']*4
need_info.append(uri)
self.contactlist[uri] = l
self.contactlist[uri][0] = ''
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][3] = 'A'
"""
ret = self.get_info(need_info)
self.set_info(ret)
return True
def get_uri(self,who):
"""get uri from fetion number"""
if who in self.__uri:
return self.__uri
if who.startswith("sip"):
return who
for uri in self.contactlist:
if who in uri:
return uri
return None
def send_msg(self,msg,to=None,flag="CatMsg"):
"""more info at send_sms function.
if someone's fetion is offline, msg will send to phone,
the same as send_sms.
"""
if not to:
to = self.__uri
#Fetion now can use mobile number(09.02.23)
#like tel: 13888888888
#but not in sending to PC
elif flag != "CatMsg" and to.startswith("tel:"):
pass
elif flag == "CatMsg" and to.startswith("tel:"):
return False
elif flag != "CatMsg" and len(to) == 11 and to.isdigit():
to = "tel:"+to
else:
to = self.get_uri(to)
if not to:
return False
msg = msg.replace('<','<')
self.get(flag,to,msg)
try:
response = self.send()
except PyFetionSocketError,e:
d_print(('e',),locals())
return False
code = self.get_code(response)
if code == 280:
d_print("Send sms OK!")
elif code == 200:
d_print("Send msg OK!")
else:
d_print(('code',),locals())
return False
return True
def send_sms(self,msg,to=None,long=True):
"""send sms to someone, if to is None, send self.
if long is True, send long sms.(Your phone should support.)
to can be mobile number or fetion number
"""
if long:
return self.send_msg(msg,to,"SendCatSMS")
else:
return self.send_msg(msg,to,"SendSMS")
def send_schedule_sms(self,msg,time,to=None):
if not to:
to = self.__uri
elif len(to) == 11 and to.isdigit():
to = "tel:"+to
else:
to = self.get_uri(to)
if not to:
return False
msg = msg.replace('<','<')
self.get("SSSetScheduleSms",msg,time,to)
response = self.send()
code = self.get_code(response)
if code == 486:
d_print("Busy Here")
return None
if code == 200:
id = re.search('id="(\d+)"',response).group(1)
d_print(('id',),locals(),"schedule_sms id")
return id
def alive(self):
"""send keepalive message"""
self.get("ALIVE",'')
response = self.send()
code = self.get_code(response)
if code == 200:
d_print("keepalive message send ok.")
return True
return False
def receive(self):
"""response from server"""
threads = []
while self.receving:
if not self.queue.empty():
response = self.queue.get()
else:
try:
response = self.recv(5)
except PyFetionSocketError,e:
yield ["NetworkError",e.msg]
continue
if response =="TimeOut":
continue
elif len(response) == 0:
d_print("logout")
return
elif response.startswith("BN"):
try:
type = re.findall('<event type="(.+?)"',response)[0]
except IndexError:
d_print("Didn't find type")
d_print(('response',),locals())
if type == "ServiceResult":
self.set_info(response)
if type == "deregistered" or type=="disconnect":
self.receving = False
yield [type]
if type == "PresenceChanged":
self.set_info(response)
ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)".+?type="sms">(\d+)\.',response)
if not ret:
ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)"',response)
#remove self uri
event = [i for i in ret if i[0] != self.__uri]
event = list(set(event))
for e in event:
if len(e) == 3 and e[2] == FetionOffline:
self.contactlist[e[0]][2] = e[2]
else:
self.contactlist[e[0]][2] = e[1]
yield [type,event]
if type == "UpdateBuddy" or type == "UpdateMobileBuddy":
uri = re.findall('uri="(.+?)"',response)[0]
l = ['']*4
self.contactlist[uri] = l
if type == "UpdateBuddy":
ret = self.get_info(uri)
self.set_info(ret)
else:
self.contactlist[uri][3] = 'T'
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][1] = uri[4:]
self.contactlist[uri][0] = uri[4:]
elif response.startswith("M"):
try:
from_uri = re.findall('F: (.*)',response)[0].strip()
msg = re.findall('\r\n\r\n(.*)',response,re.S)[0]
except:
d_print("Message without content")
continue
#if from PC remove <Font>
try:
msg = re.findall('<Font .+?>(.+?)</Font>',msg,re.S)[0]
except:
pass
#from phone or PC
try:
XI = re.findall('XI: (.*)',response)[0]
type = "PC"
except:
type = "PHONE"
#ack this message
try:
Q = re.findall('Q: (-?\d+) M',response)[0]
I = re.findall('I: (-?\d+)',response)[0]
self._ack('M',from_uri,Q,I)
except:
pass
yield ["Message",from_uri,msg,type]
elif response.startswith("I"):
try:
from_uri = re.findall('F: (.*)',response)[0].rstrip()
except:
pass
args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,self._sipc_proxy,self.presence,None]
t = on_cmd_I(self,response,args)
t.setDaemon(True)
t.start()
self.session[from_uri] = t
#print self.session
def _ack(self,cmd,from_uri,Q=0,I=0):
"""ack message """
self.get("ACK",cmd,from_uri,Q,I)
self.ack()
def __register(self,ssic,domain):
SIPC.__init__(self)
response = ''
for step in range(1,3):
self.get("REG",step,response)
response = self.send()
code = self.get_code(response)
if code == 200:
d_print("register successful.")
else:
raise PyFetionRegisterError(code,response)
def __get_system_config(self):
global FetionConfigURL
global FetionConfigXML
url = FetionConfigURL
body = FetionConfigXML % self.mobile_no
d_print(('url','body'),locals())
config_data = http_send(url,body).read()
sipc_url = re.search("<ssi-app-sign-in>(.*)</ssi-app-sign-in>",config_data).group(1)
sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",config_data).group(1)
http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",config_data).group(1)
d_print(('sipc_url','sipc_proxy','http_tunnel'),locals())
self.__sipc_url = sipc_url
self._sipc_proxy = sipc_proxy
self._http_tunnel= http_tunnel
def __get_uri(self):
url = self.__sipc_url+"?mobileno="+self.mobile_no+"&pwd="+urllib.quote(self.passwd)
d_print(('url',),locals())
ret = http_send(url,login=True)
header = str(ret.info())
body = ret.read()
try:
ssic = re.search("ssic=(.*);",header).group(1)
sid = re.search("sip:(.*)@",body).group(1)
uri = re.search('uri="(.*)" mobile-no',body).group(1)
status = re.search('user-status="(\d+)"',body).group(1)
except:
return False
domain = "fetion.com.cn"
d_print(('ssic','sid','uri','status','domain'),locals(),"Get SID OK")
self.sid = sid
self.__uri = uri
self._ssic = ssic
self._domain = domain
return True
def __print(self,vars=(),namespace=[],msg=''):
"""if only sigle variable ,arg should like this ('var',)"""
if not self.__log:
return
if vars and not namespace and not msg:
msg = vars
if vars and namespace:
for var in vars:
if var in namespace:
self.__log.debug("%s={%s}" % (var,str(namespace[var])))
if msg:
self.__log.debug("%s" % msg)
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@Gmail.com
#Ver:0.2
from PyFetion import *
from threading import Thread
from time import sleep
from copy import copy
import time
import sys
import exceptions
import cmd,wave
#from PIL import ImageGrab
ISOTIMEFORMAT='%Y-%m-%d %H:%M:%S'
userhome = os.path.expanduser('~')
config_folder = os.path.join(userhome,'.pyfetion')
config_file = os.path.join(config_folder,'config.txt')
mobile_no = ""
status = {FetionHidden:"短信在线",FetionOnline:"在线",FetionBusy:"忙碌",FetionAway:"离开",FetionOffline:"离线"}
colors = {}
class fetion_recv(Thread):
'''receive message'''
def __init__(self,phone):
self.phone = phone
Thread.__init__(self)
def run(self):
#self.phone.get_offline_msg()
global status
start_time = time.time()
#状态改变等消息在这里处理 收到的短信或者消息在recv中处理
for e in self.phone.receive():
#print e
if e[0] == "PresenceChanged":
#在登录时BN消息(e)有可能含有多个uri
for i in e[1]:
if time.time() - start_time > 5:
self.show_status(i[0],status[i[1]])
elif e[0] == "Message":
#获得消息
#系统广告 忽略之
if e[1] not in self.phone.contactlist:
continue
if e[2].startswith("!"):
self.parse_cmd(e[1],e[2])
return
self.show_message(e)
self.save_chat(e[1],e[2])
elif e[0] == "deregistered":
self.phone.receving = False
printl('')
printl("您从其它终端登录")
elif e[0] == "NetworkError":
printl("网络通讯出错:%s"%e[1])
self.phone.receving = False
printl("停止接收消息")
def show_status(self,sip,status):
try:
#os.system('play resources/online.wav')
import pynotify
outstr = self.phone.contactlist[sip][0]+'['+ str(self.get_order(sip)) + ']'
pynotify.init("Some Application or Title")
self.notification = pynotify.Notification(outstr, status,"file:///home/laputa/Projects/pytool/PyFetion/resources/fetion.png")
self.notification.set_urgency(pynotify.URGENCY_NORMAL)
self.notification.set_timeout(1)
self.notification.show()
except :
#os.system('play resources/online.wav')
print u"\n",self.phone.contactlist[sip][0],"[",self.get_order(sip),"]现在的状态:",status
def show_message(self,e):
s = {"PC":"电脑","PHONE":"手机"}
try:
#os.system('play resources/newmessage.wav')
import pynotify
outstr = self.phone.contactlist[e[1]][0] + '[' + str(self.get_order(e[1])) + ']'
pynotify.init("Some Application or Title")
self.notification = pynotify.Notification(outstr, e[2],"file:///home/laputa/Projects/pytool/PyFetion/resources/fetion.png")
self.notification.set_urgency(pynotify.URGENCY_NORMAL)
self.notification.set_timeout(1)
self.notification.show()
except:
#os.system('play resources/newmessage.wav')
print self.phone.contactlist[e[1]][0],'[',self.get_order(e[1]),']@',s[e[3]],"说:",e[2]
def parse_cmd(self,to,line):
flag = "以上信息由pyfetoin自动回复。更多指令请发送'\\help'。更多关于pyfetion的信息请访问http://code.google.com/p/pytool/"
cmd = line[1:]
print cmd
command_log_file = os.path.join(config_folder,"command.log")
file = open(command_log_file,"a")
record = to.split("@")[0].split(":")[1] + " " + time.strftime(ISOTIMEFORMAT) + " " + cmd + "\n"
file.write(record)
file.close()
if cmd == 'weather':
file = open("/home/laputa/data/WeatherForecast")
lines = file.readlines()
message = "Weather in Bejing:\n"
i = 0
for line in lines:
if i==9:
break
message = message + line
i = i + 1
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
elif cmd == 'wish':
wish = "Happy New Year!"
wish = wish + flag
if self.phone.send_msg(toUTF8(wish),to):
print "success"
elif cmd == 'mpc next':
os.system("mpc next")
print "success"
elif cmd == 'mpc prev':
os.system("mpc prev")
print "success"
elif cmd == 'help':
message = "目前已实现的指令有:weather,wish,help这三个。发送'\\'+指令即可。weather获取天气预报,wish获取祝福,help获取帮助。"
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
else:
message = "还没有这个指令呢。"
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
def save_chat(self,sip,text):
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"a")
record = sip.split("@")[0].split(":")[1] + " " + time.strftime(ISOTIMEFORMAT) + " " + text + "\n"
file.write(record)
file.close()
def get_order(self,sip):
'''get order number from sip'''
c = copy(self.phone.contactlist)
num = len(c.items())
for i in range(num):
if sip == c.keys()[i]:
return i
return None
class fetion_alive(Thread):
'''keep alive'''
def __init__(self,phone):
self.phone = phone
Thread.__init__(self)
def run(self):
last_time = time.time()
while self.phone.receving:
sleep(3)
if time.time() - last_time > 300:
last_time = time.time()
self.phone.alive()
printl("停止发送心跳")
class CLI(cmd.Cmd):
'''解析命令行参数'''
def __init__(self,phone):
global status
cmd.Cmd.__init__(self)
self.phone=phone
self.to=""
self.type="msg"
self.nickname = self.phone.get_personal_info()[0]
self.prompt = self.color(self.nickname,status[self.phone.presence]) + ">"
def preloop(self):
print u"欢迎使用PyFetion!\n要获得帮助请输入help或help help.\n更多信息请访问http://code.google.com/p/pytool/\n"
print u"当前\033[32m在线\033[0m或\033[36m离开\033[0m或\033[31m忙碌\033[0m的好友为(ls命令可以得到下面结果):"
self.do_ls("")
def default(self, line):
'''会话中:快速发送消息'''
c = copy(self.phone.contactlist)
if self.to:
if self.phone.send_msg(toUTF8(line),self.to):
print u'send to ',c[self.to][0]," at ", time.strftime(ISOTIMEFORMAT)
self.save_chat(self.to,line)
else:
printl("发送消息失败")
else:
print line, u' 不支持的命令!'
def do_test(self,line):
#os.system('play resources/online.wav')
self.prompt="jfaskdflajfklafld>"
return
def do_info(self,line):
'''用法:info
查看个人信息'''
if line:
to = self.get_sip(line)
if to == None:
return
info = self.get_info(to)
print u"序号:",self.get_order(to)
print u"昵称:",info[0]
print u"飞信号:",self.get_fetion_number(to)
print u"手机号:",info[1]
print u"状态:",status[info[2]]
return
info = self.phone.get_personal_info()
print u"昵称:",info[0]
print u"状态:",info[1]
print u"手机号:",info[2]
print u"真实姓名:",info[3]
print u"飞信号:",info[4]
#print u"性别:",info[5]
#print u"电子邮箱:",info[6]
def get_info(self,uri):
c = copy(self.phone.contactlist)
response=[]
response.append(c[uri][0])
response.append(c[uri][1])
response.append(c[uri][2])
return response
def do_la(self,line):
'''用法:ls\n按组显示所有好友列表.
\033[34m短信在线\t\033[35m离线
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
#printl(status[FetionOnline])
for group in self.phone.grouplist:
print "\033[1m["+group[0]+"]"+group[1]+"\033[0m:"
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
def do_ls(self,line):
'''用法: ls\n 显示在线好友列表
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if line:
to=self.get_sip(line)
if to == None:
return
print self.get_order(to),self.get_nickname(to)
return
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
if c[c.keys()[i]][2] != FetionHidden and c[c.keys()[i]][2] != FetionOffline:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
def do_lg(self,line):
if not line:
for group in self.phone.grouplist:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m\t",
print ""
return
#有参数,显示特定分组
c = copy(self.phone.contactlist)
num = len(c.items())
for group in self.phone.grouplist:
if line == group[0]:
print group[1]+":"
for i in range(num):
if c[c.keys()[i]][4] == line:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
return
if line == group[1]:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m:"
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
return
print u"不存在此分组"
def do_rename(self,line):
if not line:
print u'用法:rename [昵称]\n修改昵称'
return
print u'即将实现此功能'
#if self.phone.set_presence(line):
# print "修改成功"
#else:
# print "修改失败"
def do_ll(self,line):
'''用法: ll\n列出好友详细信息:序号,昵称,手机号,状态,分组.
\033[34m短信在线\t\033[35m离线
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
uri = c.keys()[i]
outstr = str(i)+"\t" + c[uri][0]+"\t" + c[uri][1]+"\t" + status[c[uri][2]]
for group in self.phone.grouplist:
if group[0] == c[uri][4]:
outstr = outstr + "\t\033[4m" + group[1] + "\033[0m"
print self.color(outstr,status[c[uri][2]])
def do_status(self,i):
'''用法: status [i]\n改变状态:\033[34m0 隐身\033[36m1 离开\033[35m 2 离线\033[31m 3 忙碌\033[32m 4 在线.\033[0m'''
if i:
if self.to:
tmpstr = self.prompt.split()
self.prompt = self.color(tmpstr[0][5:-4],i) + " [to] " + tmpstr[2]
return
self.prompt = self.color(self.prompt[5:-5],i) + ">"
i = int(i)
self.phone.set_presence(status.keys()[i])
else:
outstr = "用法: status [i]\n改变状态:\033[34m0 隐身\033[36m1 离开\033[35m 2 离线\033[31m 3 忙碌\033[32m 4 在线\033[0m."
print self.color(status[self.phone.presence],status[self.phone.presence])
print outstr
def do_msg(self,line):
"""msg [num] [text]
send text to num and save the session"""
if not line:
print u'用法:msg [num] [text]'
return
cmd = line.split()
num = cmd[0]
if num==mobile_no:
self.to = mobile_no
if len(cmd)>1:
self.phone.send_sms(cmd[1])
else:
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] self>"
return
to = self.get_sip(num)
if to == None:
return
self.to = to
nickname = self.get_nickname(self.to)
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] " + nickname + ">"
if len(cmd)>1:
if self.phone.send_msg(toUTF8(cmd[1]),self.to):
self.save_chat(self.to,cmd[1])
print u'send message to ', nickname," at ", time.strftime(ISOTIMEFORMAT)
else:
printl("发送消息失败")
def save_chat(self,sip,text):
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"a")
record ="out!" + self.get_fetion_number(sip) + " " + time.strftime(ISOTIMEFORMAT) + " " + text + "\n"
file.write(record)
file.close()
def do_sms(self,line):
'''用法:sms [num] [text]
send sms to num'''
if not line:
print u'用法:sms [num] [text]'
return
cmd = line.split()
if len(cmd) ==1:
num = cmd[0]
num = cmd[0]
if num==mobile_no:
self.to = mobile_no
if len(cmd)>1:
self.phone.send_sms(cmd[1])
else:
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] self>"
return
to=self.get_sip(num)
if to == None:
return
if not self.phone.send_sms(toUTF8(cmd[1]),to):
printl("发送短信失败")
else:
print u'已发送 ',self.get_nickname(to)
def do_find(self,line):
'''用法:find [序号|手机号]|all
隐身查询'''
if not line:
print u'用法:find [num]'
return
if line=='all':
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
uri = c.keys()[i]
if c[uri][2] == FetionHidden:
ret = self.phone.start_chat(uri)
if ret:
if ret == c[uri][2]:
print self.color("["+str(i)+"]"+c[uri][0],status[c[uri][2]]),"\t",
#elif ret == FetionOnline:
#print c[c.keys()[i]][0],u"不在线"
print ""
return
cmd = line.split()
to = self.get_sip(cmd[0])
if to == None:
return
nickname = self.get_nickname(to)
if self.phone.contactlist[to][2] != FetionHidden:
printl("拜托人家写着在线你还要查!")
else:
ret = self.phone.start_chat(to)
if ret:
if ret == self.phone.contactlist[to][2]:
print nickname, u"果然隐身"
elif ret == FetionOnline:
print nickname, u"的确不在线哦"
else:
printl("获取隐身信息出错")
def do_add(self,line):
'''用法:add 手机号或飞信号'''
if not line:
printl("命令格式:add[a] 手机号或飞信号")
return
if line.isdigit() and len(line) == 9 or len(line) == 11:
code = self.phone.add(line)
if code:
printl("添加%s成功"%line)
else:
printl("添加%s失败"%line)
else:
printl("命令格式:add[a] 手机号或飞信号")
def do_gadd(self,line):
'''Usage:gadd [group id or group name] [buddy id or buddy name]
add buddy to group'''
if not line:
return
cmd = line.split()
if not groupself.get_group_id(cmd[0]):
if not self.tmp_group:
self.tmp_group = {}
#self.tmp_group[9999] = cmd[0]
print u'创建临时分组:'+cmd[0]
return
elif self.tmp_group[9999] != cmd[0]:
ans = raw_input('已存在临时分组'+self.tmp_group[9999]+",要覆盖该分组吗(y/n)?")
if ans == 'y':
self.tmp_group.clear()
self.tmp_group[9999] = cmd[0]
print u'创建临时分组:'+cmd[0]
if len(cmd)==1:
pass
def get_group_id(self,line):
for group in self.phone.grouplist:
if line == group[0]:
return line
if line == group[1]:
return group[0]
print u'不存在此分组'
def do_del(self,line):
'''delete buddy'''
if not line:
printl("命令格式:del[d] 手机号或飞信号")
return
if line.isdigit() and len(line) == 9 or len(line) == 11:
code = self.phone.delete(line)
if code:
printl("删除%s成功"%line)
else:
printl("删除%s失败"%line)
else:
sip = self.get_sip(line)
if sip == None:
return
num = self.get_fetion_number(sip)
code = self.phone.delete(num)
if code:
printl("删除%s成功"%num)
else:
printl("删除%s失败"%num)
def get_fetion_number(self,uri):
'''get fetion number from uri'''
return uri.split("@")[0].split(":")[1]
def do_get(self,line):
self.phone.get_offline_msg()
def get_order(self,sip):
'''get order number from sip'''
c = copy(self.phone.contactlist)
num = len(c.items())
for i in range(num):
if sip == c.keys()[i]:
return i
return None
def do_update(self,line):
'''用法:update [状态]
更新飞信状态'''
pass
def do_scrot(self,line):
if line:
print "用法:scrot"
return
#im = ImageGrab.grab()
#name = time.strftime("%Y%m%d%H%M%S") + ".png"
#im.save(name)
def do_gsms(self,line):
if not line:
return
cmd = line.split()
c = copy(self.phone.contactlist)
num = len(c.items())
for group in self.phone.grouplist:
if cmd[0] == group[0]:
print group[1]+":"
if len(cmd)==1:
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
elif cmd[1]!="":
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
self.phone.send_sms(toUTF8(line[1]),c.keys()[i])
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"sended."
return
if cmd[0] == group[1]:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m:"
if len(cmd)==1:
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
elif cmd[1]!="":
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
self.phone.send_sms(toUTF8(line[1]),c.keys()[i])
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"sended."
return
print u"不存在此分组"
def do_cls(self,line):
pass
def get_sip(self,num):
'''get sip and nickname from phone number or order or fetion number'''
c = copy(self.phone.contactlist)
if not num.isdigit():
'''昵称形式'''
for uri in c.keys():
if num == c[uri][0]:
return uri
return
if len(num)==11:
'''cellphone number'''
sip = ""
for c in c.items():
if c[1][1] == num:
sip=c[0]
return sip
if not sip:
printl("手机号不是您的好友")
elif len(num) == 9:
'''fetion number'''
for uri in c.keys():
if num == self.get_fetion_number(uri):
return uri
elif len(num) < 4:
'''order number'''
n = int(num)
if n >= 0 and n < len(c):
return c.keys()[n]
else:
printl("编号超出好友范围")
def get_nickname(self,sip):
return self.phone.contactlist[sip][0]
def color(self,message,status):
if status=='0' or status == '短信在线':
'''FetionHidden'''
return "\033[34m" + message + "\033[0m"
elif status == '1' or status =='离开':
'''FetionAway'''
return "\033[36m" + message + "\033[0m"
elif status == '2' or status == '离线':
'''FetionOffline'''
return "\033[35m" + message + "\033[0m"
elif status == '3' or status == '忙碌':
'''FetionBusy'''
return "\033[31m" + message + "\033[0m"
elif status == '4' or status == '在线':
'''FetionOnline'''
return "\033[32m" + message + "\033[0m"
def do_history(self,line):
'''usage:history
show the chat history information'''
try:
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"r")
except:
return
records = file.readlines()
for record in records:
temp = record.split()
time = temp[2].split(":")[0]+":"+temp[2].split(":")[1]
text = temp[3]
fetions = temp[0].split("!")
if len(fetions)==2:
'''发出的信息'''
fetion= fetions[1]
sip = self.get_sip(fetion)
if sip == None:
return
nickname = self.get_nickname(sip)
if not line:
'''无参,全显示'''
print self.nickname," to ",nickname," ",time,text
else:
'''有参,只显示特定好友历史记录'''
the_sip = self.get_sip(line)
if the_sip == None:
return
if the_sip == sip:
print self.nickname," to ",nickname," ",time,text
else:
'''接收的信息'''
fetion=fetions[0]
sip = self.get_sip(fetion)
if sip == None:
return
nickname = self.get_nickname(sip)
if not line:
print nickname," to ",self.nickname," ",time,text
else:
the_sip = self.get_sip(line)
if the_sip == sip:
print nickname," to ",self.nickname," ",time,text
def do_log(self,line):
command_log_file = os.path.join(config_folder,"command.log")
file = open(command_log_file,"r")
records = file.readlines()
for record in records:
print record
def do_quit(self,line):
'''quit\nquit the current session'''
self.to=""
self.prompt=self.prompt.split()[0]+">"
pass
def do_exit(self,line):
'''exit\nexit the program'''
self.phone.logout()
sys.exit(0)
def do_help(self,line):
self.clear()
printl("""
------------------------基于PyFetion的一个CLI飞信客户端-------------------------
命令不区分大小写中括号里为命令的缩写
help[?] 显示本帮助信息
ls 列出在线好友列表
la 按组列出所有好友列表
ll 列出序号,备注,昵称,所在组,状态
lg 列出好友分组,带参数显示该分组的好友列表
status[st] 改变飞信状态 参数[0隐身 1离开 2忙碌 3在线]
参数为空显示自己的状态
msg[m] 发送消息 参数为序号或手机号 使用quit退出
sms[s] 发送短信 参数为序号或手机号 使用quit退出
参数为空给自己发短信
find[f] 查看好友是否隐身 参数为序号或手机号
info[i] 查看好友详细信息,无参数则显示个人信息
update[u] 更新状态
add[a] 添加好友 参数为手机号或飞信号
del[d] 删除好友 参数为手机号或飞信号
cls[c] 清屏
quit[q] 退出对话状态
exit[x] 退出飞信
""")
def clear(self):
if os.name == "posix":
os.system("clear")
else:
os.system("cls")
def do_EOF(self, line):
return True
def postloop(self):
print
#shortcut
do_q = do_quit
do_h = do_history
do_x = do_exit
do_m = do_msg
do_s = do_sms
do_st = do_status
do_f = do_find
do_a = do_add
do_d = do_del
do_i = do_info
do_u = do_update
class fetion_input(Thread):
def __init__(self,phone):
self.phone = phone
self.to = ""
self.type = "SMS"
self.hint = "PyFetion:"
Thread.__init__(self)
def run(self):
sleep(1)
#self.help()
#while self.phone.receving:
# try:
# self.hint = toEcho(self.hint)
# except :
# pass
# #self.cmd(raw_input(self.hint))
try:
CLI(self.phone).cmdloop()
except KeyboardInterrupt:
self.phone.logout()
sys.exit(0)
printl("退出输入状态")
def cmd(self,arg):
global status
if not self.phone.receving:
return
cmd = arg.strip().lower().split(' ')
if cmd[0] == "":
return
elif cmd[0] == "quit" or cmd[0] == "q":
self.to = ""
self.hint = "PyFetion:"
elif self.to == "ME":
self.phone.send_sms(toUTF8(arg))
elif self.to:
if self.type == "SMS":
if not self.phone.send_sms(toUTF8(arg),self.to):
printl("发送短信失败")
else:
if self.to in self.phone.session:
self.phone.session[self.to]._send_msg(toUTF8(arg))
return
if not self.phone.send_msg(toUTF8(arg),self.to):
printl("发送消息失败")
return
elif cmd[0] == "help" or cmd[0] == "h" or cmd[0] == '?':
#显示帮助信息
self.help()
elif cmd[0] == "status" or cmd[0] == "st":
#改变飞信的状态
if len(cmd) != 2:
printl("当前状态为[%s]" % status[self.phone.presence])
return
try:
i = int(cmd[1])
except exceptions.ValueError:
printl("当前状态为[%s]" % status[self.phone.presence])
return
if i >3 or i < 0:
printl("当前状态为[%s]" % status[self.phone.presence])
return
if self.phone.presence == status.keys()[i]:
return
else:
self.phone.set_presence(status.keys()[i])
elif cmd[0] == "sms" or cmd[0] == 'msg' or cmd[0] == 's' or cmd[0] == 'm' or cmd[0] == "find" or cmd[0] == 'f':
#发送短信或者消息
s = {"MSG":"消息","SMS":"短信","FIND":"查询"}
if len(cmd) == 1 and cmd[0].startswith('s'):
self.hint = "给自己发短信:"
self.to = "ME"
return
if len(cmd) != 2:
printl("命令格式:sms[msg] 编号[手机号]")
return
if cmd[0].startswith('s'):
self.type = "SMS"
elif cmd[0].startswith('m'):
self.type = "MSG"
else:
self.type = "FIND"
self.to = ""
try:
int(cmd[1])
except exceptions.ValueError:
if cmd[1].startswith("sip"):
self.to = cmd[1]
self.hint = "给%s发%s:" % (cmd[1],s[self.type])
else:
printl("命令格式:sms[msg] 编号[手机号]")
return
c = copy(self.phone.contactlist)
#使用编号作为参数
if len(cmd[1]) < 4:
n = int(cmd[1])
if n >= 0 and n < len(self.phone.contactlist):
self.to = c.keys()[n]
self.hint = "给%s发%s:" % (c[self.to][0],s[self.type])
else:
printl("编号超出好友范围")
return
#使用手机号作为参数
elif len(cmd[1]) == 11:
for c in c.items():
if c[1][1] == cmd[1]:
self.to = c[0]
self.hint = "给%s发%s:" % (c[1][0],s[self.type])
if not self.to:
printl("手机号不是您的好友")
else:
printl("不正确的好友")
if self.type == "FIND":
#如果好友显示为在线(包括忙碌等) 则不查询
if self.phone.contactlist[self.to][2] != FetionHidden:
printl("拜托人家写着在线你还要查!")
else:
ret = self.phone.start_chat(self.to)
if ret:
if ret == c[self.to][2]:
printl("该好友果然隐身")
elif ret == FetionOnline:
printl("该好友的确不在线哦")
else:
printl("获取隐身信息出错")
self.to = ""
self.type = "SMS"
self.hint = "PyFetion:"
elif cmd[0] == "ls" or cmd[0] == "l":
#显示好友列表
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
printl(status[FetionOnline])
for i in range(num):
if c[c.keys()[i]][2] != FetionHidden and c[c.keys()[i]][2] != FetionOffline:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
printl(status[FetionHidden])
for i in range(num):
if c[c.keys()[i]][2] == FetionHidden:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
printl(status[FetionOffline])
for i in range(num):
if c[c.keys()[i]][2] == FetionOffline:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
elif cmd[0] == "add" or cmd[0] == 'a':
if len(cmd) != 2:
printl("命令格式:add[a] 手机号或飞信号")
return
if cmd[1].isdigit() and len(cmd[1]) == 9 or len(cmd[1]) == 11:
code = self.phone.add(cmd[1])
if code:
printl("添加%s成功"%cmd[1])
else:
printl("添加%s失败"%cmd[1])
else:
printl("命令格式:add[a] 手机号或飞信号")
return
elif cmd[0] == "del" or cmd[0] == 'd':
if len(cmd) != 2:
printl("命令格式:del[d] 手机号或飞信号")
return
if cmd[1].isdigit() and len(cmd[1]) == 9 or len(cmd[1]) == 11:
code = self.phone.delete(cmd[1])
if code:
printl("删除%s成功"%cmd[1])
else:
printl("删除%s失败"%cmd[1])
else:
printl("命令格式:del[d] 手机号或飞信号")
return
elif cmd[0] == "get":
self.phone.get_offline_msg()
elif cmd[0] == "cls" or cmd[0] == 'c':
#清屏
self.clear()
elif cmd[0] == "exit" or cmd[0] == 'x':
self.phone.logout()
else:
printl("不能识别的命令 请使用help")
class progressBar(Thread):
def __init__(self):
self.running = True
Thread.__init__(self)
def run(self):
i = 1
while self.running:
sys.stderr.write('\r')
sys.stderr.write('-'*i)
sys.stderr.write('>')
sleep(0.5)
i += 1
def stop(self):
self.running = False
def toUTF8(str):
return str.decode((os.name == 'posix' and 'utf-8' or 'cp936')).encode('utf-8')
def toEcho(str):
return str.decode('utf-8').encode((os.name == 'posix' and 'utf-8' or 'cp936'))
def printl(msg):
msg = str(msg)
try:
print(msg.decode('utf-8'))
except exceptions.UnicodeEncodeError:
print(msg)
def getch():
if os.name == 'posix':
import sys,tty,termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd,termios.TCSADRAIN,old_settings)
return ch
elif os.name == 'nt':
import msvcrt
return msvcrt.getch()
def getpass(msg):
"""实现一个命令行下的密码输入界面"""
passwd = ""
sys.stdout.write(msg)
ch = getch()
while (ch != '\r'):
#Linux下得到的退格键值是\x7f 不理解
if ch == '\b' or ch == '\x7f':
passwd = passwd[:-1]
else:
passwd += ch
sys.stdout.write('\r')
sys.stdout.write(msg)
sys.stdout.write('*'*len(passwd))
sys.stdout.write(' '*(80-len(msg)-len(passwd)-1))
sys.stdout.write('\b'*(80-len(msg)-len(passwd)-1))
ch = getch()
sys.stdout.write('\n')
return passwd
def config():
if not os.path.isdir(config_folder):
os.mkdir(config_folder)
if not os.path.exists(config_file):
file = open(config_file,'w')
content = "#该文件由pyfetion生成,请勿随意修改\n#tel=12345678910\n#password=123456\n"
content +="隐身=蓝色\n离开=青蓝色\n离线=紫红色\n忙碌=红色\n在线=绿色\n"
content +="颜色和linux终端码的对应参照http://www.chinaunix.net/jh/6/54256.html"
file.write(content)
file.close()
if not os.path.exists(config_file):
print u'创建文件失败'
else:
print u'创建文件成功'
def login():
'''登录设置'''
global mobile_no
if len(sys.argv) > 3:
print u'参数错误'
elif len(sys.argv) == 3:
mobile_no = sys.argv[1]
passwd = sys.argv[2]
else:
if len(sys.argv) == 2:
mobile_no = sys.argv[1]
elif len(sys.argv) == 1:
try:
confile = open(config_file,'r')
lines = confile.readlines()
for line in lines:
if line.startswith("#"):
continue
if line.startswith("tel"):
mobile_no = line.split("=")[1][:-1]
elif line.startswith("password"):
passwd = line.split("=")[1]
phone = PyFetion(mobile_no,passwd,"TCP",debug="FILE")
return phone
except:
mobile_no = raw_input(toEcho("手机号:"))
passwd = getpass(toEcho("口 令:"))
save = raw_input(toEcho("是否保存手机号和密码以便下次自动登录(y/n)?"))
if save == 'y':
confile = open(config_file,'w')
content = "#该文件由pyfetion生成,请勿随意修改\n"
content = content + "tel=" + mobile_no
content = content + "\npassword=" + passwd
confile.write(content)
confile.close()
phone = PyFetion(mobile_no,passwd,"TCP",debug="FILE")
return phone
def main(phone):
'''main function'''
try:
t = progressBar()
t.start()
#可以在这里选择登录的方式[隐身 在线 忙碌 离开]
ret = phone.login(FetionHidden)
except PyFetionSupportError,e:
printl("手机号未开通飞信")
return 1
except PyFetionAuthError,e:
printl("手机号密码错误")
return 1
except PyFetionSocketError,e:
print(e.msg)
printl("网络通信出错 请检查网络连接")
return 1
finally:
t.stop()
if ret:
printl("登录成功")
else:
printl("登录失败")
return 1
threads = []
threads.append(fetion_recv(phone))
threads.append(fetion_alive(phone))
#threads.append(fetion_input(phone))
t1 = fetion_input(phone)
t1.setDaemon(True)
t1.start()
for t in threads:
t.setDaemon(True)
t.start()
while len(threads):
t = threads.pop()
if t.isAlive():
t.join()
del t1
printl("飞信退出")
#phone.send_schedule_sms("请注意,这个是定时短信",time)
#time_format = "%Y-%m-%d %H:%M:%S"
#time.strftime(time_format,time.gmtime())
if __name__ == "__main__":
config()
phone = login()
sys.exit(main(phone))
| Python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@Gmail.com
#Ver:0.2
from PyFetion import *
from threading import Thread
from time import sleep
from copy import copy
import time
import sys
import exceptions
import cmd,wave
#from PIL import ImageGrab
ISOTIMEFORMAT='%Y-%m-%d %H:%M:%S'
userhome = os.path.expanduser('~')
config_folder = os.path.join(userhome,'.pyfetion')
config_file = os.path.join(config_folder,'config.txt')
mobile_no = ""
status = {FetionHidden:"短信在线",FetionOnline:"在线",FetionBusy:"忙碌",FetionAway:"离开",FetionOffline:"离线"}
colors = {}
class fetion_recv(Thread):
'''receive message'''
def __init__(self,phone):
self.phone = phone
Thread.__init__(self)
def run(self):
#self.phone.get_offline_msg()
global status
start_time = time.time()
#状态改变等消息在这里处理 收到的短信或者消息在recv中处理
for e in self.phone.receive():
#print e
if e[0] == "PresenceChanged":
#在登录时BN消息(e)有可能含有多个uri
for i in e[1]:
if time.time() - start_time > 5:
self.show_status(i[0],status[i[1]])
elif e[0] == "Message":
#获得消息
#系统广告 忽略之
if e[1] not in self.phone.contactlist:
continue
if e[2].startswith("!"):
self.parse_cmd(e[1],e[2])
return
self.show_message(e)
self.save_chat(e[1],e[2])
elif e[0] == "deregistered":
self.phone.receving = False
printl('')
printl("您从其它终端登录")
elif e[0] == "NetworkError":
printl("网络通讯出错:%s"%e[1])
self.phone.receving = False
printl("停止接收消息")
def show_status(self,sip,status):
try:
#os.system('play resources/online.wav')
import pynotify
outstr = self.phone.contactlist[sip][0]+'['+ str(self.get_order(sip)) + ']'
pynotify.init("Some Application or Title")
self.notification = pynotify.Notification(outstr, status,"file:///home/laputa/Projects/pytool/PyFetion/resources/fetion.png")
self.notification.set_urgency(pynotify.URGENCY_NORMAL)
self.notification.set_timeout(1)
self.notification.show()
except :
#os.system('play resources/online.wav')
print u"\n",self.phone.contactlist[sip][0],"[",self.get_order(sip),"]现在的状态:",status
def show_message(self,e):
s = {"PC":"电脑","PHONE":"手机"}
try:
#os.system('play resources/newmessage.wav')
import pynotify
outstr = self.phone.contactlist[e[1]][0] + '[' + str(self.get_order(e[1])) + ']'
pynotify.init("Some Application or Title")
self.notification = pynotify.Notification(outstr, e[2],"file:///home/laputa/Projects/pytool/PyFetion/resources/fetion.png")
self.notification.set_urgency(pynotify.URGENCY_NORMAL)
self.notification.set_timeout(1)
self.notification.show()
except:
#os.system('play resources/newmessage.wav')
print self.phone.contactlist[e[1]][0],'[',self.get_order(e[1]),']@',s[e[3]],"说:",e[2]
def parse_cmd(self,to,line):
flag = "以上信息由pyfetoin自动回复。更多指令请发送'\\help'。更多关于pyfetion的信息请访问http://code.google.com/p/pytool/"
cmd = line[1:]
print cmd
command_log_file = os.path.join(config_folder,"command.log")
file = open(command_log_file,"a")
record = to.split("@")[0].split(":")[1] + " " + time.strftime(ISOTIMEFORMAT) + " " + cmd + "\n"
file.write(record)
file.close()
if cmd == 'weather':
file = open("/home/laputa/data/WeatherForecast")
lines = file.readlines()
message = "Weather in Bejing:\n"
i = 0
for line in lines:
if i==9:
break
message = message + line
i = i + 1
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
elif cmd == 'wish':
wish = "Happy New Year!"
wish = wish + flag
if self.phone.send_msg(toUTF8(wish),to):
print "success"
elif cmd == 'mpc next':
os.system("mpc next")
print "success"
elif cmd == 'mpc prev':
os.system("mpc prev")
print "success"
elif cmd == 'help':
message = "目前已实现的指令有:weather,wish,help这三个。发送'\\'+指令即可。weather获取天气预报,wish获取祝福,help获取帮助。"
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
else:
message = "还没有这个指令呢。"
message = message + flag
if self.phone.send_msg(toUTF8(message),to):
print "success"
def save_chat(self,sip,text):
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"a")
record = sip.split("@")[0].split(":")[1] + " " + time.strftime(ISOTIMEFORMAT) + " " + text + "\n"
file.write(record)
file.close()
def get_order(self,sip):
'''get order number from sip'''
c = copy(self.phone.contactlist)
num = len(c.items())
for i in range(num):
if sip == c.keys()[i]:
return i
return None
class fetion_alive(Thread):
'''keep alive'''
def __init__(self,phone):
self.phone = phone
Thread.__init__(self)
def run(self):
last_time = time.time()
while self.phone.receving:
sleep(3)
if time.time() - last_time > 300:
last_time = time.time()
self.phone.alive()
printl("停止发送心跳")
class CLI(cmd.Cmd):
'''解析命令行参数'''
def __init__(self,phone):
global status
cmd.Cmd.__init__(self)
self.phone=phone
self.to=""
self.type="msg"
self.nickname = self.phone.get_personal_info()[0]
self.prompt = self.color(self.nickname,status[self.phone.presence]) + ">"
def preloop(self):
print u"欢迎使用PyFetion!\n要获得帮助请输入help或help help.\n更多信息请访问http://code.google.com/p/pytool/\n"
print u"当前\033[32m在线\033[0m或\033[36m离开\033[0m或\033[31m忙碌\033[0m的好友为(ls命令可以得到下面结果):"
self.do_ls("")
def default(self, line):
'''会话中:快速发送消息'''
c = copy(self.phone.contactlist)
if self.to:
if self.phone.send_msg(toUTF8(line),self.to):
print u'send to ',c[self.to][0]," at ", time.strftime(ISOTIMEFORMAT)
self.save_chat(self.to,line)
else:
printl("发送消息失败")
else:
print line, u' 不支持的命令!'
def do_test(self,line):
#os.system('play resources/online.wav')
self.prompt="jfaskdflajfklafld>"
return
def do_info(self,line):
'''用法:info
查看个人信息'''
if line:
to = self.get_sip(line)
if to == None:
return
info = self.get_info(to)
print u"序号:",self.get_order(to)
print u"昵称:",info[0]
print u"飞信号:",self.get_fetion_number(to)
print u"手机号:",info[1]
print u"状态:",status[info[2]]
return
info = self.phone.get_personal_info()
print u"昵称:",info[0]
print u"状态:",info[1]
print u"手机号:",info[2]
print u"真实姓名:",info[3]
print u"飞信号:",info[4]
#print u"性别:",info[5]
#print u"电子邮箱:",info[6]
def get_info(self,uri):
c = copy(self.phone.contactlist)
response=[]
response.append(c[uri][0])
response.append(c[uri][1])
response.append(c[uri][2])
return response
def do_la(self,line):
'''用法:ls\n按组显示所有好友列表.
\033[34m短信在线\t\033[35m离线
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
#printl(status[FetionOnline])
for group in self.phone.grouplist:
print "\033[1m["+group[0]+"]"+group[1]+"\033[0m:"
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
def do_ls(self,line):
'''用法: ls\n 显示在线好友列表
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if line:
to=self.get_sip(line)
if to == None:
return
print self.get_order(to),self.get_nickname(to)
return
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
if c[c.keys()[i]][2] != FetionHidden and c[c.keys()[i]][2] != FetionOffline:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
def do_lg(self,line):
if not line:
for group in self.phone.grouplist:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m\t",
print ""
return
#有参数,显示特定分组
c = copy(self.phone.contactlist)
num = len(c.items())
for group in self.phone.grouplist:
if line == group[0]:
print group[1]+":"
for i in range(num):
if c[c.keys()[i]][4] == line:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
return
if line == group[1]:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m:"
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
return
print u"不存在此分组"
def do_rename(self,line):
if not line:
print u'用法:rename [昵称]\n修改昵称'
return
print u'即将实现此功能'
#if self.phone.set_presence(line):
# print "修改成功"
#else:
# print "修改失败"
def do_ll(self,line):
'''用法: ll\n列出好友详细信息:序号,昵称,手机号,状态,分组.
\033[34m短信在线\t\033[35m离线
\033[36m离开\t\033[31m忙碌\t\033[32m在线\033[0m'''
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
uri = c.keys()[i]
outstr = str(i)+"\t" + c[uri][0]+"\t" + c[uri][1]+"\t" + status[c[uri][2]]
for group in self.phone.grouplist:
if group[0] == c[uri][4]:
outstr = outstr + "\t\033[4m" + group[1] + "\033[0m"
print self.color(outstr,status[c[uri][2]])
def do_status(self,i):
'''用法: status [i]\n改变状态:\033[34m0 隐身\033[36m1 离开\033[35m 2 离线\033[31m 3 忙碌\033[32m 4 在线.\033[0m'''
if i:
if self.to:
tmpstr = self.prompt.split()
self.prompt = self.color(tmpstr[0][5:-4],i) + " [to] " + tmpstr[2]
return
self.prompt = self.color(self.prompt[5:-5],i) + ">"
i = int(i)
self.phone.set_presence(status.keys()[i])
else:
outstr = "用法: status [i]\n改变状态:\033[34m0 隐身\033[36m1 离开\033[35m 2 离线\033[31m 3 忙碌\033[32m 4 在线\033[0m."
print self.color(status[self.phone.presence],status[self.phone.presence])
print outstr
def do_msg(self,line):
"""msg [num] [text]
send text to num and save the session"""
if not line:
print u'用法:msg [num] [text]'
return
cmd = line.split()
num = cmd[0]
if num==mobile_no:
self.to = mobile_no
if len(cmd)>1:
self.phone.send_sms(cmd[1])
else:
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] self>"
return
to = self.get_sip(num)
if to == None:
return
self.to = to
nickname = self.get_nickname(self.to)
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] " + nickname + ">"
if len(cmd)>1:
if self.phone.send_msg(toUTF8(cmd[1]),self.to):
self.save_chat(self.to,cmd[1])
print u'send message to ', nickname," at ", time.strftime(ISOTIMEFORMAT)
else:
printl("发送消息失败")
def save_chat(self,sip,text):
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"a")
record ="out!" + self.get_fetion_number(sip) + " " + time.strftime(ISOTIMEFORMAT) + " " + text + "\n"
file.write(record)
file.close()
def do_sms(self,line):
'''用法:sms [num] [text]
send sms to num'''
if not line:
print u'用法:sms [num] [text]'
return
cmd = line.split()
if len(cmd) ==1:
num = cmd[0]
num = cmd[0]
if num==mobile_no:
self.to = mobile_no
if len(cmd)>1:
self.phone.send_sms(cmd[1])
else:
self.prompt = self.color(self.nickname,status[self.phone.presence]) + " [to] self>"
return
to=self.get_sip(num)
if to == None:
return
if not self.phone.send_sms(toUTF8(cmd[1]),to):
printl("发送短信失败")
else:
print u'已发送 ',self.get_nickname(to)
def do_find(self,line):
'''用法:find [序号|手机号]|all
隐身查询'''
if not line:
print u'用法:find [num]'
return
if line=='all':
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
for i in range(num):
uri = c.keys()[i]
if c[uri][2] == FetionHidden:
ret = self.phone.start_chat(uri)
if ret:
if ret == c[uri][2]:
print self.color("["+str(i)+"]"+c[uri][0],status[c[uri][2]]),"\t",
#elif ret == FetionOnline:
#print c[c.keys()[i]][0],u"不在线"
print ""
return
cmd = line.split()
to = self.get_sip(cmd[0])
if to == None:
return
nickname = self.get_nickname(to)
if self.phone.contactlist[to][2] != FetionHidden:
printl("拜托人家写着在线你还要查!")
else:
ret = self.phone.start_chat(to)
if ret:
if ret == self.phone.contactlist[to][2]:
print nickname, u"果然隐身"
elif ret == FetionOnline:
print nickname, u"的确不在线哦"
else:
printl("获取隐身信息出错")
def do_add(self,line):
'''用法:add 手机号或飞信号'''
if not line:
printl("命令格式:add[a] 手机号或飞信号")
return
if line.isdigit() and len(line) == 9 or len(line) == 11:
code = self.phone.add(line)
if code:
printl("添加%s成功"%line)
else:
printl("添加%s失败"%line)
else:
printl("命令格式:add[a] 手机号或飞信号")
def do_gadd(self,line):
'''Usage:gadd [group id or group name] [buddy id or buddy name]
add buddy to group'''
if not line:
return
cmd = line.split()
if not groupself.get_group_id(cmd[0]):
if not self.tmp_group:
self.tmp_group = {}
#self.tmp_group[9999] = cmd[0]
print u'创建临时分组:'+cmd[0]
return
elif self.tmp_group[9999] != cmd[0]:
ans = raw_input('已存在临时分组'+self.tmp_group[9999]+",要覆盖该分组吗(y/n)?")
if ans == 'y':
self.tmp_group.clear()
self.tmp_group[9999] = cmd[0]
print u'创建临时分组:'+cmd[0]
if len(cmd)==1:
pass
def get_group_id(self,line):
for group in self.phone.grouplist:
if line == group[0]:
return line
if line == group[1]:
return group[0]
print u'不存在此分组'
def do_del(self,line):
'''delete buddy'''
if not line:
printl("命令格式:del[d] 手机号或飞信号")
return
if line.isdigit() and len(line) == 9 or len(line) == 11:
code = self.phone.delete(line)
if code:
printl("删除%s成功"%line)
else:
printl("删除%s失败"%line)
else:
sip = self.get_sip(line)
if sip == None:
return
num = self.get_fetion_number(sip)
code = self.phone.delete(num)
if code:
printl("删除%s成功"%num)
else:
printl("删除%s失败"%num)
def get_fetion_number(self,uri):
'''get fetion number from uri'''
return uri.split("@")[0].split(":")[1]
def do_get(self,line):
self.phone.get_offline_msg()
def get_order(self,sip):
'''get order number from sip'''
c = copy(self.phone.contactlist)
num = len(c.items())
for i in range(num):
if sip == c.keys()[i]:
return i
return None
def do_update(self,line):
'''用法:update [状态]
更新飞信状态'''
pass
def do_scrot(self,line):
if line:
print "用法:scrot"
return
#im = ImageGrab.grab()
#name = time.strftime("%Y%m%d%H%M%S") + ".png"
#im.save(name)
def do_gsms(self,line):
if not line:
return
cmd = line.split()
c = copy(self.phone.contactlist)
num = len(c.items())
for group in self.phone.grouplist:
if cmd[0] == group[0]:
print group[1]+":"
if len(cmd)==1:
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
elif cmd[1]!="":
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
self.phone.send_sms(toUTF8(line[1]),c.keys()[i])
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"sended."
return
if cmd[0] == group[1]:
print "["+group[0]+"]\033[4m"+group[1]+"\033[0m:"
if len(cmd)==1:
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"\t",
print ""
elif cmd[1]!="":
for i in range(num):
if c[c.keys()[i]][4] == group[0]:
self.phone.send_sms(toUTF8(line[1]),c.keys()[i])
outstr = "[" + str(i) + "]" + c[c.keys()[i]][0]
print self.color(outstr,status[c[c.keys()[i]][2]]),"sended."
return
print u"不存在此分组"
def do_cls(self,line):
pass
def get_sip(self,num):
'''get sip and nickname from phone number or order or fetion number'''
c = copy(self.phone.contactlist)
if not num.isdigit():
'''昵称形式'''
for uri in c.keys():
if num == c[uri][0]:
return uri
return
if len(num)==11:
'''cellphone number'''
sip = ""
for c in c.items():
if c[1][1] == num:
sip=c[0]
return sip
if not sip:
printl("手机号不是您的好友")
elif len(num) == 9:
'''fetion number'''
for uri in c.keys():
if num == self.get_fetion_number(uri):
return uri
elif len(num) < 4:
'''order number'''
n = int(num)
if n >= 0 and n < len(c):
return c.keys()[n]
else:
printl("编号超出好友范围")
def get_nickname(self,sip):
return self.phone.contactlist[sip][0]
def color(self,message,status):
if status=='0' or status == '短信在线':
'''FetionHidden'''
return "\033[34m" + message + "\033[0m"
elif status == '1' or status =='离开':
'''FetionAway'''
return "\033[36m" + message + "\033[0m"
elif status == '2' or status == '离线':
'''FetionOffline'''
return "\033[35m" + message + "\033[0m"
elif status == '3' or status == '忙碌':
'''FetionBusy'''
return "\033[31m" + message + "\033[0m"
elif status == '4' or status == '在线':
'''FetionOnline'''
return "\033[32m" + message + "\033[0m"
def do_history(self,line):
'''usage:history
show the chat history information'''
try:
chat_history_file = os.path.join(config_folder,"chat_history.dat")
file = open(chat_history_file,"r")
except:
return
records = file.readlines()
for record in records:
temp = record.split()
time = temp[2].split(":")[0]+":"+temp[2].split(":")[1]
text = temp[3]
fetions = temp[0].split("!")
if len(fetions)==2:
'''发出的信息'''
fetion= fetions[1]
sip = self.get_sip(fetion)
if sip == None:
return
nickname = self.get_nickname(sip)
if not line:
'''无参,全显示'''
print self.nickname," to ",nickname," ",time,text
else:
'''有参,只显示特定好友历史记录'''
the_sip = self.get_sip(line)
if the_sip == None:
return
if the_sip == sip:
print self.nickname," to ",nickname," ",time,text
else:
'''接收的信息'''
fetion=fetions[0]
sip = self.get_sip(fetion)
if sip == None:
return
nickname = self.get_nickname(sip)
if not line:
print nickname," to ",self.nickname," ",time,text
else:
the_sip = self.get_sip(line)
if the_sip == sip:
print nickname," to ",self.nickname," ",time,text
def do_log(self,line):
command_log_file = os.path.join(config_folder,"command.log")
file = open(command_log_file,"r")
records = file.readlines()
for record in records:
print record
def do_quit(self,line):
'''quit\nquit the current session'''
self.to=""
self.prompt=self.prompt.split()[0]+">"
pass
def do_exit(self,line):
'''exit\nexit the program'''
self.phone.logout()
sys.exit(0)
def do_help(self,line):
self.clear()
printl("""
------------------------基于PyFetion的一个CLI飞信客户端-------------------------
命令不区分大小写中括号里为命令的缩写
help[?] 显示本帮助信息
ls 列出在线好友列表
la 按组列出所有好友列表
ll 列出序号,备注,昵称,所在组,状态
lg 列出好友分组,带参数显示该分组的好友列表
status[st] 改变飞信状态 参数[0隐身 1离开 2忙碌 3在线]
参数为空显示自己的状态
msg[m] 发送消息 参数为序号或手机号 使用quit退出
sms[s] 发送短信 参数为序号或手机号 使用quit退出
参数为空给自己发短信
find[f] 查看好友是否隐身 参数为序号或手机号
info[i] 查看好友详细信息,无参数则显示个人信息
update[u] 更新状态
add[a] 添加好友 参数为手机号或飞信号
del[d] 删除好友 参数为手机号或飞信号
cls[c] 清屏
quit[q] 退出对话状态
exit[x] 退出飞信
""")
def clear(self):
if os.name == "posix":
os.system("clear")
else:
os.system("cls")
def do_EOF(self, line):
return True
def postloop(self):
print
#shortcut
do_q = do_quit
do_h = do_history
do_x = do_exit
do_m = do_msg
do_s = do_sms
do_st = do_status
do_f = do_find
do_a = do_add
do_d = do_del
do_i = do_info
do_u = do_update
class fetion_input(Thread):
def __init__(self,phone):
self.phone = phone
self.to = ""
self.type = "SMS"
self.hint = "PyFetion:"
Thread.__init__(self)
def run(self):
sleep(1)
#self.help()
#while self.phone.receving:
# try:
# self.hint = toEcho(self.hint)
# except :
# pass
# #self.cmd(raw_input(self.hint))
try:
CLI(self.phone).cmdloop()
except KeyboardInterrupt:
self.phone.logout()
sys.exit(0)
printl("退出输入状态")
def cmd(self,arg):
global status
if not self.phone.receving:
return
cmd = arg.strip().lower().split(' ')
if cmd[0] == "":
return
elif cmd[0] == "quit" or cmd[0] == "q":
self.to = ""
self.hint = "PyFetion:"
elif self.to == "ME":
self.phone.send_sms(toUTF8(arg))
elif self.to:
if self.type == "SMS":
if not self.phone.send_sms(toUTF8(arg),self.to):
printl("发送短信失败")
else:
if self.to in self.phone.session:
self.phone.session[self.to]._send_msg(toUTF8(arg))
return
if not self.phone.send_msg(toUTF8(arg),self.to):
printl("发送消息失败")
return
elif cmd[0] == "help" or cmd[0] == "h" or cmd[0] == '?':
#显示帮助信息
self.help()
elif cmd[0] == "status" or cmd[0] == "st":
#改变飞信的状态
if len(cmd) != 2:
printl("当前状态为[%s]" % status[self.phone.presence])
return
try:
i = int(cmd[1])
except exceptions.ValueError:
printl("当前状态为[%s]" % status[self.phone.presence])
return
if i >3 or i < 0:
printl("当前状态为[%s]" % status[self.phone.presence])
return
if self.phone.presence == status.keys()[i]:
return
else:
self.phone.set_presence(status.keys()[i])
elif cmd[0] == "sms" or cmd[0] == 'msg' or cmd[0] == 's' or cmd[0] == 'm' or cmd[0] == "find" or cmd[0] == 'f':
#发送短信或者消息
s = {"MSG":"消息","SMS":"短信","FIND":"查询"}
if len(cmd) == 1 and cmd[0].startswith('s'):
self.hint = "给自己发短信:"
self.to = "ME"
return
if len(cmd) != 2:
printl("命令格式:sms[msg] 编号[手机号]")
return
if cmd[0].startswith('s'):
self.type = "SMS"
elif cmd[0].startswith('m'):
self.type = "MSG"
else:
self.type = "FIND"
self.to = ""
try:
int(cmd[1])
except exceptions.ValueError:
if cmd[1].startswith("sip"):
self.to = cmd[1]
self.hint = "给%s发%s:" % (cmd[1],s[self.type])
else:
printl("命令格式:sms[msg] 编号[手机号]")
return
c = copy(self.phone.contactlist)
#使用编号作为参数
if len(cmd[1]) < 4:
n = int(cmd[1])
if n >= 0 and n < len(self.phone.contactlist):
self.to = c.keys()[n]
self.hint = "给%s发%s:" % (c[self.to][0],s[self.type])
else:
printl("编号超出好友范围")
return
#使用手机号作为参数
elif len(cmd[1]) == 11:
for c in c.items():
if c[1][1] == cmd[1]:
self.to = c[0]
self.hint = "给%s发%s:" % (c[1][0],s[self.type])
if not self.to:
printl("手机号不是您的好友")
else:
printl("不正确的好友")
if self.type == "FIND":
#如果好友显示为在线(包括忙碌等) 则不查询
if self.phone.contactlist[self.to][2] != FetionHidden:
printl("拜托人家写着在线你还要查!")
else:
ret = self.phone.start_chat(self.to)
if ret:
if ret == c[self.to][2]:
printl("该好友果然隐身")
elif ret == FetionOnline:
printl("该好友的确不在线哦")
else:
printl("获取隐身信息出错")
self.to = ""
self.type = "SMS"
self.hint = "PyFetion:"
elif cmd[0] == "ls" or cmd[0] == "l":
#显示好友列表
if not self.phone.contactlist:
printl("没有好友")
return
if self.phone.contactlist.values()[0] != 0:
pass
#当好友列表中昵称为空重新获取
else:
self.phone.get_contactlist()
#print self.phone.contactlist
c = copy(self.phone.contactlist)
num = len(c.items())
for i in c:
if c[i][0] == '':
c[i][0] = i[4:4+9]
printl(status[FetionOnline])
for i in range(num):
if c[c.keys()[i]][2] != FetionHidden and c[c.keys()[i]][2] != FetionOffline:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
printl(status[FetionHidden])
for i in range(num):
if c[c.keys()[i]][2] == FetionHidden:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
printl(status[FetionOffline])
for i in range(num):
if c[c.keys()[i]][2] == FetionOffline:
printl("%-4d%-20s" % (i,c[c.keys()[i]][0]))
elif cmd[0] == "add" or cmd[0] == 'a':
if len(cmd) != 2:
printl("命令格式:add[a] 手机号或飞信号")
return
if cmd[1].isdigit() and len(cmd[1]) == 9 or len(cmd[1]) == 11:
code = self.phone.add(cmd[1])
if code:
printl("添加%s成功"%cmd[1])
else:
printl("添加%s失败"%cmd[1])
else:
printl("命令格式:add[a] 手机号或飞信号")
return
elif cmd[0] == "del" or cmd[0] == 'd':
if len(cmd) != 2:
printl("命令格式:del[d] 手机号或飞信号")
return
if cmd[1].isdigit() and len(cmd[1]) == 9 or len(cmd[1]) == 11:
code = self.phone.delete(cmd[1])
if code:
printl("删除%s成功"%cmd[1])
else:
printl("删除%s失败"%cmd[1])
else:
printl("命令格式:del[d] 手机号或飞信号")
return
elif cmd[0] == "get":
self.phone.get_offline_msg()
elif cmd[0] == "cls" or cmd[0] == 'c':
#清屏
self.clear()
elif cmd[0] == "exit" or cmd[0] == 'x':
self.phone.logout()
else:
printl("不能识别的命令 请使用help")
class progressBar(Thread):
def __init__(self):
self.running = True
Thread.__init__(self)
def run(self):
i = 1
while self.running:
sys.stderr.write('\r')
sys.stderr.write('-'*i)
sys.stderr.write('>')
sleep(0.5)
i += 1
def stop(self):
self.running = False
def toUTF8(str):
return str.decode((os.name == 'posix' and 'utf-8' or 'cp936')).encode('utf-8')
def toEcho(str):
return str.decode('utf-8').encode((os.name == 'posix' and 'utf-8' or 'cp936'))
def printl(msg):
msg = str(msg)
try:
print(msg.decode('utf-8'))
except exceptions.UnicodeEncodeError:
print(msg)
def getch():
if os.name == 'posix':
import sys,tty,termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd,termios.TCSADRAIN,old_settings)
return ch
elif os.name == 'nt':
import msvcrt
return msvcrt.getch()
def getpass(msg):
"""实现一个命令行下的密码输入界面"""
passwd = ""
sys.stdout.write(msg)
ch = getch()
while (ch != '\r'):
#Linux下得到的退格键值是\x7f 不理解
if ch == '\b' or ch == '\x7f':
passwd = passwd[:-1]
else:
passwd += ch
sys.stdout.write('\r')
sys.stdout.write(msg)
sys.stdout.write('*'*len(passwd))
sys.stdout.write(' '*(80-len(msg)-len(passwd)-1))
sys.stdout.write('\b'*(80-len(msg)-len(passwd)-1))
ch = getch()
sys.stdout.write('\n')
return passwd
def config():
if not os.path.isdir(config_folder):
os.mkdir(config_folder)
if not os.path.exists(config_file):
file = open(config_file,'w')
content = "#该文件由pyfetion生成,请勿随意修改\n#tel=12345678910\n#password=123456\n"
content +="隐身=蓝色\n离开=青蓝色\n离线=紫红色\n忙碌=红色\n在线=绿色\n"
content +="颜色和linux终端码的对应参照http://www.chinaunix.net/jh/6/54256.html"
file.write(content)
file.close()
if not os.path.exists(config_file):
print u'创建文件失败'
else:
print u'创建文件成功'
def login():
'''登录设置'''
global mobile_no
if len(sys.argv) > 3:
print u'参数错误'
elif len(sys.argv) == 3:
mobile_no = sys.argv[1]
passwd = sys.argv[2]
else:
if len(sys.argv) == 2:
mobile_no = sys.argv[1]
elif len(sys.argv) == 1:
try:
confile = open(config_file,'r')
lines = confile.readlines()
for line in lines:
if line.startswith("#"):
continue
if line.startswith("tel"):
mobile_no = line.split("=")[1][:-1]
elif line.startswith("password"):
passwd = line.split("=")[1]
phone = PyFetion(mobile_no,passwd,"TCP",debug="FILE")
return phone
except:
mobile_no = raw_input(toEcho("手机号:"))
passwd = getpass(toEcho("口 令:"))
save = raw_input(toEcho("是否保存手机号和密码以便下次自动登录(y/n)?"))
if save == 'y':
confile = open(config_file,'w')
content = "#该文件由pyfetion生成,请勿随意修改\n"
content = content + "tel=" + mobile_no
content = content + "\npassword=" + passwd
confile.write(content)
confile.close()
phone = PyFetion(mobile_no,passwd,"TCP",debug="FILE")
return phone
def main(phone):
'''main function'''
try:
t = progressBar()
t.start()
#可以在这里选择登录的方式[隐身 在线 忙碌 离开]
ret = phone.login(FetionHidden)
except PyFetionSupportError,e:
printl("手机号未开通飞信")
return 1
except PyFetionAuthError,e:
printl("手机号密码错误")
return 1
except PyFetionSocketError,e:
print(e.msg)
printl("网络通信出错 请检查网络连接")
return 1
finally:
t.stop()
if ret:
printl("登录成功")
else:
printl("登录失败")
return 1
threads = []
threads.append(fetion_recv(phone))
threads.append(fetion_alive(phone))
#threads.append(fetion_input(phone))
t1 = fetion_input(phone)
t1.setDaemon(True)
t1.start()
for t in threads:
t.setDaemon(True)
t.start()
while len(threads):
t = threads.pop()
if t.isAlive():
t.join()
del t1
printl("飞信退出")
#phone.send_schedule_sms("请注意,这个是定时短信",time)
#time_format = "%Y-%m-%d %H:%M:%S"
#time.strftime(time_format,time.gmtime())
if __name__ == "__main__":
config()
phone = login()
sys.exit(main(phone))
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#MIT License
#By : cocobear.cn@gmail.com
#Ver:0.2
import urllib
import urllib2
import sys,re
import binascii
import hashlib
import socket
import os
import time
import exceptions
import logging
from hashlib import md5
from hashlib import sha1
from uuid import uuid1
from threading import RLock
from threading import Thread
from select import select
from Queue import Queue
from copy import copy
FetionOnline = "400"
FetionBusy = "600"
FetionAway = "100"
FetionHidden = "0"
FetionOffline = "365"
FetionVer = "2008"
#"SIPP" USED IN HTTP CONNECTION
FetionSIPP= "SIPP"
FetionNavURL = "nav.fetion.com.cn"
FetionConfigURL = "http://nav.fetion.com.cn/nav/getsystemconfig.aspx"
FetionConfigXML = """<config><user mobile-no="%s" /><client type="PC" version="3.5.2540" platform="W6.1" /><servers version="0" /><service-no version="0" /><parameters version="0" /><hints version="0" /><http-applications version="0" /><client-config version="0" /><services version="0" /></config>"""
FetionLoginXML = """<args><device type="PC" version="1" client-version="3.5.2540" /><caps value="simple-im;im-session;temp-group;personal-group;im-relay;xeno-im;direct-sms;sms2fetion" /><events value="contact;permission;system-message;personal-group;compact" /><user-info attributes="all" /><presence><basic value="%s" desc="" /></presence></args>"""
proxy_info = False
d_print = ''
#uncomment below line if you need proxy
"""
proxy_info = {'user' : '',
'pass' : '',
'host' : '218.249.83.87',
'port' : 8080
}
"""
class PyFetionException(Exception):
"""Base class for all exceptions
"""
def __init__(self, code, msg):
self.args = (code,msg)
class PyFetionSocketError(PyFetionException):
"""any socket error"""
def __init__(self,e,msg=''):
if msg:
self.args = (e,msg)
self.code = e
self.msg = msg
elif type(e) is int:
self.args = (e,socket.errorTab[e])
self.code = e
self.msg = socket.errorTab[e]
else:
args = e.args
d_print(('args',),locals())
try:
self.args = (e.errno,msg)
msg = socket.errorTab[e.errno]
self.code = e.errno
except:
msg = e
self.msg = msg
class PyFetionAuthError(PyFetionException):
"""Authentication error.
Your password error.
"""
class PyFetionSupportError(PyFetionException):
"""Support error.
Your phone number don't support fetion.
"""
class PyFetionRegisterError(PyFetionException):
"""RegisterError.
"""
class SIPC():
global FetionVer
global FetionSIPP
global FetionLoginXML
_header = ''
#body = ''
_content = ''
code = ''
ver = "SIP-C/2.0"
Q = 1
I = 1
queue = Queue()
def __init__(self,args=[]):
self.__seq = 1
if args:
[self.sid, self._domain,self.login_type, self._http_tunnel,\
self._ssic, self._sipc_proxy, self.presence, self._lock] = args
if self.login_type == "HTTP":
guid = str(uuid1())
self.__exheaders = {
'Cookie':'ssic=%s' % self._ssic,
'Content-Type':'application/oct-stream',
'Pragma':'xz4BBcV%s' % guid,
}
else:
self.__tcp_init()
def init_ack(self,type):
self._content = "%s 200 OK\r\n" % self.ver
self._header = [('F',self.sid),
('I',self.I),
('Q','%s %s' % (self.Q,type)),
]
def init(self,type):
self._content = '%s %s %s\r\n' % (type,self._domain,self.ver)
self._header = [('F',self.sid),
('I',self.I),
('Q','%s %s' % (self.Q,type)),
]
def recv(self,timeout=False):
if self.login_type == "HTTP":
time.sleep(10)
return self.get_offline_msg()
pass
else:
if timeout:
infd,outfd,errfd = select([self.__sock,],[],[],timeout)
else:
infd,outfd,errfd = select([self.__sock,],[],[])
if len(infd) != 0:
ret = self.__tcp_recv()
num = len(ret)
d_print(('num',),locals())
if num == 0:
return ret
if num == 1:
return ret[0]
for r in ret:
self.queue.put(r)
d_print(('r',),locals())
if not self.queue.empty():
return self.queue.get()
else:
return "TimeOut"
def get_code(self,response):
cmd = ''
try:
self.code =int(re.search("%s (\d{3})" % self.ver,response).group(1))
self.msg =re.search("%s \d{3} (.*)\r" % self.ver,response).group(1)
except AttributeError,e:
try:
cmd = re.search("(.+?) %s" % self.ver,response).group(1)
d_print(('cmd',),locals())
except AttributeError,e:
pass
return cmd
return self.code
def get(self,cmd,arg,*extra):
body = ''
if extra:
body = extra[0]
if cmd == "REG":
body = FetionLoginXML % self.presence
self.init('R')
if arg == 1:
pass
if arg == 2:
nonce = re.search('nonce="(.*)"',extra[0]).group(1)
cnonce = self.__get_cnonce()
if FetionVer == "2008":
response=self.__get_response_sha1(nonce,cnonce)
elif FetionVer == "2006":
response=self.__get_response_md5(nonce,cnonce)
salt = self.__get_salt()
d_print(('nonce','cnonce','response','salt'),locals())
#If this step failed try to uncomment this lines
#del self._header[2]
#self._header.insert(2,('Q','2 R'))
if FetionVer == "2008":
self._header.insert(3,('A','Digest algorithm="SHA1-sess",response="%s",cnonce="%s",salt="%s",ssic="%s"' % (response,cnonce,salt,self._ssic)))
elif FetionVer == "2006":
self._header.insert(3,('A','Digest response="%s",cnonce="%s"' % (response,cnonce)))
#If register successful 200 code get
if arg == 3:
return self.code
if cmd == "CatMsg":
self.init('M')
self._header.append(('T',arg))
self._header.append(('C','text/plain'))
self._header.append(('K','SaveHistory'))
self._header.append(('N',cmd))
if cmd == "SendMsg":
self.init('M')
self._header.append(('C','text/plain'))
self._header.append(('K','SaveHistory'))
if cmd == "SendSMS":
self.init('M')
self._header.append(('T',arg))
self._header.append(('N',cmd))
if cmd == "SendCatSMS":
self.init('M')
self._header.append(('T',arg))
self._header.append(('N',cmd))
if cmd == "NUDGE":
self.init('IN')
self._header.append(('T',arg))
body = "<is-composing><state>nudge</state></is-composing>"
if cmd == "ALIVE":
self.init('R')
if cmd == "DEAD":
self.init('R')
self._header.append(('X','0'))
if cmd == "ACK":
body = ''
if arg == 'M':
self.Q = extra[1]
self.I = extra[2]
self.init_ack(arg)
del self._header[0]
self._header.insert(0,('F',extra[0]))
if cmd == "IN":
body ="<is-composing><state>fetion-show:\xe5\x9b\xa70x000101010000010001000000000000010000000</state></is-composing>"
self.init('IN')
self._header.insert(3,('T',arg))
if cmd == "BYE":
body = ''
self.init('B')
if cmd == "SetPresence":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><presence><basic value="%s" /></presence></args>' % arg
if cmd == "PGPresence":
self.init('SUB')
self._header.append(('N',cmd))
self._header.append(('X','0'))
body = '<args><subscription><groups /></subscription></args>'
if cmd == "PGSetPresence":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><groups /></args>'
if cmd == "compactlist":
self.init('SUB')
self._header.append(('N',cmd))
body = '<args><subscription><contacts><contact uri="%s" type="3" />'% arg
for i in extra[0]:
body += '<contact uri="%s" type="3" />' % i
body += '</contacts></subscription></args>'
if cmd == "StartChat":
if arg == '':
self.init('S')
self._header.append(('N',cmd))
else:
self.init('R')
self._header.append(('A','TICKS auth="%s"' % arg))
self._header.append(('K','text/html-fragment'))
self._header.append(('K','multiparty'))
self._header.append(('K','nudge'))
self._header.append(('K','share-background'))
self._header.append(('K','fetion-show'))
if cmd == "InviteBuddy":
self.init('S')
self._header.append(('N',cmd))
body = '<args><contacts><contact uri="%s" /></contacts></args>'%arg
if cmd == "PGGetGroupList":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><group-list version="1" attributes="name;identity" /></args>'
if cmd == "SSSetScheduleSms":
self.init('S')
self._header.insert(3,('N',cmd))
body = '<args><schedule-sms send-time="%s"><message>%s</message><receivers><receiver uri="%s" /></receivers></schedule-sms></args>' % (extra[0],arg,extra[1])
if cmd == "GetOfflineMessages":
self.init('S')
self._header.insert(3,('N',cmd))
if cmd == "INFO":
self.init('S')
self._header.insert(3,('N',arg))
if arg == "GetPersonalInfo":
body = '<args><personal attributes="all" /><services version="" attributes="all" /><config attributes="all" /><quota attributes="all" /></args>'
elif arg == "GetContactList":
body = '<args><contacts><buddy-lists /><buddies attributes="all" /><mobile-buddies attributes="all" /><chat-friends /><blacklist /><allow-list /></contacts></args>'
elif arg == "GetContactsInfo":
body = '<args><contacts attributes="all">'
for i in extra[0]:
body += '<contact uri="%s" />' % i
body += '</contacts></args>'
elif arg == "AddBuddy":
tag = "sip"
if len(extra[0]) == 11:
tag = "tel"
body = '<args><contacts><buddies><buddy uri="%s:%s" buddy-lists="" desc="%s" addbuddy-phrase-id="0" /></buddies></contacts></args>' % (tag,extra[0],extra[1])
elif arg == "AddMobileBuddy":
body = '<args><contacts><mobile-buddies><mobile-buddy uri="tel:%s" buddy-lists="1" desc="%s" invite="0" /></mobile-buddies></contacts></args>' % (extra[0],extra[1])
elif arg == "DeleteBuddy":
body = '<args><contacts><buddies><buddy uri="%s" /></buddies></contacts></args>' % extra[0]
#general SIPC info
if len(body) != 0:
self._header.append(('L',len(body)))
for k in self._header:
self._content = self._content + k[0] + ": " + str(k[1]) + "\r\n"
self._content+="\r\n"
self._content+= body
if self.login_type == "HTTP":
#IN TCP CONNECTION "SIPP" SHOULD NOT BEEN SEND
self._content+= FetionSIPP
return self._content
def ack(self):
"""ack message from server"""
content = self._content
d_print(('content',),locals())
self.__tcp_send(content)
def send(self):
content = self._content
response = ''
if self._lock:
d_print("acquire lock ")
self._lock.acquire()
d_print("acquire lock ok ")
d_print(('content',),locals())
if self.login_type == "HTTP":
#First time t SHOULD SET AS 'i'
#Otherwise 405 code get
if self.__seq == 1:
t = 'i'
else:
t = 's'
url = self._http_tunnel+"?t=%s&i=%s" % (t,self.__seq)
ret = http_send(url,content,self.__exheaders)
if not ret:
raise PyFetionSocketError(405,'http stoped')
response = ret.read()
self.__seq+=1
response = self.__sendSIPP()
i = 0
while response == FetionSIPP and i < 5:
response = self.__sendSIPP()
i += 1
ret = self.__split(response)
num = len(ret)
d_print(('num',),locals())
for rs in ret:
code = self.get_code(rs)
d_print(('rs',),locals())
try:
int(code)
d_print(('code',),locals())
response = rs
except exceptions.ValueError:
self.queue.put(rs)
continue
else:
self.__tcp_send(content)
while response is '':
try:
ret = self.__tcp_recv()
except socket.error,e:
raise PyFetionSocketError(e)
num = len(ret)
d_print(('num',),locals())
for rs in ret:
code = self.get_code(rs)
d_print(('rs',),locals())
try:
int(code)
d_print(('code',),locals())
response = rs
except exceptions.ValueError:
self.queue.put(rs)
continue
if self._lock:
self._lock.release()
d_print("release lock")
return response
def __sendSIPP(self):
body = FetionSIPP
url = self._http_tunnel+"?t=s&i=%s" % self.__seq
ret = http_send(url,body,self.__exheaders)
if not ret:
raise PyFetionSocketError(405,'Http error')
response = ret.read()
d_print(('response',),locals())
self.__seq+=1
return response
def __tcp_init(self):
try:
self.__sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
s = None
raise PyFetionSocketError(e)
(host,port) = tuple(self._sipc_proxy.split(":"))
port = int(port)
try:
self.__sock.connect((host,port))
except socket.error,e:
self.__sock.close()
raise PyFetionSocketError(e)
def close(self):
self.__sock.close()
def __tcp_send(self,msg):
try:
self.__sock.send(msg)
except socket.error,e:
self.__sock.close()
raise PyFetionSocketError(e)
def __tcp_recv(self):
"""read bs bytes first,if there's still more data, read left data.
get length from header :
L: 1022
"""
total_data = []
bs = 1024
try:
data = self.__sock.recv(bs)
total_data.append(data)
while True and data:
if not re.search("L: (\d+)",data) and not data[-4:] == '\r\n\r\n':
data = self.__sock.recv(bs)
total_data.append(data)
elif not re.search("L: (\d+)",data) and data[-4:] == '\r\n\r\n':
return total_data
else:
break
while re.search("L: (\d+)",data):
n = len(data)
L = int(re.findall("L: (\d+)",data)[-1])
p = data.rfind('\r\n\r\n')
abc = data
data = ''
p1 = data.rfind(str(L))
if p < p1:
d_print("rn before L")
left = L + n - (p1 + len(str(L))) + 4
else:
left = L - (n - p -4)
if left == L:
d_print("It happened!")
break
d_print(('n','L','p','left',),locals())
#if more bytes then last L
#come across another command: BN etc.
#read until another L come
if left < 0:
d_print(('abc',),locals())
d = ''
left = 0
while True:
d = self.__sock.recv(bs)
data += d
if re.search("L: (\d+)",d):
break
d_print("read left bytes")
d_print(('data',),locals())
total_data.append(data)
#read left bytes in last L
while left:
data = self.__sock.recv(left)
n = len(data)
left = left - n
if not data:
break
total_data.append(data)
except socket.error,e:
#self.__sock.close()
raise PyFetionSocketError(e)
return self.__split(''.join(total_data))
#return ''.join(total_data)
def __split(self,data):
c = []
d = []
#remove string "SIPP"
if self.login_type == "HTTP":
data = data[:-4]
L = re.findall("L: (\d+)",data)
L = [int(i) for i in L]
d_print(('data',),locals())
b = data.split('\r\n\r\n')
for i in range(len(b)):
if b[i].startswith(self.ver) and "L:" not in b[i]:
d.append(b[i]+'\r\n\r\n')
del b[i]
break
c.append(b[0])
d_print(('L','b',),locals())
for i in range(0,len(L)):
c.append(b[i+1][:L[i]])
c.append(b[i+1][L[i]:])
d_print(('c',),locals())
#remove last empty string
if c[-1] == '':
c.pop()
c.reverse()
while c:
s = c.pop()
s += '\r\n\r\n'
if c:
s += c.pop()
d.append(s)
d_print(('d',),locals())
return d
def __get_salt(self):
return self.__hash_passwd()[:8]
def __get_cnonce(self):
return md5(str(uuid1())).hexdigest().upper()
def __get_response_md5(self,nonce,cnonce):
#nonce = "3D8348924962579418512B8B3966294E"
#cnonce= "9E169DCA9CBD85F1D1A89A893E00917E"
key = md5("%s:%s:%s" % (self.sid,self._domain,self.passwd)).digest()
h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper()
h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper()
response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper()
#d_print(('nonce','cnonce','key','h1','h2','response'),locals())
return response
def __get_response_sha1(self,nonce,cnonce):
#nonce = "3D8348924962579418512B8B3966294E"
#cnonce= "9E169DCA9CBD85F1D1A89A893E00917E"
hash_passwd = self.__hash_passwd()
hash_passwd_str = binascii.unhexlify(hash_passwd[8:])
key = sha1("%s:%s:%s" % (self.sid,self._domain,hash_passwd_str)).digest()
h1 = md5("%s:%s:%s" % (key,nonce,cnonce)).hexdigest().upper()
h2 = md5("REGISTER:%s" % self.sid).hexdigest().upper()
response = md5("%s:%s:%s" % (h1,nonce,h2)).hexdigest().upper()
return response
def __hash_passwd(self):
#salt = '%s%s%s%s' % (chr(0x77), chr(0x7A), chr(0x6D), chr(0x03))
salt = 'wzm\x03'
src = salt+sha1(self.passwd).digest()
return "777A6D03"+sha1(src).hexdigest().upper()
def http_send(url,body='',exheaders='',login=False):
global proxy_info
conn = ''
headers = {
'User-Agent':'IIC2.0/PC 3.2.0540',
}
headers.update(exheaders)
if proxy_info:
proxy_support = urllib2.ProxyHandler(\
{"http":"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support)
else:
opener = urllib2.build_opener()
urllib2.install_opener(opener)
request = urllib2.Request(url,headers=headers,data=body)
#add retry for GAE.
#PyFetion will get 405 code sometimes, we should re-send the request.
retry = 5
while retry:
try:
conn = urllib2.urlopen(request)
except urllib2.URLError, e:
if hasattr(e,'code'):
code = e.code
msg = e.read()
else:
code = e.reason.errno
msg = e.reason.strerror
d_print(('code','msg'),locals())
if code == 401 or code == 400:
if login:
raise PyFetionAuthError(code,msg)
if code == 404 or code == 500:
raise PyFetionSupportError(code,msg)
if code == 405:
retry = retry - 1
continue
raise PyFetionSocketError(code,msg)
break
return conn
class on_cmd_I(Thread,SIPC):
#if there is invitation SIP method [I]
def __init__(self,fetion,response,args):
self.fetion = fetion
self.response = response
self.args = args
self.begin = time.time()
self.Q = 4
self.I = 4
self.from_uri = ''
Thread.__init__(self)
def run(self):
running = True
try:
self.from_uri = re.findall('F: (.*)',self.response)[0]
credential = re.findall('credential="(.+?)"',self.response)[0]
sipc_proxy = re.findall('address="(.+?);',self.response)[0]
except:
d_print("find tag error")
return
self.from_uri = self.from_uri.rstrip()
self.fetion._ack('I',self.from_uri)
self.args[5] = sipc_proxy
#no lock
self.args[7] = None
#SIPC(self.args)
SIPC.__init__(self,self.args)
self.get("StartChat",credential)
response = self.send()
self.deal_msg(response)
while running:
if not self.queue.empty():
response = self.queue.get()
else:
response = self.recv()
if len(response) == 0:
d_print("User Left converstion")
self.fetion.session.pop(self.from_uri)
return
self.deal_msg(response)
#self._bye()
def deal_msg(self,response):
try:
Q = re.findall('Q: (-?\d+) M',response)
I = re.findall('I: (-?\d+)',response)
except:
d_print("NO Q")
return False
for i in range(len(Q)):
self.Q = Q[i]
self.fetion.queue.put(response)
self._ack('M')
self._ack('IN')
return True
def _ack(self,cmd):
"""ack message from uri"""
self.get("ACK",cmd,self.from_uri,self.Q,self.I)
self.response = self.ack()
self.deal_msg(self.response)
def _send_msg(self,msg):
msg = msg.replace('<','<')
self.get("SendMsg",'',msg)
self.send()
def _bye(self):
"""say bye to this session"""
self.get("BYE",'')
self.send()
class PyFetion(SIPC):
__log = ''
__sipc_url = ''
_ssic = ''
_lock = RLock()
_sipc_proxy = ''
_domain = ''
_http_tunnel = ''
mobile_no = ''
passwd = ''
queue = Queue()
sid = ''
login_type = ''
receving = False
presence = ''
debug = False
contactlist = {}
grouplist = {}
session = {}
def __init__(self,mobile_no,passwd,login_type="TCP",debug=False):
self.mobile_no = mobile_no
self.passwd = passwd
self.login_type = login_type
if debug == True:
logging.basicConfig(level=logging.DEBUG,format='%(message)s')
self.__log = logging
elif debug == "FILE":
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(thread)d %(message)s',
filename='./PyFetion.log',
filemode='w')
self.__log = logging
global d_print
#replace global function with self method
d_print = self.__print
self.__sipc_url = "https://uid.fetion.com.cn/ssiportal/SSIAppSignIn.aspx"
self._sipc_proxy = "221.176.31.45:8080"
self._http_tunnel= "http://221.176.31.45/ht/sd.aspx"
#uncomment this line for getting configuration from server everytime
#It's very slow sometimes, so default use fixed configuration
#self.__set_system_config()
def login(self,presence=FetionOnline):
if not self.__get_uri():
return False
self.presence = presence
try:
self.__register(self._ssic,self._domain)
except PyFetionRegisterError,e:
d_print("Register Failed!")
return False
#self.get_personal_info()
if not self.get_contactlist():
d_print("get contactlist error")
return False
self.get("compactlist",self.__uri,self.contactlist.keys())
response = self.send()
code = self.get_code(response)
if code != 200:
return False
#self.get("PGGetGroupList",self.__uri)
#response = self.send()
self.get_offline_msg()
self.receving = True
return True
def logout(self):
self.get("DEAD",'')
self.send()
self.receving = False
def start_chat(self,who):
self.get("StartChat",'')
response = self.send()
try:
credential = re.findall('credential="(.+?)"',response)[0]
sipc_proxy = re.findall('address="(.+?);',response)[0]
except:
d_print("find tag error")
return False
args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,sipc_proxy,self.presence,None]
_SIPC = SIPC(args)
_SIPC.get("StartChat",credential)
response = _SIPC.send()
_SIPC.get("InviteBuddy",who)
response = _SIPC.send()
code = _SIPC.get_code(response)
if code != 200:
return False
response = _SIPC.recv()
try:
type = re.findall('<event type="(.+?)"',response)[0]
except :
return False
if type == "UserEntered":
return FetionHidden
elif type == "UserFailed":
return FetionOnline
def set_presence(self,presence):
"""set status of fetion"""
if self.presence == presence:
return True
self.get("SetPresence",presence)
response = self.send()
code = self.get_code(response)
if code == 200:
self.presence = presence
d_print("set presence ok.")
return True
return False
#self.get("PGSetPresence",presence)
#response = self.send()
def get_offline_msg(self):
"""get offline message from server"""
self.get("GetOfflineMessages",'')
response = self.send()
return response
def add(self,who):
"""add friend who should be mobile number or fetion number"""
my_info = self.get_info()
try:
#nick_name = re.findall('nickname="(.*?)" ',my_info)[0]
nick_name = my_info[0]
except IndexError:
nick_name = " "
#code = self._add(who,nick_name,"AddMobileBuddy")
code = self._add(who,nick_name)
if code == 522:
code = self._add(who,nick_name,"AddMobileBuddy")
if code == 404 or code == 400 :
d_print("Not Found")
return False
if code == 521:
d_print("Aleady added.")
return True
if code == 200:
return True
return False
def delete(self,who):
if who.isdigit() and len(who) == 11:
who = "tel:" + who
else:
who = self.get_uri(who)
if not who:
return False
self.get("INFO","DeleteBuddy",who)
response = self.send()
code = self.get_code(response)
if code == 404 or code == 400 :
d_print("Not Found")
return False
if code == 200:
return True
return False
def _add(self,who,nick_name,type="AddBuddy"):
self.get("INFO",type,who,nick_name)
response = self.send()
code = self.get_code(response)
return code
def get_personal_info(self):
"""get detail information of me"""
self.get("INFO","GetPersonalInfo")
response = self.send()
nickname = re.findall('nickname="(.+?)"',response)[0]
impresa = re.findall('impresa="(.+?)"',response)[0]
#mobile = re.findall('mobile-no="(^1[35]\d{9})"',response)[0]
mobile = re.findall('mobile-no="(.+?)"',response)[0]
name = re.findall(' name="(.+?)"',response)[0]
gender = re.findall('gender="([01])"',response)[0]
fetion_number = re.findall('user-id="(\d{9})"',response)[0]
#email = re.findall('personal-email="(.+?)"',response)[0]
response = []
response.append(nickname)
response.append(impresa)
response.append(mobile)
response.append(name)
response.append(fetion_number)
#response.append(gender)
#response.append(email)
return response
def get_info(self,who=None):
"""get contact info.
who should be uri. string or list
"""
alluri = []
if who == None:
return self.get_personal_info()
if type(who) is not list:
alluri.append(who)
else:
alluri = who
self.get("INFO","GetContactsInfo",alluri)
response = self.send()
return response
def set_info(self,info):
contacts = re.findall('<contact (.+?)</contact>',info)
contacts += re.findall('<presence (.+?)</presence>',info)
for contact in contacts:
#print contacts
uri = ''
nickname = ''
mobile_no = ''
try:
(uri,mobile_no,nickname) = re.findall('uri="(.+?)".+?mobile-no="(.*?)".+?nickname="(.*?)"',contact)[0]
except:
try:
(uri,nickname) = re.findall('uri="(.+?)".+?nickname="(.*?)"',contact)[0]
except:
continue
#print uri,nickname,mobile_no
if uri == self.__uri:
continue
if self.contactlist[uri][0] == '':
self.contactlist[uri][0] = nickname
if self.contactlist[uri][1] == '':
self.contactlist[uri][1] = mobile_no
def get_contactlist(self):
"""get contact list
contactlist is a dict:
{uri:[name,mobile-no,status,type,group-id]}
"""
buddy_list = ''
allow_list = ''
chat_friends = ''
need_info = []
self.get("INFO","GetContactList")
response = self.send()
code = self.get_code(response)
if code != 200:
return False
try:
d = re.findall('<buddy-lists>(.*?)<allow-list>',response)[0]
#No buddy here
except:
return True
try:
buddy_list = re.findall('uri="(.+?)" user-id="\d+" local-name="(.*?)" buddy-lists="(.*?)"',d)
self.grouplist = re.findall('id="(\d+)" name="(.*?)"',d)
except:
return False
try:
d = re.findall('<chat-friends>(.*?)</chat-friends>',d)[0]
chat_friends = re.findall('uri="(.+?)" user-id="\d+"',d)
except:
pass
for uri in chat_friends:
if uri not in self.contactlist:
l = ['']*5
need_info.append(uri)
self.contactlist[uri] = l
self.contactlist[uri][0] = ''
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][3] = 'A'
#buddy_list [(uri,local_name),...]
for p in buddy_list:
l = ['']*5
#set uri
self.contactlist[p[0]] = l
#set local-name
self.contactlist[p[0]][0] = p[1]
#set default status
self.contactlist[p[0]][2] = FetionHidden
#self.contactlist[p[0]][2] = FetionOffline
#set group id here!
self.contactlist[p[0]][4] = p[2]
if p[0].startswith("tel"):
self.contactlist[p[0]][3] = 'T'
self.contactlist[p[0]][2] = FetionHidden
#set mobile_no
self.contactlist[p[0]][1] = p[0][4:]
#if no local-name use mobile-no as name
if p[1] == '':
self.contactlist[p[0]][0] = self.contactlist[p[0]][1]
else:
self.contactlist[p[0]][3] = 'B'
if self.contactlist[p[0]][0] == '':
need_info.append(p[0])
"""
try:
s = re.findall('<allow-list>(.+?)</allow-list>',response)[0]
allow_list = re.findall('uri="(.+?)"',s)
except:
pass
#allow_list [uri,...]
for uri in allow_list:
if uri not in self.contactlist:
l = ['']*4
need_info.append(uri)
self.contactlist[uri] = l
self.contactlist[uri][0] = ''
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][3] = 'A'
"""
ret = self.get_info(need_info)
self.set_info(ret)
return True
def get_uri(self,who):
"""get uri from fetion number"""
if who in self.__uri:
return self.__uri
if who.startswith("sip"):
return who
for uri in self.contactlist:
if who in uri:
return uri
return None
def send_msg(self,msg,to=None,flag="CatMsg"):
"""more info at send_sms function.
if someone's fetion is offline, msg will send to phone,
the same as send_sms.
"""
if not to:
to = self.__uri
#Fetion now can use mobile number(09.02.23)
#like tel: 13888888888
#but not in sending to PC
elif flag != "CatMsg" and to.startswith("tel:"):
pass
elif flag == "CatMsg" and to.startswith("tel:"):
return False
elif flag != "CatMsg" and len(to) == 11 and to.isdigit():
to = "tel:"+to
else:
to = self.get_uri(to)
if not to:
return False
msg = msg.replace('<','<')
self.get(flag,to,msg)
try:
response = self.send()
except PyFetionSocketError,e:
d_print(('e',),locals())
return False
code = self.get_code(response)
if code == 280:
d_print("Send sms OK!")
elif code == 200:
d_print("Send msg OK!")
else:
d_print(('code',),locals())
return False
return True
def send_sms(self,msg,to=None,long=True):
"""send sms to someone, if to is None, send self.
if long is True, send long sms.(Your phone should support.)
to can be mobile number or fetion number
"""
if long:
return self.send_msg(msg,to,"SendCatSMS")
else:
return self.send_msg(msg,to,"SendSMS")
def send_schedule_sms(self,msg,time,to=None):
if not to:
to = self.__uri
elif len(to) == 11 and to.isdigit():
to = "tel:"+to
else:
to = self.get_uri(to)
if not to:
return False
msg = msg.replace('<','<')
self.get("SSSetScheduleSms",msg,time,to)
response = self.send()
code = self.get_code(response)
if code == 486:
d_print("Busy Here")
return None
if code == 200:
id = re.search('id="(\d+)"',response).group(1)
d_print(('id',),locals(),"schedule_sms id")
return id
def alive(self):
"""send keepalive message"""
self.get("ALIVE",'')
response = self.send()
code = self.get_code(response)
if code == 200:
d_print("keepalive message send ok.")
return True
return False
def receive(self):
"""response from server"""
threads = []
while self.receving:
if not self.queue.empty():
response = self.queue.get()
else:
try:
response = self.recv(5)
except PyFetionSocketError,e:
yield ["NetworkError",e.msg]
continue
if response =="TimeOut":
continue
elif len(response) == 0:
d_print("logout")
return
elif response.startswith("BN"):
try:
type = re.findall('<event type="(.+?)"',response)[0]
except IndexError:
d_print("Didn't find type")
d_print(('response',),locals())
if type == "ServiceResult":
self.set_info(response)
if type == "deregistered" or type=="disconnect":
self.receving = False
yield [type]
if type == "PresenceChanged":
self.set_info(response)
ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)".+?type="sms">(\d+)\.',response)
if not ret:
ret = re.findall('<presence uri="(.+?)">.+?value="(.+?)"',response)
#remove self uri
event = [i for i in ret if i[0] != self.__uri]
event = list(set(event))
for e in event:
if len(e) == 3 and e[2] == FetionOffline:
self.contactlist[e[0]][2] = e[2]
else:
self.contactlist[e[0]][2] = e[1]
yield [type,event]
if type == "UpdateBuddy" or type == "UpdateMobileBuddy":
uri = re.findall('uri="(.+?)"',response)[0]
l = ['']*4
self.contactlist[uri] = l
if type == "UpdateBuddy":
ret = self.get_info(uri)
self.set_info(ret)
else:
self.contactlist[uri][3] = 'T'
self.contactlist[uri][2] = FetionHidden
self.contactlist[uri][1] = uri[4:]
self.contactlist[uri][0] = uri[4:]
elif response.startswith("M"):
try:
from_uri = re.findall('F: (.*)',response)[0].strip()
msg = re.findall('\r\n\r\n(.*)',response,re.S)[0]
except:
d_print("Message without content")
continue
#if from PC remove <Font>
try:
msg = re.findall('<Font .+?>(.+?)</Font>',msg,re.S)[0]
except:
pass
#from phone or PC
try:
XI = re.findall('XI: (.*)',response)[0]
type = "PC"
except:
type = "PHONE"
#ack this message
try:
Q = re.findall('Q: (-?\d+) M',response)[0]
I = re.findall('I: (-?\d+)',response)[0]
self._ack('M',from_uri,Q,I)
except:
pass
yield ["Message",from_uri,msg,type]
elif response.startswith("I"):
try:
from_uri = re.findall('F: (.*)',response)[0].rstrip()
except:
pass
args = [self.sid,self._domain,self.login_type,self._http_tunnel,self._ssic,self._sipc_proxy,self.presence,None]
t = on_cmd_I(self,response,args)
t.setDaemon(True)
t.start()
self.session[from_uri] = t
#print self.session
def _ack(self,cmd,from_uri,Q=0,I=0):
"""ack message """
self.get("ACK",cmd,from_uri,Q,I)
self.ack()
def __register(self,ssic,domain):
SIPC.__init__(self)
response = ''
for step in range(1,3):
self.get("REG",step,response)
response = self.send()
code = self.get_code(response)
if code == 200:
d_print("register successful.")
else:
raise PyFetionRegisterError(code,response)
def __get_system_config(self):
global FetionConfigURL
global FetionConfigXML
url = FetionConfigURL
body = FetionConfigXML % self.mobile_no
d_print(('url','body'),locals())
config_data = http_send(url,body).read()
sipc_url = re.search("<ssi-app-sign-in>(.*)</ssi-app-sign-in>",config_data).group(1)
sipc_proxy = re.search("<sipc-proxy>(.*)</sipc-proxy>",config_data).group(1)
http_tunnel = re.search("<http-tunnel>(.*)</http-tunnel>",config_data).group(1)
d_print(('sipc_url','sipc_proxy','http_tunnel'),locals())
self.__sipc_url = sipc_url
self._sipc_proxy = sipc_proxy
self._http_tunnel= http_tunnel
def __get_uri(self):
url = self.__sipc_url+"?mobileno="+self.mobile_no+"&pwd="+urllib.quote(self.passwd)
d_print(('url',),locals())
ret = http_send(url,login=True)
header = str(ret.info())
body = ret.read()
try:
ssic = re.search("ssic=(.*);",header).group(1)
sid = re.search("sip:(.*)@",body).group(1)
uri = re.search('uri="(.*)" mobile-no',body).group(1)
status = re.search('user-status="(\d+)"',body).group(1)
except:
return False
domain = "fetion.com.cn"
d_print(('ssic','sid','uri','status','domain'),locals(),"Get SID OK")
self.sid = sid
self.__uri = uri
self._ssic = ssic
self._domain = domain
return True
def __print(self,vars=(),namespace=[],msg=''):
"""if only sigle variable ,arg should like this ('var',)"""
if not self.__log:
return
if vars and not namespace and not msg:
msg = vars
if vars and namespace:
for var in vars:
if var in namespace:
self.__log.debug("%s={%s}" % (var,str(namespace[var])))
if msg:
self.__log.debug("%s" % msg)
| Python |
#! /usr/bin/python -u
#-*- coding: utf-8 -*-
#
# After connecting to a jabber server it will echo messages, and accept any
# presence subscriptions. This bot has basic Disco support (implemented in
# pyxmpp.jabber.client.Client class) and jabber:iq:vesion.
import sys,os,time,cmd,re
from threading import Thread
import logging
import locale
import codecs
has_pynotify=0
try:
import pynotify
has_pynotify=1
except:
pass
import smtplib,urllib,libxml2
from pyxmpp import streamtls
from pyxmpp.all import JID, Iq, Presence, Message, StreamError
from pyxmpp.jabber.client import JabberClient
from pyxmpp.interface import implements
from pyxmpp.interfaces import *
my_id=''
fromadd=''
passwd=''
toadd=''
userhome = os.path.expanduser('~')
config_folder = os.path.join(userhome,'.pyrenren')
if not os.path.isdir(config_folder):
os.mkdir(config_folder)
chat_history= os.path.join(config_folder,'chat_history.txt')
renren_log= os.path.join(config_folder,'renren.log')
data_file = os.path.join(config_folder,'renren.dat')
img_folder = os.path.join(config_folder,"img")
renren_icon = os.path.join(img_folder,'renren.jpg')
class EchoHandler(object):
"""提供一个机器人的回答功能
对于presence和message XML节的处理器的实现
"""
implements(IMessageHandlersProvider, IPresenceHandlersProvider)
def __init__(self, client):
"""Just remember who created this."""
self.client = client
def get_message_handlers(self):
"""Return list of (message_type, message_handler) tuples.
The handlers returned will be called when matching message is received
in a client session."""
return [("normal", self.message)]
def get_presence_handlers(self):
"""Return list of (presence_type, presence_handler) tuples.
The handlers returned will be called when matching presence stanza is
received in a client session."""
return [
(None, self.presence),
('unavailable', self.presence),
('subscribe', self.presence_control),
('subscribed', self.presence_control),
('unsubscribe', self.presence_control),
('unsubscribed', self.presence_control)]
def get_content(self,tag_name,xmlstr):
reg = tag_name + ">(.+?)</.+?" + tag_name + ">"
raw_content = re.findall(reg,xmlstr)
if not len(raw_content):
return ""
xmldoc = "<?xml version='1.0' encoding='utf-8'?><xmpp>"+raw_content[0]+"</xmpp>"
xml = libxml2.parseDoc(xmldoc)
cont = re.findall("<(.+?)>",xml.content)
if len(cont):
xmldoc = "<?xml version='1.0' encoding='utf-8'?><xmpp>"+xml.content+"</xmpp>"
xml = libxml2.parseDoc(xmldoc)
return xml.content
def color(self,str):
'''涂上蓝色'''
return "\033[34m" + str + "\033[0m"
def message(self, stanza):
"""Message handler for the component.
Echoes the message back if its type is not 'error' or
'headline', also sets own presence status to the message body. Please
note that all message types but 'error' will be passed to the handler
for 'normal' message unless some dedicated handler process them.
:returns: `True` to indicate, that the stanza should not be processed
any further."""
xml = str(stanza.get_node())
if stanza.get_type() == "chat":
renren_id = stanza.get_from().as_utf8().split("@")[0]
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
body = stanza.get_body()
print buddy,"说:",self.color(body)
self.renrennotify(renren_id,body)
self.send_mail(buddy+"说:"+body)
return
renren_id = re.findall("actor>(.+?)</.+?actor>",xml)
if len(renren_id):
renren_id = renren_id[0]
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
else:
buddy = ""
else:
buddy = "你"
subject = stanza.get_subject()
type = re.findall("stype>(.+?)</.+?stype>",xml)
if not len(type):
return
stype = type[0]
body = ""
if stype =='-65549':
print "reply"
#elif stype =='':
#elif stype =='-4':
elif stype == '-33':
'''上传照片?'''
title = self.get_content("title",xml)
body = "上传了1张照片至" + title
msg = "上传了1张照片至" + self.color(title)
print buddy,msg
print buddy,"回复了你的分享"
elif stype == '-34':
print buddy,"回复了你的分享"
elif stype == '-4':
'''程序截图回复了我'''
title = self.get_content("title",xml)
body = "在 "+title+"回复你"
msg = "在 "+self.color(title)+"回复你"
print buddy,msg
elif stype == "102":
'''分享日志'''
fID = re.findall("fID>(.+?)</.+?fID>",xml)[0]
uName = self.get_content("uName",xml)
blog_title = self.get_content("title",xml)
blog_digest = self.get_content("digest",xml)
college = self.get_content("net",xml)
blog_url = re.findall("url>(.+?)</.+?url>",xml)[0]
body = "分享来自 "+college + " 的 "+uName+" 的日志 "+blog_title
msg = "分享来自 " + self.color(college) + " 的"+self.color(uName)+" 的日志 "+self.color(blog_title)+"\n"+blog_digest
print buddy,msg
elif stype=='103':
'''分享照片'''
uName = self.get_content("uName",xml)
aName = self.get_content("aName",xml)
photo_title = self.get_content("title",xml)
body = "分享 "+uName+" 的照片 "+aName+""
msg = "分享 "+self.color(uName)+" 的照片 "+ self.color(aName) + "\n" + photo_title
print buddy,msg
elif stype == "104":
'''分享相册'''
uName = self.get_content("uName",xml)
title = self.get_content("title",xml)
count = self.get_content("count",xml)
body = "分享 "+uName+" 的相册 " + title+"\n共 "+count+" 张照片"
msg = "分享 "+self.color(uName)+" 的相册 " + self.color(title)+"\n共 "+self.color(count) + " 张照片"
print buddy,msg
elif stype == "107":
''''''
body = "正在"
elif stype == "110":
'''分享视频'''
title = self.get_content("title",xml)
body = "分享视频 " + title
msg = "分享视频 "+ self.color(title)
print buddy,msg
elif stype == "400":
'''拜年'''
print buddy,"正在给自己的好友拜年呢"
elif stype == "502":
'''新签名'''
fName = self.get_content("fName",xml)
title = self.get_content("title",xml)
body = "更新了签名:"+title
msg = "更新了签名:"+self.color(title)
print buddy,msg
self.client.buddies[renren_id][3] = title
elif stype == "507":
'''好友留言'''
un = self.get_content("un",xml)
con = self.get_content("con",xml)
rt = self.get_content("rt",xml)
body = un +" "+ rt + " " +con
msg = self.color(un)+" "+ rt + " " + self.color(con)
print buddy + ":"+ self.client.buddies[renren_id][3]
print msg
elif stype == "601":
'''发表日志'''
blog_title = self.get_content("title",xml)
blog_brief = self.get_content("brief",xml)
body = "发表日志 " + blog_title
msg = "发表日志 " + self.color(blog_title)+"\n"+blog_brief
print buddy,msg
elif stype == '602':
'''冷笑话回复了粉丝'''
print ""
elif stype == '701':
'''上传照片'''
aName = self.get_content("aName",xml)
aName = self.get_content("aName",xml)
body = "上传了1张照片至" + aName
msg = "上传了1张照片至" + self.color(aName)
print buddy,msg
elif stype == '704':
'''好友的好友回复了好友?貌似可以删除,因为有507类型了'''
fName = self.get_content("fName",xml)
body = "的好友 "+fName+" 回复了 "+buddy
msg = "的好友 "+self.color(fName)+" 回复了 "+buddy
elif stype=='705':
body = ""
msg = ""
print buddy,msg
elif stype=='708':
'''照片有新回复'''
un = self.get_content("un",xml)
desc = self.get_content("desc",xml)
body = "TA的好友 " + un + "在相册 " + desc + "中留言了"
msg = "的好友 " + self.color(un) + "在相册 " + self.color(desc) + "中留言了"
elif stype=='799':
'''上传照片'''
title = self.get_content("title",xml)
body = "上传了照片至" + title
msg = "上传了照片至" + self.color(title)
print buddy,msg
elif stype == "801":
'''收到礼物'''
body = "收到了"
print buddy,body
elif stype == "802":
'''收到礼物'''
title = self.get_content("title",xml)
uName = self.get_content("uName",xml)
body = "收到"+uName+"送的礼物"+title
msg = "收到"+self.color(uName)+"送的礼物"+self.color(title)
print buddy,msg
elif stype == "2002":
'''加冷笑话为好友'''
title = self.get_content("title",xml)
uName = self.get_content("uName",xml)
brief = self.get_content("brief",xml)
body = "在人人成为了"+title+"的好友"
msg = "在人人成为了"+self.color(title)+"的好友"
print buddy,msg
elif stype == '2003':
'''分享日志'''
uName = self.get_content("uName",xml)
title = self.get_content("title",xml)
digest = self.get_content("digest",xml)
body = "分享"+uName+"的日志"+title
msg = "分享"+self.color(uName)+"的日志"+self.color(title)
print buddy,msg
print digest
elif stype == '2401':
'''使用应用'''
title = self.get_content("title",xml)
body = "在使用应用 "+ title
msg = "在使用应用 "+ self.color(title)
desc = self.get_content("desc",xml)
print buddy,msg
print desc
elif stype == "8190":
title = self.get_content("title",xml)
body = "分享游戏 " + title
msg = "分享游戏 " + self.color(title)
print buddy,msg
elif stype == "45106":
body = "游戏邀请"
print buddy,body
elif stype == "2011":
''''''
blog_title = self.get_content("title",xml)
blog_brief = self.get_content("brief",xml)
buddy = self.get_content("fName",xml)
body = "发表日志 " + blog_title
msg = "发表日志 " + self.color(blog_title)+"\n"+blog_brief
print buddy,msg
elif stype == "2016":
'''生活大爆炸'''
comm = self.get_content("comm",xml)
buddy = self.get_content("fName",xml)
body = comm
msg = self.color(comm)
print buddy,msg
elif stype == '26352':
app_body = self.get_content("body",xml)
body = "邀请你参加" + self.color(app_body)
msg = "邀请你参加" + app_body
print msg
else:
body = "不知道想干嘛,先存着再说"
print buddy,"\033[31m不知道想干嘛,先存着再说\033[0m"
file_path = os.path.join(config_folder,type[0]+".xml")
file = open(file_path,"w")
temp = "<?xml version='1.0'?>" + xml
file.write(temp+"\n")
file.close()
os.system("xmllint --format "+file_path)
file = open(file_path,"a")
temp = stanza.get_node().content+"\n"
file.write(temp)
file.close()
print ""
if type[0] != "502" or type[0] != "507" or type!='601':
file_path = os.path.join(config_folder,"_new.xml")
file = open(file_path,"w")
temp = "<?xml version='1.0'?>" + xml
file.write(temp+"\n")
file.close()
#os.system("xmllint --format "+file_path)
file_path2 = os.path.join(config_folder,"new.xml")
os.system("xmllint --format "+file_path+">"+file_path2)
print ""
temp = stanza.get_node().content+"\n"
#print temp
file_path = os.path.join(config_folder,"renren.xml")
file_path2 = os.path.join(config_folder,"new.xml")
file = open(file_path,"a")
file2 = open(file_path2,"r")
for line in file2.readlines():
file.write(line)
file.write(temp)
file2.close()
file.close()
#os.system("gvim "+file_path)
ISOTIMEFORMAT=" %H:%M "
body = time.strftime(ISOTIMEFORMAT) + body
self.save_file(buddy+body)
if has_pynotify:
self.renrennotify(renren_id,body)
if subject =="reply":
if fromadd!='':
self.send_mail("You have one new reply in http://www.renren.com/Home.do")
if subject:
subject = u'Re: ' + subject
body = stanza.get_body()
m = Message(
to_jid=stanza.get_from(),
from_jid=stanza.get_to(),
stanza_type=stanza.get_type(),
subject=subject,
body=body)
if body:
p = Presence(status=u'新签名:' + body)
return [m, p]
return m
def send_mail(self,message):
print "Send mail from ",fromadd,"to ",toadd
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(fromadd,passwd)
server.sendmail(fromadd,toadd,"From: renren <"+fromadd+">\r\nTo: "+toadd+"\r\nSubject: renren\r\n\r\n"+message)
server.quit()
def presence(self, stanza):
"""Handle 'available' (without 'type') and 'unavailable' <presence/ >."""
xml = str(stanza.get_node())
renren_id = stanza.get_from().as_utf8().split("@")[0]
if self.client.buddies.has_key(renren_id):
item = self.client.buddies[renren_id]
groups = item[2]
group = ",".join(groups)
if len(groups)>0:
group = group + ":"
else:
self.client.buddies[renren_id] = ['']*5
self.client.buddies[renren_id][0] = renren_id
buddy = self.client.buddies[renren_id][0]
picture = re.findall("EXTVAL>(.+?)</.+?EXTVAL>",xml)
file_path = ""
if len(picture):
picture = picture[0]
file_path = os.path.join(img_folder,renren_id+"_"+buddy+".jpg")
urllib.urlretrieve(picture,file_path)
else:
file_path = renren_icon
msg = ""
show = stanza.get_show()
if show:
msg += show
t = stanza.get_type()
ISOTIMEFORMAT=" %H:%M "
msg = msg + time.strftime(ISOTIMEFORMAT)
if t == 'unavailable':
body = "离线"
msg += u' \033[31m离线\033[0m'
self.client.buddies[renren_id][1] = 0
if renren_id=='230099057':
self.send_mail("lww is off~")
else:
body = "上线"
msg += u' \033[32m上线\033[0m'
self.client.buddies[renren_id][1] = 1
if renren_id=='230099057':
self.send_mail("lww is online!")
status = stanza.get_status()
if status:
msg += u': '+status
body += u":" + status
self.client.buddies[renren_id][3]=status
print buddy,msg,"\n"
self.renrennotify(renren_id,body)
self.save_file(buddy+time.strftime(ISOTIMEFORMAT)+body)
def save_file(self,msg):
file = open(chat_history,"a")
file.write(time.strftime("%Y-%m-%d ")+msg+"\n")
file.close()
def presence_control(self, stanza):
"""Handle subscription control <presence /> stanzas -- acknowledge
them."""
msg = unicode(stanza.get_from())
t = stanza.get_type()
if t == 'subscribe':
msg += u' has requested presence subscription.'
elif t == 'subscribed':
msg += u' has accepted our presence subscription request.'
elif t =='unsubscribe':
msg += u' has canceled his subscription of our.'
elif t == 'unsubscribed':
msg += u' has canceled our subscription of his presence.'
print msg
if has_pynotify:
self.renrennotify("-1",msg)
#Create "accept" response for the "subscribe"/"subscribed"/"unsubscribe"/"unsubscribed" presence stanza.
return stanza.make_accept_response()
def renrennotify(self,renren_id,body):
'''renren notify'''
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
icon = os.path.join(img_folder,renren_id+"_"+buddy+".jpg")
else:
buddy = "人人网"
icon = renren_icon
pynotify.init("Some Application or Title")
notification = pynotify.Notification(buddy,body,icon)
notification.set_urgency(pynotify.URGENCY_NORMAL)
notification.set_timeout(1)
notification.show()
class VersionHandler(object):
"""Provides handler for a version query.
This class will answer version query and announce 'jabber:iq:version' namespace
in the client's disco#info results."""
implements(IIqHandlersProvider, IFeaturesProvider)
def __init__(self, client):
"""Just remember who created this."""
self.client = client
def get_features(self):
"""Return namespace which should the client include in its reply to a
disco#info query."""
return ["jabber:iq:version"]
def get_iq_get_handlers(self):
"""Return list of tuples (element_name, namespace, handler) describing
handlers of <iq type='get' /> stanzas"""
return [
("query", "jabber:iq:version", self.get_version),]
def get_iq_set_handlers(self):
"""Return empty list, as this class provides no <iq type='set'/ > stanza handler."""
return []
def get_version(self,iq):
"""Handler for jabber:iq:version queries.
jabber:iq:version queries are not supported directly by PyXMPP, so the
XML node is accessed directly through the libxml2 API. This should be
used very carefully!"""
iq = iq.make_result_response()
q = iq.new_query("jabber:iq:version")
q.newTextChild(q.ns(),"name","Echo component")
q.newTextChild(q.ns(),"version","1.0")
return iq
class Client(JabberClient):
"""Simple bot (client) example. Uses `pyxmpp.jabber.client.JabberClient`
class as base. That class provides basic stream setup (including
authentication) and Service Discovery server. It also does server address
and port discovery based on the JID provided."""
buddies={}
def __init__(self, jid, password):
# if bare JID is provided add a resource -- it is required
if not jid.resource:
jid=JID(jid.node, jid.domain, 'w3erbot')
#tls验证设置
tls = streamtls.TLSSettings(require=True, verify_peer=False)
auth = ['sasl:PLAIN']
# setup client with provided connection information
# and identity data
JabberClient.__init__(self, jid, password,
disco_name='W3er Bot', disco_type='bot',
tls_settings=tls, auth_methods=auth)
# 添加自己实现的组件
self.interface_providers = [
VersionHandler(self),
EchoHandler(self),
]
def stream_state_changed(self,state,arg):
"""This one is called when the state of stream connecting the component
to a server changes. This will usually be used to let the user
know what is going on."""
#print "*** State changed: %s %r ***" % (state,arg)
def print_roster_item(self,item):
if item.name:
name = item.name
else:
name = u''
#print (u'%s "%s" 订阅=%s 群组=%s' % (unicode(item.jid), name, item.subscription, u','.join(item.groups)) )
renren_id = item.jid.as_utf8().split("@")[0]
if not self.buddies.has_key(renren_id):
self.buddies[renren_id] = ['']*5
'''name, on/offline, groups, personal_sign'''
self.buddies[renren_id][0] = name
#self.buddies[renren_id][1] =
self.buddies[renren_id][2] = item.groups
#self.buddies[renren_id][3] =
self.buddies[renren_id][4] = item.subscription
#print "add",renren_id,name,",".join(item.groups)
def roster_updated(self,item=None):
if not item:
for item in self.roster.get_items():
self.print_roster_item(item)
print u'花名册更新完毕'
return
print u'花名册更新完毕'
self.print_roster_item(item)
class CLI(cmd.Cmd):
def __init__(self,client):
cmd.Cmd.__init__(self)
self.client = client
self.prompt="pyrenren>"
def default(self,line):
print "no such command!"
def do_exit(self,line):
print u'与服务器断开连接'
self.client.disconnect()
sys.exit()
def do_ls(self,line):
keys = self.client.buddies.keys()
for key in keys:
if self.client.buddies[key][1]:
print self.client.buddies[key][0]+"\t",
print ""
class Cline(Thread):
def __init__(self,client):
Thread.__init__(self)
self.client = client
def run(self):
CLI(self.client).cmdloop()
class Renren(Thread):
def __init__(self,client):
Thread.__init__(self)
self.client = client
def run(self):
print u'开始监控'
self.client.loop(1)
print u'退出程序'
def main():
"""# XMPP protocol is Unicode-based to properly display data received
# _must_ convert it to local encoding or UnicodeException may be raised
#locale.setlocale(locale.LC_CTYPE, "")
#encoding = locale.getlocale()[1]
#if not encoding:
# encoding = "us-ascii"
#sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors = "replace")
#sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors = "replace")
"""
if len(sys.argv) !=3 and len(sys.argv) !=6:
print u"Usage:"
print "\t%s renren_ID password gmail_account passwd to_address" % (sys.argv[0],)
print "example:"
print "\t%s 64306080 verysecret abcdefg@gmail.com secret 13425678910@139.com" % (sys.argv[0],)
sys.exit(1)
global fromadd,toadd,passwd
if len(sys.argv) == 6:
fromadd = sys.argv[3]
passwd = sys.argv[4]
toadd = sys.argv[5]
print u'创建客户端实例'
c = Client(JID(sys.argv[1]+"@talk.xiaonei.com"), sys.argv[2])
print u'开始连接服务器'
c.connect()
threads = []
#threads.append(Cline(c))
threads.append(Renren(c))
for t in threads:
t.setDaemon(True)
t.start()
while len(threads):
t = threads.pop()
if t.isAlive():
t.join()
#printl("人人退出")
if __name__ == '__main__':
logger = logging.getLogger()
#logger.addHandler( logging.StreamHandler() )
hdlr = logging.FileHandler(renren_log)
formatter = logging.Formatter('%(asctime)s%(levelname)s%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler( hdlr )
logger.setLevel( logging.DEBUG )
sys.exit(main())
| Python |
#! /usr/bin/python -u
#-*- coding: utf-8 -*-
#
# After connecting to a jabber server it will echo messages, and accept any
# presence subscriptions. This bot has basic Disco support (implemented in
# pyxmpp.jabber.client.Client class) and jabber:iq:vesion.
import sys,os,time,cmd,re
from threading import Thread
import logging
import locale
import codecs
has_pynotify=0
try:
import pynotify
has_pynotify=1
except:
pass
import smtplib,urllib,libxml2
from pyxmpp import streamtls
from pyxmpp.all import JID, Iq, Presence, Message, StreamError
from pyxmpp.jabber.client import JabberClient
from pyxmpp.interface import implements
from pyxmpp.interfaces import *
my_id=''
fromadd=''
passwd=''
toadd=''
userhome = os.path.expanduser('~')
config_folder = os.path.join(userhome,'.pyrenren')
if not os.path.isdir(config_folder):
os.mkdir(config_folder)
chat_history= os.path.join(config_folder,'chat_history.txt')
renren_log= os.path.join(config_folder,'renren.log')
data_file = os.path.join(config_folder,'renren.dat')
img_folder = os.path.join(config_folder,"img")
renren_icon = os.path.join(img_folder,'renren.jpg')
class EchoHandler(object):
"""提供一个机器人的回答功能
对于presence和message XML节的处理器的实现
"""
implements(IMessageHandlersProvider, IPresenceHandlersProvider)
def __init__(self, client):
"""Just remember who created this."""
self.client = client
def get_message_handlers(self):
"""Return list of (message_type, message_handler) tuples.
The handlers returned will be called when matching message is received
in a client session."""
return [("normal", self.message)]
def get_presence_handlers(self):
"""Return list of (presence_type, presence_handler) tuples.
The handlers returned will be called when matching presence stanza is
received in a client session."""
return [
(None, self.presence),
('unavailable', self.presence),
('subscribe', self.presence_control),
('subscribed', self.presence_control),
('unsubscribe', self.presence_control),
('unsubscribed', self.presence_control)]
def get_content(self,tag_name,xmlstr):
reg = tag_name + ">(.+?)</.+?" + tag_name + ">"
raw_content = re.findall(reg,xmlstr)
if not len(raw_content):
return ""
xmldoc = "<?xml version='1.0' encoding='utf-8'?><xmpp>"+raw_content[0]+"</xmpp>"
xml = libxml2.parseDoc(xmldoc)
cont = re.findall("<(.+?)>",xml.content)
if len(cont):
xmldoc = "<?xml version='1.0' encoding='utf-8'?><xmpp>"+xml.content+"</xmpp>"
xml = libxml2.parseDoc(xmldoc)
return xml.content
def color(self,str):
'''涂上蓝色'''
return "\033[34m" + str + "\033[0m"
def message(self, stanza):
"""Message handler for the component.
Echoes the message back if its type is not 'error' or
'headline', also sets own presence status to the message body. Please
note that all message types but 'error' will be passed to the handler
for 'normal' message unless some dedicated handler process them.
:returns: `True` to indicate, that the stanza should not be processed
any further."""
xml = str(stanza.get_node())
if stanza.get_type() == "chat":
renren_id = stanza.get_from().as_utf8().split("@")[0]
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
body = stanza.get_body()
print buddy,"说:",self.color(body)
self.renrennotify(renren_id,body)
self.send_mail(buddy+"说:"+body)
return
renren_id = re.findall("actor>(.+?)</.+?actor>",xml)
if len(renren_id):
renren_id = renren_id[0]
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
else:
buddy = ""
else:
buddy = "你"
subject = stanza.get_subject()
type = re.findall("stype>(.+?)</.+?stype>",xml)
if not len(type):
return
stype = type[0]
body = ""
if stype =='-65549':
print "reply"
#elif stype =='':
#elif stype =='-4':
elif stype == '-33':
'''上传照片?'''
title = self.get_content("title",xml)
body = "上传了1张照片至" + title
msg = "上传了1张照片至" + self.color(title)
print buddy,msg
print buddy,"回复了你的分享"
elif stype == '-34':
print buddy,"回复了你的分享"
elif stype == '-4':
'''程序截图回复了我'''
title = self.get_content("title",xml)
body = "在 "+title+"回复你"
msg = "在 "+self.color(title)+"回复你"
print buddy,msg
elif stype == "102":
'''分享日志'''
fID = re.findall("fID>(.+?)</.+?fID>",xml)[0]
uName = self.get_content("uName",xml)
blog_title = self.get_content("title",xml)
blog_digest = self.get_content("digest",xml)
college = self.get_content("net",xml)
blog_url = re.findall("url>(.+?)</.+?url>",xml)[0]
body = "分享来自 "+college + " 的 "+uName+" 的日志 "+blog_title
msg = "分享来自 " + self.color(college) + " 的"+self.color(uName)+" 的日志 "+self.color(blog_title)+"\n"+blog_digest
print buddy,msg
elif stype=='103':
'''分享照片'''
uName = self.get_content("uName",xml)
aName = self.get_content("aName",xml)
photo_title = self.get_content("title",xml)
body = "分享 "+uName+" 的照片 "+aName+""
msg = "分享 "+self.color(uName)+" 的照片 "+ self.color(aName) + "\n" + photo_title
print buddy,msg
elif stype == "104":
'''分享相册'''
uName = self.get_content("uName",xml)
title = self.get_content("title",xml)
count = self.get_content("count",xml)
body = "分享 "+uName+" 的相册 " + title+"\n共 "+count+" 张照片"
msg = "分享 "+self.color(uName)+" 的相册 " + self.color(title)+"\n共 "+self.color(count) + " 张照片"
print buddy,msg
elif stype == "107":
''''''
body = "正在"
elif stype == "110":
'''分享视频'''
title = self.get_content("title",xml)
body = "分享视频 " + title
msg = "分享视频 "+ self.color(title)
print buddy,msg
elif stype == "400":
'''拜年'''
print buddy,"正在给自己的好友拜年呢"
elif stype == "502":
'''新签名'''
fName = self.get_content("fName",xml)
title = self.get_content("title",xml)
body = "更新了签名:"+title
msg = "更新了签名:"+self.color(title)
print buddy,msg
self.client.buddies[renren_id][3] = title
elif stype == "507":
'''好友留言'''
un = self.get_content("un",xml)
con = self.get_content("con",xml)
rt = self.get_content("rt",xml)
body = un +" "+ rt + " " +con
msg = self.color(un)+" "+ rt + " " + self.color(con)
print buddy + ":"+ self.client.buddies[renren_id][3]
print msg
elif stype == "601":
'''发表日志'''
blog_title = self.get_content("title",xml)
blog_brief = self.get_content("brief",xml)
body = "发表日志 " + blog_title
msg = "发表日志 " + self.color(blog_title)+"\n"+blog_brief
print buddy,msg
elif stype == '602':
'''冷笑话回复了粉丝'''
print ""
elif stype == '701':
'''上传照片'''
aName = self.get_content("aName",xml)
aName = self.get_content("aName",xml)
body = "上传了1张照片至" + aName
msg = "上传了1张照片至" + self.color(aName)
print buddy,msg
elif stype == '704':
'''好友的好友回复了好友?貌似可以删除,因为有507类型了'''
fName = self.get_content("fName",xml)
body = "的好友 "+fName+" 回复了 "+buddy
msg = "的好友 "+self.color(fName)+" 回复了 "+buddy
elif stype=='705':
body = ""
msg = ""
print buddy,msg
elif stype=='708':
'''照片有新回复'''
un = self.get_content("un",xml)
desc = self.get_content("desc",xml)
body = "TA的好友 " + un + "在相册 " + desc + "中留言了"
msg = "的好友 " + self.color(un) + "在相册 " + self.color(desc) + "中留言了"
elif stype=='799':
'''上传照片'''
title = self.get_content("title",xml)
body = "上传了照片至" + title
msg = "上传了照片至" + self.color(title)
print buddy,msg
elif stype == "801":
'''收到礼物'''
body = "收到了"
print buddy,body
elif stype == "802":
'''收到礼物'''
title = self.get_content("title",xml)
uName = self.get_content("uName",xml)
body = "收到"+uName+"送的礼物"+title
msg = "收到"+self.color(uName)+"送的礼物"+self.color(title)
print buddy,msg
elif stype == "2002":
'''加冷笑话为好友'''
title = self.get_content("title",xml)
uName = self.get_content("uName",xml)
brief = self.get_content("brief",xml)
body = "在人人成为了"+title+"的好友"
msg = "在人人成为了"+self.color(title)+"的好友"
print buddy,msg
elif stype == '2003':
'''分享日志'''
uName = self.get_content("uName",xml)
title = self.get_content("title",xml)
digest = self.get_content("digest",xml)
body = "分享"+uName+"的日志"+title
msg = "分享"+self.color(uName)+"的日志"+self.color(title)
print buddy,msg
print digest
elif stype == '2401':
'''使用应用'''
title = self.get_content("title",xml)
body = "在使用应用 "+ title
msg = "在使用应用 "+ self.color(title)
desc = self.get_content("desc",xml)
print buddy,msg
print desc
elif stype == "8190":
title = self.get_content("title",xml)
body = "分享游戏 " + title
msg = "分享游戏 " + self.color(title)
print buddy,msg
elif stype == "45106":
body = "游戏邀请"
print buddy,body
elif stype == "2011":
''''''
blog_title = self.get_content("title",xml)
blog_brief = self.get_content("brief",xml)
buddy = self.get_content("fName",xml)
body = "发表日志 " + blog_title
msg = "发表日志 " + self.color(blog_title)+"\n"+blog_brief
print buddy,msg
elif stype == "2016":
'''生活大爆炸'''
comm = self.get_content("comm",xml)
buddy = self.get_content("fName",xml)
body = comm
msg = self.color(comm)
print buddy,msg
elif stype == '26352':
app_body = self.get_content("body",xml)
body = "邀请你参加" + self.color(app_body)
msg = "邀请你参加" + app_body
print msg
else:
body = "不知道想干嘛,先存着再说"
print buddy,"\033[31m不知道想干嘛,先存着再说\033[0m"
file_path = os.path.join(config_folder,type[0]+".xml")
file = open(file_path,"w")
temp = "<?xml version='1.0'?>" + xml
file.write(temp+"\n")
file.close()
os.system("xmllint --format "+file_path)
file = open(file_path,"a")
temp = stanza.get_node().content+"\n"
file.write(temp)
file.close()
print ""
if type[0] != "502" or type[0] != "507" or type!='601':
file_path = os.path.join(config_folder,"_new.xml")
file = open(file_path,"w")
temp = "<?xml version='1.0'?>" + xml
file.write(temp+"\n")
file.close()
#os.system("xmllint --format "+file_path)
file_path2 = os.path.join(config_folder,"new.xml")
os.system("xmllint --format "+file_path+">"+file_path2)
print ""
temp = stanza.get_node().content+"\n"
#print temp
file_path = os.path.join(config_folder,"renren.xml")
file_path2 = os.path.join(config_folder,"new.xml")
file = open(file_path,"a")
file2 = open(file_path2,"r")
for line in file2.readlines():
file.write(line)
file.write(temp)
file2.close()
file.close()
#os.system("gvim "+file_path)
ISOTIMEFORMAT=" %H:%M "
body = time.strftime(ISOTIMEFORMAT) + body
self.save_file(buddy+body)
if has_pynotify:
self.renrennotify(renren_id,body)
if subject =="reply":
if fromadd!='':
self.send_mail("You have one new reply in http://www.renren.com/Home.do")
if subject:
subject = u'Re: ' + subject
body = stanza.get_body()
m = Message(
to_jid=stanza.get_from(),
from_jid=stanza.get_to(),
stanza_type=stanza.get_type(),
subject=subject,
body=body)
if body:
p = Presence(status=u'新签名:' + body)
return [m, p]
return m
def send_mail(self,message):
print "Send mail from ",fromadd,"to ",toadd
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(fromadd,passwd)
server.sendmail(fromadd,toadd,"From: renren <"+fromadd+">\r\nTo: "+toadd+"\r\nSubject: renren\r\n\r\n"+message)
server.quit()
def presence(self, stanza):
"""Handle 'available' (without 'type') and 'unavailable' <presence/ >."""
xml = str(stanza.get_node())
renren_id = stanza.get_from().as_utf8().split("@")[0]
if self.client.buddies.has_key(renren_id):
item = self.client.buddies[renren_id]
groups = item[2]
group = ",".join(groups)
if len(groups)>0:
group = group + ":"
else:
self.client.buddies[renren_id] = ['']*5
self.client.buddies[renren_id][0] = renren_id
buddy = self.client.buddies[renren_id][0]
picture = re.findall("EXTVAL>(.+?)</.+?EXTVAL>",xml)
file_path = ""
if len(picture):
picture = picture[0]
file_path = os.path.join(img_folder,renren_id+"_"+buddy+".jpg")
urllib.urlretrieve(picture,file_path)
else:
file_path = renren_icon
msg = ""
show = stanza.get_show()
if show:
msg += show
t = stanza.get_type()
ISOTIMEFORMAT=" %H:%M "
msg = msg + time.strftime(ISOTIMEFORMAT)
if t == 'unavailable':
body = "离线"
msg += u' \033[31m离线\033[0m'
self.client.buddies[renren_id][1] = 0
if renren_id=='230099057':
self.send_mail("lww is off~")
else:
body = "上线"
msg += u' \033[32m上线\033[0m'
self.client.buddies[renren_id][1] = 1
if renren_id=='230099057':
self.send_mail("lww is online!")
status = stanza.get_status()
if status:
msg += u': '+status
body += u":" + status
self.client.buddies[renren_id][3]=status
print buddy,msg,"\n"
self.renrennotify(renren_id,body)
self.save_file(buddy+time.strftime(ISOTIMEFORMAT)+body)
def save_file(self,msg):
file = open(chat_history,"a")
file.write(time.strftime("%Y-%m-%d ")+msg+"\n")
file.close()
def presence_control(self, stanza):
"""Handle subscription control <presence /> stanzas -- acknowledge
them."""
msg = unicode(stanza.get_from())
t = stanza.get_type()
if t == 'subscribe':
msg += u' has requested presence subscription.'
elif t == 'subscribed':
msg += u' has accepted our presence subscription request.'
elif t =='unsubscribe':
msg += u' has canceled his subscription of our.'
elif t == 'unsubscribed':
msg += u' has canceled our subscription of his presence.'
print msg
if has_pynotify:
self.renrennotify("-1",msg)
#Create "accept" response for the "subscribe"/"subscribed"/"unsubscribe"/"unsubscribed" presence stanza.
return stanza.make_accept_response()
def renrennotify(self,renren_id,body):
'''renren notify'''
if self.client.buddies.has_key(renren_id):
buddy = self.client.buddies[renren_id][0]
icon = os.path.join(img_folder,renren_id+"_"+buddy+".jpg")
else:
buddy = "人人网"
icon = renren_icon
pynotify.init("Some Application or Title")
notification = pynotify.Notification(buddy,body,icon)
notification.set_urgency(pynotify.URGENCY_NORMAL)
notification.set_timeout(1)
notification.show()
class VersionHandler(object):
"""Provides handler for a version query.
This class will answer version query and announce 'jabber:iq:version' namespace
in the client's disco#info results."""
implements(IIqHandlersProvider, IFeaturesProvider)
def __init__(self, client):
"""Just remember who created this."""
self.client = client
def get_features(self):
"""Return namespace which should the client include in its reply to a
disco#info query."""
return ["jabber:iq:version"]
def get_iq_get_handlers(self):
"""Return list of tuples (element_name, namespace, handler) describing
handlers of <iq type='get' /> stanzas"""
return [
("query", "jabber:iq:version", self.get_version),]
def get_iq_set_handlers(self):
"""Return empty list, as this class provides no <iq type='set'/ > stanza handler."""
return []
def get_version(self,iq):
"""Handler for jabber:iq:version queries.
jabber:iq:version queries are not supported directly by PyXMPP, so the
XML node is accessed directly through the libxml2 API. This should be
used very carefully!"""
iq = iq.make_result_response()
q = iq.new_query("jabber:iq:version")
q.newTextChild(q.ns(),"name","Echo component")
q.newTextChild(q.ns(),"version","1.0")
return iq
class Client(JabberClient):
"""Simple bot (client) example. Uses `pyxmpp.jabber.client.JabberClient`
class as base. That class provides basic stream setup (including
authentication) and Service Discovery server. It also does server address
and port discovery based on the JID provided."""
buddies={}
def __init__(self, jid, password):
# if bare JID is provided add a resource -- it is required
if not jid.resource:
jid=JID(jid.node, jid.domain, 'w3erbot')
#tls验证设置
tls = streamtls.TLSSettings(require=True, verify_peer=False)
auth = ['sasl:PLAIN']
# setup client with provided connection information
# and identity data
JabberClient.__init__(self, jid, password,
disco_name='W3er Bot', disco_type='bot',
tls_settings=tls, auth_methods=auth)
# 添加自己实现的组件
self.interface_providers = [
VersionHandler(self),
EchoHandler(self),
]
def stream_state_changed(self,state,arg):
"""This one is called when the state of stream connecting the component
to a server changes. This will usually be used to let the user
know what is going on."""
#print "*** State changed: %s %r ***" % (state,arg)
def print_roster_item(self,item):
if item.name:
name = item.name
else:
name = u''
#print (u'%s "%s" 订阅=%s 群组=%s' % (unicode(item.jid), name, item.subscription, u','.join(item.groups)) )
renren_id = item.jid.as_utf8().split("@")[0]
if not self.buddies.has_key(renren_id):
self.buddies[renren_id] = ['']*5
'''name, on/offline, groups, personal_sign'''
self.buddies[renren_id][0] = name
#self.buddies[renren_id][1] =
self.buddies[renren_id][2] = item.groups
#self.buddies[renren_id][3] =
self.buddies[renren_id][4] = item.subscription
#print "add",renren_id,name,",".join(item.groups)
def roster_updated(self,item=None):
if not item:
for item in self.roster.get_items():
self.print_roster_item(item)
print u'花名册更新完毕'
return
print u'花名册更新完毕'
self.print_roster_item(item)
class CLI(cmd.Cmd):
def __init__(self,client):
cmd.Cmd.__init__(self)
self.client = client
self.prompt="pyrenren>"
def default(self,line):
print "no such command!"
def do_exit(self,line):
print u'与服务器断开连接'
self.client.disconnect()
sys.exit()
def do_ls(self,line):
keys = self.client.buddies.keys()
for key in keys:
if self.client.buddies[key][1]:
print self.client.buddies[key][0]+"\t",
print ""
class Cline(Thread):
def __init__(self,client):
Thread.__init__(self)
self.client = client
def run(self):
CLI(self.client).cmdloop()
class Renren(Thread):
def __init__(self,client):
Thread.__init__(self)
self.client = client
def run(self):
print u'开始监控'
self.client.loop(1)
print u'退出程序'
def main():
"""# XMPP protocol is Unicode-based to properly display data received
# _must_ convert it to local encoding or UnicodeException may be raised
#locale.setlocale(locale.LC_CTYPE, "")
#encoding = locale.getlocale()[1]
#if not encoding:
# encoding = "us-ascii"
#sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors = "replace")
#sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors = "replace")
"""
if len(sys.argv) !=3 and len(sys.argv) !=6:
print u"Usage:"
print "\t%s renren_ID password gmail_account passwd to_address" % (sys.argv[0],)
print "example:"
print "\t%s 64306080 verysecret abcdefg@gmail.com secret 13425678910@139.com" % (sys.argv[0],)
sys.exit(1)
global fromadd,toadd,passwd
if len(sys.argv) == 6:
fromadd = sys.argv[3]
passwd = sys.argv[4]
toadd = sys.argv[5]
print u'创建客户端实例'
c = Client(JID(sys.argv[1]+"@talk.xiaonei.com"), sys.argv[2])
print u'开始连接服务器'
c.connect()
threads = []
#threads.append(Cline(c))
threads.append(Renren(c))
for t in threads:
t.setDaemon(True)
t.start()
while len(threads):
t = threads.pop()
if t.isAlive():
t.join()
#printl("人人退出")
if __name__ == '__main__':
logger = logging.getLogger()
#logger.addHandler( logging.StreamHandler() )
hdlr = logging.FileHandler(renren_log)
formatter = logging.Formatter('%(asctime)s%(levelname)s%(message)s')
hdlr.setFormatter(formatter)
logger.addHandler( hdlr )
logger.setLevel( logging.DEBUG )
sys.exit(main())
| Python |
#! /usr/bin/python -u
#-*- coding: utf-8 -*-
#
#
| Python |
'''
FogBugz Abstraction to facilitate the posting and editing of new cases
through interfaces that are not FogBugz. Oh and please, let the tests
drive any changes to this class. If you don't a man will come to you
in your sleep... I'm not saying what he'll do, just FYI.
Wayne Witzel III
Tower Hill Insurance Group
Copyright 2008
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import unittest
from fogbugz import Authentication
from fogbugz import Case
class TestFogBugz(unittest.TestCase):
def setUp(self):
self.credentials = ('WWitzel','Password')
self.bad_credentials = ('xyz','xyz')
def tearDown(self):
pass
def testFailedAuthentication(self):
auth = Authentication(*self.bad_credentials)
auth.logon()
self.assertFalse(auth.valid)
def testAuthentication(self):
auth = Authentication(*self.credentials)
auth.logon()
self.assertTrue(auth.valid)
auth.logoff()
self.assertFalse(auth.valid)
def testFileAttachCase(self):
auth = Authentication(*self.credentials)
c = Case(auth)
c.sTitle = 'Test Case File Attach'
c.ixProject = 'Notes'
c.ixPersonAssignedTo = 'Wayne Witzel III'
c.sComputer = 'Systems'
c.sCustomerEmail = 'wwitzel@thig.com'
c.ixMailbox = 1
c.attachFile('./tests/external/test.txt')
c.attachFile('./tests/external/test2.txt')
c.attachFile('./tests/external/test3.jpg')
c.save()
self.assertFalse(c.error)
def testNewCase(self):
auth = Authentication(*self.credentials)
c = Case(auth)
c.sTitle = 'Test Case'
c.ixProject = 'Notes'
c.ixPersonAssignedTo = 'Wayne Witzel III'
c.sComputer = 'Systems'
c.sCustomerEmail = 'wwitzel@thig.com'
c.ixMailbox = 1
c.save()
self.assertFalse(c.error)
self.assertTrue(c.ixBug)
def testEditCase(self):
auth = Authentication(*self.credentials)
c = Case(auth, 299)
self.assertEquals(c.ixBug,'299')
import time
timestamp = '%.0f' % time.time()
title = 'Test Case (%s)' % timestamp
c.sTitle = title
c.save()
c = Case(auth, 299)
self.assertEquals(c.sTitle,title)
| Python |
'''
FogBugz Abstraction to facilitate the posting and editing of new cases
through interfaces that are not FogBugz. Oh and please, let the tests
drive any changes to this class. If you don't a man will come to you
in your sleep... I'm not saying what he'll do, just FYI.
Wayne Witzel III
Tower Hill Insurance Group
Copyright 2008
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
| Python |
'''
FogBugz Abstraction to facilitate the posting and editing of new cases
through interfaces that are not FogBugz. Oh and please, let the tests
drive any changes to this class. If you don't a man will come to you
in your sleep... I'm not saying what he'll do, just FYI.
Wayne Witzel III
Tower Hill Insurance Group
Copyright 2008
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import pycurl as curl
from xml.dom.minidom import parseString
# Start here if you aren't sure.
FOGBUGZ_API_URL = 'http://fogbugz.thig.com/api.php'
FOGBUGZ_RESPONSE_COLS = ['ixBug', 'sTitle']
# Stop here if you aren't sure.
class Response(object):
def __init__(self):
self.data = ''
def callback(self, r):
self.data = self.data + r
class Request(object):
def __init__(self, cmd):
self.c = curl.Curl()
self.response = Response()
self.c.setopt(curl.WRITEFUNCTION,self.response.callback)
self.cmd = cmd
self.params = {}
def perform(self):
# For some reason I can't do q(params[p]) when using
# string replacement, so we have this for loop instead
# of the obfuscated list comprehension I was gonna use.
#
self.params['cmd'] = self.cmd
query_string = '?cols=' + ','.join(FOGBUGZ_RESPONSE_COLS)
postdata = []
for k in self.params:
value = self.params[k]
if value:
if type(value) is tuple:
postdata.append((k,value))
else:
value = str(value)
postdata.append((k, '%s' % value))
else:
postdata.append((k, ''))
self.c.setopt(curl.HTTPPOST, postdata)
self.c.setopt(curl.URL, FOGBUGZ_API_URL + query_string)
self.c.perform()
self.c.close()
fbzdom = parseString(self.response.data)
# Yeah, it is wrong to just ignore the rest of the
# values in the node, assuming there is more. Right now, ol' well.
#
error_nodes = fbzdom.getElementsByTagName("error")
if error_nodes.length:
self.params['error'] = error_nodes[0].childNodes[0].nodeValue
else:
self.params['error'] = None
token_nodes = fbzdom.getElementsByTagName("token")
if token_nodes.length:
self.params['token'] = token_nodes[0].childNodes[0].nodeValue
for col in FOGBUGZ_RESPONSE_COLS:
nodes = fbzdom.getElementsByTagName(col)
if nodes.length:
self.params[col] = nodes[0].childNodes[0].nodeValue
return self.params
# The following class methods are just so I can
# maintain the interface to the Request object if
# FogBugz decides to change the `logon` action to `login`
#
def logon(cls):
return cls('logon')
logon = classmethod(logon)
def logoff(cls):
return cls('logoff')
logoff = classmethod(logoff)
def new(cls):
return cls('new')
new = classmethod(new)
def edit(cls):
return cls('edit')
edit = classmethod(edit)
def search(cls):
return cls('search')
search = classmethod(search)
class Authentication(object):
def __init__(self, email, password):
self.email = email
self.password = password
self.valid = None
def logon(self):
r = Request.logon()
r.params = self.__dict__
for k,v in r.perform().items():
if getattr(self, k) != v:
setattr(self, k, v)
try:
self.valid = True
return self.token
except AttributeError:
self.valid = False
return None
def logoff(self):
r = Request.logoff()
r.params = self.__dict__
for k,v in r.perform().items():
if getattr(self, k) != v:
setattr(self, k, v)
self.valid = False
class Case(object):
def __init__(self, auth, ixBug=None):
self.token = auth.logon()
self.ixBug = ixBug
self.nFileCount = 0
if self.ixBug:
# load up information from FogBugz
self.q = self.ixBug
r = Request.search()
self._perform(r)
else:
pass
def attachFile(self, filename):
# Making a note here, since this might bite me
# then I can say I told you so.
#
self.nFileCount += 1
self.__dict__['File%d' % self.nFileCount] = (curl.FORM_FILE, filename)
def save(self):
if self.ixBug:
r = Request.edit()
self._perform(r)
else:
r = Request.new()
self._perform(r)
def _perform(self, request):
# You think this is safe? I do .. mostly.
#
request.params = self.__dict__
self.__dict__ = request.perform()
| Python |
#!/usr/bin/env python
""" Setup file for PyFoo package """
from distutils.core import setup
setup(name='folc',
version='0.1',
description='Folc package',
long_description = "Fiction Book online to local converter",
author='Sergei Danilov',
author_email='sergeidanilov@gmail.com',
url='http://business-toys.org',
packages=[ 'folc', ],
scripts=['folc.py'],
classifiers=(
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Language :: Python',
),
license="GPL-2"
) | Python |
#!/usr/bin/python
import sys
from folc.Folc import httpWidget
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = httpWidget()
myapp.show()
sys.exit(app.exec_()) | Python |
# Requires wxPython. This sample demonstrates:
#
# - single file exe using wxPython as GUI.
from distutils.core import setup
import py2exe
import sys
# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "0.6.1"
self.company_name = "No Company"
self.copyright = "no copyright"
self.name = "py2exe sample files"
################################################################
# A program using wxPython
# The manifest will be inserted as resource into test_wx.exe. This
# gives the controls the Windows XP appearance (if run on XP ;-)
#
# Another option would be to store it in a file named
# test_wx.exe.manifest, and copy it with the data_files option into
# the dist-dir.
#
manifest_template = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="5.0.0.0"
processorArchitecture="x86"
name="%(prog)s"
type="win32"
/>
<description>%(prog)s Program</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
'''
RT_MANIFEST = 24
folc = Target(
# used for the versioninfo resource
description = "A sample GUI app",
# what to build
script = "folc.py",
# other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="folc"))],
## icon_resources = [(1, "icon.ico")],
dest_base="folc",
uac_info="requireAdministrator")
################################################################
setup(
options = {"py2exe": {"includes" : ["sip", "PyQt4.QtNetwork","encodings.utf_8","encodings.ascii"],
"compressed": 1,
"optimize": 2,
"ascii": 1,
"bundle_files": 1}},
zipfile = None,
windows = [folc],
)
| Python |
#!/usr/bin/python
import sys
from folc.Folc import httpWidget
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = httpWidget()
myapp.show()
sys.exit(app.exec_()) | Python |
#!/usr/bin/env python
""" Setup file for PyFoo package """
from distutils.core import setup
setup(name='folc',
version='0.1',
description='Folc package',
long_description = "Fiction Book online to local converter",
author='Sergei Danilov',
author_email='sergeidanilov@gmail.com',
url='http://business-toys.org',
packages=[ 'folc', ],
scripts=['folc.py'],
classifiers=(
'Development Status :: 2 - Pre-Alpha',
'Environment :: Console',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: POSIX',
'Operating System :: Unix',
'Programming Language :: Python',
),
license="GPL-2"
) | Python |
# Requires wxPython. This sample demonstrates:
#
# - single file exe using wxPython as GUI.
from distutils.core import setup
import py2exe
import sys
# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
class Target:
def __init__(self, **kw):
self.__dict__.update(kw)
# for the versioninfo resources
self.version = "0.6.1"
self.company_name = "No Company"
self.copyright = "no copyright"
self.name = "py2exe sample files"
################################################################
# A program using wxPython
# The manifest will be inserted as resource into test_wx.exe. This
# gives the controls the Windows XP appearance (if run on XP ;-)
#
# Another option would be to store it in a file named
# test_wx.exe.manifest, and copy it with the data_files option into
# the dist-dir.
#
manifest_template = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
version="5.0.0.0"
processorArchitecture="x86"
name="%(prog)s"
type="win32"
/>
<description>%(prog)s Program</description>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>
'''
RT_MANIFEST = 24
folc = Target(
# used for the versioninfo resource
description = "A sample GUI app",
# what to build
script = "folc.py",
other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="folc"))],
## icon_resources = [(1, "icon.ico")],
dest_base = "folc")
################################################################
setup(
options = {"py2exe": {"includes" : ["sip", "PyQt4.QtNetwork"],
"dll_excludes": ["msvcr90.dll"],
"compressed": 1,
"optimize": 2,
"ascii": 1,
"bundle_files": 1}},
zipfile = None,
windows = [folc],
)
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'httpWidget.ui'
#
# Created: Thu Mar 05 12:19:53 2009
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_HttpWidget(object):
def setupUi(self, HttpWidget):
HttpWidget.setObjectName("HttpWidget")
HttpWidget.resize(730, 544)
self.gridLayout = QtGui.QGridLayout(HttpWidget)
self.gridLayout.setObjectName("gridLayout")
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.label_3 = QtGui.QLabel(HttpWidget)
self.label_3.setObjectName("label_3")
self.horizontalLayout.addWidget(self.label_3)
self.url_3 = QtGui.QLineEdit(HttpWidget)
self.url_3.setObjectName("url_3")
self.horizontalLayout.addWidget(self.url_3)
self.spinBox = QtGui.QSpinBox(HttpWidget)
self.spinBox.setObjectName("spinBox")
self.horizontalLayout.addWidget(self.spinBox)
self.spinBox_2 = QtGui.QSpinBox(HttpWidget)
self.spinBox_2.setObjectName("spinBox_2")
self.horizontalLayout.addWidget(self.spinBox_2)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setSpacing(6)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label_4 = QtGui.QLabel(HttpWidget)
self.label_4.setMaximumSize(QtCore.QSize(16777215, 29))
self.label_4.setObjectName("label_4")
self.horizontalLayout_2.addWidget(self.label_4)
self.url_2 = QtGui.QLineEdit(HttpWidget)
self.url_2.setObjectName("url_2")
self.horizontalLayout_2.addWidget(self.url_2)
self.reload_2 = QtGui.QPushButton(HttpWidget)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("reload.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.reload_2.setIcon(icon)
self.reload_2.setObjectName("reload_2")
self.horizontalLayout_2.addWidget(self.reload_2)
self.gridLayout.addLayout(self.horizontalLayout_2, 1, 0, 1, 1)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label_2 = QtGui.QLabel(HttpWidget)
self.label_2.setObjectName("label_2")
self.horizontalLayout_3.addWidget(self.label_2)
self.url_4 = QtGui.QLineEdit(HttpWidget)
self.url_4.setObjectName("url_4")
self.horizontalLayout_3.addWidget(self.url_4)
self.gridLayout.addLayout(self.horizontalLayout_3, 2, 0, 1, 1)
self.webView = QtWebKit.QWebView(HttpWidget)
self.webView.setUrl(QtCore.QUrl("about:blank"))
self.webView.setObjectName("webView")
self.gridLayout.addWidget(self.webView, 3, 0, 1, 1)
self.label_5 = QtGui.QLabel(HttpWidget)
self.label_5.setMaximumSize(QtCore.QSize(16777215, 13))
self.label_5.setObjectName("label_5")
self.gridLayout.addWidget(self.label_5, 4, 0, 1, 1)
self.label = QtGui.QLabel(HttpWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 5, 0, 1, 1)
self.retranslateUi(HttpWidget)
QtCore.QMetaObject.connectSlotsByName(HttpWidget)
def retranslateUi(self, HttpWidget):
HttpWidget.setWindowTitle(QtGui.QApplication.translate("HttpWidget", "Fictionbook.ru online to local converter", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("HttpWidget", "Какие страницы качать", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("HttpWidget", "Первая страница", None, QtGui.QApplication.UnicodeUTF8))
self.reload_2.setToolTip(QtGui.QApplication.translate("HttpWidget", "Reload", None, QtGui.QApplication.UnicodeUTF8))
self.reload_2.setText(QtGui.QApplication.translate("HttpWidget", "Start", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("HttpWidget", "Сохранить книгу в файл: ", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("HttpWidget", "Скачивание пока не начато", None, QtGui.QApplication.UnicodeUTF8))
from PyQt4 import QtWebKit
| Python |
"""Beautiful Soup
Elixir and Tonic
"The Screen-Scraper's Friend"
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup parses a (possibly invalid) XML or HTML document into a
tree representation. It provides methods and Pythonic idioms that make
it easy to navigate, search, and modify the tree.
A well-formed XML/HTML document yields a well-formed data
structure. An ill-formed XML/HTML document yields a correspondingly
ill-formed data structure. If your document is only locally
well-formed, you can use this library to find and process the
well-formed part of it.
Beautiful Soup works with Python 2.2 and up. It has no external
dependencies, but you'll have more success at converting data to UTF-8
if you also install these three packages:
* chardet, for auto-detecting character encodings
http://chardet.feedparser.org/
* cjkcodecs and iconv_codec, which add more encodings to the ones supported
by stock Python.
http://cjkpython.i18n.org/
Beautiful Soup defines classes for two main parsing strategies:
* BeautifulStoneSoup, for parsing XML, SGML, or your domain-specific
language that kind of looks like XML.
* BeautifulSoup, for parsing run-of-the-mill HTML code, be it valid
or invalid. This class has web browser-like heuristics for
obtaining a sensible parse tree in the face of common HTML errors.
Beautiful Soup also defines a class (UnicodeDammit) for autodetecting
the encoding of an HTML or XML document, and converting it to
Unicode. Much of this code is taken from Mark Pilgrim's Universal Feed Parser.
For more than you ever wanted to know about Beautiful Soup, see the
documentation:
http://www.crummy.com/software/BeautifulSoup/documentation.html
Here, have some legalese:
Copyright (c) 2004-2008, Leonard Richardson
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the the Beautiful Soup Consortium and All
Night Kosher Bakery nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE, DAMMIT.
"""
from __future__ import generators
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "3.0.7"
__copyright__ = "Copyright (c) 2004-2008 Leonard Richardson"
__license__ = "New-style BSD"
from sgmllib import SGMLParser, SGMLParseError
import codecs
import markupbase
import types
import re
import sgmllib
try:
from htmlentitydefs import name2codepoint
except ImportError:
name2codepoint = {}
#These hacks make Beautiful Soup able to parse XML with namespaces
sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
markupbase._declname_match = re.compile(r'[a-zA-Z][-_.:a-zA-Z0-9]*\s*').match
DEFAULT_OUTPUT_ENCODING = "utf-8"
# First, the classes that represent markup elements.
class PageElement:
"""Contains the navigational information for some part of the page
(either a tag or a piece of text)"""
def setup(self, parent=None, previous=None):
"""Sets up the initial relations between this element and
other elements."""
self.parent = parent
self.previous = previous
self.next = None
self.previousSibling = None
self.nextSibling = None
if self.parent and self.parent.contents:
self.previousSibling = self.parent.contents[-1]
self.previousSibling.nextSibling = self
def replaceWith(self, replaceWith):
oldParent = self.parent
myIndex = self.parent.contents.index(self)
if hasattr(replaceWith, 'parent') and replaceWith.parent == self.parent:
# We're replacing this element with one of its siblings.
index = self.parent.contents.index(replaceWith)
if index and index < myIndex:
# Furthermore, it comes before this element. That
# means that when we extract it, the index of this
# element will change.
myIndex = myIndex - 1
self.extract()
oldParent.insert(myIndex, replaceWith)
def extract(self):
"""Destructively rips this element out of the tree."""
if self.parent:
try:
self.parent.contents.remove(self)
except ValueError:
pass
#Find the two elements that would be next to each other if
#this element (and any children) hadn't been parsed. Connect
#the two.
lastChild = self._lastRecursiveChild()
nextElement = lastChild.next
if self.previous:
self.previous.next = nextElement
if nextElement:
nextElement.previous = self.previous
self.previous = None
lastChild.next = None
self.parent = None
if self.previousSibling:
self.previousSibling.nextSibling = self.nextSibling
if self.nextSibling:
self.nextSibling.previousSibling = self.previousSibling
self.previousSibling = self.nextSibling = None
return self
def _lastRecursiveChild(self):
"Finds the last element beneath this object to be parsed."
lastChild = self
while hasattr(lastChild, 'contents') and lastChild.contents:
lastChild = lastChild.contents[-1]
return lastChild
def insert(self, position, newChild):
if (isinstance(newChild, basestring)
or isinstance(newChild, unicode)) \
and not isinstance(newChild, NavigableString):
newChild = NavigableString(newChild)
position = min(position, len(self.contents))
if hasattr(newChild, 'parent') and newChild.parent != None:
# We're 'inserting' an element that's already one
# of this object's children.
if newChild.parent == self:
index = self.find(newChild)
if index and index < position:
# Furthermore we're moving it further down the
# list of this object's children. That means that
# when we extract this element, our target index
# will jump down one.
position = position - 1
newChild.extract()
newChild.parent = self
previousChild = None
if position == 0:
newChild.previousSibling = None
newChild.previous = self
else:
previousChild = self.contents[position-1]
newChild.previousSibling = previousChild
newChild.previousSibling.nextSibling = newChild
newChild.previous = previousChild._lastRecursiveChild()
if newChild.previous:
newChild.previous.next = newChild
newChildsLastElement = newChild._lastRecursiveChild()
if position >= len(self.contents):
newChild.nextSibling = None
parent = self
parentsNextSibling = None
while not parentsNextSibling:
parentsNextSibling = parent.nextSibling
parent = parent.parent
if not parent: # This is the last element in the document.
break
if parentsNextSibling:
newChildsLastElement.next = parentsNextSibling
else:
newChildsLastElement.next = None
else:
nextChild = self.contents[position]
newChild.nextSibling = nextChild
if newChild.nextSibling:
newChild.nextSibling.previousSibling = newChild
newChildsLastElement.next = nextChild
if newChildsLastElement.next:
newChildsLastElement.next.previous = newChildsLastElement
self.contents.insert(position, newChild)
def append(self, tag):
"""Appends the given tag to the contents of this tag."""
self.insert(len(self.contents), tag)
def findNext(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears after this Tag in the document."""
return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
def findAllNext(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
after this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.nextGenerator,
**kwargs)
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears after this Tag in the document."""
return self._findOne(self.findNextSiblings, name, attrs, text,
**kwargs)
def findNextSiblings(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear after this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.nextSiblingGenerator, **kwargs)
fetchNextSiblings = findNextSiblings # Compatibility with pre-3.x
def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the first item that matches the given criteria and
appears before this Tag in the document."""
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None,
**kwargs):
"""Returns all items that match the given criteria and appear
before this Tag in the document."""
return self._findAll(name, attrs, text, limit, self.previousGenerator,
**kwargs)
fetchPrevious = findAllPrevious # Compatibility with pre-3.x
def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._findOne(self.findPreviousSiblings, name, attrs, text,
**kwargs)
def findPreviousSiblings(self, name=None, attrs={}, text=None,
limit=None, **kwargs):
"""Returns the siblings of this Tag that match the given
criteria and appear before this Tag in the document."""
return self._findAll(name, attrs, text, limit,
self.previousSiblingGenerator, **kwargs)
fetchPreviousSiblings = findPreviousSiblings # Compatibility with pre-3.x
def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
if l:
r = l[0]
return r
def findParents(self, name=None, attrs={}, limit=None, **kwargs):
"""Returns the parents of this Tag that match the given
criteria."""
return self._findAll(name, attrs, None, limit, self.parentGenerator,
**kwargs)
fetchParents = findParents # Compatibility with pre-3.x
#These methods do the real heavy lifting.
def _findOne(self, method, name, attrs, text, **kwargs):
r = None
l = method(name, attrs, text, 1, **kwargs)
if l:
r = l[0]
return r
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if isinstance(name, SoupStrainer):
strainer = name
else:
# Build a SoupStrainer
strainer = SoupStrainer(name, attrs, text, **kwargs)
results = ResultSet(strainer)
g = generator()
while True:
try:
i = g.next()
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if limit and len(results) >= limit:
break
return results
#These Generators can be used to navigate starting from both
#NavigableStrings and Tags.
def nextGenerator(self):
i = self
while i:
i = i.next
yield i
def nextSiblingGenerator(self):
i = self
while i:
i = i.nextSibling
yield i
def previousGenerator(self):
i = self
while i:
i = i.previous
yield i
def previousSiblingGenerator(self):
i = self
while i:
i = i.previousSibling
yield i
def parentGenerator(self):
i = self
while i:
i = i.parent
yield i
# Utility methods
def substituteEncoding(self, str, encoding=None):
encoding = encoding or "utf-8"
return str.replace("%SOUP-ENCODING%", encoding)
def toEncoding(self, s, encoding=None):
"""Encodes an object to a string in some encoding, or to Unicode.
."""
if isinstance(s, unicode):
if encoding:
s = s.encode(encoding)
elif isinstance(s, str):
if encoding:
s = s.encode(encoding)
else:
s = unicode(s)
else:
if encoding:
s = self.toEncoding(str(s), encoding)
else:
s = unicode(s)
return s
class NavigableString(unicode, PageElement):
def __new__(cls, value):
"""Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass's __new__ or the superclass won't know
how to handle non-ASCII characters.
"""
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):
return (NavigableString.__str__(self),)
def __getattr__(self, attr):
"""text.string gives you text. This is for backwards
compatibility for Navigable*String, but for CData* it lets you
get the string without the CData wrapper."""
if attr == 'string':
return self
else:
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)
def __unicode__(self):
return str(self).decode(DEFAULT_OUTPUT_ENCODING)
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
if encoding:
return self.encode(encoding)
else:
return self
class CData(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<![CDATA[%s]]>" % NavigableString.__str__(self, encoding)
class ProcessingInstruction(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
output = self
if "%SOUP-ENCODING%" in output:
output = self.substituteEncoding(output, encoding)
return "<?%s?>" % self.toEncoding(output, encoding)
class Comment(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!--%s-->" % NavigableString.__str__(self, encoding)
class Declaration(NavigableString):
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return "<!%s>" % NavigableString.__str__(self, encoding)
class Tag(PageElement):
"""Represents a found HTML tag with its attributes and contents."""
def _invert(h):
"Cheap function to invert a hash."
i = {}
for k,v in h.items():
i[v] = k
return i
XML_ENTITIES_TO_SPECIAL_CHARS = { "apos" : "'",
"quot" : '"',
"amp" : "&",
"lt" : "<",
"gt" : ">" }
XML_SPECIAL_CHARS_TO_ENTITIES = _invert(XML_ENTITIES_TO_SPECIAL_CHARS)
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntities and x in name2codepoint:
return unichr(name2codepoint[x])
elif x in self.XML_ENTITIES_TO_SPECIAL_CHARS:
if self.convertXMLEntities:
return self.XML_ENTITIES_TO_SPECIAL_CHARS[x]
else:
return u'&%s;' % x
elif len(x) > 0 and x[0] == '#':
# Handle numeric entities
if len(x) > 1 and x[1] == 'x':
return unichr(int(x[2:], 16))
else:
return unichr(int(x[1:]))
elif self.escapeUnrecognizedEntities:
return u'&%s;' % x
else:
return u'&%s;' % x
def __init__(self, parser, name, attrs=None, parent=None,
previous=None):
"Basic constructor."
# We don't actually store the parser object: that lets extracted
# chunks be garbage-collected
self.parserClass = parser.__class__
self.isSelfClosing = parser.isSelfClosingTag(name)
self.name = name
if attrs == None:
attrs = []
self.attrs = attrs
self.contents = []
self.setup(parent, previous)
self.hidden = False
self.containsSubstitutions = False
self.convertHTMLEntities = parser.convertHTMLEntities
self.convertXMLEntities = parser.convertXMLEntities
self.escapeUnrecognizedEntities = parser.escapeUnrecognizedEntities
# Convert any HTML, XML, or numeric entities in the attribute values.
convert = lambda(k, val): (k,
re.sub("&(#\d+|#x[0-9a-fA-F]+|\w+);",
self._convertEntities,
val))
self.attrs = map(convert, self.attrs)
def get(self, key, default=None):
"""Returns the value of the 'key' attribute for the tag, or
the value given for 'default' if it doesn't have that
attribute."""
return self._getAttrMap().get(key, default)
def has_key(self, key):
return self._getAttrMap().has_key(key)
def __getitem__(self, key):
"""tag[key] returns the value of the 'key' attribute for the tag,
and throws an exception if it's not there."""
return self._getAttrMap()[key]
def __iter__(self):
"Iterating over a tag iterates over its contents."
return iter(self.contents)
def __len__(self):
"The length of a tag is the length of its list of contents."
return len(self.contents)
def __contains__(self, x):
return x in self.contents
def __nonzero__(self):
"A tag is non-None even if it has no contents."
return True
def __setitem__(self, key, value):
"""Setting tag[key] sets the value of the 'key' attribute for the
tag."""
self._getAttrMap()
self.attrMap[key] = value
found = False
for i in range(0, len(self.attrs)):
if self.attrs[i][0] == key:
self.attrs[i] = (key, value)
found = True
if not found:
self.attrs.append((key, value))
self._getAttrMap()[key] = value
def __delitem__(self, key):
"Deleting tag[key] deletes all 'key' attributes for the tag."
for item in self.attrs:
if item[0] == key:
self.attrs.remove(item)
#We don't break because bad HTML can define the same
#attribute multiple times.
self._getAttrMap()
if self.attrMap.has_key(key):
del self.attrMap[key]
def __call__(self, *args, **kwargs):
"""Calling a tag like a function is the same as calling its
findAll() method. Eg. tag('a') returns a list of all the A tags
found within this tag."""
return apply(self.findAll, args, kwargs)
def __getattr__(self, tag):
#print "Getattr %s.%s" % (self.__class__, tag)
if len(tag) > 3 and tag.rfind('Tag') == len(tag)-3:
return self.find(tag[:-3])
elif tag.find('__') != 0:
return self.find(tag)
raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__, tag)
def __eq__(self, other):
"""Returns true iff this tag has the same name, the same attributes,
and the same contents (recursively) as the given tag.
NOTE: right now this will return false if two tags have the
same attributes in a different order. Should this be fixed?"""
if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other):
return False
for i in range(0, len(self.contents)):
if self.contents[i] != other.contents[i]:
return False
return True
def __ne__(self, other):
"""Returns true iff this tag is not identical to the other tag,
as defined in __eq__."""
return not self == other
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
"""Renders this tag as a string."""
return self.__str__(encoding)
def __unicode__(self):
return self.__str__(None)
BARE_AMPERSAND_OR_BRACKET = re.compile("([<>]|"
+ "&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)"
+ ")")
def _sub_entity(self, x):
"""Used with a regular expression to substitute the
appropriate XML entity for an XML special character."""
return "&" + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]] + ";"
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Returns a string or Unicode representation of this tag and
its contents. To get Unicode, pass None for encoding.
NOTE: since Python's HTML parser consumes whitespace, this
method is not certain to reproduce the whitespace present in
the original string."""
encodedName = self.toEncoding(self.name, encoding)
attrs = []
if self.attrs:
for key, val in self.attrs:
fmt = '%s="%s"'
if isString(val):
if self.containsSubstitutions and '%SOUP-ENCODING%' in val:
val = self.substituteEncoding(val, encoding)
# The attribute value either:
#
# * Contains no embedded double quotes or single quotes.
# No problem: we enclose it in double quotes.
# * Contains embedded single quotes. No problem:
# double quotes work here too.
# * Contains embedded double quotes. No problem:
# we enclose it in single quotes.
# * Embeds both single _and_ double quotes. This
# can't happen naturally, but it can happen if
# you modify an attribute value after parsing
# the document. Now we have a bit of a
# problem. We solve it by enclosing the
# attribute in single quotes, and escaping any
# embedded single quotes to XML entities.
if '"' in val:
fmt = "%s='%s'"
if "'" in val:
# TODO: replace with apos when
# appropriate.
val = val.replace("'", "&squot;")
# Now we're okay w/r/t quotes. But the attribute
# value might also contain angle brackets, or
# ampersands that aren't part of entities. We need
# to escape those to XML entities too.
val = self.BARE_AMPERSAND_OR_BRACKET.sub(self._sub_entity, val)
attrs.append(fmt % (self.toEncoding(key, encoding),
self.toEncoding(val, encoding)))
close = ''
closeTag = ''
if self.isSelfClosing:
close = ' /'
else:
closeTag = '</%s>' % encodedName
indentTag, indentContents = 0, 0
if prettyPrint:
indentTag = indentLevel
space = (' ' * (indentTag-1))
indentContents = indentTag + 1
contents = self.renderContents(encoding, prettyPrint, indentContents)
if self.hidden:
s = contents
else:
s = []
attributeString = ''
if attrs:
attributeString = ' ' + ' '.join(attrs)
if prettyPrint:
s.append(space)
s.append('<%s%s%s>' % (encodedName, attributeString, close))
if prettyPrint:
s.append("\n")
s.append(contents)
if prettyPrint and contents and contents[-1] != "\n":
s.append("\n")
if prettyPrint and closeTag:
s.append(space)
s.append(closeTag)
if prettyPrint and closeTag and self.nextSibling:
s.append("\n")
s = ''.join(s)
return s
def decompose(self):
"""Recursively destroys the contents of this tree."""
contents = [i for i in self.contents]
for i in contents:
if isinstance(i, Tag):
i.decompose()
else:
i.extract()
self.extract()
def prettify(self, encoding=DEFAULT_OUTPUT_ENCODING):
return self.__str__(encoding, True)
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING,
prettyPrint=False, indentLevel=0):
"""Renders the contents of this tag as a string in the given
encoding. If encoding is None, returns a Unicode string.."""
s=[]
for c in self:
text = None
if isinstance(c, NavigableString):
text = c.__str__(encoding)
elif isinstance(c, Tag):
s.append(c.__str__(encoding, prettyPrint, indentLevel))
if text and prettyPrint:
text = text.strip()
if text:
if prettyPrint:
s.append(" " * (indentLevel-1))
s.append(text)
if prettyPrint:
s.append("\n")
return ''.join(s)
#Soup methods
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.findAll(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
def findAll(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.recursiveChildGenerator
if not recursive:
generator = self.childGenerator
return self._findAll(name, attrs, text, limit, generator, **kwargs)
findChildren = findAll
# Pre-3.x compatibility methods
first = find
fetch = findAll
def fetchText(self, text=None, recursive=True, limit=None):
return self.findAll(text=text, recursive=recursive, limit=limit)
def firstText(self, text=None, recursive=True):
return self.find(text=text, recursive=recursive)
#Private methods
def _getAttrMap(self):
"""Initializes a map representation of this tag's attributes,
if not already initialized."""
if not getattr(self, 'attrMap'):
self.attrMap = {}
for (key, value) in self.attrs:
self.attrMap[key] = value
return self.attrMap
#Generator methods
def childGenerator(self):
for i in range(0, len(self.contents)):
yield self.contents[i]
raise StopIteration
def recursiveChildGenerator(self):
stack = [(self, 0)]
while stack:
tag, start = stack.pop()
if isinstance(tag, Tag):
for i in range(start, len(tag.contents)):
a = tag.contents[i]
yield a
if isinstance(a, Tag) and tag.contents:
if i < len(tag.contents) - 1:
stack.append((tag, i+1))
stack.append((a, 0))
break
raise StopIteration
# Next, a couple classes to represent queries and their results.
class SoupStrainer:
"""Encapsulates a number of ways of matching a markup element (tag or
text)."""
def __init__(self, name=None, attrs={}, text=None, **kwargs):
self.name = name
if isString(attrs):
kwargs['class'] = attrs
attrs = None
if kwargs:
if attrs:
attrs = attrs.copy()
attrs.update(kwargs)
else:
attrs = kwargs
self.attrs = attrs
self.text = text
def __str__(self):
if self.text:
return self.text
else:
return "%s|%s" % (self.name, self.attrs)
def searchTag(self, markupName=None, markupAttrs={}):
found = None
markup = None
if isinstance(markupName, Tag):
markup = markupName
markupAttrs = markup
callFunctionWithTagData = callable(self.name) \
and not isinstance(markupName, Tag)
if (not self.name) \
or callFunctionWithTagData \
or (markup and self._matches(markup, self.name)) \
or (not markup and self._matches(markupName, self.name)):
if callFunctionWithTagData:
match = self.name(markupName, markupAttrs)
else:
match = True
markupAttrMap = None
for attr, matchAgainst in self.attrs.items():
if not markupAttrMap:
if hasattr(markupAttrs, 'get'):
markupAttrMap = markupAttrs
else:
markupAttrMap = {}
for k,v in markupAttrs:
markupAttrMap[k] = v
attrValue = markupAttrMap.get(attr)
if not self._matches(attrValue, matchAgainst):
match = False
break
if match:
if markup:
found = markup
else:
found = markupName
return found
def search(self, markup):
#print 'looking for %s in %s' % (self, markup)
found = None
# If given a list of items, scan it for a text element that
# matches.
if isList(markup) and not isinstance(markup, Tag):
for element in markup:
if isinstance(element, NavigableString) \
and self.search(element):
found = element
break
# If it's a Tag, make sure its name or attributes match.
# Don't bother with Tags if we're searching for text.
elif isinstance(markup, Tag):
if not self.text:
found = self.searchTag(markup)
# If it's text, make sure the text matches.
elif isinstance(markup, NavigableString) or \
isString(markup):
if self._matches(markup, self.text):
found = markup
else:
raise Exception, "I don't know how to match against a %s" \
% markup.__class__
return found
def _matches(self, markup, matchAgainst):
#print "Matching %s against %s" % (markup, matchAgainst)
result = False
if matchAgainst == True and type(matchAgainst) == types.BooleanType:
result = markup != None
elif callable(matchAgainst):
result = matchAgainst(markup)
else:
#Custom match methods take the tag as an argument, but all
#other ways of matching match the tag name as a string.
if isinstance(markup, Tag):
markup = markup.name
if markup and not isString(markup):
markup = unicode(markup)
#Now we know that chunk is either a string, or None.
if hasattr(matchAgainst, 'match'):
# It's a regexp object.
result = markup and matchAgainst.search(markup)
elif isList(matchAgainst):
result = markup in matchAgainst
elif hasattr(matchAgainst, 'items'):
result = markup.has_key(matchAgainst)
elif matchAgainst and isString(markup):
if isinstance(markup, unicode):
matchAgainst = unicode(matchAgainst)
else:
matchAgainst = str(matchAgainst)
if not result:
result = matchAgainst == markup
return result
class ResultSet(list):
"""A ResultSet is just a list that keeps track of the SoupStrainer
that created it."""
def __init__(self, source):
list.__init__([])
self.source = source
# Now, some helper functions.
def isList(l):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is listlike."""
return hasattr(l, '__iter__') \
or (type(l) in (types.ListType, types.TupleType))
def isString(s):
"""Convenience method that works with all 2.x versions of Python
to determine whether or not something is stringlike."""
try:
return isinstance(s, unicode) or isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def buildTagMap(default, *args):
"""Turns a list of maps, lists, or scalars into a single map.
Used to build the SELF_CLOSING_TAGS, NESTABLE_TAGS, and
NESTING_RESET_TAGS maps out of lists and partial maps."""
built = {}
for portion in args:
if hasattr(portion, 'items'):
#It's a map. Merge it.
for k,v in portion.items():
built[k] = v
elif isList(portion):
#It's a list. Map each item to the default.
for k in portion:
built[k] = default
else:
#It's a scalar. Map it to the default.
built[portion] = default
return built
# Now, the parser classes.
class BeautifulStoneSoup(Tag, SGMLParser):
"""This class contains the basic parser and search code. It defines
a parser that knows nothing about tag behavior except for the
following:
You can't close a tag without closing all the tags it encloses.
That is, "<foo><bar></foo>" actually means
"<foo><bar></bar></foo>".
[Another possible explanation is "<foo><bar /></foo>", but since
this class defines no SELF_CLOSING_TAGS, it will never use that
explanation.]
This class is useful for parsing XML or made-up markup languages,
or when BeautifulSoup makes an assumption counter to what you were
expecting."""
SELF_CLOSING_TAGS = {}
NESTABLE_TAGS = {}
RESET_NESTING_TAGS = {}
QUOTE_TAGS = {}
PRESERVE_WHITESPACE_TAGS = []
MARKUP_MASSAGE = [(re.compile('(<[^<>]*)/>'),
lambda x: x.group(1) + ' />'),
(re.compile('<!\s+([^<>]*)>'),
lambda x: '<!' + x.group(1) + '>')
]
ROOT_TAG_NAME = u'[document]'
HTML_ENTITIES = "html"
XML_ENTITIES = "xml"
XHTML_ENTITIES = "xhtml"
# TODO: This only exists for backwards-compatibility
ALL_ENTITIES = XHTML_ENTITIES
# Used when determining whether a text node is all whitespace and
# can be replaced with a single space. A text node that contains
# fancy Unicode spaces (usually non-breaking) should be left
# alone.
STRIP_ASCII_SPACES = { 9: None, 10: None, 12: None, 13: None, 32: None, }
def __init__(self, markup="", parseOnlyThese=None, fromEncoding=None,
markupMassage=True, smartQuotesTo=XML_ENTITIES,
convertEntities=None, selfClosingTags=None, isHTML=False):
"""The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser.
sgmllib will process most bad HTML, and the BeautifulSoup
class has some tricks for dealing with some HTML that kills
sgmllib, but Beautiful Soup can nonetheless choke or lose data
if your data uses self-closing tags or declarations
incorrectly.
By default, Beautiful Soup uses regexes to sanitize input,
avoiding the vast majority of these problems. If the problems
don't apply to you, pass in False for markupMassage, and
you'll get better performance.
The default parser massage techniques fix the two most common
instances of invalid HTML that choke sgmllib:
<br/> (No space between name of closing tag and tag close)
<! --Comment--> (Extraneous whitespace in declaration)
You can pass in a custom list of (RE object, replace method)
tuples to get Beautiful Soup to scrub your input the way you
want."""
self.parseOnlyThese = parseOnlyThese
self.fromEncoding = fromEncoding
self.smartQuotesTo = smartQuotesTo
self.convertEntities = convertEntities
# Set the rules for how we'll deal with the entities we
# encounter
if self.convertEntities:
# It doesn't make sense to convert encoded characters to
# entities even while you're converting entities to Unicode.
# Just convert it all to Unicode.
self.smartQuotesTo = None
if convertEntities == self.HTML_ENTITIES:
self.convertXMLEntities = False
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = True
elif convertEntities == self.XHTML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = True
self.escapeUnrecognizedEntities = False
elif convertEntities == self.XML_ENTITIES:
self.convertXMLEntities = True
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
else:
self.convertXMLEntities = False
self.convertHTMLEntities = False
self.escapeUnrecognizedEntities = False
self.instanceSelfClosingTags = buildTagMap(None, selfClosingTags)
SGMLParser.__init__(self)
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
self.markup = markup
self.markupMassage = markupMassage
try:
self._feed(isHTML=isHTML)
except StopParsing:
pass
self.markup = None # The markup can now be GCed
def convert_charref(self, name):
"""This method fixes a bug in Python's SGMLParser."""
try:
n = int(name)
except ValueError:
return
if not 0 <= n <= 127 : # ASCII ends at 127, not 255
return
return self.convert_codepoint(n)
def _feed(self, inDocumentEncoding=None, isHTML=False):
# Convert the document to Unicode.
markup = self.markup
if isinstance(markup, unicode):
if not hasattr(self, 'originalEncoding'):
self.originalEncoding = None
else:
dammit = UnicodeDammit\
(markup, [self.fromEncoding, inDocumentEncoding],
smartQuotesTo=self.smartQuotesTo, isHTML=isHTML)
markup = dammit.unicode
self.originalEncoding = dammit.originalEncoding
self.declaredHTMLEncoding = dammit.declaredHTMLEncoding
if markup:
if self.markupMassage:
if not isList(self.markupMassage):
self.markupMassage = self.MARKUP_MASSAGE
for fix, m in self.markupMassage:
markup = fix.sub(m, markup)
# TODO: We get rid of markupMassage so that the
# soup object can be deepcopied later on. Some
# Python installations can't copy regexes. If anyone
# was relying on the existence of markupMassage, this
# might cause problems.
del(self.markupMassage)
self.reset()
SGMLParser.feed(self, markup)
# Close out any unfinished strings and close all the open tags.
self.endData()
while self.currentTag.name != self.ROOT_TAG_NAME:
self.popTag()
def __getattr__(self, methodName):
"""This method routes method call requests to either the SGMLParser
superclass or the Tag superclass, depending on the method name."""
#print "__getattr__ called on %s.%s" % (self.__class__, methodName)
if methodName.find('start_') == 0 or methodName.find('end_') == 0 \
or methodName.find('do_') == 0:
return SGMLParser.__getattr__(self, methodName)
elif methodName.find('__') != 0:
return Tag.__getattr__(self, methodName)
else:
raise AttributeError
def isSelfClosingTag(self, name):
"""Returns true iff the given string is the name of a
self-closing tag according to this parser."""
return self.SELF_CLOSING_TAGS.has_key(name) \
or self.instanceSelfClosingTags.has_key(name)
def reset(self):
Tag.__init__(self, self, self.ROOT_TAG_NAME)
self.hidden = 1
SGMLParser.reset(self)
self.currentData = []
self.currentTag = None
self.tagStack = []
self.quoteStack = []
self.pushTag(self)
def popTag(self):
tag = self.tagStack.pop()
# Tags with just one string-owning child get the child as a
# 'string' property, so that soup.tag.string is shorthand for
# soup.tag.contents[0]
if len(self.currentTag.contents) == 1 and \
isinstance(self.currentTag.contents[0], NavigableString):
self.currentTag.string = self.currentTag.contents[0]
#print "Pop", tag.name
if self.tagStack:
self.currentTag = self.tagStack[-1]
return self.currentTag
def pushTag(self, tag):
#print "Push", tag.name
if self.currentTag:
self.currentTag.contents.append(tag)
self.tagStack.append(tag)
self.currentTag = self.tagStack[-1]
def endData(self, containerClass=NavigableString):
if self.currentData:
currentData = u''.join(self.currentData)
if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and
not set([tag.name for tag in self.tagStack]).intersection(
self.PRESERVE_WHITESPACE_TAGS)):
if '\n' in currentData:
currentData = '\n'
else:
currentData = ' '
self.currentData = []
if self.parseOnlyThese and len(self.tagStack) <= 1 and \
(not self.parseOnlyThese.text or \
not self.parseOnlyThese.search(currentData)):
return
o = containerClass(currentData)
o.setup(self.currentTag, self.previous)
if self.previous:
self.previous.next = o
self.previous = o
self.currentTag.contents.append(o)
def _popToTag(self, name, inclusivePop=True):
"""Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag."""
#print "Popping to %s" % name
if name == self.ROOT_TAG_NAME:
return
numPops = 0
mostRecentTag = None
for i in range(len(self.tagStack)-1, 0, -1):
if name == self.tagStack[i].name:
numPops = len(self.tagStack)-i
break
if not inclusivePop:
numPops = numPops - 1
for i in range(0, numPops):
mostRecentTag = self.popTag()
return mostRecentTag
def _smartPop(self, name):
"""We need to pop up to the previous tag of this type, unless
one of this tag's nesting reset triggers comes between this
tag and the previous tag of this type, OR unless this tag is a
generic nesting trigger and another generic nesting trigger
comes between this tag and the previous tag of this type.
Examples:
<p>Foo<b>Bar *<p>* should pop to 'p', not 'b'.
<p>Foo<table>Bar *<p>* should pop to 'table', not 'p'.
<p>Foo<table><tr>Bar *<p>* should pop to 'tr', not 'p'.
<li><ul><li> *<li>* should pop to 'ul', not the first 'li'.
<tr><table><tr> *<tr>* should pop to 'table', not the first 'tr'
<td><tr><td> *<td>* should pop to 'tr', not the first 'td'
"""
nestingResetTriggers = self.NESTABLE_TAGS.get(name)
isNestable = nestingResetTriggers != None
isResetNesting = self.RESET_NESTING_TAGS.has_key(name)
popTo = None
inclusive = True
for i in range(len(self.tagStack)-1, 0, -1):
p = self.tagStack[i]
if (not p or p.name == name) and not isNestable:
#Non-nestable tags get popped to the top or to their
#last occurance.
popTo = name
break
if (nestingResetTriggers != None
and p.name in nestingResetTriggers) \
or (nestingResetTriggers == None and isResetNesting
and self.RESET_NESTING_TAGS.has_key(p.name)):
#If we encounter one of the nesting reset triggers
#peculiar to this tag, or we encounter another tag
#that causes nesting to reset, pop up to but not
#including that tag.
popTo = p.name
inclusive = False
break
p = p.parent
if popTo:
self._popToTag(popTo, inclusive)
def unknown_starttag(self, name, attrs, selfClosing=0):
#print "Start tag %s: %s" % (name, attrs)
if self.quoteStack:
#This is not a real tag.
#print "<%s> is not real!" % name
attrs = ''.join(map(lambda(x, y): ' %s="%s"' % (x, y), attrs))
self.handle_data('<%s%s>' % (name, attrs))
return
self.endData()
if not self.isSelfClosingTag(name) and not selfClosing:
self._smartPop(name)
if self.parseOnlyThese and len(self.tagStack) <= 1 \
and (self.parseOnlyThese.text or not self.parseOnlyThese.searchTag(name, attrs)):
return
tag = Tag(self, name, attrs, self.currentTag, self.previous)
if self.previous:
self.previous.next = tag
self.previous = tag
self.pushTag(tag)
if selfClosing or self.isSelfClosingTag(name):
self.popTag()
if name in self.QUOTE_TAGS:
#print "Beginning quote (%s)" % name
self.quoteStack.append(name)
self.literal = 1
return tag
def unknown_endtag(self, name):
#print "End tag %s" % name
if self.quoteStack and self.quoteStack[-1] != name:
#This is not a real end tag.
#print "</%s> is not real!" % name
self.handle_data('</%s>' % name)
return
self.endData()
self._popToTag(name)
if self.quoteStack and self.quoteStack[-1] == name:
self.quoteStack.pop()
self.literal = (len(self.quoteStack) > 0)
def handle_data(self, data):
self.currentData.append(data)
def _toStringSubclass(self, text, subclass):
"""Adds a certain piece of text to the tree as a NavigableString
subclass."""
self.endData()
self.handle_data(text)
self.endData(subclass)
def handle_pi(self, text):
"""Handle a processing instruction as a ProcessingInstruction
object, possibly one with a %SOUP-ENCODING% slot into which an
encoding will be plugged later."""
if text[:3] == "xml":
text = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
self._toStringSubclass(text, ProcessingInstruction)
def handle_comment(self, text):
"Handle comments as Comment objects."
self._toStringSubclass(text, Comment)
def handle_charref(self, ref):
"Handle character references as data."
if self.convertEntities:
data = unichr(int(ref))
else:
data = '&#%s;' % ref
self.handle_data(data)
def handle_entityref(self, ref):
"""Handle entity references as data, possibly converting known
HTML and/or XML entity references to the corresponding Unicode
characters."""
data = None
if self.convertHTMLEntities:
try:
data = unichr(name2codepoint[ref])
except KeyError:
pass
if not data and self.convertXMLEntities:
data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref)
if not data and self.convertHTMLEntities and \
not self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref):
# TODO: We've got a problem here. We're told this is
# an entity reference, but it's not an XML entity
# reference or an HTML entity reference. Nonetheless,
# the logical thing to do is to pass it through as an
# unrecognized entity reference.
#
# Except: when the input is "&carol;" this function
# will be called with input "carol". When the input is
# "AT&T", this function will be called with input
# "T". We have no way of knowing whether a semicolon
# was present originally, so we don't know whether
# this is an unknown entity or just a misplaced
# ampersand.
#
# The more common case is a misplaced ampersand, so I
# escape the ampersand and omit the trailing semicolon.
data = "&%s" % ref
if not data:
# This case is different from the one above, because we
# haven't already gone through a supposedly comprehensive
# mapping of entities to Unicode characters. We might not
# have gone through any mapping at all. So the chances are
# very high that this is a real entity, and not a
# misplaced ampersand.
data = "&%s;" % ref
self.handle_data(data)
def handle_decl(self, data):
"Handle DOCTYPEs and the like as Declaration objects."
self._toStringSubclass(data, Declaration)
def parse_declaration(self, i):
"""Treat a bogus SGML declaration as raw data. Treat a CDATA
declaration as a CData object."""
j = None
if self.rawdata[i:i+9] == '<![CDATA[':
k = self.rawdata.find(']]>', i)
if k == -1:
k = len(self.rawdata)
data = self.rawdata[i+9:k]
j = k+3
self._toStringSubclass(data, CData)
else:
try:
j = SGMLParser.parse_declaration(self, i)
except SGMLParseError:
toHandle = self.rawdata[i:]
self.handle_data(toHandle)
j = i + len(toHandle)
return j
class BeautifulSoup(BeautifulStoneSoup):
"""This parser knows the following facts about HTML:
* Some tags have no closing tag and should be interpreted as being
closed as soon as they are encountered.
* The text inside some tags (ie. 'script') may contain tags which
are not really part of the document and which should be parsed
as text, not tags. If you want to parse the text as tags, you can
always fetch it and parse it explicitly.
* Tag nesting rules:
Most tags can't be nested at all. For instance, the occurance of
a <p> tag should implicitly close the previous <p> tag.
<p>Para1<p>Para2
should be transformed into:
<p>Para1</p><p>Para2
Some tags can be nested arbitrarily. For instance, the occurance
of a <blockquote> tag should _not_ implicitly close the previous
<blockquote> tag.
Alice said: <blockquote>Bob said: <blockquote>Blah
should NOT be transformed into:
Alice said: <blockquote>Bob said: </blockquote><blockquote>Blah
Some tags can be nested, but the nesting is reset by the
interposition of other tags. For instance, a <tr> tag should
implicitly close the previous <tr> tag within the same <table>,
but not close a <tr> tag in another table.
<table><tr>Blah<tr>Blah
should be transformed into:
<table><tr>Blah</tr><tr>Blah
but,
<tr>Blah<table><tr>Blah
should NOT be transformed into
<tr>Blah<table></tr><tr>Blah
Differing assumptions about tag nesting rules are a major source
of problems with the BeautifulSoup class. If BeautifulSoup is not
treating as nestable a tag your page author treats as nestable,
try ICantBelieveItsBeautifulSoup, MinimalSoup, or
BeautifulStoneSoup before writing your own subclass."""
def __init__(self, *args, **kwargs):
if not kwargs.has_key('smartQuotesTo'):
kwargs['smartQuotesTo'] = self.HTML_ENTITIES
kwargs['isHTML'] = True
BeautifulStoneSoup.__init__(self, *args, **kwargs)
SELF_CLOSING_TAGS = buildTagMap(None,
['br' , 'hr', 'input', 'img', 'meta',
'spacer', 'link', 'frame', 'base'])
PRESERVE_WHITESPACE_TAGS = set(['pre', 'textarea'])
QUOTE_TAGS = {'script' : None, 'textarea' : None}
#According to the HTML standard, each of these inline tags can
#contain another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_INLINE_TAGS = ['span', 'font', 'q', 'object', 'bdo', 'sub', 'sup',
'center']
#According to the HTML standard, these block tags can contain
#another tag of the same type. Furthermore, it's common
#to actually use these tags this way.
NESTABLE_BLOCK_TAGS = ['blockquote', 'div', 'fieldset', 'ins', 'del']
#Lists can contain other lists, but there are restrictions.
NESTABLE_LIST_TAGS = { 'ol' : [],
'ul' : [],
'li' : ['ul', 'ol'],
'dl' : [],
'dd' : ['dl'],
'dt' : ['dl'] }
#Tables can contain other tables, but there are restrictions.
NESTABLE_TABLE_TAGS = {'table' : [],
'tr' : ['table', 'tbody', 'tfoot', 'thead'],
'td' : ['tr'],
'th' : ['tr'],
'thead' : ['table'],
'tbody' : ['table'],
'tfoot' : ['table'],
}
NON_NESTABLE_BLOCK_TAGS = ['address', 'form', 'p', 'pre']
#If one of these tags is encountered, all tags up to the next tag of
#this type are popped.
RESET_NESTING_TAGS = buildTagMap(None, NESTABLE_BLOCK_TAGS, 'noscript',
NON_NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS,
NESTABLE_TABLE_TAGS)
NESTABLE_TAGS = buildTagMap([], NESTABLE_INLINE_TAGS, NESTABLE_BLOCK_TAGS,
NESTABLE_LIST_TAGS, NESTABLE_TABLE_TAGS)
# Used to detect the charset in a META tag; see start_meta
CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M)
def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSubstitution = False
for i in range(0, len(attrs)):
key, value = attrs[i]
key = key.lower()
if key == 'http-equiv':
httpEquiv = value
elif key == 'content':
contentType = value
contentTypeIndex = i
if httpEquiv and contentType: # It's an interesting meta tag.
match = self.CHARSET_RE.search(contentType)
if match:
if (self.declaredHTMLEncoding is not None or
self.originalEncoding == self.fromEncoding):
# An HTML encoding was sniffed while converting
# the document to Unicode, or an HTML encoding was
# sniffed during a previous pass through the
# document, or an encoding was specified
# explicitly and it worked. Rewrite the meta tag.
def rewrite(match):
return match.group(1) + "%SOUP-ENCODING%"
newAttr = self.CHARSET_RE.sub(rewrite, contentType)
attrs[contentTypeIndex] = (attrs[contentTypeIndex][0],
newAttr)
tagNeedsEncodingSubstitution = True
else:
# This is our first pass through the document.
# Go through it again with the encoding information.
newCharset = match.group(3)
if newCharset and newCharset != self.originalEncoding:
self.declaredHTMLEncoding = newCharset
self._feed(self.declaredHTMLEncoding)
raise StopParsing
pass
tag = self.unknown_starttag("meta", attrs)
if tag and tagNeedsEncodingSubstitution:
tag.containsSubstitutions = True
class StopParsing(Exception):
pass
class ICantBelieveItsBeautifulSoup(BeautifulSoup):
"""The BeautifulSoup class is oriented towards skipping over
common HTML errors like unclosed tags. However, sometimes it makes
errors of its own. For instance, consider this fragment:
<b>Foo<b>Bar</b></b>
This is perfectly valid (if bizarre) HTML. However, the
BeautifulSoup class will implicitly close the first b tag when it
encounters the second 'b'. It will think the author wrote
"<b>Foo<b>Bar", and didn't close the first 'b' tag, because
there's no real-world reason to bold something that's already
bold. When it encounters '</b></b>' it will close two more 'b'
tags, for a grand total of three tags closed instead of two. This
can throw off the rest of your document structure. The same is
true of a number of other tags, listed below.
It's much more common for someone to forget to close a 'b' tag
than to actually use nested 'b' tags, and the BeautifulSoup class
handles the common case. This class handles the not-co-common
case: where you can't believe someone wrote what they did, but
it's valid HTML and BeautifulSoup screwed up by assuming it
wouldn't be."""
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS = \
['em', 'big', 'i', 'small', 'tt', 'abbr', 'acronym', 'strong',
'cite', 'code', 'dfn', 'kbd', 'samp', 'strong', 'var', 'b',
'big']
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS = ['noscript']
NESTABLE_TAGS = buildTagMap([], BeautifulSoup.NESTABLE_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_BLOCK_TAGS,
I_CANT_BELIEVE_THEYRE_NESTABLE_INLINE_TAGS)
class MinimalSoup(BeautifulSoup):
"""The MinimalSoup class is for parsing HTML that contains
pathologically bad markup. It makes no assumptions about tag
nesting, but it does know which tags are self-closing, that
<script> tags contain Javascript and should not be parsed, that
META tags may contain encoding information, and so on.
This also makes it better for subclassing than BeautifulStoneSoup
or BeautifulSoup."""
RESET_NESTING_TAGS = buildTagMap('noscript')
NESTABLE_TAGS = {}
class BeautifulSOAP(BeautifulStoneSoup):
"""This class will push a tag with only a single string child into
the tag's parent as an attribute. The attribute's name is the tag
name, and the value is the string child. An example should give
the flavor of the change:
<foo><bar>baz</bar></foo>
=>
<foo bar="baz"><bar>baz</bar></foo>
You can then access fooTag['bar'] instead of fooTag.barTag.string.
This is, of course, useful for scraping structures that tend to
use subelements instead of attributes, such as SOAP messages. Note
that it modifies its input, so don't print the modified version
out.
I'm not sure how many people really want to use this class; let me
know if you do. Mainly I like the name."""
def popTag(self):
if len(self.tagStack) > 1:
tag = self.tagStack[-1]
parent = self.tagStack[-2]
parent._getAttrMap()
if (isinstance(tag, Tag) and len(tag.contents) == 1 and
isinstance(tag.contents[0], NavigableString) and
not parent.attrMap.has_key(tag.name)):
parent[tag.name] = tag.contents[0]
BeautifulStoneSoup.popTag(self)
#Enterprise class names! It has come to our attention that some people
#think the names of the Beautiful Soup parser classes are too silly
#and "unprofessional" for use in enterprise screen-scraping. We feel
#your pain! For such-minded folk, the Beautiful Soup Consortium And
#All-Night Kosher Bakery recommends renaming this file to
#"RobustParser.py" (or, in cases of extreme enterprisiness,
#"RobustParserBeanInterface.class") and using the following
#enterprise-friendly class aliases:
class RobustXMLParser(BeautifulStoneSoup):
pass
class RobustHTMLParser(BeautifulSoup):
pass
class RobustWackAssHTMLParser(ICantBelieveItsBeautifulSoup):
pass
class RobustInsanelyWackAssHTMLParser(MinimalSoup):
pass
class SimplifyingSOAPParser(BeautifulSOAP):
pass
######################################################
#
# Bonus library: Unicode, Dammit
#
# This class forces XML data into a standard format (usually to UTF-8
# or Unicode). It is heavily based on code from Mark Pilgrim's
# Universal Feed Parser. It does not rewrite the XML or HTML to
# reflect a new encoding: that happens in BeautifulStoneSoup.handle_pi
# (XML) and BeautifulSoup.start_meta (HTML).
# Autodetects character encodings.
# Download from http://chardet.feedparser.org/
try:
import chardet
# import chardet.constants
# chardet.constants._debug = 1
except ImportError:
chardet = None
# cjkcodecs and iconv_codec make Python know about more character encodings.
# Both are available from http://cjkpython.i18n.org/
# They're built in if you use Python 2.4.
try:
import cjkcodecs.aliases
except ImportError:
pass
try:
import iconv_codec
except ImportError:
pass
class UnicodeDammit:
"""A class for detecting the encoding of a *ML document and
converting it to a Unicode string. If the source encoding is
windows-1252, can replace MS smart quotes with their HTML or XML
equivalents."""
# This dictionary maps commonly seen values for "charset" in HTML
# meta tags to the corresponding Python codec names. It only covers
# values that aren't in Python's aliases and can't be determined
# by the heuristics in find_codec.
CHARSET_ALIASES = { "macintosh" : "mac-roman",
"x-sjis" : "shift-jis" }
def __init__(self, markup, overrideEncodings=[],
smartQuotesTo='xml', isHTML=False):
self.declaredHTMLEncoding = None
self.markup, documentEncoding, sniffedEncoding = \
self._detectEncoding(markup, isHTML)
self.smartQuotesTo = smartQuotesTo
self.triedEncodings = []
if markup == '' or isinstance(markup, unicode):
self.originalEncoding = None
self.unicode = unicode(markup)
return
u = None
for proposedEncoding in overrideEncodings:
u = self._convertFrom(proposedEncoding)
if u: break
if not u:
for proposedEncoding in (documentEncoding, sniffedEncoding):
u = self._convertFrom(proposedEncoding)
if u: break
# If no luck and we have auto-detection library, try that:
if not u and chardet and not isinstance(self.markup, unicode):
u = self._convertFrom(chardet.detect(self.markup)['encoding'])
# As a last resort, try utf-8 and windows-1252:
if not u:
for proposed_encoding in ("utf-8", "windows-1252"):
u = self._convertFrom(proposed_encoding)
if u: break
self.unicode = u
if not u: self.originalEncoding = None
def _subMSChar(self, orig):
"""Changes a MS smart quote character to an XML or HTML
entity."""
sub = self.MS_CHARS.get(orig)
if type(sub) == types.TupleType:
if self.smartQuotesTo == 'xml':
sub = '&#x%s;' % sub[1]
else:
sub = '&%s;' % sub[0]
return sub
def _convertFrom(self, proposed):
proposed = self.find_codec(proposed)
if not proposed or proposed in self.triedEncodings:
return None
self.triedEncodings.append(proposed)
markup = self.markup
# Convert smart quotes to HTML if coming from an encoding
# that might have them.
if self.smartQuotesTo and proposed.lower() in("windows-1252",
"iso-8859-1",
"iso-8859-2"):
markup = re.compile("([\x80-\x9f])").sub \
(lambda(x): self._subMSChar(x.group(1)),
markup)
try:
# print "Trying to convert document to %s" % proposed
u = self._toUnicode(markup, proposed)
self.markup = u
self.originalEncoding = proposed
except Exception, e:
# print "That didn't work!"
# print e
return None
#print "Correct encoding: %s" % proposed
return self.markup
def _toUnicode(self, data, encoding):
'''Given a string and its encoding, decodes the string into Unicode.
%encoding is a string recognized by encodings.aliases'''
# strip Byte Order Mark (if present)
if (len(data) >= 4) and (data[:2] == '\xfe\xff') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16be'
data = data[2:]
elif (len(data) >= 4) and (data[:2] == '\xff\xfe') \
and (data[2:4] != '\x00\x00'):
encoding = 'utf-16le'
data = data[2:]
elif data[:3] == '\xef\xbb\xbf':
encoding = 'utf-8'
data = data[3:]
elif data[:4] == '\x00\x00\xfe\xff':
encoding = 'utf-32be'
data = data[4:]
elif data[:4] == '\xff\xfe\x00\x00':
encoding = 'utf-32le'
data = data[4:]
newdata = unicode(data, encoding)
return newdata
def _detectEncoding(self, xml_data, isHTML=False):
"""Given a document, tries to detect its XML encoding."""
xml_encoding = sniffed_xml_encoding = None
try:
if xml_data[:4] == '\x4c\x6f\xa7\x94':
# EBCDIC
xml_data = self._ebcdic_to_ascii(xml_data)
elif xml_data[:4] == '\x00\x3c\x00\x3f':
# UTF-16BE
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') \
and (xml_data[2:4] != '\x00\x00'):
# UTF-16BE with BOM
sniffed_xml_encoding = 'utf-16be'
xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x3f\x00':
# UTF-16LE
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and \
(xml_data[2:4] != '\x00\x00'):
# UTF-16LE with BOM
sniffed_xml_encoding = 'utf-16le'
xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\x00\x3c':
# UTF-32BE
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\x3c\x00\x00\x00':
# UTF-32LE
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
elif xml_data[:4] == '\x00\x00\xfe\xff':
# UTF-32BE with BOM
sniffed_xml_encoding = 'utf-32be'
xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
elif xml_data[:4] == '\xff\xfe\x00\x00':
# UTF-32LE with BOM
sniffed_xml_encoding = 'utf-32le'
xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
elif xml_data[:3] == '\xef\xbb\xbf':
# UTF-8 with BOM
sniffed_xml_encoding = 'utf-8'
xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
else:
sniffed_xml_encoding = 'ascii'
pass
except:
xml_encoding_match = None
xml_encoding_match = re.compile(
'^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
if not xml_encoding_match and isHTML:
regexp = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
xml_encoding_match = regexp.search(xml_data)
if xml_encoding_match is not None:
xml_encoding = xml_encoding_match.groups()[0].lower()
if isHTML:
self.declaredHTMLEncoding = xml_encoding
if sniffed_xml_encoding and \
(xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
'iso-10646-ucs-4', 'ucs-4', 'csucs4',
'utf-16', 'utf-32', 'utf_16', 'utf_32',
'utf16', 'u16')):
xml_encoding = sniffed_xml_encoding
print "xmldata="+xml_data
print "encoding="+xml_encoding
print "sniffed encoding="+sniffed_xml_encoding
return xml_data, xml_encoding, sniffed_xml_encoding
def find_codec(self, charset):
return self._codec(self.CHARSET_ALIASES.get(charset, charset)) \
or (charset and self._codec(charset.replace("-", ""))) \
or (charset and self._codec(charset.replace("-", "_"))) \
or charset
def _codec(self, charset):
if not charset: return charset
codec = None
try:
codecs.lookup(charset)
codec = charset
except (LookupError, ValueError):
pass
return codec
EBCDIC_TO_ASCII_MAP = None
def _ebcdic_to_ascii(self, s):
c = self.__class__
if not c.EBCDIC_TO_ASCII_MAP:
emap = (0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,
201,202,106,107,108,109,110,111,112,113,114,203,204,205,
206,207,208,209,126,115,116,117,118,119,120,121,122,210,
211,212,213,214,215,216,217,218,219,220,221,222,223,224,
225,226,227,228,229,230,231,123,65,66,67,68,69,70,71,72,
73,232,233,234,235,236,237,125,74,75,76,77,78,79,80,81,
82,238,239,240,241,242,243,92,159,83,84,85,86,87,88,89,
90,244,245,246,247,248,249,48,49,50,51,52,53,54,55,56,57,
250,251,252,253,254,255)
import string
c.EBCDIC_TO_ASCII_MAP = string.maketrans( \
''.join(map(chr, range(256))), ''.join(map(chr, emap)))
return s.translate(c.EBCDIC_TO_ASCII_MAP)
MS_CHARS = { '\x80' : ('euro', '20AC'),
'\x81' : ' ',
'\x82' : ('sbquo', '201A'),
'\x83' : ('fnof', '192'),
'\x84' : ('bdquo', '201E'),
'\x85' : ('hellip', '2026'),
'\x86' : ('dagger', '2020'),
'\x87' : ('Dagger', '2021'),
'\x88' : ('circ', '2C6'),
'\x89' : ('permil', '2030'),
'\x8A' : ('Scaron', '160'),
'\x8B' : ('lsaquo', '2039'),
'\x8C' : ('OElig', '152'),
'\x8D' : '?',
'\x8E' : ('#x17D', '17D'),
'\x8F' : '?',
'\x90' : '?',
'\x91' : ('lsquo', '2018'),
'\x92' : ('rsquo', '2019'),
'\x93' : ('ldquo', '201C'),
'\x94' : ('rdquo', '201D'),
'\x95' : ('bull', '2022'),
'\x96' : ('ndash', '2013'),
'\x97' : ('mdash', '2014'),
'\x98' : ('tilde', '2DC'),
'\x99' : ('trade', '2122'),
'\x9a' : ('scaron', '161'),
'\x9b' : ('rsaquo', '203A'),
'\x9c' : ('oelig', '153'),
'\x9d' : '?',
'\x9e' : ('#x17E', '17E'),
'\x9f' : ('Yuml', ''),}
#######################################################################
#By default, act as an HTML pretty-printer.
if __name__ == '__main__':
import sys
soup = BeautifulSoup(sys.stdin)
print soup.prettify()
| Python |
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from httpWidget import Ui_HttpWidget
import os
class httpWidget(QtGui.QWidget):
def __init__(self, parent=None):
self.isParametersValid=True
self.currentPage = ''
self.currentPageNumber = 0
self.lastPageNumber=0
self.lastDownloadResult = True
super(httpWidget, self).__init__(parent)
self.ui = Ui_HttpWidget()
self.ui.setupUi(self)
self.ui.url_2.setReadOnly(True)
QtCore.QObject.connect(self.ui.webView, QtCore.SIGNAL("loadProgress (int)"), self.displayLoadProgress)
QtCore.QObject.connect(self.ui.webView, QtCore.SIGNAL("loadFinished (bool)"), self.processHtml)
QtCore.QObject.connect(self.ui.reload_2, QtCore.SIGNAL("clicked()"), self.start)
QtCore.QObject.connect(self.ui.url_3, QtCore.SIGNAL("textChanged (const QString&)"), self.calculateFinalPage)
QtCore.QObject.connect(self.ui.spinBox, QtCore.SIGNAL("valueChanged (const QString&)"), self.onSpinBoxChange)
QtCore.QMetaObject.connectSlotsByName(self)
def calculateFinalPage(self, urlName):
text = urlName + str(self.ui.spinBox.value())
self.ui.url_2.setText(text)
def onSpinBoxChange(self, value):
self.calculateFinalPage(self.ui.url_3.text())
def displayLoadProgress(self, progress):
text = self.trUtf8("""Закачиваем страницу для конвертации: Прогресс """) + str(progress) + "%"
self.ui.label.setText("<font color='" + "blue" + "'>" + text + "</font>")
label2text=self.trUtf8("Текущая страница: ")+self.currentPage
self.ui.label_5.setText("<font color='" + "blue" + "'>" + label2text + "</font>")
def start(self):
self.isParametersValid=True
if (self.ui.url_2.text()) == '':
self.setLabelText("Заполните название страницы для скачки", "red")
self.isParametersValid=False
if (self.ui.url_4.text()) == '':
self.setLabelText("Укажите файл для сохранения книги", "red")
self.isParametersValid=False
if self.isParametersValid:
unicodeName=self.trUtf8(self.ui.url_4.text())
bookfilename=str(unicodeName)
if os.path.exists(bookfilename):
os.remove(bookfilename)
self.currentPageNumber=self.ui.spinBox.value()
self.lastPageNumber=self.ui.spinBox_2.value()
self.loadNextPage()
def setLabelText(self, text, color):
text = self.trUtf8(text)
self.ui.label.setText("<font color='" + color + "'>" + text + "</font>")
def loadNextPage(self):
if self.currentPageNumber<=self.lastPageNumber:
self.currentPage = self.ui.url_3.text()+ str(self.currentPageNumber)
self.ui.webView.setUrl(QtCore.QUrl(self.currentPage))
else:
self.setLabelText("Конвертация всех страниц закончена", "blue")
def processHtml(self, result):
if result:
self.setLabelText("Стартуем конвертацию страницы", "blue")
text = self.ui.webView.page().mainFrame().toHtml()
merger = HtmlMerger()
text=unicode(text)
text = merger.getTextFromHtml(text)
filename=unicode(self.ui.url_4.text())
file = open(filename, 'a')
file.write(text)
file.close()
self.setLabelText("Страница успешно конвертирована", "blue")
else:
self.setLabelText("Закачка страницы не удалась", "blue")
self.lastDownloadResult = result
self.currentPageNumber=self.currentPageNumber+1
self.loadNextPage()
class HtmlMerger():
def getTextFromHtml(self, htmlText):
from BeautifulSoup import BeautifulSoup
html=htmlText.encode("utf-8")
soup = BeautifulSoup(html)
table = soup.find('table', id="onlineread_host")
import re
out = ''
for row in table.findAll(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'p']):
out = out + self.clean(row) + "\n"
return out
def clean(self, val):
import re
val = str(val)
val = re.sub(r'<br.*?>', "\n", val) #remove annoying spans
val = re.sub(r'<span class=.*?>*?</span>', '', val) #remove annoying spans
val = re.sub(r'<.*?>', '', val) #remove tags
val = re.sub(r' ', '', val) #remove defises
val = re.sub(r'следующий лист >>', '', val) #remove defises
val = re.sub(r'<< предыдущий лист', '', val) #remove defises
return val
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = httpWidget()
myapp.show()
sys.exit(app.exec_())
| Python |
import sys
import folc
from PyQt4 import QtCore, QtGui
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = httpWidget()
myapp.show()
sys.exit(app.exec_()) | Python |
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class fm_command:
"""A simple example class"""
def help(self):
return 'fm_command help'
def on_msg(self,msg):
print (msg)
if __name__=="__main__":
a = fm_command()
a.help()
| Python |
#!/usr/bin/env python
from Tkinter import *
root = Tk()
def key(event):
print "pressed", repr(event.char)
def callback(event):
frame.focus_set()
print "clicked at", event.x, event.y
frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
| Python |
# Echo server program
import socket
import sys
HOST = None # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.bind(sa)
s.listen(1)
except socket.error as msg:
s.close()
s = None
continue
break
if s is None:
print 'could not open socket'
sys.exit(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
| Python |
#!/usr/bin/env python
import cv2.cv as cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class fmUIdemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(0) # Capture image from device "0"
cv.NamedWindow( "fmUIdemo", 1 )
cv.NamedWindow( "fmProcessed", 1 )
cv.SetMouseCallback( "fmUIdemo", self.on_mouse)
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
print( "Keys:\n"
" ESC - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
def run(self):
while True:
frame = cv.QueryFrame( self.capture )
# If mouse is pressed, highlight the current selected rectangle
# and recompute the fmProcessed
c = cv.WaitKey(7) % 0x100
if c == 27:
break
elif c == ord("b"):
backproject_mode = not backproject_mode
elif c<> 0xff:
print c
if __name__=="__main__":
demo = fmUIdemo()
demo.run()
cv.DestroyAllWindows()
| Python |
import sys
print "hello world 11"
| Python |
#!/usr/bin/env python
import cv2.cv as cv
import numpy as np
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class fmTrackingDemo:
def __init__(self):
self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 2, 2)
cv.NamedWindow( "fmTracking_Preview_Window", 1 )
cv.NamedWindow( "fmTracking_Output_Window", 1 )
cv.SetMouseCallback( "fmTracking_Preview_Window", self.on_mouse)
self.__myStr=''
self.__myTerm='\r'
self.__myCmd=''
self.__myState=0
self.filename=''
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
self.selection = (0,0,0,0)
print( "Keys:\n"
" EXIT - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def set_capture_resolution(self, width, height):
self.capture = cv.CaptureFromCAM(1)
self.preview_scale = 0.5
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height)
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, width)
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FORMAT, cv.IPL_DEPTH_32F)
def set_capture_file(self,filename):
self.preview_scale = 1
self.filename = filename
def on_msgArrival(self,iStr):
self.__myStr += iStr
pos = self.__myStr.find(self.__myTerm)
while (pos >=0):
self.on_Command(self.__myStr[0:pos])
self.__myStr=self.__myStr[pos+1:len(self.__myStr)]
pos = self.__myStr.find(self.__myTerm)
def on_Command(self,cmd):
if len(cmd)>0 :
print (":" + cmd)
if (cmd == 'exit'):
self.__myState=-1;
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
# print x,y
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
# print self.selection
def running_average(self, input_frame):
output_frame = input_frame
return output_frame
def run(self):
if (self.filename ==''):
frame = cv.QueryFrame( self.capture )
else:
frame = cv.LoadImage(self.filename)
size = cv.GetSize(frame)
print (size)
while True:
# greb a frame
if (self.filename ==''):
frame = cv.QueryFrame( self.capture )
# update preview window
preview_frame = cv.CreateImage( ( int(size[0]*self.preview_scale) , int(size[1]*self.preview_scale)), frame.depth, frame.nChannels)
cv.Resize(frame, preview_frame)
cv.PutText(preview_frame,self.__myStr, (20,30),self.font,250) #Draw the text
# cv.Circle(preview_frame,(100,100),50,(250,0,0),1,8)
# cv.Rectangle(preview_frame,(100,100),(200,200),(250,0,0),1,8,0)
if is_rect_nonzero(self.selection):
x,y,w,h = self.selection
cv.Rectangle(preview_frame,(x,y),(x+w,y+h),(250,0,0),1,8,0)
cv.ShowImage( "fmTracking_Preview_Window", preview_frame)
# Compute process frame
if self.__myState==0: # do nothing
procssed_frame = frame
if self.__myState==1: # running average
procssed_frame = self.running_average(frame)
elif self.__myState==-1:
break;
# update Output window
procssed_frame = cv.CreateImage( ( int(size[0]*self.preview_scale) , int(size[1]*self.preview_scale)), frame.depth, frame.nChannels)
cv.Resize(frame, procssed_frame)
if is_rect_nonzero(self.selection):
roi_x,roi_y,roi_width,roi_height=self.selection
else:
roi_x,roi_y,roi_width,roi_height=0,0,procssed_frame.width,procssed_frame.height
cropped = cv.CreateImage((roi_width, roi_height), procssed_frame.depth, procssed_frame.nChannels)
src_region = cv.GetSubRect(procssed_frame, (roi_x, roi_y, roi_width, roi_height))
cv.Copy(src_region, cropped)
cv.ShowImage( "fmTracking_Output_Window", cropped)
# Handle Key inputs
c = cv.WaitKey(1) % 0x100
if c<> 0xff:
self.on_msgArrival(chr(c))
if __name__=="__main__":
demo = fmTrackingDemo()
# demo.set_capture_resolution(1280,720)
demo.set_capture_file('fm_tracking_pattern_01.jpg')
demo.run()
cv.DestroyAllWindows()
| Python |
#!/usr/bin/env python
import cv2.cv as cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class CamShiftDemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(1)
cv.NamedWindow( "CamShiftDemo", 1 )
cv.NamedWindow( "Histogram", 1 )
cv.SetMouseCallback( "CamShiftDemo", self.on_mouse)
self.__myStr=''
self.__myTerm='\r'
self.__myCmd=''
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
print( "Keys:\n"
" EXIT - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def on_msgArrival(self,iStr):
self.__myStr += iStr
pos = self.__myStr.find(self.__myTerm)
while (pos >=0):
self.on_Command(self.__myStr[0:pos])
self.__myStr=self.__myStr[pos+1:len(self.__myStr)]
pos = self.__myStr.find(self.__myTerm)
def on_Command(self,cmd):
if len(cmd)>0 :
print (":" + cmd)
if (cmd == 'exit'):
self.__myCmd='exit';
def hue_histogram_as_image(self, hist):
""" Returns a nice representation of a hue histogram """
histimg_hsv = cv.CreateImage( (320,200), 8, 3)
mybins = cv.CloneMatND(hist.bins)
cv.Log(mybins, mybins)
(_, hi, _, _) = cv.MinMaxLoc(mybins)
cv.ConvertScale(mybins, mybins, 255. / hi)
w,h = cv.GetSize(histimg_hsv)
hdims = cv.GetDims(mybins)[0]
for x in range(w):
xh = (180 * x) / (w - 1) # hue sweeps from 0-180 across the image
val = int(mybins[int(hdims * x / w)] * h / 255)
cv.Rectangle( histimg_hsv, (x, 0), (x, h-val), (xh,255,64), -1)
cv.Rectangle( histimg_hsv, (x, h-val), (x, h), (xh,255,255), -1)
histimg = cv.CreateImage( (320,200), 8, 3)
cv.CvtColor(histimg_hsv, histimg, cv.CV_HSV2BGR)
return histimg
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
def run(self):
hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
backproject_mode = False
while True:
frame = cv.QueryFrame( self.capture )
# Convert to HSV and keep the hue
hsv = cv.CreateImage(cv.GetSize(frame), 8, 3)
cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
self.hue = cv.CreateImage(cv.GetSize(frame), 8, 1)
cv.Split(hsv, self.hue, None, None, None)
# Compute back projection
backproject = cv.CreateImage(cv.GetSize(frame), 8, 1)
# Run the cam-shift
cv.CalcArrBackProject( [self.hue], backproject, hist )
if self.track_window and is_rect_nonzero(self.track_window):
crit = ( cv.CV_TERMCRIT_EPS | cv.CV_TERMCRIT_ITER, 10, 1)
(iters, (area, value, rect), track_box) = cv.CamShift(backproject, self.track_window, crit)
self.track_window = rect
# If mouse is pressed, highlight the current selected rectangle
# and recompute the histogram
if self.drag_start and is_rect_nonzero(self.selection):
sub = cv.GetSubRect(frame, self.selection)
save = cv.CloneMat(sub)
cv.ConvertScale(frame, frame, 0.5)
cv.Copy(save, sub)
x,y,w,h = self.selection
cv.Rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
sel = cv.GetSubRect(self.hue, self.selection )
cv.CalcArrHist( [sel], hist, 0)
(_, max_val, _, _) = cv.GetMinMaxHistValue( hist)
if max_val != 0:
cv.ConvertScale(hist.bins, hist.bins, 255. / max_val)
elif self.track_window and is_rect_nonzero(self.track_window):
cv.EllipseBox( frame, track_box, cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )
if not backproject_mode:
cv.ShowImage( "CamShiftDemo", frame )
else:
cv.ShowImage( "CamShiftDemo", backproject)
cv.ShowImage( "Histogram", self.hue_histogram_as_image(hist))
c = cv.WaitKey(7) % 0x100
if c<> 0xff:
self.on_msgArrival(chr(c))
if self.__myCmd=='exit':
break;
# if c == 27:
# break
# elif c == ord("b"):
# backproject_mode = not backproject_mode
# elif c<> 0xff:
# self.on_msgArrival(chr(c))
# print c , chr(c) , self.__myStr
if __name__=="__main__":
demo = CamShiftDemo()
demo.run()
cv.DestroyAllWindows()
| Python |
#!/usr/bin/env python
from Tkinter import *
root = Tk()
def key(event):
print "pressed", repr(event.char)
def callback(event):
frame.focus_set()
print "clicked at", event.x, event.y
frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
| Python |
#! /usr/bin/env python
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(0)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
#blur the source image to reduce color noise
cv.Smooth(img, img, cv.CV_BLUR, 3);
#convert the image to hsv(Hue, Saturation, Value) so its
#easier to determine the color to track(hue)
hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)
#limit all pixels that don't match our criteria, in this case we are
#looking for purple but if you want you can adjust the first value in
#both turples which is the hue range(120,140). OpenCV uses 0-180 as
#a hue range for the HSV color model
thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img)
#determine the objects moments and check that the area is large
#enough to be our object
moments = cv.Moments(thresholded_img, 0)
area = cv.GetCentralMoment(moments, 0, 0)
#there can be noise in the video so ignore objects with small areas
if(area > 100000):
#determine the x and y coordinates of the center of the object
#we are tracking by dividing the 1, 0 and 0, 1 moments by the area
x = cv.GetSpatialMoment(moments, 1, 0)/area
y = cv.GetSpatialMoment(moments, 0, 1)/area
#print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area)
#create an overlay to mark the center of the tracked object
overlay = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20)
cv.Add(img, overlay, img)
#add the thresholded image back to the img so we can see what was
#left after it was applied
cv.Merge(thresholded_img, None, None, None, img)
#display the image
cv.ShowImage(color_tracker_window, img)
if cv.WaitKey(10) == 27:
break
if __name__=="__main__":
color_tracker = ColorTracker()
color_tracker.run()
| Python |
#!/usr/bin/env python
import cv2.cv as cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class fmUIdemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(0) # Capture image from device "0"
cv.NamedWindow( "fmUIdemo", 1 )
cv.NamedWindow( "fmProcessed", 1 )
cv.SetMouseCallback( "fmUIdemo", self.on_mouse)
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
print( "Keys:\n"
" ESC - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
def run(self):
while True:
frame = cv.QueryFrame( self.capture )
# If mouse is pressed, highlight the current selected rectangle
# and recompute the fmProcessed
c = cv.WaitKey(7) % 0x100
if c == 27:
break
elif c == ord("b"):
backproject_mode = not backproject_mode
elif c<> 0xff:
print c
if __name__=="__main__":
demo = fmUIdemo()
demo.run()
cv.DestroyAllWindows()
| Python |
#!/usr/bin/env python
import cv2.cv as cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class CamShiftDemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(1)
cv.NamedWindow( "CamShiftDemo", 1 )
cv.NamedWindow( "Histogram", 1 )
cv.SetMouseCallback( "CamShiftDemo", self.on_mouse)
self.__myStr=''
self.__myTerm='\r'
self.__myCmd=''
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
print( "Keys:\n"
" EXIT - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def on_msgArrival(self,iStr):
self.__myStr += iStr
pos = self.__myStr.find(self.__myTerm)
while (pos >=0):
self.on_Command(self.__myStr[0:pos])
self.__myStr=self.__myStr[pos+1:len(self.__myStr)]
pos = self.__myStr.find(self.__myTerm)
def on_Command(self,cmd):
if len(cmd)>0 :
print (":" + cmd)
if (cmd == 'exit'):
self.__myCmd='exit';
def hue_histogram_as_image(self, hist):
""" Returns a nice representation of a hue histogram """
histimg_hsv = cv.CreateImage( (320,200), 8, 3)
mybins = cv.CloneMatND(hist.bins)
cv.Log(mybins, mybins)
(_, hi, _, _) = cv.MinMaxLoc(mybins)
cv.ConvertScale(mybins, mybins, 255. / hi)
w,h = cv.GetSize(histimg_hsv)
hdims = cv.GetDims(mybins)[0]
for x in range(w):
xh = (180 * x) / (w - 1) # hue sweeps from 0-180 across the image
val = int(mybins[int(hdims * x / w)] * h / 255)
cv.Rectangle( histimg_hsv, (x, 0), (x, h-val), (xh,255,64), -1)
cv.Rectangle( histimg_hsv, (x, h-val), (x, h), (xh,255,255), -1)
histimg = cv.CreateImage( (320,200), 8, 3)
cv.CvtColor(histimg_hsv, histimg, cv.CV_HSV2BGR)
return histimg
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
def run(self):
hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
backproject_mode = False
while True:
frame = cv.QueryFrame( self.capture )
# Convert to HSV and keep the hue
hsv = cv.CreateImage(cv.GetSize(frame), 8, 3)
cv.CvtColor(frame, hsv, cv.CV_BGR2HSV)
self.hue = cv.CreateImage(cv.GetSize(frame), 8, 1)
cv.Split(hsv, self.hue, None, None, None)
# Compute back projection
backproject = cv.CreateImage(cv.GetSize(frame), 8, 1)
# Run the cam-shift
cv.CalcArrBackProject( [self.hue], backproject, hist )
if self.track_window and is_rect_nonzero(self.track_window):
crit = ( cv.CV_TERMCRIT_EPS | cv.CV_TERMCRIT_ITER, 10, 1)
(iters, (area, value, rect), track_box) = cv.CamShift(backproject, self.track_window, crit)
self.track_window = rect
# If mouse is pressed, highlight the current selected rectangle
# and recompute the histogram
if self.drag_start and is_rect_nonzero(self.selection):
sub = cv.GetSubRect(frame, self.selection)
save = cv.CloneMat(sub)
cv.ConvertScale(frame, frame, 0.5)
cv.Copy(save, sub)
x,y,w,h = self.selection
cv.Rectangle(frame, (x,y), (x+w,y+h), (255,255,255))
sel = cv.GetSubRect(self.hue, self.selection )
cv.CalcArrHist( [sel], hist, 0)
(_, max_val, _, _) = cv.GetMinMaxHistValue( hist)
if max_val != 0:
cv.ConvertScale(hist.bins, hist.bins, 255. / max_val)
elif self.track_window and is_rect_nonzero(self.track_window):
cv.EllipseBox( frame, track_box, cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )
if not backproject_mode:
cv.ShowImage( "CamShiftDemo", frame )
else:
cv.ShowImage( "CamShiftDemo", backproject)
cv.ShowImage( "Histogram", self.hue_histogram_as_image(hist))
c = cv.WaitKey(7) % 0x100
if c<> 0xff:
self.on_msgArrival(chr(c))
if self.__myCmd=='exit':
break;
# if c == 27:
# break
# elif c == ord("b"):
# backproject_mode = not backproject_mode
# elif c<> 0xff:
# self.on_msgArrival(chr(c))
# print c , chr(c) , self.__myStr
if __name__=="__main__":
demo = CamShiftDemo()
demo.run()
cv.DestroyAllWindows()
| Python |
import cv2.cv as cv
import sys
imgco = cv.LoadImage('UPC_A.jpg')
img = cv.CreateImage(cv.GetSize(imgco),8,1)
imgx = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_16S,1)
imgy = cv.CreateImage(cv.GetSize(img),cv.IPL_DEPTH_16S,1)
thresh = cv.CreateImage(cv.GetSize(img),8,1)
### Convert image to grayscale ###
cv.CvtColor(imgco,img,cv.CV_BGR2GRAY)
### Finding horizontal and vertical gradient ###
cv.Sobel(img,imgx,1,0,3)
cv.Abs(imgx,imgx)
cv.Sobel(img,imgy,0,1,3)
cv.Abs(imgy,imgy)
cv.Sub(imgx,imgy,imgx)
cv.ConvertScale(imgx,img)
### Low pass filtering ###
cv.Smooth(img,img,cv.CV_GAUSSIAN,7,7,0)
### Applying Threshold ###
cv.Threshold(img,thresh,100,255,cv.CV_THRESH_BINARY)
cv.Erode(thresh,thresh,None,2)
cv.Dilate(thresh,thresh,None,5)
### Contour finding with max. area ###
storage = cv.CreateMemStorage(0)
contour = cv.FindContours(thresh, storage, cv.CV_RETR_CCOMP, cv.CV_CHAIN_APPROX_SIMPLE)
area = 0
while contour:
max_area = cv.ContourArea(contour)
if max_area>area:
area = max_area
bar = list(contour)
contour=contour.h_next()
### Draw bounding rectangles ###
bound_rect = cv.BoundingRect(bar)
pt1 = (bound_rect[0], bound_rect[1])
pt2 = (bound_rect[0] + bound_rect[2], bound_rect[1] + bound_rect[3])
cv.Rectangle(imgco, pt1, pt2, cv.CV_RGB(0,255,255), 2)
cv.ShowImage('img',imgco)
cv.WaitKey(0)
| Python |
import cv2.cv as cv
vidFile = cv.CaptureFromFile( 'video.wmv' )
nFrames = int( cv.GetCaptureProperty( vidFile, cv.CV_CAP_PROP_FRAME_COUNT ) )
fps = cv.GetCaptureProperty( vidFile, cv.CV_CAP_PROP_FPS )
waitPerFrameInMillisec = int( 1/fps * 1000/1 )
print 'Num. Frames = ', nFrames
print 'Frame Rate = ', fps, ' frames per sec'
for f in xrange( nFrames ):
frameImg = cv.QueryFrame( vidFile )
cv.ShowImage( "My Video Window", frameImg )
cv.WaitKey( waitPerFrameInMillisec )
# When playing is done, delete the window
# NOTE: this step is not strictly necessary,
# when the script terminates it will close all windows it owns anyways
cv.DestroyWindow( "My Video Window" )
| Python |
import cv2.cv as cv
import time
## main program
cv.NamedWindow("fm_camera", 1)
capture = cv.CaptureFromCAM(1)
my_width=1280
my_height=720
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, my_height)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, my_width)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FORMAT, cv.IPL_DEPTH_32F)
img = cv.QueryFrame(capture)
print "Got frame of dimensions (", img.width, " x ", img.height, ")"
size = cv.GetSize(img)
while True:
img = cv.QueryFrame(capture)
disp_img = cv.CreateImage( ( size[0] / 4, size[1] / 4), img.depth, img.nChannels)
cv.Resize(img, disp_img)
cv.ShowImage("fm_camera", disp_img)
if cv.WaitKey(10) == 27:
break
cv.DestroyAllWindows()
| Python |
#!/usr/bin/env python
import cv2.cv as cv
import numpy as np
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class fmTrackingDemo:
def __init__(self):
self.font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 2, 2)
cv.NamedWindow( "fmTracking_Preview_Window", 1 )
cv.NamedWindow( "fmTracking_Output_Window", 1 )
cv.SetMouseCallback( "fmTracking_Preview_Window", self.on_mouse)
self.__myStr=''
self.__myTerm='\r'
self.__myCmd=''
self.__myState=0
self.filename=''
self.drag_start = None # Set to (x,y) when mouse starts drag
self.track_window = None # Set to rect when the mouse drag finishes
self.selection = (0,0,0,0)
print( "Keys:\n"
" EXIT - quit the program\n"
" b - switch to/from backprojection view\n"
"To initialize tracking, drag across the object with the mouse\n" )
def set_capture_resolution(self, width, height):
self.capture = cv.CaptureFromCAM(1)
self.preview_scale = 0.5
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height)
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, width)
cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FORMAT, cv.IPL_DEPTH_32F)
def set_capture_file(self,filename):
self.preview_scale = 1
self.filename = filename
def on_msgArrival(self,iStr):
self.__myStr += iStr
pos = self.__myStr.find(self.__myTerm)
while (pos >=0):
self.on_Command(self.__myStr[0:pos])
self.__myStr=self.__myStr[pos+1:len(self.__myStr)]
pos = self.__myStr.find(self.__myTerm)
def on_Command(self,cmd):
if len(cmd)>0 :
print (":" + cmd)
if (cmd == 'exit'):
self.__myState=-1;
def on_mouse(self, event, x, y, flags, param):
if event == cv.CV_EVENT_LBUTTONDOWN:
# print x,y
self.drag_start = (x, y)
if event == cv.CV_EVENT_LBUTTONUP:
self.drag_start = None
self.track_window = self.selection
if is_rect_nonzero(self.selection):
print self.selection
if self.drag_start:
xmin = min(x, self.drag_start[0])
ymin = min(y, self.drag_start[1])
xmax = max(x, self.drag_start[0])
ymax = max(y, self.drag_start[1])
self.selection = (xmin, ymin, xmax - xmin, ymax - ymin)
# print self.selection
def running_average(self, input_frame):
output_frame = input_frame
return output_frame
def run(self):
if (self.filename ==''):
frame = cv.QueryFrame( self.capture )
else:
frame = cv.LoadImage(self.filename)
size = cv.GetSize(frame)
print (size)
while True:
# greb a frame
if (self.filename ==''):
frame = cv.QueryFrame( self.capture )
# update preview window
preview_frame = cv.CreateImage( ( int(size[0]*self.preview_scale) , int(size[1]*self.preview_scale)), frame.depth, frame.nChannels)
cv.Resize(frame, preview_frame)
cv.PutText(preview_frame,self.__myStr, (20,30),self.font,250) #Draw the text
# cv.Circle(preview_frame,(100,100),50,(250,0,0),1,8)
# cv.Rectangle(preview_frame,(100,100),(200,200),(250,0,0),1,8,0)
if is_rect_nonzero(self.selection):
x,y,w,h = self.selection
cv.Rectangle(preview_frame,(x,y),(x+w,y+h),(250,0,0),1,8,0)
cv.ShowImage( "fmTracking_Preview_Window", preview_frame)
# Compute process frame
if self.__myState==0: # do nothing
procssed_frame = frame
if self.__myState==1: # running average
procssed_frame = self.running_average(frame)
elif self.__myState==-1:
break;
# update Output window
procssed_frame = cv.CreateImage( ( int(size[0]*self.preview_scale) , int(size[1]*self.preview_scale)), frame.depth, frame.nChannels)
cv.Resize(frame, procssed_frame)
if is_rect_nonzero(self.selection):
roi_x,roi_y,roi_width,roi_height=self.selection
else:
roi_x,roi_y,roi_width,roi_height=0,0,procssed_frame.width,procssed_frame.height
cropped = cv.CreateImage((roi_width, roi_height), procssed_frame.depth, procssed_frame.nChannels)
src_region = cv.GetSubRect(procssed_frame, (roi_x, roi_y, roi_width, roi_height))
cv.Copy(src_region, cropped)
cv.ShowImage( "fmTracking_Output_Window", cropped)
# Handle Key inputs
c = cv.WaitKey(1) % 0x100
if c<> 0xff:
self.on_msgArrival(chr(c))
if __name__=="__main__":
demo = fmTrackingDemo()
# demo.set_capture_resolution(1280,720)
demo.set_capture_file('fm_tracking_pattern_01.jpg')
demo.run()
cv.DestroyAllWindows()
| Python |
import cv2
import sys
import numpy as np
if len(sys.argv)!=2: ## Check for error in usage syntax
print "Usage : python display_image.py <image_file>"
else:
img = cv2.imread(sys.argv[1],cv2.CV_LOAD_IMAGE_COLOR) ## Read image file
if (img == None): ## Check for invalid input
print "Could not open or find the image"
else:
cv2.namedWindow('Display Window') ## create window for display
cv2.imshow('Display Window',img) ## Show image in the window
print "size of image: ",img.shape ## print size of image
cv2.waitKey(0) ## Wait for keystroke
cv2.destroyAllWindows() ## Destroy all windows
| Python |
class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):
for observer in self._bar_observers:
observer(param)
def notify_barEx(self, param):
observer(param)
def observer(param):
print "observer(%s)" % param
class Baz(object):
def observer(self, param):
print "Baz.observer(%s)" % param
class CallableClass(object):
def __call__(self, param):
print "CallableClass.__call__(%s)" % param
baz = Baz()
foo = Foo()
foo.add_bar_observer(observer) # function
#foo.add_bar_observer(baz.observer) # bound method
#foo.add_bar_observer(CallableClass()) # callable instance
foo.notify_bar('123ABC')
| Python |
## {{{ http://code.activestate.com/recipes/578333/ (r1)
#! /usr/bin/env python
""" (Q): which way to use for concatenating strings?
(A): run the script and find out yourself.
"""
import time
bloated_string = 'bloat me' * 10
# method 1, simple concatenation
def slow():
test_string = ''
start = time.clock()
for i in range(1000):
test_string += bloated_string
end = time.clock()
delta = float(end-start)
# print 'slow len: ', len(test_string)
return delta
# method 2, use list.append() and ''.join()
def fast():
test_string = list()
start = time.clock()
for i in range(1000):
test_string.append('%s' % bloated_string)
test_string = ''.join(test_string)
end = time.clock()
delta = float(end-start)
# print 'fast len: ', len(test_string)
return delta
# method 3, use list comprehension and ''.join()
def fastest():
test_string = bloated_string
start = time.clock()
test_string = ''.join([test_string for i in range(1000)])
end = time.clock()
delta = float(end-start)
# print 'fastest len', len(test_string)
return delta
if __name__ == '__main__':
print '--- CPU TIMES ---'
delta_slow = slow()
print 'delta slow: {delta_slow}'.format(delta_slow=delta_slow)
delta_fast = fast()
print 'delta fast: {delta_fast}'.format(delta_fast=delta_fast)
delta_fastest = fastest()
print 'delta fastest: {delta_fastest}'.format(delta_fastest=delta_fastest)
print '---'
print 'listcomps is %f times faster than (list.append + ''.join())' % \
(delta_fast/delta_fastest)
print 'the latter is %f times faster (slower) than simple concat' %\
(delta_slow/delta_fast)
## end of http://code.activestate.com/recipes/578333/ }}}
| Python |
import cv
import time
cv.NamedWindow("camera", 1)
capture = cv.CaptureFromCAM(0)
while True:
img = cv.QueryFrame(capture)
cv.ShowImage("camera", img)
if cv.WaitKey(10) == 27:
break
| Python |
##################################################################
class fm_command(object):
def __init__(self):
self.__myStr=''
self.__myTerm='\r'
def on_msgArrival(self,iStr):
self.__myStr += iStr
pos = self.__myStr.find(self.__myTerm)
while (pos >=0):
on_Command(self.__myStr[0:pos])
self.__myStr=self.__myStr[pos+1:len(self.__myStr)]
pos = self.__myStr.find(self.__myTerm)
##################################################################
def on_Command(cmd):
if len(cmd)>0 :
print (":" + cmd)
d = fm_command()
d.on_msgArrival('Hello\r123\r')
d.on_msgArrival('\rAABB\rccdd\r')
#d.findCmd()
| Python |
#! /usr/bin/env python
import cv2.cv as cv
color_tracker_window = "Color Tracker"
class ColorTracker:
def __init__(self):
cv.NamedWindow( color_tracker_window, 1 )
self.capture = cv.CaptureFromCAM(0)
def run(self):
while True:
img = cv.QueryFrame( self.capture )
#blur the source image to reduce color noise
cv.Smooth(img, img, cv.CV_BLUR, 3);
#convert the image to hsv(Hue, Saturation, Value) so its
#easier to determine the color to track(hue)
hsv_img = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.CvtColor(img, hsv_img, cv.CV_BGR2HSV)
#limit all pixels that don't match our criteria, in this case we are
#looking for purple but if you want you can adjust the first value in
#both turples which is the hue range(120,140). OpenCV uses 0-180 as
#a hue range for the HSV color model
thresholded_img = cv.CreateImage(cv.GetSize(hsv_img), 8, 1)
cv.InRangeS(hsv_img, (120, 80, 80), (140, 255, 255), thresholded_img)
#determine the objects moments and check that the area is large
#enough to be our object
moments = cv.Moments(thresholded_img, 0)
area = cv.GetCentralMoment(moments, 0, 0)
#there can be noise in the video so ignore objects with small areas
if(area > 100000):
#determine the x and y coordinates of the center of the object
#we are tracking by dividing the 1, 0 and 0, 1 moments by the area
x = cv.GetSpatialMoment(moments, 1, 0)/area
y = cv.GetSpatialMoment(moments, 0, 1)/area
#print 'x: ' + str(x) + ' y: ' + str(y) + ' area: ' + str(area)
#create an overlay to mark the center of the tracked object
overlay = cv.CreateImage(cv.GetSize(img), 8, 3)
cv.Circle(overlay, (x, y), 2, (255, 255, 255), 20)
cv.Add(img, overlay, img)
#add the thresholded image back to the img so we can see what was
#left after it was applied
cv.Merge(thresholded_img, None, None, None, img)
#display the image
cv.ShowImage(color_tracker_window, img)
if cv.WaitKey(10) == 27:
break
if __name__=="__main__":
color_tracker = ColorTracker()
color_tracker.run()
| Python |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#####################################################################
# Drawing methods comparison (part of FoFiX) #
# Copyright (C) 2009 Pascal Giard <evilynux@gmail.com> #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from OpenGL.GL import *
try:
from OpenGL.arrays import vbo
vbo_support = True
except:
vbo_support = False
from numpy import array, float32, append, hstack
import pygame
from pygame.locals import *
from math import cos, sin, sqrt
rot = 0.0
scale = 1.0
mode = 2
def init():
global mode, triangVbo, triangVtx, triangCol
global spiralVtx, spiralVbo, spiralCol
triangVtx = array(
[[ 0, 1, 0],
[-1, -1, 0],
[ 1, -1, 0]], dtype=float32)
triangCol = array(
[[ 0, 1, 0],
[ 1, 0, 0],
[ 0, 0, 1]], dtype=float32)
nbSteps = 200.0
for i in range(int(nbSteps)):
ratio = i/nbSteps;
angle = 21*ratio
c = cos(angle)
s = sin(angle);
r1 = 1.0 - 0.8*ratio;
r2 = 0.8 - 0.8*ratio;
alt = ratio - 0.5
nor = 0.5
up = sqrt(1.0-nor*nor)
if i == 0:
spiralVtx = array([[r1*c, alt, r1*s]],dtype=float32)
spiralCol = array([[1.0-ratio, 0.2, ratio]],dtype=float32)
else:
spiralVtx = append(spiralVtx,[[r1*c, alt, r1*s]],axis=0)
spiralCol = append(spiralCol,[[1.0-ratio, 0.2, ratio]],axis=0)
spiralVtx = append(spiralVtx,[[r2*c, alt+0.05, r2*s]],axis=0)
spiralCol = append(spiralCol,[[1.0-ratio, 0.2, ratio]],axis=0)
if vbo_support:
triangArray = hstack((triangVtx, triangCol)).astype(float32)
spiralArray = hstack((spiralVtx, spiralCol)).astype(float32)
triangVbo = vbo.VBO( triangArray, usage='GL_STATIC_DRAW' )
spiralVbo = vbo.VBO( spiralArray, usage='GL_STATIC_DRAW' )
else:
print "VBO not supported, fallbacking to array-based drawing."
mode = 1
def draw():
global mode, triangVbo, triangVtx, triangCol
global spiralVtx, spiralVbo, spiralCol, rot, scale
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glPushMatrix()
glColor(1,1,1) # triangle color
glScale(scale,scale,scale)
glRotate(rot,0,1,0)
# VBO drawing
if mode == 0 and vbo_support:
# Draw triangle
triangVbo.bind()
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 24, triangVbo )
glColorPointer(3, GL_FLOAT, 24, triangVbo+12 )
glDrawArrays(GL_TRIANGLES, 0, triangVtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
triangVbo.unbind()
# Draw spiral
# evilynux - FIXME: The following doesn't work... why?
spiralVbo.bind()
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY)
glVertexPointer(3, GL_FLOAT, 24, spiralVbo )
glColorPointer(3, GL_FLOAT, 24, spiralVbo+12 )
glDrawArrays(GL_TRIANGLE_STRIP, 0, spiralVtx.shape[0])
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
spiralVbo.unbind()
# Array-based drawing
elif mode == 1:
# Draw triangle
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glColorPointerf(triangCol)
glVertexPointerf(triangVtx)
glDrawArrays(GL_TRIANGLES, 0, triangVtx.shape[0])
# Draw spiral
glColorPointerf(spiralCol)
glVertexPointerf(spiralVtx)
glDrawArrays(GL_TRIANGLE_STRIP, 0, spiralVtx.shape[0])
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
# Direct drawing
else: # mode == 2
glBegin(GL_TRIANGLES)
for i in range(triangVtx.shape[0]):
glColor(triangCol[i])
glVertex(triangVtx[i])
glEnd()
# Draw spiral
glBegin(GL_TRIANGLE_STRIP);
for i in range(spiralVtx.shape[0]):
glColor(spiralCol[i])
glVertex(spiralVtx[i])
glEnd()
glPopMatrix()
def main():
global rot, scale, mode
scale_dir = -1
modeName = ["VBO", "Array-based", "Direct-mode"]
fps = 0
video_flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
pygame.init()
pygame.display.set_mode((640,480), video_flags)
init()
frames = 0
ticks = pygame.time.get_ticks()
clock = pygame.time.Clock()
while 1:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
elif event.type == KEYDOWN and event.key == K_RIGHT:
mode = (mode + 1) % 3
if mode == 0 and not vbo_support:
mode = (mode + 1) % 3
print "VBO not supported, fallbacking to %s drawing." % modeName[mode]
elif event.type == KEYDOWN and event.key == K_LEFT:
mode = (mode - 1) % 3
if mode == 0 and not vbo_support:
mode = (mode - 1) % 3
print "VBO not supported, fallbacking to %s drawing." % modeName[mode]
ticksDiff = pygame.time.get_ticks()-ticks
# draw all objects
draw()
# update rotation counters
rot += 0.2
scale += scale_dir*0.0002
if scale > 1.0 or scale < 0.5:
scale_dir = scale_dir*-1
# make changes visible
pygame.display.flip()
frames = frames+1
if( ticksDiff > 2000 ):
fps = ((frames*1000)/(ticksDiff))
ticks = pygame.time.get_ticks()
frames = 0
print "mode: %s, %.2f fps" % (modeName[mode], fps)
# evilynux - commented the following so we go as fast as we can
#clock.tick(60)
if __name__ == '__main__': main()
| Python |
"""
Lamina module
When you set the display mode for OpenGL, you enable all the coolness of 3D rendering,
but you disable the bread-and-butter raster SDL functionality like fill() and blit().
Since the GUI libraries use those surface methods extensively, they cannot readily be
used in OpenGL displays.
Lamina provides the LaminaPanelSurface and LaminaScreenSurface classes, which bridge
between the two.
The 'surf' attribute is a surface, and can be drawn on, blitted to, and passed to GUI
rendering functions for alteration. The 'display' method displays the surface as a
transparent textured quad in the OpenGL model-space. The 'refresh' method indicates that
the surface has changed, and that the texture needs regeneration. The 'clear' method
restores the blank and transparent original condition.
Usage is vaguely like this incomplete pseudocode:
# create gui with appropriate constructor
gui = GUI_Constructor()
# create LaminaPanelSurface
gui_screen = lamina.LaminaPanelSurface( (640,480), (-1,1,2,2) )
# draw widgets on surface
gui.draw( gui_screen.surf )
# hide mouse cursor
pygame.mouse.set_visible(0)
while 1:
# do input events ....
# pass events to gui
gui.doevent(...)
# detect changes to surface
changed = gui.update( gui_screen.surf )
if changed:
# and mark for update
gui_screen.refresh()
# draw opengl geometry .....
# display gui
# opengl code to set modelview matrix for desired gui surface pos
gui_screen.display()
If your gui screen is not sized to match the display, hide the system
mouse cursor, and use the convertMousePos method to position your own
OpenGL mouse cursor (a cone or something). The result of the
convertMousePos is 2D, (x,y) so you need to draw the mouse with the same
modelview matrix as drawing the LaminaPanelSurface itself.
mouse_pos = gui_screen.convertMousePos(mouseX, mouseY)
glTranslate(*mouse_pos)
# opengl code to display your mouse object (a cone?)
The distribution package includes several demo scripts which are functional. Refer
to them for details of working code.
"""
import OpenGL.GLU as oglu
import OpenGL.GL as ogl
import pygame
import math
def load_texture(surf):
"""Load surface into texture object. Return texture object.
@param surf: surface to make texture from.
"""
txtr = ogl.glGenTextures(1)
textureData = pygame.image.tostring(surf, "RGBA", 1)
ogl.glEnable(ogl.GL_TEXTURE_2D)
ogl.glBindTexture(ogl.GL_TEXTURE_2D, txtr)
width, height = surf.get_size()
ogl.glTexImage2D( ogl.GL_TEXTURE_2D, 0, ogl.GL_RGBA, width, height, 0,
ogl.GL_RGBA, ogl.GL_UNSIGNED_BYTE, textureData )
ogl.glTexParameterf(ogl.GL_TEXTURE_2D, ogl.GL_TEXTURE_MAG_FILTER, ogl.GL_NEAREST)
ogl.glTexParameterf(ogl.GL_TEXTURE_2D, ogl.GL_TEXTURE_MIN_FILTER, ogl.GL_NEAREST)
ogl.glDisable(ogl.GL_TEXTURE_2D)
return txtr
def overlay_texture(txtr, surf, r):
"""Load surface into texture object, replacing part of txtr
given by rect r.
@param txtr: texture to add to
@param surf: surface to copy from
@param r: rectangle indicating area to overlay.
"""
subsurf = surf.subsurface(r)
textureData = pygame.image.tostring(subsurf, "RGBA", 1)
hS, wS = surf.get_size()
rect = pygame.Rect(r.x,hS-(r.y+r.height),r.width,r.height)
ogl.glEnable(ogl.GL_TEXTURE_2D)
ogl.glBindTexture(ogl.GL_TEXTURE_2D, txtr)
ogl.glTexSubImage2D(ogl.GL_TEXTURE_2D, 0, rect.x, rect.y, rect.width, rect.height,
ogl.GL_RGBA, ogl.GL_UNSIGNED_BYTE, textureData )
ogl.glDisable(ogl.GL_TEXTURE_2D)
class LaminaPanelSurface(object):
"""Surface for imagery to overlay.
@ivar surf: surface
@ivar dims: tuple with corners of quad
"""
def __init__(self, quadDims=(-1,-1,2,2), winSize=None):
"""Initialize new instance.
@param winSize: tuple (width, height)
@param quadDims: tuple (left, top, width, height)
"""
if not winSize:
winSize = pygame.display.get_surface().get_size()
self._txtr = None
self._winSize = winSize
left, top, width, height = quadDims
right, bottom = left+width, top-height
self._qdims = quadDims
self.dims = (left,top,0), (right,top,0), (right,bottom,0), (left,bottom,0)
self.clear()
def clear(self):
"""Restore the total transparency to the surface. """
powerOfTwo = 64
while powerOfTwo < max(*self._winSize):
powerOfTwo *= 2
raw = pygame.Surface((powerOfTwo, powerOfTwo), pygame.SRCALPHA, 32)
self._surfTotal = raw.convert_alpha()
self._usable = 1.0*self._winSize[0]/powerOfTwo, 1.0*self._winSize[1]/powerOfTwo
self.surf = self._surfTotal.subsurface(0,0,self._winSize[0],self._winSize[1])
self.regen()
def regen(self):
"""Force regen of texture object. Call after change to the GUI appearance. """
if self._txtr:
ogl.glDeleteTextures([self._txtr])
self._txtr = None
def refresh(self, dirty=None):
"""Refresh the texture from the surface.
@param dirty: list of rectangles to update, None for whole panel
"""
if not self._txtr:
self._txtr = load_texture(self._surfTotal)
else:
wS, hS = self._surfTotal.get_size()
if dirty is None:
dirty = [pygame.Rect(0,0,wS,hS)]
for r in dirty:
overlay_texture(self._txtr,self._surfTotal,r)
def convertMousePos(self, pos):
"""Converts 2d pixel mouse pos to 2d gl units.
@param pos: 2-tuple with x,y of mouse
"""
x0, y0 = pos
x = x0/self._winSize[0]*self._qdims[2] + self._qdims[0]
y = y0/self._winSize[1]*self._qdims[3] + self._qdims[1]
return x, y
def display(self):
"""Draw surface to a quad. Call as part of OpenGL rendering code."""
ogl.glEnable(ogl.GL_BLEND)
ogl.glBlendFunc(ogl.GL_SRC_ALPHA, ogl.GL_ONE_MINUS_SRC_ALPHA)
ogl.glEnable(ogl.GL_TEXTURE_2D)
ogl.glBindTexture(ogl.GL_TEXTURE_2D, self._txtr)
ogl.glTexEnvf(ogl.GL_TEXTURE_ENV, ogl.GL_TEXTURE_ENV_MODE, ogl.GL_REPLACE)
ogl.glBegin(ogl.GL_QUADS)
ogl.glTexCoord2f(0.0, 1.0)
ogl.glVertex3f(*self.dims[0])
ogl.glTexCoord2f(self._usable[0], 1.0)
ogl.glVertex3f(*self.dims[1])
ogl.glTexCoord2f(self._usable[0], 1-self._usable[1])
ogl.glVertex3f(*self.dims[2])
ogl.glTexCoord2f(0.0, 1-self._usable[1])
ogl.glVertex3f(*self.dims[3])
ogl.glEnd()
ogl.glDisable(ogl.GL_BLEND)
ogl.glDisable(ogl.GL_TEXTURE_2D)
def testMode(self):
"""Draw red/transparent checkerboard. """
w, h = self._winSize[0]*0.25, self._winSize[1]*0.25
Rect = pygame.Rect
pygame.draw.rect(self.surf, (250,0,0), Rect(0,0,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(2*w,0,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(w,h,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(3*w,h,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(0,2*h,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(2*w,2*h,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(w,3*h,w,h), 0)
pygame.draw.rect(self.surf, (250,0,0), Rect(3*w,3*h,w,h), 0)
self.clear = None
class LaminaScreenSurface(LaminaPanelSurface):
"""Surface for imagery to overlay. Autofits to actual display.
@ivar surf: surface
@ivar dims: tuple with corners of quad
"""
def __init__(self, depth=0):
"""Initialize new instance.
@param depth: (0-1) z-value, if you want to draw your own 3D
cursor, set this to a small non-zero value to allow room in
front of this overlay to draw the cursor. (0.1 is a first guess)
"""
self._txtr = None
self._depth = depth
self.setup()
def setup(self):
"""Setup stuff, after pygame is inited. """
self._winSize = pygame.display.get_surface().get_size()
self.refreshPosition()
self.clear()
def refreshPosition(self):
"""Recalc where in modelspace quad needs to be to fill screen."""
depth = self._depth
bottomleft = oglu.gluUnProject(0, 0, depth)
bottomright = oglu.gluUnProject(self._winSize[0], 0, depth)
topleft = oglu.gluUnProject(0, self._winSize[1], depth)
topright = oglu.gluUnProject(self._winSize[0], self._winSize[1], depth)
self.dims = topleft, topright, bottomright, bottomleft
width = topright[0] - topleft[0]
height = topright[1] - bottomright[1]
self._qdims = topleft[0], topleft[1], width, height
class LaminaScreenSurface2(LaminaScreenSurface):
"""Surface that defers initialization to setup method. """
def __init__(self, depth=0):
"""Initialize new instance. """
self._txtr = None
self._depth = depth
def refreshPosition(self):
"""Recalc where in modelspace quad needs to be to fill screen."""
self._dirty = True
self._qdims = None, None
def getPoint(self, pt):
"""Get x,y coords of pt in 3d space."""
pt2 = oglu.gluProject(*pt)
return int(pt2[0]), int(pt2[1]), pt2[2]
def update(self):
pass
def commit(self):
pass
def display(self):
"""Display texture. """
if self._dirty:
depth = self._depth
topleft = oglu.gluUnProject(0,self._winSize[1],depth)
assert topleft, topleft
if topleft[0:2] != self._qdims[0:2]:
bottomleft = oglu.gluUnProject(0,0,depth)
bottomright = oglu.gluUnProject(self._winSize[0],0,depth)
topright = oglu.gluUnProject(self._winSize[0],self._winSize[1],depth)
self.dims = topleft, topright, bottomright, bottomleft
width = topright[0] - topleft[0]
height = topright[1] - bottomright[1]
self._qdims = topleft[0], topleft[1], width, height
LaminaScreenSurface.display(self)
class LaminaScreenSurface3(LaminaScreenSurface):
"""Surface that accepts a 3d point to constructor, and
locates surface parallel to screen through given point.
Defers initialization to setup method, like LSS2.
"""
def __init__(self, point=(0,0,0)):
"""Initialize new instance. """
self._txtr = None
self._point = point
self._depth = None
def refreshPosition(self):
"""Recalc where in modelspace quad needs to be to fill screen."""
self._dirty = True
def getPoint(self, pt):
"""Get x,y coords of pt in 3d space."""
pt2 = oglu.gluProject(*pt)
return pt2[0], pt2[1]
def update(self):
pass
def commit(self):
pass
def display(self):
"""Display texture. """
if self._dirty:
depth = oglu.gluProject(*self._point)[2]
if depth != self._depth:
bottomleft = oglu.gluUnProject(0,0,depth)
bottomright = oglu.gluUnProject(self._winSize[0],0,depth)
topleft = oglu.gluUnProject(0,self._winSize[1],depth)
topright = oglu.gluUnProject(self._winSize[0],self._winSize[1],depth)
self.dims = topleft, topright, bottomright, bottomleft
width = topright[0] - topleft[0]
height = topright[1] - bottomright[1]
self._qdims = topleft[0], topleft[1], width, height
self._depth = depth
LaminaScreenSurface.display(self)
| Python |
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyostila #
# 2008 Alarian #
# 2008 myfingershurt #
# 2008 Capo #
# 2008 Glorandwarf #
# 2008 QQStarS #
# 2008 Blazingamer #
# 2008 evilynux <evilynux@gmail.com> #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
import Player
from Song import Note, Tempo
from Mesh import Mesh
import Theme
import random
from copy import deepcopy
from Shader import shaders
from OpenGL.GL import *
import math
from numpy import array, float32
#myfingershurt: needed for multi-OS file fetching
import os
import Log
import Song #need the base song defines as well
class Guitar:
def __init__(self, engine, playerObj, editorMode = False, player = 0):
self.engine = engine
self.isDrum = False
self.isBassGuitar = False
self.isVocal = False
self.starPowerDecreaseDivisor = 200.0/self.engine.audioSpeedFactor
self.debugMode = False
self.gameMode2p = self.engine.config.get("game","multiplayer_mode")
self.matchingNotes = []
self.sameNoteHopoString = False
self.hopoProblemNoteNum = -1
self.useMidiSoloMarkers = False
self.currentGuitarSoloHitNotes = 0
self.cappedScoreMult = 0
self.starSpinFrameIndex = 0
self.starSpinFrames = 16
self.isStarPhrase = False
self.finalStarSeen = False
self.freestyleActive = False
self.drumFillsActive = False
self.bigRockEndingMarkerSeen = False
#MFH - I do not understand fully how the handicap scorecard works at the moment, nor do I have the time to figure it out.
#... so for now, I'm just writing some extra code here for the early hitwindow size handicap.
self.earlyHitWindowSizeFactor = 0.5
# Volshebnyi - BRE scoring variables
self.freestyleEnabled = False
self.freestyleStart = 0
self.freestyleFirstHit = 0
self.freestyleLength = 0
self.freestyleLastHit = 0
self.freestyleBonusFret = -2
self.freestyleLastFretHitTime = range(5)
self.freestyleBaseScore = 750
self.freestylePeriod = 1000
self.freestylePercent = 50
self.freestyleOffset = 5
self.freestyleSP = False
#empty variables for class compatibility
self.totalPhrases = 0
self.accThresholdWorstLate = 0
self.accThresholdVeryLate = 0
self.accThresholdLate = 0
self.accThresholdSlightlyLate = 0
self.accThresholdExcellentLate = 0
self.accThresholdPerfect = 0
self.accThresholdExcellentEarly = 0
self.accThresholdSlightlyEarly = 0
self.accThresholdEarly = 0
self.accThresholdVeryEarly = 0
self.tempoBpm = 120 #MFH - default is NEEDED here...
self.logClassInits = self.engine.config.get("game", "log_class_inits")
if self.logClassInits == 1:
Log.debug("Guitar class init...")
self.incomingNeckMode = self.engine.config.get("game", "incoming_neck_mode")
self.bigRockEndings = self.engine.config.get("game", "big_rock_endings")
self.boardWidth = Theme.neckWidth
self.boardLength = Theme.neckLength
#death_au: fixed neck size
if Theme.twoDnote == False or Theme.twoDkeys == False:
self.boardWidth = 3.6
self.boardLength = 9.0
self.beatsPerBoard = 5.0
self.beatsPerUnit = self.beatsPerBoard / self.boardLength
self.strings = 5
self.fretWeight = [0.0] * self.strings
self.fretActivity = [0.0] * self.strings
self.fretColors = Theme.fretColors
self.spColor = self.fretColors[5]
self.playedNotes = []
self.freestyleHitFlameCounts = [0 for n in range(self.strings+1)] #MFH
self.lastPlayedNotes = [] #MFH - for reverting when game discovers it implied incorrectly
self.missedNotes = []
self.missedNoteNums = []
self.editorMode = editorMode
self.selectedString = 0
self.time = 0.0
self.pickStartPos = 0
self.leftyMode = False
self.drumFlip = False
self.battleSuddenDeath = False
self.battleObjectsEnabled = []
self.battleSDObjectsEnabled = []
if self.engine.config.get("game", "battle_Whammy") == 1:
self.battleObjectsEnabled.append(4)
if self.engine.config.get("game", "battle_Diff_Up") == 1:
if playerObj.getDifficultyInt() > 0:
self.battleObjectsEnabled.append(2)
if self.engine.config.get("game", "battle_String_Break") == 1:
self.battleObjectsEnabled.append(3)
if self.engine.config.get("game", "battle_Double") == 1:
self.battleObjectsEnabled.append(7)
if self.engine.config.get("game", "battle_Death_Drain") == 1:
self.battleObjectsEnabled.append(1)
if self.engine.config.get("game", "battle_Amp_Overload") == 1:
self.battleObjectsEnabled.append(8)
if self.engine.config.get("game", "battle_Switch_Controls") == 1:
self.battleObjectsEnabled.append(6)
if self.engine.config.get("game", "battle_Steal") == 1:
self.battleObjectsEnabled.append(5)
#if self.engine.config.get("game", "battle_Tune") == 1:
# self.battleObjectsEnabled.append(9)
Log.debug(self.battleObjectsEnabled)
self.battleNextObject = 0
self.battleObjects = [0] * 3
self.battleBeingUsed = [0] * 2
self.battleStatus = [False] * 9
self.battleStartTimes = [0] * 9
self.battleGetTime = 0
self.battleLeftyLength = 8000 #
self.battleDiffUpLength = 15000
self.battleDiffUpValue = playerObj.getDifficultyInt()
self.battleDoubleLength = 8000
self.battleAmpLength = 8000
self.battleWhammyLimit = 6 #
self.battleWhammyNow = 0
self.battleWhammyDown = False
self.battleBreakLimit = 8.0
self.battleBreakNow = 0.0
self.battleBreakString = 0
self.battleObjectGained = 0
self.battleSuddenDeath = False
self.battleDrainStart = 0
self.battleDrainLength = 8000
#self.actualBpm = 0.0
self.currentBpm = 120.0
self.currentPeriod = 60000.0 / self.currentBpm
self.targetBpm = self.currentBpm
self.targetPeriod = 60000.0 / self.targetBpm
self.lastBpmChange = -1.0
self.baseBeat = 0.0
self.indexFps = self.engine.config.get("video", "fps") #QQstarS
#########For Animations
self.Animspeed = 30#Lower value = Faster animations
#For Animated Starnotes
self.indexCount = 0
#Alarian, For animated hitglow
self.HCount = 0
self.HCount2 = 0
self.HCountAni = False
self.Hitanim = True
self.Hitanim2 = True
#myfingershurt: to keep track of pause status here as well
self.paused = False
self.spEnabled = True
self.starPower = 0
self.starPowerGained = False
self.killPoints = False
self.starpowerMode = self.engine.config.get("game", "starpower_mode") #MFH
#get difficulty
self.difficulty = playerObj.getDifficultyInt()
self.controlType = playerObj.controlType
#myfingershurt:
self.hopoStyle = self.engine.config.get("game", "hopo_system")
self.gh2sloppy = self.engine.config.get("game", "gh2_sloppy")
if self.gh2sloppy == 1:
self.hopoStyle = 4
self.LastStrumWasChord = False
self.spRefillMode = self.engine.config.get("game","sp_notes_while_active")
self.hitglow_color = self.engine.config.get("video", "hitglow_color") #this should be global, not retrieved every fret render.
self.sfxVolume = self.engine.config.get("audio", "SFX_volume")
self.vbpmLogicType = self.engine.config.get("debug", "use_new_vbpm_beta")
#myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered.
self.notedisappear = self.engine.config.get("game", "notedisappear")
self.fretsUnderNotes = self.engine.config.get("game", "frets_under_notes")
self.muteSustainReleases = self.engine.config.get("game", "sustain_muting") #MFH
self.hitw = self.engine.config.get("game", "note_hit_window") #this should be global, not retrieved every BPM change.
if self.hitw == 0:
self.hitw = 2.3
elif self.hitw == 1:
self.hitw = 1.9
elif self.hitw == 2:
self.hitw = 1.2
elif self.hitw == 3:
self.hitw = 1.0
elif self.hitw == 4:
self.hitw = 0.70
else:
self.hitw = 1.2
self.twoChord = 0
self.twoChordApply = False
self.hopoActive = 0
#myfingershurt: need a separate variable to track whether or not hopos are actually active
self.wasLastNoteHopod = False
self.hopoLast = -1
self.hopoColor = (0, .5, .5)
self.player = player
self.hit = [False, False, False, False, False]
self.freestyleHit = [False, False, False, False, False]
self.playerObj = playerObj
playerObj = None
#Get theme
themename = self.engine.data.themeLabel
#now theme determination logic is only in data.py:
self.theme = self.engine.data.theme
#check if BRE enabled
if self.bigRockEndings == 2 or (self.theme == 2 and self.bigRockEndings == 1):
self.freestyleEnabled = True
#blazingamer
self.nstype = self.engine.config.get("game", "nstype")
self.twoDnote = Theme.twoDnote
self.twoDkeys = Theme.twoDkeys
self.threeDspin = Theme.threeDspin
self.killfx = self.engine.config.get("performance", "killfx")
self.killCount = 0
self.noterotate = self.engine.config.get("coffee", "noterotate")
#akedrou
self.coOpRescueTime = 0.0
#MFH- fixing neck speed
if self.nstype < 3: #not constant mode:
self.speed = self.engine.config.get("coffee", "neckSpeed")*0.01
else: #constant mode
self.speed = 410 - self.engine.config.get("coffee", "neckSpeed") #invert this value
self.bigMax = 1
self.keys = []
self.actions = []
self.soloKey = []
self.setBPM(self.currentBpm)
if self.starpowerMode == 1:
self.starNotesSet = False
else:
self.starNotesSet = True
self.maxStars = []
self.starNotes = []
self.totalNotes = 0
engine.loadImgDrawing(self, "glowDrawing", "glow.png")
self.oFlash = None
#MFH - making hitflames optional
self.hitFlamesPresent = False
try:
engine.loadImgDrawing(self, "hitflames1Drawing", os.path.join("themes",themename,"hitflames1.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "hitflames2Drawing", os.path.join("themes",themename,"hitflames2.png"), textureSize = (128, 128))
self.hitFlamesPresent = True
except IOError:
self.hitFlamesPresent = False
self.hitflames1Drawing = None
self.hitflames2Drawing = None
try:
engine.loadImgDrawing(self, "hitflamesAnim", os.path.join("themes",themename,"hitflamesanimation.png"), textureSize = (128, 128))
except IOError:
self.Hitanim2 = False
try:
engine.loadImgDrawing(self, "hitglowAnim", os.path.join("themes",themename,"hitglowanimation.png"), textureSize = (128, 128))
except IOError:
try:
engine.loadImgDrawing(self, "hitglowDrawing", os.path.join("themes",themename,"hitglow.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "hitglow2Drawing", os.path.join("themes",themename,"hitglow2.png"), textureSize = (128, 128))
except IOError:
self.hitglowDrawing = None
self.hitglow2Drawing = None
self.hitFlamesPresent = False #MFH - shut down all flames if these are missing.
self.Hitanim = False
#myfingershurt:
self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck")
self.guitarSoloNeckMode = self.engine.config.get("game", "guitar_solo_neck")
self.starspin = self.engine.config.get("performance", "starspin")
if self.twoDnote == True:
#Spinning starnotes or not?
#myfingershurt: allowing any non-Rock Band theme to have spinning starnotes if the SpinNotes.png is available in that theme's folder
if self.starspin == True and self.theme < 2:
#myfingershurt: check for SpinNotes, if not there then no animation
if self.gameMode2p == 6:
try:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotesbattle.png"))
self.starSpinFrames = 8
except IOError:
try:
self.starspin = False
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png"))
except IOError:
self.starspin = False
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
try:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"spinnotes.png"))
except IOError:
self.starspin = False
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
if self.gameMode2p == 6:
try:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notesbattle.png"))
except IOError:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
else:
engine.loadImgDrawing(self, "noteButtons", os.path.join("themes",themename,"notes.png"))
#mfh - adding fallback for beta option
else:
#MFH - can't use IOError for fallback logic for a Mesh() call...
if self.engine.fileExists(os.path.join("themes", themename, "note.dae")):
engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "note.dae")))
else:
engine.resource.load(self, "noteMesh", lambda: Mesh(engine.resource.fileName("note.dae")))
try:
for i in range(5):
engine.loadImgDrawing(self, "notetex"+chr(97+i), os.path.join("themes", themename, "notetex_"+chr(97+i)+".png"))
self.notetex = True
except IOError:
self.notetex = False
if self.engine.fileExists(os.path.join("themes", themename, "star.dae")):
engine.resource.load(self, "starMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "star.dae")))
else:
self.starMesh = None
try:
for i in range(5):
engine.loadImgDrawing(self, "startex"+chr(97+i), os.path.join("themes", themename, "startex_"+chr(97+i)+".png"))
self.startex = True
except IOError:
self.startex = False
if self.gameMode2p == 6:
try:
engine.loadImgDrawing(self, "battleFrets", os.path.join("themes", themename,"battle_frets.png"))
except IOError:
self.battleFrets = None
if self.twoDkeys == True:
engine.loadImgDrawing(self, "fretButtons", os.path.join("themes",themename,"fretbuttons.png"))
else:
#MFH - can't use IOError for fallback logic for a Mesh() call...
if self.engine.fileExists(os.path.join("themes", themename, "key.dae")):
engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("themes", themename, "key.dae")))
else:
engine.resource.load(self, "keyMesh", lambda: Mesh(engine.resource.fileName("key.dae")))
try:
for i in range(5):
engine.loadImgDrawing(self, "keytex"+chr(97+i), os.path.join("themes", themename, "keytex_"+chr(97+i)+".png"))
self.keytex = True
except IOError:
self.keytex = False
if self.theme == 0 or self.theme == 1:
engine.loadImgDrawing(self, "hitlightning", os.path.join("themes",themename,"lightning.png"), textureSize = (128, 128))
#inkk: loading theme-dependant tail images
#myfingershurt: must ensure the new tails don't affect the Rock Band mod...
self.simpleTails = False
try:
for i in range(0,7):
engine.loadImgDrawing(self, "tail"+str(i), os.path.join("themes",themename,"tails","tail"+str(i)+".png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "taile"+str(i), os.path.join("themes",themename,"tails","taile"+str(i)+".png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "btail"+str(i), os.path.join("themes",themename,"tails","btail"+str(i)+".png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "btaile"+str(i), os.path.join("themes",themename,"tails","btaile"+str(i)+".png"), textureSize = (128, 128))
except IOError:
self.simpleTails = True
Log.debug("Simple tails used; complex tail loading error...")
try:
engine.loadImgDrawing(self, "tail1", os.path.join("themes",themename,"tail1.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "tail2", os.path.join("themes",themename,"tail2.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "bigTail1", os.path.join("themes",themename,"bigtail1.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "bigTail2", os.path.join("themes",themename,"bigtail2.png"), textureSize = (128, 128))
except IOError:
engine.loadImgDrawing(self, "tail1", "tail1.png", textureSize = (128, 128))
engine.loadImgDrawing(self, "tail2", "tail2.png", textureSize = (128, 128))
engine.loadImgDrawing(self, "bigTail1", "bigtail1.png", textureSize = (128, 128))
engine.loadImgDrawing(self, "bigTail2", "bigtail2.png", textureSize = (128, 128))
try:
engine.loadImgDrawing(self, "kill1", os.path.join("themes", themename, "kill1.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "kill2", os.path.join("themes", themename, "kill2.png"), textureSize = (128, 128))
except IOError:
engine.loadImgDrawing(self, "kill1", "kill1.png", textureSize = (128, 128))
engine.loadImgDrawing(self, "kill2", "kill2.png", textureSize = (128, 128))
#MFH - freestyle tails (for drum fills & BREs)
try:
engine.loadImgDrawing(self, "freestyle1", os.path.join("themes", themename, "freestyletail1.png"), textureSize = (128, 128))
engine.loadImgDrawing(self, "freestyle2", os.path.join("themes", themename, "freestyletail2.png"), textureSize = (128, 128))
except IOError:
engine.loadImgDrawing(self, "freestyle1", "freestyletail1.png", textureSize = (128, 128))
engine.loadImgDrawing(self, "freestyle2", "freestyletail2.png", textureSize = (128, 128))
self.meshColor = Theme.meshColor
self.hopoColor = Theme.hopoColor
self.spotColor = Theme.spotColor
self.keyColor = Theme.keyColor
self.key2Color = Theme.key2Color
self.tracksColor = Theme.tracksColor
self.flameColors = Theme.flameColors
self.gh3flameColor = Theme.gh3flameColor
self.flameSizes = Theme.flameSizes
self.glowColor = Theme.glowColor
self.twoChordMax = False
self.disableVBPM = self.engine.config.get("game", "disable_vbpm")
self.disableNoteSFX = self.engine.config.get("video", "disable_notesfx")
self.disableFretSFX = self.engine.config.get("video", "disable_fretsfx")
self.disableFlameSFX = self.engine.config.get("video", "disable_flamesfx")
self.overdriveFlashCounts = self.indexFps/4 #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second
self.rockLevel = 0.0
#Blazingamer: These variables are updated through the guitarscene which then pass
#through to the neck because it is used in both the neck.py and the guitar.py
self.canGuitarSolo = False
self.guitarSolo = False
self.fretboardHop = 0.00 #stump
self.scoreMultiplier = 1
self.coOpFailed = False #akedrou
self.coOpRestart = False #akedrou
self.starPowerActive = False
self.overdriveFlashCount = self.overdriveFlashCounts
self.ocount = 0
def selectPreviousString(self):
self.selectedString = (self.selectedString - 1) % self.strings
def selectString(self, string):
self.selectedString = string % self.strings
def selectNextString(self):
self.selectedString = (self.selectedString + 1) % self.strings
def noteBeingHeld(self):
noteHeld = False
for i in range(0,5):
if self.hit[i] == True:
noteHeld = True
return noteHeld
def isKillswitchPossible(self):
possible = False
for i in range(0,5):
if self.hit[i] == True:
possible = True
return possible
def setBPM(self, bpm):
if bpm > 200:
bpm = 200
#MFH - Filter out unnecessary BPM settings (when currentBPM is already set!)
#if self.actualBpm != bpm:
# self.actualBpm = bpm
self.currentBpm = bpm #update current BPM as well
#MFH - Neck speed determination:
if self.nstype == 0: #BPM mode
self.neckSpeed = (340 - bpm)/self.speed
elif self.nstype == 1: #Difficulty mode
if self.difficulty == 0: #expert
self.neckSpeed = 220/self.speed
elif self.difficulty == 1:
self.neckSpeed = 250/self.speed
elif self.difficulty == 2:
self.neckSpeed = 280/self.speed
else: #easy
self.neckSpeed = 300/self.speed
elif self.nstype == 2: #BPM & Diff mode
if self.difficulty == 0: #expert
self.neckSpeed = (226-(bpm/10))/self.speed
elif self.difficulty == 1:
self.neckSpeed = (256-(bpm/10))/self.speed
elif self.difficulty == 2:
self.neckSpeed = (286-(bpm/10))/self.speed
else: #easy
self.neckSpeed = (306-(bpm/10))/self.speed
else: #Percentage mode - pre-calculated
self.neckSpeed = self.speed
self.earlyMargin = 250 - bpm/5 - 70*self.hitw
self.lateMargin = 250 - bpm/5 - 70*self.hitw
#self.earlyMargin = self.lateMargin * self.earlyHitWindowSizeFactor #MFH - scale early hit window here
#self.noteReleaseMargin = 200 - bpm/5 - 70*self.hitw
#if (self.noteReleaseMargin < (200 - bpm/5 - 70*1.2)): #MFH - enforce "tight" hitwindow minimum note release margin
# self.noteReleaseMargin = (200 - bpm/5 - 70*1.2)
if self.muteSustainReleases == 4: #tight
self.noteReleaseMargin = (200 - bpm/5 - 70*1.2)
elif self.muteSustainReleases == 3: #standard
self.noteReleaseMargin = (200 - bpm/5 - 70*1.0)
elif self.muteSustainReleases == 2: #wide
self.noteReleaseMargin = (200 - bpm/5 - 70*0.7)
else: #ultra-wide
self.noteReleaseMargin = (200 - bpm/5 - 70*0.5)
#MFH - TODO - only calculate the below values if the realtime hit accuracy feedback display is enabled - otherwise this is a waste!
self.accThresholdWorstLate = (0-self.lateMargin)
self.accThresholdVeryLate = (0-(3*self.lateMargin/4))
self.accThresholdLate = (0-(2*self.lateMargin/4))
self.accThresholdSlightlyLate = (0-(1*self.lateMargin/4))
self.accThresholdExcellentLate = -1.0
self.accThresholdPerfect = 1.0
self.accThresholdExcellentEarly = (1*self.lateMargin/4)
self.accThresholdSlightlyEarly = (2*self.lateMargin/4)
self.accThresholdEarly = (3*self.lateMargin/4)
self.accThresholdVeryEarly = (4*self.lateMargin/4)
def setMultiplier(self, multiplier):
self.scoreMultiplier = multiplier
def renderTail(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False, freestyleTail = 0, pos = 0):
#volshebnyi - if freestyleTail == 0, act normally.
# if freestyleTail == 1, render an freestyle tail
# if freestyleTail == 2, render highlighted freestyle tail
if not self.simpleTails:#Tail Colors
tailcol = (1,1,1,1)
else:
if big == False and tailOnly == True:
tailcol = (.2 + .4, .2 + .4, .2 + .4, 1)
else:
tailcol = (color)
#volshebnyi - tail color when sp is active
if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):#8bit
c = self.fretColors[5]
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
if flat:
tailscale = (1, .1, 1)
else:
tailscale = None
if sustain:
if not length == None:
size = (.08, length)
if size[1] > self.boardLength:
s = self.boardLength
else:
s = length
# if freestyleTail == 1, render freestyle tail
if freestyleTail == 0: #normal tail rendering
#myfingershurt: so any theme containing appropriate files can use new tails
if not self.simpleTails:
if big == True and tailOnly == True:
if kill and self.killfx == 0:
zsize = .25
tex1 = self.kill1
tex2 = self.kill2
#volshebnyi - killswitch tail width and color change
kEffect = ( math.sin( pos / 50 ) + 1 ) /2
size = (0.02+kEffect*0.15, s - zsize)
c = [self.fretColors[6][0],self.fretColors[6][1],self.fretColors[6][2]]
if c != [0,0,0]:
for i in range(0,3):
c[i]=c[i]*kEffect+color[i]*(1-kEffect)
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
else:
zsize = .25
size = (.17, s - zsize)
if self.starPowerActive and not color == (0,0,0,1):
tex1 = self.btail6
tex2 = self.btaile6
else:
if fret == 0:
tex1 = self.btail1
tex2 = self.btaile1
elif fret == 1:
tex1 = self.btail2
tex2 = self.btaile2
elif fret == 2:
tex1 = self.btail3
tex2 = self.btaile3
elif fret == 3:
tex1 = self.btail4
tex2 = self.btaile4
elif fret == 4:
tex1 = self.btail5
tex2 = self.btaile5
else:
zsize = .15
size = (.1, s - zsize)
if tailOnly:#Note let go
tex1 = self.tail0
tex2 = self.taile0
else:
if self.starPowerActive and not color == (0,0,0,1):
tex1 = self.tail6
tex2 = self.taile6
else:
if fret == 0:
tex1 = self.tail1
tex2 = self.taile1
elif fret == 1:
tex1 = self.tail2
tex2 = self.taile2
elif fret == 2:
tex1 = self.tail3
tex2 = self.taile3
elif fret == 3:
tex1 = self.tail4
tex2 = self.taile4
elif fret == 4:
tex1 = self.tail5
tex2 = self.taile5
else:
if big == True and tailOnly == True:
if kill:
zsize = .25
tex1 = self.kill1
tex2 = self.kill2
#volshebnyi - killswitch tail width and color change
kEffect = ( math.sin( pos / 50 ) + 1 ) /2
size = (0.02+kEffect*0.15, s - zsize)
c = [self.fretColors[6][0],self.fretColors[6][1],self.fretColors[6][2]]
if c != [0,0,0]:
for i in range(0,3):
c[i]=c[i]*kEffect+color[i]*(1-kEffect)
tailcol = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
else:
zsize = .25
size = (.11, s - zsize)
tex1 = self.bigTail1
tex2 = self.bigTail2
else:
zsize = .15
size = (.08, s - zsize)
tex1 = self.tail1
tex2 = self.tail2
else: #freestyleTail > 0
# render an inactive freestyle tail (self.freestyle1 & self.freestyle2)
zsize = .25
if self.freestyleActive:
size = (.30, s - zsize) #was .15
else:
size = (.15, s - zsize)
tex1 = self.freestyle1
tex2 = self.freestyle2
if freestyleTail == 1:
#glColor4f(*color)
c1, c2, c3, c4 = color
tailGlow = 1 - (pos - self.freestyleLastFretHitTime[fret] ) / self.freestylePeriod
if tailGlow < 0:
tailGlow = 0
color = (c1 + c1*2.0*tailGlow, c2 + c2*2.0*tailGlow, c3 + c3*2.0*tailGlow, c4*0.6 + c4*0.4*tailGlow) #MFH - this fades inactive tails' color darker
tailcol = (color)
if self.theme == 2 and freestyleTail == 0 and big and tailOnly and shaders.enable("tail"):
color = (color[0]*1.5,color[1]*1.5,color[2]*1.5,1.0)
shaders.setVar("color",color)
if kill and self.killfx == 0:
h = shaders.getVar("height")
shaders.modVar("height",0.5,0.06/h-0.1)
shaders.setVar("offset",(5.0-size[1],0.0))
size=(size[0]*15,size[1])
self.engine.draw3Dtex(tex1, vertex = (-size[0], 0, size[0], size[1]), texcoord = (0.0, 0.0, 1.0, 1.0),
scale = tailscale, color = tailcol)
self.engine.draw3Dtex(tex2, vertex = (-size[0], size[1], size[0], size[1] + (zsize)),
scale = tailscale, texcoord = (0.0, 0.05, 1.0, 0.95), color = tailcol)
shaders.disable()
#MFH - this block of code renders the tail "beginning" - before the note, for freestyle "lanes" only
#volshebnyi
if freestyleTail > 0 and pos < self.freestyleStart + self.freestyleLength:
self.engine.draw3Dtex(tex2, vertex = (-size[0], 0-(zsize), size[0], 0 + (.05)),
scale = tailscale, texcoord = (0.0, 0.95, 1.0, 0.05), color = tailcol)
if tailOnly:
return
def renderNote(self, length, sustain, kill, color, flat = False, tailOnly = False, isTappable = False, big = False, fret = 0, spNote = False):
if flat:
glScalef(1, .1, 1)
if tailOnly:
return
if self.twoDnote == True:
#myfingershurt: this should be retrieved once at init, not repeatedly in-game whenever tails are rendered.
if self.notedisappear == True:#Notes keep on going when missed
notecol = (1,1,1)#capo
else:
if flat:#Notes disappear when missed
notecol = (.1,.1,.1)
else:
notecol = (1,1,1)
tailOnly == True
if self.theme < 2:
if self.starspin:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (0.150+self.starSpinFrameIndex*0.05, 0.175+self.starSpinFrameIndex*0.05)
else:
texY = (0.125+self.starSpinFrameIndex*0.05, 0.150+self.starSpinFrameIndex*0.05)
else:
if isTappable:
texY = (0.025,0.05)
else:
texY = (0,0.025)
if self.starPowerActive:
texY = (0.10,0.125) #QQstarS
if isTappable:
texSize = (0.2,0.4)
else:
texSize = (0,0.2)
else:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (0.6, 0.8)
else:
texY = (0.4,0.6)
else:
if isTappable:
texY = (0.2,0.4)
else:
texY = (0,0.2)
if self.starPowerActive:
texY = (0.8,1)
if isTappable:
texSize = (0.2,0.4)
else:
texSize = (0,0.2)
elif self.theme == 2:
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2)
texSize = (fret/5.0,fret/5.0+0.2)
if spNote == True:
if isTappable:
texY = (3*0.166667, 4*0.166667)
else:
texY = (2*0.166667, 3*0.166667)
else:
if isTappable:
texY = (1*0.166667, 2*0.166667)
else:
texY = (0, 1*0.166667)
#myfingershurt: adding spNote==False conditional so that star notes can appear in overdrive
if self.starPowerActive and spNote == False:
if isTappable:
texY = (5*0.166667, 1)
else:
texY = (4*0.166667, 5*0.166667)
self.engine.draw3Dtex(self.noteButtons, vertex = (-size[0],size[1],size[0],-size[1]), texcoord = (texSize[0],texY[0],texSize[1],texY[1]),
scale = (1,1,1), multiples = True, color = (1,1,1), vertscale = .2)
else:
shaders.setVar("Material",color,"notes")
#mesh = outer ring (black)
#mesh_001 = main note (key color)
#mesh_002 = top (spot or hopo if no mesh_003)
#mesh_003 = hopo bump (hopo color)
if spNote == True and self.starMesh is not None:
meshObj = self.starMesh
else:
meshObj = self.noteMesh
glPushMatrix()
glEnable(GL_DEPTH_TEST)
glDepthMask(1)
glShadeModel(GL_SMOOTH)
if self.noterotate:
glRotatef(90, 0, 1, 0)
glRotatef(-90, 1, 0, 0)
if spNote == True and self.threeDspin == True:
glRotate(90 + self.time/3, 0, 1, 0)
#death_au: fixed 3D note colours
#volshebnyi - note color when sp is active
glColor4f(*color)
if self.starPowerActive and self.theme != 2 and not color == (0,0,0,1):
c = self.fretColors[5]
glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1)
glRotatef(Theme.noterotdegrees, 0, 0, Theme.noterot[fret])
if self.notetex == True and spNote == False:
glColor3f(1,1,1)
glEnable(GL_TEXTURE_2D)
getattr(self,"notetex"+chr(97+fret)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
if isTappable:
mesh = "Mesh_001"
else:
mesh = "Mesh"
meshObj.render(mesh)
if shaders.enable("notes"):
shaders.setVar("isTextured",True)
meshObj.render(mesh)
shaders.disable()
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
elif self.startex == True and spNote == True:
glColor3f(1,1,1)
glEnable(GL_TEXTURE_2D)
getattr(self,"startex"+chr(97+fret)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
if isTappable:
mesh = "Mesh_001"
else:
mesh = "Mesh"
meshObj.render(mesh)
if shaders.enable("notes"):
shaders.setVar("isTextured",True)
meshObj.render(mesh)
shaders.disable()
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
else:
if shaders.enable("notes"):
shaders.setVar("isTextured",False)
meshObj.render("Mesh_001")
shaders.disable()
glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2])
if isTappable:
if self.hopoColor[0] == -2:
glColor4f(*color)
else:
glColor3f(self.hopoColor[0], self.hopoColor[1], self.hopoColor[2])
if(meshObj.find("Mesh_003")) == True:
meshObj.render("Mesh_003")
glColor3f(self.spotColor[0], self.spotColor[1], self.spotColor[2])
meshObj.render("Mesh_002")
glColor3f(self.meshColor[0], self.meshColor[1], self.meshColor[2])
meshObj.render("Mesh")
glDepthMask(0)
glPopMatrix()
def renderFreestyleLanes(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
#boardWindowMin = pos - self.currentPeriod * 2
boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard
track = song.midiEventTrack[self.player]
#MFH - render 5 freestyle tails when Song.freestyleMarkingNote comes up
if self.freestyleEnabled:
freestyleActive = False
#for time, event in track.getEvents(boardWindowMin, boardWindowMax):
for time, event in track.getEvents(pos - self.freestyleOffset , boardWindowMax + self.freestyleOffset):
if isinstance(event, Song.MarkerNote):
if event.number == Song.freestyleMarkingNote:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
w = self.boardWidth / self.strings
self.freestyleLength = event.length #volshebnyi
self.freestyleStart = time # volshebnyi
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
#MFH - must extend the tail past the first fretboard section dynamically so we don't have to render the entire length at once
#volshebnyi - allow tail to move under frets
if time - self.freestyleOffset < pos:
freestyleActive = True
if z < -1.5:
length += z +1.5
z = -1.5
#MFH - render 5 freestyle tails
for theFret in range(0,5):
x = (self.strings / 2 - theFret) * w
c = self.fretColors[theFret]
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (theFret + 1), z)
freestyleTailMode = 1
self.renderTail(length, sustain = True, kill = False, color = color, flat = False, tailOnly = True, isTappable = False, big = True, fret = theFret, spNote = False, freestyleTail = freestyleTailMode, pos = pos)
glPopMatrix()
self.freestyleActive = freestyleActive
def renderNotes(self, visibility, song, pos, killswitch):
if not song:
return
if not song.readyToGo:
return
# Update dynamic period
self.currentPeriod = self.neckSpeed
#self.targetPeriod = self.neckSpeed
self.killPoints = False
w = self.boardWidth / self.strings
track = song.track[self.player]
num = 0
enable = True
starEventsInView = False
renderedNotes = reversed(self.getRequiredNotesForRender(song,pos))
for time, event in renderedNotes:
#for time, event in reversed(track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)): #MFH - reverse order of note rendering
if isinstance(event, Tempo):
self.tempoBpm = event.bpm
if self.lastBpmChange > 0 and self.disableVBPM == True:
continue
if (pos - time > self.currentPeriod or self.lastBpmChange < 0) and time > self.lastBpmChange:
self.baseBeat += (time - self.lastBpmChange) / self.currentPeriod
self.targetBpm = event.bpm
self.lastBpmChange = time
# self.setBPM(self.targetBpm) # glorandwarf: was setDynamicBPM(self.targetBpm)
continue
if not isinstance(event, Note):
continue
if (event.noteBpm == 0.0):
event.noteBpm = self.tempoBpm
if self.coOpFailed:
if self.coOpRestart:
if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2):
continue
elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos:
self.coOpFailed = False
self.coOpRestart = False
Log.debug("Turning off coOpFailed. Rescue successful.")
else:
continue #can't break. Tempo.
c = self.fretColors[event.number]
x = (self.strings / 2 - event.number) * w
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
#volshebnyi - hide notes in BRE zone if BRE enabled
if self.freestyleEnabled and self.freestyleStart > 0:
if time >= self.freestyleStart-self.freestyleOffset and time < self.freestyleStart + self.freestyleLength+self.freestyleOffset:
z = -2.0
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
if event.length > 120:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
else:
length = 0
flat = False
tailOnly = False
spNote = False
#myfingershurt: user setting for starpower refill / replenish notes
if self.starPowerActive:
if self.spRefillMode == 0: #mode 0 = no starpower / overdrive refill notes
self.spEnabled = False
elif self.spRefillMode == 1 and self.theme != 2: #mode 1 = overdrive refill notes in RB themes only
self.spEnabled = False
elif self.spRefillMode == 2 and song.midiStyle != 1: #mode 2 = refill based on MIDI type
self.spEnabled = False
if event.star:
#self.isStarPhrase = True
starEventsInView = True
if event.finalStar:
self.finalStarSeen = True
starEventsInView = True
if event.star and self.spEnabled:
spNote = True
if event.finalStar and self.spEnabled:
spNote = True
if event.played or event.hopod:
if event.flameCount < 1 and not self.starPowerGained:
Log.debug("star power added")
if self.gameMode2p == 6:
if self.battleSuddenDeath:
self.battleObjects = [1] + self.battleObjects[:2]
else:
self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2]
self.battleGetTime = pos
self.battleObjectGained = True
Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects))
else:
if self.starPower < 100:
self.starPower += 25
if self.starPower > 100:
self.starPower = 100
self.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer
self.starPowerGained = True
if event.tappable < 2:
isTappable = False
else:
isTappable = True
# Clip the played notes to the origin
#myfingershurt: this should be loaded once at init, not every render...
if self.notedisappear == True:#Notes keep on going when missed
###Capo###
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
if z < 0 and not (event.played or event.hopod):
color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f)
flat = True
###endCapo###
else:#Notes disappear when missed
if z < 0:
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
else:
color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f)
flat = True
big = False
self.bigMax = 0
for i in range(0,5):
if self.hit[i]:
big = True
self.bigMax += 1
#MFH - filter out this tail whitening when starpower notes have been disbled from a screwup
if self.spEnabled and killswitch:
if event.star or event.finalStar:
if big == True and tailOnly == True:
self.killPoints = True
color = (1,1,1,1)
if z + length < -1.0:
continue
if event.length <= 120:
length = None
sustain = False
if event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
sustain = True
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z)
if shaders.turnon:
shaders.setVar("note_position",(x, (1.0 - visibility) ** (event.number + 1), z),"notes")
if self.battleStatus[8]:
renderNote = random.randint(0,2)
else:
renderNote = 0
if renderNote == 0:
if big == True and num < self.bigMax:
num += 1
self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote)
else:
self.renderNote(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote)
glPopMatrix()
if (not starEventsInView and self.finalStarSeen):
self.spEnabled = True
self.finalStarSeen = False
self.isStarPhrase = False
def renderTails(self, visibility, song, pos, killswitch):
if not song:
return
if not song.readyToGo:
return
# Update dynamic period
self.currentPeriod = self.neckSpeed
#self.targetPeriod = self.neckSpeed
self.killPoints = False
w = self.boardWidth / self.strings
track = song.track[self.player]
num = 0
enable = True
renderedNotes = self.getRequiredNotesForRender(song,pos)
for time, event in renderedNotes:
#for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard):
if isinstance(event, Tempo):
self.tempoBpm = event.bpm
continue
if not isinstance(event, Note):
continue
if (event.noteBpm == 0.0):
event.noteBpm = self.tempoBpm
if self.coOpFailed:
if self.coOpRestart:
if time - self.coOpRescueTime < (self.currentPeriod * self.beatsPerBoard * 2):
continue
elif self.coOpRescueTime + (self.currentPeriod * self.beatsPerBoard * 2) < pos:
self.coOpFailed = False
self.coOpRestart = False
Log.debug("Turning off coOpFailed. Rescue successful.")
else:
continue
c = self.fretColors[event.number]
x = (self.strings / 2 - event.number) * w
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength * .8:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
color = (.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], 1 * visibility * f)
if event.length > 120:
length = (event.length - 50) / self.currentPeriod / self.beatsPerUnit
else:
length = 0
flat = False
tailOnly = False
spNote = False
#myfingershurt: user setting for starpower refill / replenish notes
if event.star and self.spEnabled:
spNote = True
if event.finalStar and self.spEnabled:
spNote = True
if event.played or event.hopod:
if event.flameCount < 1 and not self.starPowerGained:
if self.gameMode2p == 6:
if self.battleSuddenDeath:
self.battleObjects = [1] + self.battleObjects[:2]
else:
self.battleObjects = [self.battleObjectsEnabled[random.randint(0,len(self.battleObjectsEnabled)-1)]] + self.battleObjects[:2]
self.battleGetTime = pos
self.battleObjectGained = True
Log.debug("Battle Object Gained, Objects %s" % str(self.battleObjects))
else:
if self.starPower < 100:
self.starPower += 25
if self.starPower > 100:
self.starPower = 100
self.overdriveFlashCount = 0 #MFH - this triggers the oFlash strings & timer
self.starPowerGained = True
if self.theme == 2:
self.ocount = 0
if event.tappable < 2:
isTappable = False
else:
isTappable = True
# Clip the played notes to the origin
#myfingershurt: this should be loaded once at init, not every render...
if self.notedisappear == True:#Notes keep on going when missed
###Capo###
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
if z < 0 and not (event.played or event.hopod):
color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f)
flat = True
###endCapo###
else:#Notes disappear when missed
if z < 0:
if event.played or event.hopod:
tailOnly = True
length += z
z = 0
if length <= 0:
continue
else:
color = (.2 + .4, .2 + .4, .2 + .4, .5 * visibility * f)
flat = True
big = False
self.bigMax = 0
for i in range(0,5):
if self.hit[i]:
big = True
self.bigMax += 1
if self.spEnabled and killswitch:
if event.star or event.finalStar:
if big == True and tailOnly == True:
self.killPoints = True
color = (1,1,1,1)
if z + length < -1.0:
continue
if event.length <= 120:
length = None
sustain = False
if event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
sustain = True
glPushMatrix()
glTranslatef(x, (1.0 - visibility) ** (event.number + 1), z)
if self.battleStatus[8]:
renderNote = random.randint(0,2)
else:
renderNote = 0
if renderNote == 0:
if big == True and num < self.bigMax:
num += 1
self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, big = True, fret = event.number, spNote = spNote, pos = pos)
else:
self.renderTail(length, sustain = sustain, kill = killswitch, color = color, flat = flat, tailOnly = tailOnly, isTappable = isTappable, fret = event.number, spNote = spNote, pos = pos)
glPopMatrix()
if killswitch and self.killfx == 1:
glBlendFunc(GL_SRC_ALPHA, GL_ONE)
for time, event in self.playedNotes:
step = self.currentPeriod / 16
t = time + event.length
x = (self.strings / 2 - event.number) * w
c = self.fretColors[event.number]
s = t
proj = 1.0 / self.currentPeriod / self.beatsPerUnit
zStep = step * proj
def waveForm(t):
u = ((t - time) * -.1 + pos - time) / 64.0 + .0001
return (math.sin(event.number + self.time * -.01 + t * .03) + math.cos(event.number + self.time * .01 + t * .02)) * .1 + .1 + math.sin(u) / (5 * u)
glBegin(GL_TRIANGLE_STRIP)
f1 = 0
while t > time:
if ((t-pos)*proj) < self.boardLength:
z = (t - pos) * proj
else:
z = self.boardLength
if z < 0:
break
f2 = min((s - t) / (6 * step), 1.0)
a1 = waveForm(t) * f1
a2 = waveForm(t - step) * f2
if self.starPowerActive and self.theme != 2:#8bit
glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1)
else:
glColor4f(c[0], c[1], c[2], .5)
glVertex3f(x - a1, 0, z)
glVertex3f(x - a2, 0, z - zStep)
glColor4f(1, 1, 1, .75)
glVertex3f(x, 0, z)
glVertex3f(x, 0, z - zStep)
if self.starPowerActive and self.theme != 2:#8bit
glColor4f(self.spColor[0],self.spColor[1],self.spColor[2],1) #(.3,.7,.9,1)
else:
glColor4f(c[0], c[1], c[2], .5)
glVertex3f(x + a1, 0, z)
glVertex3f(x + a2, 0, z - zStep)
glVertex3f(x + a2, 0, z - zStep)
glVertex3f(x - a2, 0, z - zStep)
t -= step
f1 = f2
glEnd()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
def renderFrets(self, visibility, song, controls):
w = self.boardWidth / self.strings
size = (.22, .22)
v = 1.0 - visibility
glEnable(GL_DEPTH_TEST)
#Hitglow color option - myfingershurt sez this should be a Guitar class global, not retrieved ever fret render in-game...
for n in range(self.strings):
f = self.fretWeight[n]
c = self.fretColors[n]
if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
f += 0.25
glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility)
y = v + f / 6
x = (self.strings / 2 - n) * w
if self.twoDkeys == True:
if self.battleStatus[4]:
fretWhamOffset = self.battleWhammyNow * .15
fretColor = (1,1,1,.5)
else:
fretWhamOffset = 0
fretColor = (1,1,1,1)
size = (self.boardWidth/self.strings/2, self.boardWidth/self.strings/2.4)
if self.battleStatus[3] and self.battleFrets != None and self.battleBreakString == n:
texSize = (n/5.0+.042,n/5.0+0.158)
size = (.30, .40)
fretPos = 8 - round((self.battleBreakNow/self.battleBreakLimit) * 8)
texY = (fretPos/8.0,(fretPos + 1.0)/8)
self.engine.draw3Dtex(self.battleFrets, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]),
coord = (x,v + .08 + fretWhamOffset,0), multiples = True,color = fretColor, depth = True)
else:
texSize = (n/5.0,n/5.0+0.2)
texY = (0.0,1.0/3.0)
if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]):
texY = (1.0/3.0,2.0/3.0)
if self.hit[n] or (self.battleStatus[3] and self.battleBreakString == n):
texY = (2.0/3.0,1.0)
self.engine.draw3Dtex(self.fretButtons, vertex = (size[0],size[1],-size[0],-size[1]), texcoord = (texSize[0], texY[0], texSize[1], texY[1]),
coord = (x,v + fretWhamOffset,0), multiples = True,color = fretColor, depth = True)
else:
if self.keyMesh:
glPushMatrix()
glDepthMask(1)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glShadeModel(GL_SMOOTH)
glRotatef(90, 0, 1, 0)
glLightfv(GL_LIGHT0, GL_POSITION, (5.0, 10.0, -10.0, 0.0))
glLightfv(GL_LIGHT0, GL_AMBIENT, (.2, .2, .2, 0.0))
glLightfv(GL_LIGHT0, GL_DIFFUSE, (1.0, 1.0, 1.0, 0.0))
glRotatef(-90, 1, 0, 0)
glRotatef(-90, 0, 0, 1)
glRotatef(Theme.noterotdegrees, 0, 0, -Theme.noterot[n])
#Mesh - Main fret
#Key_001 - Top of fret (key_color)
#Key_002 - Bottom of fret (key2_color)
#Glow_001 - Only rendered when a note is hit along with the glow.svg
#if self.complexkey == True:
# glColor4f(.1 + .8 * c[0], .1 + .8 * c[1], .1 + .8 * c[2], visibility)
# if self.battleStatus[4]:
# glTranslatef(x, y + self.battleWhammyNow * .15, 0)
# else:
# glTranslatef(x, y, 0)
if self.keytex == True:
glColor4f(1,1,1,visibility)
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15, 0)
else:
glTranslatef(x, y, 0)
glEnable(GL_TEXTURE_2D)
getattr(self,"keytex"+chr(97+n)).texture.bind()
glMatrixMode(GL_TEXTURE)
glScalef(1, -1, 1)
glMatrixMode(GL_MODELVIEW)
if f and not self.hit[n]:
self.keyMesh.render("Mesh_001")
elif self.hit[n]:
self.keyMesh.render("Mesh_002")
else:
self.keyMesh.render("Mesh")
glMatrixMode(GL_TEXTURE)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
glDisable(GL_TEXTURE_2D)
else:
glColor4f(.1 + .8 * c[0] + f, .1 + .8 * c[1] + f, .1 + .8 * c[2] + f, visibility)
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15 + v * 6, 0)
else:
glTranslatef(x, y + v * 6, 0)
key = self.keyMesh
if(key.find("Glow_001")) == True:
key.render("Mesh")
if(key.find("Key_001")) == True:
glColor3f(self.keyColor[0], self.keyColor[1], self.keyColor[2])
key.render("Key_001")
if(key.find("Key_002")) == True:
glColor3f(self.key2Color[0], self.key2Color[1], self.key2Color[2])
key.render("Key_002")
else:
key.render()
glDisable(GL_LIGHTING)
glDisable(GL_LIGHT0)
glDepthMask(0)
glPopMatrix()
######################
f = self.fretActivity[n]
if f and self.disableFretSFX != True:
if self.glowColor[0] == -1:
s = 1.0
else:
s = 0.0
while s < 1:
ms = s * (math.sin(self.time) * .25 + 1)
if self.glowColor[0] == -2:
glColor3f(c[0] * (1 - ms), c[1] * (1 - ms), c[2] * (1 - ms))
else:
glColor3f(self.glowColor[0] * (1 - ms), self.glowColor[1] * (1 - ms), self.glowColor[2] * (1 - ms))
glPushMatrix()
if self.battleStatus[4]:
glTranslatef(x, y + self.battleWhammyNow * .15, 0)
else:
glTranslatef(x, y, 0)
glScalef(.1 + .02 * ms * f, .1 + .02 * ms * f, .1 + .02 * ms * f)
glRotatef( 90, 0, 1, 0)
glRotatef(-90, 1, 0, 0)
glRotatef(-90, 0, 0, 1)
if self.twoDkeys == False and self.keytex == False:
if(self.keyMesh.find("Glow_001")) == True:
key.render("Glow_001")
else:
key.render()
glPopMatrix()
s += 0.2
#Hitglow color
if self.hitglow_color == 0:
glowcol = (c[0], c[1], c[2])#Same as fret
elif self.hitglow_color == 1:
glowcol = (1, 1, 1)#Actual color in .svg-file
f += 2
if self.battleStatus[4]:
self.engine.draw3Dtex(self.glowDrawing, coord = (x, y + self.battleWhammyNow * .15, 0.01), rot = (f * 90 + self.time, 0, 1, 0),
texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f),
multiples = True, alpha = True, color = glowcol)
else:
self.engine.draw3Dtex(self.glowDrawing, coord = (x, y, 0.01), rot = (f * 90 + self.time, 0, 1, 0),
texcoord = (0.0, 0.0, 1.0, 1.0), vertex = (-size[0] * f, -size[1] * f, size[0] * f, size[1] * f),
multiples = True, alpha = True, color = glowcol)
#self.hit[n] = False #MFH -- why? This prevents frets from being rendered under / before the notes...
glDisable(GL_DEPTH_TEST)
def renderFreestyleFlames(self, visibility, controls):
if self.flameColors[0][0][0] == -1:
return
w = self.boardWidth / self.strings
#track = song.track[self.player]
size = (.22, .22)
v = 1.0 - visibility
if self.disableFlameSFX != True:
flameLimit = 10.0
flameLimitHalf = round(flameLimit/2.0)
for fretNum in range(self.strings):
if controls.getState(self.keys[fretNum]) or controls.getState(self.keys[fretNum+5]):
if self.freestyleHitFlameCounts[fretNum] < flameLimit:
ms = math.sin(self.time) * .25 + 1
x = (self.strings / 2 - fretNum) * w
ff = 1 + 0.25
y = v + ff / 6
if self.theme == 2:
y -= 0.5
#flameSize = self.flameSizes[self.scoreMultiplier - 1][fretNum]
flameSize = self.flameSizes[self.cappedScoreMult - 1][fretNum]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else: #MFH - fixing crash!
#try:
# flameColor = self.flameColors[self.scoreMultiplier - 1][fretNum]
#except IndexError:
flameColor = self.fretColors[fretNum]
if flameColor[0] == -2:
flameColor = self.fretColors[fretNum]
ff += 1.5 #ff first time is 2.75 after this
if self.freestyleHitFlameCounts[fretNum] < flameLimitHalf:
flamecol = tuple([flameColor[ifc] for ifc in range(3)])
rbStarColor = (.1, .1, .2, .3)
xOffset = (.0, - .005, .005, .0)
yOffset = (.20, .255, .255, .255)
scaleMod = .6 * ms * ff
scaleFix = (6.0, 5.5, 5.0, 4.7)
for step in range(4):
if self.starPowerActive and self.theme < 2:
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (rbStarColor[step],)*3
hfCount = self.freestyleHitFlameCounts[fretNum]
if step == 0:
hfCount += 1
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
else:
flameColorMod = 0.1 * (flameLimit - self.freestyleHitFlameCounts[fretNum])
flamecol = tuple([flameColor[ifc]*flameColorMod for ifc in range(3)])
xOffset = (.0, - .005, .005, .005)
yOffset = (.35, .405, .355, .355)
scaleMod = .6 * ms * ff
scaleFix = (3.0, 2.5, 2.0, 1.7)
for step in range(4):
hfCount = self.freestyleHitFlameCounts[fretNum]
if step == 0:
hfCount += 1
else:
if self.starPowerActive and self.theme < 2:
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.4+.1*step,)*3
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x+xOffset[step], y+yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + .05 * step + scaleMod, hfCount/scaleFix[step] + scaleMod, hfCount/scaleFix[step] + scaleMod),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
self.freestyleHitFlameCounts[fretNum] += 1
else: #MFH - flame count is done - reset it!
self.freestyleHitFlameCounts[fretNum] = 0 #MFH
def renderFlames(self, visibility, song, pos, controls):
if not song or self.flameColors[0][0][0] == -1:
return
w = self.boardWidth / self.strings
track = song.track[self.player]
size = (.22, .22)
v = 1.0 - visibility
if self.disableFlameSFX != True and (self.HCountAni == True and self.HCount2 > 12):
for n in range(self.strings):
f = self.fretWeight[n]
c = self.fretColors[n]
if f and (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
f += 0.25
y = v + f / 6
x = (self.strings / 2 - n) * w
f = self.fretActivity[n]
if f:
ms = math.sin(self.time) * .25 + 1
ff = f
ff += 1.2
#myfingershurt: need to cap flameSizes use of scoreMultiplier to 4x, the 5x and 6x bass groove mults cause crash:
self.cappedScoreMult = min(self.scoreMultiplier,4)
flameSize = self.flameSizes[self.cappedScoreMult - 1][n]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else:
flameColor = self.flameColors[self.cappedScoreMult - 1][n]
flameColorMod = (1.19, 1.97, 10.59)
flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)])
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.9,.9,.9)
if self.Hitanim != True:
self.engine.draw3Dtex(self.hitglowDrawing, coord = (x, y + .125, 0), rot = (90, 1, 0, 0),
scale = (0.5 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
#Alarian: Animated hitflames
else:
self.HCount = self.HCount + 1
if self.HCount > self.Animspeed-1:
self.HCount = 0
HIndex = (self.HCount * 16 - (self.HCount * 16) % self.Animspeed) / self.Animspeed
if HIndex > 15:
HIndex = 0
texX = (HIndex*(1/16.0), HIndex*(1/16.0)+(1/16.0))
self.engine.draw3Dtex(self.hitglowAnim, coord = (x, y + .225, 0), rot = (90, 1, 0, 0), scale = (2.4, 1, 3.3),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1))
ff += .3
flameColorMod = (1.19, 1.78, 12.22)
flamecol = tuple([flameColor[ifc]*flameColorMod[ifc] for ifc in range(3)])
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
flamecol = self.spColor
else: #Default starcolor (Rockband)
flamecol = (.8,.8,.8)
if self.Hitanim != True:
self.engine.draw3Dtex(self.hitglow2Drawing, coord = (x, y + .25, .05), rot = (90, 1, 0, 0),
scale = (.40 + .6 * ms * ff, 1.5 + .6 * ms * ff, 1 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = flamecol)
if self.disableFlameSFX != True:
flameLimit = 10.0
flameLimitHalf = round(flameLimit/2.0)
renderedNotes = self.getRequiredNotesForRender(song,pos)
for time, event in renderedNotes:
if isinstance(event, Tempo):
continue
if not isinstance(event, Note):
continue
if (event.played or event.hopod) and event.flameCount < flameLimit:
ms = math.sin(self.time) * .25 + 1
x = (self.strings / 2 - event.number) * w
xlightning = (self.strings / 2 - event.number)*2.2*w
ff = 1 + 0.25
y = v + ff / 6
if self.theme == 2:
y -= 0.5
flameSize = self.flameSizes[self.cappedScoreMult - 1][event.number]
if self.theme == 0 or self.theme == 1: #THIS SETS UP GH3 COLOR, ELSE ROCKBAND(which is DEFAULT in Theme.py)
flameColor = self.gh3flameColor
else:
flameColor = self.flameColors[self.cappedScoreMult - 1][event.number]
if flameColor[0] == -2:
flameColor = self.fretColors[event.number]
ff += 1.5 #ff first time is 2.75 after this
if self.Hitanim2 == True:
self.HCount2 = self.HCount2 + 1
self.HCountAni = False
if self.HCount2 > 12:
if not event.length > (1.4 * (60000.0 / event.noteBpm) / 4):
self.HCount2 = 0
else:
self.HCountAni = True
if event.flameCount < flameLimitHalf:
HIndex = (self.HCount2 * 13 - (self.HCount2 * 13) % 13) / 13
if HIndex > 12 and self.HCountAni != True:
HIndex = 0
texX = (HIndex*(1/13.0), HIndex*(1/13.0)+(1/13.0))
self.engine.draw3Dtex(self.hitflamesAnim, coord = (x, y + .665, 0), rot = (90, 1, 0, 0), scale = (1.6, 1.6, 4.9),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff),
texcoord = (texX[0],0.0,texX[1],1.0), multiples = True, alpha = True, color = (1,1,1))
else:
flameColorMod = 0.1 * (flameLimit - event.flameCount)
flamecol = tuple([ifc*flameColorMod for ifc in flameColor])
scaleChange = (3.0,2.5,2.0,1.7)
yOffset = (.35, .405, .355, .355)
vtx = flameSize * ff
scaleMod = .6 * ms * ff
for step in range(4):
#draw lightning in GH themes on SP gain
if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled:
self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0),
scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1))
continue
if step == 0:
yzscaleMod = event.flameCount/ scaleChange[step]
else:
yzscaleMod = (event.flameCount + 1)/ scaleChange[step]
if self.starPowerActive:
if self.theme == 0 or self.theme == 1:
spcolmod = .7+step*.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else:
flamecol = (.4+step*.1,)*3#Default starcolor (Rockband)
if self.hitFlamesPresent == True:
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod),
vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
elif self.hitFlamesPresent == True and self.Hitanim2 == False:
self.HCount2 = 13
self.HCountAni = True
if event.flameCount < flameLimitHalf:
flamecol = flameColor
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
spcolmod = .3
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else: #Default starcolor (Rockband)
flamecol = (.1,.1,.1)
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x, y + .20, 0), rot = (90, 1, 0, 0),
scale = (.25 + .6 * ms * ff, event.flameCount/6.0 + .6 * ms * ff, event.flameCount / 6.0 + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
for i in range(3):
if self.starPowerActive:
if self.theme == 0 or self.theme == 1: #GH3 starcolor
spcolmod = 0.4+i*0.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else: #Default starcolor (Rockband)
flamecol = (0.1+i*0.1,)*3
self.engine.draw3Dtex(self.hitflames2Drawing, coord = (x-.005, y + .255, 0), rot = (90, 1, 0, 0),
scale = (.30 + i*0.05 + .6 * ms * ff, event.flameCount/(5.5 - i*0.4) + .6 * ms * ff, event.flameCount / (5.5 - i*0.4) + .6 * ms * ff),
vertex = (-flameSize * ff,-flameSize * ff,flameSize * ff,flameSize * ff), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
else:
flameColorMod = 0.1 * (flameLimit - event.flameCount)
flamecol = tuple([ifc*flameColorMod for ifc in flameColor])
scaleChange = (3.0,2.5,2.0,1.7)
yOffset = (.35, .405, .355, .355)
vtx = flameSize * ff
scaleMod = .6 * ms * ff
for step in range(4):
#draw lightning in GH themes on SP gain
if step == 0 and self.theme != 2 and event.finalStar and self.spEnabled:
self.engine.draw3Dtex(self.hitlightning, coord = (xlightning, y, 3.3), rot = (90, 1, 0, 0),
scale = (.15 + .5 * ms * ff, event.flameCount / 3.0 + .6 * ms * ff, 2), vertex = (.4,-2,-.4,2),
texcoord = (0.0,0.0,1.0,1.0), multiples = True, alpha = True, color = (1,1,1))
continue
if step == 0:
yzscaleMod = event.flameCount/ scaleChange[step]
else:
yzscaleMod = (event.flameCount + 1)/ scaleChange[step]
if self.starPowerActive:
if self.theme == 0 or self.theme == 1:
spcolmod = .7+step*.1
flamecol = tuple([isp*spcolmod for isp in self.spColor])
else:
flamecol = (.4+step*.1,)*3#Default starcolor (Rockband)
self.engine.draw3Dtex(self.hitflames1Drawing, coord = (x - .005, y + yOffset[step], 0), rot = (90, 1, 0, 0),
scale = (.25 + step*.05 + scaleMod, yzscaleMod + scaleMod, yzscaleMod + scaleMod),
vertex = (-vtx,-vtx,vtx,vtx), texcoord = (0.0,0.0,1.0,1.0),
multiples = True, alpha = True, color = flamecol)
event.flameCount += 1
def render(self, visibility, song, pos, controls, killswitch):
if shaders.turnon:
shaders.globals["dfActive"] = self.drumFillsActive
shaders.globals["breActive"] = self.freestyleActive
shaders.globals["rockLevel"] = self.rockLevel
if shaders.globals["killswitch"] != killswitch:
shaders.globals["killswitchPos"] = pos
shaders.globals["killswitch"] = killswitch
shaders.modVar("height",0.2,0.2,1.0,"tail")
if not self.starNotesSet == True:
self.totalNotes = 0
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
self.totalNotes += 1
stars = []
maxStars = []
maxPhrase = self.totalNotes/120
for q in range(0,maxPhrase):
for n in range(0,10):
stars.append(self.totalNotes/maxPhrase*(q)+n+maxPhrase/4)
maxStars.append(self.totalNotes/maxPhrase*(q)+10+maxPhrase/4)
i = 0
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
for a in stars:
if i == a:
self.starNotes.append(time)
event.star = True
for a in maxStars:
if i == a:
self.maxStars.append(time)
event.finalStar = True
i += 1
for time, event in song.track[self.player].getAllEvents():
if not isinstance(event, Note):
continue
for q in self.starNotes:
if time == q:
event.star = True
for q in self.maxStars:
#if time == q and not event.finalStar:
# event.star = True
if time == q: #MFH - no need to mark only the final SP phrase note as the finalStar as in drums, they will be hit simultaneously here.
event.finalStar = True
self.starNotesSet = True
if not (self.coOpFailed and not self.coOpRestart):
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_COLOR_MATERIAL)
if self.leftyMode:
if not self.battleStatus[6]:
glScalef(-1, 1, 1)
elif self.battleStatus[6]:
glScalef(-1, 1, 1)
if self.ocount <= 1:
self.ocount = self.ocount + .1
else:
self.ocount = 1
if self.freestyleActive:
self.renderTails(visibility, song, pos, killswitch)
self.renderNotes(visibility, song, pos, killswitch)
self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes.
self.renderFrets(visibility, song, controls)
if self.hitFlamesPresent: #MFH - only if present!
self.renderFreestyleFlames(visibility, controls) #MFH - freestyle hit flames
else:
self.renderTails(visibility, song, pos, killswitch)
if self.fretsUnderNotes: #MFH
if self.twoDnote == True:
self.renderFrets(visibility, song, controls)
self.renderNotes(visibility, song, pos, killswitch)
else:
self.renderNotes(visibility, song, pos, killswitch)
self.renderFrets(visibility, song, controls)
else:
self.renderNotes(visibility, song, pos, killswitch)
self.renderFrets(visibility, song, controls)
self.renderFreestyleLanes(visibility, song, pos) #MFH - render the lanes on top of the notes.
if self.hitFlamesPresent: #MFH - only if present!
self.renderFlames(visibility, song, pos, controls) #MFH - only when freestyle inactive!
if self.leftyMode:
if not self.battleStatus[6]:
glScalef(-1, 1, 1)
elif self.battleStatus[6]:
glScalef(-1, 1, 1)
if self.theme == 2 and self.overdriveFlashCount < self.overdriveFlashCounts:
self.overdriveFlashCount = self.overdriveFlashCount + 1
def getMissedNotes(self, song, pos, catchup = False):
if not song:
return
if not song.readyToGo:
return
m1 = self.lateMargin
m2 = self.lateMargin * 2
#if catchup == True:
# m2 = 0
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - m1, pos - m2) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if (time >= (pos - m2)) and (time <= (pos - m1))]
notes = [(time, event) for time, event in notes if not event.played and not event.hopod and not event.skipped]
if catchup == True:
for time, event in notes:
event.skipped = True
return sorted(notes, key=lambda x: x[1].number)
#return notes
def getMissedNotesMFH(self, song, pos, catchup = False):
if not song:
return
if not song.readyToGo:
return
m1 = self.lateMargin
m2 = self.lateMargin * 2
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - m2, pos - m1) if isinstance(event, Note)] #was out of order
#MFH - this additional filtration step removes sustains whose Note On event time is now outside the hitwindow.
notes = [(time, event) for time, event in notes if (time >= (pos - m2)) and (time <= (pos - m1))]
notes = [(time, event) for time, event in notes if not event.played and not event.hopod and not event.skipped]
if catchup:
for time, event in notes:
event.skipped = True
return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number....
def getRequiredNotes(self, song, pos):
if self.battleStatus[2] and self.difficulty != 0:
if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
else:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not event.played]
notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))]
if notes:
t = min([time for time, event in notes])
notes = [(time, event) for time, event in notes if time - t < 1e-3]
#Log.debug(notes)
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[1].number)
def getRequiredNotes2(self, song, pos, hopo = False):
if self.battleStatus[2] and self.difficulty != 0:
if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
else:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played)]
notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))]
if notes:
t = min([time for time, event in notes])
notes = [(time, event) for time, event in notes if time - t < 1e-3]
#Log.debug(notes)
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[1].number)
def getRequiredNotes3(self, song, pos, hopo = False):
if self.battleStatus[2] and self.difficulty != 0:
if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
else:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))]
#Log.debug(notes)
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[1].number)
#MFH - corrected and optimized:
#def getRequiredNotesMFH(self, song, pos):
def getRequiredNotesMFH(self, song, pos, hopoTroubleCheck = False):
if self.battleStatus[2] and self.difficulty != 0:
if pos < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or pos > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
else:
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track = song.track[self.player]
if hopoTroubleCheck:
#notes = [(time, event) for time, event in track.getEvents(pos, pos + (self.earlyMargin*2)) if isinstance(event, Note)]
#notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
notes = [(time, event) for time, event in track.getEvents(pos, pos + (self.earlyMargin*2)) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not time==pos] #MFH - filter out the problem note that caused this check!
else:
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + self.earlyMargin) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
#MFH - this additional filtration step removes sustains whose Note On event time is now outside the hitwindow.
notes = [(time, event) for time, event in notes if (time >= (pos - self.lateMargin)) and (time <= (pos + self.earlyMargin))]
sorted(notes, key=lambda x: x[0])
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number....
def getDoubleNotes(self, notes):
if self.battleStatus[7] and notes != []:
notes = sorted(notes, key=lambda x: x[0])
curTime = 0
tempnotes = []
tempnumbers = []
tempnote = None
curNumbers = []
noteCount = 0
for time, note in notes:
noteCount += 1
if not isinstance(note, Note):
if noteCount == len(notes) and len(curNumbers) < 3 and len(curNumbers) > 0:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
continue
if time != curTime:
if curTime != 0 and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif (curTime != 0 or noteCount == len(notes)) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
tempnotes.append((time,deepcopy(note)))
curTime = time
curNumbers.append(note.number)
if noteCount == len(notes) and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
else:
curNumbers.append(note.number)
if noteCount == len(notes) and len(curNumbers) < 3:
maxNote = curNumbers[0]
minNote = curNumbers[0]
for i in range(0, len(curNumbers)):
if curNumbers[i] > maxNote:
maxNote = curNumbers[i]
if curNumbers[i] < minNote:
minNote = curNumbers[i]
curNumbers = []
if maxNote < 4:
tempnumbers.append(maxNote + 1)
elif minNote > 0:
tempnumbers.append(minNote - 1)
else:
tempnumbers.append(2)
elif noteCount == len(notes) and len(curNumbers) > 2:
tempnumbers.append(-1)
curNumbers = []
noteCount = 0
for time, note in tempnotes:
if tempnumbers[noteCount] != -1:
note.number = tempnumbers[noteCount]
noteCount += 1
if time > self.battleStartTimes[7] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[7] - self.currentPeriod * self.beatsPerBoard + self.battleDoubleLength:
notes.append((time,note))
else:
noteCount += 1
return sorted(notes, key=lambda x: x[0])
def getRequiredNotesForRender(self, song, pos):
if self.battleStatus[2] and self.difficulty != 0:
Log.debug(self.battleDiffUpValue)
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue]
track0 = song.track[self.player]
notes0 = [(time, event) for time, event in track0.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
song.difficulty[self.player] = Song.difficulties[self.battleDiffUpValue - 1]
track1 = song.track[self.player]
notes1 = [(time, event) for time, event in track1.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
notes = []
for time,note in notes0:
if time < self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard or time > self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
notes.append((time,note))
for time,note in notes1:
if time > self.battleStartTimes[2] + self.currentPeriod * self.beatsPerBoard and time < self.battleStartTimes[2] - self.currentPeriod * self.beatsPerBoard + self.battleDiffUpLength:
notes.append((time,note))
notes0 = None
notes1 = None
track0 = None
track1 = None
notes = sorted(notes, key=lambda x: x[0])
#Log.debug(notes)
else:
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard)]
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return notes
#MFH - corrected and optimized:
def getRequiredNotesForJurgenOnTime(self, song, pos):
track = song.track[self.player]
notes = [(time, event) for time, event in track.getEvents(pos - self.lateMargin, pos + 30) if isinstance(event, Note)]
notes = [(time, event) for time, event in notes if not (event.hopod or event.played or event.skipped)]
if self.battleStatus[7]:
notes = self.getDoubleNotes(notes)
return sorted(notes, key=lambda x: x[0]) #MFH - what the hell, this should be sorted by TIME not note number....
def controlsMatchNotes(self, controls, notes):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for k in self.keys:
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
for n in range(self.strings):
if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
return False
if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
# The lower frets can be held down
if n > max(requiredKeys):
return False
if twochord != 0:
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
if twochord == 2:
self.twoChord += skipped
return True
def controlsMatchNotes2(self, controls, notes, hopo = False):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])):
#if hopo == True and controls.getState(self.keys[note.number]):
self.playedNotes = []
return True
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
for n in range(self.strings):
if n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
return False
if not n in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5])):
# The lower frets can be held down
if hopo == False and n >= min(requiredKeys):
return False
if twochord != 0:
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
if twochord == 2:
self.twoChord += skipped
return True
def controlsMatchNotes3(self, controls, notes, hopo = False):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if note.hopod == True and (controls.getState(self.keys[note.number]) or controls.getState(self.keys[note.number + 5])):
#if hopo == True and controls.getState(self.keys[note.number]):
self.playedNotes = []
return True
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
#chordlist.sort(lambda a, b: cmp(a[0][0], b[0][0]))
chordlist.sort(key=lambda a: a[0][0])
self.missedNotes = []
self.missedNoteNums = []
twochord = 0
for chord in chordlist:
# matching keys?
requiredKeys = [note.number for time, note in chord]
requiredKeys = self.uniqify(requiredKeys)
if len(requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(requiredKeys) - 2
requiredKeys = [min(requiredKeys), max(requiredKeys)]
else:
twochord = 0
if (self.controlsMatchNote3(controls, chord, requiredKeys, hopo)):
if twochord != 2:
for time, note in chord:
note.played = True
else:
self.twoChordApply = True
for time, note in chord:
note.skipped = True
chord[0][1].skipped = False
chord[-1][1].skipped = False
chord[0][1].played = True
chord[-1][1].played = True
break
if hopo == True:
break
self.missedNotes.append(chord)
else:
self.missedNotes = []
self.missedNoteNums = []
for chord in self.missedNotes:
for time, note in chord:
if self.debugMode:
self.missedNoteNums.append(note.number)
note.skipped = True
note.played = False
if twochord == 2:
self.twoChord += skipped
return True
#MFH - special function for HOPO intentions checking
def controlsMatchNextChord(self, controls, notes):
# no notes?
if not notes:
return False
# check each valid chord
chords = {}
for time, note in notes:
if not time in chords:
chords[time] = []
chords[time].append((time, note))
#Make sure the notes are in the right time order
chordlist = chords.values()
chordlist.sort(key=lambda a: a[0][0])
twochord = 0
for chord in chordlist:
# matching keys?
self.requiredKeys = [note.number for time, note in chord]
self.requiredKeys = self.uniqify(self.requiredKeys)
if len(self.requiredKeys) > 2 and self.twoChordMax == True:
twochord = 0
self.twoChordApply = True
for n, k in enumerate(self.keys):
if controls.getState(k):
twochord += 1
if twochord == 2:
skipped = len(self.requiredKeys) - 2
self.requiredKeys = [min(self.requiredKeys), max(self.requiredKeys)]
else:
twochord = 0
if (self.controlsMatchNote3(controls, chord, self.requiredKeys, False)):
return True
else:
return False
def uniqify(self, seq, idfun=None):
# order preserving
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
def controlsMatchNote3(self, controls, chordTuple, requiredKeys, hopo):
if len(chordTuple) > 1:
#Chords must match exactly
for n in range(self.strings):
if (n in requiredKeys and not (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))) or (n not in requiredKeys and (controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]))):
return False
else:
#Single Note must match that note
requiredKey = requiredKeys[0]
if not controls.getState(self.keys[requiredKey]) and not controls.getState(self.keys[requiredKey+5]):
return False
#myfingershurt: this is where to filter out higher frets held when HOPOing:
if hopo == False or self.hopoStyle == 2 or self.hopoStyle == 3:
#Check for higher numbered frets if not a HOPO or if GH2 strict mode
for n, k in enumerate(self.keys):
if (n > requiredKey and n < 5) or (n > 4 and n > requiredKey + 5):
#higher numbered frets cannot be held
if controls.getState(k):
return False
return True
def areNotesTappable(self, notes):
if not notes:
return
for time, note in notes:
if note.tappable > 1:
return True
return False
def startPick(self, song, pos, controls, hopo = False):
if hopo == True:
res = startPick2(song, pos, controls, hopo)
return res
if not song:
return False
if not song.readyToGo:
return False
self.playedNotes = []
self.matchingNotes = self.getRequiredNotes(song, pos)
if self.controlsMatchNotes(controls, self.matchingNotes):
self.pickStartPos = pos
for time, note in self.matchingNotes:
if note.skipped == True:
continue
self.pickStartPos = max(self.pickStartPos, time)
note.played = True
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
return True
return False
def startPick2(self, song, pos, controls, hopo = False):
if not song:
return False
if not song.readyToGo:
return False
self.playedNotes = []
self.matchingNotes = self.getRequiredNotes2(song, pos, hopo)
if self.controlsMatchNotes2(controls, self.matchingNotes, hopo):
self.pickStartPos = pos
for time, note in self.matchingNotes:
if note.skipped == True:
continue
self.pickStartPos = max(self.pickStartPos, time)
if hopo:
note.hopod = True
else:
note.played = True
if note.tappable == 1 or note.tappable == 2:
self.hopoActive = time
self.wasLastNoteHopod = True
elif note.tappable == 3:
self.hopoActive = -time
self.wasLastNoteHopod = True
else:
self.hopoActive = 0
self.wasLastNoteHopod = False
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
self.hopoLast = note.number
return True
return False
def startPick3(self, song, pos, controls, hopo = False):
if not song:
return False
if not song.readyToGo:
return False
self.lastPlayedNotes = self.playedNotes
self.playedNotes = []
self.matchingNotes = self.getRequiredNotesMFH(song, pos)
self.controlsMatchNotes3(controls, self.matchingNotes, hopo)
#myfingershurt
for time, note in self.matchingNotes:
if note.played != True:
continue
if shaders.turnon:
shaders.var["fret"][self.player][note.number]=shaders.time()
shaders.var["fretpos"][self.player][note.number]=pos
self.pickStartPos = pos
self.pickStartPos = max(self.pickStartPos, time)
if hopo:
note.hopod = True
else:
note.played = True
#self.wasLastNoteHopod = False
if note.tappable == 1 or note.tappable == 2:
self.hopoActive = time
self.wasLastNoteHopod = True
elif note.tappable == 3:
self.hopoActive = -time
self.wasLastNoteHopod = True
if hopo: #MFH - you just tapped a 3 - make a note of it. (har har)
self.hopoProblemNoteNum = note.number
self.sameNoteHopoString = True
else:
self.hopoActive = 0
self.wasLastNoteHopod = False
self.hopoLast = note.number
self.playedNotes.append([time, note])
if self.guitarSolo:
self.currentGuitarSoloHitNotes += 1
#myfingershurt: be sure to catch when a chord is played
if len(self.playedNotes) > 1:
lastPlayedNote = None
for time, note in self.playedNotes:
if isinstance(lastPlayedNote, Note):
if note.tappable == 1 and lastPlayedNote.tappable == 1:
self.LastStrumWasChord = True
#self.sameNoteHopoString = False
else:
self.LastStrumWasChord = False
lastPlayedNote = note
elif len(self.playedNotes) > 0: #ensure at least that a note was played here
self.LastStrumWasChord = False
if len(self.playedNotes) != 0:
return True
return False
def soloFreestylePick(self, song, pos, controls):
numHits = 0
for theFret in range(5):
self.freestyleHit[theFret] = controls.getState(self.keys[theFret+5])
if self.freestyleHit[theFret]:
if shaders.turnon:
shaders.var["fret"][self.player][theFret]=shaders.time()
shaders.var["fretpos"][self.player][theFret]=pos
numHits += 1
return numHits
#MFH - TODO - handle freestyle picks here
def freestylePick(self, song, pos, controls):
numHits = 0
#if not song:
# return numHits
if not controls.getState(self.actions[0]) and not controls.getState(self.actions[1]):
return 0
for theFret in range(5):
self.freestyleHit[theFret] = controls.getState(self.keys[theFret])
if self.freestyleHit[theFret]:
if shaders.turnon:
shaders.var["fret"][self.player][theFret]=shaders.time()
shaders.var["fretpos"][self.player][theFret]=pos
numHits += 1
return numHits
def endPick(self, pos):
for time, note in self.playedNotes:
if time + note.length > pos + self.noteReleaseMargin:
self.playedNotes = []
return False
self.playedNotes = []
return True
def getPickLength(self, pos):
if not self.playedNotes:
return 0.0
# The pick length is limited by the played notes
pickLength = pos - self.pickStartPos
for time, note in self.playedNotes:
pickLength = min(pickLength, note.length)
return pickLength
def coOpRescue(self, pos):
self.coOpRestart = True #initializes Restart Timer
self.coOpRescueTime = pos
self.starPower = 0
Log.debug("Rescued at " + str(pos))
def run(self, ticks, pos, controls):
if not self.paused:
self.time += ticks
#MFH - Determine which frame to display for starpower notes
if self.starspin:
self.indexCount = self.indexCount + 1
if self.indexCount > self.Animspeed-1:
self.indexCount = 0
self.starSpinFrameIndex = (self.indexCount * self.starSpinFrames - (self.indexCount * self.starSpinFrames) % self.Animspeed) / self.Animspeed
if self.starSpinFrameIndex > self.starSpinFrames - 1:
self.starSpinFrameIndex = 0
#myfingershurt: must not decrease SP if paused.
if self.starPowerActive == True and self.paused == False:
self.starPower -= ticks/self.starPowerDecreaseDivisor
if self.starPower <= 0:
self.starPower = 0
self.starPowerActive = False
#MFH - call to play star power deactivation sound, if it exists (if not play nothing)
if self.engine.data.starDeActivateSoundFound:
#self.engine.data.starDeActivateSound.setVolume(self.sfxVolume)
self.engine.data.starDeActivateSound.play()
# update frets
if self.editorMode:
if (controls.getState(self.actions[0]) or controls.getState(self.actions[1])):
for i in range(self.strings):
if controls.getState(self.keys[i]) or controls.getState(self.keys[i+5]):
activeFrets.append(i)
activeFrets = activeFrets or [self.selectedString]
else:
activeFrets = []
else:
activeFrets = [note.number for time, note in self.playedNotes]
for n in range(self.strings):
if controls.getState(self.keys[n]) or controls.getState(self.keys[n+5]) or (self.editorMode and self.selectedString == n):
self.fretWeight[n] = 0.5
else:
self.fretWeight[n] = max(self.fretWeight[n] - ticks / 64.0, 0.0)
if n in activeFrets:
self.fretActivity[n] = min(self.fretActivity[n] + ticks / 32.0, 1.0)
else:
self.fretActivity[n] = max(self.fretActivity[n] - ticks / 64.0, 0.0)
#MFH - THIS is where note sustains should be determined... NOT in renderNotes / renderFrets / renderFlames -.-
if self.fretActivity[n]:
self.hit[n] = True
else:
self.hit[n] = False
if self.vbpmLogicType == 0: #MFH - VBPM (old)
if self.currentBpm != self.targetBpm:
diff = self.targetBpm - self.currentBpm
if (round((diff * .03), 4) != 0):
self.currentBpm = round(self.currentBpm + (diff * .03), 4)
else:
self.currentBpm = self.targetBpm
self.setBPM(self.currentBpm) # glorandwarf: was setDynamicBPM(self.currentBpm)
for time, note in self.playedNotes:
if pos > time + note.length:
return False
return True
| Python |
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#####################################################################
# Drawing methods comparison (part of FoFiX) #
# Copyright (C) 2009 Pascal Giard <evilynux@gmail.com> #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from OpenGL.GL import *
try:
from OpenGL.arrays import vbo
vbo_support = True
except:
vbo_support = False
from numpy import array, float32, append, hstack
import pygame
from pygame.locals import *
from math import cos, sin, sqrt
rot = 0.0
scale = 1.0
mode = 2
def init():
global mode, triangVbo, triangVtx, triangCol
global spiralVtx, spiralVbo, spiralCol
triangVtx = array(
[[ 0, 1, 0],
[-1, -1, 0],
[ 1, -1, 0]], dtype=float32)
triangCol = array(
[[ 0, 1, 0],
[ 1, 0, 0],
[ 0, 0, 1]], dtype=float32)
nbSteps = 200.0
for i in range(int(nbSteps)):
ratio = i/nbSteps;
angle = 21*ratio
c = cos(angle)
s = sin(angle);
r1 = 1.0 - 0.8*ratio;
r2 = 0.8 - 0.8*ratio;
alt = ratio - 0.5
nor = 0.5
up = sqrt(1.0-nor*nor)
if i == 0:
spiralVtx = array([[r1*c, alt, r1*s]],dtype=float32)
spiralCol = array([[1.0-ratio, 0.2, ratio]],dtype=float32)
else:
spiralVtx = append(spiralVtx,[[r1*c, alt, r1*s]],axis=0)
spiralCol = append(spiralCol,[[1.0-ratio, 0.2, ratio]],axis=0)
spiralVtx = append(spiralVtx,[[r2*c, alt+0.05, r2*s]],axis=0)
spiralCol = append(spiralCol,[[1.0-ratio, 0.2, ratio]],axis=0)
if vbo_support:
triangArray = hstack((triangVtx, triangCol)).astype(float32)
spiralArray = hstack((spiralVtx, spiralCol)).astype(float32)
triangVbo = vbo.VBO( triangArray, usage='GL_STATIC_DRAW' )
spiralVbo = vbo.VBO( spiralArray, usage='GL_STATIC_DRAW' )
else:
print "VBO not supported, fallbacking to array-based drawing."
mode = 1
def draw():
global mode, triangVbo, triangVtx, triangCol
global spiralVtx, spiralVbo, spiralCol, rot, scale
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glPushMatrix()
glColor(1,1,1) # triangle color
glScale(scale,scale,scale)
glRotate(rot,0,1,0)
# VBO drawing
if mode == 0 and vbo_support:
# Draw triangle
triangVbo.bind()
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 24, triangVbo )
glColorPointer(3, GL_FLOAT, 24, triangVbo+12 )
glDrawArrays(GL_TRIANGLES, 0, triangVtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
triangVbo.unbind()
# Draw spiral
# evilynux - FIXME: The following doesn't work... why?
spiralVbo.bind()
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY)
glVertexPointer(3, GL_FLOAT, 24, spiralVbo )
glColorPointer(3, GL_FLOAT, 24, spiralVbo+12 )
glDrawArrays(GL_TRIANGLE_STRIP, 0, spiralVtx.shape[0])
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
spiralVbo.unbind()
# Array-based drawing
elif mode == 1:
# Draw triangle
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glColorPointerf(triangCol)
glVertexPointerf(triangVtx)
glDrawArrays(GL_TRIANGLES, 0, triangVtx.shape[0])
# Draw spiral
glColorPointerf(spiralCol)
glVertexPointerf(spiralVtx)
glDrawArrays(GL_TRIANGLE_STRIP, 0, spiralVtx.shape[0])
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
# Direct drawing
else: # mode == 2
glBegin(GL_TRIANGLES)
for i in range(triangVtx.shape[0]):
glColor(triangCol[i])
glVertex(triangVtx[i])
glEnd()
# Draw spiral
glBegin(GL_TRIANGLE_STRIP);
for i in range(spiralVtx.shape[0]):
glColor(spiralCol[i])
glVertex(spiralVtx[i])
glEnd()
glPopMatrix()
def main():
global rot, scale, mode
scale_dir = -1
modeName = ["VBO", "Array-based", "Direct-mode"]
fps = 0
video_flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
pygame.init()
pygame.display.set_mode((640,480), video_flags)
init()
frames = 0
ticks = pygame.time.get_ticks()
clock = pygame.time.Clock()
while 1:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
elif event.type == KEYDOWN and event.key == K_RIGHT:
mode = (mode + 1) % 3
if mode == 0 and not vbo_support:
mode = (mode + 1) % 3
print "VBO not supported, fallbacking to %s drawing." % modeName[mode]
elif event.type == KEYDOWN and event.key == K_LEFT:
mode = (mode - 1) % 3
if mode == 0 and not vbo_support:
mode = (mode - 1) % 3
print "VBO not supported, fallbacking to %s drawing." % modeName[mode]
ticksDiff = pygame.time.get_ticks()-ticks
# draw all objects
draw()
# update rotation counters
rot += 0.2
scale += scale_dir*0.0002
if scale > 1.0 or scale < 0.5:
scale_dir = scale_dir*-1
# make changes visible
pygame.display.flip()
frames = frames+1
if( ticksDiff > 2000 ):
fps = ((frames*1000)/(ticksDiff))
ticks = pygame.time.get_ticks()
frames = 0
print "mode: %s, %.2f fps" % (modeName[mode], fps)
# evilynux - commented the following so we go as fast as we can
#clock.tick(60)
if __name__ == '__main__': main()
| Python |
#!/usr/bin/python
import os, fnmatch
for root, dirs, files in os.walk("."):
for svg in fnmatch.filter(files, "*.svg"):
svg = os.path.join(root, svg)
print svg, os.system("inkscape -e '%s' -D '%s' -b black -y 0.0" % (svg.replace(".svg", ".png"), svg))
| Python |
#!/usr/bin/env python
# Font tests for FoFiX by Pascal Giard <evilynux@gmail.com>
# based on the demo of laminar.PanelOverlaySurface, by
# David Keeney 2006 which is
# based on version of Nehe's OpenGL lesson04
# by Paul Furber 2001 - m@verick.co.za
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
import sys
import os
sys.path.insert( 0, '..' )
from Font import Font
from Texture import Texture
import lamina
rtri = rquad = 0.0
triOn = quadOn = True
def resize((width, height)):
if height==0:
height=1
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.0*width/height, 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def init():
global fofixFont, mode, pygameFont, pygameChar
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.5, 0.0, 0.0)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
mode = 0 # evilynux - Start with lamina
# FoFiX font rendering
fofixFont = Font(None, 24, outline = False)
# pygame font rendering
pygameFont = pygame.font.Font(None, 24)
pygameChar = []
for c in range(256):
pygameChar.append(createCharacter(chr(c)))
pygameChar = tuple(pygameChar)
def draw():
global mode, fps
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
resize((640,480))
glPushMatrix()
glTranslatef(-1.5, 0.0, -6.0)
# draw triangle
global rtri
glRotatef(rtri, 0.0, 1.0, 0.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(-1.0, -1.0, 0)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(1.0, -1.0, 0)
glEnd()
# draw quad
glLoadIdentity()
glTranslatef(1.5, 0.0, -6.0)
global rquad
glRotatef(rquad, 1.0, 0.0, 0.0)
glColor3f(0.5, 0.5, 1.0)
glBegin(GL_QUADS)
glVertex3f(-1.0, 1.0, 0)
glVertex3f(1.0, 1.0, 0)
glVertex3f(1.0, -1.0, 0)
glVertex3f(-1.0, -1.0, 0)
glEnd()
glPopMatrix()
# Lamina font rendering
glLoadIdentity()
s = str('Mode: %d, FPS: %.2f' % (mode, fps))
if( mode == 0):
global gui_screen, font
txt = font.render(s, 1, (0,0,0), (200,0,0))
gui_screen.surf.blit(txt, (640 - txt.get_size()[0], 0))
gui_screen.display()
# FoFiX font rendering
if( mode == 1):
global fofixFont
size = fofixFont.getStringSize(s)
# Text invisible unless i put a negative Z position, wtf?!
glTranslatef(-size[0], .0, -1.0)
fofixFont.render(s, (0, 0), (1,0))
# Nelson Rush method for font rendering
if( mode == 2):
global pygameFont, pygameChar
i = 0
lx = 0
length = len(s)
x = 640 - pygameChar[ord('0')][1]*length
y = 480 - pygameChar[ord('0')][2]
textView(640,480)
glPushMatrix()
while i < length:
glRasterPos2i(x + lx, y)
ch = pygameChar[ ord( s[i] ) ]
glDrawPixels(ch[1], ch[2], GL_RGBA, GL_UNSIGNED_BYTE, ch[0])
lx += ch[1]
i += 1
glPopMatrix()
def textView(w = 640, h = 480):
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, w - 1.0, 0.0, h - 1.0, -1.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def createCharacter(s):
global pygameFont
try:
letter_render = pygameFont.render(s, 1, (255,255,255), (0,0,0))
letter = pygame.image.tostring(letter_render, 'RGBA', 1)
letter_w, letter_h = letter_render.get_size()
except:
letter = None
letter_w = 0
letter_h = 0
return (letter, letter_w, letter_h)
def main():
global rtri, rquad, gui_screen
global font, fofixFont, fps, mode
fps = 0
#video_flags = OPENGL|DOUBLEBUF
video_flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
pygame.init()
pygame.display.set_mode((640,480), video_flags)
resize((640,480))
init()
# create PanelOverlaySurface
gui_screen = lamina.LaminaScreenSurface(0.985)
pointlist = [(200,200), (400,200), (400,400), (200,400)]
pygame.draw.polygon(gui_screen.surf, (200,0,0), pointlist, 0)
pointlist1 = [(250,250), (350,250), (350,350), (250,350)]
pygame.draw.polygon(gui_screen.surf, (0,0,100), pointlist1, 0)
# draw text on a new Surface
font = pygame.font.Font(None, 40)
txt = font.render('Pygame Text', 1, (0,0,0), (200,0,0))
gui_screen.surf.blit(txt, (205, 205))
gui_screen.refresh()
gui_screen.refreshPosition()
frames = 0
ticks = pygame.time.get_ticks()
clock = pygame.time.Clock()
while 1:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
elif event.type == KEYDOWN and (event.key == K_RIGHT or event.key == K_LEFT):
mode = (mode + 1) % 3
ticksDiff = pygame.time.get_ticks()-ticks
if ticksDiff > 200 and mode == 0:
gui_screen.refresh()
# draw all objects
draw()
# update rotation counters
if triOn:
rtri += 0.2
if quadOn:
rquad+= 0.2
# make changes visible
pygame.display.flip()
frames = frames+1
if( ticksDiff > 200 ):
fps = ((frames*1000)/(ticksDiff))
ticks = pygame.time.get_ticks()
frames = 0
print "mode: %s, %.2f fps" % (mode, fps)
# evilynux - commented the following so we go as fast as we can
#clock.tick(60)
if __name__ == '__main__': main()
| Python |
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire X (FoFiX) #
# Copyright (C) 2009 Team FoFiX #
# 2009 John Stumpo #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
import Log
import Audio
import math
from PitchAnalyzer import Analyzer
import numpy
import Config
try:
import pyaudio
supported = True
except ImportError:
Log.warn('Missing pyaudio - microphone support will not be possible')
supported = False
try:
import pypitch
have_pypitch = True
except ImportError:
have_pypitch = False
from Task import Task
from Language import _
if supported:
pa = pyaudio.PyAudio()
# Precompute these in the interest of saving CPU time in the note analysis loop
LN_2 = math.log(2.0)
LN_440 = math.log(440.0)
#stump: return dictionary mapping indices to device names
# -1 is magic for the default device and will be replaced by None when actually opening the mic.
def getAvailableMics():
result = {-1: _('[Default Microphone]')}
for devnum in range(pa.get_device_count()):
devinfo = pa.get_device_info_by_index(devnum)
if devinfo['maxInputChannels'] > 0:
result[devnum] = devinfo['name']
return result
class Microphone(Task):
def __init__(self, engine, controlnum, samprate=44100):
Task.__init__(self)
self.engine = engine
self.controlnum = controlnum
devnum = self.engine.input.controls.micDevice[controlnum]
if devnum == -1:
devnum = None
self.devname = pa.get_default_input_device_info()['name']
else:
self.devname = pa.get_device_info_by_index(devnum)['name']
self.mic = pa.open(samprate, 1, pyaudio.paFloat32, input=True, input_device_index=devnum, start=False)
if Config.get('game', 'use_new_pitch_analyzer') or not have_pypitch:
self.analyzer = Analyzer(samprate)
else:
self.analyzer = pypitch.Analyzer(samprate)
self.mic_started = False
self.lastPeak = 0
self.detectTaps = True
self.tapStatus = False
self.tapThreshold = -self.engine.input.controls.micTapSensitivity[controlnum]
self.passthroughQueue = []
passthroughVolume = self.engine.input.controls.micPassthroughVolume[controlnum]
if passthroughVolume > 0.0:
Log.debug('Microphone: creating passthrough stream at %d%% volume' % round(passthroughVolume * 100))
self.passthroughStream = Audio.MicrophonePassthroughStream(engine, self)
self.passthroughStream.setVolume(passthroughVolume)
else:
Log.debug('Microphone: not creating passthrough stream')
self.passthroughStream = None
def __del__(self):
self.stop()
self.mic.close()
def start(self):
if not self.mic_started:
self.mic_started = True
self.mic.start_stream()
self.engine.addTask(self, synchronized=False)
Log.debug('Microphone: started %s' % self.devname)
if self.passthroughStream is not None:
Log.debug('Microphone: starting passthrough stream')
self.passthroughStream.play()
def stop(self):
if self.mic_started:
if self.passthroughStream is not None:
Log.debug('Microphone: stopping passthrough stream')
self.passthroughStream.stop()
self.engine.removeTask(self)
self.mic.stop_stream()
self.mic_started = False
Log.debug('Microphone: stopped %s' % self.devname)
# Called by the Task machinery: pump the mic and shove the data through the analyzer.
def run(self, ticks):
while self.mic.get_read_available() > 1024:
try:
chunk = self.mic.read(1024)
except IOError, e:
if e.args[1] == pyaudio.paInputOverflowed:
Log.notice('Microphone: ignoring input buffer overflow')
chunk = '\x00' * 4096
else:
raise
if self.passthroughStream is not None:
self.passthroughQueue.append(chunk)
self.analyzer.input(numpy.frombuffer(chunk, dtype=numpy.float32))
self.analyzer.process()
pk = self.analyzer.getPeak()
if self.detectTaps:
if pk > self.tapThreshold and pk > self.lastPeak + 5.0:
self.tapStatus = True
self.lastPeak = pk
# Get the amplitude (in dB) of the peak of the most recent input window.
def getPeak(self):
return self.analyzer.getPeak()
# Get the microphone tap status.
# When a tap occurs, it is remembered until this function is called.
def getTap(self):
retval = self.tapStatus
self.tapStatus = False
return retval
def getFormants(self):
return self.analyzer.getFormants()
# Get the note currently being sung.
# Returns None if there isn't one or a PitchAnalyzer.Tone object if there is.
def getTone(self):
return self.analyzer.findTone()
# Get the note currently being sung, as an integer number of semitones above A.
# The frequency is rounded to the nearest semitone, then shifted by octaves until
# the result is between 0 and 11 (inclusive). Returns None is no note is being sung.
def getSemitones(self):
tone = self.analyzer.findTone()
if tone is None:
return tone
#print tone
return int(round((math.log(tone.freq) - LN_440) * 12.0 / LN_2) % 12)
# Work out how accurately the note (passed in as a MIDI note number) is being
# sung. Return a float in the range [-6.0, 6.0] representing the number of
# semitones difference there is from the nearest occurrence of the note. The
# octave doesn't matter. Or return None if there's no note being sung.
def getDeviation(self, midiNote):
tone = self.analyzer.findTone()
if tone is None:
return tone
# Convert to semitones from A-440.
semitonesFromA440 = (math.log(tone.freq) - LN_440) * 12.0 / LN_2
# midiNote % 12 = semitones above C, which is 3 semitones above A
semitoneDifference = (semitonesFromA440 - 3.0) - float(midiNote % 12)
# Adjust to the proper range.
acc = math.fmod(semitoneDifference, 12.0)
if acc > 6.0:
acc -= 12.0
elif acc < -6.0:
acc += 12.0
return acc
else:
def getAvailableMics():
return {-1: _('[Microphones not supported]')}
class Microphone(object):
def __new__(self, *args, **kw):
raise RuntimeError, 'Tried to instantiate Microphone when it is unsupported!'
# Turn a number of semitones above A into a human-readable note name.
def getNoteName(semitones):
return ['A', 'Bb', 'B', 'C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab'][semitones]
| Python |
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2009 Vlad Emelyanov #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
from OpenGL.GL import *
import os
import sys
import string
from random import random
import time
import Log
import pygame.image
import Config
import Version
#OGL constants for compatibility with all PyOpenGL versions
#now multitexturing should work even in PyOpenGL 2.x, if your card supports ARB ext
#stump: managed to eliminate the need for every one of these. If I was wrong, please uncomment only the necessary line and notify me.
#GL_TEXTURE_3D = 32879
#GL_TEXTURE_WRAP_R = 32882
#GL_TEXTURE0_ARB, GL_TEXTURE1_ARB, GL_TEXTURE2_ARB, GL_TEXTURE3_ARB = 33984, 33985, 33986, 33987
#GL_FRAGMENT_SHADER_ARB = 0x8B30
#GL_VERTEX_SHADER_ARB = 0x8B31
#GL_OBJECT_COMPILE_STATUS_ARB= 0x8B81
#GL_OBJECT_LINK_STATUS_ARB = 0x8B82
#GL_INFO_LOG_LENGTH_ARB = 0x8B84
#GL_CLAMP_TO_EDGE = 33071
# stump: these don't throw the exception for being unsupported - that happens later.
# There has to be an active OpenGL context already for the checking to occur.
# We do the check down in ShaderList.set().
# evilynux : Wrapped around try/except as pyopengl < 2.0.2.x fails here.
try:
from OpenGL.GL.ARB.shader_objects import *
from OpenGL.GL.ARB.vertex_shader import *
from OpenGL.GL.ARB.fragment_shader import *
from OpenGL.GL.ARB.multitexture import *
from OpenGL.GL.EXT.texture3D import *
except:
Log.warn("Importing OpenGL ARB fails therefore shaders are disabled."\
" It is most likely that your version of PyOpenGL is too old.")
glInitShaderObjectsARB = lambda: False
class ShaderCompilationError(Exception):
pass
#stump: apply some fixups for pyOpenGL 2.x if necessary.
def checkFunctionsForPyOpenGL2x():
global glShaderSourceARB
global glGetObjectParameterivARB
# Check the version of pyOpenGL.
import OpenGL
if OpenGL.__version__ < '3':
#stump: the binding of glShaderSourceARB() in pyOpenGL 2.x segfaults on use... ugh!
# (It and glGetObjectParameterivARB() also have incompatible declarations - let's fix that too.)
try:
from ctypes import c_int, c_char_p, POINTER, cdll, byref
if os.name == 'nt':
from ctypes import WINFUNCTYPE, windll
elif sys.platform == 'darwin':
from ctypes.util import find_library
except ImportError:
raise ShaderCompilationError, 'ctypes is required to use shaders with pyOpenGL 2.x.'
else:
if os.name == 'nt': # Windows - look for the functions using wglGetProcAddress()
# Grab the function pointers the standard Windows way.
# (opengl32.dll doesn't directly export extension entry points like other platforms' OpenGL libraries do.)
ptr_glShaderSourceARB = windll.opengl32.wglGetProcAddress('glShaderSourceARB')
ptr_glGetObjectParameterivARB = windll.opengl32.wglGetProcAddress('glGetObjectParameterivARB')
# If we got good function pointers, make them callable using ctypes.
if ptr_glShaderSourceARB:
func_glShaderSourceARB = WINFUNCTYPE(None, c_int, c_int, POINTER(c_char_p), POINTER(c_int))(ptr_glShaderSourceARB)
else:
raise ShaderCompilationError, 'wglGetProcAddress("glShaderSourceARB") returned NULL - are shaders supported?'
if ptr_glGetObjectParameterivARB:
func_glGetObjectParameterivARB = WINFUNCTYPE(None, c_int, c_int, POINTER(c_int))(ptr_glGetObjectParameterivARB)
else:
raise ShaderCompilationError, 'wglGetProcAddress("glGetObjectParameterivARB") returned NULL - are shaders supported?'
else: # something else - assume that the OpenGL library exports the extension entry point
# Figure out where the OpenGL library is.
if sys.platform == 'darwin': # Mac OS X
glLibrary = cdll.LoadLibrary(find_library('OpenGL'))
else: # something else; most likely GNU/Linux
glLibrary = cdll.LoadLibrary('libGL.so')
try:
func_glShaderSourceARB = glLibrary.glShaderSourceARB
func_glGetObjectParameterivARB = glLibrary.glGetObjectParameterivARB
except:
raise ShaderCompilationError, 'Cannot find glShaderSourceARB() and/or glGetObjectParameterivARB() in the OpenGL library - are shaders supported?'
# Wrap supporting glShaderSource(shader object, iterable object) returning None, as used below.
def glShaderSourceARB(shader, source):
srcList = list(source)
srcListType = c_char_p * len(srcList)
func_glShaderSourceARB(shader, len(srcList), srcListType(*srcList), None)
# Wrap supporting glGetObjectParameterivARB(shader object, parameter id) returning int, as used below.
def glGetObjectParameterivARB(shader, param):
retval = c_int(0)
func_glGetObjectParameterivARB(shader, param, byref(retval))
return retval.value
#should be placed somewhere else
if sys.platform == 'darwin':
global GL_TEXTURE_3D_EXT
global GL_TEXTURE_WRAP_R_EXT
global glTexImage3DEXT
GL_TEXTURE_3D_EXT = GL_TEXTURE_3D
GL_TEXTURE_WRAP_R_EXT = GL_TEXTURE_WRAP_R
glTexImage3DEXT = glTexImage3D
# main class for shaders library
class ShaderList:
def __init__(self):
self.shaders = {} # list of all shaders
self.active = 0 # active shader
self.texcount = 0
self.workdir = "" # dir that contains shader files
self.enabled = False # true if shaders are compiled
self.turnon = False # true if shaders are enabled in settings
self.var = {} # different variables
self.assigned = {} # list for shader replacement
self.globals = {} # list of global vars for every shader
def make(self, fname, name = ""):
"""Compile a shader.
fname = base filename for shader files
name = name to use for this shader (defaults to fname)
Returns nothing, or raises an exception on error."""
if name == "":
name = fname
fullname = os.path.join(self.workdir, fname)
vertname, fragname = fullname+".vert", fullname+".frag"
Log.debug('Compiling shader "%s" from %s and %s.' % (name, vertname, fragname))
program = self.compile(open(vertname), open(fragname))
sArray = {"program": program, "name": name, "textures": []}
self.getVars(vertname, program, sArray)
self.getVars(fragname, program, sArray)
self.shaders[name] = sArray
if self.shaders[name].has_key("Noise3D"):
self.setTexture("Noise3D",self.noise3D,name)
def compileShader(self, source, shaderType):
"""Compile shader source of given type.
source = file object open to shader source code
(or something else returning lines of GLSL code when iterated over)
shaderType = GL_VERTEX_SHADER_ARB or GL_FRAGMENT_SHADER_ARB
Returns the shader object, or raises an exception on error."""
shader = glCreateShaderObjectARB(shaderType)
glShaderSourceARB( shader, source )
glCompileShaderARB( shader )
status = glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB)
if not status:
raise ShaderCompilationError, self.log(shader)
else:
return shader
def compile(self, vertexSource, fragmentSource):
"""Create an OpenGL program object from file objects open to the source files.
vertexSource = file object open to vertex shader source code
fragmentSource = file object open to fragment shader source code
Returns the program object, or raises an exception on error."""
program = glCreateProgramObjectARB()
vertexShader = self.compileShader(vertexSource, GL_VERTEX_SHADER_ARB)
fragmentShader = self.compileShader(fragmentSource, GL_FRAGMENT_SHADER_ARB)
glAttachObjectARB(program, vertexShader)
glAttachObjectARB(program, fragmentShader)
glValidateProgramARB( program )
glLinkProgramARB(program)
glDeleteObjectARB(vertexShader)
glDeleteObjectARB(fragmentShader)
return program
def getVars(self, fname, program, sArray):
"""Read the names of uniform variables from a shader file.
fname = shader filename
program = OpenGL program object compiled from that shader file
sArray = dictionary to add variable information to"""
for line in open(fname):
aline = line[:string.find(line,";")]
aline = aline.split(' ')
if '(' in aline[0]:
break
if aline[0] == "uniform":
value = None
try: n = int(aline[1][-1])
except: n = 4
if aline[1] == "bool": value = False
elif aline[1] == "int": value = 0
elif aline[1] == "float": value = 0.0
elif aline[1][:-1] == "bvec": value = (False,)*n
elif aline[1][:-1] == "ivec": value = (0,)*n
elif aline[1][:-1] == "vec": value = (.0,)*n
elif aline[1][:-1] == "mat": value = ((.0,)*n,)*n
elif aline[1][:-2] == "sampler":
value, self.texcount = self.texcount, self.texcount + 1
if aline[1] == "sampler1D": textype = GL_TEXTURE_1D
elif aline[1] == "sampler2D": textype = GL_TEXTURE_2D
elif aline[1] == "sampler3D": textype = GL_TEXTURE_3D_EXT
sArray["textures"].append((aline[2],textype,0))
aline[2] = aline[2].split(',')
for var in aline[2]:
sArray[var] = [glGetUniformLocationARB(program, var), value]
#simplified texture binding function
def setTexture(self,name,texture,program = None):
if self.assigned.has_key(program):
program = self.assigned[program]
if program == None: program = self.active
else: program = self[program]
for i in range(len(program["textures"])):
if program["textures"][i][0] == name:
program["textures"][i] = (program["textures"][i][0], program["textures"][i][1], texture)
return True
return False
def getVar(self, var = "program", program = None):
"""Get a uniform variable value from a shader.
var = variable name
program = shader name, or None (default) for the currently active shader
Returns the value. If the variable does not exist, KeyError is raised."""
if self.assigned.has_key(program):
program = self.assigned[program]
if program is None:
program = self.active
else:
program = self[program]
if program is None or not program.has_key(var):
return False
else:
return program[var][1]
return True
def setVar(self, var, value, program = None):
"""Set a uniform variable value for a shader.
var = variable name
value = new value
program = shader name, or None (default) for the currently active shader
Returns nothing. If the variable does not exist, KeyError is raised."""
if self.assigned.has_key(program):
program = self.assigned[program]
if program is None:
program = self.active
else:
program = self[program]
if program is None or not program.has_key(var):
return
if type(value) == str:
if self.var.has_key(value):
value = self.var[value]
else:
return
pos = program[var]
pos[1] = value
if program == self.active:
if type(value) == list:
value = tuple(value)
if type(value) == bool:
if pos[1]: glUniform1iARB(pos[0],1)
else: glUniform1iARB(pos[0],0)
elif type(value) == float:
glUniform1fARB(pos[0],pos[1])
elif type(value) == int:
glUniform1iARB(pos[0],pos[1])
elif type(value) == tuple:
if type(value[0]) == float:
if len(value) == 2: glUniform2fARB(pos[0],*pos[1])
elif len(value) == 3: glUniform3fARB(pos[0],*pos[1])
elif len(value) == 4: glUniform4fARB(pos[0],*pos[1])
elif type(value[0]) == int:
if len(value) == 2: glUniform2iARB(pos[0],*pos[1])
elif len(value) == 3: glUniform3iARB(pos[0],*pos[1])
elif len(value) == 4: glUniform4iARB(pos[0],*pos[1])
elif type(value) == long:
glUniform1iARB(pos[0],pos[1])
else:
raise TypeError, 'Unsupported value type (must be bool, float, int, long, or tuple or list of float or int).'
# slightly changes uniform variable
def modVar(self, var, value, effect = 0.05, alphaAmp=1.0, program = None):
old = self.getVar(var,program)
if old is None:
return False
if type(old) == tuple:
new = ()
for i in range(len(old)):
if i==3: new += (old[i] * (1-effect) + value[i] * effect*alphaAmp,)
else: new += (old[i] * (1-effect) + value[i] * effect,)
else:
new = old * (1-effect) + value * effect
self.setVar(var,new,program)
return True
# enables shader program
def enable(self, shader):
if not self.turnon:
return False
if self.assigned.has_key(shader):
shader = self.assigned[shader]
if self[shader] is None:
return False
glUseProgramObjectARB(self[shader]["program"])
self.active = self.shaders[shader]
self.setTextures()
self.update()
self.globals["time"] = self.time()
self.setGlobals()
if self.getVar("time"):
self.setVar("dt",self.globals["time"]-self.getVar("time"))
return True
# transmit global vars to uniforms
def setGlobals(self):
for i in self.globals.keys():
self.setVar(i,self.globals[i])
# update all uniforms
def update(self):
for i in self.active.keys():
if i != "textures":
if type(self.active[i]) == list and self.active[i][1] is not None:
self.setVar(i,self.active[i][1])
# set standart OpenGL program active
def disable(self):
if self.active != 0:
glUseProgramObjectARB(0)
self.active = 0
# return active program control
def activeProgram(self):
if self.active != 0:
return self.active["name"]
else:
return 0
def log(self, shader):
"""Get the error log for a shader.
shader = object to get log from
Returns a string containing the log or None if there is no log."""
length = glGetObjectParameterivARB(shader, GL_INFO_LOG_LENGTH)
if length > 0:
log = glGetInfoLogARB(shader)
return log
# update and bind all textures
def setTextures(self, program = None):
if self.assigned.has_key(program):
program = self.assigned[program]
if program is None:
program = self.active
for i in range(len(program["textures"])):
glActiveTextureARB(self.multiTex[i])
glBindTexture(program["textures"][i][1], program["textures"][i][2])
def makeNoise3D(self,size=32, c = 1, type = GL_RED):
texels=[]
for i in range(size):
arr2 = []
for j in range(size):
arr = []
for k in range(size):
arr.append(random())
arr2.append(arr)
texels.append(arr2)
self.smoothNoise3D(size, 2, texels)
for i in range(size):
for j in range(size):
for k in range(size):
texels[i][j][k] = int(255 * texels[i][j][k])
texture = 0
glBindTexture(GL_TEXTURE_3D_EXT, texture)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage3DEXT(GL_TEXTURE_3D_EXT, 0, c,size, size, size, 0, type, GL_UNSIGNED_BYTE, texels)
return texture
def makeNoise2D(self,size=64, c = 1, type = GL_RED):
texels=[]
for i in range(size):
texels.append([])
for j in range(size):
texels[i].append(random())
self.smoothNoise(size, 2, texels)
self.smoothNoise(size, 3, texels)
self.smoothNoise(size, 4, texels)
for i in range(size):
for j in range(size):
texels[i][j] = int(255 * texels[i][j])
texture = 0
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, c,size, size, 0, type, GL_UNSIGNED_BYTE, texels)
return texture
def loadTex3D(self, fname, type = GL_RED):
file = os.path.join(self.workdir,fname)
if os.path.exists(file):
noise = open(file).read()
size = int(len(noise)**(1/3.0))
else:
Log.debug("Can't load %s; generating random 3D noise instead." % file)
return self.makeNoise3D(16)
#self.smoothNoise3D(size, 2, texels)
#self.smoothNoise3D(size, 4, texels)
texture = 0
glBindTexture(GL_TEXTURE_3D_EXT, texture)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_WRAP_R_EXT, GL_REPEAT)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_3D_EXT, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage3DEXT(GL_TEXTURE_3D_EXT, 0, 1,size, size, size, 0, type, GL_UNSIGNED_BYTE, noise)
return texture
def loadTex2D(self, fname, type = GL_RGB):
file = os.path.join(self.workdir,fname)
if os.path.exists(file):
img = pygame.image.load(file)
noise = pygame.image.tostring(img, "RGB")
else:
Log.debug("Can't load %s; generating random 2D noise instead." % fname)
return self.makeNoise2D(16)
texture = 0
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, 1, img.get_width(), img.get_height(), 0, type, GL_UNSIGNED_BYTE, noise)
return texture
def smoothNoise(self, size, c, noise):
for x in range(size):
for y in range(size):
col1 = noise[x][y]
col2 = noise[size/2/(1-c)+x/c][size/2/(1-c)+y/c]
noise[x][y] = (1-1/float(c))*col1+1/float(c)*col2
def smoothNoise3D(self, size, c, noise):
for i in range(size):
for j in range(size):
for k in range(size):
col1 = noise[i][j][k]
col2 = noise[size/2/(1-c)+i/c][size/2/(1-c)+j/c][size/2/(1-c)+k/c]
noise[i][j][k] = (1-1/float(c))*col1+1/float(c)*col2
def __getitem__(self, name):
if self.shaders.has_key(name):
return self.shaders[name]
else:
return None
def time(self):
return time.clock()
def reset(self):
self.checkIfEnabled()
if self.turnon:
self.var["color"] = {} #color for guitar neck flashing
self.var["solocolor"] = (0.0,)*4 #color for GH3 solo lightnings
self.var["eqcolor"] = (0.0,)*4 #color for equalizer
self.var["fret"] = {} #last note hit time for each player
self.var["fretpos"] = {} #last note hit pos for each player
self.var["scoreMult"] = {} #score multiplier for each player
self.var["multChangePos"] = {} #score multiplier last changing pos for each player
self.globals["bpm"] = 120.0
self.globals["breActive"] = False
self.globals["dfActive"] = False
self.globals["isDrum"] = False
self.globals["isFailing"] = False
self.globals["isMultChanged"] = False
self.globals["killswitch"] = False
self.globals["killswitchPos"] = -10.0
self.globals["multChangePos"] = -10.0
self.globals["notepos"] = -10.0
self.globals["rockLevel"] = 0.5
self.globals["scoreMult"] = 1
self.globals["soloActive"] = False
self.globals["songpos"] = 0.0
#self.loadFromIni()
# check Settings to enable, disable or assign shaders
def checkIfEnabled(self):
if Config.get("video","shader_use"):
if self.enabled:
self.turnon = True
else:
self.set(os.path.join(Version.dataPath(), "shaders"))
else:
self.turnon = False
if self.turnon:
for i in self.shaders.keys():
value = Config.get("video","shader_"+i)
if value != "None":
if value == "theme":
if Config.get("theme","shader_"+i) == "True":
value = i
else:
continue
self.assigned[i] = value
return True
return False
def defineConfig(self):
for name in self.shaders.keys():
for key in self[name].keys():
Config.define("shader", name+"_"+key, str, "None")
def loadFromIni(self):
for name in self.shaders.keys():
for key in self[name].keys():
value = Config.get("theme",name+"_"+key)
if value != "None":
if value == "True": value = True
elif value == "False": value = False
else:
value = value.split(",")
for i in range(len(value)):
value[i] = float(value[i])
if len(value) == 1: value = value[0]
else: value = tuple(value)
if key == "enabled":
if Config.get("video","shader_"+name) == 2:
self[name][key] = value
else:
if len(self[name][key]) == 2:
self[name][key][1] = value
def set(self, dir):
"""Do all shader setup.
dir = directory to load shaders from
"""
#stump: check whether all needed extensions are actually supported
if not glInitShaderObjectsARB():
Log.warn('OpenGL extension ARB_shader_objects not supported - shaders disabled')
return
if not glInitVertexShaderARB():
Log.warn('OpenGL extension ARB_vertex_shader not supported - shaders disabled')
return
if not glInitFragmentShaderARB():
Log.warn('OpenGL extension ARB_fragment_shader not supported - shaders disabled')
return
if not glInitMultitextureARB():
Log.warn('OpenGL extension ARB_multitexture not supported - shaders disabled')
return
if not glInitTexture3DEXT():
if sys.platform != 'darwin':
Log.warn('OpenGL extension EXT_texture3D not supported - shaders disabled')
return
#stump: pyOpenGL 2.x compatibility
try:
checkFunctionsForPyOpenGL2x()
except:
Log.error('Shaders disabled due to pyOpenGL 2.x compatibility issue: ')
return
self.workdir = dir
# Load textures needed by the shaders.
try:
self.noise3D = self.loadTex3D("noise3d.dds")
self.outline = self.loadTex2D("outline.tga")
except:
Log.error('Could not load shader textures - shaders disabled: ')
return
self.multiTex = (GL_TEXTURE0_ARB,GL_TEXTURE1_ARB,GL_TEXTURE2_ARB,GL_TEXTURE3_ARB)
self.enabled = True
self.turnon = True
# Compile the shader objects that we are going to use.
# Also set uniform shader variables to default values.
try:
self.make("lightning","stage")
except:
Log.error("Error compiling lightning shader: ")
else:
self.enable("stage")
self.setVar("ambientGlowHeightScale",6.0)
self.setVar("color",(0.0,0.0,0.0,0.0))
self.setVar("glowFallOff",0.024)
self.setVar("height",0.44)
self.setVar("sampleDist",0.0076)
self.setVar("speed",1.86)
self.setVar("vertNoise",0.78)
self.setVar("fading",1.0)
self.setVar("solofx",False)
self.setVar("scalexy",(5.0,2.4))
self.setVar("fixalpha",True)
self.setVar("offset",(0.0,-2.5))
self.disable()
try:
self.make("lightning","sololight")
except:
Log.error("Error compiling lightning shader: ")
else:
self.enable("sololight")
self.setVar("scalexy",(5.0,1.0))
self.setVar("ambientGlow",0.5)
self.setVar("ambientGlowHeightScale",6.0)
self.setVar("solofx",True)
self.setVar("height",0.3)
self.setVar("glowFallOff",0.024)
self.setVar("sampleDist",0.0076)
self.setVar("fading",4.0)
self.setVar("speed",1.86)
self.setVar("vertNoise",0.78)
self.setVar("solofx",True)
self.setVar("color",(0.0,0.0,0.0,0.0))
self.setVar("fixalpha",True)
self.setVar("glowStrength",100.0)
self.disable()
try:
self.make("lightning","tail")
except:
Log.error("Error compiling lightning shader: ")
else:
self.enable("tail")
self.setVar("scalexy",(5.0,1.0))
self.setVar("ambientGlow",0.1)
self.setVar("ambientGlowHeightScale",6.0)
self.setVar("solofx",True)
self.setVar("fading",4.0)
self.setVar("height",0.0)
self.setVar("glowFallOff",0.024)
self.setVar("sampleDist",0.0076)
self.setVar("speed",1.86)
self.setVar("vertNoise",0.78)
self.setVar("solofx",True)
self.setVar("color",(0.3,0.7,0.9,0.6))
self.setVar("glowStrength",70.0)
self.setVar("fixalpha",True)
self.setVar("offset",(0.0,0.0))
self.disable()
try:
self.make("rockbandtail","tail2")
except:
Log.error("Error compiling rockbandtail shader: ")
else:
self.enable("tail2")
self.setVar("height",0.2)
self.setVar("color",(0.0,0.6,1.0,1.0))
self.setVar("speed",9.0)
self.setVar("offset",(0.0,0.0))
self.setVar("scalexy",(5.0,1.0))
self.disable()
try:
self.make("metal","notes")
except:
Log.error("Error compiling metal shader: ")
else:
self.enable("notes")
self.disable()
try:
self.make("neck","neck")
except:
Log.error("Error compiling neck shader: ")
try:
self.make("cd","cd")
except:
Log.error("Error compiling cd shader: ")
#self.defineConfig()
def mixColors(c1,c2,blend=0.5):
c1 = list(c1)
c2 = list(c2)
alpha = 0.0
for i in range(3):
c1[i] = c1[i] + blend * c2[i]
alpha += c1[i]
c1 = c1[:3] + [min(alpha / 3.0,1.0)]
return tuple(c1)
shaders = ShaderList()
del ShaderList
| Python |
#####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2009 Team FoFiX #
# 2009 Blazingamer(n_hydock@comcast.net) #
# #
# This program is free software; you can redistribute it and/or #
# modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, #
# MA 02110-1301, USA. #
#####################################################################
import Player
from Song import Tempo, Bars
import Theme
import random
from copy import deepcopy
from Shader import shaders, mixColors
from OpenGL.GL import *
from numpy import array, float32
#myfingershurt: needed for multi-OS file fetching
import os
import Log
import Song #need the base song defines as well
class Neck:
def __init__(self, engine, part, playerObj):
self.engine = engine
self.player = part.player
self.part = part
self.isDrum = self.part.isDrum
self.isBassGuitar = self.part.isBassGuitar
self.isVocal = self.part.isVocal
self.oNeckovr = None #MFH - needs to be here to prevent crashes!
self.staticStrings = self.engine.config.get("performance", "static_strings")
self.indexFps = self.engine.config.get("video", "fps") #QQstarS
self.neckAlpha=[] # necks transparency
self.neckAlpha.append( self.engine.config.get("game", "necks_alpha") ) # all necks
self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "neck_alpha") ) # solo neck
self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "solo_neck_alpha") ) # solo neck
self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "bg_neck_alpha") ) # bass groove neck
self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "overlay_neck_alpha") ) # overlay neck
self.neckAlpha.append( self.neckAlpha[0] * self.engine.config.get("game", "fail_neck_alpha") ) # fail neck
self.boardWidth = Theme.neckWidth
self.boardLength = Theme.neckLength
#death_au: fixed neck size
if self.isDrum and self.engine.config.get("game", "large_drum_neck"):
self.boardWidth = 4.0
self.boardLength = 12.0
elif Theme.twoDnote == False or Theme.twoDkeys == False:
self.boardWidth = 3.6
self.boardLength = 9.0
self.beatsPerBoard = 5.0
self.beatsPerUnit = self.beatsPerBoard / self.boardLength
color = (1,1,1)
self.vis = 1
# evilynux - Neck color
self.board_col = array([[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], self.vis],
[color[0],color[1],color[2], self.vis],
[color[0],color[1],color[2], self.vis],
[color[0],color[1],color[2], self.vis],
[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], 0]], dtype=float32)
w = self.boardWidth
l = self.boardLength
# evilynux - Neck vertices
self.board_vtx = array([[-w / 2, 0, -2],
[w / 2, 0, -2],
[-w/ 2, 0, -1],
[w / 2, 0, -1],
[-w / 2, 0, l * .7],
[w / 2, 0, l * .7],
[-w / 2, 0, l],
[w / 2, 0, l]], dtype=float32)
# evilynux - Sidebars vertices
w += 0.15
self.sidebars_vtx = array([[-w / 2, 0, -2],
[w / 2, 0, -2],
[-w/ 2, 0, -1],
[w / 2, 0, -1],
[-w / 2, 0, l * .7],
[w / 2, 0, l * .7],
[-w / 2, 0, l],
[w / 2, 0, l]], dtype=float32)
# evilynux - Just in case the type has became double, convert to float32
self.board_col = self.board_col.astype(float32)
self.board_vtx = self.board_vtx.astype(float32)
self.sidebars_vtx = self.sidebars_vtx.astype(float32)
self.neckType = playerObj.neckType
if self.neckType == 0:
self.neck = engine.mainMenu.chosenNeck
else:
self.neck = str(playerObj.neck)
playerObj = None
#Get theme
themename = self.engine.data.themeLabel
#now theme determination logic is only in data.py:
self.theme = self.engine.data.theme
self.incomingNeckMode = self.engine.config.get("game", "incoming_neck_mode")
#blazingamer
self.failcount = 0
self.failcount2 = False
self.spcount = 0
self.spcount2 = 0
self.bgcount = 0
self.ovrneckoverlay = self.engine.config.get("fretboard", "ovrneckoverlay")
self.ocount = 0
self.currentBpm = 120.0
self.currentPeriod = 60000.0 / self.currentBpm
self.lastBpmChange = -1.0
self.baseBeat = 0.0
#myfingershurt:
self.bassGrooveNeckMode = self.engine.config.get("game", "bass_groove_neck")
self.guitarSoloNeckMode = self.engine.config.get("game", "guitar_solo_neck")
self.useMidiSoloMarkers = False
self.markSolos = 0
neckFind = True
themeNeckPath = os.path.join(self.engine.resource.fileName("themes", themename, "necks"))
if self.neckType == 1 and os.path.exists(themeNeckPath):
themeNeck = []
for i in os.listdir(themeNeckPath):
if str(i)[-4:] == ".png":
themeNeck.append(str(i))
if len(themeNeck) > 0:
i = random.randint(1,len(themeNeck))
engine.loadImgDrawing(self, "neckDrawing", os.path.join("themes", themename, "necks", themeNeck[i-1]), textureSize = (256, 256))
neckFind = False
if neckFind:
if not engine.data.fileExists(os.path.join("necks", self.neck + ".png")) and not engine.data.fileExists(os.path.join("necks", "Neck_" + self.neck + ".png")):
self.neck = str(engine.mainMenu.chosenNeck) #this neck is safe!
# evilynux - Fixed random neck -- MFH: further fixing random neck
if self.neck == "0" or self.neck == "Neck_0" or self.neck == "randomneck":
self.neck = []
# evilynux - improved loading logic to support arbitrary filenames
for i in os.listdir(self.engine.resource.fileName("necks")):
# evilynux - Special cases, ignore these...
if( str(i) == "overdriveneck.png" or str(i) == "randomneck.png" or str(i) == "Neck_0.png" or str(i)[-4:] != ".png" ):
continue
else:
self.neck.append(str(i)[:-4]) # evilynux - filename w/o extension
i = random.randint(1,len(self.neck))
engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck[i]+".png"), textureSize = (256, 256))
Log.debug("Random neck chosen: " + self.neck[i])
else:
try:
# evilynux - first assume the self.neck contains the full filename
engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks",self.neck+".png"), textureSize = (256, 256))
except IOError:
engine.loadImgDrawing(self, "neckDrawing", os.path.join("necks","Neck_"+self.neck+".png"), textureSize = (256, 256))
if self.theme == 2:
if self.isDrum == True:
try:
engine.loadImgDrawing(self, "oSideBars", os.path.join("themes",themename,"drum_overdrive_side_bars.png"), textureSize = (256, 256))
except IOError:
self.oSideBars = None
try:
engine.loadImgDrawing(self, "oCenterLines", os.path.join("themes",themename,"drum_overdrive_center_lines.png"))
except IOError:
#engine.loadImgDrawing(self, "centerLines", os.path.join("themes",themename,"center_lines.png"))
self.oCenterLines = None
#myfingershurt: the overdrive neck file should be in the theme folder... and also not required:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"overdriveneck_drum.png"), textureSize = (256, 256))
except IOError:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"overdriveneck.png"), textureSize = (256, 256))
except IOError:
self.oNeck = None
else:
try:
engine.loadImgDrawing(self, "oSideBars", os.path.join("themes",themename,"overdrive side_bars.png"), textureSize = (256, 256))
except IOError:
self.oSideBars = None
try:
engine.loadImgDrawing(self, "oCenterLines", os.path.join("themes",themename,"overdrive center_lines.png"), textureSize = (256, 256))
except IOError:
self.oCenterLines = None
if self.isBassGuitar == True:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"overdriveneck_bass.png"), textureSize = (256, 256))
except IOError:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"overdriveneck.png"), textureSize = (256, 256))
except IOError:
self.oNeckBass = None
else:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"overdriveneck.png"), textureSize = (256, 256))
except IOError:
self.oNeck = None
try:
engine.loadImgDrawing(self, "oNeckovr", os.path.join("themes",themename,"overdriveneckovr.png"), textureSize = (256, 256))
except IOError:
self.oNeckovr = None
#MFH: support for optional overdrive_string_flash.png
self.overdriveFlashCounts = self.indexFps/4 #how many cycles to display the oFlash: self.indexFps/2 = 1/2 second
if self.isDrum == True:
try:
engine.loadImgDrawing(self, "oFlash", os.path.join("themes",themename,"drum_overdrive_string_flash.png"), textureSize = (256, 256))
except IOError:
self.oFlash = None
else:
try:
engine.loadImgDrawing(self, "oFlash", os.path.join("themes",themename,"overdrive_string_flash.png"), textureSize = (256, 256))
except IOError:
self.oFlash = None
if self.isDrum == True:
try:
engine.loadImgDrawing(self, "centerLines", os.path.join("themes",themename,"drumcenterlines.png"))
except IOError:
#engine.loadImgDrawing(self, "centerLines", os.path.join("themes",themename,"center_lines.png"))
self.centerLines = None
else:
engine.loadImgDrawing(self, "centerLines", os.path.join("themes",themename,"center_lines.png"))
engine.loadImgDrawing(self, "sideBars", os.path.join("themes",themename,"side_bars.png"))
engine.loadImgDrawing(self, "bpm_halfbeat", os.path.join("themes",themename,"bpm_halfbeat.png"))
engine.loadImgDrawing(self, "bpm_beat", os.path.join("themes",themename,"bpm_beat.png"))
engine.loadImgDrawing(self, "bpm_measure", os.path.join("themes",themename,"bpm_measure.png"))
if self.theme == 0 or self.theme == 1:
self.oNeckovr = None #fixes GH theme crash
if self.isDrum == True:
#myfingershurt: the starpower neck file should be in the theme folder... and also not required:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"starpowerneck_drum.png"), textureSize = (256, 256))
except IOError:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"starpowerneck.png"), textureSize = (256, 256))
except IOError:
self.oNeck = None
else:
#myfingershurt: the starpower neck file should be in the theme folder... and also not required:
try:
engine.loadImgDrawing(self, "oNeck", os.path.join("themes",themename,"starpowerneck.png"), textureSize = (256, 256))
except IOError:
self.oNeck = None
try:
engine.loadImgDrawing(self, "oNeckBass", os.path.join("themes",themename,"starpowerneck_bass.png"), textureSize = (256, 256))
except IOError:
try:
engine.loadImgDrawing(self, "oNeckBass", os.path.join("themes",themename,"starpowerneck.png"), textureSize = (256, 256))
except IOError:
self.oNeckBass = None
#myfingershurt: Bass Groove neck:
if self.isBassGuitar == True:
if self.bassGrooveNeckMode > 0:
if self.bassGrooveNeckMode == 1: #replace neck
try:
engine.loadImgDrawing(self, "bassGrooveNeck", os.path.join("themes",themename,"bassgrooveneck.png"), textureSize = (256, 256))
except IOError:
self.bassGrooveNeck = None
elif self.bassGrooveNeckMode == 2: #overlay neck
try:
engine.loadImgDrawing(self, "bassGrooveNeck", os.path.join("themes",themename,"bassgrooveneckovr.png"), textureSize = (256, 256))
except IOError:
self.bassGrooveNeck = None
else:
self.bassGrooveNeck = None
else:
self.bassGrooveNeck = None
#myfingershurt: Guitar Solo neck:
if self.isBassGuitar == False and self.isVocal == False and self.isDrum == False:
if self.guitarSoloNeckMode > 0:
if self.guitarSoloNeckMode == 1: #replace neck
try:
engine.loadImgDrawing(self, "guitarSoloNeck", os.path.join("themes",themename,"guitarsoloneck.png"), textureSize = (256, 256))
except IOError:
self.guitarSoloNeck = None
elif self.guitarSoloNeckMode == 2: #overlay neck
try:
engine.loadImgDrawing(self, "guitarSoloNeck", os.path.join("themes",themename,"guitarsoloneckovr.png"), textureSize = (256, 256))
except IOError:
self.guitarSoloNeck = None
else:
self.guitarSoloNeck = None
else:
self.guitarSoloNeck = None
try:
engine.loadImgDrawing(self, "failNeck", os.path.join("themes",themename,"failneck.png"))
except IOError:
engine.loadImgDrawing(self, "failNeck", os.path.join("failneck.png"))
self.isFailing = False
self.canGuitarSolo = False
self.guitarSolo = False
self.scoreMultiplier = 1
self.coOpFailed = False
self.coOpRestart = False
self.starPowerActive = False
self.overdriveFlashCount = self.part.overdriveFlashCounts
self.paused = False
def updateBoardSettings(self):
self.paused = self.part.paused
self.canGuitarSolo = self.part.canGuitarSolo
self.guitarSolo = self.part.guitarSolo
self.overdriveFlashCount = self.part.overdriveFlashCount
self.ocount = self.part.ocount
self.coOpFailed = self.part.coOpFailed
self.coOpRestart = self.part.coOpRestart
self.starPowerActive = self.part.starPowerActive
self.scoreMultiplier = self.part.scoreMultiplier
self.currentBpm = self.part.currentBpm
self.currentPeriod = self.part.currentPeriod
self.lastBpmChange = self.part.lastBpmChange
self.baseBeat = self.part.baseBeat
if self.isFailing == True:
if self.failcount <= 1 and self.failcount2 == False:
self.failcount += .05
elif self.failcount >= 1 and self.failcount2 == False:
self.failcount = 1
self.failcount2 = True
if self.failcount >= 0 and self.failcount2 == True:
self.failcount -= .05
elif self.failcount <= 0 and self.failcount2 == True:
self.failcount = 0
self.failcount2 = False
if self.isFailing == False and self.failcount > 0:
self.failcount -= .05
self.failcount2 = False
if self.starPowerActive == True:
if self.spcount < 1.2:
self.spcount += .05
self.spcount2 = 1
elif self.spcount >=1.2:
self.spcount = 1.2
self.spcount2 = 0
else:
if self.spcount > 0:
self.spcount -= .05
self.spcount2 = 2
elif self.spcount <=0:
self.spcount = 0
self.spcount2 = 0
if self.scoreMultiplier > 4 and self.bgcount < 1:
self.bgcount += .1
if self.scoreMultiplier < 4 and self.bgcount > 0:
self.bgcount -= .1
def renderIncomingNeck(self, visibility, song, pos, time, neckTexture): #MFH - attempt to "scroll" an incoming guitar solo neck towards the player
if not song:
return
if not song.readyToGo:
return
def project(beat):
return 0.125 * beat / self.beatsPerUnit # glorandwarf: was 0.12
v = visibility
w = self.boardWidth
l = self.boardLength
#offset = (pos - self.lastBpmChange) / self.currentPeriod + self.baseBeat
offset = 0
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
color = (1,1,1)
glEnable(GL_TEXTURE_2D)
if neckTexture:
neckTexture.texture.bind()
glBegin(GL_TRIANGLE_STRIP)
glColor4f(color[0],color[1],color[2], 0)
glTexCoord2f(0.0, project(offset - 2 * self.beatsPerUnit))
#glVertex3f(-w / 2, 0, -2)
glVertex3f(-w / 2, 0, z) #point A
glTexCoord2f(1.0, project(offset - 2 * self.beatsPerUnit))
#glVertex3f( w / 2, 0, -2)
glVertex3f( w / 2, 0, z) #point B
glColor4f(color[0],color[1],color[2], v)
glTexCoord2f(0.0, project(offset - 1 * self.beatsPerUnit))
#glVertex3f(-w / 2, 0, -1)
glVertex3f(-w / 2, 0, z+1) #point C
glTexCoord2f(1.0, project(offset - 1 * self.beatsPerUnit))
#glVertex3f( w / 2, 0, -1)
glVertex3f( w / 2, 0, z+1) #point D
glTexCoord2f(0.0, project(offset + l * self.beatsPerUnit * .7))
#glVertex3f(-w / 2, 0, l * .7)
glVertex3f(-w / 2, 0, z+2+l * .7) #point E
glTexCoord2f(1.0, project(offset + l * self.beatsPerUnit * .7))
#glVertex3f( w / 2, 0, l * .7)
glVertex3f( w / 2, 0, z+2+l * .7) #point F
glColor4f(color[0],color[1],color[2], 0)
glTexCoord2f(0.0, project(offset + l * self.beatsPerUnit))
#glVertex3f(-w / 2, 0, l)
glVertex3f(-w / 2, 0, z+2+l) #point G
glTexCoord2f(1.0, project(offset + l * self.beatsPerUnit))
#glVertex3f( w / 2, 0, l)
glVertex3f( w / 2, 0, z+2+l) #point H
glEnd()
glDisable(GL_TEXTURE_2D)
def renderIncomingNecks(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
boardWindowMin = pos - self.currentPeriod * 2
boardWindowMax = pos + self.currentPeriod * self.beatsPerBoard
track = song.midiEventTrack[self.player]
if self.incomingNeckMode > 0: #if enabled
#if self.song.hasStarpowerPaths and self.song.midiStyle == Song.MIDI_TYPE_RB:
if self.useMidiSoloMarkers:
for time, event in track.getEvents(boardWindowMin, boardWindowMax):
if isinstance(event, Song.MarkerNote):
if event.number == Song.starPowerMarkingNote:
if self.guitarSoloNeck:
if event.endMarker: #solo end
if self.incomingNeckMode == 2: #render both start and end incoming necks
if self.guitarSolo: #only until the end of the guitar solo!
if self.starPowerActive and self.oNeck:
neckImg = self.oNeck
elif self.scoreMultiplier > 4 and self.bassGrooveNeck != None and self.bassGrooveNeckMode == 1:
neckImg = self.bassGrooveNeck
else:
neckImg = self.neckDrawing
self.renderIncomingNeck(visibility, song, pos, time, neckImg)
else: #solo start
if not self.guitarSolo: #only until guitar solo starts!
neckImg = self.guitarSoloNeck
self.renderIncomingNeck(visibility, song, pos, time, neckImg)
elif self.markSolos == 1: #fall back on text-based guitar solo marking track
for time, event in song.eventTracks[Song.TK_GUITAR_SOLOS].getEvents(boardWindowMin, boardWindowMax):
if self.canGuitarSolo and self.guitarSoloNeck:
if event.text.find("ON") >= 0:
if not self.guitarSolo: #only until guitar solo starts!
neckImg = self.guitarSoloNeck
self.renderIncomingNeck(visibility, song, pos, time, neckImg)
#else: #event.text.find("OFF"):
elif self.incomingNeckMode == 2: #render both start and end incoming necks
if self.guitarSolo: #only until the end of the guitar solo!
if self.starPowerActive and self.oNeck:
neckImg = self.oNeck
elif self.scoreMultiplier > 4 and self.bassGrooveNeck != None and self.bassGrooveNeckMode == 1:
neckImg = self.bassGrooveNeck
else:
neckImg = self.neckDrawing
self.renderIncomingNeck(visibility, song, pos, time, neckImg)
def renderNeckMethod(self, visibility, offset, neck, alpha = False): #blazingamer: New neck rendering method
def project(beat):
return 0.125 * beat / self.beatsPerUnit # glorandwarf: was 0.12
if self.starPowerActive and self.theme == 0:#8bit
color = Theme.fretColors[5] #self.spColor #(.3,.7,.9)
elif self.starPowerActive and self.theme == 1:
color = Theme.fretColors[5] #self.spColor #(.3,.7,.9)
else:
color = (1,1,1)
v = visibility
l = self.boardLength
glEnable(GL_TEXTURE_2D)
board_tex = array([[0.0, project(offset - 2 * self.beatsPerUnit)],
[1.0, project(offset - 2 * self.beatsPerUnit)],
[0.0, project(offset - 1 * self.beatsPerUnit)],
[1.0, project(offset - 1 * self.beatsPerUnit)],
[0.0, project(offset + l * self.beatsPerUnit * .7)],
[1.0, project(offset + l * self.beatsPerUnit * .7)],
[0.0, project(offset + l * self.beatsPerUnit)],
[1.0, project(offset + l * self.beatsPerUnit)]], dtype=float32)
#must be seperate for neck flashing.
board_col = array([[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], 0]], dtype=float32)
if alpha == True:
glBlendFunc(GL_ONE, GL_ONE)
neck.texture.bind()
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointerf(self.board_vtx)
glColorPointerf(board_col)
glTexCoordPointerf(board_tex)
glDrawArrays(GL_TRIANGLE_STRIP, 0, self.board_vtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
if alpha == True:
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glDisable(GL_TEXTURE_2D)
def renderNeck(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
v = visibility
w = self.boardWidth
l = self.boardLength
offset = (pos - self.lastBpmChange) / self.currentPeriod + self.baseBeat
#myfingershurt: every theme can have oNeck:
if self.guitarSolo and self.guitarSoloNeck != None and self.guitarSoloNeckMode == 1:
neck = self.guitarSoloNeck
elif self.scoreMultiplier > 4 and self.bassGrooveNeck != None and self.bassGrooveNeckMode == 1:
neck = self.bassGrooveNeck
elif self.starPowerActive and not (self.spcount2 != 0 and self.spcount < 1.2) and self.oNeck and self.scoreMultiplier <= 4 and self.ovrneckoverlay == False:
neck = self.oNeck
else:
neck = self.neckDrawing
if not (self.guitarSolo and self.guitarSoloNeck != None and self.guitarSoloNeckMode == 2):
self.renderNeckMethod(v*self.neckAlpha[1], offset, neck)
if self.bgcount > 0 and self.bassGrooveNeck != None and self.bassGrooveNeckMode == 2: #static bass groove overlay
self.renderNeckMethod(v*self.bgcount*self.neckAlpha[3], 0, self.bassGrooveNeck)
elif self.guitarSolo and self.guitarSoloNeck != None and self.guitarSoloNeckMode == 2: #static overlay
self.renderNeckMethod(v*self.neckAlpha[2], 0, self.guitarSoloNeck)
if self.spcount2 != 0 and self.spcount < 1.2 and self.oNeck: #static overlay
if self.oNeckovr != None and (self.scoreMultiplier > 4 or self.guitarSolo or self.ovrneckoverlay == True):
neck = self.oNeckovr
alpha = False
else:
neck = self.oNeck
alpha = True
self.renderNeckMethod(v*self.spcount*self.neckAlpha[4], offset, neck, alpha)
if self.starPowerActive and not (self.spcount2 != 0 and self.spcount < 1.2) and self.oNeck and (self.scoreMultiplier > 4 or self.guitarSolo or self.ovrneckoverlay == True): #static overlay
if self.oNeckovr != None:
neck = self.oNeckovr
alpha = False
else:
neck = self.oNeck
alpha = True
self.renderNeckMethod(v*self.neckAlpha[4], offset, neck, alpha)
if shaders.enabled:
shaders.globals["basspos"] = shaders.var["fret"][self.player][0]
shaders.globals["notepos"] = shaders.var["fret"][self.player][1:]
shaders.globals["bpm"] = self.currentBpm
shaders.globals["songpos"] = pos
shaders.globals["spEnabled"] = self.starPowerActive
shaders.globals["isFailing"] = self.isFailing
shaders.globals["isMultChanged"] = (shaders.var["scoreMult"][self.player] != self.scoreMultiplier)
if shaders.globals["isMultChanged"]:
shaders.var["multChangePos"][self.player] = pos
shaders.globals["scoreMult"] = self.scoreMultiplier
shaders.var["scoreMult"][self.player] = self.scoreMultiplier
shaders.globals["isDrum"] = self.isDrum
shaders.globals["soloActive"] = self.guitarSolo
posx = shaders.time()
fret = []
neckcol = (0,0,0)
notecolors = list(Theme.fretColors)
if self.isDrum:
notecolors[4] = notecolors[0]
notecolors[0] = Theme.opencolor
for i in range(5):
blend = max(shaders.var["fret"][self.player][i] - posx + 1.5,0.01)
neckcol = mixColors(neckcol, notecolors[i], blend)
shaders.var["color"][self.player]=neckcol
if shaders.enable("neck"):
shaders.setVar("fretcol",neckcol)
shaders.update()
glBegin(GL_TRIANGLE_STRIP)
glVertex3f(-w / 2, 0.1, -2)
glVertex3f(w / 2, 0.1, -2)
glVertex3f(-w / 2, 0.1, l)
glVertex3f(w / 2, 0.1, l)
glEnd()
shaders.disable()
else:
if self.isFailing:
self.renderNeckMethod(self.failcount, 0, self.failNeck)
if (self.guitarSolo or self.starPowerActive) and self.theme == 1:
shaders.var["solocolor"]=(0.3,0.7,0.9,0.6)
else:
shaders.var["solocolor"]=(0.0,)*4
def drawTrack(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
def project(beat):
return 0.125 * beat / self.beatsPerUnit # glorandwarf: was 0.12
if self.theme == 0 or self.theme == 1:
size = 2
else:
size = 0
v = visibility
w = self.boardWidth
l = self.boardLength
if self.staticStrings:
offset = 0
else:
offset = (pos - self.lastBpmChange) / self.currentPeriod + self.baseBeat
track_tex = array([[0.0, project(offset - 2 * self.beatsPerUnit)],
[1.0, project(offset - 2 * self.beatsPerUnit)],
[0.0, project(offset - 1 * self.beatsPerUnit)],
[1.0, project(offset - 1 * self.beatsPerUnit)],
[0.0, project(offset + l * self.beatsPerUnit * .7)],
[1.0, project(offset + l * self.beatsPerUnit * .7)],
[0.0, project(offset + l * self.beatsPerUnit)],
[1.0, project(offset + l * self.beatsPerUnit)]], dtype=float32)
glEnable(GL_TEXTURE_2D)
#MFH - logic to briefly display oFlash
if self.theme == 2 and self.overdriveFlashCount < self.overdriveFlashCounts and self.oFlash:
self.oFlash.texture.bind()
elif self.theme == 2 and self.starPowerActive and self.oCenterLines:
self.oCenterLines.texture.bind()
else:
self.centerLines.texture.bind()
track_vtx = array([[-w / 2, 0, -2+size],
[w / 2, 0, -2+size],
[-w / 2, 0, -1+size],
[w / 2, 0, -1+size],
[-w / 2, 0, l * .7],
[w / 2, 0, l * .7],
[-w / 2, 0, l],
[w / 2, 0, l]], dtype=float32)
if self.staticStrings: #MFH
color = (1,1,1)
track_col = array([[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], v],
[color[0],color[1],color[2], 0],
[color[0],color[1],color[2], 0]], dtype=float32)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointerf(track_vtx)
glColorPointerf(track_col)
glTexCoordPointerf(track_tex)
glDrawArrays(GL_TRIANGLE_STRIP, 0, track_vtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
else: #MFH: original moving strings
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointerf(track_vtx)
glColorPointerf(self.board_col)
glTexCoordPointerf(track_tex)
glDrawArrays(GL_TRIANGLE_STRIP, 0, track_vtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D)
def drawSideBars(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
def project(beat):
return 0.125 * beat / self.beatsPerUnit # glorandwarf: was 0.12
v = visibility
w = self.boardWidth + 0.15
l = self.boardLength
offset = (pos - self.lastBpmChange) / self.currentPeriod + self.baseBeat
c = (1,1,1)
board_tex = array([[0.0, project(offset - 2 * self.beatsPerUnit)],
[1.0, project(offset - 2 * self.beatsPerUnit)],
[0.0, project(offset - 1 * self.beatsPerUnit)],
[1.0, project(offset - 1 * self.beatsPerUnit)],
[0.0, project(offset + l * self.beatsPerUnit * .7)],
[1.0, project(offset + l * self.beatsPerUnit * .7)],
[0.0, project(offset + l * self.beatsPerUnit)],
[1.0, project(offset + l * self.beatsPerUnit)]], dtype=float32)
glEnable(GL_TEXTURE_2D)
if self.theme == 2 and self.starPowerActive and self.oSideBars:
self.oSideBars.texture.bind()
else:
self.sideBars.texture.bind()
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointerf(self.sidebars_vtx)
glColorPointerf(self.board_col)
glTexCoordPointerf(board_tex)
glDrawArrays(GL_TRIANGLE_STRIP, 0, self.sidebars_vtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D)
if self.theme == 1:
if shaders.enable("sololight"):
shaders.modVar("color",shaders.var["solocolor"])
shaders.setVar("offset",(-3.5,-w/2))
glBegin(GL_TRIANGLE_STRIP)
glVertex3f(w / 2-1.0, 0.4, -2)
glVertex3f(w / 2+1.0, 0.4, -2)
glVertex3f(w / 2-1.0, 0.4, l)
glVertex3f(w / 2+1.0, 0.4, l)
glEnd()
shaders.setVar("offset",(-3.5,w/2))
shaders.setVar("time",shaders.time()+0.5)
glBegin(GL_TRIANGLE_STRIP)
glVertex3f(-w / 2+1.0, 0.4, -2)
glVertex3f(-w / 2-1.0, 0.4, -2)
glVertex3f(-w / 2+1.0, 0.4, l)
glVertex3f(-w / 2-1.0, 0.4, l)
glEnd()
shaders.disable()
def drawBPM(self, visibility, song, pos):
if not song:
return
if not song.readyToGo:
return
v = visibility
w = self.boardWidth
track = song.track[self.player]
glEnable(GL_TEXTURE_2D)
for time, event in track.getEvents(pos - self.currentPeriod * 2, pos + self.currentPeriod * self.beatsPerBoard):
if not isinstance(event, Bars):
continue
glPushMatrix()
z = ((time - pos) / self.currentPeriod) / self.beatsPerUnit
z2 = ((time + event.length - pos) / self.currentPeriod) / self.beatsPerUnit
if z > self.boardLength:
f = (self.boardLength - z) / (self.boardLength * .2)
elif z < 0:
f = min(1, max(0, 1 + z2))
else:
f = 1.0
if event.barType == 0: #half-beat
sw = 0.1 #width
self.bpm_halfbeat.texture.bind()
elif event.barType == 1: #beat
sw = 0.1 #width
self.bpm_beat.texture.bind()
elif event.barType == 2: #measure
sw = 0.1 #width
self.bpm_measure.texture.bind()
bpm_vtx = array([[-(w / 2), 0, z + sw],
[-(w / 2), 0, z - sw],
[(w / 2), 0, z + sw],
[(w / 2), 0, z - sw]], dtype=float32)
bpm_tex = array([[0.0, 1.0],
[0.0, 0.0],
[1.0, 1.0],
[1.0, 0.0]], dtype=float32)
bpm_col = array([[1, 1, 1, v],
[1, 1, 1, v],
[1, 1, 1, v],
[1, 1, 1, v]], dtype=float32)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_COLOR_ARRAY)
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointerf(bpm_vtx)
glColorPointerf(bpm_col)
glTexCoordPointerf(bpm_tex)
glDrawArrays(GL_TRIANGLE_STRIP, 0, bpm_vtx.shape[0])
glDisableClientState(GL_VERTEX_ARRAY)
glDisableClientState(GL_COLOR_ARRAY)
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glPopMatrix()
glDisable(GL_TEXTURE_2D)
def render(self, visibility, song, pos):
self.updateBoardSettings() #Q update this before we check for coop becuase coop must be updated
if not (self.coOpFailed and not self.coOpRestart):
self.vis = visibility
self.renderNeck(visibility, song, pos)
self.renderIncomingNecks(visibility, song, pos) #MFH
self.drawTrack(self.ocount, song, pos)
self.drawBPM(visibility, song, pos)
self.drawSideBars(visibility, song, pos)
| Python |
""" Locale support.
The module provides low-level access to the C lib's locale APIs
and adds high level number formatting APIs as well as a locale
aliasing engine to complement these.
The aliasing engine includes support for many commonly used locale
names and maps them to values suitable for passing to the C lib's
setlocale() function. It also includes default encodings for all
supported locale names.
"""
import sys
# Try importing the _locale module.
#
# If this fails, fall back on a basic 'C' locale emulation.
# Yuck: LC_MESSAGES is non-standard: can't tell whether it exists before
# trying the import. So __all__ is also fiddled at the end of the file.
__all__ = ["setlocale","Error","localeconv","strcoll","strxfrm",
"format","str","atof","atoi","LC_CTYPE","LC_COLLATE",
"LC_TIME","LC_MONETARY","LC_NUMERIC", "LC_ALL","CHAR_MAX"]
try:
from _locale import *
except ImportError:
# Locale emulation
CHAR_MAX = 127
LC_ALL = 6
LC_COLLATE = 3
LC_CTYPE = 0
LC_MESSAGES = 5
LC_MONETARY = 4
LC_NUMERIC = 1
LC_TIME = 2
Error = ValueError
def localeconv():
""" localeconv() -> dict.
Returns numeric and monetary locale-specific parameters.
"""
# 'C' locale default values
return {'grouping': [127],
'currency_symbol': '',
'n_sign_posn': 127,
'p_cs_precedes': 127,
'n_cs_precedes': 127,
'mon_grouping': [],
'n_sep_by_space': 127,
'decimal_point': '.',
'negative_sign': '',
'positive_sign': '',
'p_sep_by_space': 127,
'int_curr_symbol': '',
'p_sign_posn': 127,
'thousands_sep': '',
'mon_thousands_sep': '',
'frac_digits': 127,
'mon_decimal_point': '',
'int_frac_digits': 127}
def setlocale(category, value=None):
""" setlocale(integer,string=None) -> string.
Activates/queries locale processing.
"""
if value not in (None, '', 'C'):
raise Error, '_locale emulation only supports "C" locale'
return 'C'
def strcoll(a,b):
""" strcoll(string,string) -> int.
Compares two strings according to the locale.
"""
return cmp(a,b)
def strxfrm(s):
""" strxfrm(string) -> string.
Returns a string that behaves for cmp locale-aware.
"""
return s
### Number formatting APIs
# Author: Martin von Loewis
#perform the grouping from right to left
def _group(s):
conv=localeconv()
grouping=conv['grouping']
if not grouping:return (s, 0)
result=""
seps = 0
spaces = ""
if s[-1] == ' ':
sp = s.find(' ')
spaces = s[sp:]
s = s[:sp]
while s and grouping:
# if grouping is -1, we are done
if grouping[0]==CHAR_MAX:
break
# 0: re-use last group ad infinitum
elif grouping[0]!=0:
#process last group
group=grouping[0]
grouping=grouping[1:]
if result:
result=s[-group:]+conv['thousands_sep']+result
seps += 1
else:
result=s[-group:]
s=s[:-group]
if s and s[-1] not in "0123456789":
# the leading string is only spaces and signs
return s+result+spaces,seps
if not result:
return s+spaces,seps
if s:
result=s+conv['thousands_sep']+result
seps += 1
return result+spaces,seps
def format(f,val,grouping=0):
"""Formats a value in the same way that the % formatting would use,
but takes the current locale into account.
Grouping is applied if the third parameter is true."""
result = f % val
fields = result.split(".")
seps = 0
if grouping:
fields[0],seps=_group(fields[0])
if len(fields)==2:
result = fields[0]+localeconv()['decimal_point']+fields[1]
elif len(fields)==1:
result = fields[0]
else:
raise Error, "Too many decimal points in result string"
while seps:
# If the number was formatted for a specific width, then it
# might have been filled with spaces to the left or right. If
# so, kill as much spaces as there where separators.
# Leading zeroes as fillers are not yet dealt with, as it is
# not clear how they should interact with grouping.
sp = result.find(" ")
if sp==-1:break
result = result[:sp]+result[sp+1:]
seps -= 1
return result
def str(val):
"""Convert float to integer, taking the locale into account."""
return format("%.12g",val)
def atof(string,func=float):
"Parses a string as a float according to the locale settings."
#First, get rid of the grouping
ts = localeconv()['thousands_sep']
if ts:
string = string.replace(ts, '')
#next, replace the decimal point with a dot
dd = localeconv()['decimal_point']
if dd:
string = string.replace(dd, '.')
#finally, parse the string
return func(string)
def atoi(str):
"Converts a string to an integer according to the locale settings."
return atof(str, int)
def _test():
setlocale(LC_ALL, "")
#do grouping
s1=format("%d", 123456789,1)
print s1, "is", atoi(s1)
#standard formatting
s1=str(3.14)
print s1, "is", atof(s1)
### Locale name aliasing engine
# Author: Marc-Andre Lemburg, mal@lemburg.com
# Various tweaks by Fredrik Lundh <fredrik@pythonware.com>
# store away the low-level version of setlocale (it's
# overridden below)
_setlocale = setlocale
def normalize(localename):
""" Returns a normalized locale code for the given locale
name.
The returned locale code is formatted for use with
setlocale().
If normalization fails, the original name is returned
unchanged.
If the given encoding is not known, the function defaults to
the default encoding for the locale code just like setlocale()
does.
"""
# Normalize the locale name and extract the encoding
fullname = localename.lower()
if ':' in fullname:
# ':' is sometimes used as encoding delimiter.
fullname = fullname.replace(':', '.')
if '.' in fullname:
langname, encoding = fullname.split('.')[:2]
fullname = langname + '.' + encoding
else:
langname = fullname
encoding = ''
# First lookup: fullname (possibly with encoding)
code = locale_alias.get(fullname, None)
if code is not None:
return code
# Second try: langname (without encoding)
code = locale_alias.get(langname, None)
if code is not None:
if '.' in code:
langname, defenc = code.split('.')
else:
langname = code
defenc = ''
if encoding:
encoding = encoding_alias.get(encoding, encoding)
else:
encoding = defenc
if encoding:
return langname + '.' + encoding
else:
return langname
else:
return localename
def _parse_localename(localename):
""" Parses the locale code for localename and returns the
result as tuple (language code, encoding).
The localename is normalized and passed through the locale
alias engine. A ValueError is raised in case the locale name
cannot be parsed.
The language code corresponds to RFC 1766. code and encoding
can be None in case the values cannot be determined or are
unknown to this implementation.
"""
code = normalize(localename)
if '@' in code:
# Deal with locale modifiers
code, modifier = code.split('@')
if modifier == 'euro' and '.' not in code:
# Assume Latin-9 for @euro locales. This is bogus,
# since some systems may use other encodings for these
# locales. Also, we ignore other modifiers.
return code, 'iso-8859-15'
if '.' in code:
return tuple(code.split('.')[:2])
elif code == 'C':
return None, None
raise ValueError, 'unknown locale: %s' % localename
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place.
"""
language, encoding = localetuple
if language is None:
language = 'C'
if encoding is None:
return language
else:
return language + '.' + encoding
def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')):
""" Tries to determine the default locale settings and returns
them as tuple (language code, encoding).
According to POSIX, a program which has not called
setlocale(LC_ALL, "") runs using the portable 'C' locale.
Calling setlocale(LC_ALL, "") lets it use the default locale as
defined by the LANG variable. Since we don't want to interfere
with the current locale setting we thus emulate the behavior
in the way described above.
To maintain compatibility with other platforms, not only the
LANG variable is tested, but a list of variables given as
envvars parameter. The first found to be defined will be
used. envvars defaults to the search path used in GNU gettext;
it must always contain the variable name 'LANG'.
Except for the code 'C', the language code corresponds to RFC
1766. code and encoding can be None in case the values cannot
be determined.
"""
try:
# check if it's supported by the _locale module
import _locale
code, encoding = _locale._getdefaultlocale()
except (ImportError, AttributeError):
pass
else:
# make sure the code/encoding values are valid
if sys.platform == "win32" and code and code[:2] == "0x":
# map windows language identifier to language name
code = windows_locale.get(int(code, 0))
# ...add other platform-specific processing here, if
# necessary...
return code, encoding
# fall back on POSIX behaviour
import os
lookup = os.environ.get
for variable in envvars:
localename = lookup(variable,None)
if localename:
if variable == 'LANGUAGE':
localename = localename.split(':')[0]
break
else:
localename = 'C'
return _parse_localename(localename)
def getlocale(category=LC_CTYPE):
""" Returns the current setting for the given locale category as
tuple (language code, encoding).
category may be one of the LC_* value except LC_ALL. It
defaults to LC_CTYPE.
Except for the code 'C', the language code corresponds to RFC
1766. code and encoding can be None in case the values cannot
be determined.
"""
localename = _setlocale(category)
if category == LC_ALL and ';' in localename:
raise TypeError, 'category LC_ALL is not supported'
return _parse_localename(localename)
def setlocale(category, locale=None):
""" Set the locale for the given category. The locale can be
a string, a locale tuple (language code, encoding), or None.
Locale tuples are converted to strings the locale aliasing
engine. Locale strings are passed directly to the C lib.
category may be given as one of the LC_* values.
"""
if locale and type(locale) is not type(""):
# convert to string
locale = normalize(_build_localename(locale))
return _setlocale(category, locale)
def resetlocale(category=LC_ALL):
""" Sets the locale for category to the default setting.
The default setting is determined by calling
getdefaultlocale(). category defaults to LC_ALL.
"""
_setlocale(category, _build_localename(getdefaultlocale()))
if sys.platform in ('win32', 'darwin', 'mac'):
# On Win32, this will return the ANSI code page
# On the Mac, it should return the system encoding;
# it might return "ascii" instead
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using."""
import _locale
return _locale._getdefaultlocale()[1]
else:
# On Unix, if CODESET is available, use that.
try:
CODESET
except NameError:
# Fall back to parsing environment variables :-(
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using,
by looking at environment variables."""
return getdefaultlocale()[1]
else:
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using,
according to the system configuration."""
if do_setlocale:
oldloc = setlocale(LC_CTYPE)
setlocale(LC_CTYPE, "")
result = nl_langinfo(CODESET)
setlocale(LC_CTYPE, oldloc)
return result
else:
return nl_langinfo(CODESET)
### Database
#
# The following data was extracted from the locale.alias file which
# comes with X11 and then hand edited removing the explicit encoding
# definitions and adding some more aliases. The file is usually
# available as /usr/lib/X11/locale/locale.alias.
#
#
# The encoding_alias table maps lowercase encoding alias names to C
# locale encoding names (case-sensitive).
#
encoding_alias = {
'437': 'C',
'c': 'C',
'iso8859': 'ISO8859-1',
'8859': 'ISO8859-1',
'88591': 'ISO8859-1',
'ascii': 'ISO8859-1',
'en': 'ISO8859-1',
'iso88591': 'ISO8859-1',
'iso_8859-1': 'ISO8859-1',
'885915': 'ISO8859-15',
'iso885915': 'ISO8859-15',
'iso_8859-15': 'ISO8859-15',
'iso8859-2': 'ISO8859-2',
'iso88592': 'ISO8859-2',
'iso_8859-2': 'ISO8859-2',
'iso88595': 'ISO8859-5',
'iso88596': 'ISO8859-6',
'iso88597': 'ISO8859-7',
'iso88598': 'ISO8859-8',
'iso88599': 'ISO8859-9',
'iso-2022-jp': 'JIS7',
'jis': 'JIS7',
'jis7': 'JIS7',
'sjis': 'SJIS',
'tis620': 'TACTIS',
'ajec': 'eucJP',
'eucjp': 'eucJP',
'ujis': 'eucJP',
'utf-8': 'utf',
'utf8': 'utf',
'utf8@ucs4': 'utf',
}
#
# The locale_alias table maps lowercase alias names to C locale names
# (case-sensitive). Encodings are always separated from the locale
# name using a dot ('.'); they should only be given in case the
# language name is needed to interpret the given encoding alias
# correctly (CJK codes often have this need).
#
locale_alias = {
'american': 'en_US.ISO8859-1',
'ar': 'ar_AA.ISO8859-6',
'ar_aa': 'ar_AA.ISO8859-6',
'ar_sa': 'ar_SA.ISO8859-6',
'arabic': 'ar_AA.ISO8859-6',
'bg': 'bg_BG.ISO8859-5',
'bg_bg': 'bg_BG.ISO8859-5',
'bulgarian': 'bg_BG.ISO8859-5',
'c-french': 'fr_CA.ISO8859-1',
'c': 'C',
'c_c': 'C',
'cextend': 'en_US.ISO8859-1',
'chinese-s': 'zh_CN.eucCN',
'chinese-t': 'zh_TW.eucTW',
'croatian': 'hr_HR.ISO8859-2',
'cs': 'cs_CZ.ISO8859-2',
'cs_cs': 'cs_CZ.ISO8859-2',
'cs_cz': 'cs_CZ.ISO8859-2',
'cz': 'cz_CZ.ISO8859-2',
'cz_cz': 'cz_CZ.ISO8859-2',
'czech': 'cs_CS.ISO8859-2',
'da': 'da_DK.ISO8859-1',
'da_dk': 'da_DK.ISO8859-1',
'danish': 'da_DK.ISO8859-1',
'de': 'de_DE.ISO8859-1',
'de_at': 'de_AT.ISO8859-1',
'de_ch': 'de_CH.ISO8859-1',
'de_de': 'de_DE.ISO8859-1',
'dutch': 'nl_BE.ISO8859-1',
'ee': 'ee_EE.ISO8859-4',
'el': 'el_GR.ISO8859-7',
'el_gr': 'el_GR.ISO8859-7',
'en': 'en_US.ISO8859-1',
'en_au': 'en_AU.ISO8859-1',
'en_ca': 'en_CA.ISO8859-1',
'en_gb': 'en_GB.ISO8859-1',
'en_ie': 'en_IE.ISO8859-1',
'en_nz': 'en_NZ.ISO8859-1',
'en_uk': 'en_GB.ISO8859-1',
'en_us': 'en_US.ISO8859-1',
'eng_gb': 'en_GB.ISO8859-1',
'english': 'en_EN.ISO8859-1',
'english_uk': 'en_GB.ISO8859-1',
'english_united-states': 'en_US.ISO8859-1',
'english_us': 'en_US.ISO8859-1',
'es': 'es_ES.ISO8859-1',
'es_ar': 'es_AR.ISO8859-1',
'es_bo': 'es_BO.ISO8859-1',
'es_cl': 'es_CL.ISO8859-1',
'es_co': 'es_CO.ISO8859-1',
'es_cr': 'es_CR.ISO8859-1',
'es_ec': 'es_EC.ISO8859-1',
'es_es': 'es_ES.ISO8859-1',
'es_gt': 'es_GT.ISO8859-1',
'es_mx': 'es_MX.ISO8859-1',
'es_ni': 'es_NI.ISO8859-1',
'es_pa': 'es_PA.ISO8859-1',
'es_pe': 'es_PE.ISO8859-1',
'es_py': 'es_PY.ISO8859-1',
'es_sv': 'es_SV.ISO8859-1',
'es_uy': 'es_UY.ISO8859-1',
'es_ve': 'es_VE.ISO8859-1',
'et': 'et_EE.ISO8859-4',
'et_ee': 'et_EE.ISO8859-4',
'fi': 'fi_FI.ISO8859-1',
'fi_fi': 'fi_FI.ISO8859-1',
'finnish': 'fi_FI.ISO8859-1',
'fr': 'fr_FR.ISO8859-1',
'fr_be': 'fr_BE.ISO8859-1',
'fr_ca': 'fr_CA.ISO8859-1',
'fr_ch': 'fr_CH.ISO8859-1',
'fr_fr': 'fr_FR.ISO8859-1',
'fre_fr': 'fr_FR.ISO8859-1',
'french': 'fr_FR.ISO8859-1',
'french_france': 'fr_FR.ISO8859-1',
'ger_de': 'de_DE.ISO8859-1',
'german': 'de_DE.ISO8859-1',
'german_germany': 'de_DE.ISO8859-1',
'greek': 'el_GR.ISO8859-7',
'hebrew': 'iw_IL.ISO8859-8',
'hr': 'hr_HR.ISO8859-2',
'hr_hr': 'hr_HR.ISO8859-2',
'hu': 'hu_HU.ISO8859-2',
'hu_hu': 'hu_HU.ISO8859-2',
'hungarian': 'hu_HU.ISO8859-2',
'icelandic': 'is_IS.ISO8859-1',
'id': 'id_ID.ISO8859-1',
'id_id': 'id_ID.ISO8859-1',
'is': 'is_IS.ISO8859-1',
'is_is': 'is_IS.ISO8859-1',
'iso-8859-1': 'en_US.ISO8859-1',
'iso-8859-15': 'en_US.ISO8859-15',
'iso8859-1': 'en_US.ISO8859-1',
'iso8859-15': 'en_US.ISO8859-15',
'iso_8859_1': 'en_US.ISO8859-1',
'iso_8859_15': 'en_US.ISO8859-15',
'it': 'it_IT.ISO8859-1',
'it_ch': 'it_CH.ISO8859-1',
'it_it': 'it_IT.ISO8859-1',
'italian': 'it_IT.ISO8859-1',
'iw': 'iw_IL.ISO8859-8',
'iw_il': 'iw_IL.ISO8859-8',
'ja': 'ja_JP.eucJP',
'ja.jis': 'ja_JP.JIS7',
'ja.sjis': 'ja_JP.SJIS',
'ja_jp': 'ja_JP.eucJP',
'ja_jp.ajec': 'ja_JP.eucJP',
'ja_jp.euc': 'ja_JP.eucJP',
'ja_jp.eucjp': 'ja_JP.eucJP',
'ja_jp.iso-2022-jp': 'ja_JP.JIS7',
'ja_jp.jis': 'ja_JP.JIS7',
'ja_jp.jis7': 'ja_JP.JIS7',
'ja_jp.mscode': 'ja_JP.SJIS',
'ja_jp.sjis': 'ja_JP.SJIS',
'ja_jp.ujis': 'ja_JP.eucJP',
'japan': 'ja_JP.eucJP',
'japanese': 'ja_JP.SJIS',
'japanese-euc': 'ja_JP.eucJP',
'japanese.euc': 'ja_JP.eucJP',
'jp_jp': 'ja_JP.eucJP',
'ko': 'ko_KR.eucKR',
'ko_kr': 'ko_KR.eucKR',
'ko_kr.euc': 'ko_KR.eucKR',
'korean': 'ko_KR.eucKR',
'lt': 'lt_LT.ISO8859-4',
'lv': 'lv_LV.ISO8859-4',
'mk': 'mk_MK.ISO8859-5',
'mk_mk': 'mk_MK.ISO8859-5',
'nl': 'nl_NL.ISO8859-1',
'nl_be': 'nl_BE.ISO8859-1',
'nl_nl': 'nl_NL.ISO8859-1',
'no': 'no_NO.ISO8859-1',
'no_no': 'no_NO.ISO8859-1',
'norwegian': 'no_NO.ISO8859-1',
'pl': 'pl_PL.ISO8859-2',
'pl_pl': 'pl_PL.ISO8859-2',
'polish': 'pl_PL.ISO8859-2',
'portuguese': 'pt_PT.ISO8859-1',
'portuguese_brazil': 'pt_BR.ISO8859-1',
'posix': 'C',
'posix-utf2': 'C',
'pt': 'pt_PT.ISO8859-1',
'pt_br': 'pt_BR.ISO8859-1',
'pt_pt': 'pt_PT.ISO8859-1',
'ro': 'ro_RO.ISO8859-2',
'ro_ro': 'ro_RO.ISO8859-2',
'ru': 'ru_RU.ISO8859-5',
'ru_ru': 'ru_RU.ISO8859-5',
'rumanian': 'ro_RO.ISO8859-2',
'russian': 'ru_RU.ISO8859-5',
'serbocroatian': 'sh_YU.ISO8859-2',
'sh': 'sh_YU.ISO8859-2',
'sh_hr': 'sh_HR.ISO8859-2',
'sh_sp': 'sh_YU.ISO8859-2',
'sh_yu': 'sh_YU.ISO8859-2',
'sk': 'sk_SK.ISO8859-2',
'sk_sk': 'sk_SK.ISO8859-2',
'sl': 'sl_CS.ISO8859-2',
'sl_cs': 'sl_CS.ISO8859-2',
'sl_si': 'sl_SI.ISO8859-2',
'slovak': 'sk_SK.ISO8859-2',
'slovene': 'sl_CS.ISO8859-2',
'sp': 'sp_YU.ISO8859-5',
'sp_yu': 'sp_YU.ISO8859-5',
'spanish': 'es_ES.ISO8859-1',
'spanish_spain': 'es_ES.ISO8859-1',
'sr_sp': 'sr_SP.ISO8859-2',
'sv': 'sv_SE.ISO8859-1',
'sv_se': 'sv_SE.ISO8859-1',
'swedish': 'sv_SE.ISO8859-1',
'th_th': 'th_TH.TACTIS',
'tr': 'tr_TR.ISO8859-9',
'tr_tr': 'tr_TR.ISO8859-9',
'turkish': 'tr_TR.ISO8859-9',
'univ': 'en_US.utf',
'universal': 'en_US.utf',
'zh': 'zh_CN.eucCN',
'zh_cn': 'zh_CN.eucCN',
'zh_cn.big5': 'zh_TW.eucTW',
'zh_cn.euc': 'zh_CN.eucCN',
'zh_tw': 'zh_TW.eucTW',
'zh_tw.euc': 'zh_TW.eucTW',
}
#
# This maps Windows language identifiers to locale strings.
#
# This list has been updated from
# http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/nls_238z.asp
# to include every locale up to Windows XP.
#
# NOTE: this mapping is incomplete. If your language is missing, please
# submit a bug report to Python bug manager, which you can find via:
# http://www.python.org/dev/
# Make sure you include the missing language identifier and the suggested
# locale code.
#
windows_locale = {
0x0436: "af_ZA", # Afrikaans
0x041c: "sq_AL", # Albanian
0x0401: "ar_SA", # Arabic - Saudi Arabia
0x0801: "ar_IQ", # Arabic - Iraq
0x0c01: "ar_EG", # Arabic - Egypt
0x1001: "ar_LY", # Arabic - Libya
0x1401: "ar_DZ", # Arabic - Algeria
0x1801: "ar_MA", # Arabic - Morocco
0x1c01: "ar_TN", # Arabic - Tunisia
0x2001: "ar_OM", # Arabic - Oman
0x2401: "ar_YE", # Arabic - Yemen
0x2801: "ar_SY", # Arabic - Syria
0x2c01: "ar_JO", # Arabic - Jordan
0x3001: "ar_LB", # Arabic - Lebanon
0x3401: "ar_KW", # Arabic - Kuwait
0x3801: "ar_AE", # Arabic - United Arab Emirates
0x3c01: "ar_BH", # Arabic - Bahrain
0x4001: "ar_QA", # Arabic - Qatar
0x042b: "hy_AM", # Armenian
0x042c: "az_AZ", # Azeri Latin
0x082c: "az_AZ", # Azeri - Cyrillic
0x042d: "eu_ES", # Basque
0x0423: "be_BY", # Belarusian
0x0445: "bn_IN", # Begali
0x201a: "bs_BA", # Bosnian
0x141a: "bs_BA", # Bosnian - Cyrillic
0x047e: "br_FR", # Breton - France
0x0402: "bg_BG", # Bulgarian
0x0403: "ca_ES", # Catalan
0x0004: "zh_CHS",# Chinese - Simplified
0x0404: "zh_TW", # Chinese - Taiwan
0x0804: "zh_CN", # Chinese - PRC
0x0c04: "zh_HK", # Chinese - Hong Kong S.A.R.
0x1004: "zh_SG", # Chinese - Singapore
0x1404: "zh_MO", # Chinese - Macao S.A.R.
0x7c04: "zh_CHT",# Chinese - Traditional
0x041a: "hr_HR", # Croatian
0x101a: "hr_BA", # Croatian - Bosnia
0x0405: "cs_CZ", # Czech
0x0406: "da_DK", # Danish
0x048c: "gbz_AF",# Dari - Afghanistan
0x0465: "div_MV",# Divehi - Maldives
0x0413: "nl_NL", # Dutch - The Netherlands
0x0813: "nl_BE", # Dutch - Belgium
0x0409: "en_US", # English - United States
0x0809: "en_GB", # English - United Kingdom
0x0c09: "en_AU", # English - Australia
0x1009: "en_CA", # English - Canada
0x1409: "en_NZ", # English - New Zealand
0x1809: "en_IE", # English - Ireland
0x1c09: "en_ZA", # English - South Africa
0x2009: "en_JA", # English - Jamaica
0x2409: "en_CB", # English - Carribbean
0x2809: "en_BZ", # English - Belize
0x2c09: "en_TT", # English - Trinidad
0x3009: "en_ZW", # English - Zimbabwe
0x3409: "en_PH", # English - Phillippines
0x0425: "et_EE", # Estonian
0x0438: "fo_FO", # Faroese
0x0464: "fil_PH",# Filipino
0x040b: "fi_FI", # Finnish
0x040c: "fr_FR", # French - France
0x080c: "fr_BE", # French - Belgium
0x0c0c: "fr_CA", # French - Canada
0x100c: "fr_CH", # French - Switzerland
0x140c: "fr_LU", # French - Luxembourg
0x180c: "fr_MC", # French - Monaco
0x0462: "fy_NL", # Frisian - Netherlands
0x0456: "gl_ES", # Galician
0x0437: "ka_GE", # Georgian
0x0407: "de_DE", # German - Germany
0x0807: "de_CH", # German - Switzerland
0x0c07: "de_AT", # German - Austria
0x1007: "de_LU", # German - Luxembourg
0x1407: "de_LI", # German - Liechtenstein
0x0408: "el_GR", # Greek
0x0447: "gu_IN", # Gujarati
0x040d: "he_IL", # Hebrew
0x0439: "hi_IN", # Hindi
0x040e: "hu_HU", # Hungarian
0x040f: "is_IS", # Icelandic
0x0421: "id_ID", # Indonesian
0x045d: "iu_CA", # Inuktitut
0x085d: "iu_CA", # Inuktitut - Latin
0x083c: "ga_IE", # Irish - Ireland
0x0434: "xh_ZA", # Xhosa - South Africa
0x0435: "zu_ZA", # Zulu
0x0410: "it_IT", # Italian - Italy
0x0810: "it_CH", # Italian - Switzerland
0x0411: "ja_JP", # Japanese
0x044b: "kn_IN", # Kannada - India
0x043f: "kk_KZ", # Kazakh
0x0457: "kok_IN",# Konkani
0x0412: "ko_KR", # Korean
0x0440: "ky_KG", # Kyrgyz
0x0426: "lv_LV", # Latvian
0x0427: "lt_LT", # Lithuanian
0x046e: "lb_LU", # Luxembourgish
0x042f: "mk_MK", # FYRO Macedonian
0x043e: "ms_MY", # Malay - Malaysia
0x083e: "ms_BN", # Malay - Brunei
0x044c: "ml_IN", # Malayalam - India
0x043a: "mt_MT", # Maltese
0x0481: "mi_NZ", # Maori
0x047a: "arn_CL",# Mapudungun
0x044e: "mr_IN", # Marathi
0x047c: "moh_CA",# Mohawk - Canada
0x0450: "mn_MN", # Mongolian
0x0461: "ne_NP", # Nepali
0x0414: "nb_NO", # Norwegian - Bokmal
0x0814: "nn_NO", # Norwegian - Nynorsk
0x0482: "oc_FR", # Occitan - France
0x0448: "or_IN", # Oriya - India
0x0463: "ps_AF", # Pashto - Afghanistan
0x0429: "fa_IR", # Persian
0x0415: "pl_PL", # Polish
0x0416: "pt_BR", # Portuguese - Brazil
0x0816: "pt_PT", # Portuguese - Portugal
0x0446: "pa_IN", # Punjabi
0x046b: "quz_BO",# Quechua (Bolivia)
0x086b: "quz_EC",# Quechua (Ecuador)
0x0c6b: "quz_PE",# Quechua (Peru)
0x0418: "ro_RO", # Romanian - Romania
0x0417: "rm_CH", # Raeto-Romanese
0x0419: "ru_RU", # Russian
0x243b: "smn_FI",# Sami Finland
0x103b: "smj_NO",# Sami Norway
0x143b: "smj_SE",# Sami Sweden
0x043b: "se_NO", # Sami Northern Norway
0x083b: "se_SE", # Sami Northern Sweden
0x0c3b: "se_FI", # Sami Northern Finland
0x203b: "sms_FI",# Sami Skolt
0x183b: "sma_NO",# Sami Southern Norway
0x1c3b: "sma_SE",# Sami Southern Sweden
0x044f: "sa_IN", # Sanskrit
0x0c1a: "sr_SP", # Serbian - Cyrillic
0x1c1a: "sr_BA", # Serbian - Bosnia Cyrillic
0x081a: "sr_SP", # Serbian - Latin
0x181a: "sr_BA", # Serbian - Bosnia Latin
0x046c: "ns_ZA", # Northern Sotho
0x0432: "tn_ZA", # Setswana - Southern Africa
0x041b: "sk_SK", # Slovak
0x0424: "sl_SI", # Slovenian
0x040a: "es_ES", # Spanish - Spain
0x080a: "es_MX", # Spanish - Mexico
0x0c0a: "es_ES", # Spanish - Spain (Modern)
0x100a: "es_GT", # Spanish - Guatemala
0x140a: "es_CR", # Spanish - Costa Rica
0x180a: "es_PA", # Spanish - Panama
0x1c0a: "es_DO", # Spanish - Dominican Republic
0x200a: "es_VE", # Spanish - Venezuela
0x240a: "es_CO", # Spanish - Colombia
0x280a: "es_PE", # Spanish - Peru
0x2c0a: "es_AR", # Spanish - Argentina
0x300a: "es_EC", # Spanish - Ecuador
0x340a: "es_CL", # Spanish - Chile
0x380a: "es_UR", # Spanish - Uruguay
0x3c0a: "es_PY", # Spanish - Paraguay
0x400a: "es_BO", # Spanish - Bolivia
0x440a: "es_SV", # Spanish - El Salvador
0x480a: "es_HN", # Spanish - Honduras
0x4c0a: "es_NI", # Spanish - Nicaragua
0x500a: "es_PR", # Spanish - Puerto Rico
0x0441: "sw_KE", # Swahili
0x041d: "sv_SE", # Swedish - Sweden
0x081d: "sv_FI", # Swedish - Finland
0x045a: "syr_SY",# Syriac
0x0449: "ta_IN", # Tamil
0x0444: "tt_RU", # Tatar
0x044a: "te_IN", # Telugu
0x041e: "th_TH", # Thai
0x041f: "tr_TR", # Turkish
0x0422: "uk_UA", # Ukrainian
0x0420: "ur_PK", # Urdu
0x0820: "ur_IN", # Urdu - India
0x0443: "uz_UZ", # Uzbek - Latin
0x0843: "uz_UZ", # Uzbek - Cyrillic
0x042a: "vi_VN", # Vietnamese
0x0452: "cy_GB", # Welsh
}
def _print_locale():
""" Test function.
"""
categories = {}
def _init_categories(categories=categories):
for k,v in globals().items():
if k[:3] == 'LC_':
categories[k] = v
_init_categories()
del categories['LC_ALL']
print 'Locale defaults as determined by getdefaultlocale():'
print '-'*72
lang, enc = getdefaultlocale()
print 'Language: ', lang or '(undefined)'
print 'Encoding: ', enc or '(undefined)'
print
print 'Locale settings on startup:'
print '-'*72
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
print
print 'Locale settings after calling resetlocale():'
print '-'*72
resetlocale()
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
try:
setlocale(LC_ALL, "")
except:
print 'NOTE:'
print 'setlocale(LC_ALL, "") does not support the default locale'
print 'given in the OS environment variables.'
else:
print
print 'Locale settings after calling setlocale(LC_ALL, ""):'
print '-'*72
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
###
try:
LC_MESSAGES
except NameError:
pass
else:
__all__.append("LC_MESSAGES")
if __name__=='__main__':
print 'Locale aliasing:'
print
_print_locale()
print
print 'Number formatting:'
print
_test()
| Python |
#!/usr/bin/env python
# Font tests for FoFiX by Pascal Giard <evilynux@gmail.com>
# based on the demo of laminar.PanelOverlaySurface, by
# David Keeney 2006 which is
# based on version of Nehe's OpenGL lesson04
# by Paul Furber 2001 - m@verick.co.za
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *
import sys
import os
sys.path.insert( 0, '..' )
from Font import Font
from Texture import Texture
import lamina
rtri = rquad = 0.0
triOn = quadOn = True
def resize((width, height)):
if height==0:
height=1
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.0*width/height, 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def init():
global fofixFont, mode, pygameFont, pygameChar
glShadeModel(GL_SMOOTH)
glClearColor(0.0, 0.5, 0.0, 0.0)
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
mode = 0 # evilynux - Start with lamina
# FoFiX font rendering
fofixFont = Font(None, 24, outline = False)
# pygame font rendering
pygameFont = pygame.font.Font(None, 24)
pygameChar = []
for c in range(256):
pygameChar.append(createCharacter(chr(c)))
pygameChar = tuple(pygameChar)
def draw():
global mode, fps
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
resize((640,480))
glPushMatrix()
glTranslatef(-1.5, 0.0, -6.0)
# draw triangle
global rtri
glRotatef(rtri, 0.0, 1.0, 0.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex3f(0.0, 1.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex3f(-1.0, -1.0, 0)
glColor3f(0.0, 0.0, 1.0)
glVertex3f(1.0, -1.0, 0)
glEnd()
# draw quad
glLoadIdentity()
glTranslatef(1.5, 0.0, -6.0)
global rquad
glRotatef(rquad, 1.0, 0.0, 0.0)
glColor3f(0.5, 0.5, 1.0)
glBegin(GL_QUADS)
glVertex3f(-1.0, 1.0, 0)
glVertex3f(1.0, 1.0, 0)
glVertex3f(1.0, -1.0, 0)
glVertex3f(-1.0, -1.0, 0)
glEnd()
glPopMatrix()
# Lamina font rendering
glLoadIdentity()
s = str('Mode: %d, FPS: %.2f' % (mode, fps))
if( mode == 0):
global gui_screen, font
txt = font.render(s, 1, (0,0,0), (200,0,0))
gui_screen.surf.blit(txt, (640 - txt.get_size()[0], 0))
gui_screen.display()
# FoFiX font rendering
if( mode == 1):
global fofixFont
size = fofixFont.getStringSize(s)
# Text invisible unless i put a negative Z position, wtf?!
glTranslatef(-size[0], .0, -1.0)
fofixFont.render(s, (0, 0), (1,0))
# Nelson Rush method for font rendering
if( mode == 2):
global pygameFont, pygameChar
i = 0
lx = 0
length = len(s)
x = 640 - pygameChar[ord('0')][1]*length
y = 480 - pygameChar[ord('0')][2]
textView(640,480)
glPushMatrix()
while i < length:
glRasterPos2i(x + lx, y)
ch = pygameChar[ ord( s[i] ) ]
glDrawPixels(ch[1], ch[2], GL_RGBA, GL_UNSIGNED_BYTE, ch[0])
lx += ch[1]
i += 1
glPopMatrix()
def textView(w = 640, h = 480):
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0.0, w - 1.0, 0.0, h - 1.0, -1.0, 1.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def createCharacter(s):
global pygameFont
try:
letter_render = pygameFont.render(s, 1, (255,255,255), (0,0,0))
letter = pygame.image.tostring(letter_render, 'RGBA', 1)
letter_w, letter_h = letter_render.get_size()
except:
letter = None
letter_w = 0
letter_h = 0
return (letter, letter_w, letter_h)
def main():
global rtri, rquad, gui_screen
global font, fofixFont, fps, mode
fps = 0
#video_flags = OPENGL|DOUBLEBUF
video_flags = DOUBLEBUF|OPENGL|HWPALETTE|HWSURFACE
pygame.init()
pygame.display.set_mode((640,480), video_flags)
resize((640,480))
init()
# create PanelOverlaySurface
gui_screen = lamina.LaminaScreenSurface(0.985)
pointlist = [(200,200), (400,200), (400,400), (200,400)]
pygame.draw.polygon(gui_screen.surf, (200,0,0), pointlist, 0)
pointlist1 = [(250,250), (350,250), (350,350), (250,350)]
pygame.draw.polygon(gui_screen.surf, (0,0,100), pointlist1, 0)
# draw text on a new Surface
font = pygame.font.Font(None, 40)
txt = font.render('Pygame Text', 1, (0,0,0), (200,0,0))
gui_screen.surf.blit(txt, (205, 205))
gui_screen.refresh()
gui_screen.refreshPosition()
frames = 0
ticks = pygame.time.get_ticks()
clock = pygame.time.Clock()
while 1:
event = pygame.event.poll()
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
break
elif event.type == KEYDOWN and (event.key == K_RIGHT or event.key == K_LEFT):
mode = (mode + 1) % 3
ticksDiff = pygame.time.get_ticks()-ticks
if ticksDiff > 200 and mode == 0:
gui_screen.refresh()
# draw all objects
draw()
# update rotation counters
if triOn:
rtri += 0.2
if quadOn:
rquad+= 0.2
# make changes visible
pygame.display.flip()
frames = frames+1
if( ticksDiff > 200 ):
fps = ((frames*1000)/(ticksDiff))
ticks = pygame.time.get_ticks()
frames = 0
print "mode: %s, %.2f fps" % (mode, fps)
# evilynux - commented the following so we go as fast as we can
#clock.tick(60)
if __name__ == '__main__': main()
| 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.